Skip to content

A local-first personal finance app

Various sankey improvements and bugfixes (#7682)

Emil Tveden Bjerglund218a3c68dd19
diff --git a/packages/desktop-client/src/components/reports/Overview.tsx b/packages/desktop-client/src/components/reports/Overview.tsx
index 30ce4fcbf3..581ce581cf 100644
--- a/packages/desktop-client/src/components/reports/Overview.tsx
+++ b/packages/desktop-client/src/components/reports/Overview.tsx
@@ -77,6 +77,26 @@ function isCustomReportWidget(
return widget.type === 'custom-report';
}
+function getWidgetMinHeight(widget: DashboardWidgetEntity) {
+ if (isCustomReportWidget(widget) || widget.type === 'markdown-card') {
+ return 1;
+ }
+
+ if (widget.type === 'sankey-card') {
+ return 3;
+ }
+
+ return 2;
+}
+
+function getWidgetMinWidth(widget: DashboardWidgetEntity) {
+ if (isCustomReportWidget(widget) || widget.type === 'markdown-card') {
+ return 2;
+ }
+
+ return 3;
+}
+
type OverviewProps = {
dashboard: DashboardPageEntity;
};
@@ -168,10 +188,8 @@ export function Overview({ dashboard }: OverviewProps) {
y: widget.y,
w: widget.width,
h: widget.height,
- minW:
- isCustomReportWidget(widget) || widget.type === 'markdown-card' ? 2 : 3,
- minH:
- isCustomReportWidget(widget) || widget.type === 'markdown-card' ? 1 : 2,
+ minW: getWidgetMinWidth(widget),
+ minH: getWidgetMinHeight(widget),
}));
}, [widgets]);
@@ -273,7 +291,7 @@ export function Overview({ dashboard }: OverviewProps) {
widget: {
type,
width: 4,
- height: 2,
+ height: type === 'sankey-card' ? 3 : 2,
meta,
dashboard_page_id: dashboard.id,
},
diff --git a/packages/desktop-client/src/components/reports/graphs/SankeyGraph.tsx b/packages/desktop-client/src/components/reports/graphs/SankeyGraph.tsx
index c18e0ed9fb..aacef7998f 100644
--- a/packages/desktop-client/src/components/reports/graphs/SankeyGraph.tsx
+++ b/packages/desktop-client/src/components/reports/graphs/SankeyGraph.tsx
@@ -188,7 +188,7 @@ export function SankeyGraph({
/>
)}
sort={false}
- iterations={1000}
+ iterations={128}
nodePadding={23}
width={width}
height={height}
diff --git a/packages/desktop-client/src/components/reports/reports/Sankey.tsx b/packages/desktop-client/src/components/reports/reports/Sankey.tsx
index 207b52e561..a1c75b3e5f 100644
--- a/packages/desktop-client/src/components/reports/reports/Sankey.tsx
+++ b/packages/desktop-client/src/components/reports/reports/Sankey.tsx
@@ -27,6 +27,8 @@ import type {
TimeFrame,
} from '@actual-app/core/types/models';
import * as d from 'date-fns';
+import type { TFunction } from 'i18next';
+import debounce from 'lodash/debounce';
import type { SankeyData } from 'recharts/types/chart/Sankey';
import { EditablePageHeaderTitle } from '#components/EditablePageHeaderTitle';
@@ -38,10 +40,12 @@ import { LoadingIndicator } from '#components/reports/LoadingIndicator';
import { ModeButton } from '#components/reports/ModeButton';
import { calculateTimeRange } from '#components/reports/reportRanges';
import {
+ buildSankeyData,
+ createBaseGraphSpreadsheet,
GRAPH_LAYER_ORDER,
GraphLayers,
- createSpreadsheet as sankeySpreadsheet,
} from '#components/reports/spreadsheets/sankey-spreadsheet';
+import type { Graph } from '#components/reports/spreadsheets/sankey-spreadsheet';
import { useReport } from '#components/reports/useReport';
import { fromDateRepr } from '#components/reports/util';
import { useCategories } from '#hooks/useCategories';
@@ -49,8 +53,8 @@ import { useDashboardWidget } from '#hooks/useDashboardWidget';
import { useFormatList } from '#hooks/useFormatList';
import { useLocale } from '#hooks/useLocale';
import { useNavigate } from '#hooks/useNavigate';
+import { useResizeObserver } from '#hooks/useResizeObserver';
import { useRuleConditionFilters } from '#hooks/useRuleConditionFilters';
-import type { useSpreadsheet } from '#hooks/useSpreadsheet';
import { addNotification } from '#notifications/notificationsSlice';
import { useDispatch } from '#redux';
import { useUpdateDashboardWidgetMutation } from '#reports/mutations';
@@ -69,15 +73,118 @@ export function Sankey() {
return <SankeyInner widget={widget} />;
}
+export function topNNodes(cardHeight: number): number {
+ const PX_PER_NODE = 35;
+ const heightBasedTopN = Math.max(2, Math.floor(cardHeight / PX_PER_NODE));
+ return heightBasedTopN;
+}
+
type GraphMode = 'budgeted' | 'spent';
-const TOP_N_OPTIONS = [10, 15, 20, 25, 30] as const;
+type LayerDirection = 'from' | 'to';
+type LayerRange = {
+ from: GraphLayers;
+ to: GraphLayers;
+};
+
+function getAvailableLayers(mode: GraphMode): GraphLayers[] {
+ return GRAPH_LAYER_ORDER.filter(layer => {
+ if (mode === 'budgeted') {
+ return layer !== GraphLayers.IncomePayee;
+ }
+
+ return layer !== GraphLayers.Budget;
+ }) as GraphLayers[];
+}
+
+export function getDefaultLayerRange(mode: GraphMode): LayerRange {
+ return {
+ from:
+ mode === 'budgeted'
+ ? GraphLayers.IncomeCategory
+ : GraphLayers.IncomePayee,
+ to: GraphLayers.Category,
+ };
+}
+
+function normalizeLayerRange(
+ mode: GraphMode,
+ candidate: LayerRange,
+ changedDirection?: LayerDirection,
+): LayerRange {
+ const availableLayers = getAvailableLayers(mode);
+ const fallback = getDefaultLayerRange(mode);
+ const defaultFromIndex = availableLayers.indexOf(fallback.from);
+ const defaultToIndex = availableLayers.indexOf(fallback.to);
+
+ let from = availableLayers.includes(candidate.from)
+ ? candidate.from
+ : fallback.from;
+ let to = availableLayers.includes(candidate.to) ? candidate.to : fallback.to;
+
+ let fromIndex = availableLayers.indexOf(from);
+ let toIndex = availableLayers.indexOf(to);
+
+ if (fromIndex >= toIndex) {
+ if (changedDirection === 'from') {
+ const adjustedToIndex = Math.min(
+ availableLayers.length - 1,
+ Math.max(fromIndex + 1, defaultToIndex),
+ );
+ to = availableLayers[adjustedToIndex] ?? fallback.to;
+ } else if (changedDirection === 'to') {
+ const adjustedFromIndex = Math.max(
+ 0,
+ Math.min(toIndex - 1, defaultFromIndex),
+ );
+ from = availableLayers[adjustedFromIndex] ?? fallback.from;
+ } else {
+ from = fallback.from;
+ to = fallback.to;
+ }
+
+ fromIndex = availableLayers.indexOf(from);
+ toIndex = availableLayers.indexOf(to);
+ }
+
+ if (fromIndex >= toIndex) {
+ return fallback;
+ }
+
+ return { from, to };
+}
+
+function getLayerMenuItems(
+ mode: GraphMode,
+ direction: LayerDirection,
+ otherLayer: GraphLayers,
+): GraphLayers[] {
+ const availableLayers = getAvailableLayers(mode);
+ const otherIndex = availableLayers.indexOf(otherLayer);
+
+ if (otherIndex === -1) {
+ return [];
+ }
+
+ if (direction === 'from') {
+ return availableLayers.slice(0, otherIndex);
+ }
+
+ return availableLayers.slice(otherIndex + 1);
+}
+
+// 1e5 is used as a sentinel value for 'All'
+const TOP_N_OPTIONS = [1e5, 10, 15, 20, 25, 30] as const;
type TopNSelectorProps = {
value: number;
onChange: (value: number) => void;
};
+function displayN(n: number, t: TFunction): string {
+ return n === 1e5 ? t('All') : String(n);
+}
+
function TopNSelector({ value, onChange }: TopNSelectorProps) {
const { t } = useTranslation();
const triggerRef = useRef<HTMLButtonElement | null>(null);
@@ -92,7 +199,9 @@ function TopNSelector({ value, onChange }: TopNSelectorProps) {
aria-label={t('Change category limit')}
>
<SvgList style={{ width: 12, height: 12 }} />
- <span style={{ marginLeft: 5 }}>{t('Show {{n}}', { n: value })}</span>
+ <span style={{ marginLeft: 5 }}>
+ {t('Show up to {{n}}', { n: displayN(value, t) })}
+ </span>
</Button>
<Popover
triggerRef={triggerRef}
@@ -107,7 +216,7 @@ function TopNSelector({ value, onChange }: TopNSelectorProps) {
}}
items={TOP_N_OPTIONS.map(n => ({
name: String(n),
- text: t('Show {{n}}', { n }),
+ text: t('Show up to {{n}}', { n: displayN(n, t) }),
}))}
/>
</Popover>
@@ -174,55 +283,24 @@ function CategorySortSelector({ value, onChange }: CategorySortSelectorProps) {
}
type LayerSelectorProps = {
- direction: 'from' | 'to';
+ direction: LayerDirection;
value: GraphLayers;
- otherLayer: GraphLayers | undefined;
+ layerLabels: Record<GraphLayers, string>;
+ menuItems: GraphLayers[];
onChange: (layer: GraphLayers) => void;
- graphMode: GraphMode;
};
function LayerSelector({
direction,
value,
- otherLayer,
+ layerLabels,
+ menuItems,
onChange,
- graphMode,
}: LayerSelectorProps) {
const { t } = useTranslation();
const triggerRef = useRef<HTMLButtonElement | null>(null);
const [isOpen, setIsOpen] = useState(false);
- const LAYER_LABELS: Record<GraphLayers, string> = {
- [GraphLayers.IncomePayee]: t('Payee'),
- [GraphLayers.IncomeCategory]: t('Income category'),
- [GraphLayers.Account]: t('Account'),
- [GraphLayers.Budget]: t('Budget'),
- [GraphLayers.CategoryGroup]: t('Category group'),
- [GraphLayers.Category]: t('Category'),
- };
-
- // Filter available layers based on graph mode
- const availableLayers: readonly GraphLayers[] =
- graphMode === 'budgeted'
- ? GRAPH_LAYER_ORDER.filter(
- layer => layer !== GraphLayers.IncomePayee, // IncomePayee not available in budgeted
- )
- : GRAPH_LAYER_ORDER.filter(
- layer => layer !== GraphLayers.Budget, // Budget not available in spent
- );
-
- const otherIndex =
- otherLayer !== undefined && availableLayers.includes(otherLayer)
- ? availableLayers.indexOf(otherLayer)
- : direction === 'from'
- ? availableLayers.length - 1
- : 0;
-
- const menuItems =
- direction === 'from'
- ? availableLayers.slice(0, otherIndex)
- : availableLayers.slice(otherIndex + 1);
-
const translatedDirection = direction === 'from' ? t('from') : t('to');
return (
@@ -235,7 +313,7 @@ function LayerSelector({
direction: translatedDirection,
})}
>
- <span style={{ marginLeft: 5 }}>{LAYER_LABELS[value]}</span>
+ <span style={{ marginLeft: 5 }}>{layerLabels[value]}</span>
</Button>
<Popover
triggerRef={triggerRef}
@@ -250,7 +328,7 @@ function LayerSelector({
}}
items={menuItems.map(layer => ({
name: layer,
- text: LAYER_LABELS[layer],
+ text: layerLabels[layer],
}))}
/>
</Popover>
@@ -295,11 +373,15 @@ function GraphModeSelector({ mode, onChange }: GraphModeSelectorProps) {
type OptionsButtonProps = {
showPercentages: boolean;
onTogglePercentages: () => void;
+ groupAccounts: boolean;
+ onToggleGroupAccounts: () => void;
};
function OptionsButton({
showPercentages,
onTogglePercentages,
+ groupAccounts,
+ onToggleGroupAccounts,
}: OptionsButtonProps) {
const { t } = useTranslation();
const triggerRef = useRef<HTMLButtonElement | null>(null);
@@ -318,6 +400,7 @@ function OptionsButton({
<Menu
onMenuSelect={item => {
if (item === 'show-percentages') onTogglePercentages();
+ if (item === 'group-accounts') onToggleGroupAccounts();
}}
items={[
{
@@ -325,6 +408,11 @@ function OptionsButton({
text: t('Show as percentages'),
toggle: showPercentages,
},
+ {
+ name: 'group-accounts',
+ text: t('Group accounts in Spent view'),
+ toggle: groupAccounts,
+ },
]}
/>
</Popover>
@@ -380,6 +468,33 @@ function SankeyInner({ widget }: SankeyInnerProps) {
widget?.meta?.topNcategories ?? 15,
);
+ const [cardHeight, setCardHeight] = useState(0);
+ const throttledSetCardHeight = useMemo(
+ () =>
+ debounce(
+ (height: number) => {
+ setCardHeight(prev => (prev === height ? prev : height));
+ },
+ 200,
+ { leading: true, trailing: true, maxWait: 200 },
+ ),
+ [],
+ );
+
+ useEffect(() => {
+ return () => {
+ throttledSetCardHeight.cancel();
+ };
+ }, [throttledSetCardHeight]);
+
+ const containerRef = useResizeObserver<HTMLDivElement>(rect => {
+ throttledSetCardHeight(rect.height);
+ });
+
+ const heightBasedTopN = topNNodes(cardHeight);
+
+ const topN = Math.min(topNcategories, heightBasedTopN);
+
const [categorySort, setCategorySort] = useState<
'per-group' | 'global' | 'budget-order'
>(widget?.meta?.categorySort ?? 'per-group');
@@ -387,82 +502,80 @@ function SankeyInner({ widget }: SankeyInnerProps) {
const [showPercentages, setShowPercentages] = useState(
widget?.meta?.showPercentages ?? false,
);
+ const [groupAccounts, setGroupAccounts] = useState(
+ widget?.meta?.groupAccounts ?? false,
+ );
- // Determine default layer based on mode
- const defaultLayerFrom = (mode: GraphMode) =>
- mode === 'budgeted' ? GraphLayers.IncomeCategory : GraphLayers.IncomePayee;
-
- const [layerFrom, setLayerFrom] = useState<GraphLayers>(() => {
- const metaLayer = widget?.meta?.layerFrom as GraphLayers | undefined;
- if (metaLayer) {
- // Validate that the layer is valid for the current mode
- const mode = widget?.meta?.mode ?? 'spent';
- if (mode === 'budgeted' && metaLayer === GraphLayers.IncomePayee) {
- return defaultLayerFrom('budgeted');
- }
- if (mode === 'spent' && metaLayer === GraphLayers.Budget) {
- return defaultLayerFrom('spent');
- }
- return metaLayer;
- }
- return defaultLayerFrom(widget?.meta?.mode ?? 'spent');
- });
+ const [layerRange, setLayerRange] = useState<LayerRange>(() =>
+ normalizeLayerRange(widget?.meta?.mode ?? 'spent', {
+ from:
+ (widget?.meta?.layerFrom as GraphLayers) ??
+ getDefaultLayerRange(widget?.meta?.mode ?? 'spent').from,
+ to:
+ (widget?.meta?.layerTo as GraphLayers) ??
+ getDefaultLayerRange(widget?.meta?.mode ?? 'spent').to,
+ }),
+ );
- const [layerTo, setLayerTo] = useState<GraphLayers>(() => {
- const metaLayer = widget?.meta?.layerTo as GraphLayers | undefined;
- if (metaLayer) {
- // Validate that the layer is valid for the current mode
- const mode = widget?.meta?.mode ?? 'spent';
- if (mode === 'budgeted' && metaLayer === GraphLayers.IncomePayee) {
- return GraphLayers.Category;
- }
- if (mode === 'spent' && metaLayer === GraphLayers.Budget) {
- return GraphLayers.Category;
- }
- return metaLayer;
- }
- return GraphLayers.Category;
- });
+ const layerFrom = layerRange.from;
+ const layerTo = layerRange.to;
- // Reset invalid layer selections when switching modes
useEffect(() => {
- const availableLayers =
- graphMode === 'budgeted'
- ? (GRAPH_LAYER_ORDER.filter(
- layer => layer !== GraphLayers.IncomePayee,
- ) as GraphLayers[])
- : (GRAPH_LAYER_ORDER.filter(
- layer => layer !== GraphLayers.Budget,
- ) as GraphLayers[]);
-
- const fromIndex = availableLayers.indexOf(layerFrom);
- const toIndex = availableLayers.indexOf(layerTo);
-
- if (fromIndex === -1 || toIndex === -1 || fromIndex >= toIndex) {
- setLayerFrom(defaultLayerFrom(graphMode));
- setLayerTo(GraphLayers.Category);
- }
- }, [graphMode, layerFrom, layerTo]);
+ setLayerRange(prev => normalizeLayerRange(graphMode, prev));
+ }, [graphMode]);
+
+ const layerLabels = useMemo<Record<GraphLayers, string>>(
+ () => ({
+ [GraphLayers.IncomePayee]: t('Payee'),
+ [GraphLayers.IncomeCategory]: t('Income category'),
+ [GraphLayers.Account]: t('Account'),
+ [GraphLayers.Budget]: t('Budget'),
+ [GraphLayers.CategoryGroup]: t('Category group'),
+ [GraphLayers.Category]: t('Category'),
+ }),
+ [t],
+ );
+
+ const fromLayerMenuItems = useMemo(
+ () => getLayerMenuItems(graphMode, 'from', layerTo),
+ [graphMode, layerTo],
+ );
+ const toLayerMenuItems = useMemo(
+ () => getLayerMenuItems(graphMode, 'to', layerFrom),
+ [graphMode, layerFrom],
+ );
+
+ function onChangeLayer(direction: LayerDirection, layer: GraphLayers) {
+ setLayerRange(prev => {
+ const next =
+ direction === 'from'
+ ? { ...prev, from: layer }
+ : { ...prev, to: layer };
+
+ return normalizeLayerRange(graphMode, next, direction);
+ });
+ }
+
+ function onResetLayers() {
+ setLayerRange(getDefaultLayerRange(graphMode));
+ }
const { data: { grouped: groupedCategories = [] } = { grouped: [] } } =
useCategories();
- const reportParams = useMemo(() => {
+ const baseGraphParams = useMemo(() => {
if (!datesInitialized) {
return null;
}
- return sankeySpreadsheet(
+ return createBaseGraphSpreadsheet(
start,
end,
groupedCategories,
conditions,
conditionsOp,
graphMode,
- topNcategories,
- categorySort,
- layerFrom,
- layerTo,
+ groupAccounts,
);
}, [
datesInitialized,
@@ -472,19 +585,46 @@ function SankeyInner({ widget }: SankeyInnerProps) {
conditions,
conditionsOp,
graphMode,
- topNcategories,
+ groupAccounts,
+ ]);
+
+ const defaultGetBaseGraph = async (
+ _spreadsheet: unknown,
+ setData: (data: Graph) => void,
+ ) => setData(new Map());
+
+ const baseGraph = useReport('sankey', baseGraphParams ?? defaultGetBaseGraph);
+ const baseGraphRef = useRef(baseGraph);
+
+ useEffect(() => {
+ if (baseGraph) {
+ baseGraphRef.current = baseGraph;
+ }
+ }, [baseGraph]);
+
+ const displayBaseGraph = baseGraph || baseGraphRef.current;
+ const displayData: SankeyData | null = useMemo(() => {
+ if (!displayBaseGraph) {
+ return null;
+ }
+
+ return buildSankeyData(
+ displayBaseGraph,
+ topN,
+ groupedCategories,
+ categorySort,
+ layerFrom,
+ layerTo,
+ );
+ }, [
+ displayBaseGraph,
+ topN,
+ groupedCategories,
categorySort,
layerFrom,
layerTo,
]);
- const defaultGetData = async (
- spreadsheet: ReturnType<typeof useSpreadsheet>,
- setData: (data: SankeyData) => void,
- ) => setData({ nodes: [], links: [] });
-
- const data = useReport('sankey', reportParams ?? defaultGetData);
-
useEffect(() => {
async function run() {
const earliestTransaction = await send('get-earliest-transaction');
@@ -577,6 +717,7 @@ function SankeyInner({ widget }: SankeyInnerProps) {
end,
mode: timeFrameMode,
},
+ groupAccounts,
},
},
},
@@ -595,17 +736,19 @@ function SankeyInner({ widget }: SankeyInnerProps) {
);
}
- const onSaveWidgetName = async (newName: string) => {
+ const onSaveWidgetName = (newName: string) => {
if (!widget) {
throw new Error('No widget that could be saved.');
}
const name = newName || t('Sankey');
- await send('dashboard-update-widget', {
- id: widget.id,
- meta: {
- ...(widget.meta ?? {}),
- name,
+ updateDashboardWidgetMutation.mutate({
+ widget: {
+ id: widget.id,
+ meta: {
+ ...(widget.meta ?? {}),
+ name,
+ },
},
});
};
@@ -630,7 +773,7 @@ function SankeyInner({ widget }: SankeyInnerProps) {
i18n.language,
);
- if (!datesInitialized || !data) {
+ if (!datesInitialized || !displayData) {
return <LoadingIndicator />;
}
@@ -716,29 +859,21 @@ function SankeyInner({ widget }: SankeyInnerProps) {
<LayerSelector
direction="from"
value={layerFrom}
- otherLayer={layerTo}
- onChange={setLayerFrom}
- graphMode={graphMode}
+ layerLabels={layerLabels}
+ menuItems={fromLayerMenuItems}
+ onChange={layer => onChangeLayer('from', layer)}
/>
<SvgCheveronRight style={{ width: 12, height: 12 }} />
<LayerSelector
direction="to"
value={layerTo}
- otherLayer={layerFrom}
- onChange={setLayerTo}
- graphMode={graphMode}
+ layerLabels={layerLabels}
+ menuItems={toLayerMenuItems}
+ onChange={layer => onChangeLayer('to', layer)}
/>
<Button
variant="bare"
- onPress={() => {
- if (graphMode === 'budgeted') {
- setLayerFrom(GraphLayers.IncomeCategory);
- setLayerTo(GraphLayers.Category);
- } else {
- setLayerFrom(GraphLayers.IncomePayee);
- setLayerTo(GraphLayers.Category);
- }
- }}
+ onPress={onResetLayers}
aria-label={t('Reset layers')}
>
<SvgRefresh style={{ width: 12, height: 12 }} />
@@ -750,6 +885,8 @@ function SankeyInner({ widget }: SankeyInnerProps) {
<OptionsButton
showPercentages={showPercentages}
onTogglePercentages={() => setShowPercentages(v => !v)}
+ groupAccounts={groupAccounts}
+ onToggleGroupAccounts={() => setGroupAccounts(v => !v)}
/>
</View>
{widget && (
@@ -797,12 +934,22 @@ function SankeyInner({ widget }: SankeyInnerProps) {
paddingTop: 10,
}}
>
- {data && data.links && data.links.length > 0 ? (
- <SankeyGraph
- style={{ flexGrow: 1 }}
- data={data}
- showPercentages={showPercentages}
- />
+ {displayData &&
+ displayData.links &&
+ displayData.links.length > 0 ? (
+ <View
+ ref={containerRef}
+ style={{
+ flexDirection: 'column',
+ flexGrow: 1,
+ }}
+ >
+ <SankeyGraph
+ style={{ flexGrow: 1 }}
+ data={displayData}
+ showPercentages={showPercentages}
+ />
+ </View>
) : (
<View
style={{
@@ -862,16 +1009,26 @@ function SankeyInner({ widget }: SankeyInnerProps) {
<Paragraph>
<strong>View options:</strong>
</Paragraph>
- <ul style={{ marginTop: 0, paddingLeft: 20 }}>
- <li style={{ marginBottom: 5 }}>
- <strong>Spent:</strong> Displays actual spending by
- category from transactions.
- </li>
- <li style={{ marginBottom: 5 }}>
- <strong>Budgeted:</strong> Shows how your budget is
- allocated across categories.
- </li>
- </ul>
+ <Paragraph>
+ <ul style={{ marginTop: 0, paddingLeft: 20 }}>
+ <li style={{ marginBottom: 5 }}>
+ <strong>Spent:</strong> Displays actual spending by
+ category from transactions.
+ </li>
+ <li style={{ marginBottom: 5 }}>
+ <strong>Budgeted:</strong> Shows how your budget is
+ allocated across categories.
+ </li>
+ </ul>
+ <strong>Disclaimer:</strong> A Sankey chart cannot
+ directly represent negative numbers. In some cases, such
+ as when funds are reallocated from categories with
+ negative budgeting (e.g. using savings to cover
+ overspending), the chart structure may differ from the
+ main budget overview. As a result, some category totals
+ and flows in this diagram may not exactly match the
+ summary figures elsewhere in the app.
+ </Paragraph>
</Trans>
</View>
)}
diff --git a/packages/desktop-client/src/components/reports/reports/SankeyCard.tsx b/packages/desktop-client/src/components/reports/reports/SankeyCard.tsx
index 0b28fcd7ff..721aa63aee 100644
--- a/packages/desktop-client/src/components/reports/reports/SankeyCard.tsx
+++ b/packages/desktop-client/src/components/reports/reports/SankeyCard.tsx
@@ -1,4 +1,4 @@
-import { useMemo, useState } from 'react';
+import { useEffect, useMemo, useRef, useState } from 'react';
import type { ReactElement } from 'react';
import { useTranslation } from 'react-i18next';
@@ -7,6 +7,7 @@ import { theme } from '@actual-app/components/theme';
import { View } from '@actual-app/components/view';
import type { SankeyWidget } from '@actual-app/core/types/models';
import * as d from 'date-fns';
+import debounce from 'lodash/debounce';
import { SankeyGraph } from '#components/reports/graphs/SankeyGraph';
import { LoadingIndicator } from '#components/reports/LoadingIndicator';
@@ -14,9 +15,17 @@ import { ReportCard } from '#components/reports/ReportCard';
import { ReportCardName } from '#components/reports/ReportCardName';
import { calculateTimeRange } from '#components/reports/reportRanges';
import {
+ getDefaultLayerRange,
+ topNNodes,
+} from '#components/reports/reports/Sankey';
+import {
+ buildSankeyData,
+ createBaseGraphSpreadsheet,
+ isGraphLayer,
+} from '#components/reports/spreadsheets/sankey-spreadsheet';
+import type {
+ Graph,
GraphLayers,
- // compactSankeyData,
- createSpreadsheet as sankeySpreadsheet,
} from '#components/reports/spreadsheets/sankey-spreadsheet';
import { useDashboardWidgetCopyMenu } from '#components/reports/useDashboardWidgetCopyMenu';
import { useReport } from '#components/reports/useReport';
@@ -52,58 +61,55 @@ export function SankeyCard({
const mode = meta?.mode ?? 'spent';
const [cardHeight, setCardHeight] = useState(0);
+ const throttledSetCardHeight = useMemo(
+ () =>
+ debounce(
+ (height: number) => {
+ setCardHeight(prev => (prev === height ? prev : height));
+ },
+ 200,
+ { leading: true, trailing: true, maxWait: 100 },
+ ),
+ [],
+ );
+
+ useEffect(() => {
+ return () => {
+ throttledSetCardHeight.cancel();
+ };
+ }, [throttledSetCardHeight]);
+
const containerRef = useResizeObserver<HTMLDivElement>(rect => {
- setCardHeight(rect.height);
+ throttledSetCardHeight(rect.height);
});
- const HEADER_HEIGHT = 82;
- const PX_PER_NODE = 50;
- const heightBasedTopN = Math.max(
- 2,
- Math.floor((cardHeight - HEADER_HEIGHT) / PX_PER_NODE),
- );
- const topN = meta?.topNcategories ?? heightBasedTopN;
-
- const isGraphLayer = (value: unknown): value is GraphLayers =>
- typeof value === 'string' &&
- (Object.values(GraphLayers) as string[]).includes(value);
-
- const defaultLayerFrom =
- mode === 'budgeted' ? GraphLayers.IncomeCategory : GraphLayers.IncomePayee;
- const defaultLayerTo = GraphLayers.CategoryGroup;
-
- const metaLayerFrom = isGraphLayer(meta?.layerFrom)
- ? meta.layerFrom
- : undefined;
- const metaLayerTo = isGraphLayer(meta?.layerTo) ? meta.layerTo : undefined;
-
- const layerFrom =
- metaLayerFrom &&
- !(mode === 'budgeted' && metaLayerFrom === GraphLayers.IncomePayee) &&
- !(mode === 'spent' && metaLayerFrom === GraphLayers.Budget)
- ? metaLayerFrom
- : defaultLayerFrom;
-
- const layerTo =
- metaLayerTo &&
- !(mode === 'budgeted' && metaLayerTo === GraphLayers.IncomePayee) &&
- !(mode === 'spent' && metaLayerTo === GraphLayers.Budget)
- ? metaLayerTo
- : defaultLayerTo;
-
- const params = useMemo(
+ const heightBasedTopN = topNNodes(cardHeight);
+ const configuredTopN = meta?.topNcategories ?? 15;
+ const topN = Math.min(configuredTopN, heightBasedTopN);
+
+ const defaultLayerRange = getDefaultLayerRange(mode);
+ let layerFrom: GraphLayers;
+ let layerTo: GraphLayers;
+ if (isGraphLayer(meta?.layerFrom) && isGraphLayer(meta?.layerTo)) {
+ layerFrom = meta.layerFrom as GraphLayers;
+ layerTo = meta.layerTo as GraphLayers;
+ } else {
+ layerFrom = defaultLayerRange.from;
+ layerTo = defaultLayerRange.to;
+ }
+
+ const groupAccounts = meta?.groupAccounts ?? false;
+
+ const baseGraphParams = useMemo(
() =>
- sankeySpreadsheet(
+ createBaseGraphSpreadsheet(
start,
end,
groupedCategories,
meta?.conditions ?? [],
meta?.conditionsOp ?? 'and',
mode,
- topN,
- meta?.categorySort,
- layerFrom,
- layerTo,
+ groupAccounts,
),
[
start,
@@ -112,15 +118,45 @@ export function SankeyCard({
meta?.conditions,
meta?.conditionsOp,
mode,
+ groupAccounts,
+ ],
+ );
+ const defaultGetBaseGraph = async (
+ _spreadsheet: unknown,
+ setData: (data: Graph) => void,
+ ) => setData(new Map());
+
+ const baseGraph = useReport('sankey', baseGraphParams ?? defaultGetBaseGraph);
+ const baseGraphRef = useRef(baseGraph);
+
+ useEffect(() => {
+ if (baseGraph) {
+ baseGraphRef.current = baseGraph;
+ }
+ }, [baseGraph]);
+
+ const displayBaseGraph = baseGraph || baseGraphRef.current;
+ const compactData = useMemo(() => {
+ if (!displayBaseGraph) {
+ return null;
+ }
+
+ return buildSankeyData(
+ displayBaseGraph,
topN,
- meta?.categorySort,
+ groupedCategories,
+ meta?.categorySort ?? 'per-group',
layerFrom,
layerTo,
- ],
- );
- const data = useReport('sankey', params);
-
- const compactData = useMemo(() => data, [data]);
+ );
+ }, [
+ displayBaseGraph,
+ topN,
+ groupedCategories,
+ meta?.categorySort,
+ layerFrom,
+ layerTo,
+ ]);
const startDate = d.parseISO(start);
const endDate = d.parseISO(end);
@@ -171,7 +207,7 @@ export function SankeyCard({
}
}}
>
- <View ref={containerRef} style={{ flex: 1 }}>
+ <View style={{ flex: 1 }}>
<View style={{ flexDirection: 'row', padding: 20 }}>
<View style={{ flex: 1 }}>
<ReportCardName
@@ -193,12 +229,14 @@ export function SankeyCard({
</View>
{compactData ? (
- <SankeyGraph
- data={compactData}
- showPercentages={meta?.showPercentages}
- showTooltip={!isEditing}
- style={{ height: 'auto', flex: 1 }}
- />
+ <View ref={containerRef} style={{ flexGrow: 1 }}>
+ <SankeyGraph
+ data={compactData}
+ showPercentages={meta?.showPercentages}
+ showTooltip={!isEditing}
+ style={{ flex: 1 }}
+ />
+ </View>
) : (
<LoadingIndicator />
)}
diff --git a/packages/desktop-client/src/components/reports/spreadsheets/sankey-spreadsheet.test.ts b/packages/desktop-client/src/components/reports/spreadsheets/sankey-spreadsheet.test.ts
new file mode 100644
index 0000000000..c814b9a9b0
--- /dev/null
+++ b/packages/desktop-client/src/components/reports/spreadsheets/sankey-spreadsheet.test.ts
@@ -0,0 +1,764 @@
+import type { RuleConditionEntity } from '@actual-app/core/types/models';
+import { describe, expect, it, vi } from 'vitest';
+
+import {
+ addNode,
+ addPercentageLabels,
+ addValueToLink,
+ cleanUpNodes,
+ convertToSankeyData,
+ createBudgetGraph,
+ createTransactionsGraph,
+ deleteLink,
+ filterCategoryGroups,
+ filterGraphByLayers,
+ getCategoryGroup,
+ getLayer,
+ getNodeValue,
+ GraphLayers,
+ hasChild,
+ hasParent,
+ isGraphLayer,
+ moveNodeToEnd,
+ moveNodeToStart,
+ nodesInLayer,
+ sortGraph,
+} from './sankey-spreadsheet';
+import type { Graph, NodeData } from './sankey-spreadsheet';
+
+// Mock i18n
+vi.mock('i18next', () => ({
+ t: (key: string, params?: Record<string, string>) => {
+ if (params && params.month) {
+ return `translated: ${key} (${params.month})`;
+ }
+ if (params && params.category) {
+ return `translated: ${key} (${params.category})`;
+ }
+ return `translated: ${key}`;
+ },
+}));
+
+describe('sankey-spreadsheet', () => {
+ describe('isGraphLayer', () => {
+ it('returns true for valid graph layers', () => {
+ expect(isGraphLayer('payee')).toBe(true);
+ expect(isGraphLayer('income_category')).toBe(true);
+ expect(isGraphLayer('account')).toBe(true);
+ expect(isGraphLayer('budget')).toBe(true);
+ expect(isGraphLayer('category_group')).toBe(true);
+ expect(isGraphLayer('category')).toBe(true);
+ });
+
+ it('returns false for invalid values', () => {
+ expect(isGraphLayer('invalid')).toBe(false);
+ expect(isGraphLayer('')).toBe(false);
+ expect(isGraphLayer(123)).toBe(false);
+ expect(isGraphLayer(null)).toBe(false);
+ expect(isGraphLayer(undefined)).toBe(false);
+ });
+ });
+
+ describe('addNode', () => {
+ it('adds a new node to the graph', () => {
+ const graph: Graph = new Map();
+ addNode(graph, 'node1', GraphLayers.Category, 'Category 1');
+
+ expect(graph.has('node1')).toBe(true);
+ const node = graph.get('node1');
+ expect(node?.type).toBe(GraphLayers.Category);
+ expect(node?.name).toBe('Category 1');
+ expect(node?.to.size).toBe(0);
+ });
+
+ it('does not overwrite existing node', () => {
+ const graph: Graph = new Map();
+ addNode(graph, 'node1', GraphLayers.Category, 'Category 1');
+ addNode(graph, 'node1', GraphLayers.Account, 'Account 1');
+
+ const node = graph.get('node1');
+ expect(node?.type).toBe(GraphLayers.Category);
+ expect(node?.name).toBe('Category 1');
+ });
+ });
+
+ describe('addValueToLink', () => {
+ it('adds a link between nodes', () => {
+ const graph: Graph = new Map();
+ addNode(graph, 'source', GraphLayers.Category, 'Source');
+ addNode(graph, 'target', GraphLayers.Category, 'Target');
+ addValueToLink(graph, 'source', 'target', 100);
+
+ const sourceNode = graph.get('source');
+ expect(sourceNode?.to.get('target')).toBe(100);
+ });
+
+ it('accumulates values for same link', () => {
+ const graph: Graph = new Map();
+ addNode(graph, 'source', GraphLayers.Category, 'Source');
+ addNode(graph, 'target', GraphLayers.Category, 'Target');
+ addValueToLink(graph, 'source', 'target', 100);
+ addValueToLink(graph, 'source', 'target', 50);
+
+ const sourceNode = graph.get('source');
+ expect(sourceNode?.to.get('target')).toBe(150);
+ });
+
+ it('does nothing if source node does not exist', () => {
+ const graph: Graph = new Map();
+ addValueToLink(graph, 'nonexistent', 'target', 100);
+
+ expect(graph.size).toBe(0);
+ });
+ });
+
+ describe('getLayer', () => {
+ it('returns 0 for root nodes (no parents)', () => {
+ const graph: Graph = new Map();
+ addNode(graph, 'root', GraphLayers.Account, 'Root');
+
+ expect(getLayer(graph, 'root')).toBe(0);
+ });
+
+ it('returns correct layer for nodes with parents', () => {
+ const graph: Graph = new Map();
+ addNode(graph, 'root', GraphLayers.Account, 'Root');
+ addNode(graph, 'child', GraphLayers.Category, 'Child');
+ addNode(graph, 'grandchild', GraphLayers.Category, 'Grandchild');
+ addValueToLink(graph, 'root', 'child', 100);
+ addValueToLink(graph, 'child', 'grandchild', 50);
+
+ expect(getLayer(graph, 'root')).toBe(0);
+ expect(getLayer(graph, 'child')).toBe(1);
+ expect(getLayer(graph, 'grandchild')).toBe(2);
+ });
+ });
+
+ describe('nodesInLayer', () => {
+ it('returns nodes in the specified layer', () => {
+ const graph: Graph = new Map();
+ addNode(graph, 'node1', GraphLayers.Category, 'Category 1');
+ addNode(graph, 'node2', GraphLayers.Category, 'Category 2');
+ addNode(graph, 'node3', GraphLayers.Account, 'Account 1');
+
+ const categoryNodes = nodesInLayer(graph, GraphLayers.Category);
+ expect(categoryNodes).toHaveLength(2);
+ expect(categoryNodes).toContain('node1');
+ expect(categoryNodes).toContain('node2');
+
+ const accountNodes = nodesInLayer(graph, GraphLayers.Account);
+ expect(accountNodes).toHaveLength(1);
+ expect(accountNodes).toContain('node3');
+ });
+
+ it('returns empty array if no nodes in layer', () => {
+ const graph: Graph = new Map();
+ const result = nodesInLayer(graph, GraphLayers.Category);
+ expect(result).toHaveLength(0);
+ });
+ });
+
+ describe('hasParent', () => {
+ it('returns true if node has a parent', () => {
+ const graph: Graph = new Map();
+ addNode(graph, 'parent', GraphLayers.Account, 'Parent');
+ addNode(graph, 'child', GraphLayers.Category, 'Child');
+ addValueToLink(graph, 'parent', 'child', 100);
+
+ expect(hasParent(graph, 'child')).toBe(true);
+ });
+
+ it('returns false if node has no parent', () => {
+ const graph: Graph = new Map();
+ addNode(graph, 'orphan', GraphLayers.Category, 'Orphan');
+
+ expect(hasParent(graph, 'orphan')).toBe(false);
+ });
+ });
+
+ describe('hasChild', () => {
+ it('returns true if node has children', () => {
+ const node: NodeData = {
+ to: new Map([['child1', 100]]),
+ type: GraphLayers.Category,
+ };
+
+ expect(hasChild(node)).toBe(true);
+ });
+
+ it('returns false if node has no children', () => {
+ const node: NodeData = {
+ to: new Map(),
+ type: GraphLayers.Category,
+ };
+
+ expect(hasChild(node)).toBe(false);
+ });
+ });
+
+ describe('getNodeValue', () => {
+ it('returns sum of outgoing links for root nodes', () => {
+ const graph: Graph = new Map();
+ addNode(graph, 'root', GraphLayers.Account, 'Root');
+ addValueToLink(graph, 'root', 'child1', 100);
+ addValueToLink(graph, 'root', 'child2', 200);
+
+ expect(getNodeValue(graph, 'root')).toBe(300);
+ });
+
+ it('returns sum of incoming links for non-root nodes', () => {
+ const graph: Graph = new Map();
+ addNode(graph, 'root', GraphLayers.Account, 'Root');
+ addNode(graph, 'child', GraphLayers.Category, 'Child');
+ addValueToLink(graph, 'root', 'child', 150);
+
+ expect(getNodeValue(graph, 'child')).toBe(150);
+ });
+ });
+
+ describe('getCategoryGroup', () => {
+ it('returns the category group for a category', () => {
+ const graph: Graph = new Map();
+ addNode(graph, 'group1', GraphLayers.CategoryGroup, 'Group 1');
+ addNode(graph, 'cat1', GraphLayers.Category, 'Category 1');
+ addValueToLink(graph, 'group1', 'cat1', 100);
+
+ const result = getCategoryGroup(graph, 'cat1');
+ expect(result).toBeDefined();
+ expect(result![0]).toBe('group1');
+ expect(result![1].type).toBe(GraphLayers.CategoryGroup);
+ });
+
+ it('returns undefined if no category group found', () => {
+ const graph: Graph = new Map();
+ addNode(graph, 'cat1', GraphLayers.Category, 'Category 1');
+
+ const result = getCategoryGroup(graph, 'cat1');
+ expect(result).toBeUndefined();
+ });
+ });
+
+ describe('deleteLink', () => {
+ it('deletes a link between nodes', () => {
+ const graph: Graph = new Map();
+ addNode(graph, 'source', GraphLayers.Category, 'Source');
+ addNode(graph, 'target', GraphLayers.Category, 'Target');
+ addValueToLink(graph, 'source', 'target', 100);
+
+ deleteLink(graph, 'source', 'target');
+
+ const sourceNode = graph.get('source');
+ expect(sourceNode?.to.has('target')).toBe(false);
+ });
+
+ it('does nothing if source node does not exist', () => {
+ const graph: Graph = new Map();
+ deleteLink(graph, 'nonexistent', 'target');
+
+ expect(graph.size).toBe(0);
+ });
+ });
+
+ describe('moveNodeToEnd', () => {
+ it('moves a node entry to the end of the array', () => {
+ const entries: Array<[string, NodeData]> = [
+ ['node1', { to: new Map(), type: GraphLayers.Category }],
+ ['node2', { to: new Map(), type: GraphLayers.Category }],
+ ['node3', { to: new Map(), type: GraphLayers.Category }],
+ ];
+
+ moveNodeToEnd(entries, 'node1');
+
+ expect(entries[0][0]).toBe('node2');
+ expect(entries[1][0]).toBe('node3');
+ expect(entries[2][0]).toBe('node1');
+ });
+
+ it('does nothing if node not found', () => {
+ const entries: Array<[string, NodeData]> = [
+ ['node1', { to: new Map(), type: GraphLayers.Category }],
+ ['node2', { to: new Map(), type: GraphLayers.Category }],
+ ];
+
+ moveNodeToEnd(entries, 'nonexistent');
+
+ expect(entries[0][0]).toBe('node1');
+ expect(entries[1][0]).toBe('node2');
+ });
+ });
+
+ describe('moveNodeToStart', () => {
+ it('moves a node entry to the start of the array', () => {
+ const entries: Array<[string, NodeData]> = [
+ ['node1', { to: new Map(), type: GraphLayers.Category }],
+ ['node2', { to: new Map(), type: GraphLayers.Category }],
+ ['node3', { to: new Map(), type: GraphLayers.Category }],
+ ];
+
+ moveNodeToStart(entries, 'node3');
+
+ expect(entries[0][0]).toBe('node3');
+ expect(entries[1][0]).toBe('node1');
+ expect(entries[2][0]).toBe('node2');
+ });
+
+ it('does nothing if node not found', () => {
+ const entries: Array<[string, NodeData]> = [
+ ['node1', { to: new Map(), type: GraphLayers.Category }],
+ ['node2', { to: new Map(), type: GraphLayers.Category }],
+ ];
+
+ moveNodeToStart(entries, 'nonexistent');
+
+ expect(entries[0][0]).toBe('node1');
+ expect(entries[1][0]).toBe('node2');
+ });
+ });
+
+ describe('filterCategoryGroups', () => {
+ const createCategoryGroup = (
+ id: string,
+ name: string,
+ isIncome: boolean,
+ categories: Array<{ id: string; name: string }>,
+ ) => ({
+ id,
+ name,
+ is_income: isIncome,
+ categories: categories.map(c => ({
+ ...c,
+ spent: 0,
+ budgeted: 0,
+ balance: 0,
+ received: 0,
+ })),
+ });
+
+ it('returns all groups if no conditions', () => {
+ const groups = [
+ createCategoryGroup('g1', 'Group 1', false, [
+ { id: 'c1', name: 'Cat 1' },
+ ]),
+ createCategoryGroup('g2', 'Group 2', false, [
+ { id: 'c2', name: 'Cat 2' },
+ ]),
+ ];
+
+ const result = filterCategoryGroups(groups, [], 'and');
+ expect(result).toHaveLength(2);
+ });
+
+ it('filters by category id with "is" operator', () => {
+ const groups = [
+ createCategoryGroup('g1', 'Group 1', false, [
+ { id: 'c1', name: 'Cat 1' },
+ { id: 'c2', name: 'Cat 2' },
+ ]),
+ ];
+
+ const conditions: RuleConditionEntity[] = [
+ { field: 'category', op: 'is', value: 'c1', customName: '' },
+ ];
+
+ const result = filterCategoryGroups(groups, conditions, 'and');
+ expect(result).toHaveLength(1);
+ expect(result[0].categories).toHaveLength(1);
+ expect(result[0].categories[0].id).toBe('c1');
+ });
+
+ it('filters by category id with "isNot" operator', () => {
+ const groups = [
+ createCategoryGroup('g1', 'Group 1', false, [
+ { id: 'c1', name: 'Cat 1' },
+ { id: 'c2', name: 'Cat 2' },
+ ]),
+ ];
+
+ const conditions: RuleConditionEntity[] = [
+ { field: 'category', op: 'isNot', value: 'c1', customName: '' },
+ ];
+
+ const result = filterCategoryGroups(groups, conditions, 'and');
+ expect(result).toHaveLength(1);
+ expect(result[0].categories).toHaveLength(1);
+ expect(result[0].categories[0].id).toBe('c2');
+ });
+
+ it('filters by category name with "contains" operator', () => {
+ const groups = [
+ createCategoryGroup('g1', 'Group 1', false, [
+ { id: 'c1', name: 'Groceries' },
+ { id: 'c2', name: 'Entertainment' },
+ ]),
+ ];
+
+ const conditions: RuleConditionEntity[] = [
+ {
+ field: 'category',
+ op: 'contains',
+ value: 'groceries',
+ customName: '',
+ },
+ ];
+
+ const result = filterCategoryGroups(groups, conditions, 'and');
+ expect(result).toHaveLength(1);
+ expect(result[0].categories).toHaveLength(1);
+ expect(result[0].categories[0].name).toBe('Groceries');
+ });
+
+ it('filters by category group with "is" operator', () => {
+ const groups = [
+ createCategoryGroup('g1', 'Group 1', false, [
+ { id: 'c1', name: 'Cat 1' },
+ ]),
+ createCategoryGroup('g2', 'Group 2', false, [
+ { id: 'c2', name: 'Cat 2' },
+ ]),
+ ];
+
+ const conditions: RuleConditionEntity[] = [
+ { field: 'category_group', op: 'is', value: 'g2', customName: '' },
+ ];
+
+ const result = filterCategoryGroups(groups, conditions, 'and');
+ expect(result).toHaveLength(1);
+ expect(result[0].id).toBe('g2');
+ });
+
+ it('returns empty if no categories match', () => {
+ const groups = [
+ createCategoryGroup('g1', 'Group 1', false, [
+ { id: 'c1', name: 'Cat 1' },
+ ]),
+ ];
+
+ const conditions: RuleConditionEntity[] = [
+ { field: 'category', op: 'is', value: 'nonexistent', customName: '' },
+ ];
+
+ const result = filterCategoryGroups(groups, conditions, 'and');
+ expect(result).toHaveLength(0);
+ });
+
+ it('handles "oneOf" operator for category', () => {
+ const groups = [
+ createCategoryGroup('g1', 'Group 1', false, [
+ { id: 'c1', name: 'Cat 1' },
+ { id: 'c2', name: 'Cat 2' },
+ { id: 'c3', name: 'Cat 3' },
+ ]),
+ ];
+
+ const conditions: RuleConditionEntity[] = [
+ { field: 'category', op: 'oneOf', value: ['c1', 'c3'], customName: '' },
+ ];
+
+ const result = filterCategoryGroups(groups, conditions, 'and');
+ expect(result).toHaveLength(1);
+ expect(result[0].categories).toHaveLength(2);
+ expect(result[0].categories.map(c => c.id)).toContain('c1');
+ expect(result[0].categories.map(c => c.id)).toContain('c3');
+ });
+ });
+
+ describe('createBudgetGraph', () => {
+ it('creates a graph with income and expense categories', () => {
+ const categoryData = [
+ {
+ categoryGroup: 'Income',
+ categoryGroupId: 'g_income',
+ category: 'Salary',
+ categoryId: 'c_salary',
+ value: 5000,
+ isIncome: true,
+ },
+ {
+ categoryGroup: 'Food',
+ categoryGroupId: 'g_food',
+ category: 'Groceries',
+ categoryId: 'c_groceries',
+ value: 500,
+ isIncome: false,
+ },
+ ];
+
+ const aggregated = {
+ toBudget: 1000,
+ fromPreviousMonth: 200,
+ lastMonthOverspent: 0,
+ categoryGroupsMap: new Map(),
+ forNextMonth: 300,
+ startMonth: '2024-01',
+ endMonth: '2024-01',
+ };
+
+ const graph = createBudgetGraph(categoryData, aggregated);
+
+ expect(graph.has('c_salary')).toBe(true);
+ expect(graph.has('c_groceries')).toBe(true);
+ expect(graph.has('budgeted')).toBe(true);
+ expect(graph.has('available_income')).toBe(true);
+ expect(graph.has('to_budget')).toBe(true);
+ });
+
+ it('marks to_budget as overbudgeted when negative', () => {
+ const categoryData: Array<{
+ categoryGroup: string;
+ categoryGroupId: string;
+ category: string;
+ categoryId: string;
+ value: number;
+ isIncome: boolean;
+ }> = [];
+
+ const aggregated = {
+ toBudget: -500,
+ fromPreviousMonth: 0,
+ lastMonthOverspent: 0,
+ categoryGroupsMap: new Map(),
+ forNextMonth: 0,
+ startMonth: '2024-01',
+ endMonth: '2024-01',
+ };
+
+ const graph = createBudgetGraph(categoryData, aggregated);
+ const toBudgetNode = graph.get('to_budget');
+
+ expect(toBudgetNode?.isOverbudgeted).toBe(true);
+ expect(toBudgetNode?.labelKey).toBe('Overbudgeted');
+ });
+ });
+
+ describe('createTransactionsGraph', () => {
+ it('creates a graph with account and category nodes', () => {
+ const categoryData = [
+ {
+ categoryGroup: 'Food',
+ categoryGroupId: 'g_food',
+ category: 'Groceries',
+ categoryId: 'c_groceries',
+ value: 100,
+ isIncome: false,
+ accountName: 'Checking',
+ accountId: 'a_checking',
+ },
+ {
+ categoryGroup: 'Income',
+ categoryGroupId: 'g_income',
+ category: 'Salary',
+ categoryId: 'c_salary',
+ value: 5000,
+ isIncome: true,
+ accountName: 'Checking',
+ accountId: 'a_checking',
+ payeeName: 'Employer',
+ payeeId: 'p_employer',
+ },
+ ];
+
+ const graph = createTransactionsGraph(categoryData);
+
+ expect(graph.has('a_checking')).toBe(true);
+ expect(graph.has('c_groceries')).toBe(true);
+ expect(graph.has('c_salary')).toBe(true);
+ expect(graph.has('p_employer')).toBe(true);
+ });
+ });
+
+ describe('sortGraph', () => {
+ it('sorts by global value when mode is global', () => {
+ const graph: Graph = new Map();
+ addNode(graph, 'node1', GraphLayers.Category, 'Node 1');
+ addNode(graph, 'node2', GraphLayers.Category, 'Node 2');
+ addNode(graph, 'node3', GraphLayers.Category, 'Node 3');
+ addValueToLink(graph, 'node1', 'target', 100);
+ addValueToLink(graph, 'node2', 'target', 300);
+ addValueToLink(graph, 'node3', 'target', 200);
+
+ const sorted = sortGraph(graph, 'global', []);
+
+ const keys = Array.from(sorted.keys());
+ expect(keys[0]).toBe('node2'); // 300
+ expect(keys[1]).toBe('node3'); // 200
+ expect(keys[2]).toBe('node1'); // 100
+ });
+
+ it('sorts by budget order when mode is budget-order', () => {
+ const graph: Graph = new Map();
+ addNode(graph, 'g1', GraphLayers.CategoryGroup, 'Group 1');
+ addNode(graph, 'g2', GraphLayers.CategoryGroup, 'Group 2');
+ addNode(graph, 'c1', GraphLayers.Category, 'Cat 1');
+ addNode(graph, 'c2', GraphLayers.Category, 'Cat 2');
+ addValueToLink(graph, 'g1', 'c1', 100);
+ addValueToLink(graph, 'g2', 'c2', 200);
+
+ const sorted = sortGraph(graph, 'budget-order', []);
+ const keys = Array.from(sorted.keys());
+
+ // Should follow the order in categories array
+ expect(keys.indexOf('g1')).toBeLessThan(keys.indexOf('c1'));
+ expect(keys.indexOf('g2')).toBeLessThan(keys.indexOf('c2'));
+ });
+
+ it('sorts payees according to income categories in per-group mode', () => {
+ const graph: Graph = new Map();
+ addNode(graph, 'payee1', GraphLayers.IncomePayee, 'Payee 1');
+ addNode(graph, 'payee2', GraphLayers.IncomePayee, 'Payee 2');
+ addNode(graph, 'payee3', GraphLayers.IncomePayee, 'Payee 3');
+ addNode(graph, 'income1', GraphLayers.IncomeCategory, 'Income 1');
+ addNode(graph, 'income2', GraphLayers.IncomeCategory, 'Income 2');
+ addNode(graph, 'account1', GraphLayers.Account, 'Account 1');
+
+ addValueToLink(graph, 'payee1', 'income1', 300);
+ addValueToLink(graph, 'payee2', 'income2', 200);
+ addValueToLink(graph, 'payee3', 'income2', 200);
+ addValueToLink(graph, 'income1', 'account1', 300);
+ addValueToLink(graph, 'income2', 'account1', 400);
+
+ const sorted = sortGraph(graph, 'per-group', []);
+ const keys = Array.from(sorted.keys());
+
+ const payee1Index = keys.indexOf('payee1');
+ const payee2Index = keys.indexOf('payee2');
+ const payee3Index = keys.indexOf('payee3');
+
+ expect(payee2Index).toBeLessThan(payee1Index);
+ expect(payee3Index).toBeLessThan(payee1Index);
+ });
+ });
+
+ describe('addPercentageLabels', () => {
+ it('adds percentage labels to all nodes', () => {
+ const graph: Graph = new Map();
+ addNode(graph, 'node1', GraphLayers.Category, 'Node 1');
+ addNode(graph, 'node2', GraphLayers.Category, 'Node 2');
+ addValueToLink(graph, 'node1', 'target', 250);
+ addValueToLink(graph, 'node2', 'target', 750);
+
+ addPercentageLabels(graph);
+
+ const node1 = graph.get('node1');
+ const node2 = graph.get('node2');
+
+ // Total layer value = 1000, node1 = 25%, node2 = 75%
+ expect(node1?.percentageLabel).toBe('25.0%');
+ expect(node2?.percentageLabel).toBe('75.0%');
+ });
+ });
+
+ describe('filterGraphByLayers', () => {
+ it('keeps only nodes within the specified layer range', () => {
+ const graph: Graph = new Map();
+ addNode(graph, 'payee1', GraphLayers.IncomePayee, 'Payee 1');
+ addNode(graph, 'cat1', GraphLayers.IncomeCategory, 'Income Cat 1');
+ addNode(graph, 'acc1', GraphLayers.Account, 'Account 1');
+ addNode(graph, 'budget', GraphLayers.Budget, 'Budgeted');
+ addNode(graph, 'group1', GraphLayers.CategoryGroup, 'Group 1');
+ addNode(graph, 'cat2', GraphLayers.Category, 'Category 2');
+
+ filterGraphByLayers(
+ graph,
+ GraphLayers.Account,
+ GraphLayers.CategoryGroup,
+ );
+
+ expect(graph.has('payee1')).toBe(false);
+ expect(graph.has('cat1')).toBe(false);
+ expect(graph.has('acc1')).toBe(true);
+ expect(graph.has('budget')).toBe(true);
+ expect(graph.has('group1')).toBe(true);
+ expect(graph.has('cat2')).toBe(false);
+ });
+
+ it('filters correctly when the from layer is the first layer', () => {
+ const graph: Graph = new Map();
+ addNode(graph, 'payee1', GraphLayers.IncomePayee, 'Payee 1');
+ addNode(graph, 'cat1', GraphLayers.IncomeCategory, 'Income Cat 1');
+ addNode(graph, 'acc1', GraphLayers.Account, 'Account 1');
+ addNode(graph, 'group1', GraphLayers.CategoryGroup, 'Group 1');
+ addNode(graph, 'cat2', GraphLayers.Category, 'Category 2');
+
+ filterGraphByLayers(
+ graph,
+ GraphLayers.IncomePayee,
+ GraphLayers.CategoryGroup,
+ );
+
+ expect(graph.has('payee1')).toBe(true);
+ expect(graph.has('cat1')).toBe(true);
+ expect(graph.has('acc1')).toBe(true);
+ expect(graph.has('group1')).toBe(true);
+ expect(graph.has('cat2')).toBe(false);
+ });
+ });
+
+ describe('cleanUpNodes', () => {
+ it('removes nodes with no incoming or outgoing links', () => {
+ const graph: Graph = new Map();
+ addNode(graph, 'used1', GraphLayers.Category, 'Used 1');
+ addNode(graph, 'used2', GraphLayers.Category, 'Used 2');
+ addNode(graph, 'orphan', GraphLayers.Category, 'Orphan');
+ addValueToLink(graph, 'used1', 'used2', 100);
+
+ cleanUpNodes(graph);
+
+ expect(graph.has('used1')).toBe(true);
+ expect(graph.has('used2')).toBe(true);
+ expect(graph.has('orphan')).toBe(false);
+ });
+
+ it('removes zero-value links before cleaning', () => {
+ const graph: Graph = new Map();
+ addNode(graph, 'node1', GraphLayers.Category, 'Node 1');
+ addNode(graph, 'node2', GraphLayers.Category, 'Node 2');
+ addValueToLink(graph, 'node1', 'node2', 0);
+
+ cleanUpNodes(graph);
+
+ expect(graph.has('node1')).toBe(false);
+ expect(graph.has('node2')).toBe(false);
+ });
+ });
+
+ describe('convertToSankeyData', () => {
+ it('converts graph to sankey data format', () => {
+ const graph: Graph = new Map();
+ addNode(graph, 'node1', GraphLayers.Category, 'Node 1');
+ addNode(graph, 'node2', GraphLayers.Category, 'Node 2');
+ addValueToLink(graph, 'node1', 'node2', 100);
+
+ const result = convertToSankeyData(graph, new Map());
+
+ expect(result.nodes).toHaveLength(2);
+ expect(result.links).toHaveLength(1);
+ expect(result.links[0].source).toBe(0);
+ expect(result.links[0].target).toBe(1);
+ expect(result.links[0].value).toBe(100);
+ });
+
+ it('includes percentage labels in nodes', () => {
+ const graph: Graph = new Map();
+ addNode(graph, 'node1', GraphLayers.Category, 'Node 1');
+ addNode(graph, 'node2', GraphLayers.Category, 'Node 2');
+ addValueToLink(graph, 'node1', 'node2', 100);
+
+ const node1 = graph.get('node1');
+ if (node1) node1.percentageLabel = '100.0%';
+
+ const result = convertToSankeyData(graph, new Map());
+
+ expect(result.nodes[0].percentageLabel).toBe('100.0%');
+ });
+
+ it('translates labelKey nodes', () => {
+ const graph: Graph = new Map();
+ addNode(graph, 'node1', GraphLayers.Budget, 'Node 1');
+ graph.get('node1')!.labelKey = 'Budgeted';
+
+ const result = convertToSankeyData(graph, new Map());
+
+ expect(result.nodes[0].name).toBe('translated: Budgeted');
+ });
+ });
+});
diff --git a/packages/desktop-client/src/components/reports/spreadsheets/sankey-spreadsheet.ts b/packages/desktop-client/src/components/reports/spreadsheets/sankey-spreadsheet.ts
index ab34ed1095..43168aee91 100644
--- a/packages/desktop-client/src/components/reports/spreadsheets/sankey-spreadsheet.ts
+++ b/packages/desktop-client/src/components/reports/spreadsheets/sankey-spreadsheet.ts
@@ -83,10 +83,10 @@ type CategoryEntry = {
type SortMode = 'per-group' | 'global' | 'budget-order';
type NodeKey = string;
-type NodeData = {
+export type NodeData = {
to: Map<NodeKey, number>;
value?: number;
- type: string;
+ type: GraphLayers;
name?: string;
labelKey?: string;
labelParams?: Record<string, string>;
@@ -95,7 +95,12 @@ type NodeData = {
percentageLabel?: string;
color?: string;
};
-type Graph = Map<NodeKey, NodeData>;
+export type Graph = Map<NodeKey, NodeData>;
+
+type TooltipInfoMap = Map<
+ NodeKey,
+ Map<NodeKey, Array<{ name: string; value: number }>>
+>;
const SpecialNodeKeys = {
ToBudget: 'to_budget',
@@ -104,7 +109,7 @@ const SpecialNodeKeys = {
ForNextMonth: 'for_next_month',
FromPrevMonth: 'from_previous_month',
AvailableIncome: 'available_income',
- GlobalOther: 'GLOBAL__OTHER_BUCKET',
+ AllAccounts: 'all_income',
OtherSuffix: '__OTHER_BUCKET',
HiddenSuffix: '__HIDDEN',
} as const;
@@ -129,60 +134,100 @@ export const GRAPH_LAYER_ORDER = [
GraphLayers.Category,
] as const;
-function isGraphLayer(value: unknown): value is GraphLayers {
+export function isGraphLayer(value: unknown): value is GraphLayers {
return (
typeof value === 'string' &&
(Object.values(GraphLayers) as string[]).includes(value)
);
}
-export function createSpreadsheet(
+export function createBaseGraphSpreadsheet(
start: string,
end: string,
categories: CategoryGroupEntity[],
conditions: RuleConditionEntity[] = [],
conditionsOp: 'and' | 'or' = 'and',
mode: 'budgeted' | 'spent' = 'spent',
- topNcategories: number = 15,
- categorySort: SortMode = 'per-group',
- layerFrom: GraphLayers,
- layerTo: GraphLayers,
+ groupAccounts: boolean = false,
) {
return async (
- spreadsheet: ReturnType<typeof useSpreadsheet>,
- setData: (data: ReturnType<typeof convertToSankeyData>) => void,
+ _spreadsheet: ReturnType<typeof useSpreadsheet>,
+ setData: (data: Graph) => void,
) => {
- let data: CategoryEntry[] = [];
- let aggregated: AggregatedBudget | undefined;
- if (mode === 'budgeted') {
- ({ data, aggregated } = await createBudgetSpreadsheet(
- start,
- end,
- conditions,
- conditionsOp,
- )());
- } else if (mode === 'spent') {
- data = await createTransactionsSpreadsheet(
- start,
- end,
- categories,
- conditions,
- conditionsOp,
- )();
- }
- processGraphData(
- data,
- topNcategories,
+ const baseGraph = await createBaseGraph(
+ start,
+ end,
categories,
- categorySort,
- setData,
- layerFrom,
- layerTo,
- aggregated,
+ conditions,
+ conditionsOp,
+ mode,
+ groupAccounts,
);
+
+ setData(baseGraph);
};
}
+async function createBaseGraph(
+ start: string,
+ end: string,
+ categories: CategoryGroupEntity[],
+ conditions: RuleConditionEntity[] = [],
+ conditionsOp: 'and' | 'or' = 'and',
+ mode: 'budgeted' | 'spent' = 'spent',
+ groupAccounts: boolean = false,
+): Promise<Graph> {
+ let data: CategoryEntry[] = [];
+ let aggregated: AggregatedBudget | undefined;
+
+ if (mode === 'budgeted') {
+ ({ data, aggregated } = await createBudgetSpreadsheet(
+ start,
+ end,
+ conditions,
+ conditionsOp,
+ )());
+ } else if (mode === 'spent') {
+ data = await createTransactionsSpreadsheet(
+ start,
+ end,
+ categories,
+ conditions,
+ conditionsOp,
+ groupAccounts,
+ )();
+ }
+
+ return aggregated
+ ? createBudgetGraph(data, aggregated)
+ : createTransactionsGraph(data);
+}
+
+export function buildSankeyData(
+ baseGraph: Graph,
+ topNcategories: number,
+ categories: CategoryGroupEntity[],
+ categorySort: SortMode,
+ layerFrom: GraphLayers,
+ layerTo: GraphLayers,
+): SankeyData {
+ const graph = cloneGraph(baseGraph);
+
+ const toolTipInfoMap = groupOtherCategories(
+ graph,
+ topNcategories,
+ categorySort,
+ );
+ const sortedGraph = sortGraph(graph, categorySort, categories);
+ addPercentageLabels(sortedGraph);
+ addColors(sortedGraph);
+ cleanUpNodes(sortedGraph);
+ addHiddenNodes(sortedGraph);
+ filterGraphByLayers(sortedGraph, layerFrom, layerTo);
+
+ return convertToSankeyData(sortedGraph, toolTipInfoMap);
+}
+
export function createBudgetSpreadsheet(
start: string,
end: string,
@@ -271,12 +316,12 @@ export function createBudgetSpreadsheet(
categoryGroupId: group.id,
category: cat.name,
categoryId: cat.id,
- isIncome: group.is_income ? rawValue > 0 : rawValue < 0,
- value: Math.abs(rawValue),
+ isIncome: group.is_income,
+ value: rawValue,
};
}),
)
- .filter(entry => entry.value > 0);
+ .filter(entry => entry.value !== 0);
const nextMonthResponse = (await send('api/budget-month', {
month: monthUtils.nextMonth(end),
@@ -303,6 +348,7 @@ export function createTransactionsSpreadsheet(
categories: CategoryGroupEntity[],
conditions: RuleConditionEntity[] = [],
conditionsOp: 'and' | 'or' = 'and',
+ groupAccounts: boolean,
) {
return async () => {
// gather filters user has set
@@ -317,42 +363,32 @@ export function createTransactionsSpreadsheet(
filters,
start,
end,
+ groupAccounts,
);
return categoryData;
};
}
-function processGraphData(
- categoryData: CategoryEntry[],
- topNcategories: number,
- categories: CategoryGroupEntity[],
- categorySort: SortMode,
- setData: (data: ReturnType<typeof convertToSankeyData>) => void,
- layerFrom: GraphLayers,
- layerTo: GraphLayers,
- aggregated?: AggregatedBudget,
-) {
- let graph: Graph;
- if (aggregated) {
- graph = createBudgetGraph(categoryData, aggregated);
- } else {
- graph = createTransactionsGraph(categoryData);
+function cloneGraph(graph: Graph): Graph {
+ const clonedGraph: Graph = new Map();
+
+ for (const [key, node] of graph) {
+ clonedGraph.set(key, {
+ ...node,
+ to: new Map(node.to),
+ tooltipInfo: node.tooltipInfo?.map(info => ({ ...info })),
+ });
}
- groupOtherCategories(graph, topNcategories, categorySort);
- const sortedGraph = sortGraph(graph, categorySort, categories);
- addPercentageLabels(sortedGraph);
- addColors(sortedGraph);
- filterGraphByLayers(sortedGraph, layerFrom, layerTo);
- cleanUpNodes(sortedGraph);
- setData(convertToSankeyData(sortedGraph));
+
+ return clonedGraph;
}
// Filter budget category groups to only those matching the user's conditions.
// Budget data is fetched unconditionally from api/budget-month, so we must
// apply category conditions manually in JS (unlike the transaction path which
// passes conditions directly into the AQL query).
-function filterCategoryGroups(
+export function filterCategoryGroups(
categoryGroups: BudgetMonthGroup[],
conditions: RuleConditionEntity[],
conditionsOp: 'and' | 'or',
@@ -453,6 +489,7 @@ async function fetchCategoryData(
filters: unknown[] = [],
start: string,
end: string,
+ groupAccounts: boolean,
): Promise<CategoryEntry[]> {
const nested = await Promise.all(
categoryGroups.map(async (categoryGroup: CategoryGroupEntity) => {
@@ -485,54 +522,55 @@ async function fetchCategoryData(
{ payeeName: { $id: '$payee.name' } },
]),
);
- return results.data
- .filter(
- (row: { amount?: number }) =>
- categoryGroup.is_income || (row.amount ?? 0) < 0,
- )
- .map(
- (row: {
- amount?: number;
- accountName?: string;
- accountId?: string;
- payeeName?: string;
- payeeId?: string;
- }) =>
- ({
- categoryGroup: categoryGroup.name,
- categoryGroupId: categoryGroup.id,
- category: category.name,
- categoryId: category.id,
- value: Math.abs(row.amount ?? 0),
- isIncome: categoryGroup.is_income ?? false,
- accountName: row.accountName ?? '',
- accountId: row.accountId ?? '',
- payeeName: row.payeeName ?? '',
- payeeId: row.payeeId ?? '',
- }) satisfies CategoryEntry,
- );
+ return results.data.map(
+ (row: {
+ amount?: number;
+ accountName?: string;
+ accountId?: string;
+ payeeName?: string;
+ payeeId?: string;
+ }) =>
+ ({
+ categoryGroup: categoryGroup.name,
+ categoryGroupId: categoryGroup.id,
+ category: category.name,
+ categoryId: category.id,
+ value: Math.abs(row.amount ?? 0),
+ isIncome: categoryGroup.is_income ?? false,
+ accountName: row.accountName ?? '',
+ accountId: row.accountId ?? '',
+ payeeName: row.payeeName ?? '',
+ payeeId: row.payeeId ?? '',
+ }) satisfies CategoryEntry,
+ );
}),
);
return entries.flat();
}),
);
- return nested.flat().filter(e => e.value > 0);
+ const allCategoryData = nested.flat();
+
+ if (groupAccounts) {
+ allCategoryData.forEach(entry => {
+ if (entry.accountName && entry.accountId) {
+ entry.accountName = SpecialNodeKeys.AllAccounts;
+ entry.accountId = SpecialNodeKeys.AllAccounts;
+ }
+ });
+ }
+
+ return allCategoryData;
}
-function createBudgetGraph(
+export function createBudgetGraph(
categoryData: CategoryEntry[],
aggregated: AggregatedBudget,
): Graph {
const graph: Graph = new Map();
// Add initial budget nodes with no links
- addNodeWithLabel(
- graph,
- SpecialNodeKeys.Budgeted,
- GraphLayers.Budget,
- 'Budgeted',
- );
- addNodeWithLabel(
+ addNode(graph, SpecialNodeKeys.Budgeted, GraphLayers.Budget, 'Budgeted');
+ addNode(
graph,
SpecialNodeKeys.AvailableIncome,
GraphLayers.Account,
@@ -555,42 +593,60 @@ function createBudgetGraph(
entry.value,
);
} else {
- // Budgeted > Category group > Category
- addNode(
- graph,
- entry.categoryGroupId,
- GraphLayers.CategoryGroup,
- entry.categoryGroup,
- );
- addNode(graph, entry.categoryId, GraphLayers.Category, entry.category);
- addValueToLink(
- graph,
- entry.categoryGroupId,
- entry.categoryId,
- entry.value,
- );
- addValueToLink(
- graph,
- SpecialNodeKeys.Budgeted,
- entry.categoryGroupId,
- entry.value,
- );
- addValueToLink(
- graph,
- SpecialNodeKeys.AvailableIncome,
- SpecialNodeKeys.Budgeted,
- entry.value,
- );
+ if (entry.value >= 0) {
+ // Budgeted > Category group > Category
+ addNode(
+ graph,
+ entry.categoryGroupId,
+ GraphLayers.CategoryGroup,
+ entry.categoryGroup,
+ );
+ addNode(graph, entry.categoryId, GraphLayers.Category, entry.category);
+ addValueToLink(
+ graph,
+ entry.categoryGroupId,
+ entry.categoryId,
+ entry.value,
+ );
+ addValueToLink(
+ graph,
+ SpecialNodeKeys.Budgeted,
+ entry.categoryGroupId,
+ entry.value,
+ );
+ addValueToLink(
+ graph,
+ SpecialNodeKeys.AvailableIncome,
+ SpecialNodeKeys.Budgeted,
+ entry.value,
+ );
+ } else {
+ addNodeWithLabel(
+ graph,
+ entry.categoryId,
+ GraphLayers.Account,
+ 'From {{category}}',
+ { category: entry.category },
+ true,
+ );
+ addValueToLink(
+ graph,
+ entry.categoryId,
+ SpecialNodeKeys.Budgeted,
+ Math.abs(entry.value),
+ );
+ addValueToLink(
+ graph,
+ SpecialNodeKeys.AvailableIncome,
+ SpecialNodeKeys.Budgeted,
+ entry.value,
+ );
+ }
}
});
if (aggregated.toBudget > 0) {
- addNodeWithLabel(
- graph,
- SpecialNodeKeys.ToBudget,
- GraphLayers.Budget,
- 'To budget',
- );
+ addNode(graph, SpecialNodeKeys.ToBudget, GraphLayers.Account, 'To budget');
addValueToLink(
graph,
SpecialNodeKeys.AvailableIncome,
@@ -601,7 +657,7 @@ function createBudgetGraph(
addNodeWithLabel(
graph,
SpecialNodeKeys.ToBudget,
- GraphLayers.Budget,
+ GraphLayers.Account,
'Overbudgeted',
undefined,
true,
@@ -609,9 +665,15 @@ function createBudgetGraph(
addValueToLink(
graph,
SpecialNodeKeys.ToBudget,
- SpecialNodeKeys.AvailableIncome,
+ SpecialNodeKeys.Budgeted,
Math.abs(aggregated.toBudget),
);
+ addValueToLink(
+ graph,
+ SpecialNodeKeys.AvailableIncome,
+ SpecialNodeKeys.Budgeted,
+ -Math.abs(aggregated.toBudget),
+ );
}
addNodeWithLabel(
@@ -640,7 +702,7 @@ function createBudgetGraph(
SpecialNodeKeys.ForNextMonth,
aggregated.forNextMonth,
);
- addNodeWithLabel(
+ addNode(
graph,
SpecialNodeKeys.LastMonthOverspent,
GraphLayers.Budget,
@@ -653,31 +715,24 @@ function createBudgetGraph(
Math.abs(aggregated.lastMonthOverspent),
);
- // Add extra synthetic links to position nodes at the right layers.
- // If the nodes don't exist, a link will not be created, so this is not seen in the graph.
- addValueToLink(
- graph,
- SpecialNodeKeys.ToBudget,
- 'to_budget' + SpecialNodeKeys.HiddenSuffix,
- -1,
- );
- addValueToLink(
- graph,
- SpecialNodeKeys.ForNextMonth,
- 'next_month' + SpecialNodeKeys.HiddenSuffix,
- -1,
- );
- addValueToLink(
- graph,
- SpecialNodeKeys.LastMonthOverspent,
- 'overspent' + SpecialNodeKeys.HiddenSuffix,
- -1,
- );
-
return graph;
}
-function createTransactionsGraph(categoryData: CategoryEntry[]): Graph {
+export function createTransactionsGraph(categoryData: CategoryEntry[]): Graph {
+ function addAccountNode(accountId: string, accountName: string): void {
+ if (accountId === SpecialNodeKeys.AllAccounts) {
+ addNodeWithLabel(
+ graph,
+ accountId,
+ GraphLayers.Account,
+ 'Income',
+ undefined,
+ );
+ } else {
+ addNode(graph, accountId, GraphLayers.Account, accountName);
+ }
+ }
+
const graph: Graph = new Map();
categoryData.forEach(entry => {
@@ -690,7 +745,7 @@ function createTransactionsGraph(categoryData: CategoryEntry[]): Graph {
GraphLayers.IncomeCategory,
entry.category,
);
- addNode(graph, entry.accountId, GraphLayers.Account, entry.accountName);
+ addAccountNode(entry.accountId, entry.accountName);
addValueToLink(graph, entry.categoryId, entry.accountId, entry.value);
if (entry.payeeId) {
addNode(
@@ -703,7 +758,7 @@ function createTransactionsGraph(categoryData: CategoryEntry[]): Graph {
}
} else {
// Account > Category group > Category
- addNode(graph, entry.accountId, GraphLayers.Account, entry.accountName);
+ addAccountNode(entry.accountId, entry.accountName);
addNode(
graph,
entry.categoryGroupId,
@@ -727,45 +782,15 @@ function createTransactionsGraph(categoryData: CategoryEntry[]): Graph {
}
});
- graph.forEach((data, key) => {
- if (
- data.type === GraphLayers.Account &&
- getLayer(graph, key) === 0 &&
- nodesInLayer(graph, GraphLayers.IncomePayee).length > 0
- ) {
- // If an account node has no parents (i.e. money was spent from the account, but no money added in the timeframe),
- // connect it to a synthetic node to ensure it appears in the graph at the right layer.
- addNode(
- graph,
- key + '_payee' + SpecialNodeKeys.HiddenSuffix,
- GraphLayers.IncomePayee,
- '',
- );
- addNode(
- graph,
- key + '_account' + SpecialNodeKeys.HiddenSuffix,
- GraphLayers.Account,
- '',
- );
- addValueToLink(
- graph,
- key + '_payee' + SpecialNodeKeys.HiddenSuffix,
- key + '_account' + SpecialNodeKeys.HiddenSuffix,
- -1,
- );
- addValueToLink(
- graph,
- key + '_account' + SpecialNodeKeys.HiddenSuffix,
- key,
- -1,
- );
- }
- });
-
return graph;
}
-function addNode(graph: Graph, key: NodeKey, type: GraphLayers, name?: string) {
+export function addNode(
+ graph: Graph,
+ key: NodeKey,
+ type: GraphLayers,
+ name?: string,
+) {
if (!graph.has(key)) {
graph.set(key, {
to: new Map(),
@@ -775,7 +800,7 @@ function addNode(graph: Graph, key: NodeKey, type: GraphLayers, name?: string) {
}
}
-function addNodeWithLabel(
+export function addNodeWithLabel(
graph: Graph,
key: NodeKey,
type: GraphLayers,
@@ -794,7 +819,7 @@ function addNodeWithLabel(
}
}
-function addValueToLink(
+export function addValueToLink(
graph: Graph,
from: NodeKey,
to: NodeKey,
@@ -806,7 +831,7 @@ function addValueToLink(
}
}
-function getLayer(graph: Graph, key: NodeKey): number {
+export function getLayer(graph: Graph, key: NodeKey): number {
// Find parent nodes for the given key
const parents: NodeKey[] = [];
for (const [parentKey, data] of graph) {
@@ -826,216 +851,269 @@ function groupOtherCategories(
graph: Graph,
topN: number,
categorySort: SortMode = 'per-group',
-) {
- // For each category group, find the top N categories by total value and group the rest into "Other"
- const deletedNodes = new Map<NodeKey, { key: NodeKey; data: NodeData }[]>();
+): TooltipInfoMap {
+ const toolTipInfoMap: TooltipInfoMap = new Map();
+ const structuralKeys = new Set<string>(Object.values(SpecialNodeKeys));
- let categoryNodes = nodesInLayer(graph, GraphLayers.Category).filter(
- s => !s.endsWith(SpecialNodeKeys.OtherSuffix),
- );
- while (categoryNodes.length > topN) {
- const categoryNodeSet = new Set(categoryNodes);
- const values = new Map<NodeKey, number>();
- graph.forEach(data => {
- data.to.forEach((v, k) => {
- if (categoryNodeSet.has(k)) values.set(k, (values.get(k) ?? 0) + v);
- });
- });
- let categoryToDelete: NodeKey | undefined;
- let min = Infinity;
- for (const k of categoryNodes) {
- const val = values.get(k) ?? 0;
- if (val < min) {
- min = val;
- categoryToDelete = k;
+ function isGroupableNode(key: NodeKey): boolean {
+ const node = graph.get(key);
+ return Boolean(
+ node &&
+ !key.endsWith(SpecialNodeKeys.OtherSuffix) &&
+ !structuralKeys.has(key) &&
+ !node.isOverbudgeted,
+ );
+ }
+
+ Object.entries(GraphLayers).forEach(([_, layer]) => {
+ let ordinaryNodes = nodesInLayer(graph, layer).filter(isGroupableNode);
+ let otherNodes = nodesInLayer(graph, layer).filter(s =>
+ s.endsWith(SpecialNodeKeys.OtherSuffix),
+ );
+
+ while (ordinaryNodes.length + otherNodes.length > topN) {
+ let minValue = Infinity;
+ let nodeToDelete: NodeKey | undefined;
+ for (const nodeKey of ordinaryNodes) {
+ const nodeValue = getNodeValue(graph, nodeKey);
+ if (nodeValue < minValue) {
+ minValue = nodeValue;
+ nodeToDelete = nodeKey;
+ }
}
- }
- if (categoryToDelete === undefined) break; // safety
+ if (nodeToDelete === undefined) break; // safety
- const categoryGroupResult = getCategoryGroup(graph, categoryToDelete);
- if (!categoryGroupResult) {
- console.error(
- `Failed to find category group for category: ${categoryToDelete}`,
+ moveToOther(
+ graph,
+ nodeToDelete,
+ toolTipInfoMap,
+ categorySort === 'global',
);
- continue;
- }
- const deletedCategoryGroupKey = categoryGroupResult[0];
- const nodeData = graph.get(categoryToDelete);
- if (!nodeData) {
- console.error(
- `Failed to find node data for category: ${categoryToDelete}`,
+ ordinaryNodes = nodesInLayer(graph, layer).filter(isGroupableNode);
+ otherNodes = nodesInLayer(graph, layer).filter(s =>
+ s.endsWith(SpecialNodeKeys.OtherSuffix),
);
- continue;
- }
-
- const deletedCategoryGroup = deletedNodes.get(deletedCategoryGroupKey);
- if (!deletedCategoryGroup) {
- deletedNodes.set(deletedCategoryGroupKey, [
- { key: categoryToDelete, data: nodeData },
- ]);
- } else {
- deletedCategoryGroup.push({ key: categoryToDelete, data: nodeData });
}
+ });
- moveToOther(graph, categoryToDelete, categorySort === 'global');
- graph.delete(categoryToDelete);
-
- categoryNodes = nodesInLayer(graph, GraphLayers.Category).filter(
- s => !s.endsWith(SpecialNodeKeys.OtherSuffix),
- );
- }
-
- promoteOtherBack(graph, deletedNodes, categorySort === 'global');
+ return toolTipInfoMap;
}
-function nodesInLayer(graph: Graph, layer: GraphLayers): NodeKey[] {
+export function nodesInLayer(graph: Graph, layer: GraphLayers): NodeKey[] {
return Array.from(graph)
.filter(([, data]) => data.type === layer)
.map(([key]) => key);
}
-function moveToOther(graph: Graph, key: NodeKey, globalOther: boolean = false) {
- const categoryGroup = getCategoryGroup(graph, key);
- if (!categoryGroup) {
- console.error(`moveToOther: Failed to find category group for key: ${key}`);
+function moveToOther(
+ graph: Graph,
+ key: NodeKey,
+ toolTipInfoMap: TooltipInfoMap,
+ globalOther: boolean = false,
+) {
+ const nodeData = graph.get(key);
+ if (!nodeData) {
return;
}
- const categoryGroupKey = categoryGroup[0];
- const categoryGroupData = categoryGroup[1];
- const categoryValue = categoryGroupData.to.get(key);
+ // Get nodes connected to this node
+ const toNodes = Array.from(graph.get(key)?.to.keys() ?? []);
+ const fromNodes = Array.from(graph).filter(([, data]) => data.to.has(key));
- if (categoryValue === undefined) {
- console.error(
- `moveToOther: No link value found from group ${categoryGroupKey} to ${key}`,
- );
- return;
- }
-
- let otherGroupKey: NodeKey;
+ let otherKey: NodeKey;
if (globalOther) {
- otherGroupKey = SpecialNodeKeys.GlobalOther;
+ otherKey = nodeData.type + SpecialNodeKeys.OtherSuffix;
} else {
- otherGroupKey = categoryGroupKey + SpecialNodeKeys.OtherSuffix;
+ otherKey = nodeData.type + SpecialNodeKeys.OtherSuffix;
+
+ if (nodeData.type === GraphLayers.Category) {
+ const categoryGroupResult = getCategoryGroup(graph, key);
+ if (categoryGroupResult) {
+ const categoryGroupKey = categoryGroupResult[0];
+ otherKey = categoryGroupKey + SpecialNodeKeys.OtherSuffix;
+ }
+ } else if (nodeData.type === GraphLayers.IncomePayee) {
+ const incomeCategoryKey = Array.from(
+ graph.get(key)?.to.keys() ?? [],
+ ).find(k => graph.get(k)?.type === GraphLayers.IncomeCategory);
+ if (incomeCategoryKey) {
+ otherKey = incomeCategoryKey + SpecialNodeKeys.OtherSuffix;
+ }
+ }
}
- addNodeWithLabel(graph, otherGroupKey, GraphLayers.Category, 'Other');
- addValueToLink(graph, categoryGroupKey, otherGroupKey, categoryValue);
- addTooltipInfo(graph, categoryGroupKey, key, categoryValue);
- deleteLink(graph, categoryGroupKey, key);
+ // Make sure the Other node exists
+ addNode(graph, otherKey, nodeData.type, 'Other');
+
+ fromNodes.forEach(([fromKey, fromData]) => {
+ const linkValue = fromData.to.get(key);
+ if (linkValue !== undefined) {
+ addValueToLink(graph, fromKey, otherKey, linkValue);
+ newAddTooltipInfo(
+ toolTipInfoMap,
+ fromKey,
+ otherKey,
+ graph.get(key)?.name ?? key,
+ linkValue,
+ );
+ }
+ });
+ toNodes.forEach(toKey => {
+ const fromData = graph.get(key);
+ const linkValue = fromData?.to.get(toKey);
+ if (linkValue !== undefined) {
+ addValueToLink(graph, otherKey, toKey, linkValue);
+ newAddTooltipInfo(
+ toolTipInfoMap,
+ otherKey,
+ toKey,
+ graph.get(key)?.name ?? key,
+ linkValue,
+ );
+ }
+ });
+
+ toNodes.forEach(toKey => {
+ deleteLink(graph, key, toKey);
+ });
+ fromNodes.forEach(([fromKey]) => {
+ deleteLink(graph, fromKey, key);
+ });
+
+ graph.delete(key);
}
-function addTooltipInfo(
- graph: Graph,
+function newAddTooltipInfo(
+ toolTipInfoMap: TooltipInfoMap,
from: NodeKey,
to: NodeKey,
+ name: string,
value: number,
) {
- const fromNode = graph.get(from);
- if (!fromNode) return;
- fromNode.tooltipInfo = fromNode.tooltipInfo ?? [];
- fromNode.tooltipInfo.push({ name: graph.get(to)?.name ?? to, value });
+ if (!toolTipInfoMap.has(from)) {
+ toolTipInfoMap.set(from, new Map());
+ }
+ const innerMap = toolTipInfoMap.get(from)!;
+ const existingInfo = innerMap.get(to) ?? [];
+ if (!existingInfo.find(info => info.name === name)) {
+ innerMap.set(to, [...existingInfo, { name, value }]);
+ }
}
-function getCategoryGroup(graph: Graph, key: NodeKey) {
+export function getCategoryGroup(graph: Graph, key: NodeKey) {
return Array.from(graph).filter(
([, data]) => data.to.has(key) && data.type === GraphLayers.CategoryGroup,
)[0];
}
-function deleteLink(graph: Graph, from: NodeKey, to: NodeKey) {
+export function deleteLink(graph: Graph, from: NodeKey, to: NodeKey) {
const fromNode = graph.get(from);
if (fromNode) {
fromNode.to.delete(to);
}
}
-function promoteOtherBack(
- graph: Graph,
- deletedNodes: Map<string, { key: string; data: NodeData }[]>,
- globalOther: boolean = false,
-) {
- // If an Other node only contains one category, we revert it to an ordinary node
- let otherGroupKey: NodeKey;
- deletedNodes.forEach((data, key) => {
- if (data.length === 1) {
- if (globalOther) {
- otherGroupKey = SpecialNodeKeys.GlobalOther;
- } else {
- otherGroupKey = key ? key + SpecialNodeKeys.OtherSuffix : 'other';
- }
- addNode(graph, data[0].key, GraphLayers.Category, data[0].data.name);
- const fromNode = graph.get(key);
- const linkValue = fromNode?.to.get(otherGroupKey);
- if (linkValue !== undefined) {
- addValueToLink(graph, key, data[0].key, linkValue);
- }
- deleteLink(graph, key, otherGroupKey);
- }
- });
-}
-
-function sortGraph(
+export function sortGraph(
graph: Graph,
categorySort: SortMode = 'per-group',
categories: CategoryGroupEntity[],
): Graph {
- let sortedEntries: Array<[string, NodeData]>;
- if (categorySort === 'global') {
- sortedEntries = Array.from(graph.entries()).sort(
- ([keyA], [keyB]) => getNodeValue(graph, keyB) - getNodeValue(graph, keyA),
- );
- moveNodeToEnd(sortedEntries, SpecialNodeKeys.GlobalOther);
- } else if (categorySort === 'per-group') {
- const categoryGroups = nodesInLayer(graph, GraphLayers.CategoryGroup);
- sortedEntries = Array.from(graph.entries()).sort(
- ([keyA], [keyB]) => getNodeValue(graph, keyB) - getNodeValue(graph, keyA),
- );
-
- categoryGroups.forEach(groupKey => {
- const group = graph.get(groupKey);
- if (!group) return;
- const groupToKeys = Array.from(group.to.keys());
+ function sortRelatedNodesAroundAnchors(
+ entries: Array<[string, NodeData]>,
+ anchorLayer: GraphLayers,
+ relatedLayer: GraphLayers,
+ placement: 'before' | 'after',
+ ) {
+ const anchorKeys = nodesInLayer(graph, anchorLayer);
+
+ anchorKeys.forEach(anchorKey => {
+ const anchor = graph.get(anchorKey);
+ if (!anchor) return;
+
+ const relatedKeys =
+ placement === 'after'
+ ? Array.from(anchor.to.keys()).filter(
+ key => graph.get(key)?.type === relatedLayer,
+ )
+ : Array.from(graph)
+ .filter(
+ ([, data]) =>
+ data.type === relatedLayer && data.to.has(anchorKey),
+ )
+ .map(([key]) => key);
- const groupOtherKey = groupToKeys.find(k =>
- k.endsWith(SpecialNodeKeys.OtherSuffix),
- );
- const childKeys = groupToKeys.filter(k => k !== groupOtherKey);
+ const otherKey = `${anchorKey}${SpecialNodeKeys.OtherSuffix}`;
+ const relatedOtherKey =
+ graph.get(otherKey)?.type === relatedLayer ? otherKey : undefined;
+ const orderedRelatedKeys = relatedKeys.filter(key => key !== otherKey);
- const childEntries = childKeys
- .map(key => sortedEntries.find(([entryKey]) => entryKey === key))
+ const relatedEntries = orderedRelatedKeys
+ .map(key => entries.find(([entryKey]) => entryKey === key))
.filter((entry): entry is [string, NodeData] => entry !== undefined);
- childEntries.sort(
- ([a], [b]) => getNodeValue(graph, b) - getNodeValue(graph, a),
+ relatedEntries.sort(
+ ([keyA], [keyB]) =>
+ getNodeValue(graph, keyB) - getNodeValue(graph, keyA),
);
- const otherEntry = groupOtherKey
- ? sortedEntries.find(([entryKey]) => entryKey === groupOtherKey)
+ const otherEntry = relatedOtherKey
+ ? entries.find(([entryKey]) => entryKey === relatedOtherKey)
: undefined;
- // Remove these children ("Other" too) from their current places
- sortedEntries = sortedEntries.filter(
- ([entryKey]) =>
- !childKeys.includes(entryKey) && entryKey !== groupOtherKey,
+ const relatedKeysToMove = new Set(orderedRelatedKeys);
+ if (relatedOtherKey) {
+ relatedKeysToMove.add(relatedOtherKey);
+ }
+ const entriesWithoutRelated = entries.filter(
+ ([entryKey]) => !relatedKeysToMove.has(entryKey),
);
-
- // Insert after group node
- const groupIndex = sortedEntries.findIndex(
- ([entryKey]) => entryKey === groupKey,
+ const anchorIndex = entriesWithoutRelated.findIndex(
+ ([entryKey]) => entryKey === anchorKey,
);
- if (groupIndex !== -1) {
- sortedEntries.splice(groupIndex + 1, 0, ...childEntries);
- if (otherEntry) {
- sortedEntries.splice(
- groupIndex + 1 + childEntries.length,
- 0,
- otherEntry,
- );
- }
+ if (anchorIndex === -1) {
+ return;
+ }
+
+ const insertionIndex =
+ placement === 'before' ? anchorIndex : anchorIndex + 1;
+ const nodesToInsert = otherEntry
+ ? [...relatedEntries, otherEntry]
+ : relatedEntries;
+
+ entriesWithoutRelated.splice(insertionIndex, 0, ...nodesToInsert);
+ entries.length = 0;
+ entries.push(...entriesWithoutRelated);
+ });
+ }
+
+ let sortedEntries: Array<[string, NodeData]>;
+ if (categorySort === 'global') {
+ sortedEntries = Array.from(graph.entries()).sort(
+ ([keyA], [keyB]) => getNodeValue(graph, keyB) - getNodeValue(graph, keyA),
+ );
+ sortedEntries.forEach(([key]) => {
+ if (key.endsWith(SpecialNodeKeys.OtherSuffix)) {
+ moveNodeToEnd(sortedEntries, key);
}
});
+ } else if (categorySort === 'per-group') {
+ sortedEntries = Array.from(graph.entries()).sort(
+ ([keyA], [keyB]) => getNodeValue(graph, keyB) - getNodeValue(graph, keyA),
+ );
+
+ sortRelatedNodesAroundAnchors(
+ sortedEntries,
+ GraphLayers.CategoryGroup,
+ GraphLayers.Category,
+ 'after',
+ );
+ sortRelatedNodesAroundAnchors(
+ sortedEntries,
+ GraphLayers.IncomeCategory,
+ GraphLayers.IncomePayee,
+ 'before',
+ );
} else {
const used = new Set<NodeKey>();
sortedEntries = [];
@@ -1074,15 +1152,30 @@ function sortGraph(
}
}
- // We always want these nodes displayed at the bottom of their layers, so its safe to just move them to the end
- moveNodeToEnd(sortedEntries, SpecialNodeKeys.ToBudget);
+ // We always want certain nodes to be shown at the start/end of their layers
+ sortedEntries
+ .filter(([, nodeData]) => nodeData.isOverbudgeted)
+ .forEach(([key]) => {
+ moveNodeToStart(sortedEntries, key);
+ });
+ const toBudgetNode = graph.get(SpecialNodeKeys.ToBudget);
+ if (toBudgetNode) {
+ if (toBudgetNode.isOverbudgeted) {
+ moveNodeToStart(sortedEntries, SpecialNodeKeys.ToBudget);
+ } else {
+ moveNodeToEnd(sortedEntries, SpecialNodeKeys.ToBudget);
+ }
+ }
moveNodeToEnd(sortedEntries, SpecialNodeKeys.LastMonthOverspent);
moveNodeToEnd(sortedEntries, SpecialNodeKeys.ForNextMonth);
moveNodeToEnd(sortedEntries, SpecialNodeKeys.FromPrevMonth);
return new Map(sortedEntries);
}
-function moveNodeToEnd(entries: Array<[string, NodeData]>, key: NodeKey) {
+export function moveNodeToEnd(
+ entries: Array<[string, NodeData]>,
+ key: NodeKey,
+) {
const nodeIndex = entries.findIndex(([nodekey]) => nodekey === key);
if (nodeIndex !== -1) {
const [entry] = entries.splice(nodeIndex, 1);
@@ -1090,7 +1183,18 @@ function moveNodeToEnd(entries: Array<[string, NodeData]>, key: NodeKey) {
}
}
-function getNodeValue(graph: Graph, key: NodeKey): number {
+export function moveNodeToStart(
+ entries: Array<[string, NodeData]>,
+ key: NodeKey,
+) {
+ const nodeIndex = entries.findIndex(([nodekey]) => nodekey === key);
+ if (nodeIndex !== -1) {
+ const [entry] = entries.splice(nodeIndex, 1);
+ entries.unshift(entry);
+ }
+}
+
+export function getNodeValue(graph: Graph, key: NodeKey): number {
let nodeValue: number = 0;
if (getLayer(graph, key) === 0) {
@@ -1120,7 +1224,7 @@ function getNodeValue(graph: Graph, key: NodeKey): number {
return nodeValue;
}
-function addPercentageLabels(graph: Graph): void {
+export function addPercentageLabels(graph: Graph): void {
const layerSums = new Map<number, number>();
// First pass: Calculate layer sums
@@ -1142,24 +1246,33 @@ function addPercentageLabels(graph: Graph): void {
function addColors(graph: Graph) {
const colors = getColorScale('qualitative');
- const keys = [...graph.keys()].sort();
- keys.forEach((key, i) => {
+ for (const key of graph.keys()) {
const node = graph.get(key);
- if (node) node.color = colors[i % colors.length];
- });
-
- const node = graph.get(SpecialNodeKeys.ToBudget);
- if (node && node.isOverbudgeted) {
- setColor(graph, SpecialNodeKeys.ToBudget, theme.toBudgetNegative);
- } else {
- setColor(graph, SpecialNodeKeys.ToBudget, theme.toBudgetPositive);
+ if (node) {
+ node.color = colors[colorIndexFromKey(key, colors.length)];
+ }
}
+
+ setColor(graph, SpecialNodeKeys.ToBudget, theme.toBudgetPositive);
+ graph.forEach((node, key) => {
+ if (node.isOverbudgeted) {
+ setColor(graph, key, theme.toBudgetNegative);
+ }
+ });
setColor(graph, SpecialNodeKeys.LastMonthOverspent, theme.toBudgetNegative);
setColor(graph, SpecialNodeKeys.FromPrevMonth, theme.reportsGray);
setColor(graph, SpecialNodeKeys.ForNextMonth, theme.reportsGray);
setColor(graph, SpecialNodeKeys.Budgeted, theme.reportsBlue);
setColor(graph, SpecialNodeKeys.AvailableIncome, theme.reportsBlue);
+ setColor(graph, SpecialNodeKeys.AllAccounts, theme.reportsBlue);
+}
+
+function colorIndexFromKey(key: string, colorCount: number): number {
+ // Use the first three chars of the key (UUID) as a stable random value
+ const hex = key.replace(/[^0-9a-f]/gi, '').slice(0, 3);
+ const val = parseInt(hex || '0', 16);
+ return val % colorCount;
}
function setColor(graph: Graph, key: NodeKey, color: string) {
@@ -1169,7 +1282,143 @@ function setColor(graph: Graph, key: NodeKey, color: string) {
}
}
-function filterGraphByLayers(
+function addHiddenNodes(graph: Graph) {
+ // Nodes with parents/children different than other nodes in the same layer might end up
+ // in the wrong place in the graph. This fixes that, by adding extra, hidden nodes.
+
+ // Group nodes by type
+ const nodesByType: Partial<Record<GraphLayers, Array<[NodeKey, NodeData]>>> =
+ {};
+
+ for (const [key, node] of graph) {
+ if (!nodesByType[node.type]) nodesByType[node.type] = [];
+ nodesByType[node.type]!.push([key, node]);
+ }
+
+ const { typeHasParent, typeHasChild } = buildTypeConnectivity(
+ graph,
+ nodesByType,
+ );
+
+ // Now: find and fix "problematic" nodes
+ for (const typeStr in nodesByType) {
+ if (!isGraphLayer(typeStr)) continue;
+ const type = typeStr;
+ const nodes = nodesByType[type];
+ if (!nodes) continue;
+ for (const [key, node] of nodes) {
+ const nodeHasParent = hasParent(graph, key);
+ const nodeHasChild = hasChild(node);
+ if (!nodeHasParent && typeHasParent[type]) {
+ // This node is at a wrong layer and need hidden parents
+ if (type === GraphLayers.IncomeCategory) {
+ addNode(
+ graph,
+ key + '_payee' + SpecialNodeKeys.HiddenSuffix,
+ GraphLayers.IncomePayee,
+ '',
+ );
+ addValueToLink(
+ graph,
+ key + '_payee' + SpecialNodeKeys.HiddenSuffix,
+ key,
+ -1,
+ );
+ } else {
+ addNode(
+ graph,
+ key + '_account' + SpecialNodeKeys.HiddenSuffix,
+ GraphLayers.Account,
+ '',
+ );
+ addValueToLink(
+ graph,
+ key + '_account' + SpecialNodeKeys.HiddenSuffix,
+ key,
+ -1,
+ );
+ addNode(
+ graph,
+ key + '_payee' + SpecialNodeKeys.HiddenSuffix,
+ GraphLayers.IncomePayee,
+ '',
+ );
+ addValueToLink(
+ graph,
+ key + '_payee' + SpecialNodeKeys.HiddenSuffix,
+ key + '_account' + SpecialNodeKeys.HiddenSuffix,
+ -1,
+ );
+ }
+ }
+ if (!nodeHasChild && typeHasChild[type]) {
+ // This node is at a wrong layer and need hidden children
+ addNode(
+ graph,
+ key + '_category_group' + SpecialNodeKeys.HiddenSuffix,
+ GraphLayers.CategoryGroup,
+ '',
+ );
+ addNode(
+ graph,
+ key + '_category' + SpecialNodeKeys.HiddenSuffix,
+ GraphLayers.Category,
+ '',
+ );
+ addValueToLink(
+ graph,
+ key,
+ key + '_category_group' + SpecialNodeKeys.HiddenSuffix,
+ -1,
+ );
+ addValueToLink(
+ graph,
+ key + '_category_group' + SpecialNodeKeys.HiddenSuffix,
+ key + '_category' + SpecialNodeKeys.HiddenSuffix,
+ -1,
+ );
+ }
+ }
+ }
+}
+
+function buildTypeConnectivity(
+ graph: Map<NodeKey, NodeData>,
+ nodesByType: Partial<Record<GraphLayers, Array<[NodeKey, NodeData]>>>,
+) {
+ const typeHasParent = {} as Record<GraphLayers, boolean>;
+ const typeHasChild = {} as Record<GraphLayers, boolean>;
+
+ for (const typeStr in nodesByType) {
+ if (!isGraphLayer(typeStr)) continue;
+ const type = typeStr;
+ const nodes = nodesByType[type];
+ if (!nodes) continue;
+ typeHasParent[type] = false;
+ typeHasChild[type] = false;
+ for (const [key, node] of nodes) {
+ if (hasParent(graph, key)) typeHasParent[type] = true;
+ if (hasChild(node)) typeHasChild[type] = true;
+ }
+ }
+ return { typeHasParent, typeHasChild };
+}
+
+export function hasParent(
+ graph: Map<NodeKey, NodeData>,
+ key: NodeKey,
+): boolean {
+ for (const [_, data] of graph) {
+ if (data.to.has(key)) return true;
+ }
+ return false;
+}
+
+export function hasChild(node: NodeData): boolean {
+ return node.to.size > 0;
+}
+
+export function filterGraphByLayers(
graph: Graph,
layerFrom: GraphLayers,
layerTo: GraphLayers,
@@ -1182,7 +1431,7 @@ function filterGraphByLayers(
const fromIndex = layerIndices.get(layerFrom);
const toIndex = layerIndices.get(layerTo);
- if (fromIndex && toIndex) {
+ if (fromIndex !== undefined && toIndex !== undefined) {
const keysToDelete: NodeKey[] = [];
graph.forEach((data, key) => {
const nodeLayerIndex = layerIndices.get(data.type);
@@ -1197,8 +1446,8 @@ function filterGraphByLayers(
}
}
-function cleanUpNodes(graph: Graph) {
- // 1. Remove all `.to` links with value === 0
+export function cleanUpNodes(graph: Graph) {
+ // 1. Remove all `.to` links with value ===0
for (const [, node] of graph) {
for (const [target, value] of node.to) {
if (value === 0) {
@@ -1231,7 +1480,10 @@ function cleanUpNodes(graph: Graph) {
}
}
-function convertToSankeyData(graph: Graph): SankeyData {
+export function convertToSankeyData(
+ graph: Graph,
+ toolTipInfoMap: TooltipInfoMap,
+): SankeyData {
const nodes = Array.from(graph, ([key, data]) => ({
key,
name: data.labelKey
@@ -1242,11 +1494,9 @@ function convertToSankeyData(graph: Graph): SankeyData {
}));
const links = Array.from(graph).flatMap(([key, data]) =>
Array.from(data.to, ([targetKey, value]) => {
- let tooltipInfo: Array<{ name: string; value: number }> = [];
- if (data.tooltipInfo && targetKey.endsWith(SpecialNodeKeys.OtherSuffix)) {
- tooltipInfo = data.tooltipInfo;
- tooltipInfo.sort((a, b) => b.value - a.value);
- }
+ const tooltipInfo = toolTipInfoMap.get(key)?.get(targetKey) ?? [];
+
+ tooltipInfo.sort((a, b) => b.value - a.value);
let color: string | undefined;
const sourceLayersWithOwnColor: readonly GraphLayers[] = [
@@ -1283,10 +1533,7 @@ function convertToSankeyData(graph: Graph): SankeyData {
if (targetKey === SpecialNodeKeys.ForNextMonth) {
color = graph.get(SpecialNodeKeys.ForNextMonth)?.color;
}
- if (
- targetKey === SpecialNodeKeys.AvailableIncome &&
- data.isOverbudgeted
- ) {
+ if (data.isOverbudgeted) {
color = data.color;
}
diff --git a/packages/loot-core/src/types/models/dashboard.ts b/packages/loot-core/src/types/models/dashboard.ts
index 412011ca83..303c53679c 100644
--- a/packages/loot-core/src/types/models/dashboard.ts
+++ b/packages/loot-core/src/types/models/dashboard.ts
@@ -224,6 +224,7 @@ export type SankeyWidget = AbstractWidget<
topNcategories?: number;
categorySort?: 'per-group' | 'global' | 'budget-order';
showPercentages?: boolean;
+ groupAccounts?: boolean;
layerFrom?: string;
layerTo?: string;
} | null
diff --git a/upcoming-release-notes/7682.md b/upcoming-release-notes/7682.md
new file mode 100644
index 0000000000..0dc938cd04
--- /dev/null
+++ b/upcoming-release-notes/7682.md
@@ -0,0 +1,6 @@
+---
+category: Enhancements
+authors: [emiltb]
+---
+
+Improved Sankey chart handling of large datasets, better color mapping and many bug fixes.