Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

Add cash_flow Sankey API and instrumented dashboard preview (#3558)

Juan José Matae526fac7e0d8
diff --git a/.env.local.example b/.env.local.example
index 21c29120c2..af55a74056 100644
--- a/.env.local.example
+++ b/.env.local.example
@@ -142,3 +142,11 @@ APNS_PRIVATE_KEY_BASE64=
# ========
SKYLIGHT_AUTHENTICATION=
SKYLIGHT_ENABLED=
+
+# Managed app/demo only: API survey in the existing PostHog project.
+# Self-hosted previews use bundled public configuration and need no keys.
+# See docs/hosting/preview-feedback.md.
+POSTHOG_SANKEY_SURVEY_ID=
+
+# Optional self-hosted opt-out (enabled by default, preview users only).
+# POSTHOG_FEEDBACK_ENABLED=false
diff --git a/app/controllers/api/v1/cash_flows_controller.rb b/app/controllers/api/v1/cash_flows_controller.rb
index 2d79321164..f3b4e71f16 100644
--- a/app/controllers/api/v1/cash_flows_controller.rb
+++ b/app/controllers/api/v1/cash_flows_controller.rb
@@ -1,26 +1,47 @@
class Api::V1::CashFlowsController < Api::V1::BaseController
- before_action :ensure_read_scope
+ before_action -> { authorize_scope!(:read) }
def show
+ response.headers["Cache-Control"] = "private, no-store"
today = Date.current
- value = params[:month]
- month = value.nil? ? today.beginning_of_month : parse_month(value)
- unless month && month.day == 1 && month <= today
- render json: { error: "invalid_month", message: "month must be a non-future ISO first day (YYYY-MM-01)" }, status: :unprocessable_entity
- return
- end
statement = IncomeStatement.new(current_resource_owner.family, user: current_resource_owner)
- render json: IncomeStatement::CashFlow.new(statement, month: month, as_of: today)
+ if params[:include] && params[:view]
+ return invalid_query("invalid_view", "include and view cannot be combined")
+ end
+ unless [ nil, "sankey" ].include?(params[:include]) && [ nil, "sankey" ].include?(params[:view])
+ return invalid_query("invalid_view", "include and view support only sankey")
+ end
+ if params[:start_date] || params[:end_date]
+ start_date, end_date = parse_date(params[:start_date]), parse_date(params[:end_date])
+ unless params[:view] == "sankey" && params[:month].nil? && start_date && end_date && start_date <= end_date
+ return invalid_query("invalid_period", "Date ranges require view=sankey, both ISO dates in order, and no month")
+ end
+ period = Period.custom(start_date: start_date, end_date: end_date)
+ else
+ month = params[:month].nil? ? today.beginning_of_month : parse_date(params[:month])
+ unless month && month.day == 1 && month <= today
+ return invalid_query("invalid_month", "month must be a non-future ISO first day (YYYY-MM-01)")
+ end
+ period = Period.custom(start_date: month, end_date: [ month.end_of_month, today ].min)
+ end
+
+ if params[:view] == "sankey"
+ # Arbitrary graph ranges must not allocate a daily comparison series.
+ render json: IncomeStatement::CashFlowGraph.new(statement, period: period, as_of: today)
+ else
+ render json: IncomeStatement::CashFlow.new(statement, month: month, as_of: today, include_sankey: params[:include] == "sankey")
+ end
end
private
- def ensure_read_scope
- authorize_scope!(:read)
+ def invalid_query(error, message)
+ render json: { error: error, message: message }, status: :unprocessable_entity
end
- def parse_month(value)
- return unless value.is_a?(String) && value.match?(/\A\d{4}-\d{2}-01\z/)
- Date.iso8601(value)
+ def parse_date(value)
+ return unless value.is_a?(String) && value.match?(/\A\d{4}-\d{2}-\d{2}\z/)
+ date = Date.iso8601(value)
+ date if date.year.positive?
rescue Date::Error
nil
end
diff --git a/app/controllers/cash_flows_controller.rb b/app/controllers/cash_flows_controller.rb
new file mode 100644
index 0000000000..86b7801070
--- /dev/null
+++ b/app/controllers/cash_flows_controller.rb
@@ -0,0 +1,27 @@
+class CashFlowsController < ApplicationController
+ before_action :require_preview_features!
+
+ def show
+ response.headers["Cache-Control"] = "private, no-store"
+ start_date, end_date = parse_date(params[:start_date]), parse_date(params[:end_date])
+ unless start_date && end_date && start_date <= end_date
+ return render json: { error: "invalid_period" }, status: :unprocessable_entity
+ end
+
+ statement = IncomeStatement.new(Current.family, user: Current.user)
+ period = Period.custom(start_date: start_date, end_date: end_date)
+ # Resolve reporting dates after ordinary session authentication has set Current.
+ Time.use_zone(resolved_timezone) do
+ render json: IncomeStatement::CashFlowGraph.new(statement, period: period)
+ end
+ end
+
+ private
+ def parse_date(value)
+ return unless value.is_a?(String) && value.match?(/\A\d{4}-\d{2}-\d{2}\z/)
+ date = Date.iso8601(value)
+ date if date.year.positive?
+ rescue Date::Error
+ nil
+ end
+end
diff --git a/app/helpers/feedback_helper.rb b/app/helpers/feedback_helper.rb
new file mode 100644
index 0000000000..bab3db701c
--- /dev/null
+++ b/app/helpers/feedback_helper.rb
@@ -0,0 +1,15 @@
+module FeedbackHelper
+ def feedback_config(feature)
+ config = Rails.configuration.x.posthog
+ destination = self_hosted? ? :self_hosted : :managed
+ return {} if destination == :self_hosted && !(Rails.env.production? && config.feedback_enabled)
+
+ survey_id = config.feedback_surveys.dig(feature, destination).presence
+ return {} unless survey_id
+
+ # Managed feedback uses the environment's existing SDK. Self-hosted feedback
+ # uses the shared public project, independently of operator-owned analytics.
+ project = destination == :self_hosted ? config.self_hosted_feedback_project : {}
+ project.merge(survey_id: survey_id)
+ end
+end
diff --git a/app/javascript/controllers/cash_flow_controller.js b/app/javascript/controllers/cash_flow_controller.js
new file mode 100644
index 0000000000..8709c18d98
--- /dev/null
+++ b/app/javascript/controllers/cash_flow_controller.js
@@ -0,0 +1,65 @@
+import { Controller } from "@hotwired/stimulus";
+import { cashFlowChartData } from "utils/cash_flow_chart_data";
+
+// One request supplies the inline and expanded renderers. No persistent browser
+// cache: Turbo snapshots must not retain a prior session's financial graph.
+export default class extends Controller {
+ static targets = ["chart", "loading", "error", "empty", "content"];
+ static values = { url: String };
+
+ connect() {
+ this.load();
+ }
+
+ disconnect() {
+ this.clear();
+ }
+
+ clear() {
+ this.request?.abort();
+ this.request = null;
+ this.chartTargets.forEach((chart) => {
+ chart.removeAttribute("data-preview-sankey-chart-data-value");
+ chart.querySelectorAll("svg").forEach((svg) => svg.remove());
+ });
+ this.show("loading");
+ }
+
+ async load() {
+ this.clear();
+ const request = new AbortController();
+ this.request = request;
+ try {
+ const response = await fetch(this.urlValue, {
+ headers: { Accept: "application/json" },
+ credentials: "same-origin",
+ cache: "no-store",
+ signal: request.signal,
+ });
+ if (!response.ok) throw new Error("Cash flow unavailable");
+ const body = await response.json();
+ const data = cashFlowChartData(body);
+ if (this.request !== request) return;
+ this.chartTargets.forEach((chart) => {
+ chart.setAttribute(
+ "data-preview-sankey-chart-currency-value",
+ body.currency,
+ );
+ chart.setAttribute(
+ "data-preview-sankey-chart-data-value",
+ JSON.stringify(data),
+ );
+ });
+ this.show(data.links.length ? "content" : "empty");
+ } catch {
+ if (this.request === request) this.show("error");
+ }
+ }
+
+ show(state) {
+ for (const name of ["loading", "error", "empty", "content"]) {
+ this[`${name}Target`].hidden = name !== state;
+ }
+ this.dispatch("state", { detail: { state, ready: state === "content" } });
+ }
+}
diff --git a/app/javascript/controllers/preview_sankey_chart_controller.js b/app/javascript/controllers/preview_sankey_chart_controller.js
new file mode 100644
index 0000000000..dd83b14653
--- /dev/null
+++ b/app/javascript/controllers/preview_sankey_chart_controller.js
@@ -0,0 +1,652 @@
+import { Controller } from "@hotwired/stimulus";
+import * as d3 from "d3";
+import { sankey } from "d3-sankey";
+import { formatCashFlowCurrency } from "utils/cash_flow_chart_data";
+import { CHART_TOOLTIP_CLASSES } from "utils/chart_tooltip";
+import { sankeyNodeHasChildren, zoomSankeyData } from "utils/sankey_zoom";
+import {
+ buildCategoryTransactionsUrl,
+ isNavigableCategoryNode,
+} from "utils/transactions_filter_url";
+
+let nextChartId = 0;
+
+// Preview-only renderer. Keep the legacy Sankey unchanged during comparison.
+export default class extends Controller {
+ static targets = ["chart", "zoomOutButton"];
+
+ static values = {
+ data: Object,
+ labels: Object,
+ nodeWidth: { type: Number, default: 15 },
+ nodePadding: { type: Number, default: 20 },
+ currency: { type: String, default: "USD" },
+ startDate: String,
+ endDate: String,
+ };
+
+ // Visual constants
+ static HOVER_OPACITY = 0.4;
+ static HOVER_FILTER = "saturate(1.3) brightness(1.1)";
+ static EXTENT_MARGIN = 16;
+ static MIN_NODE_PADDING = 4;
+ static MAX_PADDING_RATIO = 0.4;
+ static CORNER_RADIUS = 8;
+ static ZOOM_TRANSITION_MS = 220;
+ static DEFAULT_COLOR = "var(--color-gray-400)";
+ static CSS_VAR_MAP = {
+ "var(--color-success)": "#10A861",
+ "var(--color-destructive)": "#EC2222",
+ "var(--color-gray-400)": "#9E9E9E",
+ "var(--color-gray-500)": "#737373",
+ };
+ static MIN_LABEL_SPACING = 28; // Minimum vertical space needed for labels (2 lines)
+
+ connect() {
+ this.gradientPrefix ||= `preview-sankey-${++nextChartId}`;
+ this.connected = true;
+ this.zoomRootId = null;
+ this.resizeObserver = new ResizeObserver(() => this.#draw());
+ this.resizeObserver.observe(this.#chartElement());
+ this.tooltip = null;
+ this.#createTooltip();
+ this.#syncZoomControls();
+ this.#draw();
+ }
+
+ dataValueChanged() {
+ if (!this.connected) return;
+
+ this.zoomRootId = null;
+ this.#syncZoomControls();
+ this.#draw();
+ }
+
+ disconnect() {
+ this.connected = false;
+ this.resizeObserver?.disconnect();
+ clearTimeout(this.drawTimeout);
+ this.tooltip?.remove();
+ this.tooltip = null;
+ }
+
+ clear() {
+ clearTimeout(this.drawTimeout);
+ this.tooltip?.remove();
+ this.tooltip = null;
+ d3.select(this.#chartElement()).selectAll("svg").interrupt().remove();
+ }
+
+ zoomOut() {
+ if (!this.zoomRootId) return;
+
+ this.focusAfterDraw = this.zoomRootId;
+ this.zoomRootId = null;
+ this.#syncZoomControls();
+ this.#draw({ animate: true });
+ }
+
+ #draw({ animate = false } = {}) {
+ const { nodes = [], links = [] } = this.#visibleData();
+
+ // Hide tooltip and reset any hover states before redrawing
+ this.#hideTooltip();
+
+ const chartElement = this.#chartElement();
+ const focusedNode = document.activeElement?.closest("[data-node-id]");
+ if (chartElement.contains(focusedNode))
+ this.focusAfterDraw ||= focusedNode.dataset.nodeId;
+ const chart = d3.select(chartElement);
+
+ clearTimeout(this.drawTimeout);
+ chart.selectAll("svg").interrupt();
+
+ if (!nodes.length || !links.length) {
+ chart.selectAll("svg").remove();
+ return;
+ }
+
+ if (animate) {
+ chart
+ .selectAll("svg")
+ .transition()
+ .duration(this.constructor.ZOOM_TRANSITION_MS / 2)
+ .style("opacity", 0)
+ .remove();
+
+ this.drawTimeout = setTimeout(() => {
+ this.#render(nodes, links, true);
+ }, this.constructor.ZOOM_TRANSITION_MS / 2);
+ } else {
+ chart.selectAll("svg").remove();
+ this.#render(nodes, links, false);
+ }
+ }
+
+ #render(nodes, links, animate) {
+ const chartElement = this.#chartElement();
+ const chart = d3.select(chartElement);
+
+ const width = chartElement.clientWidth || 600;
+ const height = chartElement.clientHeight || 400;
+
+ const svg = chart
+ .append("svg")
+ .attr("width", width)
+ .attr("height", height)
+ .style("opacity", animate ? 0 : 1);
+
+ const effectivePadding = this.#calculateNodePadding(nodes.length, height);
+ const sankeyData = this.#generateSankeyData(
+ nodes,
+ links,
+ width,
+ height,
+ effectivePadding,
+ );
+
+ this.#createGradients(svg, sankeyData.links);
+
+ const linkPaths = this.#drawLinks(svg, sankeyData.links);
+ const { nodeGroups, hiddenLabels } = this.#drawNodes(
+ svg,
+ sankeyData.nodes,
+ width,
+ );
+
+ this.#attachHoverEvents(linkPaths, nodeGroups, sankeyData, hiddenLabels);
+
+ if (animate) {
+ svg
+ .transition()
+ .duration(this.constructor.ZOOM_TRANSITION_MS / 2)
+ .style("opacity", 1);
+ }
+ }
+
+ #chartElement() {
+ return this.hasChartTarget ? this.chartTarget : this.element;
+ }
+
+ #visibleData() {
+ if (!this.zoomRootId) return this.dataValue || {};
+
+ return zoomSankeyData(this.dataValue, this.zoomRootId);
+ }
+
+ #syncZoomControls() {
+ this.zoomOutButtonTargets.forEach((button) => {
+ button.hidden = !this.zoomRootId;
+ });
+ }
+
+ #zoomIn(node) {
+ if (!node.id || !sankeyNodeHasChildren(this.#visibleData(), node.id))
+ return;
+
+ if (this.element.contains(document.activeElement))
+ this.focusAfterDraw = node.id;
+ this.zoomRootId = node.id;
+ this.#syncZoomControls();
+ this.#draw({ animate: true });
+ }
+
+ #nodeAction(node) {
+ if (sankeyNodeHasChildren(this.#visibleData(), node.id)) return "button";
+ if (isNavigableCategoryNode(node.id) && node.filter_value) return "link";
+ return null;
+ }
+
+ #activateNode(node) {
+ const action = this.#nodeAction(node);
+ if (action === "button") {
+ this.#zoomIn(node);
+ } else if (action === "link") {
+ Turbo.visit(
+ buildCategoryTransactionsUrl({
+ filterValue: node.filter_value,
+ startDate: this.startDateValue,
+ endDate: this.endDateValue,
+ }),
+ );
+ }
+ }
+
+ // Dynamic padding prevents padding from dominating when there are many nodes
+ #calculateNodePadding(nodeCount, height) {
+ const margin = this.constructor.EXTENT_MARGIN;
+ const availableHeight = height - margin * 2;
+ const maxPaddingTotal =
+ availableHeight * this.constructor.MAX_PADDING_RATIO;
+ const gaps = Math.max(nodeCount - 1, 1);
+ const dynamicPadding = Math.min(
+ this.nodePaddingValue,
+ Math.floor(maxPaddingTotal / gaps),
+ );
+ return Math.max(this.constructor.MIN_NODE_PADDING, dynamicPadding);
+ }
+
+ #generateSankeyData(nodes, links, width, height, nodePadding) {
+ const margin = this.constructor.EXTENT_MARGIN;
+ const sankeyGenerator = sankey()
+ .nodeWidth(this.nodeWidthValue)
+ .nodePadding(nodePadding)
+ .extent([
+ [margin, margin],
+ [width - margin, height - margin],
+ ]);
+
+ return sankeyGenerator({
+ nodes: nodes.map((d) => ({
+ ...d,
+ // Structural labels belong to the UI locale, not the API fallback name.
+ name: this.labelsValue[d.kind] || d.name,
+ })),
+ links: links.map((d) => ({ ...d })),
+ });
+ }
+
+ #createGradients(svg, links) {
+ const defs = svg.append("defs");
+
+ links.forEach((link, i) => {
+ const gradientId = this.#gradientId(link, i);
+ const gradient = defs
+ .append("linearGradient")
+ .attr("id", gradientId)
+ .attr("gradientUnits", "userSpaceOnUse")
+ .attr("x1", link.source.x1)
+ .attr("x2", link.target.x0);
+
+ gradient
+ .append("stop")
+ .attr("offset", "0%")
+ .attr("stop-color", this.#colorWithOpacity(link.source.color));
+
+ gradient
+ .append("stop")
+ .attr("offset", "100%")
+ .attr("stop-color", this.#colorWithOpacity(link.target.color));
+ });
+ }
+
+ #gradientId(link, index) {
+ return `${this.gradientPrefix}-link-gradient-${link.source.index}-${link.target.index}-${index}`;
+ }
+
+ #colorWithOpacity(nodeColor, opacity = 0.1) {
+ const defaultColor = this.constructor.DEFAULT_COLOR;
+ let colorStr = nodeColor || defaultColor;
+
+ // Map CSS variables to hex values for d3 color manipulation
+ colorStr = this.constructor.CSS_VAR_MAP[colorStr] || colorStr;
+
+ // Unmapped CSS vars cannot be manipulated, return as-is
+ if (colorStr.startsWith("var(--")) return colorStr;
+
+ const d3Color = d3.color(colorStr);
+ return d3Color ? d3Color.copy({ opacity }) : defaultColor;
+ }
+
+ #drawLinks(svg, links) {
+ return svg
+ .append("g")
+ .attr("fill", "none")
+ .selectAll("path")
+ .data(links)
+ .join("path")
+ .attr("class", "sankey-link")
+ .attr("d", (d) =>
+ d3.linkHorizontal()({
+ source: [d.source.x1, d.y0],
+ target: [d.target.x0, d.y1],
+ }),
+ )
+ .attr("stroke", (d, i) => `url(#${this.#gradientId(d, i)})`)
+ .attr("stroke-width", (d) => Math.max(1, d.width))
+ .style("transition", "opacity 0.3s ease");
+ }
+
+ #drawNodes(svg, nodes, width) {
+ const nodeGroups = svg
+ .append("g")
+ .selectAll("g")
+ .data(nodes)
+ .join("g")
+ .style("transition", "opacity 0.3s ease");
+
+ nodeGroups
+ .append("path")
+ .attr("d", (d) => this.#nodePath(d))
+ .attr("fill", (d) => d.color || this.constructor.DEFAULT_COLOR)
+ .attr("stroke", (d) => (d.color ? "none" : "var(--color-gray-500)"));
+
+ const hiddenLabels = this.#addNodeLabels(nodeGroups, width, nodes);
+
+ return { nodeGroups, hiddenLabels };
+ }
+
+ #nodePath(node) {
+ const { x0, y0, x1, y1 } = node;
+ const height = y1 - y0;
+ const radius = Math.max(
+ 0,
+ Math.min(this.constructor.CORNER_RADIUS, height / 2),
+ );
+
+ const isSourceNode =
+ node.sourceLinks?.length > 0 && !node.targetLinks?.length;
+ const isTargetNode =
+ node.targetLinks?.length > 0 && !node.sourceLinks?.length;
+
+ // Too small for rounded corners
+ if (height < radius * 2) {
+ return this.#rectPath(x0, y0, x1, y1);
+ }
+
+ if (isSourceNode) {
+ return this.#roundedLeftPath(x0, y0, x1, y1, radius);
+ }
+
+ if (isTargetNode) {
+ return this.#roundedRightPath(x0, y0, x1, y1, radius);
+ }
+
+ return this.#rectPath(x0, y0, x1, y1);
+ }
+
+ #rectPath(x0, y0, x1, y1) {
+ return `M ${x0},${y0} L ${x1},${y0} L ${x1},${y1} L ${x0},${y1} Z`;
+ }
+
+ #roundedLeftPath(x0, y0, x1, y1, r) {
+ return `M ${x0 + r},${y0}
+ L ${x1},${y0}
+ L ${x1},${y1}
+ L ${x0 + r},${y1}
+ Q ${x0},${y1} ${x0},${y1 - r}
+ L ${x0},${y0 + r}
+ Q ${x0},${y0} ${x0 + r},${y0} Z`;
+ }
+
+ #roundedRightPath(x0, y0, x1, y1, r) {
+ return `M ${x0},${y0}
+ L ${x1 - r},${y0}
+ Q ${x1},${y0} ${x1},${y0 + r}
+ L ${x1},${y1 - r}
+ Q ${x1},${y1} ${x1 - r},${y1}
+ L ${x0},${y1} Z`;
+ }
+
+ #addNodeLabels(nodeGroups, width, nodes) {
+ const controller = this;
+ const hiddenLabels = this.#calculateHiddenLabels(nodes);
+
+ nodeGroups
+ .append("text")
+ .attr("x", (d) => (d.x0 < width / 2 ? d.x1 + 6 : d.x0 - 6))
+ .attr("y", (d) => (d.y1 + d.y0) / 2)
+ .attr("dy", "-0.2em")
+ .attr("text-anchor", (d) => (d.x0 < width / 2 ? "start" : "end"))
+ .attr(
+ "class",
+ "text-xs font-medium text-primary fill-current select-none",
+ )
+ .style("cursor", "default")
+ .style("opacity", (d) => (hiddenLabels.has(d.index) ? 0 : 1))
+ .style("transition", "opacity 0.2s ease")
+ .each(function (d) {
+ const textEl = d3.select(this);
+ textEl.selectAll("tspan").remove();
+
+ textEl.append("tspan").text(d.name);
+
+ textEl
+ .append("tspan")
+ .attr("x", textEl.attr("x"))
+ .attr("dy", "1.2em")
+ .attr("class", "font-mono text-secondary")
+ .style("font-size", "0.65rem")
+ .text(controller.#formatCurrency(d.value));
+ });
+
+ return hiddenLabels;
+ }
+
+ // Calculate which labels should be hidden to prevent overlap
+ #calculateHiddenLabels(nodes) {
+ const hiddenLabels = new Set();
+ const height = this.#chartElement().clientHeight || 400;
+ const isLargeGraph = height > 600;
+ const minSpacing = isLargeGraph
+ ? this.constructor.MIN_LABEL_SPACING * 0.7
+ : this.constructor.MIN_LABEL_SPACING;
+
+ // Group nodes by column (using depth which d3-sankey assigns)
+ const columns = new Map();
+ nodes.forEach((node) => {
+ const depth = node.depth;
+ if (!columns.has(depth)) columns.set(depth, []);
+ columns.get(depth).push(node);
+ });
+
+ // For each column, check for overlapping labels
+ columns.forEach((columnNodes) => {
+ // Sort by vertical position
+ columnNodes.sort((a, b) => (a.y0 + a.y1) / 2 - (b.y0 + b.y1) / 2);
+
+ let lastVisibleY = Number.NEGATIVE_INFINITY;
+
+ columnNodes.forEach((node) => {
+ const nodeY = (node.y0 + node.y1) / 2;
+ const nodeHeight = node.y1 - node.y0;
+
+ if (isLargeGraph && nodeHeight > minSpacing * 1.5) {
+ lastVisibleY = nodeY;
+ } else if (nodeY - lastVisibleY < minSpacing) {
+ // Too close to previous visible label, hide this one
+ hiddenLabels.add(node.index);
+ } else {
+ lastVisibleY = nodeY;
+ }
+ });
+ });
+
+ return hiddenLabels;
+ }
+
+ #attachHoverEvents(linkPaths, nodeGroups, sankeyData, hiddenLabels) {
+ const applyHover = (targetLinks) => {
+ const targetSet = new Set(targetLinks);
+ const connectedNodes = new Set(
+ targetLinks.flatMap((l) => [l.source, l.target]),
+ );
+
+ linkPaths
+ .style("opacity", (d) =>
+ targetSet.has(d) ? 1 : this.constructor.HOVER_OPACITY,
+ )
+ .style("filter", (d) =>
+ targetSet.has(d) ? this.constructor.HOVER_FILTER : "none",
+ );
+
+ nodeGroups.style("opacity", (d) =>
+ connectedNodes.has(d) ? 1 : this.constructor.HOVER_OPACITY,
+ );
+
+ // Show labels for connected nodes (even if normally hidden)
+ nodeGroups
+ .selectAll("text")
+ .style("opacity", (d) =>
+ connectedNodes.has(d)
+ ? 1
+ : hiddenLabels.has(d.index)
+ ? 0
+ : this.constructor.HOVER_OPACITY,
+ );
+ };
+
+ const resetHover = () => {
+ linkPaths.style("opacity", 1).style("filter", "none");
+ nodeGroups.style("opacity", 1);
+ // Restore hidden labels to hidden state
+ nodeGroups
+ .selectAll("text")
+ .style("opacity", (d) => (hiddenLabels.has(d.index) ? 0 : 1));
+ };
+
+ linkPaths
+ .on("mouseenter", (event, d) => {
+ applyHover([d]);
+ // A link is a flow between two named nodes — without the names the
+ // value floats context-free (the old tooltip showed only "$X (Y%)").
+ this.#showTooltip(
+ event,
+ d.value,
+ d.percentage,
+ this.#tooltipContext(
+ `${this.#esc(d.source.name)} → ${this.#esc(d.target.name)}`,
+ ),
+ );
+ })
+ .on("mousemove", (event) => this.#updateTooltipPosition(event))
+ .on("mouseleave", () => {
+ resetHover();
+ this.#hideTooltip();
+ });
+
+ // One focus target per node; its bar and label share the same action.
+ nodeGroups
+ .attr("data-node-id", (d) => d.id)
+ .attr("tabindex", (d) => (this.#nodeAction(d) ? 0 : null))
+ .attr("role", (d) => this.#nodeAction(d))
+ .attr("aria-label", (d) => `${d.name}, ${this.#formatCurrency(d.value)}`)
+ .style("cursor", (d) => (this.#nodeAction(d) ? "pointer" : "default"))
+ .on("click", (event, d) => {
+ event.stopPropagation();
+ this.#activateNode(d);
+ })
+ .on("keydown", (event, d) => {
+ if (!["Enter", " "].includes(event.key) || !this.#nodeAction(d)) return;
+ event.preventDefault();
+ event.stopPropagation();
+ this.#activateNode(d);
+ })
+ .on("focus", (event, d) => {
+ applyHover(
+ sankeyData.links.filter((l) => l.source === d || l.target === d),
+ );
+ })
+ .on("blur", resetHover)
+ .on("mouseenter", (event, d) => {
+ applyHover(
+ sankeyData.links.filter((l) => l.source === d || l.target === d),
+ );
+ this.#showTooltip(
+ event,
+ d.value,
+ d.percentage,
+ this.#tooltipContext(this.#esc(d.name)),
+ );
+ })
+ .on("mousemove", (event) => this.#updateTooltipPosition(event))
+ .on("mouseleave", () => {
+ resetHover();
+ this.#hideTooltip();
+ });
+ nodeGroups.selectAll("text").style("cursor", "inherit");
+
+ if (this.focusAfterDraw) {
+ nodeGroups
+ .filter((d) => d.id === this.focusAfterDraw)
+ .node()
+ ?.focus();
+ this.focusAfterDraw = null;
+ }
+ }
+
+ // Tooltip methods
+
+ #createTooltip() {
+ const dialog = this.element.closest("dialog");
+ this.tooltip = d3
+ .select(dialog || document.body)
+ .append("div")
+ // Shared visual contract + this chart's positioning class; opacity is
+ // toggled via inline style below.
+ .attr("class", `${CHART_TOOLTIP_CLASSES} top-0 ph-no-capture`)
+ .style("opacity", 0)
+ .style("pointer-events", "none");
+ }
+
+ // Node names are user-named categories; escape anything interpolated into
+ // .html() (the previous code injected them raw).
+ #esc(s) {
+ return String(s).replace(
+ /[&<>"']/g,
+ (c) =>
+ ({
+ "&": "&amp;",
+ "<": "&lt;",
+ ">": "&gt;",
+ '"': "&quot;",
+ "'": "&#39;",
+ })[c],
+ );
+ }
+
+ // Context line shared by node and link tooltips: the (escaped) name(s) of
+ // what's hovered. No color swatch — the hover highlight on the diagram
+ // itself already says which ribbon the card belongs to.
+ #tooltipContext(label) {
+ // max-w-64 gives truncate a constraint to fire against — an absolute
+ // tooltip otherwise grows to fit and never ellipsizes deep flows.
+ return `<div class="max-w-64 text-xs text-secondary mb-1 truncate">${label}</div>`;
+ }
+
+ #showTooltip(event, value, percentage, contextHtml = null) {
+ if (!this.tooltip) this.#createTooltip();
+
+ const valueLine = `<span class="font-medium tabular-nums">${this.#formatCurrency(value)}</span> <span class="text-secondary">(${percentage || 0}%)</span>`;
+ const content = contextHtml
+ ? `${contextHtml}<div>${valueLine}</div>`
+ : valueLine;
+
+ const isInDialog = !!this.element.closest("dialog");
+ const x = isInDialog ? event.clientX : event.pageX;
+ const y = isInDialog ? event.clientY : event.pageY;
+
+ this.tooltip
+ .html(content)
+ .style("position", isInDialog ? "fixed" : "absolute")
+ .style("left", `${x + 10}px`)
+ .style("top", `${y - 10}px`)
+ .transition()
+ .duration(100)
+ .style("opacity", 1);
+ }
+
+ #updateTooltipPosition(event) {
+ if (this.tooltip) {
+ const isInDialog = !!this.element.closest("dialog");
+ const x = isInDialog ? event.clientX : event.pageX;
+ const y = isInDialog ? event.clientY : event.pageY;
+
+ this.tooltip?.style("left", `${x + 10}px`).style("top", `${y - 10}px`);
+ }
+ }
+
+ #hideTooltip() {
+ if (this.tooltip) {
+ this.tooltip
+ ?.transition()
+ .duration(100)
+ .style("opacity", 0)
+ .style("pointer-events", "none");
+ }
+ }
+
+ #formatCurrency(value) {
+ return formatCashFlowCurrency(value, this.currencyValue);
+ }
+}
diff --git a/app/javascript/controllers/sankey_preview_controller.js b/app/javascript/controllers/sankey_preview_controller.js
new file mode 100644
index 0000000000..832fe01f38
--- /dev/null
+++ b/app/javascript/controllers/sankey_preview_controller.js
@@ -0,0 +1,221 @@
+import { Controller } from "@hotwired/stimulus";
+import {
+ capturePreviewEvent,
+ feedbackClient,
+ initializeSelfHostedFeedback,
+ sankeyFeedbackResponse,
+ sankeyFeedbackSurvey,
+} from "utils/sankey_preview_analytics";
+
+export default class extends Controller {
+ static targets = [
+ "display",
+ "expandButton",
+ "expandedDialog",
+ "feedbackDialog",
+ "status",
+ "form",
+ ];
+ static values = {
+ surveyId: String,
+ selfHosted: Boolean,
+ feedbackKey: String,
+ feedbackHost: String,
+ };
+
+ connect() {
+ if (this.selfHostedValue) {
+ initializeSelfHostedFeedback(
+ window.posthog,
+ this.feedbackKeyValue,
+ this.feedbackHostValue,
+ () => document.dispatchEvent(new Event("posthog:ready")),
+ );
+ }
+ this.displays = new Set();
+ this.state = "loading";
+ this.active = true;
+ this.observer = new IntersectionObserver(([entry]) => {
+ this.visible = entry.isIntersecting;
+ this.trackDisplay();
+ });
+ this.observer.observe(this.displayTarget);
+ }
+
+ get posthog() {
+ if (this.selfHostedValue && !this.feedbackKeyValue) return undefined;
+ return feedbackClient(window.posthog, this.selfHostedValue);
+ }
+
+ disconnect() {
+ this.clear();
+ this.observer?.disconnect();
+ }
+
+ clear() {
+ this.dismiss();
+ this.active = false;
+ this.feedbackRequest = null;
+ clearTimeout(this.feedbackTimeout);
+ this.expandedDialogTarget.close();
+ this.restoreDrag();
+ this.feedbackDialogTarget.close();
+ this.formTarget.reset();
+ this.survey = null;
+ }
+
+ update({ detail }) {
+ if (detail.state === "loading") this.displays.clear();
+ this.state = detail.state;
+ this.expandButtonTarget.disabled = !detail.ready;
+ this.trackDisplay();
+ }
+
+ trackDisplay() {
+ if (
+ !this.active ||
+ document.hidden ||
+ !this.visible ||
+ this.state === "loading" ||
+ !this.displayTarget.getClientRects().length
+ )
+ return;
+ // Count each rendered result once. Scrolling and resize callbacks aren't
+ // additional displays; a date-range navigation creates a new controller.
+ const key = `inline:${this.state}`;
+ if (this.displays.has(key)) return;
+ if (
+ capturePreviewEvent(this.posthog, "sankey_preview_displayed", {
+ surface: "inline",
+ state: this.state,
+ })
+ ) {
+ this.displays.add(key);
+ }
+ }
+
+ expand() {
+ if (this.state !== "content" || this.expandedDialogTarget.open) return;
+ this.section = this.element.closest(
+ "[data-dashboard-sortable-target='section']",
+ );
+ this.originalDraggable = this.section?.getAttribute("draggable");
+ this.section?.setAttribute("draggable", "false");
+ this.expandedDialogTarget.showModal();
+ capturePreviewEvent(this.posthog, "sankey_preview_displayed", {
+ surface: "expanded",
+ state: this.state,
+ });
+ }
+
+ restoreDrag() {
+ if (!this.section) return;
+ if (this.originalDraggable === null)
+ this.section.removeAttribute("draggable");
+ else this.section.setAttribute("draggable", this.originalDraggable);
+ this.section = null;
+ }
+
+ stopKeydown(event) {
+ // The enclosing dashboard section also handles Enter/Space for reordering.
+ event.stopPropagation();
+ }
+
+ feedback({ params: { rating } }) {
+ if (!["positive", "negative"].includes(rating)) return;
+ this.rating = rating;
+ this.survey = null;
+ this.sent = false;
+ this.formTarget.reset();
+ this.formTarget.hidden = true;
+ this.statusTarget.textContent = this.statusTarget.dataset.loading;
+ this.feedbackDialogTarget.showModal();
+ const posthog = this.posthog;
+ if (
+ !this.hasSurveyIdValue ||
+ !this.surveyIdValue ||
+ !posthog?.__loaded ||
+ posthog.has_opted_out_capturing?.()
+ ) {
+ this.unavailable();
+ return;
+ }
+ capturePreviewEvent(posthog, "sankey_preview_feedback_clicked", {
+ rating,
+ state: this.state,
+ });
+ const request = {};
+ this.feedbackRequest = request;
+ this.feedbackTimeout = setTimeout(() => {
+ if (this.feedbackRequest === request) this.unavailable();
+ }, 5000);
+ try {
+ posthog.getSurveys((surveys) => {
+ if (
+ !this.active ||
+ this.feedbackRequest !== request ||
+ !this.feedbackDialogTarget.open
+ )
+ return;
+ clearTimeout(this.feedbackTimeout);
+ this.survey = sankeyFeedbackSurvey(surveys, this.surveyIdValue);
+ if (!this.survey) return this.unavailable();
+ this.statusTarget.textContent = "";
+ this.formTarget.querySelector("[data-feedback-question]").textContent =
+ this.survey.feedback.question;
+ const input = this.formTarget.elements.feedback;
+ input.required = !this.survey.feedback.optional;
+ this.formTarget.hidden = false;
+ capturePreviewEvent(posthog, "survey shown", {
+ $survey_id: this.survey.id,
+ });
+ input.focus();
+ });
+ } catch {
+ this.unavailable();
+ }
+ }
+
+ unavailable() {
+ this.feedbackRequest = null;
+ clearTimeout(this.feedbackTimeout);
+ this.formTarget.hidden = true;
+ this.statusTarget.textContent = this.statusTarget.dataset.unavailable;
+ }
+
+ submit(event) {
+ event.preventDefault();
+ if (!this.survey || this.sent) return;
+ const feedback = this.formTarget.elements.feedback.value.trim();
+ if (!feedback && !this.survey.feedback.optional) {
+ this.formTarget.elements.feedback.value = "";
+ this.formTarget.reportValidity();
+ return;
+ }
+ if (
+ !capturePreviewEvent(
+ this.posthog,
+ "survey sent",
+ sankeyFeedbackResponse(this.survey, this.rating, feedback),
+ )
+ ) {
+ this.unavailable();
+ return;
+ }
+ this.sent = true;
+ this.formTarget.reset();
+ this.formTarget.hidden = true;
+ this.statusTarget.textContent = this.statusTarget.dataset.thanks;
+ }
+
+ dismiss() {
+ this.feedbackRequest = null;
+ clearTimeout(this.feedbackTimeout);
+ if (this.survey && !this.sent)
+ capturePreviewEvent(this.posthog, "survey dismissed", {
+ $survey_id: this.survey.id,
+ });
+ this.survey = null;
+ this.formTarget.reset();
+ }
+}
diff --git a/app/javascript/utils/cash_flow_chart_data.mjs b/app/javascript/utils/cash_flow_chart_data.mjs
new file mode 100644
index 0000000000..3534738732
--- /dev/null
+++ b/app/javascript/utils/cash_flow_chart_data.mjs
@@ -0,0 +1,93 @@
+// Decimal strings remain authoritative on the wire. Conversion to Number is
+// exclusively for D3 geometry and locale formatting, never financial totals.
+export function cashFlowChartData(body) {
+ const graph = body.sankey;
+ if (
+ !/^[A-Z]{3,5}$/.test(body.currency) ||
+ graph?.basis !== "net_by_category" ||
+ !Array.isArray(graph.nodes) ||
+ !Array.isArray(graph.links)
+ ) {
+ throw new Error("Invalid cash flow graph");
+ }
+ const number = (value) => {
+ if (
+ typeof value !== "string" ||
+ !/^\d+(\.\d+)?$/.test(value) ||
+ !Number.isFinite(Number(value))
+ ) {
+ throw new Error("Invalid cash flow value");
+ }
+ return Number(value);
+ };
+ const ids = new Set();
+ const nodes = graph.nodes.map((node) => {
+ if (
+ typeof node.id !== "string" ||
+ ids.has(node.id) ||
+ typeof node.name !== "string" ||
+ !["income", "expense", "cash_flow", "surplus", "deficit"].includes(
+ node.kind,
+ )
+ ) {
+ throw new Error("Invalid cash flow node");
+ }
+ ids.add(node.id);
+ const color = /^#[0-9a-f]{6}$/i.test(node.color)
+ ? node.color
+ : ["expense", "deficit"].includes(node.kind)
+ ? "var(--color-destructive)"
+ : "var(--color-success)";
+ const value = number(node.value),
+ percentage = number(node.percentage);
+ if (value <= 0 || percentage > 100)
+ throw new Error("Invalid cash flow node value");
+ return { ...node, value, percentage, color };
+ });
+ const links = graph.links.map((link) => {
+ if (
+ ![link.source, link.target].every(
+ (index) =>
+ Number.isInteger(index) && index >= 0 && index < nodes.length,
+ ) ||
+ link.source === link.target
+ ) {
+ throw new Error("Invalid cash flow link");
+ }
+ const value = number(link.value),
+ percentage = number(link.percentage);
+ if (value <= 0 || percentage > 100)
+ throw new Error("Invalid cash flow link value");
+ return { ...link, value, percentage };
+ });
+ const indegree = nodes.map(() => 0);
+ const outgoing = nodes.map(() => []);
+ links.forEach(({ source, target }) => {
+ indegree[target]++;
+ outgoing[source].push(target);
+ });
+ const queue = indegree.flatMap((count, index) =>
+ count === 0 ? [index] : [],
+ );
+ for (let i = 0; i < queue.length; i++) {
+ outgoing[queue[i]].forEach((target) => {
+ if (--indegree[target] === 0) queue.push(target);
+ });
+ }
+ if (queue.length !== nodes.length) throw new Error("Cyclic cash flow graph");
+ return { nodes, links };
+}
+
+// Sure also supports currencies (such as DOGE/USDC) outside Intl's three-letter
+// currency identifiers. Preserve the unit in that display-only fallback.
+export function formatCashFlowCurrency(value, currency, locale) {
+ try {
+ return Number(value).toLocaleString(locale, {
+ style: "currency",
+ currency,
+ });
+ } catch (error) {
+ if (!(error instanceof RangeError)) throw error;
+ return `${Number(value).toLocaleString(locale, { maximumFractionDigits: 8 })} ${currency}`;
+ }
+}
diff --git a/app/javascript/utils/sankey_preview_analytics.mjs b/app/javascript/utils/sankey_preview_analytics.mjs
new file mode 100644
index 0000000000..eb0e6a749c
--- /dev/null
+++ b/app/javascript/utils/sankey_preview_analytics.mjs
@@ -0,0 +1,118 @@
+export const SANKEY_PREVIEW_VERSION = "cash_flow_v1";
+
+export function capturePreviewEvent(posthog, event, properties = {}) {
+ try {
+ if (!posthog?.__loaded || posthog.has_opted_out_capturing?.()) return false;
+ return Boolean(
+ posthog.capture(event, {
+ preview_version: SANKEY_PREVIEW_VERSION,
+ ...properties,
+ }),
+ );
+ } catch {
+ // Analytics availability must not affect the financial view.
+ return false;
+ }
+}
+
+// The project owns the question UUIDs. Resolve them by type, never by order.
+export function sankeyFeedbackSurvey(surveys, id) {
+ if (!Array.isArray(surveys)) return null;
+ const survey = surveys.find((candidate) => candidate?.id === id);
+ if (
+ !survey ||
+ survey.type !== "api" ||
+ !survey.start_date ||
+ survey.end_date ||
+ survey.archived
+ )
+ return null;
+ if (!Array.isArray(survey.questions) || survey.questions.length !== 2)
+ return null;
+ const rating = survey.questions.find((q) => q?.type === "single_choice");
+ const feedback = survey.questions.find((q) => q?.type === "open");
+ if (
+ !rating?.id ||
+ !feedback?.id ||
+ !feedback.question ||
+ !Array.isArray(rating.choices) ||
+ rating.choices.length !== 2 ||
+ !rating.choices.includes("Looks right") ||
+ !rating.choices.includes("Something looks wrong")
+ )
+ return null;
+ return { id: survey.id, rating, feedback };
+}
+
+export function sankeyFeedbackResponse(survey, rating, feedback) {
+ return {
+ $survey_id: survey.id,
+ [`$survey_response_${survey.rating.id}`]:
+ rating === "positive" ? "Looks right" : "Something looks wrong",
+ [`$survey_response_${survey.feedback.id}`]: feedback,
+ };
+}
+
+export function feedbackClient(posthog, selfHosted) {
+ if (posthog?.has_opted_out_capturing?.()) return undefined;
+ return selfHosted ? posthog?.sankeyFeedback : posthog;
+}
+
+export function selfHostedFeedbackOptions(host) {
+ return {
+ api_host: host,
+ defaults: "2025-11-30",
+ person_profiles: "never",
+ persistence: "memory",
+ autocapture: false,
+ capture_pageview: false,
+ capture_pageleave: false,
+ capture_dead_clicks: false,
+ capture_exceptions: false,
+ capture_heatmaps: false,
+ capture_performance: false,
+ disable_session_recording: true,
+ enable_recording_console_log: false,
+ disable_surveys: false,
+ before_send: sanitizeSelfHostedFeedback,
+ };
+}
+
+// A separate project must not receive SDK page URLs, referrers, person data,
+// or any other telemetry from a self-hosted installation.
+export function sanitizeSelfHostedFeedback(event) {
+ if (!event || ![
+ "sankey_preview_displayed",
+ "sankey_preview_feedback_clicked",
+ "survey shown",
+ "survey sent",
+ "survey dismissed",
+ ].includes(event.event)) return null;
+ // The browser SDK carries its public ingestion token inside properties.
+ const allowed = new Set([
+ "token", "distinct_id", "preview_version", "surface", "state", "rating", "$survey_id",
+ ]);
+ event.properties = Object.fromEntries(
+ Object.entries(event.properties || {}).filter(([key]) =>
+ allowed.has(key) || (event.event === "survey sent" && /^\$survey_response_[\da-f-]+$/i.test(key)),
+ ),
+ );
+ delete event.$set;
+ delete event.$set_once;
+ event.properties.$geoip_disable = true;
+ event.properties.$process_person_profile = false;
+ return event;
+}
+
+export function initializeSelfHostedFeedback(posthog, key, host, loaded) {
+ try {
+ if (!key || posthog?.sankeyFeedback || posthog?.has_opted_out_capturing?.()) return;
+ posthog?.init?.(key, {
+ ...selfHostedFeedbackOptions(host),
+ // The SDK assigns named instances after their loaded callback returns.
+ loaded: () => queueMicrotask(loaded),
+ }, "sankeyFeedback");
+ } catch {
+ // Blocked analytics must not prevent chart setup or navigation.
+ }
+}
diff --git a/app/models/income_statement/cash_flow.rb b/app/models/income_statement/cash_flow.rb
index 61e52505a5..6a1b90cfbd 100644
--- a/app/models/income_statement/cash_flow.rb
+++ b/app/models/income_statement/cash_flow.rb
@@ -1,13 +1,14 @@
# A bounded monthly projection of Sure's existing reporting calculations.
# The client never needs to download transaction history to reproduce these rules.
class IncomeStatement::CashFlow
- def initialize(statement, month:, as_of: Date.current, time_zone: Time.zone.tzinfo.identifier)
+ def initialize(statement, month:, as_of: Date.current, time_zone: Time.zone.tzinfo.identifier, include_sankey: false)
raise ArgumentError, "month must be a non-future first day" unless month.day == 1 && month <= as_of
@statement = statement
@month = month
@as_of = as_of
@time_zone = time_zone
+ @include_sankey = include_sankey
end
def as_json(*)
@@ -23,7 +24,7 @@ class IncomeStatement::CashFlow
previous_total = previous.fetch(comparison_day - 1).fetch(:amount).to_d
current_total = current.last.fetch(:amount).to_d
- {
+ result = {
month: @month.iso8601, as_of: @as_of.iso8601, time_zone: @time_zone,
currency: @statement.family.currency,
period: period_json(current_period), income: decimal(income), spending: decimal(spending),
@@ -36,6 +37,8 @@ class IncomeStatement::CashFlow
delta: decimal(current_total - previous_total), current: current, previous: previous
}
}
+ result[:sankey] = IncomeStatement::Sankey.new(@statement, period: current_period).as_json if @include_sankey
+ result
end
private
diff --git a/app/models/income_statement/cash_flow_graph.rb b/app/models/income_statement/cash_flow_graph.rb
new file mode 100644
index 0000000000..7d36efaa61
--- /dev/null
+++ b/app/models/income_statement/cash_flow_graph.rb
@@ -0,0 +1,15 @@
+# Shared graph representation for the public API and session-authenticated web UI.
+# Aggregation stays in Sankey; neither controller builds its own financial totals.
+class IncomeStatement::CashFlowGraph
+ def initialize(statement, period:, as_of: Date.current, time_zone: Time.zone.tzinfo.identifier)
+ @statement, @period, @as_of, @time_zone = statement, period, as_of, time_zone
+ end
+
+ def as_json(*)
+ {
+ as_of: @as_of.iso8601, time_zone: @time_zone, currency: @statement.family.currency,
+ period: { start_date: @period.start_date.iso8601, end_date: @period.end_date.iso8601 },
+ sankey: IncomeStatement::Sankey.new(@statement, period: @period).as_json
+ }
+ end
+end
diff --git a/app/models/income_statement/sankey.rb b/app/models/income_statement/sankey.rb
new file mode 100644
index 0000000000..4522c055d5
--- /dev/null
+++ b/app/models/income_statement/sankey.rb
@@ -0,0 +1,101 @@
+# Nets refunds within each category before arranging flows. Parent totals already
+# include children: subtract those children before partitioning by direction, so
+# a refund in a child cannot be counted again in its parent's net amount.
+class IncomeStatement::Sankey
+ def initialize(statement, period:)
+ @statement, @period = statement, period
+ end
+
+ def as_json(*)
+ @nodes, @links = [], []
+ groups = category_groups
+ income = groups.sum { |group| side_total(group, :income) }.to_d
+ spending = groups.sum { |group| side_total(group, :expense) }.to_d
+ capacity = [ income, spending ].max
+ unless capacity.zero?
+ center = add_node("cash_flow_node", "Cash Flow", :cash_flow, capacity, 100)
+ groups.each do |group|
+ add_group(group, :income, income, center)
+ add_group(group, :expense, spending, center)
+ end
+ net = income - spending
+ unless net.zero?
+ kind = net.positive? ? :surplus : :deficit
+ index = add_node("#{kind}_node", kind.to_s.capitalize, kind, net.abs, percentage(net.abs, capacity))
+ source, target = net.positive? ? [ center, index ] : [ index, center ]
+ add_link(source, target, net.abs, percentage(net.abs, capacity))
+ end
+ end
+ { basis: "net_by_category", income: decimal(income), spending: decimal(spending),
+ net_savings: decimal(income - spending), nodes: @nodes, links: @links }
+ end
+
+ private
+ # Keep this hierarchy-aware netting separate from IncomeStatement#net_category_totals
+ # while the original dashboard Sankey remains available for preview comparisons.
+ def category_groups
+ expense = @statement.expense_totals(period: @period).category_totals.index_by { |ct| category_key(ct.category) }
+ income = @statement.income_totals(period: @period).category_totals.index_by { |ct| category_key(ct.category) }
+ entries = (expense.keys | income.keys).sort.map do |key|
+ category = (expense[key] || income[key]).category
+ { category: category, net: (expense[key]&.total || 0).to_d - (income[key]&.total || 0).to_d }
+ end
+ children = entries.select { |entry| entry[:category].subcategory? }.group_by { |entry| entry[:category].parent_id }
+ entries.reject { |entry| entry[:category].subcategory? }.map do |root|
+ subs = children.fetch(root[:category].id, [])
+ { category: root[:category], direct: root[:net] - subs.sum { |sub| sub[:net] }, children: subs }
+ end
+ end
+
+ def category_key(category)
+ return "uncategorized" if category.uncategorized?
+ return "other_investments" if category.other_investments?
+ category.id
+ end
+
+ def side_amount(net, side)
+ [ side == :expense ? net : -net, 0 ].max
+ end
+
+ def side_total(group, side)
+ side_amount(group[:direct], side) + group[:children].sum { |child| side_amount(child[:net], side) }
+ end
+
+ def add_group(group, side, total, center)
+ amount = side_total(group, side)
+ return if amount.zero?
+ category = group[:category]
+ pct = percentage(amount, total)
+ root = add_node("#{side}_#{category_key(category)}", category.name, side, amount, pct, category)
+ source, target = side == :income ? [ root, center ] : [ center, root ]
+ add_link(source, target, amount, pct)
+ group[:children].each do |child|
+ value = side_amount(child[:net], side)
+ next if value.zero?
+ category = child[:category]
+ pct = percentage(value, amount)
+ index = add_node("#{side}_sub_#{category.id}", category.name, side, value, pct, category)
+ source, target = side == :income ? [ index, root ] : [ root, index ]
+ add_link(source, target, value, pct)
+ end
+ end
+
+ def add_node(id, name, kind, value, percentage, category = nil)
+ @nodes << { id: id, name: name, kind: kind.to_s, value: decimal(value), percentage: decimal(percentage),
+ category_id: category&.id, filter_value: category && !category.other_investments? ? category.filter_value : nil,
+ color: category&.color }
+ @nodes.size - 1
+ end
+
+ def add_link(source, target, value, percentage)
+ @links << { source: source, target: target, value: decimal(value), percentage: decimal(percentage) }
+ end
+
+ def percentage(value, total)
+ total.zero? ? 0 : (value.to_d / total * 100).round(1)
+ end
+
+ def decimal(value)
+ value.to_d.to_s("F")
+ end
+end
diff --git a/app/views/pages/dashboard.html.erb b/app/views/pages/dashboard.html.erb
index 997d5eb4aa..fa7c4311b8 100644
--- a/app/views/pages/dashboard.html.erb
+++ b/app/views/pages/dashboard.html.erb
@@ -169,6 +169,9 @@
</div>
<div class="py-4" data-dashboard-section-target="content">
<%= render partial: section[:partial], locals: section[:locals] %>
+ <% if section[:key] == "cashflow_sankey" && preview_features_enabled? %>
+ <%= render "pages/dashboard/cashflow_preview", period: @period %>
+ <% end %>
</div>
</section>
<% end %>
diff --git a/app/views/pages/dashboard/_cashflow_preview.html.erb b/app/views/pages/dashboard/_cashflow_preview.html.erb
new file mode 100644
index 0000000000..89a8031a0e
--- /dev/null
+++ b/app/views/pages/dashboard/_cashflow_preview.html.erb
@@ -0,0 +1,70 @@
+<%# locals: (period:) %>
+<% feedback = feedback_config(:sankey) %>
+<% if feedback[:api_key].present? %>
+ <%= render "shared/posthog_bootstrap" %>
+<% end %>
+<section id="cashflow-preview" class="mt-6 border-t border-primary pt-4 space-y-4"
+ data-controller="sankey-preview"
+ data-sankey-preview-self-hosted-value="<%= self_hosted? %>"
+ data-sankey-preview-feedback-key-value="<%= feedback[:api_key] %>"
+ data-sankey-preview-feedback-host-value="<%= feedback[:host] %>"
+ data-sankey-preview-survey-id-value="<%= feedback[:survey_id] %>"
+ data-action="cash-flow:state->sankey-preview#update posthog:ready@document->sankey-preview#trackDisplay visibilitychange@document->sankey-preview#trackDisplay turbo:before-cache@document->sankey-preview#clear keydown->sankey-preview#stopKeydown">
+ <header class="px-4 flex flex-wrap items-center justify-between gap-2">
+ <div class="flex flex-wrap items-center gap-2">
+ <h3 class="font-medium text-primary"><%= t("pages.dashboard.cashflow_preview.title") %></h3>
+ <%= render DS::Pill.new(label: t("pages.dashboard.cashflow_preview.preview")) %>
+ </div>
+ <%= render DS::Button.new(icon: "maximize-2", text: t("global.expand"), variant: :ghost, disabled: true,
+ data: { action: "sankey-preview#expand", sankey_preview_target: "expandButton" }) %>
+ </header>
+ <p class="px-4 text-sm text-secondary"><%= t("pages.dashboard.cashflow_preview.description") %></p>
+ <div data-controller="cash-flow" data-sankey-preview-target="display" class="ph-no-capture"
+ data-action="turbo:before-cache@document->cash-flow#clear"
+ data-cash-flow-url-value="<%= dashboard_cash_flow_path(start_date: period.start_date.iso8601, end_date: period.end_date.iso8601) %>">
+ <p data-cash-flow-target="loading" role="status" class="p-4 text-secondary"><%= t("pages.dashboard.cashflow_sankey.loading") %></p>
+ <div data-cash-flow-target="error" hidden role="alert" class="p-4 space-y-3">
+ <p><%= t("pages.dashboard.cashflow_sankey.load_error") %></p>
+ <%= render DS::Button.new(text: t("pages.dashboard.cashflow_sankey.retry"), data: { action: "cash-flow#load" }) %>
+ </div>
+ <div data-cash-flow-target="content" hidden>
+ <div class="w-full h-96 overflow-x-auto overscroll-x-contain" tabindex="0" role="region" aria-label="<%= t("pages.dashboard.cashflow_preview.title") %>"><%= render "pages/dashboard/cashflow_preview_chart", period: period %></div>
+ <%= render DS::Dialog.new(id: "cashflow-preview-expanded-dialog", auto_open: false, width: "expanded", disable_frame: true,
+ data: { sankey_preview_target: "expandedDialog", action: "close->sankey-preview#restoreDrag" }) do |dialog| %>
+ <% dialog.with_header(title: t("pages.dashboard.cashflow_preview.title")) %>
+ <% dialog.with_body do %>
+ <div class="w-full h-[85dvh] max-h-[90dvh] overflow-auto overscroll-contain" tabindex="0" role="region" aria-label="<%= t("pages.dashboard.cashflow_preview.title") %>">
+ <%= render "pages/dashboard/cashflow_preview_chart", period: period %>
+ </div>
+ <% end %>
+ <% end %>
+ <p class="px-4 text-xs text-secondary"><%= t("pages.dashboard.cashflow_sankey.basis") %></p>
+ </div>
+ <p data-cash-flow-target="empty" hidden class="p-4 text-secondary"><%= t("pages.dashboard.cashflow_sankey.no_data_title") %></p>
+ </div>
+ <div class="px-4 flex flex-wrap items-center gap-2 ph-no-capture">
+ <p class="text-sm text-secondary"><%= t("pages.dashboard.cashflow_preview.feedback_prompt") %></p>
+ <%= render DS::Button.new(icon: "thumbs-up", text: t("pages.dashboard.cashflow_preview.positive"), variant: :outline,
+ data: { action: "sankey-preview#feedback", sankey_preview_rating_param: "positive" }) %>
+ <%= render DS::Button.new(icon: "thumbs-down", text: t("pages.dashboard.cashflow_preview.negative"), variant: :outline,
+ data: { action: "sankey-preview#feedback", sankey_preview_rating_param: "negative" }) %>
+ </div>
+ <%= render DS::Dialog.new(id: "cashflow-preview-feedback-dialog", auto_open: false, disable_frame: true,
+ data: { sankey_preview_target: "feedbackDialog", action: "close->sankey-preview#dismiss" }) do |dialog| %>
+ <% dialog.with_header(title: t("pages.dashboard.cashflow_preview.feedback_title")) %>
+ <% dialog.with_body do %>
+ <p role="status" data-sankey-preview-target="status"
+ data-loading="<%= t("pages.dashboard.cashflow_preview.feedback_loading") %>"
+ data-unavailable="<%= t("pages.dashboard.cashflow_preview.feedback_unavailable") %>"
+ data-thanks="<%= t("pages.dashboard.cashflow_preview.feedback_thanks") %>"></p>
+ <form hidden data-sankey-preview-target="form" data-action="submit->sankey-preview#submit" class="space-y-4 ph-no-capture">
+ <label for="cashflow-preview-feedback" class="block text-sm font-medium" data-feedback-question></label>
+ <textarea id="cashflow-preview-feedback" name="feedback" rows="4" maxlength="2000"
+ aria-describedby="cashflow-preview-feedback-privacy"
+ class="w-full rounded-lg border border-primary bg-container text-primary ph-no-capture"></textarea>
+ <p id="cashflow-preview-feedback-privacy" class="text-xs text-secondary"><%= t("pages.dashboard.cashflow_preview.feedback_privacy") %></p>
+ <%= render DS::Button.new(text: t("pages.dashboard.cashflow_preview.feedback_submit"), type: :submit) %>
+ </form>
+ <% end %>
+ <% end %>
+</section>
diff --git a/app/views/pages/dashboard/_cashflow_preview_chart.html.erb b/app/views/pages/dashboard/_cashflow_preview_chart.html.erb
new file mode 100644
index 0000000000..0967405621
--- /dev/null
+++ b/app/views/pages/dashboard/_cashflow_preview_chart.html.erb
@@ -0,0 +1,25 @@
+<%# locals: (period:) %>
+<div
+ data-controller="preview-sankey-chart"
+ data-action="turbo:before-cache@document->preview-sankey-chart#clear"
+ data-cash-flow-target="chart"
+ data-preview-sankey-chart-labels-value="<%= t("pages.dashboard.cashflow_preview.node_labels").to_json %>"
+ data-preview-sankey-chart-start-date-value="<%= period.start_date&.iso8601 %>"
+ data-preview-sankey-chart-end-date-value="<%= period.end_date&.iso8601 %>"
+ class="w-full min-w-lg h-full privacy-sensitive flex flex-col gap-2">
+ <div class="flex justify-start px-4">
+ <%= render DS::Button.new(
+ variant: :icon,
+ icon: "arrow-left",
+ type: "button",
+ title: t("pages.dashboard.cashflow_sankey.zoom_out"),
+ aria: { label: t("pages.dashboard.cashflow_sankey.zoom_out") },
+ hidden: true,
+ data: {
+ preview_sankey_chart_target: "zoomOutButton",
+ action: "preview-sankey-chart#zoomOut"
+ }
+ ) %>
+ </div>
+ <div data-preview-sankey-chart-target="chart" class="min-h-0 flex-1"></div>
+</div>
diff --git a/app/views/shared/_posthog.html.erb b/app/views/shared/_posthog.html.erb
index 8258d48a28..f219063aa3 100644
--- a/app/views/shared/_posthog.html.erb
+++ b/app/views/shared/_posthog.html.erb
@@ -1,9 +1,9 @@
-<!-- PostHog -->
+<%= render "shared/posthog_bootstrap" %>
<script nonce="<%= content_security_policy_nonce %>">
- !function(t,e){var o,n,p,r;e.__SV||(window.posthog && window.posthog.__loaded)||(window.posthog=e,e._i=[],e.init=function(i,s,a){function g(t,e){var o=e.split(".");2==o.length&&(t=t[o[0]],e=o[1]),t[e]=function(){t.push([e].concat(Array.prototype.slice.call(arguments,0)))}}(p=t.createElement("script")).type="text/javascript",p.crossOrigin="anonymous",p.async=!0,p.src=s.api_host.replace(".i.posthog.com","-assets.i.posthog.com")+"/static/array.js",(r=t.getElementsByTagName("script")[0]).parentNode.insertBefore(p,r);var u=e;for(void 0!==a?u=e[a]=[]:a="posthog",u.people=u.people||[],u.toString=function(t){var e="posthog";return"posthog"!==a&&(e+="."+a),t||(e+=" (stub)"),e},u.people.toString=function(){return u.toString(1)+".people (stub)"},o="init ss us bi os hs es ns capture Bi calculateEventProperties cs register register_once register_for_session unregister unregister_for_session getFeatureFlag getFeatureFlagPayload isFeatureEnabled reloadFeatureFlags updateFlags updateEarlyAccessFeatureEnrollment getEarlyAccessFeatures on onFeatureFlags onSurveysLoaded onSessionId getSurveys getActiveMatchingSurveys renderSurvey displaySurvey cancelPendingSurvey canRenderSurvey canRenderSurveyAsync identify setPersonProperties group resetGroups setPersonPropertiesForFlags resetPersonPropertiesForFlags setGroupPropertiesForFlags resetGroupPropertiesForFlags reset get_distinct_id getGroups get_session_id get_session_replay_url alias set_config startSessionRecording stopSessionRecording sessionRecordingStarted captureException startExceptionAutocapture stopExceptionAutocapture loadToolbar get_property getSessionProperty ps vs createPersonProfile gs Zr ys opt_in_capturing opt_out_capturing has_opted_in_capturing has_opted_out_capturing get_explicit_consent_status is_capturing clear_opt_in_out_capturing ds debug O fs getPageViewId captureTraceFeedback captureTraceMetric Yr".split(" "),n=0;n<o.length;n++)g(u,o[n]);e._i.push([i,s,a])},e.__SV=1)}(document,window.posthog||[]);
posthog.init('<%= posthog_api_key %>', {
api_host: '<%= posthog_host %>',
defaults: '2025-11-30',
person_profiles: 'always', // or 'identified_only'
+ loaded: function() { document.dispatchEvent(new Event('posthog:ready')); },
})
</script>
diff --git a/app/views/shared/_posthog_bootstrap.html.erb b/app/views/shared/_posthog_bootstrap.html.erb
new file mode 100644
index 0000000000..258017c38e
--- /dev/null
+++ b/app/views/shared/_posthog_bootstrap.html.erb
@@ -0,0 +1,3 @@
+<script nonce="<%= content_security_policy_nonce %>">
+ !function(t,e){var o,n,p,r;e.__SV||(window.posthog && window.posthog.__loaded)||(window.posthog=e,e._i=[],e.init=function(i,s,a){function g(t,e){var o=e.split(".");2==o.length&&(t=t[o[0]],e=o[1]),t[e]=function(){t.push([e].concat(Array.prototype.slice.call(arguments,0)))}}(p=t.createElement("script")).type="text/javascript",p.crossOrigin="anonymous",p.async=!0,p.src=s.api_host.replace(".i.posthog.com","-assets.i.posthog.com")+"/static/array.js",(r=t.getElementsByTagName("script")[0]).parentNode.insertBefore(p,r);var u=e;for(void 0!==a?u=e[a]=[]:a="posthog",u.people=u.people||[],u.toString=function(t){var e="posthog";return"posthog"!==a&&(e+="."+a),t||(e+=" (stub)"),e},u.people.toString=function(){return u.toString(1)+".people (stub)"},o="init ss us bi os hs es ns capture Bi calculateEventProperties cs register register_once register_for_session unregister unregister_for_session getFeatureFlag getFeatureFlagPayload isFeatureEnabled reloadFeatureFlags updateFlags updateEarlyAccessFeatureEnrollment getEarlyAccessFeatures on onFeatureFlags onSurveysLoaded onSessionId getSurveys getActiveMatchingSurveys renderSurvey displaySurvey cancelPendingSurvey canRenderSurvey canRenderSurveyAsync identify setPersonProperties group resetGroups setPersonPropertiesForFlags resetPersonPropertiesForFlags setGroupPropertiesForFlags resetGroupPropertiesForFlags reset get_distinct_id getGroups get_session_id get_session_replay_url alias set_config startSessionRecording stopSessionRecording sessionRecordingStarted captureException startExceptionAutocapture stopExceptionAutocapture loadToolbar get_property getSessionProperty ps vs createPersonProfile gs Zr ys opt_in_capturing opt_out_capturing has_opted_in_capturing has_opted_out_capturing get_explicit_consent_status is_capturing clear_opt_in_out_capturing ds debug O fs getPageViewId captureTraceFeedback captureTraceMetric Yr".split(" "),n=0;n<o.length;n++)g(u,o[n]);e._i.push([i,s,a])},e.__SV=1)}(document,window.posthog||[]);
+</script>
diff --git a/config/importmap.rb b/config/importmap.rb
index 0077d95cd8..e4e4e0b276 100644
--- a/config/importmap.rb
+++ b/config/importmap.rb
@@ -58,3 +58,5 @@ pin "d3-shape-src", to: "d3-shape.js"
# "What's new" release highlight popover
pin "driver.js", to: "driver.js.mjs" # @1.8.0
+pin "utils/cash_flow_chart_data", to: "utils/cash_flow_chart_data.mjs"
+pin "utils/sankey_preview_analytics", to: "utils/sankey_preview_analytics.mjs"
diff --git a/config/initializers/posthog.rb b/config/initializers/posthog.rb
index 0d87f53b93..cf803da464 100644
--- a/config/initializers/posthog.rb
+++ b/config/initializers/posthog.rb
@@ -3,6 +3,22 @@ require "posthog"
Rails.configuration.x.posthog = ActiveSupport::OrderedOptions.new
Rails.configuration.x.posthog.api_key = ENV["POSTHOG_KEY"].presence
Rails.configuration.x.posthog.host = ENV.fetch("POSTHOG_HOST", "https://us.i.posthog.com")
+Rails.configuration.x.posthog.feedback_enabled = ActiveModel::Type::Boolean.new.cast(ENV.fetch("POSTHOG_FEEDBACK_ENABLED", "true"))
+# Public client configuration for the shared self-hosted feedback project.
+# This write-only project token is safe to distribute; it is not an admin key.
+# https://posthog.com/docs/api
+Rails.configuration.x.posthog.self_hosted_feedback_project = {
+ api_key: "phc_D4stYbjnouz4J3H434HjYNQ655XG4vqL99HJH7cA4zMk",
+ host: "https://us.i.posthog.com"
+}.freeze
+# Register each feature's survey separately from the shared project destination.
+# Managed app/demo deployments provide the survey belonging to their own project.
+Rails.configuration.x.posthog.feedback_surveys = {
+ sankey: {
+ managed: ENV["POSTHOG_SANKEY_SURVEY_ID"].presence,
+ self_hosted: "01a0a162-73a2-0000-9402-ffab5bc45b4a"
+ }.freeze
+}.freeze
if (api_key = Rails.configuration.x.posthog.api_key).present?
# Initialize PostHog client
diff --git a/config/locales/views/pages/ca.yml b/config/locales/views/pages/ca.yml
index 13f95e8863..2d54f525cc 100644
--- a/config/locales/views/pages/ca.yml
+++ b/config/locales/views/pages/ca.yml
@@ -20,6 +20,11 @@ ca:
title: Balanç patrimonial
value: Valor
weight: Pes
+ cashflow_preview:
+ node_labels:
+ cash_flow: "Flux de caixa"
+ surplus: "Superàvit"
+ deficit: "Dèficit"
cashflow_sankey:
add_transaction: Afegeix una transacció
no_data_description: Afegeix transaccions per mostrar dades de flux de caixa
diff --git a/config/locales/views/pages/de.yml b/config/locales/views/pages/de.yml
index 071e706dfe..9a0c33651e 100644
--- a/config/locales/views/pages/de.yml
+++ b/config/locales/views/pages/de.yml
@@ -38,6 +38,11 @@ de:
no_liability: Noch keine Verbindlichkeiten
value: Wert
weight: Anteil
+ cashflow_preview:
+ node_labels:
+ cash_flow: "Zahlungsfluss"
+ surplus: "Überschuss"
+ deficit: "Fehlbetrag"
cashflow_sankey:
title: "Cashflow"
no_data_title: "Keine Cashflow-Daten für diesen Zeitraum"
diff --git a/config/locales/views/pages/en.yml b/config/locales/views/pages/en.yml
index d1b705bc1d..59c45fd43b 100644
--- a/config/locales/views/pages/en.yml
+++ b/config/locales/views/pages/en.yml
@@ -78,7 +78,28 @@ en:
liability: "Liabilities"
insights_feed:
title: "Insights"
+ cashflow_preview:
+ node_labels:
+ cash_flow: "Cash Flow"
+ surplus: "Surplus"
+ deficit: "Deficit"
+ title: "New cash flow chart"
+ preview: "Preview"
+ description: "Compare this chart with the original above and let us know what looks different."
+ feedback_prompt: "Does this chart look right?"
+ positive: "Looks right"
+ negative: "Something looks wrong"
+ feedback_title: "Cash flow chart feedback"
+ feedback_loading: "Loading feedback form…"
+ feedback_unavailable: "Feedback isn't available right now. Please try again later."
+ feedback_thanks: "Thanks for helping improve the chart!"
+ feedback_privacy: "Your response is sent to PostHog. Describe the issue without account numbers, balances, or other private financial details."
+ feedback_submit: "Send feedback"
cashflow_sankey:
+ loading: "Loading cash flow…"
+ load_error: "Cash flow could not be loaded. Please try again."
+ retry: "Try again"
+ basis: "Refunds are netted within each category. Surplus or deficit balances the flow."
title: "Cashflow"
zoom_out: "Back to full cashflow"
no_data_title: "No cash flow data for this time period"
diff --git a/config/locales/views/pages/es.yml b/config/locales/views/pages/es.yml
index a6ac261343..889b44ea55 100644
--- a/config/locales/views/pages/es.yml
+++ b/config/locales/views/pages/es.yml
@@ -74,6 +74,11 @@ es:
classifications:
asset: Activos
liability: Pasivos
+ cashflow_preview:
+ node_labels:
+ cash_flow: "Flujo de caja"
+ surplus: "Superávit"
+ deficit: "Déficit"
cashflow_sankey:
title: Flujo de caja
zoom_out: Volver al flujo de caja completo
diff --git a/config/locales/views/pages/fr.yml b/config/locales/views/pages/fr.yml
index 89f2c8c7f1..9d33c06151 100644
--- a/config/locales/views/pages/fr.yml
+++ b/config/locales/views/pages/fr.yml
@@ -18,6 +18,11 @@ fr:
title: Bilan
value: Valeur
weight: Poids
+ cashflow_preview:
+ node_labels:
+ cash_flow: "Flux de trésorerie"
+ surplus: "Excédent"
+ deficit: "Déficit"
cashflow_sankey:
add_transaction: Ajouter une transaction
no_data_description: Ajoutez des transactions pour afficher les données de flux de trésorerie ou étendez la période
diff --git a/config/locales/views/pages/hu.yml b/config/locales/views/pages/hu.yml
index b1393e2b71..6857dba38f 100644
--- a/config/locales/views/pages/hu.yml
+++ b/config/locales/views/pages/hu.yml
@@ -61,6 +61,11 @@ hu:
classifications:
asset: "Vagyon"
liability: "Kötelezettségek"
+ cashflow_preview:
+ node_labels:
+ cash_flow: "Pénzforgalom"
+ surplus: "Többlet"
+ deficit: "Hiány"
cashflow_sankey:
title: "Pénzforgalom"
no_data_title: "Nincs pénzforgalmi adat erre az időszakra"
diff --git a/config/locales/views/pages/it.yml b/config/locales/views/pages/it.yml
index d9d73da0c7..c668f7de5d 100644
--- a/config/locales/views/pages/it.yml
+++ b/config/locales/views/pages/it.yml
@@ -74,6 +74,11 @@ it:
classifications:
asset: "Attività"
liability: "Passività"
+ cashflow_preview:
+ node_labels:
+ cash_flow: "Flusso di cassa"
+ surplus: "Avanzo"
+ deficit: "Disavanzo"
cashflow_sankey:
title: "Flusso di cassa"
zoom_out: "Torna al flusso completo"
diff --git a/config/locales/views/pages/nb.yml b/config/locales/views/pages/nb.yml
index be70bf4644..7456912373 100644
--- a/config/locales/views/pages/nb.yml
+++ b/config/locales/views/pages/nb.yml
@@ -4,6 +4,11 @@ nb:
changelog:
title: Hva er nytt
dashboard:
+ cashflow_preview:
+ node_labels:
+ cash_flow: "Kontantstrøm"
+ surplus: "Overskudd"
+ deficit: "Underskudd"
net_worth_chart:
data_not_available: Data ikke tilgjengelig for den valgte perioden
title: Nettoformue
diff --git a/config/locales/views/pages/nl.yml b/config/locales/views/pages/nl.yml
index c24ebb0895..7ccd76b86e 100644
--- a/config/locales/views/pages/nl.yml
+++ b/config/locales/views/pages/nl.yml
@@ -4,6 +4,11 @@ nl:
changelog:
title: Wat is er nieuw
dashboard:
+ cashflow_preview:
+ node_labels:
+ cash_flow: "Kasstroom"
+ surplus: "Overschot"
+ deficit: "Tekort"
welcome: "Welkom terug, %{name}"
subtitle: "Dit gebeurt er met uw financiën"
new: "Nieuw"
diff --git a/config/locales/views/pages/pl.yml b/config/locales/views/pages/pl.yml
index 5b70ceeabb..8d1bb4523f 100644
--- a/config/locales/views/pages/pl.yml
+++ b/config/locales/views/pages/pl.yml
@@ -4,6 +4,11 @@ pl:
changelog:
title: Co nowego
dashboard:
+ cashflow_preview:
+ node_labels:
+ cash_flow: "Przepływ gotówki"
+ surplus: "Nadwyżka"
+ deficit: "Deficyt"
balance_sheet:
add_accounts: Dodaj konta %{name}, aby zobaczyć pełny podział
add_asset_accounts: Dodaj konta aktywów, aby zobaczyć pełny podział
diff --git a/config/locales/views/pages/pt-BR.yml b/config/locales/views/pages/pt-BR.yml
index a64be88515..abdcaada7a 100644
--- a/config/locales/views/pages/pt-BR.yml
+++ b/config/locales/views/pages/pt-BR.yml
@@ -4,6 +4,11 @@ pt-BR:
changelog:
title: Novidades
dashboard:
+ cashflow_preview:
+ node_labels:
+ cash_flow: "Fluxo de caixa"
+ surplus: "Superávit"
+ deficit: "Déficit"
welcome: "Bem-vindo(a) de volta, %{name}"
subtitle: "Veja o que está acontecendo com suas finanças"
new: "Novo"
diff --git a/config/locales/views/pages/pt-PT.yml b/config/locales/views/pages/pt-PT.yml
index 03bf9286b5..61c0e60161 100644
--- a/config/locales/views/pages/pt-PT.yml
+++ b/config/locales/views/pages/pt-PT.yml
@@ -38,6 +38,11 @@ pt-PT:
heading: Termos de Serviço
placeholder: O conteúdo dos termos de serviço será apresentado aqui.
dashboard:
+ cashflow_preview:
+ node_labels:
+ cash_flow: "Fluxo de caixa"
+ surplus: "Excedente"
+ deficit: "Défice"
welcome: "Bem-vindo(a) de volta, %{name}"
subtitle: "Acompanhe a evolução das suas finanças"
new: "Novo"
diff --git a/config/locales/views/pages/ro.yml b/config/locales/views/pages/ro.yml
index 687d45bc65..b525b1e8b1 100644
--- a/config/locales/views/pages/ro.yml
+++ b/config/locales/views/pages/ro.yml
@@ -4,6 +4,11 @@ ro:
changelog:
title: Ce e nou
dashboard:
+ cashflow_preview:
+ node_labels:
+ cash_flow: "Flux de numerar"
+ surplus: "Excedent"
+ deficit: "Deficit"
welcome: "Bun venit, %{name}"
subtitle: "Iată ce se întâmplă cu finanțele tale"
new: "Nou"
diff --git a/config/locales/views/pages/ru.yml b/config/locales/views/pages/ru.yml
index 3d159b4e37..984519ef4e 100644
--- a/config/locales/views/pages/ru.yml
+++ b/config/locales/views/pages/ru.yml
@@ -4,6 +4,11 @@ ru:
changelog:
title: Что нового
dashboard:
+ cashflow_preview:
+ node_labels:
+ cash_flow: "Денежный поток"
+ surplus: "Профицит"
+ deficit: "Дефицит"
balance_sheet:
add_accounts: Добавьте счета %{name}, чтобы увидеть разбивку
add_asset_accounts: Добавьте счета активов
diff --git a/config/locales/views/pages/tr.yml b/config/locales/views/pages/tr.yml
index 6ec5c20073..75162d034b 100644
--- a/config/locales/views/pages/tr.yml
+++ b/config/locales/views/pages/tr.yml
@@ -4,6 +4,11 @@ tr:
changelog:
title: Yenilikler
dashboard:
+ cashflow_preview:
+ node_labels:
+ cash_flow: "Nakit akışı"
+ surplus: "Fazla"
+ deficit: "Açık"
balance_sheet:
add_accounts: Tam bir döküm görmek için %{name} hesaplarınızı ekleyin
add_asset_accounts: Tam bir döküm görmek için varlık hesaplarınızı ekleyin
diff --git a/config/locales/views/pages/uk.yml b/config/locales/views/pages/uk.yml
index cf185383ff..a176ec0026 100644
--- a/config/locales/views/pages/uk.yml
+++ b/config/locales/views/pages/uk.yml
@@ -37,6 +37,11 @@ uk:
heading: Умови надання послуг
placeholder: Тут буде відображено вміст умов надання послуг.
dashboard:
+ cashflow_preview:
+ node_labels:
+ cash_flow: "Грошовий потік"
+ surplus: "Профіцит"
+ deficit: "Дефіцит"
welcome: "З поверненням, %{name}"
subtitle: "Ось що відбувається з вашими фінансами"
new: "Нове"
diff --git a/config/locales/views/pages/vi.yml b/config/locales/views/pages/vi.yml
index 881e6962ab..ae7e355e6b 100644
--- a/config/locales/views/pages/vi.yml
+++ b/config/locales/views/pages/vi.yml
@@ -35,6 +35,11 @@ vi:
heading: Điều khoản dịch vụ
placeholder: Nội dung điều khoản dịch vụ sẽ được hiển thị ở đây.
dashboard:
+ cashflow_preview:
+ node_labels:
+ cash_flow: "Dòng tiền"
+ surplus: "Thặng dư"
+ deficit: "Thâm hụt"
welcome: "Chào mừng trở lại, %{name}"
subtitle: "Đây là tình hình tài chính của bạn"
new: "Mới"
diff --git a/config/locales/views/pages/zh-CN.yml b/config/locales/views/pages/zh-CN.yml
index 4d4a025c91..369d68eeac 100644
--- a/config/locales/views/pages/zh-CN.yml
+++ b/config/locales/views/pages/zh-CN.yml
@@ -35,6 +35,11 @@ zh-CN:
heading: 服务条款
placeholder: 服务条款内容将显示在这里。
dashboard:
+ cashflow_preview:
+ node_labels:
+ cash_flow: "现金流"
+ surplus: "盈余"
+ deficit: "赤字"
welcome: 欢迎回来,%{name}
subtitle: 以下是您的财务状况概览
new: 新建
diff --git a/config/locales/views/pages/zh-TW.yml b/config/locales/views/pages/zh-TW.yml
index 3b054722d3..3197b5f2ae 100644
--- a/config/locales/views/pages/zh-TW.yml
+++ b/config/locales/views/pages/zh-TW.yml
@@ -38,6 +38,11 @@ zh-TW:
heading: 服務條款
placeholder: 服務條款的內容會顯示在這裡。
dashboard:
+ cashflow_preview:
+ node_labels:
+ cash_flow: "現金流"
+ surplus: "盈餘"
+ deficit: "赤字"
welcome: 歡迎回來,%{name}
subtitle: 這是您目前的財務概況
new: 新增帳戶
diff --git a/config/routes.rb b/config/routes.rb
index ffcae05184..87bbb14f0c 100644
--- a/config/routes.rb
+++ b/config/routes.rb
@@ -334,6 +334,7 @@ Rails.application.routes.draw do
get "release_highlight", to: "release_highlights#show"
patch "release_highlight/dismiss", to: "release_highlights#dismiss"
get "feedback", to: "pages#feedback"
+ get "dashboard/cash_flow", to: "cash_flows#show", as: :dashboard_cash_flow
patch "dashboard/preferences", to: "pages#update_preferences"
resource :current_session, only: %i[update]
diff --git a/docs/api/openapi.yaml b/docs/api/openapi.yaml
index b10d23cfe7..2a222cefbd 100644
--- a/docs/api/openapi.yaml
+++ b/docs/api/openapi.yaml
@@ -3228,6 +3228,122 @@ components:
amount:
type: string
description: Cumulative decimal amount in family currency
+ CashFlowSankey:
+ type: object
+ required:
+ - basis
+ - income
+ - spending
+ - net_savings
+ - nodes
+ - links
+ description: Refunds net within each category. Parent direct amounts exclude
+ child totals before partitioning by direction. Graph income/spending may differ
+ from gross monthly totals; net savings agrees. Decimal strings retain FX precision.
+ Empty flow has empty nodes and links.
+ properties:
+ basis:
+ type: string
+ enum:
+ - net_by_category
+ income:
+ type: string
+ spending:
+ type: string
+ net_savings:
+ type: string
+ nodes:
+ type: array
+ items:
+ type: object
+ required:
+ - id
+ - name
+ - kind
+ - value
+ - percentage
+ - category_id
+ - filter_value
+ - color
+ properties:
+ id:
+ type: string
+ description: Stable direction-prefixed category identifier or structural
+ identifier
+ name:
+ type: string
+ kind:
+ type: string
+ enum:
+ - income
+ - expense
+ - cash_flow
+ - surplus
+ - deficit
+ value:
+ type: string
+ description: Nonnegative decimal in envelope currency
+ percentage:
+ type: string
+ description: Percentage of parent, or side total for root categories;
+ structural balancing nodes use central capacity
+ category_id:
+ type: string
+ format: uuid
+ nullable: true
+ filter_value:
+ type: string
+ nullable: true
+ description: Web transaction category filter; null means no category
+ drill-down
+ color:
+ type: string
+ nullable: true
+ description: User category color; structural colors belong to the
+ client
+ links:
+ type: array
+ items:
+ type: object
+ required:
+ - source
+ - target
+ - value
+ - percentage
+ properties:
+ source:
+ type: integer
+ minimum: 0
+ description: Zero-based nodes index
+ target:
+ type: integer
+ minimum: 0
+ description: Zero-based nodes index
+ value:
+ type: string
+ description: Positive decimal in envelope currency
+ percentage:
+ type: string
+ CashFlowGraph:
+ type: object
+ required:
+ - as_of
+ - time_zone
+ - currency
+ - period
+ - sankey
+ properties:
+ as_of:
+ type: string
+ format: date
+ time_zone:
+ type: string
+ currency:
+ type: string
+ period:
+ "$ref": "#/components/schemas/FinancialPeriod"
+ sankey:
+ "$ref": "#/components/schemas/CashFlowSankey"
CashFlow:
type: object
required:
@@ -3260,6 +3376,8 @@ components:
type: string
net_savings:
type: string
+ sankey:
+ "$ref": "#/components/schemas/CashFlowSankey"
savings_rate:
type: string
nullable: true
@@ -4487,12 +4605,13 @@ paths:
"$ref": "#/components/schemas/ErrorResponse"
"/api/v1/cash_flow":
get:
- summary: Show monthly cash flow
+ summary: Show cash flow and optional Sankey graph
tags:
- Cash Flow
description: Server-calculated income, spending, savings, and daily cumulative
comparison in family currency. Uses the authenticated user’s finance accounts
- and Sure reporting rules.
+ and Sure reporting rules. Browser sessions do not authenticate this public
+ API.
parameters:
- name: month
in: query
@@ -4502,6 +4621,40 @@ paths:
format: date
description: Non-future first day YYYY-MM-01; defaults to the current month
in the family time zone.
+ - name: include
+ in: query
+ required: false
+ schema:
+ type: string
+ enum:
+ - sankey
+ description: Append server-calculated graph to the monthly summary; cannot
+ combine with view.
+ - name: view
+ in: query
+ required: false
+ schema:
+ type: string
+ enum:
+ - sankey
+ description: Graph-only envelope; omits daily comparison. Accepts month or
+ an explicit date range; cannot combine with include.
+ - name: start_date
+ in: query
+ required: false
+ schema:
+ type: string
+ format: date
+ description: Inclusive ISO date. Requires end_date and view=sankey; cannot
+ combine with month.
+ - name: end_date
+ in: query
+ required: false
+ schema:
+ type: string
+ format: date
+ description: Inclusive ISO date at or after start_date. Explicit ranges preserve
+ their bounds, including future dates.
security:
- apiKeyAuth: []
responses:
@@ -4510,9 +4663,11 @@ paths:
content:
application/json:
schema:
- "$ref": "#/components/schemas/CashFlow"
+ anyOf:
+ - "$ref": "#/components/schemas/CashFlow"
+ - "$ref": "#/components/schemas/CashFlowGraph"
'422':
- description: invalid month
+ description: invalid query
content:
application/json:
schema:
diff --git a/docs/clients.md b/docs/clients.md
index aafc2d14df..32901ab36d 100644
--- a/docs/clients.md
+++ b/docs/clients.md
@@ -111,9 +111,44 @@ to access it.
### Native reporting and device continuity
Read monthly server-calculated totals and the daily spending comparison using
-[`GET /api/v1/cash_flow`](api/cash-flow.md). Native clients should
+[`GET /api/v1/cash_flow`](api/openapi.yaml). Native clients should
use these values instead of rebuilding Sure's reporting rules from transactions.
+Structural node `name` values are fallback labels; clients should localize
+`cash_flow`, `surplus`, and `deficit` by `kind` at the presentation boundary.
+
+`include` and `view` are mutually exclusive; combining them returns `422 invalid_view`.
+
+Request `include=sankey` to append category nodes and links to the monthly
+summary. For arbitrary date filters, request
+`view=sankey&start_date=YYYY-MM-DD&end_date=YYYY-MM-DD` to receive only the graph
+and its currency, time zone, as-of date, and inclusive period. This avoids building
+a daily series for long date ranges. The default monthly response is unchanged.
+
+Graph values are decimal strings in family currency, with stable node IDs and
+zero-based link indices. Refunds are netted within each category; parent direct
+amounts exclude children before each direction is grouped. Graph income and
+spending can therefore differ from the gross monthly figures, while net savings
+agrees. Surplus and deficit nodes balance the central flow. Clients own layout,
+formatting, and structural colors; all financial aggregation stays on Sure.
+
+The public endpoint uses the standard OAuth/API-key authentication and does not
+accept browser sessions. Responses are private and not HTTP-cacheable; native
+clients retain their own authenticated, identity-scoped offline cache.
+
+The Turbo dashboard fetches `/dashboard/cash_flow` through a normal web controller,
+with session authentication, onboarding checks, and the current user's preview
+gate. It honors the impersonated browser identity and finance-account scope. Both
+endpoints use `IncomeStatement::CashFlowGraph` and `IncomeStatement::Sankey`, sharing
+the graph representation and aggregation without sharing authentication paths.
+
+The web dashboard keeps its original Sankey unchanged and renders the new
+server-calculated chart directly below it only for users with preview features
+enabled. See
+[Preview surveys and event capture](hosting/preview-feedback.md) for deployment
+configuration, survey behavior, and event definitions. Sankey is the first
+implementation of this feedback pattern.
+
Push registration accepts an optional `device_key`: 32 securely random bytes
encoded as 64 lowercase hex characters, generated independently per server and
stored only in secure device storage. Preserve it across user logout. The server
diff --git a/docs/hosting/preview-feedback.md b/docs/hosting/preview-feedback.md
new file mode 100644
index 0000000000..1da8c4ba5b
--- /dev/null
+++ b/docs/hosting/preview-feedback.md
@@ -0,0 +1,112 @@
+# Preview surveys and event capture
+
+Preview features let users try changes before general release. Surveys collect
+what worked and what needs improvement; usage events show whether users saw or
+interacted with the feature. Enable previews in Settings → Preferences → Preview
+features. Each feature owns its access checks, feedback UI, questions, and events.
+
+The cash-flow Sankey is the first implementation. It appears below the original
+chart for comparison and offers thumbs up/down followed by an optional written
+response. The shared configuration supports future feature surveys, but the
+current browser client and event allowlist are still specific to Sankey.
+
+## Deployment and survey routing
+
+| Deployment | Feedback destination | Configuration |
+| --- | --- | --- |
+| Sure app | Its existing `[app] sure-app` PostHog project | Existing `POSTHOG_KEY` / `POSTHOG_HOST`, plus the feature's survey ID |
+| Demo | Its existing `[app] sure-demo` PostHog project | Existing `POSTHOG_KEY` / `POSTHOG_HOST`, plus the feature's survey ID |
+| Production self-hosted | Shared `[app] self-hosted` project | Bundled public project token and feature survey ID; no operator setup |
+
+Managed deployments must use a survey belonging to their own project. Sankey's
+survey variable is `POSTHOG_SANKEY_SURVEY_ID`. Self-hosted feedback stays separate
+from any analytics project configured by the operator. Operators can disable the
+shared connection with `POSTHOG_FEEDBACK_ENABLED=false`; this does not reroute
+feedback to another project. Shared collection is disabled outside production.
+
+The public project token routes requests to PostHog; it is not a private API key
+and grants no access to collected data or administration. Never distribute a
+personal or project-secret API key. Rotating bundled configuration requires a
+release and installation upgrades; older versions retain the old token. See the
+[development guide](../llm-guides/feedback-surveys.md) for configuration and rotation.
+
+## Survey behavior
+
+Use a PostHog **API survey** with Sure's own accessible dialog. The application
+controls when the survey is offered and validates the configured survey and its
+question IDs. Answers use question UUIDs rather than positional indexes. Changing
+question types or accepted choices requires a corresponding client update.
+
+Sankey currently expects one single-choice question with the wire values
+`Looks right` and `Something looks wrong`, plus one open-text question. Users can
+submit feedback more than once. Future features define their own question
+contracts instead of inheriting these choices.
+
+PostHog's [custom survey integration](https://posthog.com/docs/surveys/implementing-custom-surveys)
+uses `survey shown`, `survey sent`, and `survey dismissed`, with `$survey_id` and
+`$survey_response_<question UUID>` properties. Written feedback is sent only on
+explicit submission. Missing configuration, unavailable surveys, blocked SDKs,
+and capture opt-outs must leave the feature usable without claiming a successful
+submission. SDK acceptance is not confirmation of eventual server ingestion.
+
+## Event capture
+
+For each preview, document the event names, allowed properties, exact trigger,
+and repeat-counting rules. Keep exposure separate from feedback and interaction.
+Give each implementation a version so results from changed behavior can be
+compared. Add events only with their capture code, allowlist, and offline tests;
+registering a survey does not automatically instrument the feature.
+
+These are the events **currently implemented for Sankey**. All include
+`preview_version: cash_flow_v1`:
+
+| Event | Trigger | Additional properties |
+| --- | --- | --- |
+| `sankey_preview_displayed` | A loaded result becomes visible, or the chart is explicitly expanded | `surface: inline / expanded`, `state: content / empty / error` |
+| `sankey_preview_feedback_clicked` | Thumbs up/down, when a survey ID and capture-enabled SDK are available | `rating: positive / negative`, `state` |
+| `survey shown` | The validated survey form is presented | `$survey_id` |
+| `survey sent` | An explicit submission is accepted by the SDK | `$survey_id`, answers keyed by question UUID |
+| `survey dismissed` | A presented survey closes without submission | `$survey_id` |
+
+### Counting exposure and engagement
+
+Count `sankey_preview_displayed` with `surface=inline` and `state=content` for
+chart exposure. Count `surface=expanded` separately for expansion usage. Empty
+and error impressions describe visible result states, not successful charts.
+
+An inline result counts once per load and state. Scrolling away and back or
+resizing does not add impressions. Page visits, date changes, and retries can
+produce new impressions; each explicit expansion counts again. Hidden,
+collapsed, off-screen, and loading previews do not count. Late SDK initialization
+can capture an already-visible result.
+
+Currently, `content` means validated graph data loaded into a visible container;
+it does not confirm that SVG rendering finished. There are no dedicated load-time,
+render-success, zoom, or transaction-navigation events yet. Future instrumentation
+should distinguish those outcomes and record successful rendering before using
+impressions as proof that a chart rendered.
+
+Compare exposure and expansion counts with feedback clicks and submitted
+responses to understand engagement. These measure captured activity, not all
+usage: blocked or opted-out analytics are absent. The self-hosted client uses an
+in-memory anonymous identity, so distinct IDs are not reliable counts of returning
+people or installations across visits.
+
+## Privacy and extending the implementation
+
+Usage properties must exclude amounts, account/category names or IDs, date
+ranges, server URLs, and graph payloads. Ask users to omit private financial
+details from voluntary text. The feature and feedback form are excluded from
+autocapture and session recording.
+
+Managed deployments retain their existing SDK metadata. The dedicated self-hosted
+client disables automatic tracking, pageviews, session recording, and person
+profiles; it strips incidental URL, referrer, and device metadata. Opting out of
+either client suppresses capture. GeoIP enrichment is disabled, although the
+ingestion service necessarily receives the network connection's IP address.
+
+Use `feedback_config(:feature_name)` and the per-feature survey registry for the
+next preview. Follow [Adding feature feedback surveys](../llm-guides/feedback-surveys.md)
+for implementation and tests. Reuse project routing, while giving the new feature
+its own questions and explicit event contract. Extending the browser client must
+preserve the same routing, privacy, and opt-out behavior for both features.
diff --git a/docs/llm-guides/README.md b/docs/llm-guides/README.md
index 9c234e72e1..4ab5320d2e 100644
--- a/docs/llm-guides/README.md
+++ b/docs/llm-guides/README.md
@@ -13,6 +13,7 @@ being changed. These guides hold the detailed conventions and procedures.
| Add or modify an API v1 endpoint | [API endpoint consistency](api-endpoint-consistency.md) |
| Change provider imports, pending/FX metadata or diagnostics | [Provider sync guidance](providers.md) |
| Add a securities price provider | [Provider walkthrough](adding-a-securities-provider.md) |
+| Add a preview survey or usage event | [Feedback surveys](feedback-surveys.md) |
| Gate or release a preview feature | [Preview-feature gating](gating-a-preview-feature.md) |
| Change goals, pledges or reconciliation | [Goals](goals.md) |
diff --git a/docs/llm-guides/feedback-surveys.md b/docs/llm-guides/feedback-surveys.md
new file mode 100644
index 0000000000..13843fc616
--- /dev/null
+++ b/docs/llm-guides/feedback-surveys.md
@@ -0,0 +1,85 @@
+# Adding feature feedback surveys
+
+See [Preview surveys and event capture](../hosting/preview-feedback.md) for
+deployment behavior, privacy boundaries, and the first implementation's event
+catalog and counting rules.
+
+Use `feedback_config(:feature_name)` from `FeedbackHelper` to select a survey.
+Project routing belongs in this helper and `config/initializers/posthog.rb`;
+question wording, response mapping, UI, and events belong to the feature.
+
+## Configuration
+
+`Rails.configuration.x.posthog` separates two things:
+
+- `self_hosted_feedback_project` contains the shared public project token and
+ ingestion host. All self-hosted feedback features use this destination.
+- `feedback_surveys` maps feature symbols to their `managed` and `self_hosted`
+ survey IDs. Only implemented features should be registered.
+
+For example, the existing call is:
+
+```erb
+<% feedback = feedback_config(:sankey) %>
+```
+
+On managed app/demo deployments, the result contains `survey_id` for the current
+installation. The feature uses the existing PostHog client, whose project is
+selected by `POSTHOG_KEY` and `POSTHOG_HOST`. Each deployment sets the matching
+feature survey variable; Sankey continues to use `POSTHOG_SANKEY_SURVEY_ID`.
+
+For production self-hosted installations, the result contains `api_key`, `host`,
+and `survey_id` for the shared `[app] self-hosted` project. The token is public
+client configuration; operators need no account or key setup. It must never be a
+PostHog personal or project secret key. An operator's own analytics configuration
+must not change this destination.
+
+Unknown features, blank survey IDs, or a missing ID for the selected destination
+return `{}`. There is no fallback to another feature's survey or another project.
+Self-hosted configuration also returns `{}` outside production or when
+`POSTHOG_FEEDBACK_ENABLED=false`. This switch is specific to the shared
+self-hosted feedback connection; managed deployments retain their existing rules.
+
+## Rotating the public self-hosted project token
+
+The bundled `phc_` token is deliberately public client configuration, not a
+secret credential. It identifies the shared feedback destination and does not
+grant access to collected data or administrative APIs. Do not replace it with a personal API key.
+
+To change it, update `self_hosted_feedback_project` in the initializer, verify
+survey retrieval and ingestion against that project, and publish a release.
+Existing self-hosted versions keep their bundled token until upgraded; revoking
+the old token can therefore stop their feedback collection. Charts must remain
+usable when collection is unavailable. Operators can disable the shared
+connection immediately with `POSTHOG_FEEDBACK_ENABLED=false`.
+
+## Adding the next feature
+
+1. Create an API survey in each intended PostHog project. App and demo have
+ distinct projects; self-hosted surveys belong in `[app] self-hosted`.
+2. Add the feature to `feedback_surveys`, with a feature-specific environment
+ variable for the managed survey and the shared project's public survey ID for
+ self-hosting. Document the new environment variable in `.env.local.example`.
+ Leave an unavailable destination unconfigured rather than borrowing an ID.
+3. Call `feedback_config(:feature_name)` from the feature's view and pass values
+ through escaped Stimulus data attributes. Keep the feature's access/preview
+ gate at its existing web entry points; the helper does not grant access.
+4. Implement the feature's survey contract and response mapping. Validate the
+ active survey and question IDs, handle missing/blocked/opted-out analytics,
+ and report success only after submission is accepted by the SDK.
+5. Define the feature's event vocabulary and allowed properties. Preserve
+ anonymous identity, existing capture opt-outs, and the self-hosted operator
+ opt-out. Disable automatic capture, page tracking, session replay, and person
+ profiles for the dedicated feedback client. Send free text only on explicit
+ submission, and exclude financial records and incidental URL/device metadata.
+6. Add offline tests for both destinations, distinct feature survey IDs, missing
+ configuration, opt-outs, and the form's actual submission flow.
+
+The helper only returns configuration; it does not initialize an SDK or submit
+anything. The current `posthog.sankeyFeedback` client and its event allowlist are
+Sankey-specific. Do not reuse its question assumptions or widen its event filter
+implicitly when adding another feature. Make any shared browser-client extraction
+alongside that feature with tests for both callers.
+
+See `test/helpers/feedback_helper_test.rb` for routing coverage using a second
+test-only feature. No placeholder surveys are registered in production.
diff --git a/spec/requests/api/v1/cash_flow_spec.rb b/spec/requests/api/v1/cash_flow_spec.rb
index 029eb66b12..bb77896ad1 100644
--- a/spec/requests/api/v1/cash_flow_spec.rb
+++ b/spec/requests/api/v1/cash_flow_spec.rb
@@ -34,20 +34,24 @@ RSpec.describe 'API V1 Cash Flow', type: :request do
let(:'X-Api-Key') { api_key.plain_key }
path '/api/v1/cash_flow' do
- get 'Show monthly cash flow' do
+ get 'Show cash flow and optional Sankey graph' do
tags 'Cash Flow'
- description 'Server-calculated income, spending, savings, and daily cumulative comparison in family currency. Uses the authenticated user’s finance accounts and Sure reporting rules.'
+ description 'Server-calculated income, spending, savings, and daily cumulative comparison in family currency. Uses the authenticated user’s finance accounts and Sure reporting rules. Browser sessions do not authenticate this public API.'
parameter name: :month, in: :query, required: false, schema: { type: :string, format: :date }, description: 'Non-future first day YYYY-MM-01; defaults to the current month in the family time zone.'
+ parameter name: :include, in: :query, required: false, schema: { type: :string, enum: [ 'sankey' ] }, description: 'Append server-calculated graph to the monthly summary; cannot combine with view.'
+ parameter name: :view, in: :query, required: false, schema: { type: :string, enum: [ 'sankey' ] }, description: 'Graph-only envelope; omits daily comparison. Accepts month or an explicit date range; cannot combine with include.'
+ parameter name: :start_date, in: :query, required: false, schema: { type: :string, format: :date }, description: 'Inclusive ISO date. Requires end_date and view=sankey; cannot combine with month.'
+ parameter name: :end_date, in: :query, required: false, schema: { type: :string, format: :date }, description: 'Inclusive ISO date at or after start_date. Explicit ranges preserve their bounds, including future dates.'
security [ { apiKeyAuth: [] } ]
produces 'application/json'
response '200', 'summary returned' do
- schema '$ref' => '#/components/schemas/CashFlow'
+ schema anyOf: [ { '$ref' => '#/components/schemas/CashFlow' }, { '$ref' => '#/components/schemas/CashFlowGraph' } ]
run_test!
end
- response '422', 'invalid month' do
+ response '422', 'invalid query' do
schema '$ref' => '#/components/schemas/ErrorResponse'
let(:month) { 'invalid' }
run_test!
diff --git a/spec/swagger_helper.rb b/spec/swagger_helper.rb
index 27eabf4e4c..1ea884f996 100644
--- a/spec/swagger_helper.rb
+++ b/spec/swagger_helper.rb
@@ -1736,6 +1736,42 @@ RSpec.configure do |config|
type: :object, required: %w[date amount],
properties: { date: { type: :string, format: :date }, amount: { type: :string, description: 'Cumulative decimal amount in family currency' } }
},
+ CashFlowSankey: {
+ type: :object, required: %w[basis income spending net_savings nodes links],
+ description: 'Refunds net within each category. Parent direct amounts exclude child totals before partitioning by direction. Graph income/spending may differ from gross monthly totals; net savings agrees. Decimal strings retain FX precision. Empty flow has empty nodes and links.',
+ properties: {
+ basis: { type: :string, enum: [ 'net_by_category' ] },
+ income: { type: :string }, spending: { type: :string }, net_savings: { type: :string },
+ nodes: { type: :array, items: {
+ type: :object, required: %w[id name kind value percentage category_id filter_value color],
+ properties: {
+ id: { type: :string, description: 'Stable direction-prefixed category identifier or structural identifier' },
+ name: { type: :string }, kind: { type: :string, enum: %w[income expense cash_flow surplus deficit] },
+ value: { type: :string, description: 'Nonnegative decimal in envelope currency' },
+ percentage: { type: :string, description: 'Percentage of parent, or side total for root categories; structural balancing nodes use central capacity' },
+ category_id: { type: :string, format: :uuid, nullable: true },
+ filter_value: { type: :string, nullable: true, description: 'Web transaction category filter; null means no category drill-down' },
+ color: { type: :string, nullable: true, description: 'User category color; structural colors belong to the client' }
+ }
+ } },
+ links: { type: :array, items: {
+ type: :object, required: %w[source target value percentage],
+ properties: {
+ source: { type: :integer, minimum: 0, description: 'Zero-based nodes index' },
+ target: { type: :integer, minimum: 0, description: 'Zero-based nodes index' },
+ value: { type: :string, description: 'Positive decimal in envelope currency' }, percentage: { type: :string }
+ }
+ } }
+ }
+ },
+ CashFlowGraph: {
+ type: :object, required: %w[as_of time_zone currency period sankey],
+ properties: {
+ as_of: { type: :string, format: :date }, time_zone: { type: :string }, currency: { type: :string },
+ period: { '$ref' => '#/components/schemas/FinancialPeriod' },
+ sankey: { '$ref' => '#/components/schemas/CashFlowSankey' }
+ }
+ },
CashFlow: {
type: :object,
required: %w[month as_of time_zone currency period income spending net_savings savings_rate spending_comparison],
@@ -1744,6 +1780,7 @@ RSpec.configure do |config|
time_zone: { type: :string }, currency: { type: :string },
period: { '$ref' => '#/components/schemas/FinancialPeriod' },
income: { type: :string }, spending: { type: :string }, net_savings: { type: :string },
+ sankey: { '$ref' => '#/components/schemas/CashFlowSankey' },
savings_rate: { type: :string, nullable: true, description: 'Percentage points; null when income is nonpositive. May be negative.' },
spending_comparison: {
type: :object,
diff --git a/test/controllers/api/v1/cash_flows_controller_test.rb b/test/controllers/api/v1/cash_flows_controller_test.rb
index faa0692987..58b163bd08 100644
--- a/test/controllers/api/v1/cash_flows_controller_test.rb
+++ b/test/controllers/api/v1/cash_flows_controller_test.rb
@@ -47,12 +47,63 @@ class Api::V1::CashFlowsControllerTest < ActionDispatch::IntegrationTest
excluded.account_shares.create!(user: @user, permission: "read_only", include_in_finances: false)
create_transaction(account: own, amount: 12, date: month)
create_transaction(account: excluded, amount: 900, date: month)
- get "/api/v1/cash_flow", params: { month: month.iso8601 }, headers: api_headers(@auth)
+ get "/api/v1/cash_flow", params: { month: month.iso8601, include: "sankey" }, headers: api_headers(@auth)
assert_response :success
+ assert_equal "12.0", response.parsed_body.dig("sankey", "spending")
assert_equal "12.0", response.parsed_body["spending"]
assert_equal "12.0", response.parsed_body.dig("spending_comparison", "current_total")
end
+ test "graph is opt-in and date ranges do not calculate daily series" do
+ get "/api/v1/cash_flow", headers: api_headers(@auth)
+ assert_not response.parsed_body.key?("sankey")
+ get "/api/v1/cash_flow", params: { include: "sankey" }, headers: api_headers(@auth)
+ assert_response :success
+ assert_equal "net_by_category", response.parsed_body.dig("sankey", "basis")
+ IncomeStatement.any_instance.expects(:daily_expense_series).never
+ get "/api/v1/cash_flow", params: { view: "sankey", start_date: "2000-01-01", end_date: "2024-02-29" }, headers: api_headers(@auth)
+ assert_response :success
+ assert_equal "2000-01-01", response.parsed_body.dig("period", "start_date")
+ assert_not response.parsed_body.key?("spending_comparison")
+ end
+
+ test "rejects ambiguous or invalid graph ranges" do
+ [ { start_date: "2024-01-01" }, { view: "sankey", start_date: "2024-01-01" },
+ { view: "sankey", start_date: "2024-02-30", end_date: "2024-03-01" },
+ { view: "sankey", start_date: "2024-02-01", end_date: "2024-01-01" },
+ { view: "sankey", month: "2024-01-01", start_date: "2024-01-01", end_date: "2024-01-02" },
+ { view: "invalid" }, { include: "invalid" } ].each do |query|
+ get "/api/v1/cash_flow", params: query, headers: api_headers(@auth)
+ assert_response :unprocessable_entity
+ end
+ end
+
+ test "rejects conflicting graph modes" do
+ [ {}, { month: "2024-01-01" }, { start_date: "2024-01-01", end_date: "2024-01-02" } ].each do |period|
+ get "/api/v1/cash_flow", params: period.merge(include: "sankey", view: "sankey"), headers: api_headers(@auth)
+ assert_response :unprocessable_entity
+ assert_equal "invalid_view", response.parsed_body["error"]
+ end
+ end
+
+ test "a browser session cannot authenticate the API" do
+ sign_in @user
+ get "/api/v1/cash_flow", params: { view: "sankey" }
+ assert_response :unauthorized
+ get "/api/v1/cash_flow", headers: { "X-Api-Key" => "invalid" }
+ assert_response :unauthorized
+ end
+
+ test "API credentials keep their own identity during browser impersonation" do
+ users(:family_member).family.update!(currency: "JPY")
+ @auth.update!(user: users(:empty))
+ sign_in users(:sure_support_staff)
+ post join_impersonation_sessions_path, params: { impersonation_session_id: impersonation_sessions(:in_progress).id }
+ get "/api/v1/cash_flow", params: { view: "sankey" }, headers: api_headers(@auth)
+ assert_response :success
+ assert_equal users(:empty).family.currency, response.parsed_body["currency"]
+ end
+
private
def api_headers(auth)
{ "X-Api-Key" => auth.display_key }
diff --git a/test/controllers/cash_flow_preview_test.rb b/test/controllers/cash_flow_preview_test.rb
new file mode 100644
index 0000000000..31ad552301
--- /dev/null
+++ b/test/controllers/cash_flow_preview_test.rb
@@ -0,0 +1,73 @@
+require "test_helper"
+
+class CashFlowPreviewTest < ActionDispatch::IntegrationTest
+ setup do
+ sign_in @user = users(:family_admin)
+ end
+
+ test "preview opt-in adds the web chart below identical legacy chart data" do
+ @user.update!(preferences: @user.preferences.merge("preview_features_enabled" => false))
+ get root_path
+ assert_response :success
+ assert_select "#cashflow-preview", count: 0
+ assert_select "[data-controller='cash-flow']", count: 0
+ legacy = css_select("[data-controller='sankey-chart']").map { |chart| chart["data-sankey-chart-data-value"] }
+ assert_equal 2, legacy.length
+
+ @user.update!(preferences: @user.preferences.merge("preview_features_enabled" => true))
+ get root_path
+ assert_response :success
+ assert_select "#cashflow-sankey-chart + #cashflow-preview", count: 1
+ assert_select "#cashflow-preview [data-controller='preview-sankey-chart']", count: 2
+ assert_select "#cashflow-preview [data-cash-flow-url-value*='/dashboard/cash_flow?']", count: 1
+ assert_equal legacy, css_select("[data-controller='sankey-chart']").map { |chart| chart["data-sankey-chart-data-value"] }
+ end
+
+ test "a family member's preview opt-in does not expose the preview to this user" do
+ @user.update!(preferences: @user.preferences.merge("preview_features_enabled" => false))
+ @user.family.users.where.not(id: @user.id).first.update!(preferences: { "preview_features_enabled" => true })
+ get root_path
+ assert_response :success
+ assert_select "#cashflow-preview", count: 0
+ end
+
+ test "self-hosted production preview needs no operator key or survey configuration" do
+ @user.update!(preferences: @user.preferences.merge("preview_features_enabled" => true))
+ config = Rails.configuration.x.posthog
+ config.stubs(:api_key).returns(nil)
+ stub_managed_survey(nil)
+ config.stubs(:feedback_enabled).returns(true)
+ with_self_hosting do
+ get root_path
+ assert_select "#cashflow-preview[data-sankey-preview-self-hosted-value='true'][data-sankey-preview-feedback-key-value=''][data-sankey-preview-survey-id-value='']"
+ Rails.env.stubs(:production?).returns(true)
+ get root_path
+ assert_select "#cashflow-preview[data-sankey-preview-feedback-key-value^='phc_'][data-sankey-preview-survey-id-value='01a0a162-73a2-0000-9402-ffab5bc45b4a']"
+ config.stubs(:api_key).returns("operator-owned-project")
+ stub_managed_survey("operator-owned-survey")
+ get root_path
+ assert_select "#cashflow-preview[data-sankey-preview-feedback-key-value^='phc_'][data-sankey-preview-survey-id-value='01a0a162-73a2-0000-9402-ffab5bc45b4a']"
+ config.stubs(:feedback_enabled).returns(false)
+ get root_path
+ assert_select "#cashflow-preview[data-sankey-preview-feedback-key-value=''][data-sankey-preview-survey-id-value='']"
+ end
+ end
+
+ test "managed app and demo use the configured environment survey without the shared feedback client" do
+ @user.update!(preferences: @user.preferences.merge("preview_features_enabled" => true))
+ Rails.configuration.stubs(:app_mode).returns("managed".inquiry)
+ Rails.env.stubs(:production?).returns(true)
+ [ "app-survey", "demo-survey" ].each do |survey_id|
+ stub_managed_survey(survey_id)
+ get root_path
+ assert_select "#cashflow-preview[data-sankey-preview-self-hosted-value='false'][data-sankey-preview-feedback-key-value=''][data-sankey-preview-survey-id-value='#{survey_id}']"
+ end
+ end
+
+ private
+ def stub_managed_survey(survey_id)
+ config = Rails.configuration.x.posthog
+ surveys = config.feedback_surveys
+ config.stubs(:feedback_surveys).returns(surveys.merge(sankey: surveys.fetch(:sankey).merge(managed: survey_id)))
+ end
+end
diff --git a/test/controllers/cash_flows_controller_test.rb b/test/controllers/cash_flows_controller_test.rb
new file mode 100644
index 0000000000..d679bba704
--- /dev/null
+++ b/test/controllers/cash_flows_controller_test.rb
@@ -0,0 +1,98 @@
+require "test_helper"
+
+class CashFlowsControllerTest < ActionDispatch::IntegrationTest
+ include EntriesTestHelper
+
+ setup do
+ @user = users(:family_admin)
+ @user.update!(preferences: @user.preferences.merge("preview_features_enabled" => true))
+ @dates = { start_date: "2024-02-01", end_date: "2024-02-29" }
+ end
+
+ test "requires a browser session even when an API key is supplied" do
+ get dashboard_cash_flow_path, params: @dates, headers: { "X-Api-Key" => api_key.display_key }
+ assert_redirected_to new_session_path
+ end
+
+ test "requires the current user's preview opt-in" do
+ sign_in @user
+ @user.update!(preferences: @user.preferences.merge("preview_features_enabled" => false))
+ users(:family_member).update!(preferences: { "preview_features_enabled" => true })
+ get dashboard_cash_flow_path, params: @dates
+ assert_redirected_to root_path
+ end
+
+ test "retains ordinary onboarding and inactive-session checks" do
+ sign_in @user
+ @user.update!(onboarded_at: nil)
+ get dashboard_cash_flow_path, params: @dates
+ assert_redirected_to onboarding_path
+ @user.update_column(:active, false)
+ get dashboard_cash_flow_path, params: @dates
+ assert_redirected_to new_session_path
+ end
+
+ test "matches the API graph with family timezone and finance-account scope" do
+ @user.family.update!(timezone: "Pacific Time (US & Canada)")
+ own = @user.family.accounts.create!(name: "Own", owner: @user, currency: "USD", balance: 0, accountable: Depository.new)
+ other = @user.family.accounts.create!(name: "Excluded", owner: users(:family_member), currency: "USD", balance: 0, accountable: Depository.new)
+ other.account_shares.create!(user: @user, permission: "read_only", include_in_finances: false)
+ create_transaction(account: own, amount: 12, date: Date.new(2024, 2, 1))
+ create_transaction(account: other, amount: 900, date: Date.new(2024, 2, 1))
+ unrelated = users(:empty).family.accounts.create!(name: "Other family", currency: "USD", balance: 0, accountable: Depository.new)
+ create_transaction(account: unrelated, amount: 700, date: Date.new(2024, 2, 1))
+ sign_in @user
+ key = api_key
+ IncomeStatement.any_instance.expects(:daily_expense_series).never
+ travel_to Time.utc(2024, 3, 1, 1) do
+ get dashboard_cash_flow_path, params: @dates
+ assert_response :success
+ assert_equal "private, no-store", response.headers["Cache-Control"]
+ graph = response.parsed_body
+ assert_equal "2024-02-29", graph["as_of"]
+ assert_equal "America/Los_Angeles", graph["time_zone"]
+ assert_equal "12.0", graph.dig("sankey", "spending")
+ get "/api/v1/cash_flow", params: @dates.merge(view: "sankey"), headers: { "X-Api-Key" => key.display_key }
+ assert_response :success
+ assert_equal graph, response.parsed_body
+ end
+ end
+
+ test "rejects incomplete malformed and reversed date ranges" do
+ sign_in @user
+ [ {}, { start_date: "2024-01-01" }, { start_date: "2024-02-30", end_date: "2024-03-01" },
+ { start_date: "2024-2-1", end_date: "2024-03-01" }, { start_date: "2024-03-01", end_date: "2024-02-01" },
+ { start_date: [ "2024-01-01" ], end_date: "2024-03-01" } ].each do |dates|
+ get dashboard_cash_flow_path, params: dates
+ assert_response :unprocessable_entity
+ assert_equal "invalid_period", response.parsed_body["error"]
+ end
+ end
+
+ test "preserves explicit range bounds and empty graphs" do
+ sign_in @user
+ get dashboard_cash_flow_path, params: { start_date: "1900-01-01", end_date: "1900-01-02" }
+ assert_response :success
+ assert_empty response.parsed_body.dig("sankey", "nodes")
+ get dashboard_cash_flow_path, params: { start_date: "2099-01-01", end_date: "2099-01-02" }
+ assert_response :success
+ assert_equal "2099-01-02", response.parsed_body.dig("period", "end_date")
+ end
+
+ test "uses the impersonated browser identity without adopting API credentials" do
+ target = users(:family_member)
+ target.update!(preferences: { "preview_features_enabled" => true })
+ target.family.update!(currency: "JPY")
+ sign_in users(:sure_support_staff)
+ post join_impersonation_sessions_path, params: { impersonation_session_id: impersonation_sessions(:in_progress).id }
+ get dashboard_cash_flow_path, params: @dates, headers: { "X-Api-Key" => "not-used-for-browser-auth" }
+ assert_response :success
+ assert_equal "JPY", response.parsed_body["currency"]
+ end
+
+ private
+ def api_key
+ ApiKey.create!(user: @user, name: "Graph Read", scopes: [ "read" ],
+ display_key: "test_ro_#{SecureRandom.hex(8)}", source: "mobile")
+ end
+end
diff --git a/test/helpers/feedback_helper_test.rb b/test/helpers/feedback_helper_test.rb
new file mode 100644
index 0000000000..dbe083d9a5
--- /dev/null
+++ b/test/helpers/feedback_helper_test.rb
@@ -0,0 +1,58 @@
+require "test_helper"
+
+class FeedbackHelperTest < ActionView::TestCase
+ setup do
+ @config = Rails.configuration.x.posthog
+ @surveys = {
+ sankey: { managed: "managed-sankey", self_hosted: "shared-sankey" }.freeze,
+ another_feature: { managed: "managed-other", self_hosted: "shared-other" }.freeze
+ }.freeze
+ @project = { api_key: "public-test-token", host: "https://feedback.example.test" }.freeze
+ @config.stubs(:feedback_surveys).returns(@surveys)
+ @config.stubs(:self_hosted_feedback_project).returns(@project)
+ @config.stubs(:feedback_enabled).returns(true)
+ Rails.env.stubs(:production?).returns(true)
+ end
+
+ test "managed features select their own surveys without initializing another project" do
+ stubs(:self_hosted?).returns(false)
+ @config.expects(:self_hosted_feedback_project).never
+ assert_equal({ survey_id: "managed-sankey" }, feedback_config(:sankey))
+ assert_equal({ survey_id: "managed-other" }, feedback_config(:another_feature))
+ end
+
+ test "self-hosted features share the public project but keep distinct surveys" do
+ stubs(:self_hosted?).returns(true)
+ assert_equal @project.merge(survey_id: "shared-sankey"), feedback_config(:sankey)
+ assert_equal @project.merge(survey_id: "shared-other"), feedback_config(:another_feature)
+ result = feedback_config(:sankey)
+ result[:survey_id] = "changed-by-caller"
+ assert_equal "shared-sankey", feedback_config(:sankey)[:survey_id]
+ assert_not @project.key?(:survey_id)
+ end
+
+ test "unknown or unconfigured surveys never fall back to another destination" do
+ @config.stubs(:feedback_surveys).returns(@surveys.merge(
+ managed_only: { managed: "managed-only" },
+ shared_only: { self_hosted: "shared-only" },
+ blank: { managed: " ", self_hosted: "" }
+ ))
+ [ false, true ].each do |self_hosted|
+ stubs(:self_hosted?).returns(self_hosted)
+ assert_empty feedback_config(:unknown)
+ assert_empty feedback_config(:blank)
+ assert_empty feedback_config(self_hosted ? :managed_only : :shared_only)
+ end
+ end
+
+ test "self-hosted feedback stays disabled outside production or after operator opt-out" do
+ stubs(:self_hosted?).returns(true)
+ Rails.env.stubs(:production?).returns(false)
+ assert_empty feedback_config(:sankey)
+ Rails.env.stubs(:production?).returns(true)
+ @config.stubs(:feedback_enabled).returns(false)
+ assert_empty feedback_config(:another_feature)
+ stubs(:self_hosted?).returns(false)
+ assert_equal({ survey_id: "managed-other" }, feedback_config(:another_feature))
+ end
+end
diff --git a/test/javascript/utils/cash_flow_chart_data_test.mjs b/test/javascript/utils/cash_flow_chart_data_test.mjs
new file mode 100644
index 0000000000..ecea158fd2
--- /dev/null
+++ b/test/javascript/utils/cash_flow_chart_data_test.mjs
@@ -0,0 +1,79 @@
+import assert from "node:assert/strict";
+import { test } from "node:test";
+import {
+ cashFlowChartData,
+ formatCashFlowCurrency,
+} from "../../../app/javascript/utils/cash_flow_chart_data.mjs";
+const payload = () => ({
+ currency: "JPY",
+ sankey: {
+ basis: "net_by_category",
+ nodes: [
+ {
+ id: "income_one",
+ name: "Income",
+ kind: "income",
+ value: "12.345",
+ percentage: "100.0",
+ color: "#123456",
+ },
+ {
+ id: "cash_flow_node",
+ name: "Cash Flow",
+ kind: "cash_flow",
+ value: "12.345",
+ percentage: "100.0",
+ },
+ ],
+ links: [{ source: 0, target: 1, value: "12.345", percentage: "100.0" }],
+ },
+});
+test("maps graph geometry without rounding or changing API payload", () => {
+ const body = payload();
+ const graph = cashFlowChartData(body);
+ assert.equal(graph.nodes[0].value, 12.345);
+ assert.equal(body.sankey.nodes[0].value, "12.345");
+ assert.equal(graph.nodes[0].color, "#123456");
+});
+test("accepts empty graphs", () => {
+ assert.deepEqual(
+ cashFlowChartData({
+ currency: "USD",
+ sankey: { basis: "net_by_category", nodes: [], links: [] },
+ }),
+ { nodes: [], links: [] },
+ );
+});
+test("rejects malformed, unsafe, and cyclic graphs", () => {
+ for (const mutate of [
+ (p) => (p.sankey.nodes[0].value = "Infinity"),
+ (p) => (p.sankey.nodes[0].value = "-1"),
+ (p) => (p.sankey.links[0].value = "0"),
+ (p) => (p.sankey.nodes[0].percentage = "101"),
+ (p) => (p.sankey.nodes[0].id = "cash_flow_node"),
+ (p) => (p.sankey.links[0].target = 9),
+ (p) =>
+ p.sankey.links.push({
+ source: 1,
+ target: 0,
+ value: "1",
+ percentage: "1",
+ }),
+ ]) {
+ const body = payload();
+ mutate(body);
+ assert.throws(() => cashFlowChartData(body));
+ }
+});
+
+test("formats zero-decimal currencies and Sure currencies outside Intl", () => {
+ assert.equal(formatCashFlowCurrency(1234, "JPY", "en-US"), "¥1,234");
+ assert.equal(formatCashFlowCurrency(1.234, "BHD", "en-US"), "BHD\u00a01.234");
+ assert.equal(
+ formatCashFlowCurrency(0.00000012, "DOGE", "en-US"),
+ "0.00000012 DOGE",
+ );
+ const body = payload();
+ body.currency = "DOGE";
+ assert.equal(cashFlowChartData(body).links.length, 1);
+});
diff --git a/test/javascript/utils/sankey_preview_analytics_test.mjs b/test/javascript/utils/sankey_preview_analytics_test.mjs
new file mode 100644
index 0000000000..7e99675893
--- /dev/null
+++ b/test/javascript/utils/sankey_preview_analytics_test.mjs
@@ -0,0 +1,91 @@
+import assert from "node:assert/strict";
+import { test } from "node:test";
+import { capturePreviewEvent, feedbackClient, initializeSelfHostedFeedback, selfHostedFeedbackOptions, sanitizeSelfHostedFeedback, sankeyFeedbackSurvey, sankeyFeedbackResponse } from "../../../app/javascript/utils/sankey_preview_analytics.mjs";
+
+const fixture = () => ({
+ id: "test-survey", type: "api", start_date: "2026-09-14T00:00:00Z", end_date: null,
+ questions: [
+ { id: "feedback-id", type: "open", question: "What did not show correctly?", optional: true },
+ { id: "rating-id", type: "single_choice", choices: ["Looks right", "Something looks wrong"] },
+ ],
+});
+
+test("resolves real survey question IDs independently of order", () => {
+ const survey = sankeyFeedbackSurvey([fixture()], "test-survey");
+ assert.deepEqual(sankeyFeedbackResponse(survey, "negative", "Labels overlap"), {
+ $survey_id: "test-survey",
+ "$survey_response_rating-id": "Something looks wrong",
+ "$survey_response_feedback-id": "Labels overlap",
+ });
+ assert.equal(sankeyFeedbackResponse(survey, "positive", "")["$survey_response_rating-id"], "Looks right");
+});
+
+test("rejects missing, inactive and incompatible surveys", () => {
+ assert.equal(sankeyFeedbackSurvey([], "test-survey"), null);
+ for (const changes of [{ start_date: null }, { end_date: "2026-09-14" }, { archived: true }, { type: "popover" }, { questions: [] }]) {
+ assert.equal(sankeyFeedbackSurvey([{ ...fixture(), ...changes }], "test-survey"), null);
+ }
+});
+
+test("missing, blocked, opted-out and throwing analytics do not break the view", () => {
+ assert.equal(capturePreviewEvent(undefined, "sankey_preview_displayed"), false);
+ assert.equal(capturePreviewEvent({ __loaded: false }, "sankey_preview_displayed"), false);
+ assert.equal(capturePreviewEvent({ __loaded: true, has_opted_out_capturing: () => true }, "sankey_preview_displayed"), false);
+ assert.equal(capturePreviewEvent({ __loaded: true, capture() { throw new Error("Blocked"); } }, "sankey_preview_displayed"), false);
+});
+
+test("display events contain only the version, surface and state", () => {
+ const captures = [];
+ const posthog = { __loaded: true, capture(event, properties) { captures.push({ event, properties }); return {}; } };
+ assert.equal(capturePreviewEvent(posthog, "sankey_preview_displayed", { surface: "inline", state: "content" }), true);
+ assert.deepEqual(captures, [{ event: "sankey_preview_displayed", properties: { preview_version: "cash_flow_v1", surface: "inline", state: "content" } }]);
+});
+
+
+test("routes managed environments to their existing project and self-hosting only to the feedback project", () => {
+ const shared = { __loaded: true };
+ const posthog = { __loaded: true, sankeyFeedback: shared };
+ assert.equal(feedbackClient(posthog, false), posthog);
+ assert.equal(feedbackClient(posthog, true), shared);
+ assert.equal(feedbackClient({ __loaded: true }, true), undefined);
+ posthog.has_opted_out_capturing = () => true;
+ assert.equal(feedbackClient(posthog, true), undefined);
+ assert.equal(feedbackClient(posthog, false), undefined);
+});
+
+test("dedicated initialization is optional, idempotent and announces readiness after the named client exists", async () => {
+ const calls = [];
+ const sdk = { init(...args) { calls.push(args); args[1].loaded(); this.sankeyFeedback = {}; } };
+ let readyClient;
+ const ready = () => { readyClient = sdk.sankeyFeedback; };
+ initializeSelfHostedFeedback(sdk, "", "https://us.i.posthog.com", ready);
+ assert.equal(calls.length, 0);
+ initializeSelfHostedFeedback(sdk, "public-feedback-token", "https://us.i.posthog.com", ready);
+ initializeSelfHostedFeedback(sdk, "public-feedback-token", "https://us.i.posthog.com", ready);
+ assert.equal(calls.length, 1);
+ assert.equal(calls[0][0], "public-feedback-token");
+ assert.equal(calls[0][2], "sankeyFeedback");
+ assert.equal(readyClient, undefined);
+ await Promise.resolve();
+ assert.equal(readyClient, sdk.sankeyFeedback);
+ assert.doesNotThrow(() => initializeSelfHostedFeedback({ init() { throw Error("blocked"); } }, "key", "host", ready));
+ initializeSelfHostedFeedback({ has_opted_out_capturing: () => true, init() { assert.fail("opt-out must prevent initialization"); } }, "key", "host", ready);
+});
+
+test("self-hosted feedback disables automatic collection and strips incidental SDK metadata", () => {
+ const options = selfHostedFeedbackOptions("https://us.i.posthog.com");
+ for (const name of ["autocapture", "capture_pageview", "capture_pageleave", "capture_dead_clicks", "capture_exceptions", "capture_heatmaps", "capture_performance", "enable_recording_console_log"]) assert.equal(options[name], false);
+ assert.equal(options.disable_session_recording, true);
+ assert.equal(options.person_profiles, "never");
+ assert.equal(options.persistence, "memory");
+ const event = options.before_send({ event: "sankey_preview_displayed", properties: {
+ token: "public-project-token", distinct_id: "anonymous", preview_version: "cash_flow_v1", surface: "inline", state: "content",
+ $current_url: "https://private.example/", $referrer: "https://private.example/accounts", email: "[email protected]", $set: { name: "Private" }, $device_id: "device",
+ } });
+ assert.deepEqual(event.properties, { token: "public-project-token", distinct_id: "anonymous", preview_version: "cash_flow_v1", surface: "inline", state: "content", $geoip_disable: true, $process_person_profile: false });
+ assert.equal(sanitizeSelfHostedFeedback({ event: "$pageview" }), null);
+ assert.equal(sanitizeSelfHostedFeedback({ event: "$identify" }), null);
+ const responseKey = "$survey_response_01a0a162-73a2-0000-9402-ffab5bc45b4a";
+ assert.equal(sanitizeSelfHostedFeedback({ event: "survey sent", properties: { [responseKey]: "Labels overlap" } }).properties[responseKey], "Labels overlap");
+ assert.equal(sanitizeSelfHostedFeedback({ event: "survey shown", properties: { [responseKey]: "Not submitted" } }).properties[responseKey], undefined);
+});
diff --git a/test/models/income_statement/sankey_test.rb b/test/models/income_statement/sankey_test.rb
new file mode 100644
index 0000000000..9547706c05
--- /dev/null
+++ b/test/models/income_statement/sankey_test.rb
@@ -0,0 +1,124 @@
+require "test_helper"
+
+class IncomeStatement::SankeyTest < ActiveSupport::TestCase
+ include EntriesTestHelper
+
+ setup do
+ @family = families(:empty)
+ @account = @family.accounts.create!(name: "Checking", currency: "USD", balance: 0, accountable: Depository.new)
+ @month = Date.new(2024, 2, 1)
+ @parent = @family.categories.create!(name: "Shopping", color: "#123456")
+ @child = @family.categories.create!(name: "Rebates", parent: @parent)
+ end
+
+ test "opposite direction children are not double counted in parent totals" do
+ transaction(100, @parent)
+ transaction(-30, @child)
+ result = graph
+ assert_equal "100.0", result[:spending]
+ assert_equal "30.0", result[:income]
+ assert_equal "-70.0", result[:net_savings]
+ assert_equal "100.0", node(result, "expense_#{@parent.id}")[:value]
+ assert_equal "30.0", node(result, "income_#{@parent.id}")[:value]
+ assert_equal @child.filter_value, node(result, "income_sub_#{@child.id}")[:filter_value]
+ assert_equal "70.0", node(result, "deficit_node")[:value]
+ assert_balanced(result)
+ end
+
+ test "zero net parent retains both directions and same-category refunds net once" do
+ transaction(150, @parent)
+ transaction(-50, @parent)
+ transaction(-100, @child)
+ result = graph
+ assert_equal "100.0", result[:income]
+ assert_equal "100.0", result[:spending]
+ assert_equal "0.0", result[:net_savings]
+ assert_balanced(result)
+ end
+
+ test "same direction children share parent capacity without duplicating totals" do
+ transaction(10, @parent)
+ transaction(20, @child)
+ result = graph
+ assert_equal "30.0", result[:spending]
+ assert_equal "30.0", node(result, "expense_#{@parent.id}")[:value]
+ assert_equal "20.0", node(result, "expense_sub_#{@child.id}")[:value]
+ assert_balanced(result)
+ end
+
+ test "decimal netting retains sub-cent precision beyond floating point accuracy" do
+ transaction("900719925474.1234".to_d, @parent)
+ transaction("-900719925474.1233".to_d, @parent)
+ transaction("0.2".to_d, @child)
+ result = graph
+ assert_equal "0.2001", result[:spending]
+ assert_equal "0.2001", node(result, "expense_#{@parent.id}")[:value]
+ assert_equal "0.2", node(result, "expense_sub_#{@child.id}")[:value]
+ assert_equal "0.2001", node(result, "deficit_node")[:value]
+ assert_balanced(result)
+ end
+
+ test "a spending-only period has an explicit deficit through cash flow to expenses" do
+ transaction(160, @parent)
+ result = graph
+ assert_equal "0.0", result[:income]
+ assert_equal "160.0", result[:spending]
+ assert_equal "-160.0", result[:net_savings]
+ assert_equal [
+ [ "cash_flow_node", "expense_#{@parent.id}", "160.0" ],
+ [ "deficit_node", "cash_flow_node", "160.0" ]
+ ].sort, result[:links].map { |link| [ result[:nodes][link[:source]][:id], result[:nodes][link[:target]][:id], link[:value] ] }.sort
+ assert_balanced(result)
+ end
+
+ test "preserves FX precision, reporting eligibility and surplus" do
+ eur = @family.accounts.create!(name: "EUR", currency: "EUR", balance: 0, accountable: Depository.new)
+ ExchangeRate.create!(from_currency: "EUR", to_currency: "USD", date: @month, rate: "1.2345")
+ create_transaction(account: eur, currency: "EUR", amount: 10, date: @month, category: @child)
+ transaction(-100, @parent)
+ create_transaction(account: @account, amount: 900, date: @month, excluded: true)
+ create_transaction(account: @account, amount: 800, date: @month, kind: "cc_payment")
+ pending = create_transaction(account: @account, amount: 700, date: @month)
+ pending.entryable.update!(extra: { "simplefin" => { "pending" => true } })
+ create_transaction(account: accounts(:depository), amount: 600, date: @month)
+ result = graph
+ assert_equal "12.345", result[:spending]
+ assert_equal "87.655", node(result, "surplus_node")[:value]
+ assert_balanced(result)
+ end
+
+ test "empty graph and uncategorized identifiers are deterministic" do
+ assert_empty graph[:nodes]
+ assert_empty graph[:links]
+ transaction(10, nil)
+ assert_equal "10.0", node(graph, "expense_uncategorized")[:value]
+ assert_equal graph, graph
+ end
+
+ private
+ def transaction(amount, category)
+ create_transaction(account: @account, amount: amount, category: category, date: @month)
+ end
+
+ def graph
+ IncomeStatement::Sankey.new(IncomeStatement.new(@family), period: Period.custom(start_date: @month, end_date: @month.end_of_month)).as_json
+ end
+
+ def node(graph, id)
+ graph[:nodes].find { |node| node[:id] == id }
+ end
+
+ def assert_balanced(graph)
+ center = graph[:nodes].index { |node| node[:id] == "cash_flow_node" }
+ incoming = graph[:links].select { |link| link[:target] == center }.sum { |link| link[:value].to_d }
+ outgoing = graph[:links].select { |link| link[:source] == center }.sum { |link| link[:value].to_d }
+ assert_equal incoming, outgoing
+ graph[:nodes].each_with_index do |node, index|
+ allocations = %i[source target].map do |end_point|
+ graph[:links].select { |link| link[end_point] == index }.sum { |link| link[:value].to_d }
+ end
+ assert_operator node[:value].to_d, :>, 0
+ assert_equal node[:value].to_d, allocations.max, "#{node[:id]} must match its links' capacity"
+ end
+ end
+end
diff --git a/test/system/cash_flow_test.rb b/test/system/cash_flow_test.rb
new file mode 100644
index 0000000000..729bee50e0
--- /dev/null
+++ b/test/system/cash_flow_test.rb
@@ -0,0 +1,346 @@
+require "application_system_test_case"
+
+class CashFlowTest < ApplicationSystemTestCase
+ include EntriesTestHelper
+
+ setup do
+ @user = users(:family_admin)
+ @month = Date.current.beginning_of_month
+ @user.update!(preferences: @user.preferences.merge("preview_features_enabled" => true))
+ parent = @user.family.categories.create!(name: "Sankey Shopping", color: "#123456")
+ child = @user.family.categories.create!(name: "Sankey Groceries", parent: parent)
+ account = @user.family.accounts.create!(name: "Sankey checking", currency: "USD", balance: 0, accountable: Depository.new)
+ create_transaction(account: account, category: parent, amount: 100, date: @month)
+ create_transaction(account: account, category: child, amount: 50, date: @month)
+ end
+
+ test "loads the dashboard graph, expands, zooms, and preserves transaction date filters" do
+ sign_in @user
+ visit root_path(start_date: @month.iso8601, end_date: Date.current.iso8601)
+ chart = find("#cashflow-preview [data-preview-sankey-chart-target='chart']", match: :first)
+ assert_selector "#cashflow-preview svg .sankey-link"
+ assert page.evaluate_script("performance.getEntriesByType('resource').some(e => e.name.includes('/dashboard/cash_flow?'))")
+ within "#cashflow-preview" do
+ click_button "Expand"
+ end
+ within "#cashflow-preview-expanded-dialog" do
+ assert_selector "svg .sankey-link"
+ end
+ gradients = page.evaluate_script(<<~JS)
+ Array.from(document.querySelectorAll('#cashflow-preview linearGradient')).map(g => g.id)
+ JS
+ assert_selector "#cashflow-preview [data-preview-sankey-chart-target='chart'] svg", count: 2
+ assert gradients.any?
+ assert_equal gradients.uniq, gradients
+ assert page.evaluate_script(<<~JS)
+ Array.from(document.querySelectorAll('#cashflow-preview .sankey-link')).every(link => {
+ const id = link.getAttribute('stroke').slice(5, -1);
+ return link.ownerSVGElement.querySelector(`[id="${id}"]`);
+ })
+ JS
+ page.execute_script("document.querySelector('#cashflow-preview-expanded-dialog').close()")
+ parent = chart.find("svg text", text: "Sankey Shopping", match: :first)
+ parent.find(:xpath, "..").find("path").click
+ assert_selector "[data-preview-sankey-chart-target='zoomOutButton']:not([hidden])"
+ find("[data-preview-sankey-chart-target='zoomOutButton']", match: :first).click
+ chart.find("svg text", text: "Sankey Groceries", match: :first).find(:xpath, "..").find("path").click
+ assert_current_path(%r{/transactions\?})
+ query = Rack::Utils.parse_nested_query(URI.parse(page.current_url).query)
+ assert_equal [ "Sankey Groceries" ], query.dig("q", "categories")
+ assert_equal @month.iso8601, query.dig("q", "start_date")
+ assert_equal Date.current.iso8601, query.dig("q", "end_date")
+ end
+
+ test "bars labels Enter and Space share zoom and transaction actions" do
+ sign_in @user
+ [ :bar, :label, :enter, :space ].each do |activation|
+ visit root_path(start_date: @month.iso8601, end_date: Date.current.iso8601)
+ chart = find("#cashflow-preview [data-preview-sankey-chart-target='chart']", match: :first)
+ parent = chart.find("g[role='button'][tabindex='0'][aria-label^='Sankey Shopping,']")
+ activate_node(parent, activation)
+ assert_selector "[data-preview-sankey-chart-target='zoomOutButton']:not([hidden])"
+ assert_selector "g[aria-label^='Sankey Shopping,']:focus" if [ :enter, :space ].include?(activation)
+ assert_equal "false", find("[data-section-key='cashflow_sankey']")["aria-grabbed"]
+ find("[data-preview-sankey-chart-target='zoomOutButton']", match: :first).send_keys(:enter)
+ assert_selector "g[aria-label^='Sankey Shopping,']:focus"
+ leaf = chart.find("g[role='link'][tabindex='0'][aria-label^='Sankey Groceries,']")
+ activate_node(leaf, activation)
+ assert_current_path(%r{/transactions\?})
+ query = Rack::Utils.parse_nested_query(URI.parse(page.current_url).query)
+ assert_equal [ "Sankey Groceries" ], query.dig("q", "categories")
+ assert_equal @month.iso8601, query.dig("q", "start_date")
+ assert_equal Date.current.iso8601, query.dig("q", "end_date")
+ end
+ end
+
+ test "closing the expanded chart returns focus to Expand after keyboard zoom" do
+ sign_in @user
+ [ :escape, :close_button ].each do |closing|
+ visit root_path(start_date: @month.iso8601, end_date: Date.current.iso8601)
+ expand = find("#cashflow-preview button", text: "Expand")
+ expand.send_keys(:enter)
+ within "#cashflow-preview-expanded-dialog[open]" do
+ find("g[role='button'][aria-label^='Sankey Shopping,']").send_keys(:enter)
+ assert_selector "g[aria-label^='Sankey Shopping,']:focus"
+ if closing == :escape
+ find("g:focus").send_keys(:escape)
+ else
+ find("button[data-action='DS--dialog#close']").click
+ end
+ end
+ assert_no_selector "#cashflow-preview-expanded-dialog[open]"
+ assert_selector "#cashflow-preview button:focus", text: "Expand"
+ assert_equal "true", find("[data-section-key='cashflow_sankey']")["draggable"]
+ end
+ end
+
+ test "spending without income renders the deficit cash flow expense path" do
+ date = Date.new(2001, 2, 1)
+ category = @user.family.categories.find_by!(name: "Sankey Shopping")
+ account = @user.family.accounts.find_by!(name: "Sankey checking")
+ create_transaction(account: account, category: category, amount: 160, date: date)
+ sign_in @user
+ visit root_path(start_date: date.iso8601, end_date: date.iso8601)
+ chart = find("#cashflow-preview [data-preview-sankey-chart-target='chart']", match: :first)
+ [ "Deficit", "Cash Flow", "Sankey Shopping" ].each do |name|
+ assert_selector "#cashflow-preview g[aria-label='#{name}, $160.00']"
+ end
+ links = chart.all(".sankey-link").map do |link|
+ assert link["d"].present?
+ link.evaluate_script("[this.__data__.source.id, this.__data__.target.id, this.__data__.value]")
+ end
+ assert_equal [
+ [ "cash_flow_node", "expense_#{category.id}", 160 ],
+ [ "deficit_node", "cash_flow_node", 160 ]
+ ].sort, links.sort
+ end
+
+ test "preview structural labels and tooltips use the user locale" do
+ @user.update!(locale: "es")
+ sign_in @user
+ chart = find("#cashflow-preview [data-preview-sankey-chart-target='chart']", match: :first)
+ assert_selector "#cashflow-preview svg text", text: "Flujo de caja"
+ assert_selector "#cashflow-preview svg text", text: "Déficit"
+ chart.find("svg text", text: "Déficit", match: :first).hover
+ assert_selector ".chart-tooltip.ph-no-capture", text: "Déficit"
+ assert_selector "#cashflow-preview svg text", text: "Sankey Groceries"
+ account = @user.family.accounts.find_by!(name: "Sankey checking")
+ create_transaction(account: account, amount: -1000, date: @month)
+ visit root_path(start_date: @month.iso8601, end_date: Date.current.iso8601)
+ assert_selector "#cashflow-preview svg text", text: "Superávit"
+ end
+
+ test "failed load can retry and an empty range clears old chart data" do
+ sign_in @user
+ assert_selector "#cashflow-preview svg .sankey-link"
+ page.execute_script(<<~JS)
+ window.originalCashFlowFetch = window.fetch;
+ window.fetch = (url, options) => String(url).includes('/dashboard/cash_flow')
+ ? Promise.resolve(new Response('{}', {status: 503})) : window.originalCashFlowFetch(url, options);
+ document.querySelector('[data-action="cash-flow#load"]').click();
+ JS
+ assert_selector "[data-cash-flow-target='error']:not([hidden])"
+ assert_selector "#cashflow-sankey-chart svg .sankey-link"
+ assert_no_selector "[data-preview-sankey-chart-target='chart'] svg"
+ page.execute_script("window.fetch = window.originalCashFlowFetch")
+ within "[data-cash-flow-target='error']" do
+ click_button "Try again"
+ end
+ assert_selector "#cashflow-preview svg .sankey-link"
+ visit root_path(start_date: "1900-01-01", end_date: "1900-01-02")
+ assert_selector "[data-cash-flow-target='empty']:not([hidden])"
+ assert_no_selector "#cashflow-sankey-chart svg .sankey-link"
+ assert_no_selector "[data-preview-sankey-chart-target='chart'] svg"
+ end
+
+ test "preview displays are counted once and feedback uses PostHog survey question IDs" do
+ sign_in @user
+ assert_selector "#cashflow-preview svg .sankey-link"
+ install_posthog_fake
+ find("#cashflow-preview").scroll_to(:center)
+ assert_selector "#cashflow-preview [data-preview-sankey-chart-target='chart'] svg"
+ assert_event_count "sankey_preview_displayed", 1
+ page.execute_script("document.dispatchEvent(new Event('posthog:ready'))")
+ assert_event_count "sankey_preview_displayed", 1
+
+ within "#cashflow-preview" do
+ click_button "Expand"
+ end
+ assert_selector "#cashflow-preview-expanded-dialog[open] svg .sankey-link"
+ assert_equal "false", find("[data-section-key='cashflow_sankey']")["draggable"]
+ assert_event_count "sankey_preview_displayed", 2
+ within "#cashflow-preview-expanded-dialog" do
+ find("button[data-action='DS--dialog#close']").click
+ end
+ assert_equal "true", find("[data-section-key='cashflow_sankey']")["draggable"]
+
+ [ "Looks right", "Something looks wrong" ].each_with_index do |rating, index|
+ within "#cashflow-preview" do
+ click_button rating
+ end
+ within "#cashflow-preview-feedback-dialog" do
+ fill_in "What did not show correctly?", with: "Labels overlap"
+ click_button "Send feedback"
+ assert_text "Thanks for helping improve the chart!"
+ find("button[data-action='DS--dialog#close']").click
+ end
+ assert_event_count "survey sent", index + 1
+ response = page.evaluate_script("window.sankeyEvents.filter(e => e.event === 'survey sent').at(-1).properties")
+ assert_equal rating, response.fetch("$survey_response_rating-id")
+ assert_equal "Labels overlap", response.fetch("$survey_response_feedback-id")
+ assert_equal "test-survey", response.fetch("$survey_id")
+ end
+ assert_event_count "survey shown", 2
+ assert_event_count "survey dismissed", 0
+ end
+
+ test "dismissing feedback does not submit it and absent analytics keeps both charts usable" do
+ sign_in @user
+ assert_selector "#cashflow-preview svg .sankey-link"
+ within "#cashflow-preview" do
+ click_button "Something looks wrong"
+ end
+ within "#cashflow-preview-feedback-dialog" do
+ assert_text "Feedback isn't available right now"
+ find("button[data-action='DS--dialog#close']").click
+ end
+ install_posthog_fake
+ within "#cashflow-preview" do
+ click_button "Something looks wrong"
+ end
+ within "#cashflow-preview-feedback-dialog" do
+ fill_in "What did not show correctly?", with: "Not submitted"
+ find("button[data-action='DS--dialog#close']").click
+ end
+ assert_event_count "survey dismissed", 1
+ assert_event_count "survey sent", 0
+ assert_selector "#cashflow-sankey-chart svg .sankey-link"
+ assert_selector "#cashflow-preview svg .sankey-link"
+ end
+
+ test "collapsed previews do not count until visible and keyboard expansion preserves section order" do
+ sign_in @user
+ assert_selector "#cashflow-preview svg .sankey-link"
+ section = find("[data-section-key='cashflow_sankey']")
+ section.find("[data-dashboard-section-target='button']").click
+ assert_no_selector "#cashflow-preview"
+ install_posthog_fake
+ assert_event_count "sankey_preview_displayed", 0
+ section.find("[data-dashboard-section-target='button']").click
+ find("#cashflow-preview").scroll_to(:center)
+ assert_event_count "sankey_preview_displayed", 1
+ within "#cashflow-preview" do
+ find_button("Expand").send_keys(:enter)
+ end
+ assert_selector "#cashflow-preview-expanded-dialog[open]"
+ assert_equal "false", section["aria-grabbed"]
+ assert_event_count "sankey_preview_displayed", 2
+ end
+
+ test "Turbo snapshots clear preview graphs, floating tooltips, and unsubmitted feedback" do
+ sign_in @user
+ assert_selector "#cashflow-preview svg .sankey-link"
+ install_posthog_fake
+ find("#cashflow-preview svg text", text: "Sankey Shopping", match: :first).hover
+ assert_selector ".chart-tooltip.ph-no-capture", text: "Sankey Shopping"
+ within "#cashflow-preview" do
+ click_button "Something looks wrong"
+ end
+ within "#cashflow-preview-feedback-dialog" do
+ fill_in "What did not show correctly?", with: "Not submitted"
+ end
+ snapshot = page.evaluate_script(<<~JS)
+ (() => {
+ document.dispatchEvent(new Event('turbo:before-cache'));
+ const copy = document.body.cloneNode(true);
+ return {
+ previewGraphs: copy.querySelectorAll('#cashflow-preview svg .sankey-link').length,
+ tooltips: copy.querySelectorAll('.chart-tooltip.ph-no-capture').length,
+ feedback: copy.querySelector('#cashflow-preview-feedback').value,
+ legacyGraph: !!copy.querySelector('#cashflow-sankey-chart svg .sankey-link')
+ };
+ })()
+ JS
+ assert_equal({ "previewGraphs" => 0, "tooltips" => 0, "feedback" => "", "legacyGraph" => true }, snapshot)
+ assert_event_count "survey sent", 0
+ assert_event_count "survey dismissed", 1
+ end
+
+ test "self-hosted displays and feedback use only the separate project" do
+ with_self_hosting do
+ sign_in @user
+ visit root_path(start_date: @month.iso8601, end_date: Date.current.iso8601)
+ assert_selector "#cashflow-preview svg .sankey-link"
+ install_posthog_fake
+ page.execute_script(<<~JS)
+ const shared = window.posthog;
+ window.posthog = {
+ __loaded: true,
+ has_opted_out_capturing: () => false,
+ capture: () => { throw new Error('Wrong analytics destination'); },
+ getSurveys: () => { throw new Error('Wrong survey destination'); },
+ sankeyFeedback: shared
+ };
+ document.dispatchEvent(new Event('posthog:ready'));
+ JS
+ find("#cashflow-preview").scroll_to(:center)
+ assert_event_count "sankey_preview_displayed", 1
+ within "#cashflow-preview" do
+ click_button "Expand"
+ end
+ assert_event_count "sankey_preview_displayed", 2
+ find("#cashflow-preview-expanded-dialog").find("button[data-action='DS--dialog#close']").click
+ within "#cashflow-preview" do
+ click_button "Something looks wrong"
+ end
+ fill_in "cashflow-preview-feedback", with: "The labels overlap"
+ click_button "Send feedback"
+ assert_event_count "survey sent", 1
+ assert page.evaluate_script("window.sankeyEvents.some(e => e.event === 'survey sent' && e.properties.$survey_id === 'test-survey')")
+ find("#cashflow-preview-feedback-dialog").find("button[data-action='DS--dialog#close']").click
+ page.execute_script("document.querySelector('#cashflow-preview').setAttribute('data-sankey-preview-feedback-key-value', '')")
+ within "#cashflow-preview" do
+ click_button "Looks right"
+ end
+ assert_selector "#cashflow-preview-feedback-dialog[open] [role='status']", text: "Feedback isn't available right now"
+ assert_event_count "survey shown", 1
+ assert_event_count "survey sent", 1
+ end
+ end
+
+ private
+ def activate_node(node, activation)
+ case activation
+ when :bar then node.find("path").click
+ when :label then node.find("text", match: :first).click
+ else node.send_keys(activation)
+ end
+ end
+
+ def install_posthog_fake
+ page.execute_script(<<~JS)
+ window.sankeyEvents = [];
+ window.posthog = {
+ __loaded: true,
+ has_opted_out_capturing: () => false,
+ capture: (event, properties) => { window.sankeyEvents.push({event, properties}); return {}; },
+ getSurveys: callback => callback([{
+ id: 'test-survey', type: 'api', start_date: '2026-09-14', end_date: null,
+ questions: [
+ {id: 'feedback-id', type: 'open', question: 'What did not show correctly?', optional: true},
+ {id: 'rating-id', type: 'single_choice', choices: ['Looks right', 'Something looks wrong']}
+ ]
+ }])
+ };
+ document.querySelector('#cashflow-preview').setAttribute('data-sankey-preview-survey-id-value', 'test-survey');
+ document.querySelector('#cashflow-preview').setAttribute('data-sankey-preview-feedback-key-value', 'test-public-token');
+ document.dispatchEvent(new Event('posthog:ready'));
+ JS
+ end
+
+ def assert_event_count(event, count)
+ assert_selector "body" do
+ page.evaluate_script("window.sankeyEvents.filter(e => e.event === #{event.to_json}).length") == count
+ end
+ end
+end