A local-first personal finance app
Add option to show transfers in Sankey chart Spent view (#8780)
Emil Tveden Bjerglund766cc8a7244c
diff --git a/packages/desktop-client/src/components/reports/reports/Sankey.tsx b/packages/desktop-client/src/components/reports/reports/Sankey.tsxindex ed0ca8f0b3..7e8371e602 100644--- a/packages/desktop-client/src/components/reports/reports/Sankey.tsx+++ b/packages/desktop-client/src/components/reports/reports/Sankey.tsx@@ -375,6 +375,8 @@ type OptionsButtonProps = {onTogglePercentages: () => void;groupAccounts: boolean;onToggleGroupAccounts: () => void;+ showTransfers: boolean;+ onToggleShowTransfers: () => void;};function OptionsButton({@@ -382,6 +384,8 @@ function OptionsButton({onTogglePercentages,groupAccounts,onToggleGroupAccounts,+ showTransfers,+ onToggleShowTransfers,}: OptionsButtonProps) {const { t } = useTranslation();const triggerRef = useRef<HTMLButtonElement | null>(null);@@ -401,6 +405,7 @@ function OptionsButton({onMenuSelect={item => {if (item === 'show-percentages') onTogglePercentages();if (item === 'group-accounts') onToggleGroupAccounts();+ if (item === 'show-transfers') onToggleShowTransfers();}}items={[{@@ -413,6 +418,11 @@ function OptionsButton({text: t('Group accounts in Spent view'),toggle: groupAccounts,},+ {+ name: 'show-transfers',+ text: t('Show transfers in Spent view'),+ toggle: showTransfers,+ },]}/></Popover>@@ -505,6 +515,9 @@ function SankeyInner({ widget }: SankeyInnerProps) {const [groupAccounts, setGroupAccounts] = useState(widget?.meta?.groupAccounts ?? false,);+ const [showTransfers, setShowTransfers] = useState(+ widget?.meta?.showTransfers ?? false,+ );const [layerRange, setLayerRange] = useState<LayerRange>(() =>normalizeLayerRange(widget?.meta?.mode ?? 'spent', {@@ -576,6 +589,7 @@ function SankeyInner({ widget }: SankeyInnerProps) {conditionsOp,graphMode,groupAccounts,+ showTransfers,);}, [datesInitialized,@@ -586,6 +600,7 @@ function SankeyInner({ widget }: SankeyInnerProps) {conditionsOp,graphMode,groupAccounts,+ showTransfers,]);const defaultGetBaseGraph = async (@@ -710,6 +725,7 @@ function SankeyInner({ widget }: SankeyInnerProps) {topNcategories,categorySort,showPercentages,+ showTransfers,layerFrom,layerTo,timeFrame: {@@ -883,6 +899,8 @@ function SankeyInner({ widget }: SankeyInnerProps) {onTogglePercentages={() => setShowPercentages(v => !v)}groupAccounts={groupAccounts}onToggleGroupAccounts={() => setGroupAccounts(v => !v)}+ showTransfers={showTransfers}+ onToggleShowTransfers={() => setShowTransfers(v => !v)}/></View>{widget && (diff --git a/packages/desktop-client/src/components/reports/reports/SankeyCard.tsx b/packages/desktop-client/src/components/reports/reports/SankeyCard.tsxindex 0ba45fb181..1a485bff81 100644--- a/packages/desktop-client/src/components/reports/reports/SankeyCard.tsx+++ b/packages/desktop-client/src/components/reports/reports/SankeyCard.tsx@@ -103,6 +103,7 @@ export function SankeyCard({meta?.conditionsOp ?? 'and',mode,groupAccounts,+ meta?.showTransfers ?? false,),[start,@@ -112,6 +113,7 @@ export function SankeyCard({meta?.conditionsOp,mode,groupAccounts,+ meta?.showTransfers,],);const defaultGetBaseGraph = async (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.tsindex 792ab848dc..d0db15b879 100644--- a/packages/desktop-client/src/components/reports/spreadsheets/sankey-spreadsheet.test.ts+++ b/packages/desktop-client/src/components/reports/spreadsheets/sankey-spreadsheet.test.ts@@ -2,9 +2,11 @@ import type { RuleConditionEntity } from '@actual-app/core/types/models';import { describe, expect, it, vi } from 'vitest';import {+ addHiddenNodes,addNode,addPercentageLabels,addValueToLink,+ aggregateTransferPairs,buildSankeyData,cleanUpNodes,convertToSankeyData,@@ -133,6 +135,39 @@ describe('sankey-spreadsheet', () => {expect(getLayer(graph, 'child')).toBe(1);expect(getLayer(graph, 'grandchild')).toBe(2);});++ it('does not recurse infinitely when links form a cycle', () => {+ const graph: Graph = new Map();+ addNode(graph, 'account-a', GraphLayers.Account, 'Account A');+ addNode(graph, 'account-b', GraphLayers.Account, 'Account B');+ addValueToLink(graph, 'account-a', 'account-b', 100);+ addValueToLink(graph, 'account-b', 'account-a', 80);++ expect(() => getLayer(graph, 'account-a')).not.toThrow();+ expect(() => getLayer(graph, 'account-b')).not.toThrow();+ expect(Number.isFinite(getLayer(graph, 'account-a'))).toBe(true);+ expect(Number.isFinite(getLayer(graph, 'account-b'))).toBe(true);+ });++ it('uses a shared cache consistently across query orders for cyclic nodes', () => {+ const graph: Graph = new Map();+ addNode(graph, 'account-a', GraphLayers.Account, 'Account A');+ addNode(graph, 'account-b', GraphLayers.Account, 'Account B');+ addValueToLink(graph, 'account-a', 'account-b', 100);+ addValueToLink(graph, 'account-b', 'account-a', 80);++ const cacheFromAB = new Map<string, number>();+ getLayer(graph, 'account-a', cacheFromAB);+ getLayer(graph, 'account-b', cacheFromAB);++ const cacheFromBA = new Map<string, number>();+ getLayer(graph, 'account-b', cacheFromBA);+ getLayer(graph, 'account-a', cacheFromBA);++ expect(cacheFromAB.get('account-a')).toBe(cacheFromBA.get('account-a'));+ expect(cacheFromAB.get('account-b')).toBe(cacheFromBA.get('account-b'));+ expect(cacheFromAB.get('account-a')).toBe(cacheFromAB.get('account-b'));+ });});describe('nodesInLayer', () => {@@ -572,6 +607,72 @@ describe('sankey-spreadsheet', () => {});});+ describe('aggregateTransferPairs', () => {+ it('keeps transfer direction when source account id sorts after destination', () => {+ const transferPairs = aggregateTransferPairs([+ {+ id: 'tx-1',+ transfer_id: 'tx-2',+ accountId: 'z-account',+ accountName: 'Z Account',+ amount: -125,+ },+ {+ id: 'tx-2',+ transfer_id: 'tx-1',+ accountId: 'a-account',+ accountName: 'A Account',+ amount: 125,+ },+ ]);++ expect(transferPairs).toEqual([+ {+ fromAccountId: 'z-account',+ fromAccountName: 'Z Account',+ toAccountId: 'a-account',+ toAccountName: 'A Account',+ amount: 125,+ },+ ]);+ });++ it('nets reciprocal transfers and omits zero-value pairs', () => {+ const transferPairs = aggregateTransferPairs([+ {+ id: 'tx-1',+ transfer_id: 'tx-2',+ accountId: 'a-account',+ accountName: 'A Account',+ amount: -100,+ },+ {+ id: 'tx-2',+ transfer_id: 'tx-1',+ accountId: 'z-account',+ accountName: 'Z Account',+ amount: 100,+ },+ {+ id: 'tx-3',+ transfer_id: 'tx-4',+ accountId: 'z-account',+ accountName: 'Z Account',+ amount: -100,+ },+ {+ id: 'tx-4',+ transfer_id: 'tx-3',+ accountId: 'a-account',+ accountName: 'A Account',+ amount: 100,+ },+ ]);++ expect(transferPairs).toEqual([]);+ });+ });+describe('sortGraph', () => {it('sorts by global value when mode is global', () => {const graph: Graph = new Map();@@ -652,24 +753,42 @@ describe('sankey-spreadsheet', () => {expect(node2?.percentageLabel).toBe('75.0%');});- it('normalizes percentages per GraphLayer, not computed depth', () => {+ it('normalizes percentages per computed graph layer', () => {const graph: Graph = new Map();- addNode(graph, 'payee', GraphLayers.IncomePayee, 'Payee');- addNode(graph, 'income-cat', GraphLayers.IncomeCategory, 'Income Cat');- addNode(graph, 'account-incoming', GraphLayers.Account, 'Account A');-- addNode(graph, 'account-root', GraphLayers.Account, 'Account B');+ addNode(graph, 'account-root', GraphLayers.Account, 'Account A');+ addNode(graph, 'account-transfer', GraphLayers.Account, 'Account B');addNode(graph, 'group', GraphLayers.CategoryGroup, 'Group');+ addNode(graph, 'category', GraphLayers.Category, 'Category');- addValueToLink(graph, 'payee', 'income-cat', 300);- addValueToLink(graph, 'income-cat', 'account-incoming', 300);+ addValueToLink(graph, 'account-root', 'account-transfer', 300);addValueToLink(graph, 'account-root', 'group', 100);+ addValueToLink(graph, 'group', 'category', 100);++ addHiddenNodes(graph);addPercentageLabels(graph);- expect(graph.get('account-root')?.percentageLabel).toBe('25.0%');- expect(graph.get('account-incoming')?.percentageLabel).toBe('75.0%');+ const percentagesByLayer = new Map<number, number>();++ for (const [key, node] of graph) {+ if (key.endsWith('__HIDDEN') || !node.percentageLabel) {+ continue;+ }++ const layer = getLayer(graph, key);+ const percentage = Number.parseFloat(node.percentageLabel);+ percentagesByLayer.set(+ layer,+ (percentagesByLayer.get(layer) ?? 0) + percentage,+ );+ }++ expect(percentagesByLayer.size).toBeGreaterThan(0);++ for (const total of percentagesByLayer.values()) {+ expect(total).toBeCloseTo(100, 1);+ }});});@@ -773,6 +892,31 @@ describe('sankey-spreadsheet', () => {expect(nodeKeys).toContain('group-no-child_category__HIDDEN');expect(nodeKeys).not.toContain('group-no-child_category_group__HIDDEN');});++ it('keeps category groups after all account sublayers when transfers exist', () => {+ const graph: Graph = new Map();++ addNode(graph, 'account-root', GraphLayers.Account, 'Account A');+ addNode(graph, 'account-transfer', GraphLayers.Account, 'Account B');+ addNode(graph, 'group', GraphLayers.CategoryGroup, 'Group');+ addNode(graph, 'category', GraphLayers.Category, 'Category');++ addValueToLink(graph, 'account-root', 'account-transfer', 300);+ addValueToLink(graph, 'account-root', 'group', 100);+ addValueToLink(graph, 'group', 'category', 100);++ const sankeyData = buildSankeyData(+ graph,+ 100,+ [],+ 'global',+ GraphLayers.Account,+ GraphLayers.Category,+ );++ const nodeKeys = sankeyData.nodes.map(node => node.key);+ expect(nodeKeys).toContain('group_account_1__HIDDEN');+ });});describe('convertToSankeyData', () => {diff --git a/packages/desktop-client/src/components/reports/spreadsheets/sankey-spreadsheet.ts b/packages/desktop-client/src/components/reports/spreadsheets/sankey-spreadsheet.tsindex 2f404c8529..8fa3bdde89 100644--- a/packages/desktop-client/src/components/reports/spreadsheets/sankey-spreadsheet.ts+++ b/packages/desktop-client/src/components/reports/spreadsheets/sankey-spreadsheet.ts@@ -81,6 +81,22 @@ type CategoryEntry = {payeeId?: string;};+type TransferEntry = {+ accountId: string;+ accountName: string;+ amount: number;+ id: string;+ transfer_id: string;+};++type TransferPair = {+ fromAccountId: string;+ fromAccountName: string;+ toAccountId: string;+ toAccountName: string;+ amount: number;+};+type SortMode = 'per-group' | 'global' | 'budget-order';type NodeKey = string;@@ -97,6 +113,7 @@ export type NodeData = {color?: string;};export type Graph = Map<NodeKey, NodeData>;+type VisualLayerIndex = number;type TooltipInfoMap = Map<NodeKey,@@ -151,6 +168,7 @@ export function createBaseGraphSpreadsheet(conditionsOp: 'and' | 'or' = 'and',mode: 'budgeted' | 'spent' = 'spent',groupAccounts: boolean = false,+ showTransfers: boolean = false,) {return async (_spreadsheet: ReturnType<typeof useSpreadsheet>,@@ -164,6 +182,7 @@ export function createBaseGraphSpreadsheet(conditionsOp,mode,groupAccounts,+ showTransfers,);setData(baseGraph);@@ -178,9 +197,11 @@ async function createBaseGraph(conditionsOp: 'and' | 'or' = 'and',mode: 'budgeted' | 'spent' = 'spent',groupAccounts: boolean = false,+ showTransfers: boolean = false,): Promise<Graph> {let data: CategoryEntry[] = [];let aggregated: AggregatedBudget | undefined;+ let transferData: TransferPair[] | undefined;if (mode === 'budgeted') {({ data, aggregated } = await createBudgetSpreadsheet(@@ -190,19 +211,22 @@ async function createBaseGraph(conditionsOp,)());} else if (mode === 'spent') {- data = await createTransactionsSpreadsheet(+ const res = await createTransactionsSpreadsheet(start,end,categories,conditions,conditionsOp,groupAccounts,+ showTransfers,)();+ data = res.data;+ transferData = res.transferData;}return aggregated? createBudgetGraph(data, aggregated)- : createTransactionsGraph(data);+ : createTransactionsGraph(data, transferData, groupAccounts);}export function buildSankeyData(@@ -221,10 +245,10 @@ export function buildSankeyData(categorySort,);const sortedGraph = sortGraph(graph, categorySort, categories);- addPercentageLabels(sortedGraph);- addColors(sortedGraph);cleanUpNodes(sortedGraph);addHiddenNodes(sortedGraph);+ addPercentageLabels(sortedGraph);+ addColors(sortedGraph);filterGraphByLayers(sortedGraph, layerFrom, layerTo);return convertToSankeyData(sortedGraph, toolTipInfoMap);@@ -352,6 +376,7 @@ export function createTransactionsSpreadsheet(conditions: RuleConditionEntity[] = [],conditionsOp: 'and' | 'or' = 'and',groupAccounts: boolean,+ showTransfers: boolean,) {return async () => {// gather filters user has set@@ -369,7 +394,17 @@ export function createTransactionsSpreadsheet(groupAccounts,);- return categoryData;+ let transferData: TransferPair[] = [];+ if (showTransfers) {+ transferData = await fetchTransferData(+ conditionsOpKey,+ filters,+ start,+ end,+ );+ }++ return { data: categoryData, transferData };};}@@ -566,6 +601,97 @@ async function fetchCategoryData(return allCategoryData;}+// Fetch transactions that are transfers within the provided month range+async function fetchTransferData(+ conditionsOpKey: string = '$and',+ filters: unknown[] = [],+ start: string,+ end: string,+): Promise<TransferPair[]> {+ const results = await aqlQuery(+ q('transactions')+ .filter({ [conditionsOpKey]: filters })+ .filter({+ $and: [+ { date: { $gte: monthUtils.firstDayOfMonth(start) } },+ { date: { $lte: monthUtils.lastDayOfMonth(end) } },+ ],+ })+ .filter({ transfer_id: { $ne: null }, 'account.offbudget': false })+ .select([+ { id: 'id' },+ { amount: 'amount' },+ { accountId: { $id: '$account.id' } },+ { accountName: { $id: '$account.name' } },+ { transfer_id: 'transfer_id' },+ ]),+ );++ const raw_results: TransferEntry[] = results.data.map(+ (row: {+ id?: string;+ amount?: number;+ accountId?: string;+ accountName?: string;+ transfer_id?: string;+ }) =>+ ({+ id: row.id ?? '',+ amount: row.amount ?? 0,+ accountId: row.accountId ?? '',+ accountName: row.accountName ?? '',+ transfer_id: row.transfer_id ?? '',+ }) satisfies TransferEntry,+ );++ return aggregateTransferPairs(raw_results);+}++export function aggregateTransferPairs(+ rawResults: TransferEntry[],+): TransferPair[] {+ const byId = new Map<string, TransferEntry>();+ const byAccountId = new Map<string, string>();++ rawResults.forEach((transfer: TransferEntry) => {+ byId.set(String(transfer.id), transfer);+ byAccountId.set(String(transfer.accountId), transfer.accountName);+ });++ const resultPairs = new Map<string, number>();++ rawResults.forEach((from: TransferEntry) => {+ const to = byId.get(String(from.transfer_id));+ if (!to) return;++ if (from.accountId > to.accountId) return;++ const [accountId1, accountId2] = [from.accountId, to.accountId].sort();+ const pairKey = `${accountId1}|${accountId2}`;+ const sourceAccountId = from.amount < 0 ? from.accountId : to.accountId;+ const sign = sourceAccountId === accountId1 ? 1 : -1;+ const existingValue = resultPairs.get(pairKey) ?? 0;++ resultPairs.set(pairKey, existingValue + sign * Math.abs(from.amount));+ });++ return Array.from(resultPairs.entries())+ .filter(([, value]) => value !== 0)+ .map(([key, value]) => {+ const [accountId1, accountId2] = key.split('|');+ const fromAccountId = value > 0 ? accountId1 : accountId2;+ const toAccountId = value > 0 ? accountId2 : accountId1;++ return {+ fromAccountId,+ fromAccountName: byAccountId.get(fromAccountId) || '',+ toAccountId,+ toAccountName: byAccountId.get(toAccountId) || '',+ amount: Math.abs(value),+ };+ }) satisfies TransferPair[];+}+export function createBudgetGraph(categoryData: CategoryEntry[],aggregated: AggregatedBudget,@@ -729,7 +855,11 @@ export function createBudgetGraph(return graph;}-export function createTransactionsGraph(categoryData: CategoryEntry[]): Graph {+export function createTransactionsGraph(+ categoryData: CategoryEntry[],+ transferData?: TransferPair[],+ groupAccounts?: boolean,+): Graph {function addAccountNode(accountId: string, accountName: string): void {if (accountId === SpecialNodeKeys.AllAccounts) {addNodeWithLabel(@@ -833,6 +963,17 @@ export function createTransactionsGraph(categoryData: CategoryEntry[]): Graph {}}});++ // If transfer data is provided, add links between accounts representing transfers.+ // Pair transactions strictly by transfer_id === id.+ if (transferData && transferData.length > 0 && !groupAccounts) {+ transferData.forEach((pair: TransferPair) => {+ addAccountNode(pair.fromAccountId, pair.fromAccountName);+ addAccountNode(pair.toAccountId, pair.toAccountName);+ addValueToLink(graph, pair.fromAccountId, pair.toAccountId, pair.amount);+ });+ }+return graph;}@@ -882,20 +1023,167 @@ export function addValueToLink(}}-export function getLayer(graph: Graph, key: NodeKey): number {- // Find parent nodes for the given key- const parents: NodeKey[] = [];- for (const [parentKey, data] of graph) {- if (data.to.has(key)) {- parents.push(parentKey);- }+export function getLayer(+ graph: Graph,+ key: NodeKey,+ layerCache?: Map<NodeKey, VisualLayerIndex>,+): number {+ const resolvedLayerCache = layerCache ?? new Map<NodeKey, VisualLayerIndex>();++ const cachedLayer = resolvedLayerCache.get(key);+ if (cachedLayer !== undefined) {+ return cachedLayer;}- if (parents.length === 0) {- // No parents: this is a root node, layer 0++ if (!graph.has(key)) {+ resolvedLayerCache.set(key, 0);return 0;}- // Otherwise, 1 + max parent's layer- return 1 + Math.max(...parents.map(parentKey => getLayer(graph, parentKey)));++ const computedLayers = getLayersByStronglyConnectedComponents(graph);+ computedLayers.forEach((layer, nodeKey) => {+ resolvedLayerCache.set(nodeKey, layer);+ });++ return resolvedLayerCache.get(key) ?? 0;+}++function getLayersByStronglyConnectedComponents(+ graph: Graph,+): Map<NodeKey, VisualLayerIndex> {+ const visitedIndex = new Map<NodeKey, number>();+ const lowlink = new Map<NodeKey, number>();+ const stack: NodeKey[] = [];+ const activeStack = new Set<NodeKey>();+ const componentByNode = new Map<NodeKey, number>();+ const components: NodeKey[][] = [];+ let index = 0;++ function strongConnect(nodeKey: NodeKey) {+ visitedIndex.set(nodeKey, index);+ lowlink.set(nodeKey, index);+ index += 1;+ stack.push(nodeKey);+ activeStack.add(nodeKey);++ const node = graph.get(nodeKey);+ if (node) {+ for (const childKey of node.to.keys()) {+ if (!graph.has(childKey)) {+ continue;+ }++ if (!visitedIndex.has(childKey)) {+ strongConnect(childKey);+ lowlink.set(+ nodeKey,+ Math.min(lowlink.get(nodeKey) ?? 0, lowlink.get(childKey) ?? 0),+ );+ } else if (activeStack.has(childKey)) {+ lowlink.set(+ nodeKey,+ Math.min(+ lowlink.get(nodeKey) ?? 0,+ visitedIndex.get(childKey) ?? 0,+ ),+ );+ }+ }+ }++ if (lowlink.get(nodeKey) === visitedIndex.get(nodeKey)) {+ const componentIndex = components.length;+ const componentNodes: NodeKey[] = [];++ let poppedNode: NodeKey | undefined;+ do {+ poppedNode = stack.pop();+ if (!poppedNode) {+ break;+ }++ activeStack.delete(poppedNode);+ componentByNode.set(poppedNode, componentIndex);+ componentNodes.push(poppedNode);+ } while (poppedNode !== nodeKey);++ components.push(componentNodes);+ }+ }++ for (const nodeKey of graph.keys()) {+ if (!visitedIndex.has(nodeKey)) {+ strongConnect(nodeKey);+ }+ }++ const parentsByComponent = new Map<number, Set<number>>();+ for (+ let componentIndex = 0;+ componentIndex < components.length;+ componentIndex += 1+ ) {+ parentsByComponent.set(componentIndex, new Set());+ }++ for (const [sourceKey, sourceNode] of graph) {+ const sourceComponent = componentByNode.get(sourceKey);+ if (sourceComponent === undefined) {+ continue;+ }++ for (const targetKey of sourceNode.to.keys()) {+ const targetComponent = componentByNode.get(targetKey);+ if (+ targetComponent === undefined ||+ targetComponent === sourceComponent+ ) {+ continue;+ }++ parentsByComponent.get(targetComponent)?.add(sourceComponent);+ }+ }++ const layerByComponent = new Map<number, VisualLayerIndex>();+ function resolveComponentLayer(componentIndex: number): VisualLayerIndex {+ const cachedComponentLayer = layerByComponent.get(componentIndex);+ if (cachedComponentLayer !== undefined) {+ return cachedComponentLayer;+ }++ const parents = parentsByComponent.get(componentIndex);+ if (!parents || parents.size === 0) {+ layerByComponent.set(componentIndex, 0);+ return 0;+ }++ const layer =+ 1 + Math.max(...Array.from(parents).map(resolveComponentLayer));+ layerByComponent.set(componentIndex, layer);+ return layer;+ }++ const layerByNode = new Map<NodeKey, VisualLayerIndex>();+ for (const [nodeKey, componentIndex] of componentByNode) {+ layerByNode.set(nodeKey, resolveComponentLayer(componentIndex));+ }++ return layerByNode;+}++function getComputedNodeLayers(graph: Graph): Map<NodeKey, VisualLayerIndex> {+ const layerCache = new Map<NodeKey, VisualLayerIndex>();++ for (const key of graph.keys()) {+ getLayer(graph, key, layerCache);+ }++ return layerCache;+}++function isHiddenNodeKey(key: NodeKey): boolean {+ return key.endsWith(SpecialNodeKeys.HiddenSuffix);}function groupOtherCategories(@@ -1001,28 +1289,35 @@ function moveToOther(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,- );+ // Avoid creating self-links (otherKey -> otherKey) which produce+ // immediate cycles and can break recursive layer computation.+ if (fromKey !== otherKey) {+ 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,- );+ // Avoid creating self-links (otherKey -> otherKey)+ if (otherKey !== toKey) {+ addValueToLink(graph, otherKey, toKey, linkValue);+ newAddTooltipInfo(+ toolTipInfoMap,+ otherKey,+ toKey,+ graph.get(key)?.name ?? key,+ linkValue,+ );+ }}});@@ -1245,19 +1540,31 @@ export function moveNodeToStart(}}-export function getNodeValue(graph: Graph, key: NodeKey): number {+export function getNodeValue(+ graph: Graph,+ key: NodeKey,+ computedLayersByNode?: Map<NodeKey, VisualLayerIndex>,+): number {+ const resolvedLayersByNode =+ computedLayersByNode ?? getComputedNodeLayers(graph);let nodeValue: number = 0;- if (getLayer(graph, key) === 0) {+ if ((resolvedLayersByNode.get(key) ?? 0) === 0) {// Look at outgoing links for root nodesconst node = graph.get(key);if (node) {- node.to.forEach(value => {+ node.to.forEach((value, targetKey) => {+ if (isHiddenNodeKey(targetKey)) {+ return;+ }nodeValue += value ?? 0;});}} else {- graph.forEach(data => {+ graph.forEach((data, sourceKey) => {+ if (isHiddenNodeKey(sourceKey)) {+ return;+ }nodeValue += data.to.get(key) ?? 0;});@@ -1266,7 +1573,10 @@ export function getNodeValue(graph: Graph, key: NodeKey): number {nodeValue = 0;const node = graph.get(key);if (node) {- node.to.forEach(value => {+ node.to.forEach((value, targetKey) => {+ if (isHiddenNodeKey(targetKey)) {+ return;+ }nodeValue += value;});}@@ -1276,22 +1586,38 @@ export function getNodeValue(graph: Graph, key: NodeKey): number {}export function addPercentageLabels(graph: Graph): void {- const layerSums = new Map<GraphLayers, number>();+ const layerSums = new Map<VisualLayerIndex, number>();+ const computedLayersByNode = getComputedNodeLayers(graph);- // First pass: calculate GraphLayer sums+ // First pass: calculate visual-layer sumsgraph.forEach((_: NodeData, key: NodeKey) => {- const layer = graph.get(key)?.type;- if (!layer) {+ if (isHiddenNodeKey(key)) {+ return;+ }++ const layer = computedLayersByNode.get(key);+ if (layer === undefined) {return;}- const nodeValue = getNodeValue(graph, key);++ const nodeValue = getNodeValue(graph, key, computedLayersByNode);layerSums.set(layer, (layerSums.get(layer) ?? 0) + nodeValue);});// Second pass: assign percentage label to each nodegraph.forEach((data: NodeData, key: NodeKey) => {- const layer = data.type;- const nodeValue = getNodeValue(graph, key);+ if (isHiddenNodeKey(key)) {+ data.percentageLabel = undefined;+ return;+ }++ const layer = computedLayersByNode.get(key);+ if (layer === undefined) {+ data.percentageLabel = undefined;+ return;+ }++ const nodeValue = getNodeValue(graph, key, computedLayersByNode);const layerTotal = layerSums.get(layer) ?? 1;const percentage = layerTotal ? (nodeValue / layerTotal) * 100 : 0;data.percentageLabel = `${percentage.toFixed(1)}%`;@@ -1336,7 +1662,7 @@ function setColor(graph: Graph, key: NodeKey, color: string) {}}-function addHiddenNodes(graph: Graph) {+export 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.@@ -1423,6 +1749,88 @@ function addHiddenNodes(graph: Graph) {}}}++ ensureCategoryGroupsFollowAccountLayers(graph);+}++function ensureCategoryGroupsFollowAccountLayers(graph: Graph) {+ let computedLayersByNode = getComputedNodeLayers(graph);++ let maxVisibleAccountLayer = -1;+ for (const [key, node] of graph) {+ if (node.type !== GraphLayers.Account || isHiddenNodeKey(key)) {+ continue;+ }++ const nodeLayer = computedLayersByNode.get(key);+ if (nodeLayer !== undefined && nodeLayer > maxVisibleAccountLayer) {+ maxVisibleAccountLayer = nodeLayer;+ }+ }++ if (maxVisibleAccountLayer < 0) {+ return;+ }++ const categoryGroupsToPush: NodeKey[] = [];+ for (const [key, node] of graph) {+ if (node.type !== GraphLayers.CategoryGroup) {+ continue;+ }++ const nodeLayer = computedLayersByNode.get(key);+ if (nodeLayer !== undefined && nodeLayer <= maxVisibleAccountLayer) {+ categoryGroupsToPush.push(key);+ }+ }++ for (const key of categoryGroupsToPush) {+ let currentLayer = computedLayersByNode.get(key);+ while (+ currentLayer !== undefined &&+ currentLayer <= maxVisibleAccountLayer+ ) {+ const deepestParent = getDeepestParentKey(+ graph,+ key,+ computedLayersByNode,+ );+ if (!deepestParent) {+ break;+ }++ const hiddenParentKey = `${key}_${GraphLayers.Account}_${currentLayer}${SpecialNodeKeys.HiddenSuffix}`;+ addNode(graph, hiddenParentKey, GraphLayers.Account, '');+ addValueToLink(graph, deepestParent, hiddenParentKey, -1);+ addValueToLink(graph, hiddenParentKey, key, -1);++ computedLayersByNode = getComputedNodeLayers(graph);+ currentLayer = computedLayersByNode.get(key);+ }+ }+}++function getDeepestParentKey(+ graph: Graph,+ nodeKey: NodeKey,+ computedLayersByNode: Map<NodeKey, VisualLayerIndex>,+): NodeKey | undefined {+ let deepestParent: NodeKey | undefined;+ let deepestLayer = -Infinity;++ for (const [parentKey, data] of graph) {+ if (!data.to.has(nodeKey)) {+ continue;+ }++ const parentLayer = computedLayersByNode.get(parentKey);+ if (parentLayer !== undefined && parentLayer > deepestLayer) {+ deepestLayer = parentLayer;+ deepestParent = parentKey;+ }+ }++ return deepestParent;}function buildTypeConnectivity(diff --git a/packages/loot-core/src/types/models/dashboard.ts b/packages/loot-core/src/types/models/dashboard.tsindex 25550496f3..78d50efc49 100644--- a/packages/loot-core/src/types/models/dashboard.ts+++ b/packages/loot-core/src/types/models/dashboard.ts@@ -394,6 +394,7 @@ export type SankeyWidget = AbstractWidget<categorySort?: 'per-group' | 'global' | 'budget-order';showPercentages?: boolean;groupAccounts?: boolean;+ showTransfers?: boolean;layerFrom?: string;layerTo?: string;} | nulldiff --git a/upcoming-release-notes/sankey-add-transfers.md b/upcoming-release-notes/sankey-add-transfers.mdnew file mode 100644index 0000000000..25802cd0de--- /dev/null+++ b/upcoming-release-notes/sankey-add-transfers.md@@ -0,0 +1,6 @@+---+category: Features+authors: [emiltb]+---++Add option to show transfers in Sankey spent view