Skip to content

A local-first personal finance app

Customizeable Reports (#1791)

Neil1f105999af89
diff --git a/packages/desktop-client/src/components/accounts/Header.js b/packages/desktop-client/src/components/accounts/Header.js
index 1e7dcbbe85..0dc588443f 100644
--- a/packages/desktop-client/src/components/accounts/Header.js
+++ b/packages/desktop-client/src/components/accounts/Header.js
@@ -239,7 +239,7 @@ export function AccountHeader({
</Button>
)}
<View style={{ flexShrink: 0 }}>
- <FilterButton onApply={onApplyFilter} />
+ <FilterButton onApply={onApplyFilter} type="accounts" />
</View>
<View style={{ flex: 1 }} />
<Search
diff --git a/packages/desktop-client/src/components/filters/FiltersMenu.js b/packages/desktop-client/src/components/filters/FiltersMenu.js
index 7e51e9cd89..db13a1ba94 100644
--- a/packages/desktop-client/src/components/filters/FiltersMenu.js
+++ b/packages/desktop-client/src/components/filters/FiltersMenu.js
@@ -24,6 +24,7 @@ import {
import { titleFirst } from 'loot-core/src/shared/util';
import DeleteIcon from '../../icons/v0/Delete';
+import Filter from '../../icons/v1/Filter';
import SettingsSliderAlternate from '../../icons/v2/SettingsSliderAlternate';
import { theme } from '../../style';
import Button from '../common/Button';
@@ -335,7 +336,28 @@ function ConfigureField({
);
}
-export function FilterButton({ onApply }) {
+function ButtonType({ type, dispatch }) {
+ return (
+ <Button
+ type="bare"
+ onClick={() => dispatch({ type: 'select-field' })}
+ title={type && 'Filters'}
+ >
+ {type === 'reports' ? (
+ <Filter width={15} height={15} />
+ ) : (
+ <>
+ <SettingsSliderAlternate
+ style={{ width: 16, height: 16, marginRight: 5 }}
+ />{' '}
+ Filter
+ </>
+ )}
+ </Button>
+ );
+}
+
+export function FilterButton({ onApply, type }) {
let filters = useFilters();
let { dateFormat } = useSelector(state => {
@@ -418,12 +440,7 @@ export function FilterButton({ onApply }) {
return (
<View>
- <Button type="bare" onClick={() => dispatch({ type: 'select-field' })}>
- <SettingsSliderAlternate
- style={{ width: 16, height: 16, marginRight: 5 }}
- />{' '}
- Filter
- </Button>
+ <ButtonType type={type} dispatch={dispatch} />
{state.fieldsOpen && (
<Tooltip
position="bottom-left"
diff --git a/packages/desktop-client/src/components/reports/ChooseGraph.js b/packages/desktop-client/src/components/reports/ChooseGraph.js
new file mode 100644
index 0000000000..49318f468e
--- /dev/null
+++ b/packages/desktop-client/src/components/reports/ChooseGraph.js
@@ -0,0 +1,138 @@
+import React from 'react';
+
+import View from '../common/View';
+
+import AreaGraph from './graphs/AreaGraph';
+import BarGraph from './graphs/BarGraph';
+import BarLineGraph from './graphs/BarLineGraph';
+import DonutGraph from './graphs/DonutGraph';
+import LineGraph from './graphs/LineGraph';
+import StackedBarGraph from './graphs/StackedBarGraph';
+import { ReportOptions } from './ReportOptions';
+import ReportTable from './ReportTable';
+import ReportTableHeader from './ReportTableHeader';
+import ReportTableList from './ReportTableList';
+import ReportTableTotals from './ReportTableTotals';
+
+export function ChooseGraph({
+ start,
+ end,
+ data,
+ mode,
+ graphType,
+ balanceType,
+ groupBy,
+ empty,
+ scrollWidth,
+ setScrollWidth,
+ months,
+}) {
+ function saveScrollWidth(parent, child) {
+ let width = parent > 0 && child > 0 && parent - child;
+
+ setScrollWidth(!width ? 0 : width);
+ }
+
+ if (graphType === 'AreaGraph') {
+ return (
+ <AreaGraph
+ style={{ flexGrow: 1 }}
+ start={start}
+ end={end}
+ data={data}
+ balanceTypeOp={ReportOptions.balanceTypeMap.get(balanceType)}
+ />
+ );
+ }
+ if (graphType === 'BarGraph') {
+ return (
+ <BarGraph
+ style={{ flexGrow: 1 }}
+ start={start}
+ end={end}
+ data={data}
+ groupBy={groupBy}
+ empty={empty}
+ balanceTypeOp={ReportOptions.balanceTypeMap.get(balanceType)}
+ />
+ );
+ }
+ if (graphType === 'BarLineGraph') {
+ return (
+ <BarLineGraph
+ style={{ flexGrow: 1 }}
+ start={start}
+ end={end}
+ graphData={data.graphData}
+ />
+ );
+ }
+ if (graphType === 'DonutGraph') {
+ return (
+ <DonutGraph
+ style={{ flexGrow: 1 }}
+ start={start}
+ end={end}
+ data={data}
+ groupBy={groupBy}
+ empty={empty}
+ balanceTypeOp={ReportOptions.balanceTypeMap.get(balanceType)}
+ />
+ );
+ }
+ if (graphType === 'LineGraph') {
+ return (
+ <LineGraph
+ style={{ flexGrow: 1 }}
+ start={start}
+ end={end}
+ graphData={data.graphData}
+ />
+ );
+ }
+ if (graphType === 'StackedBarGraph') {
+ return (
+ <StackedBarGraph
+ style={{ flexGrow: 1 }}
+ start={start}
+ end={end}
+ data={data}
+ balanceTypeOp={ReportOptions.balanceTypeMap.get(balanceType)}
+ />
+ );
+ }
+ if (graphType === 'TableGraph') {
+ return (
+ <View
+ style={{
+ overflow: 'auto',
+ }}
+ >
+ <ReportTableHeader
+ interval={mode === 'time' && months}
+ scrollWidth={scrollWidth}
+ groupBy={groupBy}
+ balanceType={balanceType}
+ />
+ <ReportTable saveScrollWidth={saveScrollWidth}>
+ <ReportTableList
+ data={data}
+ empty={empty}
+ monthsCount={months.length}
+ balanceTypeOp={ReportOptions.balanceTypeMap.get(balanceType)}
+ mode={mode}
+ groupBy={groupBy}
+ />
+ <ReportTableTotals
+ scrollWidth={scrollWidth}
+ data={data}
+ mode={mode}
+ balanceTypeOp={ReportOptions.balanceTypeMap.get(balanceType)}
+ monthsCount={months.length}
+ balanceType={balanceType}
+ />
+ </ReportTable>
+ </View>
+ );
+ }
+}
diff --git a/packages/desktop-client/src/components/reports/Header.js b/packages/desktop-client/src/components/reports/Header.js
index dca96e47e9..1e8fc51850 100644
--- a/packages/desktop-client/src/components/reports/Header.js
+++ b/packages/desktop-client/src/components/reports/Header.js
@@ -1,3 +1,5 @@
+import { useLocation } from 'react-router-dom';
+
import * as monthUtils from 'loot-core/src/shared/months';
import ArrowLeft from '../../icons/v1/ArrowLeft';
@@ -8,7 +10,7 @@ import Select from '../common/Select';
import View from '../common/View';
import { FilterButton, AppliedFilters } from '../filters/FiltersMenu';
-function validateStart(allMonths, start, end) {
+export function validateStart(allMonths, start, end) {
const earliest = allMonths[allMonths.length - 1].name;
if (end < start) {
end = monthUtils.addMonths(start, 6);
@@ -16,7 +18,7 @@ function validateStart(allMonths, start, end) {
return boundedRange(earliest, start, end);
}
-function validateEnd(allMonths, start, end) {
+export function validateEnd(allMonths, start, end) {
const earliest = allMonths[allMonths.length - 1].name;
if (start > end) {
start = monthUtils.subMonths(end, 6);
@@ -35,13 +37,13 @@ function boundedRange(earliest, start, end) {
return [start, end];
}
-function getLatestRange(offset) {
+export function getLatestRange(offset) {
const end = monthUtils.currentMonth();
const start = monthUtils.subMonths(end, offset);
return [start, end];
}
-function getFullRange(allMonths) {
+export function getFullRange(allMonths) {
const start = allMonths[allMonths.length - 1].name;
const end = monthUtils.currentMonth();
return [start, end];
@@ -61,7 +63,11 @@ function Header({
onDeleteFilter,
onCondOpChange,
headerPrefixItems,
+ selectGraph,
}) {
+ let location = useLocation();
+ let path = location.pathname;
+
return (
<View
style={{
@@ -79,70 +85,79 @@ function Header({
</ButtonLink>
<View style={styles.veryLargeText}>{title}</View>
- <View
- style={{
- flexDirection: 'row',
- alignItems: 'center',
- marginTop: 15,
- gap: 15,
- }}
- >
- {headerPrefixItems}
-
+ {path !== '/reports/custom' && (
<View
style={{
flexDirection: 'row',
alignItems: 'center',
- gap: 5,
+ marginTop: 15,
+ gap: 15,
}}
>
- <Select
- onChange={newValue =>
- onChangeDates(...validateStart(allMonths, newValue, end))
- }
- value={start}
- defaultLabel={monthUtils.format(start, 'MMMM, yyyy')}
- options={allMonths.map(({ name, pretty }) => [name, pretty])}
- />
- <View>to</View>
- <Select
- onChange={newValue =>
- onChangeDates(...validateEnd(allMonths, start, newValue))
- }
- value={end}
- options={allMonths.map(({ name, pretty }) => [name, pretty])}
- />
- </View>
+ {headerPrefixItems}
- {filters && <FilterButton onApply={onApply} />}
+ <View
+ style={{
+ flexDirection: 'row',
+ alignItems: 'center',
+ gap: 5,
+ }}
+ >
+ <Select
+ onChange={newValue =>
+ onChangeDates(...validateStart(allMonths, newValue, end))
+ }
+ value={start}
+ defaultLabel={monthUtils.format(start, 'MMMM, yyyy')}
+ options={allMonths.map(({ name, pretty }) => [name, pretty])}
+ />
+ <View>to</View>
+ <Select
+ onChange={newValue =>
+ onChangeDates(...validateEnd(allMonths, start, newValue))
+ }
+ value={end}
+ options={allMonths.map(({ name, pretty }) => [name, pretty])}
+ />
+ </View>
+
+ {filters && <FilterButton onApply={onApply} type="accounts" />}
- {show1Month && (
+ {show1Month && (
+ <Button
+ type="bare"
+ onClick={() => onChangeDates(...getLatestRange(1))}
+ >
+ 1 month
+ </Button>
+ )}
<Button
type="bare"
- onClick={() => onChangeDates(...getLatestRange(1))}
+ onClick={() => onChangeDates(...getLatestRange(2))}
>
- 1 month
+ 3 months
</Button>
- )}
- <Button type="bare" onClick={() => onChangeDates(...getLatestRange(2))}>
- 3 months
- </Button>
- <Button type="bare" onClick={() => onChangeDates(...getLatestRange(5))}>
- 6 months
- </Button>
- <Button
- type="bare"
- onClick={() => onChangeDates(...getLatestRange(11))}
- >
- 1 Year
- </Button>
- <Button
- type="bare"
- onClick={() => onChangeDates(...getFullRange(allMonths))}
- >
- All Time
- </Button>
- </View>
+ <Button
+ type="bare"
+ onClick={() => onChangeDates(...getLatestRange(5))}
+ >
+ 6 months
+ </Button>
+ <Button
+ type="bare"
+ onClick={() => onChangeDates(...getLatestRange(11))}
+ >
+ 1 Year
+ </Button>
+ <Button
+ type="bare"
+ onClick={() => onChangeDates(...getFullRange(allMonths))}
+ >
+ All Time
+ </Button>
+ <View style={{ flex: 1 }} />
+ </View>
+ )}
{filters && filters.length > 0 && (
<View
style={{ marginTop: 5 }}
diff --git a/packages/desktop-client/src/components/reports/Overview.js b/packages/desktop-client/src/components/reports/Overview.js
index 0758f187a1..05082df5a8 100644
--- a/packages/desktop-client/src/components/reports/Overview.js
+++ b/packages/desktop-client/src/components/reports/Overview.js
@@ -1,73 +1,18 @@
-import React, { useCallback, useMemo, useState } from 'react';
+import React from 'react';
import { useSelector } from 'react-redux';
-import { VictoryBar, VictoryGroup, VictoryVoronoiContainer } from 'victory';
-
-import * as monthUtils from 'loot-core/src/shared/months';
-import { integerToCurrency } from 'loot-core/src/shared/util';
-
-import useCategories from '../../hooks/useCategories';
import useFeatureFlag from '../../hooks/useFeatureFlag';
import AnimatedLoading from '../../icons/AnimatedLoading';
-import { theme, styles } from '../../style';
-import AnchorLink from '../common/AnchorLink';
-import Block from '../common/Block';
+import { styles } from '../../style';
import View from '../common/View';
-import PrivacyFilter from '../PrivacyFilter';
-
-import Change from './Change';
-import { chartTheme } from './chart-theme';
-import Container from './Container';
-import DateRange from './DateRange';
-import { simpleCashFlow } from './graphs/cash-flow-spreadsheet';
-import categorySpendingSpreadsheet from './graphs/category-spending-spreadsheet';
-import CategorySpendingGraph from './graphs/CategorySpendingGraph';
-import netWorthSpreadsheet from './graphs/net-worth-spreadsheet';
-import NetWorthGraph from './graphs/NetWorthGraph';
-import sankeySpreadsheet from './graphs/sankey-spreadsheet';
-import SankeyGraph from './graphs/SankeyGraph';
-import Tooltip from './Tooltip';
-import useReport from './useReport';
-
-function Card({ flex, to, style, children }) {
- const containerProps = { flex, margin: 15 };
-
- const content = (
- <View
- style={{
- backgroundColor: theme.tableBackground,
- borderRadius: 2,
- height: 200,
- boxShadow: '0 2px 6px rgba(0, 0, 0, .15)',
- transition: 'box-shadow .25s',
- '& .recharts-surface:hover': {
- cursor: 'pointer',
- },
- ':hover': to && {
- boxShadow: '0 4px 6px rgba(0, 0, 0, .15)',
- },
- ...(to ? null : containerProps),
- ...style,
- }}
- >
- {children}
- </View>
- );
- if (to) {
- return (
- <AnchorLink
- to={to}
- style={{ textDecoration: 'none', flex, ...containerProps }}
- >
- {content}
- </AnchorLink>
- );
- }
- return content;
-}
+import CashFlowCard from './reports/CashFlowCard';
+import CategorySpendingCard from './reports/CategorySpendingCard';
+import CustomReportCard from './reports/CustomReportCard';
+import NetWorthCard from './reports/NetWorthCard';
+import SankeyCard from './reports/SankeyCard';
-function LoadingIndicator() {
+export function LoadingIndicator() {
return (
<View
style={{
@@ -81,293 +26,14 @@ function LoadingIndicator() {
);
}
-function NetWorthCard({ accounts }) {
- const end = monthUtils.currentMonth();
- const start = monthUtils.subMonths(end, 5);
- const [isCardHovered, setIsCardHovered] = useState(false);
- const onCardHover = useCallback(() => setIsCardHovered(true));
- const onCardHoverEnd = useCallback(() => setIsCardHovered(false));
-
- const params = useMemo(
- () => netWorthSpreadsheet(start, end, accounts),
- [start, end, accounts],
- );
- const data = useReport('net_worth', params);
-
- return (
- <Card flex={2} to="/reports/net-worth">
- <View
- style={{ flex: 1 }}
- onPointerEnter={onCardHover}
- onPointerLeave={onCardHoverEnd}
- >
- <View style={{ flexDirection: 'row', padding: 20 }}>
- <View style={{ flex: 1 }}>
- <Block
- style={{ ...styles.mediumText, fontWeight: 500, marginBottom: 5 }}
- role="heading"
- >
- Net Worth
- </Block>
- <DateRange start={start} end={end} />
- </View>
- {data && (
- <View style={{ textAlign: 'right' }}>
- <Block
- style={{
- ...styles.mediumText,
- fontWeight: 500,
- marginBottom: 5,
- }}
- >
- <PrivacyFilter activationFilters={[!isCardHovered]}>
- {integerToCurrency(data.netWorth)}
- </PrivacyFilter>
- </Block>
- <PrivacyFilter activationFilters={[!isCardHovered]}>
- <Change
- amount={data.totalChange}
- style={{ color: theme.tableTextLight, fontWeight: 300 }}
- />
- </PrivacyFilter>
- </View>
- )}
- </View>
-
- {data ? (
- <NetWorthGraph
- start={start}
- end={end}
- graphData={data.graphData}
- compact={true}
- style={{ height: 'auto', flex: 1 }}
- />
- ) : (
- <LoadingIndicator />
- )}
- </View>
- </Card>
- );
-}
-
-function CashFlowCard() {
- const end = monthUtils.currentDay();
- const start = monthUtils.currentMonth() + '-01';
-
- const params = useMemo(() => simpleCashFlow(start, end), [start, end]);
- const data = useReport('cash_flow_simple', params);
- const [isCardHovered, setIsCardHovered] = useState(false);
- const onCardHover = useCallback(() => setIsCardHovered(true));
- const onCardHoverEnd = useCallback(() => setIsCardHovered(false));
-
- const { graphData } = data || {};
- const expense = -(graphData?.expense || 0);
- const income = graphData?.income || 0;
-
- return (
- <Card flex={1} to="/reports/cash-flow">
- <View
- style={{ flex: 1 }}
- onPointerEnter={onCardHover}
- onPointerLeave={onCardHoverEnd}
- >
- <View style={{ flexDirection: 'row', padding: 20 }}>
- <View style={{ flex: 1 }}>
- <Block
- style={{ ...styles.mediumText, fontWeight: 500, marginBottom: 5 }}
- role="heading"
- >
- Cash Flow
- </Block>
- <DateRange start={start} end={end} />
- </View>
- {data && (
- <View style={{ textAlign: 'right' }}>
- <PrivacyFilter activationFilters={[!isCardHovered]}>
- <Change
- amount={income - expense}
- style={{ color: theme.tableTextLight, fontWeight: 300 }}
- />
- </PrivacyFilter>
- </View>
- )}
- </View>
-
- {data ? (
- <Container style={{ height: 'auto', flex: 1 }}>
- {(width, height, portalHost) => (
- <VictoryGroup
- colorScale={[chartTheme.colors.blue, chartTheme.colors.red]}
- width={100}
- height={height}
- theme={chartTheme}
- domain={{
- x: [0, 100],
- y: [0, Math.max(income, expense, 100)],
- }}
- containerComponent={
- <VictoryVoronoiContainer voronoiDimension="x" />
- }
- labelComponent={
- <Tooltip
- portalHost={portalHost}
- offsetX={(width - 100) / 2}
- offsetY={y => (y + 40 > height ? height - 40 : y)}
- light={true}
- forceActive={true}
- style={{
- padding: 0,
- }}
- />
- }
- padding={{
- top: 0,
- bottom: 0,
- left: 0,
- right: 0,
- }}
- >
- <VictoryBar
- barWidth={13}
- data={[
- {
- x: 30,
- y: Math.max(income, 5),
- premadeLabel: (
- <View style={{ textAlign: 'right' }}>
- Income
- <View>
- <PrivacyFilter activationFilters={[!isCardHovered]}>
- {integerToCurrency(income)}
- </PrivacyFilter>
- </View>
- </View>
- ),
- labelPosition: 'left',
- },
- ]}
- labels={d => d.premadeLabel}
- />
- <VictoryBar
- barWidth={13}
- data={[
- {
- x: 60,
- y: Math.max(expense, 5),
- premadeLabel: (
- <View>
- Expenses
- <View>
- <PrivacyFilter activationFilters={[!isCardHovered]}>
- {integerToCurrency(expense)}
- </PrivacyFilter>
- </View>
- </View>
- ),
- labelPosition: 'right',
- },
- ]}
- labels={d => d.premadeLabel}
- />
- </VictoryGroup>
- )}
- </Container>
- ) : (
- <LoadingIndicator />
- )}
- </View>
- </Card>
- );
-}
-
-function CategorySpendingCard() {
- const { list: categories = [] } = useCategories();
-
- const end = monthUtils.currentDay();
- const start = monthUtils.subMonths(end, 3);
-
- const params = useMemo(() => {
- return categorySpendingSpreadsheet(
- start,
- end,
- 3,
- categories.filter(category => !category.is_income && !category.hidden),
- );
- }, [start, end, categories]);
-
- const perCategorySpending = useReport('category_spending', params);
-
- return (
- <Card flex={1} to="/reports/category-spending">
- <View>
- <View style={{ flexDirection: 'row', padding: '20px 20px 0' }}>
- <View style={{ flex: 1 }}>
- <Block
- style={{ ...styles.mediumText, fontWeight: 500, marginBottom: 5 }}
- role="heading"
- >
- Spending
- </Block>
- <DateRange start={start} end={end} />
- </View>
- </View>
- </View>
-
- {perCategorySpending ? (
- <CategorySpendingGraph
- start={start}
- end={end}
- graphData={perCategorySpending}
- compact={true}
- />
- ) : (
- <LoadingIndicator />
- )}
- </Card>
- );
-}
-
-function SankeyCard() {
- const { grouped: categoryGroups } = useCategories();
- const end = monthUtils.currentMonth();
- const start = monthUtils.subMonths(end, 5);
-
- const params = useMemo(
- () => sankeySpreadsheet(start, end, categoryGroups),
- [start, end, categoryGroups],
- );
- const data = useReport('sankey', params);
-
- return (
- <Card flex={1} to="/reports/sankey">
- <View style={{ flexDirection: 'row', padding: 20 }}>
- <View style={{ flex: 1 }}>
- <Block
- style={{ ...styles.mediumText, fontWeight: 500, marginBottom: 5 }}
- role="heading"
- >
- Sankey
- </Block>
- <DateRange start={start} end={end} />
- </View>
- </View>
- <View style={{ flex: 1 }}>
- {data ? (
- <SankeyGraph data={data} compact={true} />
- ) : (
- <LoadingIndicator />
- )}
- </View>
- </Card>
- );
-}
-
export default function Overview() {
let categorySpendingReportFeatureFlag = useFeatureFlag(
'categorySpendingReport',
);
let sankeyFeatureFlag = useFeatureFlag('sankeyReport');
+ let customReportsFeatureFlag = useFeatureFlag('customReports');
+
let accounts = useSelector(state => state.queries.accounts);
return (
<View
@@ -385,24 +51,22 @@ export default function Overview() {
<NetWorthCard accounts={accounts} />
<CashFlowCard />
</View>
-
- {(sankeyFeatureFlag || categorySpendingReportFeatureFlag) && (
- <View
- style={{
- flex: '0 0 auto',
- flexDirection: 'row',
- }}
- >
- {categorySpendingReportFeatureFlag && <CategorySpendingCard />}
- {sankeyFeatureFlag && <SankeyCard />}
- {(!categorySpendingReportFeatureFlag || !sankeyFeatureFlag) && (
- <>
- <div style={{ flex: 1 }} />
- <div style={{ flex: 1 }} />
- </>
- )}
- </View>
- )}
+ <View
+ style={{
+ flex: '0 0 auto',
+ flexDirection: 'row',
+ }}
+ >
+ {categorySpendingReportFeatureFlag && <CategorySpendingCard />}
+ {sankeyFeatureFlag && <SankeyCard />}
+ {customReportsFeatureFlag ? (
+ <CustomReportCard />
+ ) : (
+ <div style={{ flex: 1 }} />
+ )}
+ {!categorySpendingReportFeatureFlag && <div style={{ flex: 1 }} />}
+ {!sankeyFeatureFlag && <div style={{ flex: 1 }} />}
+ </View>
</View>
);
}
diff --git a/packages/desktop-client/src/components/reports/ReportCard.tsx b/packages/desktop-client/src/components/reports/ReportCard.tsx
new file mode 100644
index 0000000000..0be8e56727
--- /dev/null
+++ b/packages/desktop-client/src/components/reports/ReportCard.tsx
@@ -0,0 +1,43 @@
+import React from 'react';
+
+import { theme } from '../../style';
+import AnchorLink from '../common/AnchorLink';
+import View from '../common/View';
+
+export default function ReportCard({ flex, to, style, children }) {
+ const containerProps = { flex, margin: 15 };
+
+ const content = (
+ <View
+ style={{
+ backgroundColor: theme.tableBackground,
+ borderRadius: 2,
+ height: 200,
+ boxShadow: '0 2px 6px rgba(0, 0, 0, .15)',
+ transition: 'box-shadow .25s',
+ '& .recharts-surface:hover': {
+ cursor: 'pointer',
+ },
+ ':hover': to && {
+ boxShadow: '0 4px 6px rgba(0, 0, 0, .15)',
+ },
+ ...(to ? null : containerProps),
+ ...style,
+ }}
+ >
+ {children}
+ </View>
+ );
+
+ if (to) {
+ return (
+ <AnchorLink
+ to={to}
+ style={{ textDecoration: 'none', flex, ...containerProps }}
+ >
+ {content}
+ </AnchorLink>
+ );
+ }
+ return content;
+}
diff --git a/packages/desktop-client/src/components/reports/ReportOptions.tsx b/packages/desktop-client/src/components/reports/ReportOptions.tsx
new file mode 100644
index 0000000000..a310a5f026
--- /dev/null
+++ b/packages/desktop-client/src/components/reports/ReportOptions.tsx
@@ -0,0 +1,44 @@
+const balanceTypeOptions = [
+ { description: 'Expense', format: 'totalDebts' },
+ { description: 'Income', format: 'totalAssets' },
+ { description: 'Net', format: 'totalTotals' },
+];
+
+const groupByOptions = [
+ { description: 'Category' },
+ { description: 'Group' },
+ { description: 'Payee' },
+ { description: 'Account' },
+ { description: 'Month' },
+ { description: 'Year' },
+];
+
+const dateRangeOptions = [
+ { description: '1 month', name: 1 },
+ { description: '3 months', name: 2 },
+ { description: '6 months', name: 5 },
+ { description: '1 year', name: 11 },
+ { description: 'All time', name: 'allMonths' },
+];
+
+export const ReportOptions = {
+ groupBy: groupByOptions,
+ balanceType: balanceTypeOptions,
+ balanceTypeMap: new Map(
+ balanceTypeOptions.map(item => [item.description, item.format]),
+ ),
+ dateRange: dateRangeOptions,
+ dateRangeMap: new Map(
+ dateRangeOptions.map(item => [item.description, item.name]),
+ ),
+};
+
+/*
+const intervalOptions = [
+{ value: 1, description: 'Daily', name: 1,
+{ value: 2, description: 'Weekly', name: 2,
+{ value: 3, description: 'Fortnightly', name: 3,
+{ value: 4, description: 'Monthly', name: 4,
+{ value: 5, description: 'Yearly', name: 5,
+];
+*/
diff --git a/packages/desktop-client/src/components/reports/ReportRouter.js b/packages/desktop-client/src/components/reports/ReportRouter.js
index 868889e348..088c6942cf 100644
--- a/packages/desktop-client/src/components/reports/ReportRouter.js
+++ b/packages/desktop-client/src/components/reports/ReportRouter.js
@@ -1,11 +1,12 @@
import React from 'react';
import { Route, Routes } from 'react-router-dom';
-import CashFlow from './CashFlow';
-import CategorySpending from './CategorySpending';
-import NetWorth from './NetWorth';
import Overview from './Overview';
-import Sankey from './Sankey';
+import CashFlow from './reports/CashFlow';
+import CategorySpending from './reports/CategorySpending';
+import CustomReport from './reports/CustomReport';
+import NetWorth from './reports/NetWorth';
+import Sankey from './reports/Sankey';
export function ReportRouter() {
return (
@@ -14,6 +15,7 @@ export function ReportRouter() {
<Route path="/net-worth" element={<NetWorth />} />
<Route path="/cash-flow" element={<CashFlow />} />
<Route path="/category-spending" element={<CategorySpending />} />
+ <Route path="/custom" element={<CustomReport />} />
<Route path="/sankey" element={<Sankey />} />
</Routes>
);
diff --git a/packages/desktop-client/src/components/reports/ReportSidebar.js b/packages/desktop-client/src/components/reports/ReportSidebar.js
new file mode 100644
index 0000000000..8a43f59d64
--- /dev/null
+++ b/packages/desktop-client/src/components/reports/ReportSidebar.js
@@ -0,0 +1,411 @@
+import React from 'react';
+
+import * as monthUtils from 'loot-core/src/shared/months';
+
+import { theme } from '../../style';
+import Button from '../common/Button';
+import Select from '../common/Select';
+import Text from '../common/Text';
+import View from '../common/View';
+import { Checkbox } from '../forms';
+
+import CategorySelector from './CategorySelector';
+import {
+ validateStart,
+ validateEnd,
+ getLatestRange,
+ getFullRange,
+} from './Header';
+import { ReportOptions } from './ReportOptions';
+
+function ModeButton({ selected, children, style, onSelect }) {
+ return (
+ <Button
+ type="bare"
+ style={{
+ padding: '5px 10px',
+ backgroundColor: theme.menuBackground,
+ marginRight: 5,
+ fontSize: 'inherit',
+ ...(selected && {
+ backgroundColor: theme.buttonPrimaryBackground,
+ color: theme.buttonPrimaryText,
+ ':hover': {
+ backgroundColor: theme.buttonPrimaryBackgroundHover,
+ color: theme.buttonPrimaryTextHover,
+ },
+ }),
+ ...style,
+ }}
+ onClick={onSelect}
+ >
+ {children}
+ </Button>
+ );
+}
+
+export function ReportSidebar({
+ start,
+ end,
+ onChangeDates,
+ dateRange,
+ setDateRange,
+ dateRangeLine,
+ allMonths,
+ graphType,
+ setGraphType,
+ setViewLegend,
+ typeDisabled,
+ setTypeDisabled,
+ groupBy,
+ setGroupBy,
+ balanceType,
+ setBalanceType,
+ mode,
+ setMode,
+ empty,
+ setEmpty,
+ hidden,
+ setHidden,
+ uncat,
+ setUncat,
+ categories,
+ selectedCategories,
+ setSelectedCategories,
+}) {
+ function onChangeMode(cond) {
+ setMode(cond);
+ if (cond === 'time') {
+ if (graphType === 'TableGraph') {
+ setTypeDisabled([]);
+ } else {
+ setTypeDisabled(['Net']);
+ if (['Net'].includes(balanceType)) {
+ setBalanceType('Expense');
+ }
+ }
+ if (graphType === 'BarGraph') {
+ setGraphType('StackedBarGraph');
+ }
+ if (['AreaGraph', 'DonutGraph'].includes(graphType)) {
+ setGraphType('TableGraph');
+ //setViewLegend(false);
+ }
+ if (['Month', 'Year'].includes(groupBy)) {
+ setGroupBy('Category');
+ }
+ } else {
+ if (graphType === 'StackedBarGraph') {
+ setGraphType('BarGraph');
+ } else {
+ setTypeDisabled([]);
+ }
+ }
+ }
+
+ function onChangeSplit(cond) {
+ setGroupBy(cond);
+ if (mode === 'total') {
+ if (graphType !== 'TableGraph') {
+ setTypeDisabled(!['Month', 'Year'].includes(groupBy) ? [] : ['Net']);
+ }
+ }
+ if (['Net'].includes(balanceType) && graphType !== 'TableGraph') {
+ setBalanceType('Expense');
+ }
+ }
+
+ return (
+ <View
+ style={{
+ width: 200,
+ paddingTop: 10,
+ paddingRight: 10,
+ flexShrink: 0,
+ }}
+ >
+ <View style={{ flexShrink: 0 }}>
+ <View
+ style={{
+ flexDirection: 'row',
+ marginBottom: 5,
+ alignItems: 'center',
+ }}
+ >
+ <Text>
+ <strong>Display</strong>
+ </Text>
+ </View>
+ <View
+ style={{
+ flexDirection: 'row',
+ padding: 5,
+ alignItems: 'center',
+ }}
+ >
+ <Text style={{ width: 40, textAlign: 'right', marginRight: 5 }}>
+ Mode:
+ </Text>
+ <ModeButton
+ selected={mode === 'total'}
+ onSelect={() => onChangeMode('total')}
+ >
+ Total
+ </ModeButton>
+ <ModeButton
+ selected={mode === 'time'}
+ onSelect={() => onChangeMode('time')}
+ >
+ Time
+ </ModeButton>
+ </View>
+ <View
+ style={{
+ flexDirection: 'row',
+ padding: 5,
+ alignItems: 'center',
+ }}
+ >
+ <Text style={{ width: 40, textAlign: 'right', marginRight: 5 }}>
+ Split:
+ </Text>
+ <Select
+ value={groupBy}
+ onChange={e => onChangeSplit(e)}
+ options={ReportOptions.groupBy.map(option => [
+ option.description,
+ option.description,
+ ])}
+ disabledKeys={
+ mode === 'time'
+ ? ['Month', 'Year']
+ : graphType === 'AreaGraph'
+ ? ['Category', 'Group', 'Payee', 'Account', 'Year']
+ : ['Year']
+ }
+ />
+ </View>
+ <View
+ style={{
+ flexDirection: 'row',
+ padding: 5,
+ alignItems: 'center',
+ }}
+ >
+ <Text style={{ width: 40, textAlign: 'right', marginRight: 5 }}>
+ Type:
+ </Text>
+ <Select
+ value={balanceType}
+ onChange={setBalanceType}
+ options={ReportOptions.balanceType.map(option => [
+ option.description,
+ option.description,
+ ])}
+ disabledKeys={typeDisabled}
+ />
+ </View>
+ {/* //It would be nice to retain this for future usage
+ <View
+ style={{
+ flexDirection: 'row',
+ padding: 5,
+ alignItems: 'center',
+ }}
+ >
+ <Text style={{ width: 40, textAlign: 'right', marginRight: 5, paddingLeft: -10 }}>
+ Interval:
+ </Text>
+ <Select
+ value={interval}
+ onChange={setInterval}
+ options={intervalOptions.map(option => [
+ option.value,
+ option.description,
+ ])}
+ disabledKeys={
+ [1,2,3,4,5]
+ }
+ />
+ </View>
+ */}
+ <View
+ style={{
+ flexDirection: 'row',
+ padding: 5,
+ alignItems: 'center',
+ }}
+ >
+ <Text style={{ width: 40, textAlign: 'right', marginRight: 5 }} />
+
+ <Checkbox
+ id="show-empty-columns"
+ checked={empty}
+ value={empty}
+ onChange={() => setEmpty(!empty)}
+ />
+ <label
+ htmlFor="show-empty-columns"
+ title="Show rows that are zero or blank"
+ style={{ fontSize: 12 }}
+ >
+ Show Empty Rows
+ </label>
+ </View>
+ <View
+ style={{
+ flexDirection: 'row',
+ padding: 5,
+ alignItems: 'center',
+ }}
+ >
+ <Text style={{ width: 40, textAlign: 'right', marginRight: 5 }} />
+
+ <Checkbox
+ id="show-hidden-columns"
+ checked={hidden}
+ value={hidden}
+ onChange={() => setHidden(!hidden)}
+ />
+ <label
+ htmlFor="show-hidden-columns"
+ title="Show off budget accounts and hidden categories"
+ style={{ fontSize: 12 }}
+ >
+ Off Budget Items
+ </label>
+ </View>
+ <View
+ style={{
+ flexDirection: 'row',
+ padding: 5,
+ alignItems: 'center',
+ }}
+ >
+ <Text style={{ width: 40, textAlign: 'right', marginRight: 5 }} />
+
+ <Checkbox
+ id="show-uncategorized"
+ checked={uncat}
+ value={uncat}
+ onChange={() => setUncat(!uncat)}
+ />
+ <label
+ htmlFor="show-uncategorized"
+ title="Show uncategorized transactions"
+ style={{ fontSize: 12 }}
+ >
+ Uncategorized
+ </label>
+ </View>
+ <View
+ style={{
+ height: 1,
+ backgroundColor: theme.altPillBorder,
+ marginTop: 10,
+ flexShrink: 0,
+ }}
+ />
+ <View
+ style={{
+ flexDirection: 'row',
+ marginTop: 10,
+ marginBottom: 5,
+ alignItems: 'center',
+ }}
+ >
+ <Text>
+ <strong>Date filters</strong>
+ </Text>
+ </View>
+ <View
+ style={{
+ flexDirection: 'row',
+ padding: 5,
+ alignItems: 'center',
+ }}
+ >
+ <Text style={{ width: 40, textAlign: 'right', marginRight: 5 }}>
+ Range:
+ </Text>
+ <Select
+ value={dateRange}
+ onChange={e => {
+ setDateRange(e);
+ if (e === 'allMonths') {
+ onChangeDates(...getFullRange(allMonths));
+ } else {
+ onChangeDates(
+ ...getLatestRange(ReportOptions.dateRangeMap.get(e)),
+ );
+ }
+ }}
+ options={ReportOptions.dateRange.map(option => [
+ option.description,
+ option.description,
+ ])}
+ line={dateRangeLine}
+ />
+ </View>
+ <View
+ style={{
+ flexDirection: 'row',
+ padding: 5,
+ alignItems: 'center',
+ }}
+ >
+ <Text style={{ width: 40, textAlign: 'right', marginRight: 5 }}>
+ From:
+ </Text>
+ <Select
+ onChange={newValue =>
+ onChangeDates(...validateStart(allMonths, newValue, end))
+ }
+ value={start}
+ defaultLabel={monthUtils.format(start, 'MMMM, yyyy')}
+ options={allMonths.map(({ name, pretty }) => [name, pretty])}
+ />
+ </View>
+ <View
+ style={{
+ flexDirection: 'row',
+ padding: 5,
+ alignItems: 'center',
+ }}
+ >
+ <Text style={{ width: 40, textAlign: 'right', marginRight: 5 }}>
+ To:
+ </Text>
+ <Select
+ onChange={newValue =>
+ onChangeDates(...validateEnd(allMonths, start, newValue))
+ }
+ value={end}
+ options={allMonths.map(({ name, pretty }) => [name, pretty])}
+ />
+ </View>
+ <View
+ style={{
+ height: 1,
+ backgroundColor: theme.altPillBorder,
+ marginTop: 10,
+ flexShrink: 0,
+ }}
+ />
+ </View>
+ {['Category', 'Group'].includes(groupBy) && (
+ <View
+ style={{
+ marginTop: 10,
+ }}
+ >
+ <CategorySelector
+ categoryGroups={categories.grouped}
+ selectedCategories={selectedCategories}
+ setSelectedCategories={setSelectedCategories}
+ />
+ </View>
+ )}
+ </View>
+ );
+}
diff --git a/packages/desktop-client/src/components/reports/ReportSummary.js b/packages/desktop-client/src/components/reports/ReportSummary.js
new file mode 100644
index 0000000000..562de58605
--- /dev/null
+++ b/packages/desktop-client/src/components/reports/ReportSummary.js
@@ -0,0 +1,197 @@
+import React from 'react';
+
+import * as monthUtils from 'loot-core/src/shared/months';
+import {
+ amountToCurrency,
+ integerToCurrency,
+ amountToInteger,
+} from 'loot-core/src/shared/util';
+
+import { theme, styles } from '../../style';
+import Text from '../common/Text';
+import View from '../common/View';
+import PrivacyFilter from '../PrivacyFilter';
+
+export function ReportSummary({
+ start,
+ end,
+ data,
+ balanceTypeOp,
+ monthsCount,
+}) {
+ let net = data.totalDebts > data.totalAssets ? 'EXPENSE' : 'INCOME';
+ const average = amountToInteger(data[balanceTypeOp]) / monthsCount;
+ return (
+ <View
+ style={{
+ flexDirection: 'column',
+ marginBottom: 10,
+ }}
+ >
+ <View
+ style={{
+ backgroundColor: theme.pageBackground,
+ padding: 15,
+ alignItems: 'center',
+ justifyContent: 'center',
+ }}
+ >
+ <Text
+ style={[
+ styles.largeText,
+ {
+ alignItems: 'center',
+ marginBottom: 2,
+ fontWeight: 600,
+ },
+ ]}
+ >
+ {monthUtils.format(start, 'MMM yyyy')} -{' '}
+ {monthUtils.format(end, 'MMM yyyy')}
+ </Text>
+ </View>
+ <View
+ style={{
+ backgroundColor: theme.pageBackground,
+ padding: 15,
+ justifyContent: 'center',
+ alignItems: 'center',
+ marginTop: 10,
+ }}
+ >
+ <Text
+ style={[
+ styles.mediumText,
+ {
+ alignItems: 'center',
+ marginBottom: 2,
+ fontWeight: 400,
+ },
+ ]}
+ >
+ {balanceTypeOp === 'totalDebts'
+ ? 'TOTAL SPENDING'
+ : balanceTypeOp === 'totalAssets'
+ ? 'TOTAL INCOME'
+ : 'NET ' + net}
+ </Text>
+ <Text
+ style={[
+ styles.veryLargeText,
+ {
+ alignItems: 'center',
+ marginBottom: 2,
+ fontWeight: 800,
+ },
+ ]}
+ >
+ <PrivacyFilter blurIntensity={7}>
+ {amountToCurrency(data[balanceTypeOp])}
+ </PrivacyFilter>
+ </Text>
+ <Text style={{ fontWeight: 600 }}>For this time period</Text>
+ </View>
+ <View
+ style={{
+ backgroundColor: theme.pageBackground,
+ padding: 15,
+ justifyContent: 'center',
+ alignItems: 'center',
+ marginTop: 10,
+ }}
+ >
+ <Text
+ style={[
+ styles.mediumText,
+ {
+ alignItems: 'center',
+ marginBottom: 2,
+ fontWeight: 400,
+ },
+ ]}
+ >
+ {balanceTypeOp === 'totalDebts'
+ ? 'AVERAGE SPENDING'
+ : balanceTypeOp === 'totalAssets'
+ ? 'AVERAGE INCOME'
+ : 'AVERAGE NET'}
+ </Text>
+ <Text
+ style={[
+ styles.veryLargeText,
+ {
+ alignItems: 'center',
+ marginBottom: 2,
+ fontWeight: 800,
+ },
+ ]}
+ >
+ <PrivacyFilter blurIntensity={7}>
+ {integerToCurrency(Math.round(average))}
+ </PrivacyFilter>
+ </Text>
+ <Text style={{ fontWeight: 600 }}>Per month</Text>
+ </View>
+ </View>
+ );
+}
+
+export function ReportLegend({ data, legend, groupBy }) {
+ return (
+ <View
+ style={{
+ backgroundColor: theme.pageBackground,
+ alignItems: 'center',
+ flex: 1,
+ overflowY: 'auto',
+ }}
+ >
+ <Text
+ style={[
+ styles.largeText,
+ {
+ alignItems: 'center',
+ marginBottom: 2,
+ fontWeight: 400,
+ paddingTop: 10,
+ },
+ ]}
+ >
+ {groupBy}
+ </Text>
+ <View>
+ {legend.map(item => {
+ return (
+ <View
+ key={item.name}
+ style={{
+ padding: 10,
+ flexDirection: 'row',
+ alignItems: 'center',
+ }}
+ >
+ <View
+ style={{
+ marginRight: 5,
+ borderRadius: 1000,
+ width: 14,
+ height: 14,
+ backgroundColor: item.color,
+ }}
+ />
+ <Text
+ style={{
+ whiteSpace: 'nowrap',
+ textOverflow: 'ellipsis',
+ flexShrink: 0,
+ }}
+ >
+ {item.name}
+ </Text>
+ </View>
+ );
+ })}
+ </View>
+ </View>
+ );
+}
diff --git a/packages/desktop-client/src/components/reports/ReportTable.tsx b/packages/desktop-client/src/components/reports/ReportTable.tsx
new file mode 100644
index 0000000000..fd7f8999ef
--- /dev/null
+++ b/packages/desktop-client/src/components/reports/ReportTable.tsx
@@ -0,0 +1,35 @@
+import React, { useLayoutEffect, useRef } from 'react';
+
+import View from '../common/View';
+
+export default function ReportTable({ saveScrollWidth, style, children }) {
+ let contentRef = useRef<HTMLDivElement>();
+
+ useLayoutEffect(() => {
+ if (contentRef.current && saveScrollWidth) {
+ saveScrollWidth(
+ contentRef.current.offsetParent
+ ? contentRef.current.parentElement.offsetWidth
+ : 0,
+ contentRef.current ? contentRef.current.offsetWidth : 0,
+ );
+ }
+ });
+
+ return (
+ <View
+ style={{
+ flex: 1,
+ outline: 'none',
+ '& .animated .animated-row': { transition: '.25s transform' },
+ ...style,
+ }}
+ tabIndex={1}
+ data-testid="table"
+ >
+ <View>
+ <div ref={contentRef}>{children}</div>
+ </View>
+ </View>
+ );
+}
diff --git a/packages/desktop-client/src/components/reports/ReportTableHeader.tsx b/packages/desktop-client/src/components/reports/ReportTableHeader.tsx
new file mode 100644
index 0000000000..932d7e4a34
--- /dev/null
+++ b/packages/desktop-client/src/components/reports/ReportTableHeader.tsx
@@ -0,0 +1,79 @@
+import React from 'react';
+
+import * as d from 'date-fns';
+
+import { theme } from '../../style';
+import { Row, Cell } from '../table';
+
+export default function ReportTableHeader({
+ scrollWidth,
+ groupBy,
+ interval,
+ balanceType,
+}) {
+ return (
+ <Row
+ collapsed={true}
+ style={{
+ color: theme.tableHeaderText,
+ backgroundColor: theme.tableHeaderBackground,
+ fontWeight: 600,
+ }}
+ >
+ <Cell
+ style={{
+ minWidth: 125,
+ }}
+ value={groupBy}
+ width="flex"
+ />
+ {interval
+ ? interval.map(header => {
+ return (
+ <Cell
+ style={{
+ minWidth: 85,
+ }}
+ key={header}
+ // eslint-disable-next-line rulesdir/typography
+ value={d.format(d.parseISO(`${header}-01`), "MMM ''yy")}
+ width="flex"
+ />
+ );
+ })
+ : balanceType === 'Net' && (
+ <>
+ <Cell
+ style={{
+ minWidth: 85,
+ }}
+ value={'Assets'}
+ width="flex"
+ />
+ <Cell
+ style={{
+ minWidth: 85,
+ }}
+ value={'Debts'}
+ width="flex"
+ />
+ </>
+ )}
+ <Cell
+ style={{
+ minWidth: 85,
+ }}
+ value={'Totals'}
+ width="flex"
+ />
+ <Cell
+ style={{
+ minWidth: 85,
+ }}
+ value={'Average'}
+ width="flex"
+ />
+ {scrollWidth > 0 && <Cell width={scrollWidth} />}
+ </Row>
+ );
+}
diff --git a/packages/desktop-client/src/components/reports/ReportTableList.tsx b/packages/desktop-client/src/components/reports/ReportTableList.tsx
new file mode 100644
index 0000000000..216e6fef49
--- /dev/null
+++ b/packages/desktop-client/src/components/reports/ReportTableList.tsx
@@ -0,0 +1,237 @@
+import React, { memo } from 'react';
+
+import {
+ amountToCurrency,
+ amountToInteger,
+ integerToCurrency,
+} from 'loot-core/src/shared/util';
+
+import { theme } from '../../style';
+import View from '../common/View';
+import { Row, Cell } from '../table';
+
+type TableRowProps = {
+ item: {
+ date: string;
+ name: string;
+ monthData: [];
+ totalAssets: number;
+ totalDebts: number;
+ };
+ balanceTypeOp?: string | null;
+ groupByItem: string;
+ mode: string;
+ monthsCount: number;
+ style?: object | null;
+};
+
+const TableRow = memo(
+ ({
+ item,
+ balanceTypeOp,
+ groupByItem,
+ mode,
+ monthsCount,
+ style,
+ }: TableRowProps) => {
+ const average = amountToInteger(item[balanceTypeOp]) / monthsCount;
+ return (
+ <Row
+ key={item[groupByItem]}
+ collapsed={true}
+ style={{
+ color: theme.tableText,
+ backgroundColor: theme.tableBackground,
+ ...style,
+ }}
+ >
+ <Cell
+ value={item[groupByItem]}
+ width="flex"
+ title={item[groupByItem].length > 12 && item[groupByItem]}
+ style={{
+ minWidth: 125,
+ }}
+ />
+ {item.monthData && mode === 'time'
+ ? item.monthData.map(month => {
+ return (
+ <Cell
+ style={{
+ minWidth: 85,
+ }}
+ key={amountToCurrency(month[balanceTypeOp])}
+ value={amountToCurrency(month[balanceTypeOp])}
+ title={
+ Math.abs(month[balanceTypeOp]) > 100000 &&
+ amountToCurrency(month[balanceTypeOp])
+ }
+ width="flex"
+ privacyFilter
+ />
+ );
+ })
+ : balanceTypeOp === 'totalTotals' && (
+ <>
+ <Cell
+ value={amountToCurrency(item.totalAssets)}
+ title={
+ Math.abs(item.totalAssets) > 100000 &&
+ amountToCurrency(item.totalAssets)
+ }
+ width="flex"
+ style={{
+ minWidth: 85,
+ }}
+ />
+ <Cell
+ value={amountToCurrency(item.totalDebts)}
+ title={
+ Math.abs(item.totalDebts) > 100000 &&
+ amountToCurrency(item.totalDebts)
+ }
+ width="flex"
+ style={{
+ minWidth: 85,
+ }}
+ />
+ </>
+ )}
+ <Cell
+ value={amountToCurrency(item[balanceTypeOp])}
+ title={
+ Math.abs(item[balanceTypeOp]) > 100000 &&
+ amountToCurrency(item[balanceTypeOp])
+ }
+ style={{
+ fontWeight: 600,
+ minWidth: 85,
+ }}
+ width="flex"
+ privacyFilter
+ />
+ <Cell
+ value={integerToCurrency(Math.round(average))}
+ title={
+ Math.abs(Math.round(average / 100)) > 100000 &&
+ integerToCurrency(Math.round(average))
+ }
+ style={{
+ fontWeight: 600,
+ minWidth: 85,
+ }}
+ width="flex"
+ privacyFilter
+ />
+ </Row>
+ );
+ },
+);
+
+function GroupedTableRow({
+ item,
+ balanceTypeOp,
+ groupByItem,
+ mode,
+ monthsCount,
+ empty,
+}) {
+ return (
+ <>
+ <TableRow
+ key={item.id}
+ item={item}
+ balanceTypeOp={balanceTypeOp}
+ groupByItem={groupByItem}
+ mode={mode}
+ monthsCount={monthsCount}
+ style={{
+ color: theme.tableRowHeaderText,
+ backgroundColor: theme.tableRowHeaderBackground,
+ fontWeight: 600,
+ }}
+ />
+ <View>
+ {item.categories
+ .filter(i =>
+ !empty
+ ? balanceTypeOp === 'totalTotals'
+ ? i.totalAssets !== 0 ||
+ i.totalDebts !== 0 ||
+ i.totalTotals !== 0
+ : i[balanceTypeOp] !== 0
+ : true,
+ )
+ .map(cat => {
+ return (
+ <TableRow
+ key={cat.id}
+ item={cat}
+ balanceTypeOp={balanceTypeOp}
+ groupByItem={groupByItem}
+ mode={mode}
+ monthsCount={monthsCount}
+ />
+ );
+ })}
+ </View>
+ <Row height={20} />
+ </>
+ );
+}
+
+export default function ReportTableList({
+ data,
+ empty,
+ monthsCount,
+ balanceTypeOp,
+ mode,
+ groupBy,
+}) {
+ const groupByItem = ['Month', 'Year'].includes(groupBy) ? 'date' : 'name';
+ const groupByData =
+ groupBy === 'Category'
+ ? 'groupData'
+ : ['Month', 'Year'].includes(groupBy)
+ ? 'monthData'
+ : 'data';
+
+ return (
+ <View>
+ {data[groupByData]
+ .filter(i =>
+ !empty
+ ? balanceTypeOp === 'totalTotals'
+ ? i.totalAssets !== 0 || i.totalDebts !== 0 || i.totalTotals !== 0
+ : i[balanceTypeOp] !== 0
+ : true,
+ )
+ .map(item => {
+ if (groupBy === 'Category') {
+ return (
+ <GroupedTableRow
+ key={item.id}
+ item={item}
+ balanceTypeOp={balanceTypeOp}
+ groupByItem={groupByItem}
+ mode={mode}
+ monthsCount={monthsCount}
+ empty={empty}
+ />
+ );
+ } else {
+ return (
+ <TableRow
+ key={item.id}
+ item={item}
+ balanceTypeOp={balanceTypeOp}
+ groupByItem={groupByItem}
+ mode={mode}
+ monthsCount={monthsCount}
+ />
+ );
+ }
+ })}
+ </View>
+ );
+}
diff --git a/packages/desktop-client/src/components/reports/ReportTableTotals.tsx b/packages/desktop-client/src/components/reports/ReportTableTotals.tsx
new file mode 100644
index 0000000000..5f37740a9c
--- /dev/null
+++ b/packages/desktop-client/src/components/reports/ReportTableTotals.tsx
@@ -0,0 +1,108 @@
+import React from 'react';
+
+import {
+ amountToCurrency,
+ amountToInteger,
+ integerToCurrency,
+} from 'loot-core/src/shared/util';
+
+import { theme } from '../../style';
+import { Row, Cell } from '../table';
+
+export default function ReportTableTotals({
+ data,
+ scrollWidth,
+ balanceTypeOp,
+ mode,
+ monthsCount,
+}) {
+ const average = amountToInteger(data[balanceTypeOp]) / monthsCount;
+ return (
+ <Row
+ collapsed={true}
+ style={{
+ color: theme.tableHeaderText,
+ backgroundColor: theme.tableHeaderBackground,
+ fontWeight: 600,
+ }}
+ >
+ <Cell
+ style={{
+ minWidth: 125,
+ }}
+ value={'Totals'}
+ width="flex"
+ />
+ {mode === 'time'
+ ? data.monthData.map(item => {
+ return (
+ <Cell
+ style={{
+ minWidth: 85,
+ }}
+ key={amountToCurrency(item[balanceTypeOp])}
+ value={amountToCurrency(item[balanceTypeOp])}
+ title={
+ Math.abs(item[balanceTypeOp]) > 100000 &&
+ amountToCurrency(item[balanceTypeOp])
+ }
+ width="flex"
+ privacyFilter
+ />
+ );
+ })
+ : balanceTypeOp === 'totalTotals' && (
+ <>
+ <Cell
+ style={{
+ minWidth: 85,
+ }}
+ value={amountToCurrency(data.totalAssets)}
+ title={
+ Math.abs(data.totalAssets) > 100000 &&
+ amountToCurrency(data.totalAssets)
+ }
+ width="flex"
+ />
+ <Cell
+ style={{
+ minWidth: 85,
+ }}
+ value={amountToCurrency(data.totalDebts)}
+ title={
+ Math.abs(data.totalDebts) > 100000 &&
+ amountToCurrency(data.totalDebts)
+ }
+ width="flex"
+ />
+ </>
+ )}
+ <Cell
+ style={{
+ minWidth: 85,
+ }}
+ value={amountToCurrency(data[balanceTypeOp])}
+ title={
+ Math.abs(data[balanceTypeOp]) > 100000 &&
+ amountToCurrency(data[balanceTypeOp])
+ }
+ width="flex"
+ privacyFilter
+ />
+ <Cell
+ style={{
+ minWidth: 85,
+ }}
+ value={integerToCurrency(Math.round(average))}
+ title={
+ Math.abs(Math.round(average / 100)) > 100000 &&
+ integerToCurrency(Math.round(average))
+ }
+ width="flex"
+ privacyFilter
+ />
+
+ {scrollWidth > 0 && <Cell width={scrollWidth} />}
+ </Row>
+ );
+}
diff --git a/packages/desktop-client/src/components/reports/ReportTopbar.js b/packages/desktop-client/src/components/reports/ReportTopbar.js
new file mode 100644
index 0000000000..9f675a347b
--- /dev/null
+++ b/packages/desktop-client/src/components/reports/ReportTopbar.js
@@ -0,0 +1,179 @@
+import React from 'react';
+
+import Calculator from '../../icons/v1/Calculator';
+import Chart from '../../icons/v1/Chart';
+import ChartBar from '../../icons/v1/ChartBar';
+import ChartPie from '../../icons/v1/ChartPie';
+import ListBullet from '../../icons/v1/ListBullet';
+import Queue from '../../icons/v1/Queue';
+import Tag from '../../icons/v1/Tag';
+import { theme } from '../../style';
+import Button from '../common/Button';
+import View from '../common/View';
+import { FilterButton } from '../filters/FiltersMenu';
+
+import { SaveReportMenuButton } from './SaveReport';
+
+function GraphButton({ selected, children, style, onSelect, title, disabled }) {
+ return (
+ <Button
+ type="bare"
+ style={{
+ ...(selected && {
+ backgroundColor: theme.buttonBareBackgroundHover,
+ }),
+ ...style,
+ }}
+ onClick={onSelect}
+ title={title}
+ disabled={disabled}
+ >
+ {children}
+ </Button>
+ );
+}
+
+export function ReportTopbar({
+ graphType,
+ setGraphType,
+ mode,
+ viewLegend,
+ setViewLegend,
+ setTypeDisabled,
+ balanceType,
+ setBalanceType,
+ groupBy,
+ setGroupBy,
+ viewSummary,
+ setViewSummary,
+ viewLabels,
+ setViewLabels,
+ onApplyFilter,
+}) {
+ return (
+ <View
+ style={{
+ flexDirection: 'row',
+ alignItems: 'center',
+ marginBottom: 10,
+ flexShrink: 0,
+ }}
+ >
+ <GraphButton
+ selected={graphType === 'TableGraph'}
+ title="Data Table"
+ onSelect={() => {
+ setGraphType('TableGraph');
+ //setViewLegend(false);
+ setTypeDisabled([]);
+ }}
+ >
+ <Queue width={15} height={15} />
+ </GraphButton>
+ <GraphButton
+ title={mode === 'total' ? 'Bar Graph' : 'Stacked Bar Graph'}
+ selected={graphType === 'BarGraph' || graphType === 'StackedBarGraph'}
+ onSelect={() => {
+ if (mode === 'total') {
+ setGraphType('BarGraph');
+ if (['Net'].includes(balanceType)) {
+ setBalanceType('Expense');
+ }
+ setTypeDisabled(['Month', 'Year'].includes(groupBy) ? [] : ['Net']);
+ } else {
+ setGraphType('StackedBarGraph');
+ setTypeDisabled(['Net']);
+ setBalanceType('Expense');
+ }
+ }}
+ style={{ marginLeft: 15 }}
+ >
+ <ChartBar width={15} height={15} />
+ </GraphButton>
+ <GraphButton
+ title="Area Graph"
+ selected={graphType === 'AreaGraph'}
+ onSelect={() => {
+ setGraphType('AreaGraph');
+ setGroupBy('Month');
+ //setViewLegend(false);
+ setTypeDisabled([]);
+ }}
+ style={{ marginLeft: 15 }}
+ disabled={mode === 'total' ? false : true}
+ >
+ <Chart width={15} height={15} />
+ </GraphButton>
+ <GraphButton
+ title="Donut Graph"
+ selected={graphType === 'DonutGraph'}
+ onSelect={() => {
+ setGraphType('DonutGraph');
+ setTypeDisabled(['Net']);
+ setBalanceType('Expense');
+ }}
+ style={{ marginLeft: 15 }}
+ disabled={mode === 'total' ? false : true}
+ >
+ <ChartPie width={15} height={15} />
+ </GraphButton>
+ <View
+ style={{
+ width: 1,
+ height: 30,
+ backgroundColor: theme.altPillBorder,
+ marginLeft: 15,
+ flexShrink: 0,
+ }}
+ />
+ <GraphButton
+ selected={viewLegend}
+ onSelect={() => {
+ setViewLegend(!viewLegend);
+ }}
+ style={{ marginLeft: 15 }}
+ title="Show Legend"
+ disabled={
+ true //descoping for future PR
+ //graphType === 'TableGraph' || graphType === 'AreaGraph' ? true : false
+ }
+ >
+ <ListBullet width={15} height={15} />
+ </GraphButton>
+ <GraphButton
+ selected={viewSummary}
+ onSelect={() => {
+ setViewSummary(!viewSummary);
+ }}
+ style={{ marginLeft: 15 }}
+ title="Show Summary"
+ >
+ <Calculator width={15} height={15} />
+ </GraphButton>
+ <GraphButton
+ selected={viewLabels}
+ onSelect={() => {
+ setViewLabels(!viewLabels);
+ }}
+ style={{ marginLeft: 15 }}
+ title="Show labels"
+ disabled={true}
+ >
+ <Tag width={15} height={15} />
+ </GraphButton>
+ <View
+ style={{
+ width: 1,
+ height: 30,
+ backgroundColor: theme.altPillBorder,
+ marginRight: 15,
+ marginLeft: 15,
+ flexShrink: 0,
+ }}
+ />
+ <FilterButton onApply={onApplyFilter} type="reports" />
+ <View style={{ flex: 1 }} />
+ <SaveReportMenuButton />
+ </View>
+ );
+}
diff --git a/packages/desktop-client/src/components/reports/SaveReport.tsx b/packages/desktop-client/src/components/reports/SaveReport.tsx
new file mode 100644
index 0000000000..b6303870ac
--- /dev/null
+++ b/packages/desktop-client/src/components/reports/SaveReport.tsx
@@ -0,0 +1,72 @@
+import React, { useState } from 'react';
+
+import ExpandArrow from '../../icons/v0/ExpandArrow';
+import Button from '../common/Button';
+import Menu from '../common/Menu';
+import MenuTooltip from '../common/MenuTooltip';
+import Text from '../common/Text';
+import View from '../common/View';
+
+function SaveReportMenu({ setMenuOpen }) {
+ return (
+ <MenuTooltip width={150} onClose={() => setMenuOpen(false)}>
+ <Menu
+ onMenuSelect={item => {
+ switch (item) {
+ case 'save':
+ case 'clear':
+ setMenuOpen(false);
+ break;
+ default:
+ }
+ }}
+ items={[
+ {
+ name: 'save',
+ text: 'Save new report',
+ disabled: true,
+ },
+ {
+ name: 'clear',
+ text: 'Clear all',
+ disabled: true,
+ },
+ ]}
+ />
+ </MenuTooltip>
+ );
+}
+
+export function SaveReportMenuButton() {
+ let [menuOpen, setMenuOpen] = useState(false);
+
+ return (
+ <View
+ style={{
+ flexDirection: 'row',
+ alignItems: 'center',
+ }}
+ >
+ <Button
+ type="bare"
+ onClick={() => {
+ setMenuOpen(true);
+ }}
+ >
+ <Text
+ style={{
+ maxWidth: 150,
+ whiteSpace: 'nowrap',
+ overflow: 'hidden',
+ textOverflow: 'ellipsis',
+ flexShrink: 0,
+ }}
+ >
+ {'Unsaved Report'}&nbsp;
+ </Text>
+ <ExpandArrow width={8} height={8} style={{ marginRight: 5 }} />
+ </Button>
+ {menuOpen && <SaveReportMenu setMenuOpen={setMenuOpen} />}
+ </View>
+ );
+}
diff --git a/packages/desktop-client/src/components/reports/chart-theme.js b/packages/desktop-client/src/components/reports/chart-theme.js
index b8e1c2bd9e..391786a17c 100644
--- a/packages/desktop-client/src/components/reports/chart-theme.js
+++ b/packages/desktop-client/src/components/reports/chart-theme.js
@@ -111,3 +111,27 @@ export const chartTheme = {
},
},
};
+
+export function getColorScale(name) {
+ const scales = {
+ grayscale: ['#cccccc', '#969696', '#636363', '#252525'],
+ qualitative: [
+ '#45B29D', //Dark Teal
+ '#EFC94C', //Yellow
+ '#E27A3F', //Orange
+ '#DF5A49', //Light Red
+ '#5F91B8', //Blue
+ '#E2A37F', //Peach
+ '#55DBC1', //Light Teal
+ '#EFDA97', //Light Yellow
+ '#DF948A', //Light Red
+ ],
+ heatmap: ['#428517', '#77D200', '#D6D305', '#EC8E19', '#C92B05'],
+ warm: ['#940031', '#C43343', '#DC5429', '#FF821D', '#FFAF55'],
+ cool: ['#2746B9', '#0B69D4', '#2794DB', '#31BB76', '#60E83B'],
+ red: ['#FCAE91', '#FB6A4A', '#DE2D26', '#A50F15', '#750B0E'],
+ blue: ['#002C61', '#004B8F', '#006BC9', '#3795E5', '#65B4F4'],
+ green: ['#354722', '#466631', '#649146', '#8AB25C', '#A9C97E'],
+ };
+ return name ? scales[name] : scales.grayscale;
+}
diff --git a/packages/desktop-client/src/components/reports/graphs/AreaGraph.tsx b/packages/desktop-client/src/components/reports/graphs/AreaGraph.tsx
new file mode 100644
index 0000000000..18cbf71b7d
--- /dev/null
+++ b/packages/desktop-client/src/components/reports/graphs/AreaGraph.tsx
@@ -0,0 +1,191 @@
+import React from 'react';
+
+import { css } from 'glamor';
+import {
+ AreaChart,
+ Area,
+ CartesianGrid,
+ XAxis,
+ YAxis,
+ Tooltip,
+ ResponsiveContainer,
+} from 'recharts';
+
+import { amountToCurrency } from 'loot-core/src/shared/util';
+
+import { theme } from '../../../style';
+import { type CSSProperties } from '../../../style';
+import AlignedText from '../../common/AlignedText';
+import PrivacyFilter from '../../PrivacyFilter';
+import Container from '../Container';
+import numberFormatterTooltip from '../numberFormatter';
+
+type PayloadItem = {
+ payload: {
+ date: string;
+ totalAssets: number | string;
+ totalDebts: number | string;
+ totalTotals: number | string;
+ };
+};
+
+type CustomTooltipProps = {
+ active?: boolean;
+ payload?: PayloadItem[];
+ balanceTypeOp?: string;
+};
+
+const CustomTooltip = ({
+ active,
+ payload,
+ balanceTypeOp,
+}: CustomTooltipProps) => {
+ if (active && payload && payload.length) {
+ return (
+ <div
+ className={`${css({
+ zIndex: 1000,
+ pointerEvents: 'none',
+ borderRadius: 2,
+ boxShadow: '0 1px 6px rgba(0, 0, 0, .20)',
+ backgroundColor: theme.menuAutoCompleteBackground,
+ color: theme.menuAutoCompleteText,
+ padding: 10,
+ })}`}
+ >
+ <div>
+ <div style={{ marginBottom: 10 }}>
+ <strong>{payload[0].payload.date}</strong>
+ </div>
+ <div style={{ lineHeight: 1.5 }}>
+ <PrivacyFilter>
+ {['totalAssets', 'totalTotals'].includes(balanceTypeOp) && (
+ <AlignedText
+ left="Assets:"
+ right={amountToCurrency(payload[0].payload.totalAssets)}
+ />
+ )}
+ {['totalDebts', 'totalTotals'].includes(balanceTypeOp) && (
+ <AlignedText
+ left="Debt:"
+ right={amountToCurrency(payload[0].payload.totalDebts)}
+ />
+ )}
+ {['totalTotals'].includes(balanceTypeOp) && (
+ <AlignedText
+ left="Net:"
+ right={
+ <strong>
+ {amountToCurrency(payload[0].payload.totalTotals)}
+ </strong>
+ }
+ />
+ )}
+ </PrivacyFilter>
+ </div>
+ </div>
+ </div>
+ );
+ }
+};
+
+type AreaGraphProps = {
+ style?: CSSProperties;
+ data;
+ balanceTypeOp;
+ compact: boolean;
+ domain?: {
+ totalTotals?: [number, number];
+ };
+};
+
+function AreaGraph({ style, data, balanceTypeOp, compact }: AreaGraphProps) {
+ const tickFormatter = tick => {
+ return `${Math.round(tick).toLocaleString()}`; // Formats the tick values as strings with commas
+ };
+
+ const gradientOffset = () => {
+ const dataMax = Math.max(...data.monthData.map(i => i[balanceTypeOp]));
+ const dataMin = Math.min(...data.monthData.map(i => i[balanceTypeOp]));
+
+ if (dataMax <= 0) {
+ return 0;
+ }
+ if (dataMin >= 0) {
+ return 1;
+ }
+
+ return dataMax / (dataMax - dataMin);
+ };
+
+ const off = gradientOffset();
+
+ return (
+ <Container
+ style={{
+ ...style,
+ ...(compact && { height: 'auto' }),
+ }}
+ >
+ {(width, height, portalHost) =>
+ data.monthData && (
+ <ResponsiveContainer>
+ <div>
+ {!compact && <div style={{ marginTop: '15px' }} />}
+ <AreaChart
+ width={width}
+ height={height}
+ data={data.monthData}
+ margin={{ top: 0, right: 0, left: 0, bottom: 0 }}
+ >
+ {compact ? null : (
+ <CartesianGrid strokeDasharray="3 3" vertical={false} />
+ )}
+ {compact ? null : <XAxis dataKey="date" />}
+ {compact ? null : (
+ <YAxis
+ dataKey={...balanceTypeOp}
+ domain={['auto', 'auto']}
+ tickFormatter={tickFormatter}
+ />
+ )}
+ <Tooltip
+ content={<CustomTooltip balanceTypeOp={balanceTypeOp} />}
+ formatter={numberFormatterTooltip}
+ isAnimationActive={false}
+ />
+ <defs>
+ <linearGradient id="splitColor" x1="0" y1="0" x2="0" y2="1">
+ <stop
+ offset={off}
+ stopColor={theme.reportsBlue}
+ stopOpacity={0.2}
+ />
+ <stop
+ offset={off}
+ stopColor={theme.reportsRed}
+ stopOpacity={0.2}
+ />
+ </linearGradient>
+ </defs>
+
+ <Area
+ type="linear"
+ dot={false}
+ activeDot={false}
+ animationDuration={0}
+ dataKey={...balanceTypeOp}
+ stroke={theme.reportsBlue}
+ fill="url(#splitColor)"
+ fillOpacity={1}
+ />
+ </AreaChart>
+ </div>
+ </ResponsiveContainer>
+ )
+ }
+ </Container>
+ );
+}
+
+export default AreaGraph;
diff --git a/packages/desktop-client/src/components/reports/graphs/BarGraph.tsx b/packages/desktop-client/src/components/reports/graphs/BarGraph.tsx
new file mode 100644
index 0000000000..5b3e75b9a8
--- /dev/null
+++ b/packages/desktop-client/src/components/reports/graphs/BarGraph.tsx
@@ -0,0 +1,251 @@
+import React from 'react';
+
+import { css } from 'glamor';
+import {
+ BarChart,
+ Bar,
+ CartesianGrid,
+ //Legend,
+ Cell,
+ ReferenceLine,
+ XAxis,
+ YAxis,
+ Tooltip,
+ ResponsiveContainer,
+} from 'recharts';
+
+import { amountToCurrency } from 'loot-core/src/shared/util';
+
+import { theme } from '../../../style';
+import { type CSSProperties } from '../../../style';
+import AlignedText from '../../common/AlignedText';
+import PrivacyFilter from '../../PrivacyFilter';
+import { getColorScale } from '../chart-theme';
+import Container from '../Container';
+import numberFormatterTooltip from '../numberFormatter';
+
+type PayloadChild = {
+ props: {
+ name: string;
+ fill: string;
+ };
+};
+
+type PayloadItem = {
+ value: string;
+ payload: {
+ name: string;
+ totalAssets: number | string;
+ totalDebts: number | string;
+ totalTotals: number | string;
+ networth: number | string;
+ totalChange: number | string;
+ children: [PayloadChild];
+ };
+};
+
+type CustomTooltipProps = {
+ active?: boolean;
+ payload?: PayloadItem[];
+ balanceTypeOp?: string;
+ yAxis?: string;
+};
+
+const CustomTooltip = ({
+ active,
+ payload,
+ balanceTypeOp,
+ yAxis,
+}: CustomTooltipProps) => {
+ if (active && payload && payload.length) {
+ return (
+ <div
+ className={`${css({
+ zIndex: 1000,
+ pointerEvents: 'none',
+ borderRadius: 2,
+ boxShadow: '0 1px 6px rgba(0, 0, 0, .20)',
+ backgroundColor: theme.menuAutoCompleteBackground,
+ color: theme.menuAutoCompleteText,
+ padding: 10,
+ })}`}
+ >
+ <div>
+ <div style={{ marginBottom: 10 }}>
+ <strong>{payload[0].payload[yAxis]}</strong>
+ </div>
+ <div style={{ lineHeight: 1.5 }}>
+ <PrivacyFilter>
+ {['totalAssets', 'totalTotals'].includes(balanceTypeOp) && (
+ <AlignedText
+ left="Assets:"
+ right={amountToCurrency(payload[0].payload.totalAssets)}
+ />
+ )}
+ {['totalDebts', 'totalTotals'].includes(balanceTypeOp) && (
+ <AlignedText
+ left="Debt:"
+ right={amountToCurrency(payload[0].payload.totalDebts)}
+ />
+ )}
+ {['totalTotals'].includes(balanceTypeOp) && (
+ <AlignedText
+ left="Net:"
+ right={
+ <strong>
+ {amountToCurrency(payload[0].payload.totalTotals)}
+ </strong>
+ }
+ />
+ )}
+ </PrivacyFilter>
+ </div>
+ </div>
+ </div>
+ );
+ }
+};
+
+/* Descoped for future PR
+type CustomLegendProps = {
+ active?: boolean;
+ payload?: PayloadItem[];
+ label?: string;
+};
+
+const CustomLegend = ({ active, payload, label }: CustomLegendProps) => {
+ const agg = payload[0].payload.children.map(leg => {
+ return {
+ name: leg.props.name,
+ color: leg.props.fill,
+ };
+ });
+
+ OnChangeLegend(agg);
+
+ return <div />;
+};
+*/
+
+type BarGraphProps = {
+ style?: CSSProperties;
+ data;
+ groupBy;
+ balanceTypeOp;
+ empty;
+ compact: boolean;
+ domain?: {
+ y?: [number, number];
+ };
+};
+
+function BarGraph({
+ style,
+ data,
+ groupBy,
+ empty,
+ balanceTypeOp,
+ compact,
+ domain,
+}: BarGraphProps) {
+ const colorScale = getColorScale('qualitative');
+ const yAxis = ['Month', 'Year'].includes(groupBy) ? 'date' : 'name';
+ const splitData = ['Month', 'Year'].includes(groupBy) ? 'monthData' : 'data';
+
+ const getVal = obj => {
+ if (balanceTypeOp === 'totalDebts') {
+ return -1 * obj.totalDebts;
+ } else {
+ return obj.totalAssets;
+ }
+ };
+
+ const longestLabelLength = data[splitData]
+ .map(c => c[yAxis])
+ .reduce((acc, cur) => (cur.length > acc ? cur.length : acc), 0);
+
+ return (
+ <Container
+ style={{
+ ...style,
+ ...(compact && { height: 'auto' }),
+ }}
+ >
+ {(width, height, portalHost) =>
+ data[splitData] && (
+ <ResponsiveContainer>
+ <div>
+ {!compact && <div style={{ marginTop: '15px' }} />}
+ <BarChart
+ width={width}
+ height={height}
+ stackOffset="sign"
+ data={data[splitData].filter(i =>
+ !empty ? i[balanceTypeOp] !== 0 : true,
+ )}
+ margin={{ top: 0, right: 0, left: 0, bottom: 0 }}
+ >
+ {
+ //!compact && <Legend content={<CustomLegend />} />
+ }
+ <Tooltip
+ content={
+ <CustomTooltip
+ balanceTypeOp={balanceTypeOp}
+ yAxis={yAxis}
+ />
+ }
+ formatter={numberFormatterTooltip}
+ isAnimationActive={false}
+ />
+ {!compact && <CartesianGrid strokeDasharray="3 3" />}
+ {!compact && (
+ <XAxis
+ dataKey={yAxis}
+ angle={-35}
+ textAnchor="end"
+ height={Math.sqrt(longestLabelLength) * 25}
+ />
+ )}
+ {!compact && <YAxis />}
+ {!compact && <ReferenceLine y={0} stroke="#000" />}
+ <Bar dataKey={val => getVal(val)} stackId="a">
+ {data[splitData]
+ .filter(i => (!empty ? i[balanceTypeOp] !== 0 : true))
+ .map((entry, index) => (
+ <Cell
+ key={`cell-${index}`}
+ fill={
+ yAxis === 'date'
+ ? balanceTypeOp === 'totalDebts'
+ ? theme.reportsRed
+ : theme.reportsBlue
+ : colorScale[index % colorScale.length]
+ }
+ name={entry[yAxis]}
+ />
+ ))}
+ </Bar>
+ {yAxis === 'date' && balanceTypeOp === 'totalTotals' && (
+ <Bar dataKey={'totalDebts'} stackId="a">
+ {data[splitData]
+ .filter(i => (!empty ? i[balanceTypeOp] !== 0 : true))
+ .map((entry, index) => (
+ <Cell
+ key={`cell-${index}`}
+ fill={theme.reportsRed}
+ name={entry.name}
+ />
+ ))}
+ </Bar>
+ )}
+ </BarChart>
+ </div>
+ </ResponsiveContainer>
+ )
+ }
+ </Container>
+ );
+}
+
+export default BarGraph;
diff --git a/packages/desktop-client/src/components/reports/graphs/BarLineGraph.tsx b/packages/desktop-client/src/components/reports/graphs/BarLineGraph.tsx
new file mode 100644
index 0000000000..390fa5e5a1
--- /dev/null
+++ b/packages/desktop-client/src/components/reports/graphs/BarLineGraph.tsx
@@ -0,0 +1,128 @@
+import React from 'react';
+
+import { css } from 'glamor';
+import {
+ ComposedChart,
+ Line,
+ Bar,
+ CartesianGrid,
+ XAxis,
+ YAxis,
+ Tooltip,
+ ResponsiveContainer,
+} from 'recharts';
+
+import { theme } from '../../../style';
+import { type CSSProperties } from '../../../style';
+import AlignedText from '../../common/AlignedText';
+import PrivacyFilter from '../../PrivacyFilter';
+import Container from '../Container';
+import numberFormatterTooltip from '../numberFormatter';
+
+type PayloadItem = {
+ payload: {
+ date: string;
+ assets: number | string;
+ debt: number | string;
+ networth: number | string;
+ change: number | string;
+ };
+};
+
+type CustomTooltipProps = {
+ active?: boolean;
+ payload?: PayloadItem[];
+ label?: string;
+};
+
+const CustomTooltip = ({ active, payload, label }: CustomTooltipProps) => {
+ if (active && payload && payload.length) {
+ return (
+ <div
+ className={`${css({
+ zIndex: 1000,
+ pointerEvents: 'none',
+ borderRadius: 2,
+ boxShadow: '0 1px 6px rgba(0, 0, 0, .20)',
+ backgroundColor: theme.menuAutoCompleteBackground,
+ color: theme.menuAutoCompleteText,
+ padding: 10,
+ })}`}
+ >
+ <div>
+ <div style={{ marginBottom: 10 }}>
+ <strong>{payload[0].payload.date}</strong>
+ </div>
+ <div style={{ lineHeight: 1.5 }}>
+ <PrivacyFilter>
+ <AlignedText left="Assets:" right={payload[0].payload.assets} />
+ <AlignedText left="Debt:" right={payload[0].payload.debt} />
+ <AlignedText
+ left="Change:"
+ right={<strong>{payload[0].payload.change}</strong>}
+ />
+ </PrivacyFilter>
+ </div>
+ </div>
+ </div>
+ );
+ }
+};
+
+type BarLineGraphProps = {
+ style?: CSSProperties;
+ graphData;
+ compact: boolean;
+ domain?: {
+ y?: [number, number];
+ };
+};
+
+function BarLineGraph({
+ style,
+ graphData,
+ compact,
+ domain,
+}: BarLineGraphProps) {
+ const tickFormatter = tick => {
+ return `${Math.round(tick).toLocaleString()}`; // Formats the tick values as strings with commas
+ };
+
+ return (
+ <Container
+ style={{
+ ...style,
+ ...(compact && { height: 'auto' }),
+ }}
+ >
+ {(width, height, portalHost) =>
+ graphData && (
+ <ResponsiveContainer>
+ <div>
+ {!compact && <div style={{ marginTop: '15px' }} />}
+ <ComposedChart
+ width={width}
+ height={height}
+ data={graphData.data}
+ margin={{ top: 0, right: 0, left: 0, bottom: 0 }}
+ >
+ <Tooltip
+ content={<CustomTooltip />}
+ formatter={numberFormatterTooltip}
+ isAnimationActive={false}
+ />
+ <CartesianGrid strokeDasharray="3 3" />
+ <XAxis dataKey="x" />
+ <YAxis dataKey="y" tickFormatter={tickFormatter} />
+ <Bar type="monotone" dataKey="y" fill="#8884d8" />
+ <Line type="monotone" dataKey="y" stroke="#8884d8" />
+ </ComposedChart>
+ </div>
+ </ResponsiveContainer>
+ )
+ }
+ </Container>
+ );
+}
+
+export default BarLineGraph;
diff --git a/packages/desktop-client/src/components/reports/graphs/CategorySpendingGraph.tsx b/packages/desktop-client/src/components/reports/graphs/CategorySpendingGraph.tsx
index a74c5ebf7b..671101561e 100644
--- a/packages/desktop-client/src/components/reports/graphs/CategorySpendingGraph.tsx
+++ b/packages/desktop-client/src/components/reports/graphs/CategorySpendingGraph.tsx
@@ -5,9 +5,9 @@ import { VictoryAxis, VictoryBar, VictoryChart, VictoryStack } from 'victory';
import { chartTheme } from '../chart-theme';
import Container from '../Container';
+import { type CategorySpendingGraphData } from '../spreadsheets/category-spending-spreadsheet';
import Tooltip from '../Tooltip';
-import { type CategorySpendingGraphData } from './category-spending-spreadsheet';
import { Area } from './common';
type CategorySpendingGraphProps = {
diff --git a/packages/desktop-client/src/components/reports/graphs/DonutGraph.tsx b/packages/desktop-client/src/components/reports/graphs/DonutGraph.tsx
new file mode 100644
index 0000000000..41798b395a
--- /dev/null
+++ b/packages/desktop-client/src/components/reports/graphs/DonutGraph.tsx
@@ -0,0 +1,175 @@
+import React from 'react';
+
+import { css } from 'glamor';
+import {
+ PieChart,
+ Pie,
+ Cell,
+ //Legend,
+ Tooltip,
+ ResponsiveContainer,
+} from 'recharts';
+
+import { amountToCurrency } from 'loot-core/src/shared/util';
+
+import { theme } from '../../../style';
+import { type CSSProperties } from '../../../style';
+import Text from '../../common/Text';
+import PrivacyFilter from '../../PrivacyFilter';
+import { getColorScale } from '../chart-theme';
+import Container from '../Container';
+import numberFormatterTooltip from '../numberFormatter';
+
+type PayloadItem = {
+ name: string;
+ value: string;
+ color: string;
+ payload: {
+ date: string;
+ assets: number | string;
+ debt: number | string;
+ networth: number | string;
+ change: number | string;
+ fill: string;
+ };
+};
+
+type CustomTooltipProps = {
+ active?: boolean;
+ payload?: PayloadItem[];
+ label?: string;
+};
+
+const CustomTooltip = ({ active, payload, label }: CustomTooltipProps) => {
+ if (active && payload && payload.length) {
+ return (
+ <div
+ className={`${css({
+ zIndex: 1000,
+ pointerEvents: 'none',
+ borderRadius: 2,
+ boxShadow: '0 1px 6px rgba(0, 0, 0, .20)',
+ backgroundColor: theme.menuAutoCompleteBackground,
+ color: theme.menuAutoCompleteText,
+ padding: 10,
+ })}`}
+ >
+ <div>
+ <div style={{ marginBottom: 10 }}>
+ <strong>{payload[0].name}</strong>
+ </div>
+ <div style={{ lineHeight: 1.5 }}>
+ <PrivacyFilter>
+ <Text style={{ color: payload[0].payload.fill }}>
+ {amountToCurrency(payload[0].value)}
+ </Text>
+ </PrivacyFilter>
+ </div>
+ </div>
+ </div>
+ );
+ }
+};
+
+/* Descoped for future PR
+type CustomLegendProps = {
+ active?: boolean;
+ payload?: PayloadItem[];
+ label?: string;
+};
+
+const CustomLegend = ({ active, payload, label }: CustomLegendProps) => {
+ const agg = payload.map(leg => {
+ return {
+ name: leg.value,
+ color: leg.color,
+ };
+ });
+
+ OnChangeLegend(agg);
+
+ return <div />;
+};
+*/
+
+type DonutGraphProps = {
+ style?: CSSProperties;
+ data;
+ groupBy;
+ balanceTypeOp;
+ empty;
+ compact: boolean;
+ domain?: {
+ y?: [number, number];
+ };
+};
+
+function DonutGraph({
+ style,
+ data,
+ groupBy,
+ empty,
+ balanceTypeOp,
+ compact,
+ domain,
+}: DonutGraphProps) {
+ const colorScale = getColorScale('qualitative');
+ const yAxis = ['Month', 'Year'].includes(groupBy) ? 'date' : 'name';
+ const splitData = ['Month', 'Year'].includes(groupBy) ? 'monthData' : 'data';
+
+ const getVal = obj => {
+ if (balanceTypeOp === 'totalDebts') {
+ return -1 * obj[balanceTypeOp];
+ } else {
+ return obj[balanceTypeOp];
+ }
+ };
+
+ return (
+ <Container
+ style={{
+ ...style,
+ ...(compact && { height: 'auto' }),
+ }}
+ >
+ {(width, height, portalHost) =>
+ data[splitData] && (
+ <ResponsiveContainer>
+ <div>
+ {!compact && <div style={{ marginTop: '15px' }} />}
+ <PieChart width={width} height={height}>
+ {
+ //<Legend content={<CustomLegend />} />
+ }
+ <Tooltip
+ content={<CustomTooltip />}
+ formatter={numberFormatterTooltip}
+ isAnimationActive={false}
+ />
+ <Pie
+ dataKey={val => getVal(val)}
+ nameKey={yAxis}
+ isAnimationActive={false}
+ data={data[splitData].filter(i =>
+ !empty ? i[balanceTypeOp] !== 0 : true,
+ )}
+ innerRadius={Math.min(width, height) * 0.2}
+ fill="#8884d8"
+ >
+ {data[splitData].map((entry, index) => (
+ <Cell
+ key={`cell-${index}`}
+ fill={colorScale[index % colorScale.length]}
+ />
+ ))}
+ </Pie>
+ </PieChart>
+ </div>
+ </ResponsiveContainer>
+ )
+ }
+ </Container>
+ );
+}
+
+export default DonutGraph;
diff --git a/packages/desktop-client/src/components/reports/graphs/LineGraph.tsx b/packages/desktop-client/src/components/reports/graphs/LineGraph.tsx
new file mode 100644
index 0000000000..1c373de393
--- /dev/null
+++ b/packages/desktop-client/src/components/reports/graphs/LineGraph.tsx
@@ -0,0 +1,121 @@
+import React from 'react';
+
+import { css } from 'glamor';
+import {
+ LineChart,
+ Line,
+ CartesianGrid,
+ XAxis,
+ YAxis,
+ Tooltip,
+ ResponsiveContainer,
+} from 'recharts';
+
+import { theme } from '../../../style';
+import { type CSSProperties } from '../../../style';
+import AlignedText from '../../common/AlignedText';
+import PrivacyFilter from '../../PrivacyFilter';
+import Container from '../Container';
+import numberFormatterTooltip from '../numberFormatter';
+
+type PayloadItem = {
+ payload: {
+ date: string;
+ assets: number | string;
+ debt: number | string;
+ networth: number | string;
+ change: number | string;
+ };
+};
+
+type CustomTooltipProps = {
+ active?: boolean;
+ payload?: PayloadItem[];
+ label?: string;
+};
+
+const CustomTooltip = ({ active, payload, label }: CustomTooltipProps) => {
+ if (active && payload && payload.length) {
+ return (
+ <div
+ className={`${css({
+ zIndex: 1000,
+ pointerEvents: 'none',
+ borderRadius: 2,
+ boxShadow: '0 1px 6px rgba(0, 0, 0, .20)',
+ backgroundColor: theme.menuAutoCompleteBackground,
+ color: theme.menuAutoCompleteText,
+ padding: 10,
+ })}`}
+ >
+ <div>
+ <div style={{ marginBottom: 10 }}>
+ <strong>{payload[0].payload.date}</strong>
+ </div>
+ <div style={{ lineHeight: 1.5 }}>
+ <PrivacyFilter>
+ <AlignedText left="Assets:" right={payload[0].payload.assets} />
+ <AlignedText left="Debt:" right={payload[0].payload.debt} />
+ <AlignedText
+ left="Change:"
+ right={<strong>{payload[0].payload.change}</strong>}
+ />
+ </PrivacyFilter>
+ </div>
+ </div>
+ </div>
+ );
+ }
+};
+
+type LineGraphProps = {
+ style?: CSSProperties;
+ graphData;
+ compact: boolean;
+ domain?: {
+ y?: [number, number];
+ };
+};
+
+function LineGraph({ style, graphData, compact, domain }: LineGraphProps) {
+ const tickFormatter = tick => {
+ return `${Math.round(tick).toLocaleString()}`; // Formats the tick values as strings with commas
+ };
+
+ return (
+ <Container
+ style={{
+ ...style,
+ ...(compact && { height: 'auto' }),
+ }}
+ >
+ {(width, height, portalHost) =>
+ graphData && (
+ <ResponsiveContainer>
+ <div>
+ {!compact && <div style={{ marginTop: '15px' }} />}
+ <LineChart
+ width={width}
+ height={height}
+ data={graphData.data}
+ margin={{ top: 0, right: 0, left: 0, bottom: 0 }}
+ >
+ <Tooltip
+ content={<CustomTooltip />}
+ formatter={numberFormatterTooltip}
+ isAnimationActive={false}
+ />
+ <CartesianGrid strokeDasharray="3 3" />
+ <XAxis dataKey="x" />
+ <YAxis dataKey="y" tickFormatter={tickFormatter} />
+ <Line type="monotone" dataKey="y" stroke="#8884d8" />
+ </LineChart>
+ </div>
+ </ResponsiveContainer>
+ )
+ }
+ </Container>
+ );
+}
+
+export default LineGraph;
diff --git a/packages/desktop-client/src/components/reports/graphs/NetWorthGraph.tsx b/packages/desktop-client/src/components/reports/graphs/NetWorthGraph.tsx
index 5a09531c7a..142ffb75d5 100644
--- a/packages/desktop-client/src/components/reports/graphs/NetWorthGraph.tsx
+++ b/packages/desktop-client/src/components/reports/graphs/NetWorthGraph.tsx
@@ -15,6 +15,7 @@ import { theme } from '../../../style';
import { type CSSProperties } from '../../../style';
import AlignedText from '../../common/AlignedText';
import Container from '../Container';
+import numberFormatterTooltip from '../numberFormatter';
type NetWorthGraphProps = {
style?: CSSProperties;
@@ -24,14 +25,6 @@ type NetWorthGraphProps = {
y?: [number, number];
};
};
-type PotentialNumber = number | string | undefined | null;
-
-const numberFormatterTooltip = (value: PotentialNumber): number | null => {
- if (typeof value === 'number') {
- return Math.round(value);
- }
- return null; // or some default value for other cases
-};
function NetWorthGraph({
style,
diff --git a/packages/desktop-client/src/components/reports/graphs/SankeyGraph.tsx b/packages/desktop-client/src/components/reports/graphs/SankeyGraph.tsx
index 182b0fc7d4..de73a14d6f 100644
--- a/packages/desktop-client/src/components/reports/graphs/SankeyGraph.tsx
+++ b/packages/desktop-client/src/components/reports/graphs/SankeyGraph.tsx
@@ -9,20 +9,13 @@ import {
} from 'recharts';
import Container from '../Container';
+import numberFormatterTooltip from '../numberFormatter';
type SankeyProps = {
style;
data;
compact: boolean;
};
-type PotentialNumber = number | string | undefined | null;
-
-const numberFormatterTooltip = (value: PotentialNumber): number | null => {
- if (typeof value === 'number') {
- return Math.round(value);
- }
- return null; // or some default value for other cases
-};
function SankeyNode({ x, y, width, height, index, payload, containerWidth }) {
const isOut = x + width + 6 > containerWidth;
diff --git a/packages/desktop-client/src/components/reports/graphs/StackedBarGraph.tsx b/packages/desktop-client/src/components/reports/graphs/StackedBarGraph.tsx
new file mode 100644
index 0000000000..df19427fb6
--- /dev/null
+++ b/packages/desktop-client/src/components/reports/graphs/StackedBarGraph.tsx
@@ -0,0 +1,191 @@
+import React from 'react';
+
+import { css } from 'glamor';
+import {
+ BarChart,
+ Bar,
+ CartesianGrid,
+ //Legend,
+ XAxis,
+ YAxis,
+ Tooltip,
+ ResponsiveContainer,
+} from 'recharts';
+
+import { amountToCurrency } from 'loot-core/src/shared/util';
+
+import { theme } from '../../../style';
+import { type CSSProperties } from '../../../style';
+import AlignedText from '../../common/AlignedText';
+import PrivacyFilter from '../../PrivacyFilter';
+import { getColorScale } from '../chart-theme';
+import Container from '../Container';
+import numberFormatterTooltip from '../numberFormatter';
+
+type PayloadItem = {
+ name: string;
+ value: number;
+ color: string;
+ payload: {
+ name: string;
+ color: number | string;
+ };
+};
+
+type CustomTooltipProps = {
+ active?: boolean;
+ payload?: PayloadItem[];
+ label?: string;
+};
+
+const CustomTooltip = ({ active, payload, label }: CustomTooltipProps) => {
+ if (active && payload && payload.length) {
+ let sumTotals = 0;
+ return (
+ <div
+ className={`${css({
+ zIndex: 1000,
+ pointerEvents: 'none',
+ borderRadius: 2,
+ boxShadow: '0 1px 6px rgba(0, 0, 0, .20)',
+ backgroundColor: theme.menuAutoCompleteBackground,
+ color: theme.menuAutoCompleteText,
+ padding: 10,
+ })}`}
+ >
+ <div>
+ <div style={{ marginBottom: 10 }}>
+ <strong>{label}</strong>
+ </div>
+ <div style={{ lineHeight: 1.5 }}>
+ <PrivacyFilter>
+ {payload
+ .slice(0)
+ .reverse()
+ .map(pay => {
+ sumTotals += pay.value;
+ return (
+ pay.value !== 0 && (
+ <AlignedText
+ key={pay.name}
+ left={pay.name}
+ right={amountToCurrency(pay.value)}
+ style={{ color: pay.color }}
+ />
+ )
+ );
+ })}
+ <AlignedText
+ left={'Total'}
+ right={amountToCurrency(sumTotals)}
+ style={{
+ fontWeight: 600,
+ }}
+ />
+ </PrivacyFilter>
+ </div>
+ </div>
+ </div>
+ );
+ }
+};
+
+/* Descoped for future PR
+type CustomLegendProps = {
+ active?: boolean;
+ payload?: PayloadItem[];
+ label?: string;
+};
+
+const CustomLegend = ({ active, payload, label }: CustomLegendProps) => {
+ const agg = payload.map(leg => {
+ return {
+ name: leg.value,
+ color: leg.color,
+ };
+ });
+
+ OnChangeLegend(agg.slice(0).reverse());
+
+ return <div />;
+};
+*/
+
+type StackedBarGraphProps = {
+ style?: CSSProperties;
+ data;
+ balanceTypeOp;
+ compact: boolean;
+ domain?: {
+ y?: [number, number];
+ };
+};
+
+function StackedBarGraph({
+ style,
+ data,
+ balanceTypeOp,
+ compact,
+ domain,
+}: StackedBarGraphProps) {
+ const colorScale = getColorScale('qualitative');
+
+ const getVal = (obj, key) => {
+ if (balanceTypeOp === 'totalDebts') {
+ return -1 * obj[key].amount;
+ } else {
+ return obj[key].amount;
+ }
+ };
+
+ return (
+ <Container
+ style={{
+ ...style,
+ ...(compact && { height: 'auto' }),
+ }}
+ >
+ {(width, height, portalHost) =>
+ data.stackedData && (
+ <ResponsiveContainer>
+ <div>
+ {!compact && <div style={{ marginTop: '15px' }} />}
+ <BarChart
+ width={width}
+ height={height}
+ data={data.stackedData}
+ margin={{ top: 0, right: 0, left: 0, bottom: 0 }}
+ >
+ {
+ //<Legend content={<CustomLegend />} />
+ }
+ <Tooltip
+ content={<CustomTooltip />}
+ formatter={numberFormatterTooltip}
+ isAnimationActive={false}
+ />
+ <CartesianGrid strokeDasharray="3 3" />
+ <XAxis dataKey="date" />
+ <YAxis />
+ {data.groupBy
+ .slice(0)
+ .reverse()
+ .map((c, index) => (
+ <Bar
+ key={c.id}
+ dataKey={val => getVal(val, c.name)}
+ name={c.name}
+ stackId="a"
+ fill={colorScale[index % colorScale.length]}
+ />
+ ))}
+ </BarChart>
+ </div>
+ </ResponsiveContainer>
+ )
+ }
+ </Container>
+ );
+}
+
+export default StackedBarGraph;
diff --git a/packages/desktop-client/src/components/reports/numberFormatter.tsx b/packages/desktop-client/src/components/reports/numberFormatter.tsx
new file mode 100644
index 0000000000..cf6af80c96
--- /dev/null
+++ b/packages/desktop-client/src/components/reports/numberFormatter.tsx
@@ -0,0 +1,10 @@
+type PotentialNumber = number | string | undefined | null;
+
+const numberFormatterTooltip = (value: PotentialNumber): number | null => {
+ if (typeof value === 'number') {
+ return Math.round(value);
+ }
+ return null; // or some default value for other cases
+};
+
+export default numberFormatterTooltip;
diff --git a/packages/desktop-client/src/components/reports/CashFlow.js b/packages/desktop-client/src/components/reports/reports/CashFlow.js
similarity index 89%
rename from packages/desktop-client/src/components/reports/CashFlow.js
rename to packages/desktop-client/src/components/reports/reports/CashFlow.js
index 5869b7083e..1b57e1424c 100644
--- a/packages/desktop-client/src/components/reports/CashFlow.js
+++ b/packages/desktop-client/src/components/reports/reports/CashFlow.js
@@ -6,20 +6,19 @@ import { send } from 'loot-core/src/platform/client/fetch';
import * as monthUtils from 'loot-core/src/shared/months';
import { integerToCurrency } from 'loot-core/src/shared/util';
-import useFilters from '../../hooks/useFilters';
-import { theme, styles } from '../../style';
-import AlignedText from '../common/AlignedText';
-import Block from '../common/Block';
-import Paragraph from '../common/Paragraph';
-import Text from '../common/Text';
-import View from '../common/View';
-import PrivacyFilter from '../PrivacyFilter';
-
-import Change from './Change';
-import { cashFlowByDate } from './graphs/cash-flow-spreadsheet';
-import CashFlowGraph from './graphs/CashFlowGraph';
-import Header from './Header';
-import useReport from './useReport';
+import useFilters from '../../../hooks/useFilters';
+import { theme, styles } from '../../../style';
+import AlignedText from '../../common/AlignedText';
+import Block from '../../common/Block';
+import Paragraph from '../../common/Paragraph';
+import Text from '../../common/Text';
+import View from '../../common/View';
+import PrivacyFilter from '../../PrivacyFilter';
+import Change from '../Change';
+import CashFlowGraph from '../graphs/CashFlowGraph';
+import Header from '../Header';
+import { cashFlowByDate } from '../spreadsheets/cash-flow-spreadsheet';
+import useReport from '../useReport';
function CashFlow() {
const {
diff --git a/packages/desktop-client/src/components/reports/reports/CashFlowCard.js b/packages/desktop-client/src/components/reports/reports/CashFlowCard.js
new file mode 100644
index 0000000000..1ccf6dfc65
--- /dev/null
+++ b/packages/desktop-client/src/components/reports/reports/CashFlowCard.js
@@ -0,0 +1,153 @@
+import React, { useState, useMemo, useCallback } from 'react';
+
+import { VictoryBar, VictoryGroup, VictoryVoronoiContainer } from 'victory';
+
+import * as monthUtils from 'loot-core/src/shared/months';
+import { integerToCurrency } from 'loot-core/src/shared/util';
+
+import { theme, styles } from '../../../style';
+import Block from '../../common/Block';
+import View from '../../common/View';
+import PrivacyFilter from '../../PrivacyFilter';
+import Change from '../Change';
+import { chartTheme } from '../chart-theme';
+import Container from '../Container';
+import DateRange from '../DateRange';
+import { LoadingIndicator } from '../Overview';
+import ReportCard from '../ReportCard';
+import { simpleCashFlow } from '../spreadsheets/cash-flow-spreadsheet';
+import Tooltip from '../Tooltip';
+import useReport from '../useReport';
+
+function CashFlowCard() {
+ const end = monthUtils.currentDay();
+ const start = monthUtils.currentMonth() + '-01';
+
+ const params = useMemo(() => simpleCashFlow(start, end), [start, end]);
+ const data = useReport('cash_flow_simple', params);
+
+ const [isCardHovered, setIsCardHovered] = useState(false);
+ const onCardHover = useCallback(() => setIsCardHovered(true));
+ const onCardHoverEnd = useCallback(() => setIsCardHovered(false));
+
+ const { graphData } = data || {};
+ const expense = -(graphData?.expense || 0);
+ const income = graphData?.income || 0;
+
+ return (
+ <ReportCard flex={1} to="/reports/cash-flow">
+ <View
+ style={{ flex: 1 }}
+ onPointerEnter={onCardHover}
+ onPointerLeave={onCardHoverEnd}
+ >
+ <View style={{ flexDirection: 'row', padding: 20 }}>
+ <View style={{ flex: 1 }}>
+ <Block
+ style={{ ...styles.mediumText, fontWeight: 500, marginBottom: 5 }}
+ role="heading"
+ >
+ Cash Flow
+ </Block>
+ <DateRange start={start} end={end} />
+ </View>
+ {data && (
+ <View style={{ textAlign: 'right' }}>
+ <PrivacyFilter activationFilters={[!isCardHovered]}>
+ <Change
+ amount={income - expense}
+ style={{ color: theme.altTableText, fontWeight: 300 }}
+ />
+ </PrivacyFilter>
+ </View>
+ )}
+ </View>
+
+ {data ? (
+ <Container style={{ height: 'auto', flex: 1 }}>
+ {(width, height, portalHost) => (
+ <VictoryGroup
+ colorScale={[chartTheme.colors.blue, chartTheme.colors.red]}
+ width={100}
+ height={height}
+ theme={chartTheme}
+ domain={{
+ x: [0, 100],
+ y: [0, Math.max(income, expense, 100)],
+ }}
+ containerComponent={
+ <VictoryVoronoiContainer voronoiDimension="x" />
+ }
+ labelComponent={
+ <Tooltip
+ portalHost={portalHost}
+ offsetX={(width - 100) / 2}
+ offsetY={y => (y + 40 > height ? height - 40 : y)}
+ light={true}
+ forceActive={true}
+ style={{
+ padding: 0,
+ }}
+ />
+ }
+ padding={{
+ top: 0,
+ bottom: 0,
+ left: 0,
+ right: 0,
+ }}
+ >
+ <VictoryBar
+ barWidth={13}
+ data={[
+ {
+ x: 30,
+ y: Math.max(income, 5),
+ premadeLabel: (
+ <View style={{ textAlign: 'right' }}>
+ Income
+ <View>
+ <PrivacyFilter activationFilters={[!isCardHovered]}>
+ {integerToCurrency(income)}
+ </PrivacyFilter>
+ </View>
+ </View>
+ ),
+ labelPosition: 'left',
+ },
+ ]}
+ labels={d => d.premadeLabel}
+ />
+ <VictoryBar
+ barWidth={13}
+ data={[
+ {
+ x: 60,
+ y: Math.max(expense, 5),
+ premadeLabel: (
+ <View>
+ Expenses
+ <View>
+ <PrivacyFilter activationFilters={[!isCardHovered]}>
+ {integerToCurrency(expense)}
+ </PrivacyFilter>
+ </View>
+ </View>
+ ),
+ labelPosition: 'right',
+ },
+ ]}
+ labels={d => d.premadeLabel}
+ />
+ </VictoryGroup>
+ )}
+ </Container>
+ ) : (
+ <LoadingIndicator />
+ )}
+ </View>
+ </ReportCard>
+ );
+}
+
+export default CashFlowCard;
diff --git a/packages/desktop-client/src/components/reports/CategorySpending.js b/packages/desktop-client/src/components/reports/reports/CategorySpending.js
similarity index 90%
rename from packages/desktop-client/src/components/reports/CategorySpending.js
rename to packages/desktop-client/src/components/reports/reports/CategorySpending.js
index eac84d9f93..23649a59e4 100644
--- a/packages/desktop-client/src/components/reports/CategorySpending.js
+++ b/packages/desktop-client/src/components/reports/reports/CategorySpending.js
@@ -5,17 +5,16 @@ import * as d from 'date-fns';
import { send } from 'loot-core/src/platform/client/fetch';
import * as monthUtils from 'loot-core/src/shared/months';
-import useCategories from '../../hooks/useCategories';
-import { styles } from '../../style';
-import Select from '../common/Select';
-import View from '../common/View';
-
-import CategorySelector from './CategorySelector';
-import categorySpendingSpreadsheet from './graphs/category-spending-spreadsheet';
-import CategorySpendingGraph from './graphs/CategorySpendingGraph';
-import Header from './Header';
-import useReport from './useReport';
-import { fromDateRepr } from './util';
+import useCategories from '../../../hooks/useCategories';
+import { styles } from '../../../style';
+import Select from '../../common/Select';
+import View from '../../common/View';
+import CategorySelector from '../CategorySelector';
+import CategorySpendingGraph from '../graphs/CategorySpendingGraph';
+import Header from '../Header';
+import categorySpendingSpreadsheet from '../spreadsheets/category-spending-spreadsheet';
+import useReport from '../useReport';
+import { fromDateRepr } from '../util';
function CategoryAverage() {
const categories = useCategories();
diff --git a/packages/desktop-client/src/components/reports/reports/CategorySpendingCard.js b/packages/desktop-client/src/components/reports/reports/CategorySpendingCard.js
new file mode 100644
index 0000000000..1b4742c182
--- /dev/null
+++ b/packages/desktop-client/src/components/reports/reports/CategorySpendingCard.js
@@ -0,0 +1,63 @@
+import React, { useMemo } from 'react';
+
+import * as monthUtils from 'loot-core/src/shared/months';
+
+import useCategories from '../../../hooks/useCategories';
+import { styles } from '../../../style';
+import Block from '../../common/Block';
+import View from '../../common/View';
+import DateRange from '../DateRange';
+import CategorySpendingGraph from '../graphs/CategorySpendingGraph';
+import { LoadingIndicator } from '../Overview';
+import ReportCard from '../ReportCard';
+import categorySpendingSpreadsheet from '../spreadsheets/category-spending-spreadsheet';
+import useReport from '../useReport';
+
+function CategorySpendingCard() {
+ const { list: categories = [] } = useCategories();
+
+ const end = monthUtils.currentDay();
+ const start = monthUtils.subMonths(end, 3);
+
+ const params = useMemo(() => {
+ return categorySpendingSpreadsheet(
+ start,
+ end,
+ 3,
+ categories.filter(category => !category.is_income && !category.hidden),
+ );
+ }, [start, end, categories]);
+
+ const perCategorySpending = useReport('category_spending', params);
+
+ return (
+ <ReportCard flex={1} to="/reports/category-spending">
+ <View>
+ <View style={{ flexDirection: 'row', padding: '20px 20px 0' }}>
+ <View style={{ flex: 1 }}>
+ <Block
+ style={{ ...styles.mediumText, fontWeight: 500, marginBottom: 5 }}
+ role="heading"
+ >
+ Spending
+ </Block>
+ <DateRange start={start} end={end} />
+ </View>
+ </View>
+ </View>
+
+ {perCategorySpending ? (
+ <CategorySpendingGraph
+ start={start}
+ end={end}
+ graphData={perCategorySpending}
+ compact={true}
+ />
+ ) : (
+ <LoadingIndicator />
+ )}
+ </ReportCard>
+ );
+}
+
+export default CategorySpendingCard;
diff --git a/packages/desktop-client/src/components/reports/reports/CustomReport.js b/packages/desktop-client/src/components/reports/reports/CustomReport.js
new file mode 100644
index 0000000000..8aeb682c95
--- /dev/null
+++ b/packages/desktop-client/src/components/reports/reports/CustomReport.js
@@ -0,0 +1,341 @@
+import React, { useState, useEffect, useMemo } from 'react';
+import { useSelector } from 'react-redux';
+
+import * as d from 'date-fns';
+
+import { send } from 'loot-core/src/platform/client/fetch';
+import * as monthUtils from 'loot-core/src/shared/months';
+import { amountToCurrency } from 'loot-core/src/shared/util';
+
+import useCategories from '../../../hooks/useCategories';
+import useFilters from '../../../hooks/useFilters';
+import { theme, styles } from '../../../style';
+import AlignedText from '../../common/AlignedText';
+import Block from '../../common/Block';
+import Text from '../../common/Text';
+import View from '../../common/View';
+import { AppliedFilters } from '../../filters/FiltersMenu';
+import PrivacyFilter from '../../PrivacyFilter';
+import { ChooseGraph } from '../ChooseGraph';
+import Header from '../Header';
+import { ReportOptions } from '../ReportOptions';
+import { ReportSidebar } from '../ReportSidebar';
+import { ReportLegend, ReportSummary } from '../ReportSummary';
+import { ReportTopbar } from '../ReportTopbar';
+import defaultSpreadsheet from '../spreadsheets/default-spreadsheet';
+import useReport from '../useReport';
+import { fromDateRepr } from '../util';
+
+export default function CustomReport() {
+ const categories = useCategories();
+
+ let { payees, accounts } = useSelector(state => {
+ return {
+ payees: state.queries.payees,
+ accounts: state.queries.accounts,
+ };
+ });
+
+ const {
+ filters,
+ conditionsOp,
+ onApply: onApplyFilter,
+ onDelete: onDeleteFilter,
+ onUpdate: onUpdateFilter,
+ onCondOpChange,
+ } = useFilters();
+
+ const [selectedCategories, setSelectedCategories] = useState(null);
+ const [allMonths, setAllMonths] = useState(null);
+ const [typeDisabled, setTypeDisabled] = useState(['Net']);
+ const [start, setStart] = useState(
+ monthUtils.subMonths(monthUtils.currentMonth(), 5),
+ );
+ const [end, setEnd] = useState(monthUtils.currentMonth());
+
+ const [mode, setMode] = useState('total');
+ const [groupBy, setGroupBy] = useState('Category');
+ const [balanceType, setBalanceType] = useState('Expense');
+ const [empty, setEmpty] = useState(false);
+ const [hidden, setHidden] = useState(false);
+ const [uncat, setUncat] = useState(false);
+ const [dateRange, setDateRange] = useState('6 months');
+
+ const [graphType, setGraphType] = useState('BarGraph');
+ const [viewLegend, setViewLegend] = useState(false);
+ const [viewSummary, setViewSummary] = useState(false);
+ const [viewLabels, setViewLabels] = useState(false);
+ //const [legend, setLegend] = useState([]);
+ let legend = [];
+ const dateRangeLine = ReportOptions.dateRange.length - 1;
+
+ const months = monthUtils.rangeInclusive(start, end);
+ const getGraphData = useMemo(() => {
+ return defaultSpreadsheet(
+ start,
+ end,
+ groupBy,
+ ReportOptions.balanceTypeMap.get(balanceType),
+ categories,
+ selectedCategories,
+ payees,
+ accounts,
+ filters,
+ conditionsOp,
+ hidden,
+ uncat,
+ );
+ }, [
+ start,
+ end,
+ groupBy,
+ balanceType,
+ categories,
+ selectedCategories,
+ payees,
+ accounts,
+ filters,
+ conditionsOp,
+ hidden,
+ uncat,
+ ]);
+ const data = useReport('default', getGraphData);
+
+ useEffect(() => {
+ if (selectedCategories === null && categories.list.length !== 0) {
+ setSelectedCategories(categories.list);
+ }
+ }, [categories, selectedCategories]);
+
+ useEffect(() => {
+ async function run() {
+ const trans = await send('get-earliest-transaction');
+ const currentMonth = monthUtils.currentMonth();
+ let earliestMonth = trans
+ ? monthUtils.monthFromDate(d.parseISO(fromDateRepr(trans.date)))
+ : currentMonth;
+
+ // Make sure the month selects are at least populates with a
+ // year's worth of months. We can undo this when we have fancier
+ // date selects.
+ const yearAgo = monthUtils.subMonths(monthUtils.currentMonth(), 12);
+ if (earliestMonth > yearAgo) {
+ earliestMonth = yearAgo;
+ }
+
+ const allMonths = monthUtils
+ .rangeInclusive(earliestMonth, monthUtils.currentMonth())
+ .map(month => ({
+ name: month,
+ pretty: monthUtils.format(month, 'MMMM, yyyy'),
+ }))
+ .reverse();
+
+ setAllMonths(allMonths);
+ }
+ run();
+ }, []);
+
+ let [scrollWidth, setScrollWidth] = useState(0);
+
+ if (!allMonths || !data) {
+ return null;
+ }
+
+ const onChangeDates = (start, end) => {
+ setStart(start);
+ setEnd(end);
+ };
+
+ return (
+ <View style={{ ...styles.page, minWidth: 650, overflow: 'hidden' }}>
+ <Header
+ title="Custom Reports"
+ allMonths={allMonths}
+ start={start}
+ end={end}
+ />
+ <View
+ style={{
+ display: 'flex',
+ flexDirection: 'row',
+ padding: 15,
+ paddingTop: 0,
+ flexGrow: 1,
+ }}
+ >
+ <ReportSidebar
+ start={start}
+ end={end}
+ onChangeDates={onChangeDates}
+ dateRange={dateRange}
+ setDateRange={setDateRange}
+ dateRangeLine={dateRangeLine}
+ allMonths={allMonths}
+ graphType={graphType}
+ setGraphType={setGraphType}
+ setViewLegend={setViewLegend}
+ typeDisabled={typeDisabled}
+ setTypeDisabled={setTypeDisabled}
+ groupBy={groupBy}
+ setGroupBy={setGroupBy}
+ balanceType={balanceType}
+ setBalanceType={setBalanceType}
+ mode={mode}
+ setMode={setMode}
+ empty={empty}
+ setEmpty={setEmpty}
+ hidden={hidden}
+ setHidden={setHidden}
+ uncat={uncat}
+ setUncat={setUncat}
+ categories={categories}
+ selectedCategories={selectedCategories}
+ setSelectedCategories={setSelectedCategories}
+ />
+ <View
+ style={{
+ flexGrow: 1,
+ }}
+ >
+ <ReportTopbar
+ graphType={graphType}
+ setGraphType={setGraphType}
+ mode={mode}
+ viewLegend={viewLegend}
+ setViewLegend={setViewLegend}
+ setTypeDisabled={setTypeDisabled}
+ balanceType={balanceType}
+ setBalanceType={setBalanceType}
+ groupBy={groupBy}
+ setGroupBy={setGroupBy}
+ viewSummary={viewSummary}
+ setViewSummary={setViewSummary}
+ viewLabels={viewLabels}
+ setViewLabels={setViewLabels}
+ onApplyFilter={onApplyFilter}
+ />
+ {filters && filters.length > 0 && (
+ <View
+ style={{ marginBottom: 10, marginLeft: 5, flexShrink: 0 }}
+ spacing={2}
+ direction="row"
+ justify="flex-start"
+ align="flex-start"
+ >
+ <AppliedFilters
+ filters={filters}
+ onUpdate={onUpdateFilter}
+ onDelete={onDeleteFilter}
+ conditionsOp={conditionsOp}
+ onCondOpChange={onCondOpChange}
+ />
+ </View>
+ )}
+ <View
+ style={{
+ backgroundColor: theme.tableBackground,
+ flexGrow: 1,
+ }}
+ >
+ <View
+ style={{
+ flexDirection: 'row',
+ flexGrow: 1,
+ }}
+ >
+ <View
+ style={{
+ flexDirection: 'column',
+ flexGrow: 1,
+ padding: 10,
+ paddingTop: 10,
+ }}
+ >
+ {graphType !== 'TableGraph' && (
+ <View
+ style={{
+ alignItems: 'flex-end',
+ paddingTop: 10,
+ }}
+ >
+ <View
+ style={{
+ ...styles.mediumText,
+ fontWeight: 500,
+ marginBottom: 5,
+ }}
+ >
+ <AlignedText
+ left={<Block>{balanceType}:</Block>}
+ right={
+ <Text>
+ <PrivacyFilter blurIntensity={5}>
+ {amountToCurrency(
+ Math.abs(
+ data[
+ ReportOptions.balanceTypeMap.get(
+ balanceType,
+ )
+ ],
+ ),
+ )}
+ </PrivacyFilter>
+ </Text>
+ }
+ />
+ </View>
+ </View>
+ )}
+ <ChooseGraph
+ start={start}
+ end={end}
+ data={data}
+ mode={mode}
+ graphType={graphType}
+ balanceType={balanceType}
+ groupBy={groupBy}
+ empty={empty}
+ scrollWidth={scrollWidth}
+ setScrollWidth={setScrollWidth}
+ months={months}
+ />
+ </View>
+ {(viewLegend || viewSummary) && (
+ <View
+ style={{
+ padding: 10,
+ flexDirection: 'column',
+ minWidth: 300,
+ marginRight: 10,
+ textAlign: 'center',
+ flexShrink: 0,
+ }}
+ >
+ {viewSummary && (
+ <ReportSummary
+ start={start}
+ end={end}
+ balanceTypeOp={ReportOptions.balanceTypeMap.get(
+ balanceType,
+ )}
+ data={data}
+ monthsCount={months.length}
+ />
+ )}
+ {viewLegend && (
+ <ReportLegend
+ data={data}
+ legend={legend}
+ groupBy={groupBy}
+ />
+ )}
+ </View>
+ )}
+ </View>
+ </View>
+ </View>
+ </View>
+ </View>
+ );
+}
diff --git a/packages/desktop-client/src/components/reports/reports/CustomReportCard.js b/packages/desktop-client/src/components/reports/reports/CustomReportCard.js
new file mode 100644
index 0000000000..1dd43b0b92
--- /dev/null
+++ b/packages/desktop-client/src/components/reports/reports/CustomReportCard.js
@@ -0,0 +1,62 @@
+import React, { useMemo } from 'react';
+
+import * as monthUtils from 'loot-core/src/shared/months';
+
+import useCategories from '../../../hooks/useCategories';
+import { styles } from '../../../style';
+import Block from '../../common/Block';
+import View from '../../common/View';
+import DateRange from '../DateRange';
+import BarGraph from '../graphs/BarGraph';
+import { LoadingIndicator } from '../Overview';
+import ReportCard from '../ReportCard';
+import defaultSpreadsheet from '../spreadsheets/default-spreadsheet';
+import useReport from '../useReport';
+
+function CustomReportCard() {
+ const categories = useCategories();
+
+ const end = monthUtils.currentMonth();
+ const start = monthUtils.subMonths(end, 3);
+ const groupBy = 'Category';
+
+ const getGraphData = useMemo(() => {
+ return defaultSpreadsheet(start, end, groupBy, 'totalDebts', categories);
+ }, [start, end, categories]);
+ const data = useReport('default', getGraphData);
+
+ return (
+ <ReportCard flex={1} to="/reports/custom">
+ <View>
+ <View style={{ flexDirection: 'row', padding: '20px 20px 0' }}>
+ <View style={{ flex: 1 }}>
+ <Block
+ style={{ ...styles.mediumText, fontWeight: 500, marginBottom: 5 }}
+ role="heading"
+ >
+ Custom Report
+ </Block>
+ <DateRange start={start} end={end} />
+ </View>
+ </View>
+ </View>
+
+ {data ? (
+ <BarGraph
+ start={start}
+ end={end}
+ data={data}
+ compact={true}
+ groupBy={groupBy}
+ empty={true}
+ balanceTypeOp={'totalDebts'}
+ style={{ height: 'auto', flex: 1 }}
+ />
+ ) : (
+ <LoadingIndicator />
+ )}
+ </ReportCard>
+ );
+}
+
+export default CustomReportCard;
diff --git a/packages/desktop-client/src/components/reports/NetWorth.js b/packages/desktop-client/src/components/reports/reports/NetWorth.js
similarity index 88%
rename from packages/desktop-client/src/components/reports/NetWorth.js
rename to packages/desktop-client/src/components/reports/reports/NetWorth.js
index e03f82d5a6..e3f928b5fb 100644
--- a/packages/desktop-client/src/components/reports/NetWorth.js
+++ b/packages/desktop-client/src/components/reports/reports/NetWorth.js
@@ -7,20 +7,19 @@ import { send } from 'loot-core/src/platform/client/fetch';
import * as monthUtils from 'loot-core/src/shared/months';
import { integerToCurrency } from 'loot-core/src/shared/util';
-import useFilters from '../../hooks/useFilters';
-import { theme, styles } from '../../style';
-import Paragraph from '../common/Paragraph';
-import View from '../common/View';
-import PrivacyFilter from '../PrivacyFilter';
-
-import Change from './Change';
-import netWorthSpreadsheet from './graphs/net-worth-spreadsheet';
-import NetWorthGraph from './graphs/NetWorthGraph';
-import Header from './Header';
-import useReport from './useReport';
-import { fromDateRepr } from './util';
-
-export default function NetWorth() {
+import useFilters from '../../../hooks/useFilters';
+import { theme, styles } from '../../../style';
+import Paragraph from '../../common/Paragraph';
+import View from '../../common/View';
+import PrivacyFilter from '../../PrivacyFilter';
+import Change from '../Change';
+import NetWorthGraph from '../graphs/NetWorthGraph';
+import Header from '../Header';
+import netWorthSpreadsheet from '../spreadsheets/net-worth-spreadsheet';
+import useReport from '../useReport';
+import { fromDateRepr } from '../util';
+
+function NetWorth() {
let accounts = useSelector(state => state.queries.accounts);
const {
filters,
@@ -153,3 +152,5 @@ export default function NetWorth() {
</View>
);
}
+
+export default NetWorth;
diff --git a/packages/desktop-client/src/components/reports/reports/NetWorthCard.js b/packages/desktop-client/src/components/reports/reports/NetWorthCard.js
new file mode 100644
index 0000000000..060636e0a7
--- /dev/null
+++ b/packages/desktop-client/src/components/reports/reports/NetWorthCard.js
@@ -0,0 +1,87 @@
+import React, { useState, useMemo, useCallback } from 'react';
+
+import * as monthUtils from 'loot-core/src/shared/months';
+import { integerToCurrency } from 'loot-core/src/shared/util';
+
+import { theme, styles } from '../../../style';
+import Block from '../../common/Block';
+import View from '../../common/View';
+import PrivacyFilter from '../../PrivacyFilter';
+import Change from '../Change';
+import DateRange from '../DateRange';
+import NetWorthGraph from '../graphs/NetWorthGraph';
+import { LoadingIndicator } from '../Overview';
+import ReportCard from '../ReportCard';
+import netWorthSpreadsheet from '../spreadsheets/net-worth-spreadsheet';
+import useReport from '../useReport';
+
+function NetWorthCard({ accounts }) {
+ const end = monthUtils.currentMonth();
+ const start = monthUtils.subMonths(end, 5);
+ const [isCardHovered, setIsCardHovered] = useState(false);
+ const onCardHover = useCallback(() => setIsCardHovered(true));
+ const onCardHoverEnd = useCallback(() => setIsCardHovered(false));
+
+ const params = useMemo(
+ () => netWorthSpreadsheet(start, end, accounts),
+ [start, end, accounts],
+ );
+ const data = useReport('net_worth', params);
+
+ return (
+ <ReportCard flex={2} to="/reports/net-worth">
+ <View
+ style={{ flex: 1 }}
+ onPointerEnter={onCardHover}
+ onPointerLeave={onCardHoverEnd}
+ >
+ <View style={{ flexDirection: 'row', padding: 20 }}>
+ <View style={{ flex: 1 }}>
+ <Block
+ style={{ ...styles.mediumText, fontWeight: 500, marginBottom: 5 }}
+ role="heading"
+ >
+ Net Worth
+ </Block>
+ <DateRange start={start} end={end} />
+ </View>
+ {data && (
+ <View style={{ textAlign: 'right' }}>
+ <Block
+ style={{
+ ...styles.mediumText,
+ fontWeight: 500,
+ marginBottom: 5,
+ }}
+ >
+ <PrivacyFilter activationFilters={[!isCardHovered]}>
+ {integerToCurrency(data.netWorth)}
+ </PrivacyFilter>
+ </Block>
+ <PrivacyFilter activationFilters={[!isCardHovered]}>
+ <Change
+ amount={data.totalChange}
+ style={{ color: theme.altTableText, fontWeight: 300 }}
+ />
+ </PrivacyFilter>
+ </View>
+ )}
+ </View>
+
+ {data ? (
+ <NetWorthGraph
+ start={start}
+ end={end}
+ graphData={data.graphData}
+ compact={true}
+ style={{ height: 'auto', flex: 1 }}
+ />
+ ) : (
+ <LoadingIndicator />
+ )}
+ </View>
+ </ReportCard>
+ );
+}
+
+export default NetWorthCard;
diff --git a/packages/desktop-client/src/components/reports/Sankey.js b/packages/desktop-client/src/components/reports/reports/Sankey.js
similarity index 88%
rename from packages/desktop-client/src/components/reports/Sankey.js
rename to packages/desktop-client/src/components/reports/reports/Sankey.js
index 849559c23f..b2b1154868 100644
--- a/packages/desktop-client/src/components/reports/Sankey.js
+++ b/packages/desktop-client/src/components/reports/reports/Sankey.js
@@ -5,17 +5,16 @@ import * as d from 'date-fns';
import { send } from 'loot-core/src/platform/client/fetch';
import * as monthUtils from 'loot-core/src/shared/months';
-import useCategories from '../../hooks/useCategories';
-import useFilters from '../../hooks/useFilters';
-import { theme, styles } from '../../style';
-import Paragraph from '../common/Paragraph';
-import View from '../common/View';
-
-import sankeySpreadsheet from './graphs/sankey-spreadsheet';
-import SankeyGraph from './graphs/SankeyGraph';
-import Header from './Header';
-import useReport from './useReport';
-import { fromDateRepr } from './util';
+import useCategories from '../../../hooks/useCategories';
+import useFilters from '../../../hooks/useFilters';
+import { theme, styles } from '../../../style';
+import Paragraph from '../../common/Paragraph';
+import View from '../../common/View';
+import SankeyGraph from '../graphs/SankeyGraph';
+import Header from '../Header';
+import sankeySpreadsheet from '../spreadsheets/sankey-spreadsheet';
+import useReport from '../useReport';
+import { fromDateRepr } from '../util';
export default function Sankey() {
const { grouped: categoryGroups } = useCategories();
diff --git a/packages/desktop-client/src/components/reports/reports/SankeyCard.js b/packages/desktop-client/src/components/reports/reports/SankeyCard.js
new file mode 100644
index 0000000000..1732311dbf
--- /dev/null
+++ b/packages/desktop-client/src/components/reports/reports/SankeyCard.js
@@ -0,0 +1,51 @@
+import React, { useMemo } from 'react';
+
+import * as monthUtils from 'loot-core/src/shared/months';
+
+import useCategories from '../../../hooks/useCategories';
+import { styles } from '../../../style';
+import Block from '../../common/Block';
+import View from '../../common/View';
+import DateRange from '../DateRange';
+import SankeyGraph from '../graphs/SankeyGraph';
+import { LoadingIndicator } from '../Overview';
+import ReportCard from '../ReportCard';
+import sankeySpreadsheet from '../spreadsheets/sankey-spreadsheet';
+import useReport from '../useReport';
+
+function SankeyCard() {
+ const { grouped: categoryGroups } = useCategories();
+ const end = monthUtils.currentMonth();
+ const start = monthUtils.subMonths(end, 5);
+
+ const params = useMemo(
+ () => sankeySpreadsheet(start, end, categoryGroups),
+ [start, end, categoryGroups],
+ );
+ const data = useReport('sankey', params);
+
+ return (
+ <ReportCard flex={1} to="/reports/sankey">
+ <View style={{ flexDirection: 'row', padding: 20 }}>
+ <View style={{ flex: 1 }}>
+ <Block
+ style={{ ...styles.mediumText, fontWeight: 500, marginBottom: 5 }}
+ role="heading"
+ >
+ Sankey
+ </Block>
+ <DateRange start={start} end={end} />
+ </View>
+ </View>
+ <View style={{ flex: 1 }}>
+ {data ? (
+ <SankeyGraph data={data} compact={true} />
+ ) : (
+ <LoadingIndicator />
+ )}
+ </View>
+ </ReportCard>
+ );
+}
+
+export default SankeyCard;
diff --git a/packages/desktop-client/src/components/reports/graphs/cash-flow-spreadsheet.tsx b/packages/desktop-client/src/components/reports/spreadsheets/cash-flow-spreadsheet.tsx
similarity index 100%
rename from packages/desktop-client/src/components/reports/graphs/cash-flow-spreadsheet.tsx
rename to packages/desktop-client/src/components/reports/spreadsheets/cash-flow-spreadsheet.tsx
diff --git a/packages/desktop-client/src/components/reports/graphs/category-spending-spreadsheet.tsx b/packages/desktop-client/src/components/reports/spreadsheets/category-spending-spreadsheet.tsx
similarity index 100%
rename from packages/desktop-client/src/components/reports/graphs/category-spending-spreadsheet.tsx
rename to packages/desktop-client/src/components/reports/spreadsheets/category-spending-spreadsheet.tsx
diff --git a/packages/desktop-client/src/components/reports/spreadsheets/default-spreadsheet.tsx b/packages/desktop-client/src/components/reports/spreadsheets/default-spreadsheet.tsx
new file mode 100644
index 0000000000..a09d95af7d
--- /dev/null
+++ b/packages/desktop-client/src/components/reports/spreadsheets/default-spreadsheet.tsx
@@ -0,0 +1,490 @@
+import * as d from 'date-fns';
+
+import q, { runQuery } from 'loot-core/src/client/query-helpers';
+import { send } from 'loot-core/src/platform/client/fetch';
+import * as monthUtils from 'loot-core/src/shared/months';
+import { integerToAmount, amountToInteger } from 'loot-core/src/shared/util';
+
+import { index } from '../util';
+
+export default function createSpreadsheet(
+ start,
+ end,
+ groupBy,
+ typeItem,
+ categories,
+ selectedCategories,
+ payees,
+ accounts,
+ conditions = [],
+ conditionsOp,
+ hidden,
+ uncat,
+) {
+ let uncatCat = {
+ name: 'Uncategorized',
+ id: null,
+ uncat_id: '1',
+ hidden: 0,
+ offBudget: false,
+ };
+ let uncatTransfer = {
+ name: 'Transfers',
+ id: null,
+ uncat_id: '2',
+ hidden: 0,
+ transfer: false,
+ };
+ let uncatOff = {
+ name: 'OffBudget',
+ id: null,
+ uncat_id: '3',
+ hidden: 0,
+ offBudget: true,
+ };
+
+ let uncatGroup = {
+ name: 'Uncategorized',
+ id: null,
+ hidden: 0,
+ categories: [uncatCat, uncatTransfer, uncatOff],
+ };
+ let catList = uncat
+ ? [...categories.list, uncatCat, uncatTransfer, uncatOff]
+ : categories.list;
+ let catGroup = uncat
+ ? [...categories.grouped, uncatGroup]
+ : categories.grouped;
+
+ let categoryFilter = (catList || []).filter(
+ category =>
+ !category.hidden &&
+ selectedCategories &&
+ selectedCategories.some(
+ selectedCategory => selectedCategory.id === category.id,
+ ),
+ );
+
+ let groupByList;
+ let groupByLabel;
+ switch (groupBy) {
+ case 'Category':
+ groupByList = catList;
+ groupByLabel = 'category';
+ break;
+ case 'Group':
+ groupByList = catList;
+ groupByLabel = 'category';
+ break;
+ case 'Payee':
+ groupByList = payees;
+ groupByLabel = 'payee';
+ break;
+ case 'Account':
+ groupByList = accounts;
+ groupByLabel = 'account';
+ break;
+ case 'Month':
+ groupByList = catList;
+ groupByLabel = 'category';
+ break;
+ case 'Year':
+ groupByList = catList;
+ groupByLabel = 'category';
+ break;
+ default:
+ }
+
+ return async (spreadsheet, setData) => {
+ if (groupByList.length === 0) {
+ return null;
+ }
+
+ let { filters } = await send('make-filters-from-conditions', {
+ conditions: conditions.filter(cond => !cond.customName),
+ });
+ const conditionsOpKey = conditionsOp === 'or' ? '$or' : '$and';
+
+ function makeQuery(splt, name) {
+ let query = q('transactions')
+ .filter(
+ //Show Offbudget and hidden categories
+ !hidden && {
+ $and: [
+ {
+ 'account.offbudget': false,
+ $or: [
+ {
+ 'category.hidden': false,
+ category: null,
+ },
+ ],
+ },
+ ],
+ $or: [
+ {
+ 'payee.transfer_acct.offbudget': true,
+ 'payee.transfer_acct': null,
+ },
+ ],
+ },
+ )
+ //Apply Category_Selector
+ .filter(
+ selectedCategories && {
+ $or: [
+ {
+ category: null,
+ $or: categoryFilter.map(category => ({
+ category: category.id,
+ })),
+ },
+ ],
+ },
+ )
+ //Calculate uncategorized transactions when box checked
+ .filter(
+ splt.uncat_id === '2'
+ ? {
+ 'payee.transfer_acct.closed': false,
+ }
+ : {
+ 'payee.transfer_acct': null,
+ 'account.offbudget': splt.offBudget ? splt.offBudget : false,
+ },
+ )
+ //Apply filters and split by "Group By"
+ .filter({
+ [conditionsOpKey]: [...filters],
+ [groupByLabel]: splt.id,
+ })
+ //Apply month range filters
+ .filter({
+ $and: [
+ { date: { $transform: '$month', $gte: start } },
+ { date: { $transform: '$month', $lte: end } },
+ ],
+ })
+ //Show assets or debts
+ .filter(
+ name === 'assets' ? { amount: { $gt: 0 } } : { amount: { $lt: 0 } },
+ );
+
+ return query
+ .groupBy({ $month: '$date' })
+ .select([
+ { date: { $month: '$date' } },
+ { [name]: { $sum: '$amount' } },
+ ]);
+ }
+
+ const graphData = await Promise.all(
+ groupByList.map(async splt => {
+ let [starting, assets, debts] = await Promise.all([
+ runQuery(
+ q('transactions')
+ .filter(
+ !hidden && {
+ $and: [
+ {
+ 'account.offbudget': false,
+ $or: [
+ {
+ 'category.hidden': false,
+ category: null,
+ },
+ ],
+ },
+ ],
+ $or: [
+ {
+ 'payee.transfer_acct.offbudget': true,
+ 'payee.transfer_acct': null,
+ },
+ ],
+ },
+ )
+ .filter(
+ splt.uncat_id === '2'
+ ? {
+ 'payee.transfer_acct.closed': false,
+ }
+ : {
+ 'payee.transfer_acct': null,
+ 'account.offbudget': splt.offBudget
+ ? splt.offBudget
+ : false,
+ },
+ )
+ .filter(
+ selectedCategories && {
+ $or: categoryFilter.map(category => ({
+ category: category.id,
+ })),
+ },
+ )
+ .filter({
+ [conditionsOpKey]: [...filters],
+ [groupByLabel]: splt.id,
+ })
+ .filter({
+ $and: [{ date: { $lt: start + '-01' } }],
+ })
+ .calculate({ $sum: '$amount' }),
+ ).then(({ data }) => data),
+
+ runQuery(makeQuery(splt, 'assets')).then(({ data }) => data),
+ runQuery(makeQuery(splt, 'debts')).then(({ data }) => data),
+ ]);
+
+ return {
+ id: splt.id,
+ uncat_id: splt.uncat_id,
+ name: splt.name,
+ starting,
+ hidden: splt.hidden,
+ assets: index(assets, 'date'),
+ debts: index(debts, 'date'),
+ };
+ }),
+ );
+
+ const months = monthUtils.rangeInclusive(start, end);
+ const calcData = graphData.map(graph => {
+ let graphStarting = 0;
+ const mon = months.map(month => {
+ let graphAssets = 0;
+ let graphDebts = 0;
+ if (graph.assets[month] || graph.debts[month]) {
+ if (graph.assets[month]) {
+ graphAssets += graph.assets[month].assets;
+ }
+ if (graph.debts[month]) {
+ graphDebts += graph.debts[month].debts;
+ }
+ }
+
+ graphStarting += graph.starting;
+ return {
+ date: month,
+ assets: graphAssets,
+ debts: graphDebts,
+ };
+ });
+
+ return {
+ id: graph.id,
+ uncat_id: graph.uncat_id,
+ name: graph.name,
+ starting: graphStarting,
+ hidden: graph.hidden,
+ balances: index(mon, 'date'),
+ };
+ });
+
+ const categoryGroupCalcData = catGroup.map(group => {
+ if (hidden || group.hidden === 0) {
+ let groupedStarting = 0;
+ const mon = months.map(month => {
+ let groupedAssets = 0;
+ let groupedDebts = 0;
+ graphData.map(graph => {
+ if (graph.assets[month] || graph.debts[month]) {
+ if (group.categories.map(v => v.id).includes(graph.id)) {
+ if (graph.assets[month]) {
+ groupedAssets += graph.assets[month].assets;
+ }
+ if (graph.debts[month]) {
+ groupedDebts += graph.debts[month].debts;
+ }
+ }
+ }
+
+ groupedStarting += graph.starting;
+ return null;
+ });
+ return {
+ date: month,
+ assets: groupedAssets,
+ debts: groupedDebts,
+ };
+ });
+
+ return {
+ id: group.id,
+ name: group.name,
+ starting: groupedStarting,
+ hidden: group.hidden,
+ balances: index(mon, 'date'),
+ };
+ } else {
+ return null;
+ }
+ });
+
+ const groupByData = groupBy === 'Group' ? categoryGroupCalcData : calcData;
+
+ const data = groupByData.map(graph => {
+ const calc = recalculate(graph, start, end);
+ return { ...calc };
+ });
+
+ const categoryGroupData = catGroup.map(group => {
+ const catData = group.categories.map(graph => {
+ let catMatch = null;
+ calcData.map(cat => {
+ if (
+ cat.id === null
+ ? cat.uncat_id === graph.uncat_id
+ : cat.id === graph.id
+ ) {
+ catMatch = cat;
+ }
+ return null;
+ });
+ const calcCat = catMatch && recalculate(catMatch, start, end);
+ return { ...calcCat };
+ });
+ let groupMatch = null;
+ categoryGroupCalcData.map(split => {
+ if (split.id === group.id) {
+ groupMatch = split;
+ }
+ return null;
+ });
+ const calcGroup = groupMatch && recalculate(groupMatch, start, end);
+ return {
+ ...calcGroup,
+ categories: catData,
+ };
+ });
+
+ let totalAssets = 0;
+ let totalDebts = 0;
+ let totalTotals = 0;
+
+ const monthData = months.map(month => {
+ let perMonthAssets = 0;
+ let perMonthDebts = 0;
+ let perMonthTotals = 0;
+ graphData.map(graph => {
+ if (graph.assets[month] || graph.debts[month]) {
+ if (graph.assets[month]) {
+ perMonthAssets += graph.assets[month].assets;
+ }
+ if (graph.debts[month]) {
+ perMonthDebts += graph.debts[month].debts;
+ }
+ perMonthTotals = perMonthAssets + perMonthDebts;
+ }
+ return null;
+ });
+ totalAssets += perMonthAssets;
+ totalDebts += perMonthDebts;
+ totalTotals += perMonthTotals;
+
+ return {
+ // eslint-disable-next-line rulesdir/typography
+ date: d.format(d.parseISO(`${month}-01`), "MMM ''yy"),
+ totalDebts: integerToAmount(perMonthDebts),
+ totalAssets: integerToAmount(perMonthAssets),
+ totalTotals: integerToAmount(perMonthTotals),
+ };
+ });
+
+ const stackedData = months.map(month => {
+ let perMonthAmounts = 0;
+ const stacked = data.map(graph => {
+ let stackAmounts = 0;
+ if (graph.indexedMonthData[month]) {
+ perMonthAmounts += graph.indexedMonthData[month][typeItem];
+ stackAmounts += graph.indexedMonthData[month][typeItem];
+ }
+ return {
+ name: graph.name,
+ id: graph.id,
+ amount: stackAmounts,
+ };
+ });
+
+ const indexedStack = index(stacked, 'name');
+ return {
+ // eslint-disable-next-line rulesdir/typography
+ date: d.format(d.parseISO(`${month}-01`), "MMM ''yy"),
+ ...indexedStack,
+ totalTotals: perMonthAmounts,
+ };
+ });
+
+ setData({
+ stackedData: stackedData,
+ groupBy: groupBy === 'Group' ? catGroup : groupByList,
+ data,
+ groupData: categoryGroupData,
+ monthData,
+ start,
+ end,
+ totalDebts: integerToAmount(totalDebts),
+ totalAssets: integerToAmount(totalAssets),
+ totalTotals: integerToAmount(totalTotals),
+ });
+ };
+}
+
+function recalculate(item, start, end) {
+ const months = monthUtils.rangeInclusive(start, end);
+
+ let totalDebts = 0;
+ let totalAssets = 0;
+ let totalTotals = 0;
+ let exists = false;
+
+ const monthData = months.reduce((arr, month) => {
+ let debts = 0;
+ let assets = 0;
+ let total = 0;
+ const last = arr.length === 0 ? null : arr[arr.length - 1];
+
+ if (item.balances[month]) {
+ exists = true;
+ if (item.balances[month].debts) {
+ debts += item.balances[month].debts;
+ totalDebts += item.balances[month].debts;
+ }
+ if (item.balances[month].assets) {
+ assets += item.balances[month].assets;
+ totalAssets += item.balances[month].assets;
+ }
+ total = assets + debts;
+ totalTotals = totalAssets + totalDebts;
+ }
+
+ const dateParse = d.parseISO(`${month}-01`);
+ const change = last ? total - amountToInteger(last.totalTotals) : 0;
+
+ arr.push({
+ dateParse,
+ totalTotals: integerToAmount(total),
+ totalAssets: integerToAmount(assets),
+ totalDebts: integerToAmount(debts),
+ totalChange: integerToAmount(change),
+ // eslint-disable-next-line rulesdir/typography
+ date: d.format(dateParse, "MMM ''yy"),
+ dateLookup: month,
+ });
+
+ return arr;
+ }, []);
+
+ const indexedMonthData = exists ? index(monthData, 'dateLookup') : monthData;
+
+ return {
+ indexedMonthData: indexedMonthData,
+ monthData: monthData,
+ totalAssets: integerToAmount(totalAssets),
+ totalDebts: integerToAmount(totalDebts),
+ totalTotals: integerToAmount(totalTotals),
+ id: item.id,
+ name: item.name,
+ };
+}
diff --git a/packages/desktop-client/src/components/reports/graphs/net-worth-spreadsheet.tsx b/packages/desktop-client/src/components/reports/spreadsheets/net-worth-spreadsheet.tsx
similarity index 100%
rename from packages/desktop-client/src/components/reports/graphs/net-worth-spreadsheet.tsx
rename to packages/desktop-client/src/components/reports/spreadsheets/net-worth-spreadsheet.tsx
diff --git a/packages/desktop-client/src/components/reports/graphs/sankey-spreadsheet.tsx b/packages/desktop-client/src/components/reports/spreadsheets/sankey-spreadsheet.tsx
similarity index 100%
rename from packages/desktop-client/src/components/reports/graphs/sankey-spreadsheet.tsx
rename to packages/desktop-client/src/components/reports/spreadsheets/sankey-spreadsheet.tsx
diff --git a/packages/desktop-client/src/components/settings/Experimental.tsx b/packages/desktop-client/src/components/settings/Experimental.tsx
index e8e62cbf7c..37ed841770 100644
--- a/packages/desktop-client/src/components/settings/Experimental.tsx
+++ b/packages/desktop-client/src/components/settings/Experimental.tsx
@@ -101,7 +101,7 @@ export default function ExperimentalFeatures() {
<FeatureToggle flag="categorySpendingReport">
Category spending report
</FeatureToggle>
-
+ <FeatureToggle flag="customReports">Custom reports</FeatureToggle>
<FeatureToggle flag="sankeyReport">Sankey report</FeatureToggle>
<ReportBudgetFeature />
diff --git a/packages/desktop-client/src/hooks/useFeatureFlag.ts b/packages/desktop-client/src/hooks/useFeatureFlag.ts
index 4a48e58578..0bd5aa83c7 100644
--- a/packages/desktop-client/src/hooks/useFeatureFlag.ts
+++ b/packages/desktop-client/src/hooks/useFeatureFlag.ts
@@ -8,6 +8,7 @@ const DEFAULT_FEATURE_FLAG_STATE: Record<FeatureFlag, boolean> = {
reportBudget: false,
goalTemplatesEnabled: false,
themes: false,
+ customReports: false,
experimentalOfxParser: true,
};
diff --git a/packages/loot-core/src/types/prefs.d.ts b/packages/loot-core/src/types/prefs.d.ts
index 65a04d4606..187897d020 100644
--- a/packages/loot-core/src/types/prefs.d.ts
+++ b/packages/loot-core/src/types/prefs.d.ts
@@ -6,6 +6,7 @@ export type FeatureFlag =
| 'reportBudget'
| 'goalTemplatesEnabled'
| 'themes'
+ | 'customReports'
| 'experimentalOfxParser';
export type LocalPrefs = Partial<
diff --git a/upcoming-release-notes/1791.md b/upcoming-release-notes/1791.md
new file mode 100644
index 0000000000..be7d15a460
--- /dev/null
+++ b/upcoming-release-notes/1791.md
@@ -0,0 +1,6 @@
+---
+category: Features
+authors: [carkom]
+---
+
+Create and implement a customizable charts page. Currently hidden under feature flag (experimental). To include ability to save charts and show tiles on Overview page (future PR)