Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

Improve Sankey preview comparison and feedback (#3585)

Juan José Mata4bdacec7be8d
diff --git a/.env.local.example b/.env.local.example
index af55a74056..5af0e08375 100644
--- a/.env.local.example
+++ b/.env.local.example
@@ -1,5 +1,5 @@
# To enable / disable self-hosting features.
-SELF_HOSTED = true
+SELF_HOSTED=true
# Custom port config
# For users who have other applications listening at 3000, this allows them to set a value puma will listen to.
@@ -28,7 +28,7 @@ LUNCHFLOW_DEBUG_RAW=false
LUNCHFLOW_INCLUDE_PENDING=false
# Controls onboarding flow (valid: open, closed, invite_only)
-ONBOARDING_STATE = open
+ONBOARDING_STATE=open
# Enable Twelve market data (careful, this will use your API credits)
TWELVE_DATA_API_KEY =
@@ -143,10 +143,16 @@ APNS_PRIVATE_KEY_BASE64=
SKYLIGHT_AUTHENTICATION=
SKYLIGHT_ENABLED=
+# PostHog
+# ========
# 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=
-
+# POSTHOG_SANKEY_SURVEY_ID=
+#
# Optional self-hosted opt-out (enabled by default, preview users only).
# POSTHOG_FEEDBACK_ENABLED=false
+#
+# Temporary local PostHog testing only; off by default. Restart after changing.
+# Uses live projects and sends real survey responses.
+# POSTHOG_DEVELOPMENT_ENABLED=true
diff --git a/app/helpers/feedback_helper.rb b/app/helpers/feedback_helper.rb
index bab3db701c..282b0afe90 100644
--- a/app/helpers/feedback_helper.rb
+++ b/app/helpers/feedback_helper.rb
@@ -1,8 +1,12 @@
module FeedbackHelper
+ def posthog_enabled?
+ Rails.env.production? || (Rails.env.development? && Rails.configuration.x.posthog.development_enabled)
+ end
+
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)
+ return {} if destination == :self_hosted && !(posthog_enabled? && config.feedback_enabled)
survey_id = config.feedback_surveys.dig(feature, destination).presence
return {} unless survey_id
diff --git a/app/javascript/controllers/cash_flow_controller.js b/app/javascript/controllers/cash_flow_controller.js
index 8709c18d98..c5ec53ccab 100644
--- a/app/javascript/controllers/cash_flow_controller.js
+++ b/app/javascript/controllers/cash_flow_controller.js
@@ -50,16 +50,18 @@ export default class extends Controller {
JSON.stringify(data),
);
});
- this.show(data.links.length ? "content" : "empty");
+ this.show(data.links.length ? "content" : "empty", data);
} catch {
if (this.request === request) this.show("error");
}
}
- show(state) {
+ show(state, graph = null) {
for (const name of ["loading", "error", "empty", "content"]) {
this[`${name}Target`].hidden = name !== state;
}
- this.dispatch("state", { detail: { state, ready: state === "content" } });
+ this.dispatch("state", {
+ detail: { state, ready: state === "content", graph },
+ });
}
}
diff --git a/app/javascript/controllers/sankey_preview_controller.js b/app/javascript/controllers/sankey_preview_controller.js
index 832fe01f38..245a9470c0 100644
--- a/app/javascript/controllers/sankey_preview_controller.js
+++ b/app/javascript/controllers/sankey_preview_controller.js
@@ -1,12 +1,15 @@
import { Controller } from "@hotwired/stimulus";
import {
capturePreviewEvent,
+ captureSankeyComparison,
feedbackClient,
initializeSelfHostedFeedback,
sankeyFeedbackResponse,
sankeyFeedbackSurvey,
} from "utils/sankey_preview_analytics";
+import { compareSankeyData } from "utils/sankey_comparison";
+
export default class extends Controller {
static targets = [
"display",
@@ -18,6 +21,7 @@ export default class extends Controller {
];
static values = {
surveyId: String,
+ legacyData: Object,
selfHosted: Boolean,
feedbackKey: String,
feedbackHost: String,
@@ -32,6 +36,9 @@ export default class extends Controller {
() => document.dispatchEvent(new Event("posthog:ready")),
);
}
+ this.comparisonDone = false;
+ this.comparisonResult = null;
+ delete this.element.dataset.sankeyComparison;
this.displays = new Set();
this.state = "loading";
this.active = true;
@@ -55,6 +62,8 @@ export default class extends Controller {
clear() {
this.dismiss();
this.active = false;
+ this.comparisonResult = null;
+ delete this.element.dataset.sankeyComparison;
this.feedbackRequest = null;
clearTimeout(this.feedbackTimeout);
this.expandedDialogTarget.close();
@@ -65,13 +74,29 @@ export default class extends Controller {
}
update({ detail }) {
- if (detail.state === "loading") this.displays.clear();
+ if (detail.state === "loading") {
+ this.displays.clear();
+ this.comparisonDone = false;
+ }
this.state = detail.state;
+ this.comparisonResult = detail.graph
+ ? compareSankeyData(this.legacyDataValue, detail.graph)
+ : null;
+ this.element.dataset.sankeyComparison = this.comparisonResult || "";
this.expandButtonTarget.disabled = !detail.ready;
this.trackDisplay();
}
+ trackComparison() {
+ if (!this.active || this.comparisonDone || !this.comparisonResult) return;
+ this.comparisonDone = captureSankeyComparison(
+ this.posthog,
+ this.comparisonResult,
+ );
+ }
+
trackDisplay() {
+ this.trackComparison();
if (
!this.active ||
document.hidden ||
@@ -170,7 +195,7 @@ export default class extends Controller {
$survey_id: this.survey.id,
});
input.focus();
- });
+ }, true); // Fetch current questions instead of a cached pre-launch/edit definition.
} catch {
this.unavailable();
}
diff --git a/app/javascript/utils/sankey_comparison.mjs b/app/javascript/utils/sankey_comparison.mjs
new file mode 100644
index 0000000000..96905b30c5
--- /dev/null
+++ b/app/javascript/utils/sankey_comparison.mjs
@@ -0,0 +1,64 @@
+// Compare financial inputs before D3 mutates them. IDs replace array indexes;
+// amounts use the legacy chart's two-decimal precision (percentages use one).
+// Labels, colors, API-only metadata and layout coordinates are not compared.
+export function compareSankeyData(legacy, preview) {
+ try {
+ const aliases = syntheticAliases(preview);
+ return JSON.stringify(normalize(legacy, aliases)) === JSON.stringify(normalize(preview))
+ ? "match"
+ : "mismatch";
+ } catch {
+ // Missing or invalid inputs are not evidence of a financial mismatch.
+ return null;
+ }
+}
+
+// Legacy synthetic IDs contain translated names; real categories use UUIDs.
+// Alias only the known synthetic categories, never arbitrary category names.
+function syntheticAliases(preview) {
+ const aliases = new Map();
+ for (const node of preview.nodes) {
+ if (/^(income|expense)_(uncategorized|other_investments)$/.test(node.id) &&
+ node.category_id == null && typeof node.name === "string") {
+ const side = node.id.split("_")[0];
+ aliases.set(`${side}_${node.name}`, node.id);
+ }
+ }
+ return aliases;
+}
+
+function normalize(graph, aliases = new Map()) {
+ if (!Array.isArray(graph?.nodes) || !Array.isArray(graph?.links))
+ throw new Error("Missing graph");
+ const ids = new Set();
+ const nodes = graph.nodes.map((node) => {
+ const id = aliases.get(node.id) || node.id;
+ if (typeof id !== "string" || ids.has(id))
+ throw new Error("Invalid node identity");
+ ids.add(id);
+ return [id, number(node.value, 2), number(node.percentage, 1)];
+ });
+ const links = graph.links.map((link) => {
+ const endpoints = [link.source, link.target].map((index) => {
+ if (!Number.isInteger(index) || !nodes[index])
+ throw new Error("Invalid endpoint");
+ return nodes[index][0];
+ });
+ return [...endpoints, number(link.value, 2), number(link.percentage, 1)];
+ });
+ // The legacy builder emits a zero-valued center even when no chart is drawn.
+ const visibleNodes = links.length ? nodes : nodes.filter((node) => node[1] !== 0);
+ const sort = (items) => items.map((item) => JSON.stringify(item)).sort();
+ return { nodes: sort(visibleNodes), links: sort(links) };
+}
+
+function number(value, precision) {
+ if (typeof value !== "number" || !Number.isFinite(value) || value < 0)
+ throw new Error("Invalid numeric value");
+ // Shift the decimal before rounding to avoid cases such as 1.005 * 100
+ // becoming 100.49999999999999. Handle scientific notation as well.
+ const [coefficient, exponent = "0"] = String(value).split("e");
+ const shifted = Number(`${coefficient}e${Number(exponent) + precision}`);
+ if (!Number.isFinite(shifted)) throw new Error("Value exceeds comparison range");
+ return Math.round(shifted) / 10 ** precision;
+}
diff --git a/app/javascript/utils/sankey_preview_analytics.mjs b/app/javascript/utils/sankey_preview_analytics.mjs
index eb0e6a749c..6af2365d5f 100644
--- a/app/javascript/utils/sankey_preview_analytics.mjs
+++ b/app/javascript/utils/sankey_preview_analytics.mjs
@@ -84,6 +84,8 @@ export function sanitizeSelfHostedFeedback(event) {
if (!event || ![
"sankey_preview_displayed",
"sankey_preview_feedback_clicked",
+ "new_sankey_match",
+ "new_sankey_mismatch",
"survey shown",
"survey sent",
"survey dismissed",
@@ -116,3 +118,10 @@ export function initializeSelfHostedFeedback(posthog, key, host, loaded) {
// Blocked analytics must not prevent chart setup or navigation.
}
}
+
+// Only the outcome leaves the browser, never the compared graphs.
+// The controller deduplicates successful SDK captures for each graph load.
+export function captureSankeyComparison(posthog, result) {
+ if (!["match", "mismatch"].includes(result)) return false;
+ return capturePreviewEvent(posthog, `new_sankey_${result}`);
+}
diff --git a/app/views/layouts/shared/_head.html.erb b/app/views/layouts/shared/_head.html.erb
index 91ea7910db..2314f0a13b 100644
--- a/app/views/layouts/shared/_head.html.erb
+++ b/app/views/layouts/shared/_head.html.erb
@@ -33,7 +33,7 @@
<link rel="apple-touch-icon" sizes="512x512" href="/logo-pwa.png">
<link rel="icon" sizes="192x192" type="image/png" href="/android-chrome-192x192.png">
- <% if Rails.env.production? && (posthog_config = Rails.configuration.x.posthog).try(:api_key).present? %>
+ <% if posthog_enabled? && (posthog_config = Rails.configuration.x.posthog).try(:api_key).present? %>
<%= render "shared/posthog", posthog_api_key: posthog_config.api_key, posthog_host: posthog_config.host %>
<% end %>
diff --git a/app/views/pages/dashboard.html.erb b/app/views/pages/dashboard.html.erb
index fa7c4311b8..fb5639cc39 100644
--- a/app/views/pages/dashboard.html.erb
+++ b/app/views/pages/dashboard.html.erb
@@ -170,7 +170,7 @@
<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 %>
+ <%= render "pages/dashboard/cashflow_preview", period: @period, legacy_data: section[:locals][:sankey_data] %>
<% end %>
</div>
</section>
diff --git a/app/views/pages/dashboard/_cashflow_preview.html.erb b/app/views/pages/dashboard/_cashflow_preview.html.erb
index 89a8031a0e..6971c5a16e 100644
--- a/app/views/pages/dashboard/_cashflow_preview.html.erb
+++ b/app/views/pages/dashboard/_cashflow_preview.html.erb
@@ -1,10 +1,11 @@
-<%# locals: (period:) %>
+<%# locals: (period:, legacy_data:) %>
<% 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"
+<section id="cashflow-preview" class="mt-6 border-t border-primary pt-4 space-y-4 ph-no-capture group/sankey-preview"
data-controller="sankey-preview"
+ data-sankey-preview-legacy-data-value="<%= legacy_data.to_json %>"
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] %>"
@@ -13,12 +14,11 @@
<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")) %>
+ <%= render DS::Pill.new(label: t("pages.dashboard.cashflow_preview.preview"), title: t("pages.dashboard.cashflow_preview.preview_tooltip")) %>
</div>
- <%= render DS::Button.new(icon: "maximize-2", text: t("global.expand"), variant: :ghost, disabled: true,
+ <%= render DS::Button.new(icon: "maximize-2", text: nil, variant: :ghost, disabled: true, aria: { label: t("global.expand") },
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) %>">
@@ -38,16 +38,19 @@
</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">
+ <div class="px-4 space-y-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 class="flex items-center justify-end gap-2">
+ <%= render DS::Button.new(icon: "thumbs-down", text: t("pages.dashboard.cashflow_preview.negative"), variant: :outline,
+ class: "group-data-[sankey-comparison=mismatch]/sankey-preview:bg-destructive/10 group-data-[sankey-comparison=mismatch]/sankey-preview:text-destructive group-data-[sankey-comparison=mismatch]/sankey-preview:border-destructive group-data-[sankey-comparison=mismatch]/sankey-preview:hover:bg-destructive/20 group-data-[sankey-comparison=mismatch]/sankey-preview:[&_svg]:text-destructive",
+ data: { action: "sankey-preview#feedback", sankey_preview_rating_param: "negative" }) %>
+ <%= render DS::Button.new(icon: "thumbs-up", text: t("pages.dashboard.cashflow_preview.positive"), variant: :outline,
+ class: "group-data-[sankey-comparison=match]/sankey-preview:bg-success/10 group-data-[sankey-comparison=match]/sankey-preview:text-success group-data-[sankey-comparison=match]/sankey-preview:border-success group-data-[sankey-comparison=match]/sankey-preview:hover:bg-success/20 group-data-[sankey-comparison=match]/sankey-preview:[&_svg]:text-success",
+ data: { action: "sankey-preview#feedback", sankey_preview_rating_param: "positive" }) %>
+ </div>
</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| %>
diff --git a/app/views/pages/dashboard/_cashflow_preview_chart.html.erb b/app/views/pages/dashboard/_cashflow_preview_chart.html.erb
index 0967405621..3a2e85676f 100644
--- a/app/views/pages/dashboard/_cashflow_preview_chart.html.erb
+++ b/app/views/pages/dashboard/_cashflow_preview_chart.html.erb
@@ -6,7 +6,7 @@
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">
+ class="w-full min-w-0 h-full privacy-sensitive flex flex-col gap-2">
<div class="flex justify-start px-4">
<%= render DS::Button.new(
variant: :icon,
diff --git a/config/importmap.rb b/config/importmap.rb
index e4e4e0b276..57c755e9ab 100644
--- a/config/importmap.rb
+++ b/config/importmap.rb
@@ -60,3 +60,5 @@ pin "d3-shape-src", to: "d3-shape.js"
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"
+
+pin "utils/sankey_comparison", to: "utils/sankey_comparison.mjs"
diff --git a/config/initializers/posthog.rb b/config/initializers/posthog.rb
index cf803da464..3e899723d8 100644
--- a/config/initializers/posthog.rb
+++ b/config/initializers/posthog.rb
@@ -1,6 +1,8 @@
require "posthog"
Rails.configuration.x.posthog = ActiveSupport::OrderedOptions.new
+# Explicit opt-in for local browser testing; production behavior is unchanged.
+Rails.configuration.x.posthog.development_enabled = ActiveModel::Type::Boolean.new.cast(ENV.fetch("POSTHOG_DEVELOPMENT_ENABLED", "false"))
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"))
diff --git a/config/locales/views/pages/en.yml b/config/locales/views/pages/en.yml
index 59c45fd43b..f7be00eb89 100644
--- a/config/locales/views/pages/en.yml
+++ b/config/locales/views/pages/en.yml
@@ -83,10 +83,10 @@ en:
cash_flow: "Cash Flow"
surplus: "Surplus"
deficit: "Deficit"
- title: "New cash flow chart"
+ title: "New Sankey 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?"
+ preview_tooltip: "This will replace the above visualization as it uses a new shared API with the mobile Swift client."
+ feedback_prompt: "Compare this chart with the original above and let us know if it looks different other than sorting."
positive: "Looks right"
negative: "Something looks wrong"
feedback_title: "Cash flow chart feedback"
@@ -99,7 +99,6 @@ en:
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/docs/hosting/preview-feedback.md b/docs/hosting/preview-feedback.md
index 1da8c4ba5b..d5ddc37d04 100644
--- a/docs/hosting/preview-feedback.md
+++ b/docs/hosting/preview-feedback.md
@@ -22,7 +22,20 @@ 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.
+feedback to another project. Shared collection is disabled outside production by default.
+
+### Local testing
+
+To test without changing Rails to production mode, temporarily set
+`POSTHOG_DEVELOPMENT_ENABLED=true` in `.env.local` and restart your development
+process. Remove the override and restart when finished. This opt-in only applies
+to development; automated test environments remain disabled.
+
+With `SELF_HOSTED=true`, enable Preview features and click the Sankey thumbs-up/down
+buttons to test the bundled API survey. `POSTHOG_FEEDBACK_ENABLED=false` still
+opts out. Standard pop-up surveys require `POSTHOG_KEY` / `POSTHOG_HOST` for their
+project; managed Sankey feedback also requires `POSTHOG_SANKEY_SURVEY_ID`.
+The override uses the configured live projects, so submitted responses are real.
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
@@ -64,10 +77,42 @@ These are the events **currently implemented for Sankey**. All include
| --- | --- | --- |
| `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` |
+| `new_sankey_match` / `new_sankey_mismatch` | Valid comparison after analytics is ready; once per graph load, including period changes | None |
| `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` |
+### Automatic graph comparison
+
+The browser compares the original dashboard graph and the validated preview graph
+before D3 mutates either input. It sorts nodes by stable identity and links by
+source/target identity, comparing amounts at the legacy chart's two-decimal
+precision and percentages at one decimal. Localized legacy IDs for synthetic
+Uncategorized/Other Investments categories map to the preview's stable IDs.
+Array order,
+labels, colors, and API-only metadata do not affect the result. An empty legacy
+zero-valued center is equivalent to an empty preview graph. Missing or invalid
+inputs produce no event. Zoomed and expanded views do not create new comparisons.
+
+Only `new_sankey_match` or `new_sankey_mismatch`, plus `preview_version`, is sent
+to PostHog. No graph, amount, category, user ID, or date range is included in the
+comparison payload. Existing managed SDK metadata and self-hosted privacy rules
+still apply. Intentional deficit/netting changes can produce mismatches;
+a match proves input equivalence, not visual correctness. The separate requests
+can also observe different data if transactions change between loads.
+
+Each successful graph load can emit one comparison event after the SDK accepts
+it. Reloading the dashboard, changing the period, or retrying the data request
+starts a new comparison. Scrolling, resizing, zooming, expanding, and repeated
+SDK-ready notifications do not duplicate that load's event. Missing or opted-out
+analytics do not mark it captured; a later SDK-ready notification can retry.
+
+There is no daily or lifetime user limit. Legacy `sankey_comparison_result`
+preferences are ignored, so an earlier mismatch does not suppress a later match.
+No date ranges or graph data are persisted for deduplication or sent to PostHog.
+These events count compared loads, not unique users. SDK acceptance does not
+guarantee ingestion. Historical events are not rewritten by this change.
+
### Counting exposure and engagement
Count `sankey_preview_displayed` with `surface=inline` and `state=content` for
diff --git a/docs/llm-guides/feedback-surveys.md b/docs/llm-guides/feedback-surveys.md
index 13843fc616..422c4e81d5 100644
--- a/docs/llm-guides/feedback-surveys.md
+++ b/docs/llm-guides/feedback-surveys.md
@@ -36,7 +36,8 @@ 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
+Self-hosted configuration also returns `{}` outside production (unless development explicitly opts in with
+`POSTHOG_DEVELOPMENT_ENABLED=true`) or when
`POSTHOG_FEEDBACK_ENABLED=false`. This switch is specific to the shared
self-hosted feedback connection; managed deployments retain their existing rules.
diff --git a/test/controllers/cash_flow_preview_test.rb b/test/controllers/cash_flow_preview_test.rb
index 31ad552301..1494024f2a 100644
--- a/test/controllers/cash_flow_preview_test.rb
+++ b/test/controllers/cash_flow_preview_test.rb
@@ -3,6 +3,7 @@ require "test_helper"
class CashFlowPreviewTest < ActionDispatch::IntegrationTest
setup do
sign_in @user = users(:family_admin)
+ Rails.configuration.x.posthog.stubs(:development_enabled).returns(false)
end
test "preview opt-in adds the web chart below identical legacy chart data" do
@@ -53,6 +54,36 @@ class CashFlowPreviewTest < ActionDispatch::IntegrationTest
end
end
+ test "self-hosted development renders bundled feedback only with testing override" do
+ @user.update!(preferences: @user.preferences.merge("preview_features_enabled" => true))
+ config = Rails.configuration.x.posthog
+ config.stubs(:api_key).returns(nil)
+ config.stubs(:feedback_enabled).returns(true)
+ stub_managed_survey(nil)
+ Rails.env.stubs(:development?).returns(true)
+ with_self_hosting do
+ get root_path
+ assert_select "#cashflow-preview[data-sankey-preview-feedback-key-value=''][data-sankey-preview-survey-id-value='']"
+ config.stubs(:development_enabled).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']"
+ assert_select "script", text: /window.posthog=e/
+ 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 "development loads configured popup surveys only with testing override" do
+ Rails.env.stubs(:development?).returns(true)
+ Rails.configuration.x.posthog.stubs(:api_key).returns("configured-test-project")
+ get root_path
+ assert_select "head script", text: /posthog.init\('configured-test-project'/, count: 0
+ Rails.configuration.x.posthog.stubs(:development_enabled).returns(true)
+ get root_path
+ assert_select "head script", text: /posthog.init\('configured-test-project'/
+ 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)
diff --git a/test/helpers/feedback_helper_test.rb b/test/helpers/feedback_helper_test.rb
index dbe083d9a5..d5970e4e51 100644
--- a/test/helpers/feedback_helper_test.rb
+++ b/test/helpers/feedback_helper_test.rb
@@ -11,6 +11,7 @@ class FeedbackHelperTest < ActionView::TestCase
@config.stubs(:feedback_surveys).returns(@surveys)
@config.stubs(:self_hosted_feedback_project).returns(@project)
@config.stubs(:feedback_enabled).returns(true)
+ @config.stubs(:development_enabled).returns(false)
Rails.env.stubs(:production?).returns(true)
end
@@ -45,7 +46,25 @@ class FeedbackHelperTest < ActionView::TestCase
end
end
- test "self-hosted feedback stays disabled outside production or after operator opt-out" do
+ test "self-hosted development requires explicit opt-in and respects feedback opt-out" do
+ stubs(:self_hosted?).returns(true)
+ Rails.env.stubs(:production?).returns(false)
+ Rails.env.stubs(:development?).returns(true)
+ assert_empty feedback_config(:sankey)
+ @config.stubs(:development_enabled).returns(true)
+ assert_equal @project.merge(survey_id: "shared-sankey"), feedback_config(:sankey)
+ @config.stubs(:feedback_enabled).returns(false)
+ assert_empty feedback_config(:sankey)
+ end
+
+ test "development override does not enable automated test environments" do
+ Rails.env.stubs(:production?).returns(false)
+ Rails.env.stubs(:development?).returns(false)
+ @config.stubs(:development_enabled).returns(true)
+ assert_not posthog_enabled?
+ end
+
+ test "self-hosted feedback stays disabled in tests or after operator opt-out" do
stubs(:self_hosted?).returns(true)
Rails.env.stubs(:production?).returns(false)
assert_empty feedback_config(:sankey)
diff --git a/test/javascript/utils/sankey_comparison_test.mjs b/test/javascript/utils/sankey_comparison_test.mjs
new file mode 100644
index 0000000000..30588588cb
--- /dev/null
+++ b/test/javascript/utils/sankey_comparison_test.mjs
@@ -0,0 +1,90 @@
+import assert from "node:assert/strict";
+import { test } from "node:test";
+import { compareSankeyData } from "../../../app/javascript/utils/sankey_comparison.mjs";
+
+const graph = () => ({
+ nodes: [
+ { id: "income_a", value: 30, percentage: 100 },
+ { id: "cash_flow_node", value: 30, percentage: 100 },
+ { id: "expense_b", value: 20, percentage: 66.7 },
+ { id: "surplus_node", value: 10, percentage: 33.3 },
+ ],
+ links: [
+ { source: 0, target: 1, value: 30, percentage: 100 },
+ { source: 1, target: 2, value: 20, percentage: 66.7 },
+ { source: 1, target: 3, value: 10, percentage: 33.3 },
+ ],
+});
+
+test("ignores ordering and display metadata without mutating either input", () => {
+ const legacy = graph();
+ const preview = {
+ nodes: [...legacy.nodes].reverse().map((node) => ({ ...node, kind: "expense", color: "different", name: "Localized" })),
+ links: [...legacy.links].reverse().map((link) => ({ ...link, source: 3 - link.source, target: 3 - link.target })),
+ };
+ const before = JSON.stringify([legacy, preview]);
+ assert.equal(compareSankeyData(legacy, preview), "match");
+ assert.equal(JSON.stringify([legacy, preview]), before);
+});
+
+test("detects changed amounts, percentages, identities, topology and duplicate links", () => {
+ for (const mutate of [
+ (data) => { data.nodes[0].value += 0.01; },
+ (data) => { data.links[0].value += 0.01; },
+ (data) => { data.links[0].percentage = 99; },
+ (data) => { data.nodes[0].percentage = 99; },
+ (data) => { data.nodes[0].id = "income_other"; },
+ (data) => { data.links[0].target = 2; },
+ (data) => { data.links.push({ ...data.links[0] }); },
+ (data) => { data.links.pop(); },
+ ]) {
+ const changed = graph();
+ mutate(changed);
+ assert.equal(compareSankeyData(graph(), changed), "mismatch");
+ }
+});
+
+test("compares empty charts and skips invalid or unavailable inputs", () => {
+ const empty = { nodes: [], links: [] };
+ assert.equal(compareSankeyData({ nodes: [{ id: "cash_flow_node", value: 0, percentage: 100 }], links: [] }, empty), "match");
+ assert.equal(compareSankeyData(empty, graph()), "mismatch");
+ assert.equal(compareSankeyData(null, graph()), null);
+ const invalid = graph();
+ invalid.links[0].source = 99;
+ assert.equal(compareSankeyData(invalid, graph()), null);
+ invalid.links[0].source = 0;
+ invalid.nodes[0].value = NaN;
+ assert.equal(compareSankeyData(invalid, graph()), null);
+});
+
+
+test("matches converted amounts at the original chart precision", () => {
+ for (const [original, precise] of [
+ [18330.03, 18330.0300864458], [18253.3, 18253.300864458],
+ [1635.93, 1635.9291627454757], [10.44, 10.44362297733607],
+ [1.01, 1.005], [10.08, 10.075], [0, 1e-8],
+ ]) {
+ const legacy = graph(), preview = graph();
+ legacy.nodes[0].value = legacy.links[0].value = original;
+ preview.nodes[0].value = preview.links[0].value = precise;
+ assert.equal(compareSankeyData(legacy, preview), "match");
+ }
+});
+
+test("normalizes synthetic category identities and their link endpoints across locales", () => {
+ for (const [key, name] of [["uncategorized", "Uncategorized"], ["uncategorized", "Sin categoría"], ["other_investments", "Other Investments"]]) {
+ const legacy = graph(), preview = graph();
+ legacy.nodes[2] = { ...legacy.nodes[2], id: `expense_${name}`, name };
+ preview.nodes[2] = { ...preview.nodes[2], id: `expense_${key}`, name, category_id: null };
+ assert.equal(compareSankeyData(legacy, preview), "match");
+ legacy.nodes[2].id = "expense_real-category-id";
+ assert.equal(compareSankeyData(legacy, preview), "mismatch");
+ }
+});
+
+test("preserves cent differences even when close to a rounding boundary", () => {
+ const legacy = graph(), preview = graph();
+ legacy.nodes[0].value = 10.44;
+ preview.nodes[0].value = 10.445;
+ assert.equal(compareSankeyData(legacy, preview), "mismatch");
+});
diff --git a/test/javascript/utils/sankey_preview_analytics_test.mjs b/test/javascript/utils/sankey_preview_analytics_test.mjs
index 7e99675893..c48643f869 100644
--- a/test/javascript/utils/sankey_preview_analytics_test.mjs
+++ b/test/javascript/utils/sankey_preview_analytics_test.mjs
@@ -89,3 +89,24 @@ test("self-hosted feedback disables automatic collection and strips incidental S
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);
});
+
+test("comparison events send only the outcome and preview version", async () => {
+ const { captureSankeyComparison } = await import("../../../app/javascript/utils/sankey_preview_analytics.mjs");
+ for (const result of ["match", "mismatch"]) {
+ const events = [];
+ const sdk = { __loaded: true, capture: (...args) => { events.push(args); return {}; } };
+ assert.equal(captureSankeyComparison(sdk, result), true);
+ assert.deepEqual(events, [[`new_sankey_${result}`, { preview_version: "cash_flow_v1" }]]);
+ const sanitized = sanitizeSelfHostedFeedback({ event: `new_sankey_${result}`, properties: { preview_version: "cash_flow_v1", nodes: ["private"], amount: 123, user_id: "private" } });
+ assert.deepEqual(sanitized.properties, { preview_version: "cash_flow_v1", $geoip_disable: true, $process_person_profile: false });
+ }
+});
+
+test("comparison waits for analytics and preserves invalid, opted-out and failed captures for retry", async () => {
+ const { captureSankeyComparison } = await import("../../../app/javascript/utils/sankey_preview_analytics.mjs");
+ for (const sdk of [undefined, { __loaded: false }, { __loaded: true, has_opted_out_capturing: () => true }, { __loaded: true, capture: () => undefined }, { __loaded: true, capture: () => { throw Error("blocked"); } }]) {
+ assert.equal(captureSankeyComparison(sdk, "match"), false);
+ }
+ const sdk = { __loaded: true, capture: () => assert.fail("must not capture") };
+ assert.equal(captureSankeyComparison(sdk, null), false);
+});
diff --git a/test/system/cash_flow_test.rb b/test/system/cash_flow_test.rb
index 729bee50e0..d669eacaa0 100644
--- a/test/system/cash_flow_test.rb
+++ b/test/system/cash_flow_test.rb
@@ -21,7 +21,7 @@ class CashFlowTest < ApplicationSystemTestCase
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"
+ click_button "Expand", enable_aria_label: true
end
within "#cashflow-preview-expanded-dialog" do
assert_selector "svg .sankey-link"
@@ -77,7 +77,7 @@ class CashFlowTest < ApplicationSystemTestCase
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 = find("#cashflow-preview [data-sankey-preview-target='expandButton']")
expand.send_keys(:enter)
within "#cashflow-preview-expanded-dialog[open]" do
find("g[role='button'][aria-label^='Sankey Shopping,']").send_keys(:enter)
@@ -89,7 +89,7 @@ class CashFlowTest < ApplicationSystemTestCase
end
end
assert_no_selector "#cashflow-preview-expanded-dialog[open]"
- assert_selector "#cashflow-preview button:focus", text: "Expand"
+ assert_selector "#cashflow-preview [data-sankey-preview-target='expandButton']:focus"
assert_equal "true", find("[data-section-key='cashflow_sankey']")["draggable"]
end
end
@@ -164,7 +164,7 @@ class CashFlowTest < ApplicationSystemTestCase
assert_event_count "sankey_preview_displayed", 1
within "#cashflow-preview" do
- click_button "Expand"
+ click_button "Expand", enable_aria_label: true
end
assert_selector "#cashflow-preview-expanded-dialog[open] svg .sankey-link"
assert_equal "false", find("[data-section-key='cashflow_sankey']")["draggable"]
@@ -230,7 +230,7 @@ class CashFlowTest < ApplicationSystemTestCase
find("#cashflow-preview").scroll_to(:center)
assert_event_count "sankey_preview_displayed", 1
within "#cashflow-preview" do
- find_button("Expand").send_keys(:enter)
+ find_button("Expand", enable_aria_label: true).send_keys(:enter)
end
assert_selector "#cashflow-preview-expanded-dialog[open]"
assert_equal "false", section["aria-grabbed"]
@@ -286,7 +286,7 @@ class CashFlowTest < ApplicationSystemTestCase
find("#cashflow-preview").scroll_to(:center)
assert_event_count "sankey_preview_displayed", 1
within "#cashflow-preview" do
- click_button "Expand"
+ click_button "Expand", enable_aria_label: true
end
assert_event_count "sankey_preview_displayed", 2
find("#cashflow-preview-expanded-dialog").find("button[data-action='DS--dialog#close']").click
@@ -308,6 +308,86 @@ class CashFlowTest < ApplicationSystemTestCase
end
end
+ test "captures once per graph load and compares each selected period independently" do
+ Rails.configuration.stubs(:app_mode).returns("managed".inquiry)
+ # A previous lifetime marker must no longer suppress comparisons.
+ @user.update!(preferences: @user.preferences.merge("sankey_comparison_result" => "mismatch"))
+ 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
+ # Expense-only input adds an explicit deficit in the new graph.
+ assert_event_count "new_sankey_mismatch", 1
+ page.execute_script("document.dispatchEvent(new Event('posthog:ready'))")
+ find("#cashflow-preview [data-sankey-preview-target='expandButton']").click
+ find("#cashflow-preview-expanded-dialog").find("button[data-action='DS--dialog#close']").click
+ assert_event_count "new_sankey_mismatch", 1
+ properties = page.evaluate_script("window.sankeyEvents.find(e => e.event === 'new_sankey_mismatch').properties")
+ assert_equal({ "preview_version" => "cash_flow_v1" }, properties)
+
+ # Retrying data within the same controller permits one new comparison.
+ page.execute_script(<<~JS)
+ const preview = document.querySelector('#cashflow-preview');
+ const loader = window.Stimulus.getControllerForElementAndIdentifier(preview.querySelector('[data-controller="cash-flow"]'), 'cash-flow');
+ loader.load();
+ JS
+ assert_event_count "new_sankey_mismatch", 2
+
+ visit root_path(start_date: "1900-01-01", end_date: "1900-01-02")
+ assert_selector "#cashflow-preview[data-sankey-comparison='match']"
+ install_posthog_fake
+ assert_event_count "new_sankey_match", 1
+ assert_event_count "new_sankey_mismatch", 0
+ page.execute_script("document.dispatchEvent(new Event('posthog:ready'))")
+ assert_event_count "new_sankey_match", 1
+ end
+
+ test "feedback buttons highlight the current comparison without analytics and reset on loading" do
+ sign_in @user
+ visit root_path(start_date: @month.iso8601, end_date: Date.current.iso8601)
+ assert_selector "#cashflow-preview[data-sankey-comparison='mismatch']"
+ positive = "#cashflow-preview button[data-sankey-preview-rating-param='positive']"
+ negative = "#cashflow-preview button[data-sankey-preview-rating-param='negative']"
+ background = ->(selector) { page.evaluate_script("getComputedStyle(document.querySelector(#{selector.to_json})).backgroundColor") }
+ neutral = background.call(positive)
+ assert_not_equal neutral, background.call(negative)
+ page.execute_script(<<~JS)
+ const preview = document.querySelector('#cashflow-preview');
+ const graph = JSON.parse(preview.querySelector('[data-preview-sankey-chart-data-value]').getAttribute('data-preview-sankey-chart-data-value'));
+ preview.setAttribute('data-sankey-preview-legacy-data-value', JSON.stringify(graph));
+ preview.dispatchEvent(new CustomEvent('cash-flow:state', { detail: { state: 'content', ready: true, graph } }));
+ JS
+ assert_selector "#cashflow-preview[data-sankey-comparison='match']"
+ assert_not_equal neutral, background.call(positive)
+ assert_equal neutral, background.call(negative)
+ page.execute_script(<<~JS)
+ document.querySelector('#cashflow-preview').dispatchEvent(new CustomEvent('cash-flow:state', { detail: { state: 'loading', ready: false } }));
+ JS
+ assert_selector "#cashflow-preview[data-sankey-comparison='']"
+ assert_equal neutral, background.call(positive)
+ assert_equal neutral, background.call(negative)
+ end
+
+ test "feedback refreshes stale cached survey definitions on each click" do
+ Rails.configuration.stubs(:app_mode).returns("managed".inquiry)
+ 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 getCurrentSurveys = window.posthog.getSurveys;
+ window.posthog.getSurveys = (callback, forceReload) => {
+ if (forceReload) getCurrentSurveys(callback);
+ else callback([]);
+ };
+ JS
+ within "#cashflow-preview" do
+ click_button "Looks right"
+ end
+ assert_selector "#cashflow-preview-feedback-dialog textarea"
+ assert_event_count "survey shown", 1
+ end
+
private
def activate_node(node, activation)
case activation