Skip to content

A local-first personal finance app

Implement Sankey report for spent and budgeted money (#7220)

Emil Tveden Bjerglund10b7385ad45d
diff --git a/packages/desktop-client/src/components/reports/Overview.tsx b/packages/desktop-client/src/components/reports/Overview.tsx
index b0ed72554e..75e80bad20 100644
--- a/packages/desktop-client/src/components/reports/Overview.tsx
+++ b/packages/desktop-client/src/components/reports/Overview.tsx
@@ -34,6 +34,7 @@ import { CustomReportListCards } from './reports/CustomReportListCards';
import { FormulaCard } from './reports/FormulaCard';
import { MarkdownCard } from './reports/MarkdownCard';
import { NetWorthCard } from './reports/NetWorthCard';
+import { SankeyCard } from './reports/SankeyCard';
import { SpendingCard } from './reports/SpendingCard';
import './overview.scss';
import { SummaryCard } from './reports/SummaryCard';
@@ -97,6 +98,8 @@ export function Overview({ dashboard }: OverviewProps) {
const { data: customReports = [], isPending: isCustomReportsLoading } =
useReports();
+ const sankeyFeatureFlag = useFeatureFlag('sankeyReport');
+
const customReportMap = useMemo(
() => new Map(customReports.map(report => [report.id, report])),
[customReports],
@@ -608,6 +611,14 @@ export function Overview({ dashboard }: OverviewProps) {
},
]
: []),
+ ...(sankeyFeatureFlag
+ ? [
+ {
+ name: 'sankey-card' as const,
+ text: t('Sankey card'),
+ },
+ ]
+ : []),
{
name: 'custom-report' as const,
text: t('New custom report'),
@@ -861,6 +872,17 @@ export function Overview({ dashboard }: OverviewProps) {
onCopyWidget(item.i, targetDashboardId)
}
/>
+ ) : widget.type === 'sankey-card' && sankeyFeatureFlag ? (
+ <SankeyCard
+ widgetId={item.i}
+ isEditing={isEditing}
+ meta={widget.meta}
+ onMetaChange={newMeta => onMetaChange(item, newMeta)}
+ onRemove={() => onRemoveWidget(item.i)}
+ onCopy={targetDashboardId =>
+ onCopyWidget(item.i, targetDashboardId)
+ }
+ />
) : null}
</div>
);
diff --git a/packages/desktop-client/src/components/reports/ReportRouter.tsx b/packages/desktop-client/src/components/reports/ReportRouter.tsx
index 4942737adb..90241b7a39 100644
--- a/packages/desktop-client/src/components/reports/ReportRouter.tsx
+++ b/packages/desktop-client/src/components/reports/ReportRouter.tsx
@@ -8,6 +8,7 @@ import { Crossover } from './reports/Crossover';
import { CustomReport } from './reports/CustomReport';
import { Formula } from './reports/Formula';
import { NetWorth } from './reports/NetWorth';
+import { Sankey } from './reports/Sankey';
import { Spending } from './reports/Spending';
import { Summary } from './reports/Summary';
import { ReportsDashboardRouter } from './ReportsDashboardRouter';
@@ -17,6 +18,7 @@ import { useFeatureFlag } from '@desktop-client/hooks/useFeatureFlag';
export function ReportRouter() {
const crossoverReportEnabled = useFeatureFlag('crossoverReport');
const budgetAnalysisReportEnabled = useFeatureFlag('budgetAnalysisReport');
+ const sankeyReportEnabled = useFeatureFlag('sankeyReport');
return (
<Routes>
@@ -48,6 +50,12 @@ export function ReportRouter() {
<Route path="/calendar/:id" element={<Calendar />} />
<Route path="/formula" element={<Formula />} />
<Route path="/formula/:id" element={<Formula />} />
+ {sankeyReportEnabled && (
+ <>
+ <Route path="/sankey" element={<Sankey />} />
+ <Route path="/sankey/:id" element={<Sankey />} />
+ </>
+ )}
</Routes>
);
}
diff --git a/packages/desktop-client/src/components/reports/graphs/SankeyGraph.tsx b/packages/desktop-client/src/components/reports/graphs/SankeyGraph.tsx
new file mode 100644
index 0000000000..163034241e
--- /dev/null
+++ b/packages/desktop-client/src/components/reports/graphs/SankeyGraph.tsx
@@ -0,0 +1,330 @@
+import { useState } from 'react';
+import type { CSSProperties } from 'react';
+
+import { theme } from '@actual-app/components/theme';
+import { css } from '@emotion/css';
+import { t } from 'i18next';
+import {
+ Layer,
+ Rectangle,
+ ResponsiveContainer,
+ Sankey,
+ Tooltip,
+} from 'recharts';
+import type { SankeyData } from 'recharts/types/chart/Sankey';
+
+import { getColorScale } from '@desktop-client/components/reports/chart-theme';
+import { Container } from '@desktop-client/components/reports/Container';
+import { useFormat } from '@desktop-client/hooks/useFormat';
+import { usePrivacyMode } from '@desktop-client/hooks/usePrivacyMode';
+
+type SankeyGraphNode = SankeyData['nodes'][number] & {
+ hasChildren?: boolean;
+ isCollapsed?: boolean;
+ toBudget?: number;
+ isNegative?: boolean;
+ actualValue?: number;
+ targetLinks?: Array<Record<string, unknown>>;
+ sourceLinks?: Array<Record<string, unknown>>;
+};
+
+type SankeyLinkProps = {
+ sourceX: number;
+ sourceY: number;
+ sourceControlX: number;
+ targetX: number;
+ targetY: number;
+ targetControlX: number;
+ linkWidth: number;
+ index: number;
+ payload: {
+ source: SankeyGraphNode;
+ target: SankeyGraphNode;
+ value: number;
+ isNegative?: boolean;
+ };
+ isHovered: boolean;
+ onMouseEnter: () => void;
+ onMouseLeave: () => void;
+ color: string;
+};
+
+function SankeyLink({
+ sourceX,
+ sourceY,
+ sourceControlX,
+ targetX,
+ targetY,
+ targetControlX,
+ linkWidth,
+ payload,
+ isHovered,
+ onMouseEnter,
+ onMouseLeave,
+ color,
+}: SankeyLinkProps) {
+ const linkColor = payload.isNegative ? theme.errorText : color;
+ const strokeWidth = linkWidth;
+ const strokeOpacity = isHovered ? 1 : 0.6;
+
+ return (
+ <path
+ d={`M${sourceX},${sourceY} C${sourceControlX},${sourceY} ${targetControlX},${targetY} ${targetX},${targetY}`}
+ fill="none"
+ stroke={linkColor}
+ strokeWidth={strokeWidth}
+ strokeOpacity={strokeOpacity}
+ cursor="default"
+ onMouseEnter={onMouseEnter}
+ onMouseLeave={onMouseLeave}
+ style={{ transition: 'stroke-opacity 0.2s ease' }}
+ />
+ );
+}
+
+type SankeyNodeProps = {
+ x: number;
+ y: number;
+ width: number;
+ height: number;
+ index: number;
+ payload: SankeyGraphNode;
+ containerWidth: number;
+ containerHeight: number;
+};
+function SankeyNode({
+ x,
+ y,
+ width,
+ height,
+ index,
+ payload,
+ containerWidth,
+ containerHeight,
+}: SankeyNodeProps) {
+ const privacyMode = usePrivacyMode();
+ const format = useFormat();
+ const isOut = x + width + 6 > containerWidth;
+
+ const fillColor = payload.isNegative ? theme.errorText : theme.reportsBlue;
+
+ const toBudget = payload.toBudget ?? 0;
+ const availableBelow = Math.max(0, containerHeight - 25 - (y + height));
+ const proportionalHeight =
+ toBudget > 0 && payload.value ? height * (toBudget / payload.value) : 0;
+ const isClamped = proportionalHeight > availableBelow;
+ const toBudgetHeight = Math.min(proportionalHeight, availableBelow);
+
+ const renderText = (
+ text: string,
+ yOffset: number,
+ fontSize = 13,
+ opacity = 1,
+ fontFamily?: string,
+ yBase = y,
+ ) => (
+ <text
+ textAnchor={isOut ? 'end' : 'start'}
+ x={isOut ? x - 6 : x + width + 6}
+ y={yBase + yOffset}
+ fontSize={fontSize}
+ strokeOpacity={opacity}
+ fill={theme.pageText}
+ fontFamily={fontFamily}
+ >
+ {text}
+ </text>
+ );
+
+ return (
+ <Layer>
+ <Rectangle x={x} y={y} width={width} height={height} fill={fillColor} />
+ {toBudgetHeight > 0 &&
+ (isClamped ? (
+ <polygon
+ points={`
+ ${x},${y + height}
+ ${x + width},${y + height}
+ ${x + width},${y + height + toBudgetHeight - 8}
+ ${x + width / 2},${y + height + toBudgetHeight}
+ ${x},${y + height + toBudgetHeight - 8}
+ `}
+ fill={theme.toBudgetPositive}
+ />
+ ) : (
+ <Rectangle
+ x={x}
+ y={y + height}
+ width={width}
+ height={toBudgetHeight}
+ fill={theme.toBudgetPositive}
+ />
+ ))}
+ {renderText(payload.name || '', height / 2)}
+ {renderText(
+ format(payload.value, 'financial'),
+ height / 2 + 13,
+ 11,
+ 0.5,
+ privacyMode ? t('Redacted Script') : undefined,
+ )}
+ {toBudgetHeight > 0 &&
+ renderText(
+ format(toBudget, 'financial'),
+ toBudgetHeight / 2 + 13,
+ 11,
+ 0.5,
+ privacyMode ? t('Redacted Script') : undefined,
+ y + height,
+ )}
+ {toBudgetHeight > 0 &&
+ renderText(
+ t('To budget'),
+ toBudgetHeight / 2,
+ 13,
+ 1,
+ undefined,
+ y + height,
+ )}
+ </Layer>
+ );
+}
+
+type SankeyGraphProps = {
+ style?: CSSProperties;
+ data: SankeyData;
+ showTooltip?: boolean;
+ collapsedNodes?: string[];
+};
+export function SankeyGraph({
+ style,
+ data,
+ showTooltip = true,
+}: SankeyGraphProps) {
+ const privacyMode = usePrivacyMode();
+ const format = useFormat();
+ const [hoveredLinkIndex, setHoveredLinkIndex] = useState<number | null>(null);
+
+ const colors = getColorScale('qualitative');
+ const sourceColorMap = new Map(
+ [
+ ...new Set(
+ data.links
+ .filter(l => (l.source as number) !== 0)
+ .map(l => data.nodes[l.source as number]?.name),
+ ),
+ ]
+ .filter(Boolean)
+ .map((name, i) => [name, colors[i % colors.length]]),
+ );
+
+ return (
+ <Container style={style}>
+ {(width, height) => (
+ <ResponsiveContainer>
+ <Sankey
+ data={data}
+ node={props => (
+ <SankeyNode
+ {...props}
+ containerWidth={width}
+ containerHeight={height}
+ />
+ )}
+ link={props => (
+ <SankeyLink
+ {...props}
+ isHovered={hoveredLinkIndex === props.index}
+ onMouseEnter={() => setHoveredLinkIndex(props.index)}
+ onMouseLeave={() => setHoveredLinkIndex(null)}
+ color={
+ sourceColorMap.get(props.payload.source.name) ??
+ theme.reportsGray
+ }
+ />
+ )}
+ sort={false}
+ iterations={1000}
+ nodePadding={23}
+ width={width}
+ height={height}
+ margin={{
+ left: 0,
+ right: 0,
+ top: 10,
+ bottom: 25,
+ }}
+ >
+ {showTooltip && (
+ <Tooltip
+ content={({ active, payload }) => {
+ if (!active || !payload?.length) return null;
+ const { value = 0, name = '' } = payload[0];
+ const tooltipInfo =
+ hoveredLinkIndex !== null
+ ? (
+ data.links[hoveredLinkIndex] as {
+ tooltipInfo?: Array<{
+ name: string;
+ value: number;
+ }>;
+ }
+ )?.tooltipInfo
+ : undefined;
+ return (
+ <div
+ className={css({
+ zIndex: 1000,
+ pointerEvents: 'none',
+ borderRadius: 2,
+ boxShadow: '0 1px 6px rgba(0, 0, 0, .20)',
+ backgroundColor: theme.menuBackground,
+ color: theme.menuItemText,
+ padding: 10,
+ })}
+ >
+ <div style={{ lineHeight: 1.4 }}>
+ {name && <div style={{ marginBottom: 5 }}>{name}</div>}
+ <div
+ style={{
+ fontFamily: privacyMode
+ ? t('Redacted Script')
+ : undefined,
+ }}
+ >
+ {format(value, 'financial')}
+ </div>
+ {tooltipInfo && tooltipInfo.length > 0 && (
+ <div
+ style={{ marginTop: 6, fontSize: 11, opacity: 0.7 }}
+ >
+ {tooltipInfo.map(item => (
+ <div key={item.name}>
+ {item.name} (
+ <span
+ style={{
+ fontFamily: privacyMode
+ ? t('Redacted Script')
+ : undefined,
+ }}
+ >
+ {format(item.value, 'financial')}
+ </span>
+ )
+ </div>
+ ))}
+ </div>
+ )}
+ </div>
+ </div>
+ );
+ }}
+ isAnimationActive={false}
+ />
+ )}
+ </Sankey>
+ </ResponsiveContainer>
+ )}
+ </Container>
+ );
+}
diff --git a/packages/desktop-client/src/components/reports/reports/Sankey.tsx b/packages/desktop-client/src/components/reports/reports/Sankey.tsx
new file mode 100644
index 0000000000..a4fd1465e9
--- /dev/null
+++ b/packages/desktop-client/src/components/reports/reports/Sankey.tsx
@@ -0,0 +1,615 @@
+import { useEffect, useMemo, useRef, useState } from 'react';
+import { Trans, useTranslation } from 'react-i18next';
+import { useParams } from 'react-router';
+
+import { Button } from '@actual-app/components/button';
+import { useResponsive } from '@actual-app/components/hooks/useResponsive';
+import { SvgArrowDown, SvgList } from '@actual-app/components/icons/v1';
+import { Menu } from '@actual-app/components/menu';
+import { Paragraph } from '@actual-app/components/paragraph';
+import { Popover } from '@actual-app/components/popover';
+import { Select } from '@actual-app/components/select';
+import { SpaceBetween } from '@actual-app/components/space-between';
+import { styles } from '@actual-app/components/styles';
+import { Text } from '@actual-app/components/text';
+import { theme } from '@actual-app/components/theme';
+import { Tooltip } from '@actual-app/components/tooltip';
+import { View } from '@actual-app/components/view';
+import * as d from 'date-fns';
+import type { SankeyData } from 'recharts/types/chart/Sankey';
+
+import { send } from 'loot-core/platform/client/connection';
+import * as monthUtils from 'loot-core/shared/months';
+import type {
+ RuleConditionEntity,
+ SankeyWidget,
+ TimeFrame,
+} from 'loot-core/types/models';
+
+import { EditablePageHeaderTitle } from '@desktop-client/components/EditablePageHeaderTitle';
+import { AppliedFilters } from '@desktop-client/components/filters/AppliedFilters';
+import { FilterButton } from '@desktop-client/components/filters/FiltersMenu';
+import { MobileBackButton } from '@desktop-client/components/mobile/MobileBackButton';
+import {
+ MobilePageHeader,
+ Page,
+ PageHeader,
+} from '@desktop-client/components/Page';
+import { SankeyGraph } from '@desktop-client/components/reports/graphs/SankeyGraph';
+import { Header } from '@desktop-client/components/reports/Header';
+import { LoadingIndicator } from '@desktop-client/components/reports/LoadingIndicator';
+import { ModeButton } from '@desktop-client/components/reports/ModeButton';
+import { calculateTimeRange } from '@desktop-client/components/reports/reportRanges';
+import { createSpreadsheet as sankeySpreadsheet } from '@desktop-client/components/reports/spreadsheets/sankey-spreadsheet';
+import { useReport } from '@desktop-client/components/reports/useReport';
+import { fromDateRepr } from '@desktop-client/components/reports/util';
+import { useCategories } from '@desktop-client/hooks/useCategories';
+import { useDashboardWidget } from '@desktop-client/hooks/useDashboardWidget';
+import { useLocale } from '@desktop-client/hooks/useLocale';
+import { useNavigate } from '@desktop-client/hooks/useNavigate';
+import { useRuleConditionFilters } from '@desktop-client/hooks/useRuleConditionFilters';
+import type { useSpreadsheet } from '@desktop-client/hooks/useSpreadsheet';
+import { addNotification } from '@desktop-client/notifications/notificationsSlice';
+import { useDispatch } from '@desktop-client/redux';
+import { useUpdateDashboardWidgetMutation } from '@desktop-client/reports/mutations';
+
+export function Sankey() {
+ const params = useParams();
+ const { data: widget, isLoading } = useDashboardWidget<SankeyWidget>({
+ id: params.id ?? '',
+ type: 'sankey-card',
+ });
+
+ if (isLoading) {
+ return <LoadingIndicator />;
+ }
+
+ return <SankeyInner widget={widget} />;
+}
+
+type GraphMode = 'budgeted' | 'spent';
+
+const TOP_N_OPTIONS = [10, 15, 20, 25, 30] as const;
+
+type TopNSelectorProps = {
+ value: number;
+ onChange: (value: number) => void;
+};
+
+function TopNSelector({ value, onChange }: TopNSelectorProps) {
+ const { t } = useTranslation();
+ const triggerRef = useRef<HTMLButtonElement | null>(null);
+ const [isOpen, setIsOpen] = useState(false);
+
+ return (
+ <>
+ <Button
+ ref={triggerRef}
+ variant="bare"
+ onPress={() => setIsOpen(true)}
+ aria-label={t('Change category limit')}
+ >
+ <SvgList style={{ width: 12, height: 12 }} />
+ <span style={{ marginLeft: 5 }}>{t('Show {{n}}', { n: value })}</span>
+ </Button>
+ <Popover
+ triggerRef={triggerRef}
+ placement="bottom start"
+ isOpen={isOpen}
+ onOpenChange={() => setIsOpen(false)}
+ >
+ <Menu
+ onMenuSelect={item => {
+ onChange(Number(item));
+ setIsOpen(false);
+ }}
+ items={TOP_N_OPTIONS.map(n => ({
+ name: String(n),
+ text: t('Show {{n}}', { n }),
+ }))}
+ />
+ </Popover>
+ </>
+ );
+}
+
+type CategorySortSelectorProps = {
+ value: 'per-group' | 'global' | 'budget-order';
+ onChange: (value: 'per-group' | 'global' | 'budget-order') => void;
+};
+
+function CategorySortSelector({ value, onChange }: CategorySortSelectorProps) {
+ const { t } = useTranslation();
+ const triggerRef = useRef<HTMLButtonElement | null>(null);
+ const [isOpen, setIsOpen] = useState(false);
+
+ const options: Array<{
+ key: 'per-group' | 'global' | 'budget-order';
+ label: string;
+ }> = [
+ { key: 'per-group', label: t('Sort per group') },
+ { key: 'global', label: t('Sort all') },
+ { key: 'budget-order', label: t('Sort as budget') },
+ ];
+
+ const currentLabel =
+ value === 'global'
+ ? t('Sort all')
+ : value === 'budget-order'
+ ? t('Sort as budget')
+ : t('Sort per group');
+
+ return (
+ <>
+ <Button
+ ref={triggerRef}
+ variant="bare"
+ onPress={() => setIsOpen(true)}
+ aria-label={t('Change category sort order')}
+ >
+ <SvgArrowDown style={{ width: 12, height: 12 }} />
+ <span style={{ marginLeft: 5 }}>{currentLabel}</span>
+ </Button>
+ <Popover
+ triggerRef={triggerRef}
+ placement="bottom start"
+ isOpen={isOpen}
+ onOpenChange={() => setIsOpen(false)}
+ >
+ <Menu
+ onMenuSelect={item => {
+ onChange(item as 'per-group' | 'global' | 'budget-order');
+ setIsOpen(false);
+ }}
+ items={options.map(({ key, label }) => ({
+ name: key,
+ text: label,
+ }))}
+ />
+ </Popover>
+ </>
+ );
+}
+
+type GraphModeSelectorProps = {
+ mode: GraphMode;
+ onChange: (mode: GraphMode) => void;
+};
+
+function GraphModeSelector({ mode, onChange }: GraphModeSelectorProps) {
+ return (
+ <SpaceBetween gap={5}>
+ <ModeButton
+ selected={mode === 'spent'}
+ style={{
+ backgroundColor: 'inherit',
+ }}
+ onSelect={() => {
+ onChange('spent');
+ }}
+ >
+ <Trans>Spent</Trans>
+ </ModeButton>
+ <ModeButton
+ selected={mode === 'budgeted'}
+ onSelect={() => {
+ onChange('budgeted');
+ }}
+ style={{
+ backgroundColor: 'inherit',
+ }}
+ >
+ <Trans>Budgeted</Trans>
+ </ModeButton>
+ </SpaceBetween>
+ );
+}
+
+type SankeyInnerProps = {
+ widget?: SankeyWidget;
+};
+function SankeyInner({ widget }: SankeyInnerProps) {
+ const locale = useLocale();
+ const dispatch = useDispatch();
+ const { t } = useTranslation();
+ const navigate = useNavigate();
+ const { isNarrowWidth } = useResponsive();
+
+ const {
+ conditions,
+ conditionsOp,
+ onApply: onApplyFilter,
+ onDelete: onDeleteFilter,
+ onUpdate: onUpdateFilter,
+ onConditionsOpChange,
+ } = useRuleConditionFilters<RuleConditionEntity>(
+ widget?.meta?.conditions,
+ widget?.meta?.conditionsOp,
+ );
+
+ const currentMonth = monthUtils.currentMonth();
+ const [allMonths, setAllMonths] = useState([
+ {
+ name: currentMonth,
+ pretty: monthUtils.format(currentMonth, 'MMMM yyyy', locale),
+ },
+ ]);
+
+ const [start, setStart] = useState(monthUtils.currentMonth());
+ const [end, setEnd] = useState(monthUtils.currentMonth());
+ const [timeFrameMode, setTimeFrameMode] = useState<TimeFrame['mode']>(
+ widget?.meta?.timeFrame?.mode ?? 'sliding-window',
+ );
+ const [datesInitialized, setDatesInitialized] = useState(false);
+
+ const [earliestTransaction, setEarliestTransaction] = useState('');
+ const [latestTransaction, setLatestTransaction] = useState('');
+
+ const [graphMode, setGraphMode] = useState<GraphMode>(
+ widget?.meta?.mode ?? 'spent',
+ );
+
+ const [topNcategories, settopNcategories] = useState<number>(
+ widget?.meta?.topNcategories ?? 15,
+ );
+
+ const [categorySort, setCategorySort] = useState<
+ 'per-group' | 'global' | 'budget-order'
+ >(widget?.meta?.categorySort ?? 'per-group');
+
+ const { data: { grouped: groupedCategories = [] } = { grouped: [] } } =
+ useCategories();
+
+ const reportParams = useMemo(() => {
+ if (!datesInitialized) {
+ return null;
+ }
+
+ return sankeySpreadsheet(
+ start,
+ end,
+ groupedCategories,
+ conditions,
+ conditionsOp,
+ graphMode,
+ topNcategories,
+ categorySort,
+ );
+ }, [
+ datesInitialized,
+ start,
+ end,
+ groupedCategories,
+ conditions,
+ conditionsOp,
+ graphMode,
+ topNcategories,
+ categorySort,
+ ]);
+
+ 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');
+ const earliestTransactionDate = earliestTransaction
+ ? earliestTransaction.date
+ : monthUtils.currentDay();
+ setEarliestTransaction(earliestTransactionDate);
+
+ const latestTransaction = await send('get-latest-transaction');
+ const latestTransactionDate = latestTransaction
+ ? latestTransaction.date
+ : monthUtils.currentDay();
+ setLatestTransaction(latestTransactionDate);
+
+ const [initialStart, initialEnd, initialMode] = calculateTimeRange(
+ widget?.meta?.timeFrame,
+ undefined,
+ latestTransactionDate,
+ );
+ setStart(initialStart);
+ setEnd(initialEnd);
+ setTimeFrameMode(initialMode);
+ setDatesInitialized(true);
+
+ const currentMonth = monthUtils.currentMonth();
+ let earliestMonth = earliestTransaction
+ ? monthUtils.monthFromDate(
+ d.parseISO(fromDateRepr(earliestTransaction.date)),
+ )
+ : currentMonth;
+ const latestTransactionMonth = latestTransaction
+ ? monthUtils.monthFromDate(
+ d.parseISO(fromDateRepr(latestTransaction.date)),
+ )
+ : currentMonth;
+
+ const latestMonth =
+ latestTransactionMonth > currentMonth
+ ? latestTransactionMonth
+ : currentMonth;
+
+ // Make sure the month selects are at least populated with a
+ // year's worth of months. We can undo this when we have fancier
+ // date selects.
+ const yearAgo = monthUtils.subMonths(latestMonth, 12);
+ if (earliestMonth > yearAgo) {
+ earliestMonth = yearAgo;
+ }
+
+ const allMonths = monthUtils
+ .rangeInclusive(earliestMonth, latestMonth)
+ .map(month => ({
+ name: month,
+ pretty: monthUtils.format(month, 'MMMM yyyy', locale),
+ }))
+ .reverse();
+
+ setAllMonths(allMonths);
+ }
+ void run();
+ }, [locale, widget?.meta?.timeFrame]);
+ function onChangeDates(start: string, end: string, mode: TimeFrame['mode']) {
+ setStart(start);
+ setEnd(end);
+ setTimeFrameMode(mode);
+ }
+
+ const updateDashboardWidgetMutation = useUpdateDashboardWidgetMutation();
+ async function onSaveWidget() {
+ if (!widget) {
+ throw new Error('No widget that could be saved.');
+ }
+
+ updateDashboardWidgetMutation.mutate(
+ {
+ widget: {
+ id: widget.id,
+ meta: {
+ ...(widget.meta ?? {}),
+ conditions,
+ conditionsOp,
+ mode: graphMode,
+ topNcategories,
+ categorySort,
+ timeFrame: {
+ start,
+ end,
+ mode: timeFrameMode,
+ },
+ },
+ },
+ },
+ {
+ onSuccess: () => {
+ dispatch(
+ addNotification({
+ notification: {
+ type: 'message',
+ message: t('Dashboard widget successfully saved.'),
+ },
+ }),
+ );
+ },
+ },
+ );
+ }
+
+ const onSaveWidgetName = async (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,
+ },
+ });
+ };
+
+ const title = widget?.meta?.name || t('Sankey');
+
+ if (!datesInitialized || !data) {
+ return <LoadingIndicator />;
+ }
+
+ return (
+ <Page
+ header={
+ isNarrowWidth ? (
+ <MobilePageHeader
+ title={title}
+ leftContent={
+ <MobileBackButton onPress={() => navigate('/reports')} />
+ }
+ />
+ ) : (
+ <PageHeader
+ title={
+ widget ? (
+ <EditablePageHeaderTitle
+ title={title}
+ onSave={onSaveWidgetName}
+ />
+ ) : (
+ title
+ )
+ }
+ />
+ )
+ }
+ padding={0}
+ >
+ <Header
+ allMonths={allMonths}
+ start={start}
+ end={end}
+ mode={timeFrameMode}
+ show1Month
+ earliestTransaction={earliestTransaction}
+ latestTransaction={latestTransaction}
+ onChangeDates={onChangeDates}
+ filters={conditions}
+ onApply={onApplyFilter}
+ onUpdateFilter={onUpdateFilter}
+ onDeleteFilter={onDeleteFilter}
+ conditionsOp={conditionsOp}
+ onConditionsOpChange={onConditionsOpChange}
+ filterExclude={[
+ 'date',
+ 'payee',
+ 'notes',
+ 'amount',
+ 'cleared',
+ 'reconciled',
+ 'transfer',
+ ]}
+ inlineContent={
+ <>
+ <View
+ style={{
+ width: 1,
+ height: 28,
+ backgroundColor: theme.pillBorderDark,
+ marginRight: 10,
+ marginLeft: 10,
+ }}
+ />
+ <GraphModeSelector mode={graphMode} onChange={setGraphMode} />
+ <View
+ style={{
+ width: 1,
+ height: 28,
+ backgroundColor: theme.pillBorderDark,
+ marginRight: 10,
+ marginLeft: 10,
+ }}
+ />
+ <TopNSelector value={topNcategories} onChange={settopNcategories} />
+ <CategorySortSelector
+ value={categorySort}
+ onChange={setCategorySort}
+ />
+ </>
+ }
+ >
+ {widget && (
+ <Button variant="primary" onPress={onSaveWidget}>
+ <Trans>Save widget</Trans>
+ </Button>
+ )}
+ </Header>
+ <View
+ style={{
+ backgroundColor: theme.tableBackground,
+ padding: 20,
+ paddingTop: 0,
+ flex: '1 0 auto',
+ overflowY: 'visible',
+ }}
+ >
+ <View
+ style={{
+ display: 'flex',
+ flexDirection: 'row',
+ paddingTop: 0,
+ flexGrow: 1,
+ }}
+ >
+ <View
+ style={{
+ flexGrow: 1,
+ }}
+ >
+ <View
+ style={{
+ backgroundColor: theme.tableBackground,
+ padding: 20,
+ paddingTop: 0,
+ flex: '1 0 auto',
+ overflowY: 'auto',
+ }}
+ >
+ <View
+ style={{
+ flexDirection: 'column',
+ flexGrow: 1,
+ padding: 10,
+ paddingTop: 10,
+ }}
+ >
+ {data && data.links && data.links.length > 0 ? (
+ <SankeyGraph
+ style={{ flexGrow: 1 }}
+ data={data as SankeyData}
+ />
+ ) : (
+ <View
+ style={{
+ flexGrow: 1,
+ alignItems: 'center',
+ justifyContent: 'center',
+ color: theme.pageTextSubdued,
+ }}
+ >
+ <Text style={{ fontSize: 16, textAlign: 'center' }}>
+ {graphMode === 'budgeted' && (
+ <Trans>
+ No data available for this period. Try budgeting
+ categories or selecting a different period.
+ </Trans>
+ )}
+ {graphMode === 'spent' && (
+ <Trans>
+ No data available for this period. Try adding
+ transactions or selecting a different period.
+ </Trans>
+ )}
+ </Text>
+ </View>
+ )}
+
+ {!isNarrowWidth && (
+ <View style={{ marginTop: 30 }}>
+ <Trans>
+ <Paragraph>
+ <strong>What is a Sankey plot?</strong>
+ </Paragraph>
+ <Paragraph>
+ A Sankey plot visualizes the flow of quantities between
+ multiple categories, emphasizing the distribution and
+ proportional relationships of data streams.
+ </Paragraph>
+ <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>
+ </Trans>
+ </View>
+ )}
+ </View>
+ </View>
+ </View>
+ </View>
+ </View>
+ </Page>
+ );
+}
diff --git a/packages/desktop-client/src/components/reports/reports/SankeyCard.tsx b/packages/desktop-client/src/components/reports/reports/SankeyCard.tsx
new file mode 100644
index 0000000000..ca76a697e4
--- /dev/null
+++ b/packages/desktop-client/src/components/reports/reports/SankeyCard.tsx
@@ -0,0 +1,168 @@
+import { useMemo, useState } from 'react';
+import type { ReactElement } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { Block } from '@actual-app/components/block';
+import { theme } from '@actual-app/components/theme';
+import { View } from '@actual-app/components/view';
+import * as d from 'date-fns';
+
+import type { SankeyWidget } from 'loot-core/types/models';
+
+import { DateRange } from '@desktop-client/components/reports/DateRange';
+import { SankeyGraph } from '@desktop-client/components/reports/graphs/SankeyGraph';
+import { LoadingIndicator } from '@desktop-client/components/reports/LoadingIndicator';
+import { ReportCard } from '@desktop-client/components/reports/ReportCard';
+import { ReportCardName } from '@desktop-client/components/reports/ReportCardName';
+import { calculateTimeRange } from '@desktop-client/components/reports/reportRanges';
+import {
+ compactSankeyData,
+ createSpreadsheet as sankeySpreadsheet,
+} from '@desktop-client/components/reports/spreadsheets/sankey-spreadsheet';
+import { useDashboardWidgetCopyMenu } from '@desktop-client/components/reports/useDashboardWidgetCopyMenu';
+import { useReport } from '@desktop-client/components/reports/useReport';
+import { useCategories } from '@desktop-client/hooks/useCategories';
+import { useLocale } from '@desktop-client/hooks/useLocale';
+import { useResizeObserver } from '@desktop-client/hooks/useResizeObserver';
+
+type SankeyCardProps = {
+ widgetId: string;
+ isEditing?: boolean;
+ meta?: SankeyWidget['meta'];
+ onMetaChange: (newMeta: SankeyWidget['meta']) => void;
+ onRemove: () => void;
+ onCopy: (targetDashboardId: string) => void;
+};
+export function SankeyCard({
+ widgetId,
+ isEditing,
+ meta,
+ onMetaChange,
+ onRemove,
+ onCopy,
+}: SankeyCardProps) {
+ const { t } = useTranslation();
+ const locale = useLocale();
+ const [nameMenuOpen, setNameMenuOpen] = useState(false);
+ const { menuItems: copyMenuItems, handleMenuSelect: handleCopyMenuSelect } =
+ useDashboardWidgetCopyMenu(onCopy);
+ const { data: { grouped: groupedCategories = [] } = { grouped: [] } } =
+ useCategories();
+
+ const [start, end] = calculateTimeRange(meta?.timeFrame);
+ const mode = meta?.mode ?? 'spent';
+
+ const [cardHeight, setCardHeight] = useState(0);
+ const containerRef = useResizeObserver<HTMLDivElement>(rect => {
+ setCardHeight(rect.height);
+ });
+
+ const params = useMemo(
+ () =>
+ sankeySpreadsheet(
+ start,
+ end,
+ groupedCategories,
+ meta?.conditions ?? [],
+ meta?.conditionsOp ?? 'and',
+ mode,
+ ),
+ [start, end, groupedCategories, meta?.conditions, meta?.conditionsOp, mode],
+ );
+ const data = useReport('sankey', params);
+
+ const HEADER_HEIGHT = 82;
+ const PX_PER_NODE = 50;
+ const topN = Math.max(
+ 2,
+ Math.floor((cardHeight - HEADER_HEIGHT) / PX_PER_NODE),
+ );
+
+ const compactData = useMemo(
+ () => (data ? compactSankeyData(data, topN) : null),
+ [data, topN],
+ );
+
+ const startDate = d.parseISO(start);
+ const endDate = d.parseISO(end);
+ const formattedStartDate = d.format(startDate, 'MMM yyyy', { locale });
+ const formattedEndDate = d.format(endDate, 'MMM yyyy', { locale });
+
+ let dateDescription: string | ReactElement;
+ if (
+ startDate.getFullYear() !== endDate.getFullYear() ||
+ startDate.getMonth() !== endDate.getMonth()
+ ) {
+ dateDescription = formattedStartDate + ' - ' + formattedEndDate;
+ } else {
+ dateDescription = formattedEndDate;
+ }
+
+ const modeLabel = mode === 'budgeted' ? t('Budgeted') : t('Spent');
+
+ dateDescription += ` (${modeLabel})`;
+
+ return (
+ <ReportCard
+ isEditing={isEditing}
+ disableClick={nameMenuOpen}
+ to={`/reports/sankey/${widgetId}`}
+ menuItems={[
+ {
+ name: 'rename',
+ text: t('Rename'),
+ },
+ {
+ name: 'remove',
+ text: t('Remove'),
+ },
+ ...copyMenuItems,
+ ]}
+ onMenuSelect={item => {
+ if (handleCopyMenuSelect(item)) return;
+ switch (item) {
+ case 'rename':
+ setNameMenuOpen(true);
+ break;
+ case 'remove':
+ onRemove();
+ break;
+ default:
+ throw new Error(`Unrecognized selection: ${item}`);
+ }
+ }}
+ >
+ <View ref={containerRef} style={{ flex: 1 }}>
+ <View style={{ flexDirection: 'row', padding: 20 }}>
+ <View style={{ flex: 1 }}>
+ <ReportCardName
+ name={meta?.name || t('Sankey')}
+ isEditing={nameMenuOpen}
+ onChange={newName => {
+ onMetaChange({
+ ...meta,
+ name: newName,
+ });
+ setNameMenuOpen(false);
+ }}
+ onClose={() => setNameMenuOpen(false)}
+ />
+ <Block style={{ color: theme.pageTextSubdued }}>
+ {dateDescription}
+ </Block>
+ </View>
+ </View>
+
+ {compactData ? (
+ <SankeyGraph
+ data={compactData}
+ showTooltip={!isEditing}
+ style={{ height: 'auto', flex: 1 }}
+ />
+ ) : (
+ <LoadingIndicator />
+ )}
+ </View>
+ </ReportCard>
+ );
+}
diff --git a/packages/desktop-client/src/components/reports/spreadsheets/sankey-spreadsheet.ts b/packages/desktop-client/src/components/reports/spreadsheets/sankey-spreadsheet.ts
new file mode 100644
index 0000000000..20f002bf32
--- /dev/null
+++ b/packages/desktop-client/src/components/reports/spreadsheets/sankey-spreadsheet.ts
@@ -0,0 +1,730 @@
+import { send } from 'loot-core/platform/client/connection';
+import * as monthUtils from 'loot-core/shared/months';
+import { q } from 'loot-core/shared/query';
+import type {
+ CategoryGroupEntity,
+ RuleConditionEntity,
+} from 'loot-core/types/models';
+
+import type { useSpreadsheet } from '@desktop-client/hooks/useSpreadsheet';
+import { aqlQuery } from '@desktop-client/queries/aqlQuery';
+
+type BudgetMonthCategory = {
+ id: string;
+ name: string;
+ spent?: number;
+ budgeted?: number;
+ balance?: number;
+};
+
+type BudgetMonthGroup = {
+ id: string;
+ name: string;
+ is_income: boolean;
+ categories: BudgetMonthCategory[];
+};
+
+type BudgetMonthResponse = {
+ categoryGroups: BudgetMonthGroup[];
+ totalIncome: number;
+ fromLastMonth: number;
+ forNextMonth: number;
+ toBudget: number;
+};
+
+type AggregatedBudget = {
+ toBudget: number;
+ categoryGroupsMap: Map<string, BudgetMonthGroup>;
+};
+
+type SankeyNode = {
+ name: string;
+ toBudget?: number;
+ isNegative?: boolean;
+};
+
+type SankeyLink = {
+ source: number;
+ target: number;
+ value: number;
+ isNegative?: boolean;
+ tooltipInfo?: Array<{ name: string; value: number }>;
+};
+
+type SankeyData = {
+ nodes: SankeyNode[];
+ links: SankeyLink[];
+};
+
+type CategoryEntry = {
+ mainCategory: string;
+ group: string;
+ value: number;
+ isNegative?: boolean;
+};
+
+type CategoryOrder = Array<{ mainCategory: string; categories: string[] }>;
+
+// 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(
+ categoryGroups: BudgetMonthGroup[],
+ conditions: RuleConditionEntity[],
+ conditionsOp: 'and' | 'or',
+): BudgetMonthGroup[] {
+ const categoryConditions = conditions.filter(
+ cond => cond.field === 'category',
+ );
+ const categoryGroupConditions = conditions.filter(
+ cond => cond.field === 'category_group',
+ );
+
+ if (categoryConditions.length === 0 && categoryGroupConditions.length === 0) {
+ return categoryGroups;
+ }
+
+ const matchesStringCondition = (
+ id: string,
+ name: string,
+ cond: RuleConditionEntity,
+ ): boolean => {
+ const value = cond.value;
+ const op = cond.op as string;
+ if (op === 'is') return id === value;
+ if (op === 'isNot') return id !== value;
+ if (op === 'oneOf') return Array.isArray(value) && value.includes(id);
+ if (op === 'notOneOf') return !Array.isArray(value) || !value.includes(id);
+ if (op === 'contains') {
+ return (
+ typeof value === 'string' &&
+ name.toLowerCase().includes(value.toLowerCase())
+ );
+ }
+ if (op === 'doesNotContain') {
+ return (
+ typeof value === 'string' &&
+ !name.toLowerCase().includes(value.toLowerCase())
+ );
+ }
+ if (op === 'matches') {
+ if (typeof value !== 'string') return false;
+ try {
+ const regex =
+ value.startsWith('/') && value.lastIndexOf('/') > 0
+ ? new RegExp(
+ value.slice(1, value.lastIndexOf('/')),
+ value.slice(value.lastIndexOf('/') + 1),
+ )
+ : new RegExp(value);
+ return regex.test(name);
+ } catch {
+ return false;
+ }
+ }
+ return false;
+ };
+
+ const categoryMatchesConditions = (
+ catId: string,
+ catName: string,
+ groupId: string,
+ groupName: string,
+ ): boolean => {
+ const matchesCat = (cond: RuleConditionEntity) =>
+ matchesStringCondition(catId, catName, cond);
+ const matchesGroup = (cond: RuleConditionEntity) =>
+ matchesStringCondition(groupId, groupName, cond);
+
+ if (conditionsOp === 'or') {
+ return (
+ categoryConditions.some(matchesCat) ||
+ categoryGroupConditions.some(matchesGroup)
+ );
+ }
+ // 'and': all category conditions AND all category_group conditions must match
+ const catMatch =
+ categoryConditions.length === 0 || categoryConditions.every(matchesCat);
+ const groupMatch =
+ categoryGroupConditions.length === 0 ||
+ categoryGroupConditions.every(matchesGroup);
+ return catMatch && groupMatch;
+ };
+
+ return categoryGroups
+ .map(group => ({
+ ...group,
+ categories: group.categories.filter(cat =>
+ categoryMatchesConditions(cat.id, cat.name, group.id, group.name),
+ ),
+ }))
+ .filter(group => group.categories.length > 0);
+}
+
+export function createSpreadsheet(
+ start: string,
+ end: string,
+ categories: CategoryGroupEntity[],
+ conditions: RuleConditionEntity[] = [],
+ conditionsOp: 'and' | 'or' = 'and',
+ mode: 'budgeted' | 'spent' = 'spent',
+ topNcategories: number = 15,
+ categorySort: 'per-group' | 'global' | 'budget-order' = 'per-group',
+) {
+ let globalOther: boolean;
+ let groupSort: 'per-group' | 'global';
+ let categoryOrder: CategoryOrder | undefined;
+
+ if (categorySort === 'global') {
+ globalOther = true;
+ groupSort = 'global';
+ } else if (categorySort === 'budget-order') {
+ globalOther = false;
+ groupSort = 'per-group';
+ categoryOrder = categories
+ .filter(g => !g.hidden && !g.is_income)
+ .map(g => ({
+ mainCategory: g.name,
+ categories: (g.categories ?? [])
+ .filter(c => !c.hidden)
+ .map(c => c.name),
+ }));
+ } else {
+ globalOther = false;
+ groupSort = 'per-group';
+ }
+
+ return async (
+ spreadsheet: ReturnType<typeof useSpreadsheet>,
+ setData: (data: ReturnType<typeof transformToSankeyData>) => void,
+ ) => {
+ if (mode === 'budgeted') {
+ const data = await createBudgetSpreadsheet(
+ start,
+ end,
+ conditions,
+ conditionsOp,
+ globalOther,
+ topNcategories,
+ groupSort,
+ categoryOrder,
+ )(spreadsheet, setData);
+ return data;
+ } else if (mode === 'spent') {
+ const data = await createTransactionsSpreadsheet(
+ start,
+ end,
+ categories,
+ conditions,
+ conditionsOp,
+ globalOther,
+ topNcategories,
+ groupSort,
+ categoryOrder,
+ )(spreadsheet, setData);
+ return data;
+ }
+ };
+}
+
+export function createBudgetSpreadsheet(
+ start: string,
+ end: string,
+ conditions: RuleConditionEntity[] = [],
+ conditionsOp: 'and' | 'or' = 'and',
+ globalOther: boolean = false,
+ topNcategories: number = 15,
+ groupSort: 'per-group' | 'global' = 'per-group',
+ categoryOrder?: CategoryOrder,
+) {
+ return async (
+ spreadsheet: ReturnType<typeof useSpreadsheet>,
+ setData: (data: ReturnType<typeof transformToSankeyData>) => void,
+ ) => {
+ const months =
+ end && end !== start ? monthUtils.rangeInclusive(start, end) : [start];
+
+ const monthResponses = await Promise.all(
+ months.map(
+ m =>
+ send('api/budget-month', {
+ month: m,
+ }) as unknown as Promise<BudgetMonthResponse>,
+ ),
+ );
+
+ const aggregated = monthResponses.reduce<AggregatedBudget>(
+ (acc, response) => {
+ acc.toBudget += response.toBudget;
+
+ for (const group of response.categoryGroups) {
+ const existingGroup = acc.categoryGroupsMap.get(group.id);
+ if (!existingGroup) {
+ acc.categoryGroupsMap.set(group.id, {
+ ...group,
+ categories: group.categories.map(cat => ({ ...cat })),
+ });
+ continue;
+ }
+
+ for (const cat of group.categories) {
+ const existingCat = existingGroup.categories.find(
+ c => c.id === cat.id,
+ );
+ if (!existingCat) {
+ existingGroup.categories.push({ ...cat });
+ continue;
+ }
+ existingCat.budgeted =
+ (existingCat.budgeted ?? 0) + (cat.budgeted ?? 0);
+ existingCat.spent = (existingCat.spent ?? 0) + (cat.spent ?? 0);
+ existingCat.balance =
+ (existingCat.balance ?? 0) + (cat.balance ?? 0);
+ }
+ }
+
+ return acc;
+ },
+ {
+ toBudget: 0,
+ categoryGroupsMap: new Map<string, BudgetMonthGroup>(),
+ },
+ );
+
+ const categoryGroups = Array.from(aggregated.categoryGroupsMap.values());
+
+ const filteredCategoryGroups = filterCategoryGroups(
+ categoryGroups,
+ conditions,
+ conditionsOp,
+ );
+
+ const categoryData: CategoryEntry[] = filteredCategoryGroups
+ .filter(group => !group.is_income)
+ .flatMap(group =>
+ group.categories.map(cat => ({
+ mainCategory: group.name,
+ group: cat.name,
+ value: cat.budgeted ?? 0,
+ })),
+ );
+
+ const { toBudget } = aggregated;
+
+ setData(
+ transformToSankeyData(
+ categoryData,
+ toBudget,
+ 'Budgeted',
+ topNcategories,
+ globalOther,
+ groupSort,
+ categoryOrder,
+ ),
+ );
+ };
+}
+
+export function createTransactionsSpreadsheet(
+ start: string,
+ end: string,
+ categories: CategoryGroupEntity[],
+ conditions: RuleConditionEntity[] = [],
+ conditionsOp: 'and' | 'or' = 'and',
+ globalOther: boolean = false,
+ topNcategories: number = 15,
+ groupSort: 'per-group' | 'global' = 'per-group',
+ categoryOrder?: CategoryOrder,
+) {
+ return async (
+ spreadsheet: ReturnType<typeof useSpreadsheet>,
+ setData: (data: ReturnType<typeof transformToSankeyData>) => void,
+ ) => {
+ // gather filters user has set
+ const { filters } = await send('make-filters-from-conditions', {
+ conditions: conditions.filter(cond => !cond.customName),
+ });
+ const conditionsOpKey = conditionsOp === 'or' ? '$or' : '$and';
+
+ const categoryData = await fetchCategoryData(
+ categories,
+ conditionsOpKey,
+ filters,
+ start,
+ end,
+ );
+
+ // convert retrieved data into the proper sankey format
+ setData(
+ transformToSankeyData(
+ categoryData,
+ 0,
+ 'Spent',
+ topNcategories,
+ globalOther,
+ groupSort,
+ categoryOrder,
+ ),
+ );
+ };
+}
+
+// retrieve sum of group expenses
+async function fetchCategoryData(
+ categories: CategoryGroupEntity[],
+ conditionsOpKey: string = '$and',
+ filters: unknown[] = [],
+ start: string,
+ end: string,
+): Promise<CategoryEntry[]> {
+ const nested = await Promise.all(
+ categories.map(async (mainCategory: CategoryGroupEntity) => {
+ const entries = await Promise.all(
+ (mainCategory.categories || [])
+ .filter(group => !group?.is_income)
+ .map(async group => {
+ const results = await aqlQuery(
+ q('transactions')
+ .filter({ [conditionsOpKey]: filters })
+ .filter({
+ $and: [
+ { date: { $gte: monthUtils.firstDayOfMonth(start) } },
+ { date: { $lte: monthUtils.lastDayOfMonth(end) } },
+ ],
+ })
+ .filter({ category: group.id })
+ .calculate({ $sum: '$amount' }),
+ );
+ return {
+ mainCategory: mainCategory.name,
+ group: group.name,
+ value: results.data * -1,
+ } satisfies CategoryEntry;
+ }),
+ );
+ return entries;
+ }),
+ );
+ return nested.flat();
+}
+
+type LeafState = {
+ mainCategory: string;
+ group: string;
+ value: number;
+ isNegative: boolean;
+ visible: boolean;
+};
+
+type OtherBucket = {
+ total: number;
+ entries: Array<{ name: string; value: number }>;
+};
+
+type GreedyReductionResult = {
+ allLeaves: LeafState[];
+ perCategoryOther: Map<string, OtherBucket>;
+ globalOtherBucket: OtherBucket;
+};
+
+function greedyReduceLeaves(
+ allLeaves: LeafState[],
+ topNcategories: number,
+ globalOther: boolean,
+): GreedyReductionResult {
+ const perCategoryOther = new Map<string, OtherBucket>();
+ const globalOtherBucket: OtherBucket = { total: 0, entries: [] };
+
+ let visibleCount = allLeaves.length;
+ let otherNodeCount = 0;
+
+ // Collapse the lowest-value visible leaf into an Other bucket until the
+ // total displayed node count (individual + Other nodes) <= topNcategories.
+ while (visibleCount + otherNodeCount > topNcategories && visibleCount > 0) {
+ const minLeaf = allLeaves
+ .filter(l => l.visible)
+ .reduce((min, l) => (l.value < min.value ? l : min));
+
+ minLeaf.visible = false;
+ visibleCount -= 1;
+
+ if (globalOther) {
+ if (globalOtherBucket.total === 0) otherNodeCount += 1;
+ globalOtherBucket.total += minLeaf.value;
+ globalOtherBucket.entries.push({
+ name: minLeaf.group,
+ value: minLeaf.value,
+ });
+ } else {
+ if (!perCategoryOther.has(minLeaf.mainCategory)) otherNodeCount += 1;
+ const bucket = perCategoryOther.get(minLeaf.mainCategory) ?? {
+ total: 0,
+ entries: [],
+ };
+ bucket.total += minLeaf.value;
+ bucket.entries.push({ name: minLeaf.group, value: minLeaf.value });
+ perCategoryOther.set(minLeaf.mainCategory, bucket);
+ }
+ }
+
+ // Promote single-entry Other buckets back to visible — a 1-item "Other"
+ // node wastes a slot and hides information.
+ if (globalOther) {
+ if (globalOtherBucket.entries.length === 1) {
+ const entry = globalOtherBucket.entries[0];
+ const leaf = allLeaves.find(l => l.group === entry.name && !l.visible);
+ if (leaf) {
+ leaf.visible = true;
+ globalOtherBucket.total = 0;
+ globalOtherBucket.entries = [];
+ }
+ }
+ } else {
+ for (const [catName, bucket] of perCategoryOther) {
+ if (bucket.entries.length === 1) {
+ const entry = bucket.entries[0];
+ const leaf = allLeaves.find(
+ l =>
+ l.mainCategory === catName && l.group === entry.name && !l.visible,
+ );
+ if (leaf) {
+ leaf.visible = true;
+ perCategoryOther.delete(catName);
+ }
+ }
+ }
+ }
+
+ return { allLeaves, perCategoryOther, globalOtherBucket };
+}
+
+function transformToSankeyData(
+ categoryData: CategoryEntry[],
+ toBudgetAmount: number = 0,
+ rootNodeName: string,
+ topNcategories: number = 15,
+ globalOther: boolean = false,
+ groupSort: 'per-group' | 'global' = 'per-group',
+ categoryOrder?: CategoryOrder,
+): SankeyData {
+ // Phase 1 — Initialise leaves
+ const allLeaves: LeafState[] = categoryData
+ .filter(e => e.value > 0)
+ .map(e => ({
+ mainCategory: e.mainCategory,
+ group: e.group,
+ value: e.value,
+ isNegative: e.isNegative ?? false,
+ visible: true,
+ }));
+
+ // Phase 2 — Greedy reduction (collapse lowest-value leaves into Other buckets)
+ const { perCategoryOther, globalOtherBucket } = greedyReduceLeaves(
+ allLeaves,
+ topNcategories,
+ globalOther,
+ );
+
+ // Phase 3 — Compute category totals (sum of ALL leaves including collapsed)
+ const categoryTotals = new Map<string, number>();
+ for (const leaf of allLeaves) {
+ categoryTotals.set(
+ leaf.mainCategory,
+ (categoryTotals.get(leaf.mainCategory) ?? 0) + leaf.value,
+ );
+ }
+
+ const sortedCategories = categoryOrder
+ ? categoryOrder
+ .map(c => c.mainCategory)
+ .filter(name => categoryTotals.has(name))
+ .concat(
+ [...categoryTotals.keys()]
+ .filter(name => !categoryOrder.some(c => c.mainCategory === name))
+ .sort(
+ (a, b) =>
+ (categoryTotals.get(b) ?? 0) - (categoryTotals.get(a) ?? 0),
+ ),
+ )
+ : [...categoryTotals.keys()].sort(
+ (a, b) => (categoryTotals.get(b) ?? 0) - (categoryTotals.get(a) ?? 0),
+ );
+
+ // Phase 4 — Build nodes/links
+ const nodes: SankeyNode[] = [
+ { name: rootNodeName, toBudget: toBudgetAmount },
+ ];
+ const links: SankeyLink[] = [];
+ const catNodeIndexMap = new Map<string, number>();
+
+ // Add all category nodes first (needed for global sort so indices are known)
+ for (const catName of sortedCategories) {
+ nodes.push({ name: catName });
+ catNodeIndexMap.set(catName, nodes.length - 1);
+ links.push({
+ source: 0,
+ target: nodes.length - 1,
+ value: categoryTotals.get(catName) ?? 0,
+ });
+ }
+
+ if (groupSort === 'global') {
+ // All visible categories sorted by value globally
+ const allVisibleLeaves = allLeaves
+ .filter(l => l.visible)
+ .sort((a, b) => b.value - a.value);
+
+ for (const leaf of allVisibleLeaves) {
+ const catIdx = catNodeIndexMap.get(leaf.mainCategory) ?? 0;
+ nodes.push({ name: leaf.group, isNegative: leaf.isNegative });
+ links.push({
+ source: catIdx,
+ target: nodes.length - 1,
+ value: leaf.value,
+ isNegative: leaf.isNegative,
+ });
+ }
+
+ // per-group Other nodes (globalOther=false only)
+ if (!globalOther) {
+ for (const catName of sortedCategories) {
+ const bucket = perCategoryOther.get(catName);
+ if (bucket) {
+ const catIdx = catNodeIndexMap.get(catName) ?? 0;
+ nodes.push({ name: 'Other' });
+ links.push({
+ source: catIdx,
+ target: nodes.length - 1,
+ value: bucket.total,
+ tooltipInfo: [...bucket.entries].sort((a, b) => b.value - a.value),
+ });
+ }
+ }
+ }
+ } else {
+ // per-group sort or budget-order: each category's categories sorted independently
+ for (const catName of sortedCategories) {
+ const catIdx = catNodeIndexMap.get(catName) ?? 0;
+
+ const subcatOrder = categoryOrder?.find(
+ c => c.mainCategory === catName,
+ )?.categories;
+
+ const visibleLeaves = allLeaves
+ .filter(l => l.mainCategory === catName && l.visible)
+ .sort((a, b) => {
+ if (subcatOrder) {
+ const ai = subcatOrder.indexOf(a.group);
+ const bi = subcatOrder.indexOf(b.group);
+ if (ai === -1 && bi === -1) return b.value - a.value;
+ if (ai === -1) return 1;
+ if (bi === -1) return -1;
+ return ai - bi;
+ }
+ return b.value - a.value;
+ });
+
+ for (const leaf of visibleLeaves) {
+ nodes.push({ name: leaf.group, isNegative: leaf.isNegative });
+ links.push({
+ source: catIdx,
+ target: nodes.length - 1,
+ value: leaf.value,
+ isNegative: leaf.isNegative,
+ });
+ }
+
+ // per-group Other node (globalOther=false only)
+ if (!globalOther) {
+ const bucket = perCategoryOther.get(catName);
+ if (bucket) {
+ nodes.push({ name: 'Other' });
+ links.push({
+ source: catIdx,
+ target: nodes.length - 1,
+ value: bucket.total,
+ tooltipInfo: [...bucket.entries].sort((a, b) => b.value - a.value),
+ });
+ }
+ }
+ }
+ }
+
+ // Global Other node (globalOther=true only)
+ if (globalOther && globalOtherBucket.total > 0) {
+ nodes.push({ name: 'Other' });
+ const globalOtherIdx = nodes.length - 1;
+
+ // Group entries by main category and emit one link per group
+ const byCategory = new Map<
+ string,
+ Array<{ name: string; value: number }>
+ >();
+ for (const entry of globalOtherBucket.entries) {
+ // Find which main category this group belongs to
+ const leaf = allLeaves.find(l => l.group === entry.name && !l.visible);
+ if (!leaf) continue;
+ const group = byCategory.get(leaf.mainCategory) ?? [];
+ group.push(entry);
+ byCategory.set(leaf.mainCategory, group);
+ }
+
+ for (const [catName, entries] of byCategory) {
+ const sourceCatIdx = catNodeIndexMap.get(catName);
+ if (sourceCatIdx === undefined) continue;
+ const groupTotal = entries.reduce((sum, e) => sum + e.value, 0);
+ links.push({
+ source: sourceCatIdx,
+ target: globalOtherIdx,
+ value: groupTotal,
+ tooltipInfo: [...entries].sort((a, b) => b.value - a.value),
+ });
+ }
+ }
+
+ return { nodes, links };
+}
+
+export function compactSankeyData(
+ data: SankeyData,
+ topN: number = 5,
+): SankeyData {
+ const compactedData: SankeyData = { nodes: [], links: [] };
+ compactedData.nodes.push(data.nodes[0]); // root node
+
+ // Find all root→mainCategory links and sort by value descending
+ const rootLinks = data.links
+ .filter(link => link.source === 0)
+ .sort((a, b) => b.value - a.value);
+
+ const topLinks = rootLinks.slice(0, topN - 1);
+ const otherLinks = rootLinks.slice(topN - 1);
+ const otherTotal = otherLinks.reduce((sum, link) => sum + link.value, 0);
+
+ // Add top category nodes and their links from root
+ for (const link of topLinks) {
+ compactedData.nodes.push(data.nodes[link.target]);
+ compactedData.links.push({
+ source: 0,
+ target: compactedData.nodes.length - 1,
+ value: link.value,
+ });
+ }
+
+ // Lump remaining categories into a single "Other" node
+ if (otherTotal > 0) {
+ compactedData.nodes.push({ name: 'Other' });
+ compactedData.links.push({
+ source: 0,
+ target: compactedData.nodes.length - 1,
+ value: otherTotal,
+ tooltipInfo: otherLinks.map(link => ({
+ name: data.nodes[link.target].name,
+ value: link.value,
+ })),
+ });
+ }
+
+ return compactedData;
+}
diff --git a/packages/desktop-client/src/components/settings/Experimental.tsx b/packages/desktop-client/src/components/settings/Experimental.tsx
index 5d5709e53c..8a709d7747 100644
--- a/packages/desktop-client/src/components/settings/Experimental.tsx
+++ b/packages/desktop-client/src/components/settings/Experimental.tsx
@@ -196,7 +196,12 @@ export function ExperimentalFeatures() {
>
<Trans>Currency support</Trans>
</FeatureToggle>
-
+ <FeatureToggle
+ flag="sankeyReport"
+ feedbackLink="https://github.com/actualbudget/actual/issues/1919"
+ >
+ <Trans>Sankey report</Trans>
+ </FeatureToggle>
<FeatureToggle
flag="crossoverReport"
feedbackLink="https://github.com/actualbudget/actual/issues/6134"
diff --git a/packages/desktop-client/src/hooks/useFeatureFlag.ts b/packages/desktop-client/src/hooks/useFeatureFlag.ts
index 0e0e3436cc..643eabf2a2 100644
--- a/packages/desktop-client/src/hooks/useFeatureFlag.ts
+++ b/packages/desktop-client/src/hooks/useFeatureFlag.ts
@@ -12,6 +12,7 @@ const DEFAULT_FEATURE_FLAG_STATE: Record<FeatureFlag, boolean> = {
customThemes: false,
budgetAnalysisReport: false,
payeeLocations: false,
+ sankeyReport: false,
};
export function useFeatureFlag(name: FeatureFlag): boolean {
diff --git a/packages/loot-core/src/server/dashboard/app.ts b/packages/loot-core/src/server/dashboard/app.ts
index 4b8901dded..6bb450c63b 100644
--- a/packages/loot-core/src/server/dashboard/app.ts
+++ b/packages/loot-core/src/server/dashboard/app.ts
@@ -40,6 +40,7 @@ function isWidgetType(type: string): type is DashboardWidgetEntity['type'] {
'calendar-card',
'formula-card',
'custom-report',
+ 'sankey-card',
].includes(type);
}
diff --git a/packages/loot-core/src/types/models/dashboard.ts b/packages/loot-core/src/types/models/dashboard.ts
index 594f27630a..a3eec2e969 100644
--- a/packages/loot-core/src/types/models/dashboard.ts
+++ b/packages/loot-core/src/types/models/dashboard.ts
@@ -114,13 +114,13 @@ type SpecializedWidget =
| MarkdownWidget
| SummaryWidget
| CalendarWidget
- | FormulaWidget;
+ | FormulaWidget
+ | SankeyWidget;
export type DashboardWidgetEntity = SpecializedWidget | CustomReportWidget;
export type NewDashboardWidgetEntity = Omit<
DashboardWidgetEntity,
'id' | 'tombstone' | 'dashboard_page_id'
>;
-
// Exported/imported (json) widget definition
export type ExportImportCustomReportWidget = Omit<
CustomReportWidget,
@@ -197,3 +197,16 @@ export type FormulaWidget = AbstractWidget<
>;
} | null
>;
+
+export type SankeyWidget = AbstractWidget<
+ 'sankey-card',
+ {
+ name?: string;
+ conditions?: RuleConditionEntity[];
+ conditionsOp?: 'and' | 'or';
+ timeFrame?: TimeFrame;
+ mode?: 'budgeted' | 'spent';
+ topNcategories?: number;
+ categorySort?: 'per-group' | 'global' | 'budget-order';
+ } | null
+>;
diff --git a/packages/loot-core/src/types/prefs.ts b/packages/loot-core/src/types/prefs.ts
index 6d47b3e0b0..4bc02d92e9 100644
--- a/packages/loot-core/src/types/prefs.ts
+++ b/packages/loot-core/src/types/prefs.ts
@@ -7,7 +7,8 @@ export type FeatureFlag =
| 'crossoverReport'
| 'customThemes'
| 'budgetAnalysisReport'
- | 'payeeLocations';
+ | 'payeeLocations'
+ | 'sankeyReport';
/**
* Cross-device preferences. These sync across devices when they are changed.
diff --git a/upcoming-release-notes/7220.md b/upcoming-release-notes/7220.md
new file mode 100644
index 0000000000..96557a7494
--- /dev/null
+++ b/upcoming-release-notes/7220.md
@@ -0,0 +1,6 @@
+---
+category: Features
+authors: [emiltb, andrewhumble]
+---
+
+Add Sankey diagram report with two view modes (spent and budgeted) to visualize money flow through categories