Open-source personal finance manager. Self-hosted, privacy-first.
feat(reports): add Money Map cashflow Sankey (#333)
Tássio Noronha3eae2eb19fa6
diff --git a/backend/app/services/report_service.py b/backend/app/services/report_service.pyindex 42bbee84..99a83d83 100644--- a/backend/app/services/report_service.py+++ b/backend/app/services/report_service.py@@ -684,6 +684,49 @@ async def get_income_expenses_report(if comp_map[comp_key]["value"] <= 0:comp_map.pop(comp_key)+ # Investment-style outflows: transactions in `treat_as_transfer` categories+ # are excluded from P&L by counts_as_user_pnl (an investment application's+ # counterpart is an Asset/Holding, not spending). But for the cashflow Sankey+ # we surface them as their own "investments" group — money set aside, distinct+ # from spending and from leftover surplus (mirrors how Sure shows an+ # "Investment Contributions" node). Paired account transfers stay excluded via+ # the transfer_pair_id filter, so only one-sided movements (contributions)+ # appear here.+ inv_result = await session.execute(+ select(+ Category.id,+ Category.name,+ Category.color,+ func.sum(amount_expr),+ )+ .select_from(Transaction)+ .join(Account, Transaction.account_id == Account.id)+ .join(Category, Transaction.category_id == Category.id)+ .where(+ Transaction.workspace_id == workspace_id,+ Account.is_closed == False,+ report_date >= start,+ report_date <= today,+ Transaction.source != "opening_balance",+ Transaction.type == "debit",+ Transaction.transfer_pair_id.is_(None),+ Transaction.is_ignored.is_(False),+ Category.treat_as_transfer.is_(True),+ Category.is_ignored.is_(False),+ *acct_filter,+ )+ .group_by(Category.id, Category.name, Category.color)+ )+ for cat_id, cat_name, cat_color, total_amount in inv_result.all():+ amount = abs(float(total_amount or 0))+ if amount <= 0:+ continue+ comp_map[(str(cat_id), "investments")] = {+ "label": cat_name or "Investments",+ "color": cat_color or "#0EA5E9",+ "value": amount,+ }+# Build per-category trend (sparklines) for the full date rangecat_trend_result = await session.execute(select(diff --git a/frontend/package-lock.json b/frontend/package-lock.jsonindex c39f1fc7..40f91eb5 100644--- a/frontend/package-lock.json+++ b/frontend/package-lock.json@@ -14,6 +14,7 @@"class-variance-authority": "^0.7.1","clsx": "^2.1.1","cmdk": "^1.1.1",+ "d3-sankey": "^0.12.3","date-fns": "^4.1.0","i18next": "^25.8.13","i18next-browser-languagedetector": "^8.2.1",@@ -38,6 +39,7 @@"devDependencies": {"@eslint/js": "^9.39.1","@tailwindcss/vite": "^4.2.1",+ "@types/d3-sankey": "^0.12.5","@types/node": "^24.10.13","@types/react": "^19.2.7","@types/react-dom": "^19.2.3",@@ -4371,6 +4373,33 @@"integrity": "sha512-VMZBYyQvbGmWyWVea0EHs/BwLgxc+MKi1zLDCONksozI4YJMcTt8ZEuIR4Sb1MMTE8MMW49v0IwI5+b7RmfWlg==","license": "MIT"},+ "node_modules/@types/d3-sankey": {+ "version": "0.12.5",+ "resolved": "https://registry.npmjs.org/@types/d3-sankey/-/d3-sankey-0.12.5.tgz",+ "integrity": "sha512-/3RZSew0cLAtzGQ+C89hq/Rp3H20QJuVRSqFy6RKLe7E0B8kd2iOS1oBsodrgds4PcNVpqWhdUEng/SHvBcJ6Q==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@types/d3-shape": "^1"+ }+ },+ "node_modules/@types/d3-sankey/node_modules/@types/d3-path": {+ "version": "1.0.11",+ "resolved": "https://registry.npmjs.org/@types/d3-path/-/d3-path-1.0.11.tgz",+ "integrity": "sha512-4pQMp8ldf7UaB/gR8Fvvy69psNHkTpD/pVw3vmEi8iZAB9EPMBruB1JvHO4BIq9QkUUd2lV1F5YXpMNj7JPBpw==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/@types/d3-sankey/node_modules/@types/d3-shape": {+ "version": "1.3.12",+ "resolved": "https://registry.npmjs.org/@types/d3-shape/-/d3-shape-1.3.12.tgz",+ "integrity": "sha512-8oMzcd4+poSLGgV0R1Q1rOlx/xdmozS4Xab7np0eamFFUYq71AU9pOCJEFnkXW2aI/oXdVYJzw6pssbSut7Z9Q==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@types/d3-path": "^1"+ }+ },"node_modules/@types/d3-scale": {"version": "4.0.9","resolved": "https://registry.npmjs.org/@types/d3-scale/-/d3-scale-4.0.9.tgz",@@ -5761,6 +5790,46 @@"node": ">=12"}},+ "node_modules/d3-sankey": {+ "version": "0.12.3",+ "resolved": "https://registry.npmjs.org/d3-sankey/-/d3-sankey-0.12.3.tgz",+ "integrity": "sha512-nQhsBRmM19Ax5xEIPLMY9ZmJ/cDvd1BG3UVvt5h3WRxKg5zGRbvnteTyWAbzeSvlh3tW7ZEmq4VwR5mB3tutmQ==",+ "license": "BSD-3-Clause",+ "dependencies": {+ "d3-array": "1 - 2",+ "d3-shape": "^1.2.0"+ }+ },+ "node_modules/d3-sankey/node_modules/d3-array": {+ "version": "2.12.1",+ "resolved": "https://registry.npmjs.org/d3-array/-/d3-array-2.12.1.tgz",+ "integrity": "sha512-B0ErZK/66mHtEsR1TkPEEkwdy+WDesimkM5gpZr5Dsg54BiTA5RXtYW5qTLIAcekaS9xfZrzBLF/OAkB3Qn1YQ==",+ "license": "BSD-3-Clause",+ "dependencies": {+ "internmap": "^1.0.0"+ }+ },+ "node_modules/d3-sankey/node_modules/d3-path": {+ "version": "1.0.9",+ "resolved": "https://registry.npmjs.org/d3-path/-/d3-path-1.0.9.tgz",+ "integrity": "sha512-VLaYcn81dtHVTjEHd8B+pbe9yHWpXKZUC87PzoFmsFrJqgFwDe/qxfp5MlfsfM1V5E/iVt0MmEbWQ7FVIXh/bg==",+ "license": "BSD-3-Clause"+ },+ "node_modules/d3-sankey/node_modules/d3-shape": {+ "version": "1.3.7",+ "resolved": "https://registry.npmjs.org/d3-shape/-/d3-shape-1.3.7.tgz",+ "integrity": "sha512-EUkvKjqPFUAZyOlhY5gzCxCeI0Aep04LwIRpsZ/mLFelJiUfnK56jo5JMDSE7yyP2kLSb6LtF+S5chMk7uqPqw==",+ "license": "BSD-3-Clause",+ "dependencies": {+ "d3-path": "1"+ }+ },+ "node_modules/d3-sankey/node_modules/internmap": {+ "version": "1.0.1",+ "resolved": "https://registry.npmjs.org/internmap/-/internmap-1.0.1.tgz",+ "integrity": "sha512-lDB5YccMydFBtasVtxnZ3MRBHuaoE8GKsppq+EchKL2U4nK/DmEpPHNH8MZe5HkMtpSiTSOZwfN0tzYjO/lJEw==",+ "license": "ISC"+ },"node_modules/d3-scale": {"version": "4.0.2","resolved": "https://registry.npmjs.org/d3-scale/-/d3-scale-4.0.2.tgz",diff --git a/frontend/package.json b/frontend/package.jsonindex 385fd12c..ea0e334c 100644--- a/frontend/package.json+++ b/frontend/package.json@@ -17,6 +17,7 @@"class-variance-authority": "^0.7.1","clsx": "^2.1.1","cmdk": "^1.1.1",+ "d3-sankey": "^0.12.3","date-fns": "^4.1.0","i18next": "^25.8.13","i18next-browser-languagedetector": "^8.2.1",@@ -41,6 +42,7 @@"devDependencies": {"@eslint/js": "^9.39.1","@tailwindcss/vite": "^4.2.1",+ "@types/d3-sankey": "^0.12.5","@types/node": "^24.10.13","@types/react": "^19.2.7","@types/react-dom": "^19.2.3",diff --git a/frontend/src/components/reports/CashflowSankey.tsx b/frontend/src/components/reports/CashflowSankey.tsxnew file mode 100644index 00000000..24ef3d06--- /dev/null+++ b/frontend/src/components/reports/CashflowSankey.tsx@@ -0,0 +1,480 @@+import { useEffect, useMemo, useRef, useState } from 'react'+import { useTranslation } from 'react-i18next'+import {+ sankey as d3Sankey,+ sankeyLinkHorizontal,+ sankeyJustify,+} from 'd3-sankey'+import { usePrivacyMode } from '@/hooks/use-privacy-mode'+import type { ReportCompositionItem } from '@/types'++// Colour carries MEANING, not category identity: green = money in, red = money+// out, gray = uncategorised/folded. Tinting by category (the old approach) made+// a green "Groceries" expense look like green "Salary" income — the direction of+// flow was invisible. Category identity is carried by the always-on labels+// instead. Links fade from their source colour to their target colour, so an+// expense flow visibly turns from green (cash flow) to red at the category.+const INCOME_COLOR = '#10B981' // emerald — money in+const EXPENSE_COLOR = '#F43F5E' // rose — money out+const INVEST_COLOR = '#0EA5E9' // sky blue — money set aside (investments)+const CENTER_COLOR = '#059669' // deeper emerald — the cash-flow hub+const SURPLUS_COLOR = '#10B981' // emerald — leftover income+const DEFICIT_COLOR = '#F59E0B' // amber — overspend drawn from reserves+const NEUTRAL_COLOR = '#9CA3AF' // gray — uncategorised / folded long tail++// Keep the diagram legible: personal-finance Sankeys read best at ~a dozen+// streams per side. Beyond this we fold the smallest categories into "Other".+const MAX_NODES_PER_SIDE = 9++const NODE_WIDTH = 16+const NODE_PADDING = 16+// Vertical space a two-line label (name + amount) needs; labels are pushed+// apart to at least this gap so thin adjacent nodes stay readable.+const LABEL_MIN_GAP = 26+const TOP_GUTTER = 30 // header room above the nodes for the centre label++interface SankeyNodeDatum {+ id: string+ name: string+ color: string+ side: 'income' | 'center' | 'expense' | 'investment'+}++interface SankeyLinkDatum {+ source: number+ target: number+ value: number+}++// What the cursor is isolating. A plain node hover lights its own flows; the+// two halves of the centre bar light *all* expenses or the surplus at once —+// the "show me everything I spent" gesture the single bar couldn't offer.+type Hover =+ | { kind: 'node'; index: number }+ | { kind: 'expenses' }+ | { kind: 'investments' }+ | { kind: 'surplus' }++function formatMoney(value: number, currency: string, locale: string, compact: boolean) {+ return new Intl.NumberFormat(locale, {+ style: 'currency',+ currency,+ notation: compact ? 'compact' : 'standard',+ maximumFractionDigits: compact ? 1 : 0,+ }).format(value)+}++/** Sort largest-first, then fold everything past the cap into a single "Other". */+function collapse(items: ReportCompositionItem[], otherLabel: string): ReportCompositionItem[] {+ const sorted = [...items].sort((a, b) => b.value - a.value)+ if (sorted.length <= MAX_NODES_PER_SIDE) return sorted+ const top = sorted.slice(0, MAX_NODES_PER_SIDE - 1)+ const rest = sorted.slice(MAX_NODES_PER_SIDE - 1)+ const otherValue = rest.reduce((s, c) => s + c.value, 0)+ return [+ ...top,+ { key: 'other', label: otherLabel, value: otherValue, color: NEUTRAL_COLOR, group: rest[0].group },+ ]+}++interface CashflowSankeyProps {+ composition: ReportCompositionItem[]+ currency: string+ locale: string+}++export function CashflowSankey({ composition, currency, locale }: CashflowSankeyProps) {+ const { t } = useTranslation()+ const { privacyMode, MASK } = usePrivacyMode()+ const containerRef = useRef<HTMLDivElement>(null)+ const [width, setWidth] = useState(0)+ const [hover, setHover] = useState<Hover | null>(null)++ useEffect(() => {+ const el = containerRef.current+ if (!el) return+ const observer = new ResizeObserver((entries) => {+ setWidth(entries[0].contentRect.width)+ })+ observer.observe(el)+ return () => observer.disconnect()+ }, [])++ const { nodes: rawNodes, links: rawLinks, hasData } = useMemo(() => {+ const income = collapse(+ composition.filter((c) => c.group === 'income' && c.value > 0),+ t('reports.other'),+ )+ const expense = collapse(+ composition.filter((c) => c.group === 'expenses' && c.value > 0),+ t('reports.other'),+ )+ // Investments are a third outflow lane — money set aside, neither spent nor+ // surplus. Treated like Sure's "Investment Contributions" node.+ const investment = collapse(+ composition.filter((c) => c.group === 'investments' && c.value > 0),+ t('reports.other'),+ )++ if (income.length === 0 && expense.length === 0 && investment.length === 0) {+ return { nodes: [] as SankeyNodeDatum[], links: [] as SankeyLinkDatum[], hasData: false }+ }++ const totalIncome = income.reduce((s, c) => s + c.value, 0)+ const totalExpense = expense.reduce((s, c) => s + c.value, 0)+ const totalInvest = investment.reduce((s, c) => s + c.value, 0)+ // Surplus is what's left after BOTH spending and investing — so investing+ // shrinks surplus instead of silently inflating it.+ const net = totalIncome - totalExpense - totalInvest++ const nodes: SankeyNodeDatum[] = []+ const links: SankeyLinkDatum[] = []+ const indexOf = new Map<string, number>()+ const pushNode = (n: SankeyNodeDatum) => {+ indexOf.set(n.id, nodes.length)+ nodes.push(n)+ return nodes.length - 1+ }++ const labelFor = (c: ReportCompositionItem) =>+ c.key === 'uncategorized' ? t('reports.uncategorized')+ : c.key === 'other' ? t('reports.other')+ : c.label+ const isNeutral = (c: ReportCompositionItem) => c.key === 'uncategorized' || c.key === 'other'++ income.forEach((c, i) =>+ pushNode({+ id: `in-${c.key}-${i}`,+ name: labelFor(c),+ color: isNeutral(c) ? NEUTRAL_COLOR : INCOME_COLOR,+ side: 'income',+ }),+ )++ // Deficit appears as an inflow on the income side so the centre balances.+ if (net < 0) {+ pushNode({ id: 'deficit', name: t('reports.deficit'), color: DEFICIT_COLOR, side: 'income' })+ }++ const centerIdx = pushNode({+ id: 'center',+ name: t('reports.cashFlowNode'),+ color: CENTER_COLOR,+ side: 'center',+ })++ // Right column, top → bottom: expenses (red), investments (teal), surplus+ // (green) — matching the centre bar's stacked split.+ expense.forEach((c, i) =>+ pushNode({+ id: `ex-${c.key}-${i}`,+ name: labelFor(c),+ color: isNeutral(c) ? NEUTRAL_COLOR : EXPENSE_COLOR,+ side: 'expense',+ }),+ )++ investment.forEach((c, i) =>+ pushNode({+ id: `inv-${c.key}-${i}`,+ name: c.key === 'other' ? t('reports.other') : c.label,+ color: c.key === 'other' ? NEUTRAL_COLOR : INVEST_COLOR,+ side: 'investment',+ }),+ )++ if (net > 0) {+ pushNode({ id: 'surplus', name: t('reports.surplus'), color: SURPLUS_COLOR, side: 'expense' })+ }++ income.forEach((c, i) =>+ links.push({ source: indexOf.get(`in-${c.key}-${i}`)!, target: centerIdx, value: c.value }),+ )+ if (net < 0) {+ links.push({ source: indexOf.get('deficit')!, target: centerIdx, value: -net })+ }+ expense.forEach((c, i) =>+ links.push({ source: centerIdx, target: indexOf.get(`ex-${c.key}-${i}`)!, value: c.value }),+ )+ investment.forEach((c, i) =>+ links.push({ source: centerIdx, target: indexOf.get(`inv-${c.key}-${i}`)!, value: c.value }),+ )+ if (net > 0) {+ links.push({ source: centerIdx, target: indexOf.get('surplus')!, value: net })+ }++ return { nodes, links, hasData: true }+ }, [composition, t])++ // Tall enough that the busier side's nodes don't crowd; grows with node count.+ const maxSide = useMemo(() => {+ const incomeCount = rawNodes.filter((n) => n.side === 'income').length+ const outflowCount = rawNodes.filter((n) => n.side === 'expense' || n.side === 'investment').length+ return Math.max(incomeCount, outflowCount, 1)+ }, [rawNodes])+ const height = Math.min(780, Math.max(380, maxSide * 60))++ const layout = useMemo(() => {+ if (!hasData || width === 0) return null+ const generator = d3Sankey<SankeyNodeDatum, SankeyLinkDatum>()+ .nodeWidth(NODE_WIDTH)+ .nodePadding(NODE_PADDING)+ .nodeAlign(sankeyJustify)+ .extent([+ [8, TOP_GUTTER],+ [width - 8, height - 14],+ ])+ // d3-sankey mutates its input — clone so re-renders stay pure.+ return generator({+ nodes: rawNodes.map((n) => ({ ...n })),+ links: rawLinks.map((l) => ({ ...l })),+ })+ }, [rawNodes, rawLinks, width, height, hasData])++ // Always-on labels: place each node's label and push overlapping neighbours+ // apart per column so even a 1px-tall node keeps a readable name + amount.+ const labelY = useMemo(() => {+ const pos = new Map<number, number>()+ if (!layout) return pos+ for (const left of [true, false]) {+ const column = layout.nodes+ .filter((n) => n.id !== 'center')+ .filter((n) => ((n.x0 ?? 0) < width / 2) === left)+ .sort((a, b) => ((a.y0! + a.y1!) / 2) - ((b.y0! + b.y1!) / 2))+ let prev = -Infinity+ for (const n of column) {+ let y = (n.y0! + n.y1!) / 2+ if (y < prev + LABEL_MIN_GAP) y = prev + LABEL_MIN_GAP+ pos.set((n as SankeyNodeDatum & { index: number }).index, y)+ prev = y+ }+ }+ return pos+ }, [layout, width])++ // Resolve the current hover into the exact set of links/nodes to keep lit.+ const { activeLinks, activeNodes } = useMemo(() => {+ const links = new Set<number>()+ const nodes = new Set<number>()+ if (layout && hover) {+ layout.links.forEach((lk, i) => {+ const s = lk.source as SankeyNodeDatum & { index: number }+ const tg = lk.target as SankeyNodeDatum & { index: number }+ let on = false+ if (hover.kind === 'node') on = s.index === hover.index || tg.index === hover.index+ else if (hover.kind === 'expenses') on = s.id === 'center' && tg.side === 'expense' && tg.id !== 'surplus'+ else if (hover.kind === 'investments') on = s.id === 'center' && tg.side === 'investment'+ else if (hover.kind === 'surplus') on = tg.id === 'surplus'+ if (on) {+ links.add(i)+ nodes.add(s.index)+ nodes.add(tg.index)+ }+ })+ }+ return { activeLinks: links, activeNodes: nodes }+ }, [layout, hover])++ if (!hasData) {+ return (+ <p className="text-muted-foreground text-sm text-center py-16">{t('reports.noData')}</p>+ )+ }++ const linkPath = sankeyLinkHorizontal<SankeyNodeDatum, SankeyLinkDatum>()+ // Percentages are relative to total cash-flow throughput — the centre node's+ // value (d3-sankey sets it to the larger of its in/out sums).+ const total = layout?.nodes.find((n) => n.id === 'center')?.value ?? 0+ const fmtAmount = (v: number) =>+ privacyMode ? MASK : formatMoney(v, currency, locale, true)++ // The centre bar's outflow split: spent (red) vs invested (teal) vs kept+ // (green). Links attach top→bottom in node order (expenses, investments,+ // surplus), so stacking the bar's colours in that order lines up with where+ // the flows actually leave the hub.+ const outBy = (pred: (n: SankeyNodeDatum) => boolean) => layout+ ? layout.links+ .filter((l) => (l.source as SankeyNodeDatum).id === 'center' && pred(l.target as SankeyNodeDatum))+ .reduce((s, l) => s + l.value, 0)+ : 0+ const expenseOut = outBy((n) => n.side === 'expense' && n.id !== 'surplus')+ const investOut = outBy((n) => n.side === 'investment')+ const surplusOut = outBy((n) => n.id === 'surplus')++ const linkDimmed = (i: number) => hover !== null && !activeLinks.has(i)+ const nodeDimmed = (idx: number) => hover !== null && !activeNodes.has(idx)++ return (+ <div ref={containerRef} className="w-full privacy-sensitive">+ {layout && (+ <svg+ width={width}+ height={height}+ role="img"+ aria-label={t('reports.flowChartAria')}+ onMouseLeave={() => setHover(null)}+ >+ <defs>+ {layout.links.map((link, i) => {+ const src = link.source as SankeyNodeDatum & { x1: number }+ const tgt = link.target as SankeyNodeDatum & { x0: number }+ return (+ <linearGradient+ key={i}+ id={`flow-grad-${i}`}+ gradientUnits="userSpaceOnUse"+ x1={src.x1}+ x2={tgt.x0}+ >+ <stop offset="0%" stopColor={src.color} />+ <stop offset="100%" stopColor={tgt.color} />+ </linearGradient>+ )+ })}+ </defs>++ {/* Links — gradient from source colour to target colour */}+ <g fill="none">+ {layout.links.map((link, i) => {+ const dimmed = linkDimmed(i)+ const active = hover !== null && activeLinks.has(i)+ const pct = total > 0 ? ((link.value / total) * 100).toFixed(1) : '0'+ return (+ <path+ key={i}+ d={linkPath(link) ?? undefined}+ stroke={`url(#flow-grad-${i})`}+ strokeOpacity={dimmed ? 0.07 : active ? 0.6 : 0.4}+ strokeWidth={Math.max(1.5, link.width ?? 1)}+ style={{ transition: 'stroke-opacity 0.2s ease' }}+ >+ <title>+ {(link.target as SankeyNodeDatum).id === 'center'+ ? (link.source as SankeyNodeDatum).name+ : (link.target as SankeyNodeDatum).name}+ : {fmtAmount(link.value)} ({pct}%)+ </title>+ </path>+ )+ })}+ </g>++ {/* Nodes + always-on labels */}+ <g>+ {layout.nodes.map((node, i) => {+ const x0 = node.x0 ?? 0+ const x1 = node.x1 ?? 0+ const y0 = node.y0 ?? 0+ const y1 = node.y1 ?? 0+ const nodeHeight = Math.max(1, y1 - y0)+ const isCenter = node.id === 'center'+ const dimmed = nodeDimmed(i)+ const nodeWidthPx = Math.max(1, x1 - x0)++ // Centre bar is split into spent (red), invested (teal) and kept+ // (green) zones, each its own hover target so the cursor can+ // isolate ALL of that flow type at once. Label sits in the top+ // gutter. Segments are stacked in the same order the links leave+ // the hub (expenses, investments, surplus).+ if (isCenter) {+ const cx = (x0 + x1) / 2+ const out = expenseOut + investOut + surplusOut || 1+ const redH = nodeHeight * (expenseOut / out)+ const tealH = nodeHeight * (investOut / out)+ const segments = [+ { h: redH, fill: EXPENSE_COLOR, hover: { kind: 'expenses' } as Hover, title: t('reports.expenses'), val: expenseOut },+ { h: tealH, fill: INVEST_COLOR, hover: { kind: 'investments' } as Hover, title: t('reports.investments'), val: investOut },+ { h: Math.max(0, nodeHeight - redH - tealH), fill: SURPLUS_COLOR, hover: { kind: 'surplus' } as Hover, title: t('reports.surplus'), val: surplusOut },+ ]+ let segY = y0+ return (+ <g key={i} style={{ transition: 'opacity 0.2s ease', opacity: dimmed ? 0.4 : 1 }}>+ {segments.filter((seg) => seg.val > 0).map((seg, si) => {+ const yy = segY+ segY += seg.h+ return (+ <rect+ key={si}+ x={x0} y={yy} width={nodeWidthPx} height={Math.max(1, seg.h)}+ fill={seg.fill} rx={4}+ style={{ cursor: 'pointer' }}+ onMouseEnter={() => setHover(seg.hover)}+ >+ <title>{seg.title}: {fmtAmount(seg.val)}</title>+ </rect>+ )+ })}+ <text x={cx} y={10} textAnchor="middle" className="fill-foreground pointer-events-none" style={{ fontSize: 11, fontWeight: 600 }}>+ {node.name}+ <tspan x={cx} dy={13} className="fill-muted-foreground" style={{ fontSize: 10, fontFamily: 'var(--font-mono, monospace)', fontWeight: 400 }}>+ {fmtAmount(node.value ?? 0)}+ </tspan>+ </text>+ </g>+ )+ }++ const onLeft = x0 < width / 2+ const labelX = onLeft ? x1 + 8 : x0 - 8+ const ly = labelY.get(i) ?? (y0 + y1) / 2+ return (+ <g+ key={i}+ style={{ transition: 'opacity 0.2s ease', opacity: dimmed ? 0.35 : 1 }}+ onMouseEnter={() => setHover({ kind: 'node', index: i })}+ >+ <rect x={x0} y={y0} width={Math.max(1, x1 - x0)} height={nodeHeight} fill={node.color} rx={3}>+ <title>{node.name}: {fmtAmount(node.value ?? 0)}</title>+ </rect>+ <text+ x={labelX}+ y={ly}+ textAnchor={onLeft ? 'start' : 'end'}+ dominantBaseline="middle"+ className="fill-foreground"+ style={{ fontSize: 11, fontWeight: 500 }}+ >+ {node.name}+ <tspan+ x={labelX}+ dy={13}+ className="fill-muted-foreground"+ style={{ fontSize: 10, fontFamily: 'var(--font-mono, monospace)' }}+ >+ {fmtAmount(node.value ?? 0)}+ </tspan>+ </text>+ </g>+ )+ })}+ </g>+ </svg>+ )}++ {/* Accessible table fallback — also a non-visual summary of the flows. */}+ <table className="sr-only">+ <caption>{t('reports.flowChartAria')}</caption>+ <thead>+ <tr>+ <th>{t('reports.category')}</th>+ <th>{t('reports.amount')}</th>+ </tr>+ </thead>+ <tbody>+ {rawNodes+ .filter((n) => n.side !== 'center')+ .map((n, i) => {+ const idx = rawNodes.indexOf(n)+ const value = layout?.nodes[idx]?.value ?? 0+ return (+ <tr key={i}>+ <td>{n.name}</td>+ <td>{fmtAmount(value)}</td>+ </tr>+ )+ })}+ </tbody>+ </table>+ </div>+ )+}diff --git a/frontend/src/locales/en.json b/frontend/src/locales/en.jsonindex 05b1c8e7..e208ef1a 100644--- a/frontend/src/locales/en.json+++ b/frontend/src/locales/en.json@@ -1087,7 +1087,16 @@"forecastBaseline": "Forecast with estimate","includeEstimate": "Include estimate","includeEstimateHelp": "Estimates future inflows and outflows from your history average (up to 12 months, or all available data), instead of using your recurring rules",- "baseline": "Estimate"+ "baseline": "Estimate",+ "surplus": "Surplus",+ "deficit": "Deficit",+ "cashFlowNode": "Cash Flow",+ "flowChartAria": "Cashflow diagram: income sources flowing through to expenses",+ "category": "Category",+ "amount": "Amount",+ "investments": "Investments",+ "moneyMap": "Money Map",+ "range30d": "30D"},"payees": {"title": "Payees",diff --git a/frontend/src/locales/es.json b/frontend/src/locales/es.jsonindex d330caa4..e9718d1f 100644--- a/frontend/src/locales/es.json+++ b/frontend/src/locales/es.json@@ -1085,7 +1085,16 @@"forecastBaseline": "Pronóstico con estimación","includeEstimate": "Incluir estimación","includeEstimateHelp": "Estima entradas y salidas futuras a partir del promedio de tu historial (hasta 12 meses, o todos los datos disponibles), en lugar de usar tus reglas recurrentes",- "baseline": "Estimación"+ "baseline": "Estimación",+ "surplus": "Superávit",+ "deficit": "Déficit",+ "cashFlowNode": "Flujo de caja",+ "flowChartAria": "Diagrama de flujo de caja: ingresos que fluyen hacia los gastos",+ "category": "Categoría",+ "amount": "Importe",+ "investments": "Inversiones",+ "moneyMap": "Mapa del Dinero",+ "range30d": "30D"},"payees": {"title": "Beneficiarios",diff --git a/frontend/src/locales/it.json b/frontend/src/locales/it.jsonindex 9b0b0f15..77ee1097 100644--- a/frontend/src/locales/it.json+++ b/frontend/src/locales/it.json@@ -1059,7 +1059,16 @@"forecastBaseline": "Previsione con stima","includeEstimate": "Includi stima","includeEstimateHelp": "Stima entrate e uscite future dalla media della tua cronologia (fino a 12 mesi, o tutti i dati disponibili), invece di usare le tue regole ricorrenti",- "baseline": "Stima"+ "baseline": "Stima",+ "surplus": "Avanzo",+ "deficit": "Disavanzo",+ "cashFlowNode": "Flusso di cassa",+ "flowChartAria": "Diagramma del flusso di cassa: entrate che confluiscono nelle spese",+ "category": "Categoria",+ "amount": "Importo",+ "investments": "Investimenti",+ "moneyMap": "Mappa del Denaro",+ "range30d": "30D"},"payees": {"title": "Beneficiari",diff --git a/frontend/src/locales/pl.json b/frontend/src/locales/pl.jsonindex 88d299ac..534357f6 100644--- a/frontend/src/locales/pl.json+++ b/frontend/src/locales/pl.json@@ -1156,7 +1156,16 @@"forecastBaseline": "Prognoza z szacunkiem","includeEstimate": "Uwzględnij szacunek","includeEstimateHelp": "Szacuje przyszłe wpływy i wypływy na podstawie średniej z historii (do 12 miesięcy lub wszystkich dostępnych danych), zamiast używać reguł cyklicznych",- "baseline": "Szacunek"+ "baseline": "Szacunek",+ "surplus": "Nadwyżka",+ "deficit": "Deficyt",+ "cashFlowNode": "Przepływ pieniędzy",+ "flowChartAria": "Diagram przepływu pieniędzy: przychody przepływające do wydatków",+ "category": "Kategoria",+ "amount": "Kwota",+ "investments": "Inwestycje",+ "moneyMap": "Mapa Pieniędzy",+ "range30d": "30D"},"payees": {"title": "Odbiorcy",diff --git a/frontend/src/locales/pt-BR.json b/frontend/src/locales/pt-BR.jsonindex 9b6e366a..4d1ab646 100644--- a/frontend/src/locales/pt-BR.json+++ b/frontend/src/locales/pt-BR.json@@ -1087,7 +1087,16 @@"forecastBaseline": "Projeção com estimativa","includeEstimate": "Incluir estimativa","includeEstimateHelp": "Estima entradas e saídas futuras pela média do seu histórico (até 12 meses, ou todo o histórico disponível), em vez das transações recorrentes cadastradas",- "baseline": "Estimativa"+ "baseline": "Estimativa",+ "surplus": "Sobra",+ "deficit": "Déficit",+ "cashFlowNode": "Fluxo de Caixa",+ "flowChartAria": "Diagrama de fluxo de caixa: receitas fluindo para as despesas",+ "category": "Categoria",+ "amount": "Valor",+ "investments": "Investimentos",+ "moneyMap": "Mapa do Dinheiro",+ "range30d": "30D"},"payees": {"title": "Beneficiários",diff --git a/frontend/src/pages/reports.tsx b/frontend/src/pages/reports.tsxindex 05ba60bb..c0c9d8a4 100644--- a/frontend/src/pages/reports.tsx+++ b/frontend/src/pages/reports.tsx@@ -23,6 +23,7 @@ import { reports } from '@/lib/api'import { Skeleton } from '@/components/ui/skeleton'import { Popover, PopoverTrigger, PopoverContent } from '@/components/ui/popover'import { PageHeader } from '@/components/page-header'+import { CashflowSankey } from '@/components/reports/CashflowSankey'import { usePrivacyMode } from '@/hooks/use-privacy-mode'import { useAuth } from '@/contexts/auth-context'import { useCollectionFilter } from '@/contexts/collection-filter-context'@@ -76,6 +77,16 @@ const FORWARD_RANGE_OPTIONS: readonly RangeOption[] = [{ key: '12m', months: 12 },]+// The Money Map answers "where did my money go lately", so it leans on recent+// windows (down to 30 days) and drops the 2Y trend view the other tabs keep.+const MONEY_MAP_RANGE_OPTIONS: readonly RangeOption[] = [+ { key: '30d', months: 1 },+ { key: '3m', months: 3 },+ { key: '6m', months: 6 },+ { key: 'ytd', months: 12, period: 'ytd' },+ { key: '1y', months: 12 },+]+const HISTORICAL_INTERVAL_OPTIONS = [{ key: 'daily', value: 'daily' },{ key: 'weekly', value: 'weekly' },@@ -97,6 +108,7 @@ const INTERVAL_LABELS: Record<string, string> = {}const RANGE_LABELS: Record<string, string> = {+ '30d': 'range30d','3m': 'range3m','6m': 'range6m','1y': 'range1y',@@ -115,6 +127,7 @@ const REPORT_TABS: ReportTab[] = [{ key: 'net_worth', labelKey: 'reports.netWorth', enabled: true },{ key: 'income_expenses', labelKey: 'reports.incomeExpenses', enabled: true },{ key: 'cash_flow', labelKey: 'reports.cashFlow', enabled: true },+ { key: 'money_map', labelKey: 'reports.moneyMap', enabled: true },]export default function ReportsPage() {@@ -144,7 +157,14 @@ export default function ReportsPage() {const currentTab = REPORT_TABS.find((tab) => tab.key === activeTab) ?? REPORT_TABS[0]const isCashFlow = activeTab === 'cash_flow'- const rangeOptions = isCashFlow ? FORWARD_RANGE_OPTIONS : HISTORICAL_RANGE_OPTIONS+ // The Money Map (Sankey) tab is driven by the same income/expenses+ // composition, aggregated over the selected historical range.+ const isMoneyMap = activeTab === 'money_map'+ const rangeOptions = isCashFlow+ ? FORWARD_RANGE_OPTIONS+ : isMoneyMap+ ? MONEY_MAP_RANGE_OPTIONS+ : HISTORICAL_RANGE_OPTIONSconst intervalOptions = isCashFlow ? CASH_FLOW_INTERVAL_OPTIONS : HISTORICAL_INTERVAL_OPTIONSconst selectedRange = rangeOptions.find((r) => r.key === rangeKey) ?? rangeOptions[0]const months = selectedRange.months@@ -155,9 +175,13 @@ export default function ReportsPage() {setCompositionView(key === 'net_worth' ? 'netWorth' : 'net')setSparklinePage(0)// Clamp months/interval to options supported by the new tab- const nextRanges = key === 'cash_flow' ? FORWARD_RANGE_OPTIONS : HISTORICAL_RANGE_OPTIONS+ const nextRanges = key === 'cash_flow'+ ? FORWARD_RANGE_OPTIONS+ : key === 'money_map'+ ? MONEY_MAP_RANGE_OPTIONS+ : HISTORICAL_RANGE_OPTIONSif (!nextRanges.some((r) => r.key === rangeKey)) {- setRangeKey(key === 'cash_flow' ? '6m' : '1y')+ setRangeKey(key === 'cash_flow' ? '6m' : key === 'money_map' ? '3m' : '1y')}const nextIntervals = key === 'cash_flow' ? CASH_FLOW_INTERVAL_OPTIONS : HISTORICAL_INTERVAL_OPTIONSif (!nextIntervals.some((i) => i.value === interval)) {@@ -170,7 +194,7 @@ export default function ReportsPage() {queryFn: () =>isCashFlow? reports.cashFlow(months, interval, cashFlowBaseline, acctIds)- : activeTab === 'income_expenses'+ : activeTab === 'income_expenses' || isMoneyMap? reports.incomeExpenses(months, interval, acctIds, period): reports.netWorth(months, interval, acctIds, walletIds, period),enabled: currentTab.enabled && !(noAccounts && activeTab !== 'net_worth'),@@ -377,7 +401,7 @@ export default function ReportsPage() {</button>))}</div>- <div className="flex items-center rounded-lg border border-border bg-card overflow-hidden">+ <div className={`flex items-center rounded-lg border border-border bg-card overflow-hidden ${isMoneyMap ? 'hidden' : ''}`}>{intervalOptions.map((opt) => (<buttonkey={opt.key}@@ -480,6 +504,44 @@ export default function ReportsPage() {</div></div>+ {/* Flow (Sankey) */}+ {isMoneyMap && (+ <div className="bg-card rounded-xl border border-border shadow-sm mb-5">+ <div className="px-5 pt-5 pb-2 flex items-center justify-between">+ <p className="text-sm font-semibold text-foreground">+ {t('reports.moneyMap')}+ </p>+ <div className="flex items-center gap-3">+ <div className="flex items-center gap-1.5">+ <div className="w-2 h-2 rounded-full" style={{ backgroundColor: '#10B981' }} />+ <span className="text-[11px] text-muted-foreground">{t('reports.income')}</span>+ </div>+ <div className="flex items-center gap-1.5">+ <div className="w-2 h-2 rounded-full" style={{ backgroundColor: '#F43F5E' }} />+ <span className="text-[11px] text-muted-foreground">{t('reports.expenses')}</span>+ </div>+ <div className="flex items-center gap-1.5">+ <div className="w-2 h-2 rounded-full" style={{ backgroundColor: '#0EA5E9' }} />+ <span className="text-[11px] text-muted-foreground">{t('reports.investments')}</span>+ </div>+ <div className="flex items-center gap-1.5">+ <div className="w-2 h-2 rounded-full" style={{ backgroundColor: '#F59E0B' }} />+ <span className="text-[11px] text-muted-foreground">{t('reports.deficit')}</span>+ </div>+ </div>+ </div>+ <div className="px-3 pb-5">+ {isLoading ? (+ <div className="px-2"><Skeleton className="h-[360px] w-full" /></div>+ ) : (+ <CashflowSankey composition={composition} currency={userCurrency} locale={locale} />+ )}+ </div>+ </div>+ )}++ {!isMoneyMap && (+ <>{/* Main Trend Chart */}<div className="bg-card rounded-xl border border-border shadow-sm mb-5"><div className="px-5 pt-5 pb-2 flex items-center justify-between">@@ -1222,6 +1284,8 @@ export default function ReportsPage() {)}</div></div>+ </>+ )}</div>)}