The personal finance app for everyone (by everyone)
Ruby
Add Sure version and enable GeoIP for PostHog events (#3628)
Juan José Matae30e741546c1
diff --git a/app/javascript/controllers/sankey_preview_controller.js b/app/javascript/controllers/sankey_preview_controller.jsindex 245a9470c0..b17e65e352 100644--- a/app/javascript/controllers/sankey_preview_controller.js+++ b/app/javascript/controllers/sankey_preview_controller.js@@ -21,6 +21,7 @@ export default class extends Controller {];static values = {surveyId: String,+ sureVersion: String,legacyData: Object,selfHosted: Boolean,feedbackKey: String,@@ -34,6 +35,7 @@ export default class extends Controller {this.feedbackKeyValue,this.feedbackHostValue,() => document.dispatchEvent(new Event("posthog:ready")),+ this.sureVersionValue,);}this.comparisonDone = false;diff --git a/app/javascript/utils/sankey_preview_analytics.mjs b/app/javascript/utils/sankey_preview_analytics.mjsindex 6af2365d5f..d83e2e4048 100644--- a/app/javascript/utils/sankey_preview_analytics.mjs+++ b/app/javascript/utils/sankey_preview_analytics.mjs@@ -92,7 +92,7 @@ export function sanitizeSelfHostedFeedback(event) {].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",+ "token", "distinct_id", "sure_version", "preview_version", "surface", "state", "rating", "$survey_id",]);event.properties = Object.fromEntries(Object.entries(event.properties || {}).filter(([key]) =>@@ -101,18 +101,22 @@ export function sanitizeSelfHostedFeedback(event) {);delete event.$set;delete event.$set_once;- event.properties.$geoip_disable = true;+ // Use the browser connection IP for PostHog location enrichment.+ event.properties.$geoip_disable = false;event.properties.$process_person_profile = false;return event;}-export function initializeSelfHostedFeedback(posthog, key, host, loaded) {+export function initializeSelfHostedFeedback(posthog, key, host, loaded, sureVersion) {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),+ loaded: (client) => {+ client.register({ sure_version: sureVersion });+ queueMicrotask(loaded);+ },}, "sankeyFeedback");} catch {// Blocked analytics must not prevent chart setup or navigation.diff --git a/app/views/pages/dashboard/_cashflow_preview.html.erb b/app/views/pages/dashboard/_cashflow_preview.html.erbindex 6971c5a16e..ce7bcef676 100644--- a/app/views/pages/dashboard/_cashflow_preview.html.erb+++ b/app/views/pages/dashboard/_cashflow_preview.html.erb@@ -5,6 +5,7 @@<% end %><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-sure-version-value="<%= Sure.version.to_s %>"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] %>"diff --git a/app/views/shared/_posthog.html.erb b/app/views/shared/_posthog.html.erbindex f219063aa3..93d056c2dd 100644--- a/app/views/shared/_posthog.html.erb+++ b/app/views/shared/_posthog.html.erb@@ -4,6 +4,9 @@api_host: '<%= posthog_host %>',defaults: '2025-11-30',person_profiles: 'always', // or 'identified_only'- loaded: function() { document.dispatchEvent(new Event('posthog:ready')); },+ loaded: function(client) {+ client.register({ sure_version: <%= raw json_escape(Sure.version.to_s.to_json) %> });+ document.dispatchEvent(new Event('posthog:ready'));+ },})</script>diff --git a/docs/hosting/preview-feedback.md b/docs/hosting/preview-feedback.mdindex d5ddc37d04..51f54ba98d 100644--- a/docs/hosting/preview-feedback.md+++ b/docs/hosting/preview-feedback.md@@ -71,7 +71,8 @@ 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`:+`preview_version: cash_flow_v1` and `sure_version` (the deployed release string+from `.sure-version`, including any prerelease suffix):| Event | Trigger | Additional properties || --- | --- | --- |@@ -94,8 +95,8 @@ labels, colors, and API-only metadata do not affect the result. An empty legacyzero-valued center is equivalent to an empty preview graph. Missing or invalidinputs 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+Only `new_sankey_match` or `new_sankey_mismatch`, plus `preview_version` and+`sure_version`, is sent to PostHog. No graph, amount, category, user ID, or date range is included in thecomparison payload. Existing managed SDK metadata and self-hosted privacy rulesstill apply. Intentional deficit/netting changes can produce mismatches;a match proves input equivalence, not visual correctness. The separate requests@@ -147,8 +148,9 @@ autocapture and session recording.Managed deployments retain their existing SDK metadata. The dedicated self-hostedclient disables automatic tracking, pageviews, session recording, and personprofiles; 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.+either client suppresses capture. GeoIP enrichment is enabled using the browser+connection's IP address, allowing PostHog to add approximate location properties+to these events without creating person profiles. The destination project must also allow GeoIP enrichment.Use `feedback_config(:feature_name)` and the per-feature survey registry for thenext preview. Follow [Adding feature feedback surveys](../llm-guides/feedback-surveys.md)diff --git a/test/controllers/cash_flow_preview_test.rb b/test/controllers/cash_flow_preview_test.rbindex 1494024f2a..678adbf290 100644--- a/test/controllers/cash_flow_preview_test.rb+++ b/test/controllers/cash_flow_preview_test.rb@@ -19,6 +19,7 @@ class CashFlowPreviewTest < ActionDispatch::IntegrationTestget root_pathassert_response :successassert_select "#cashflow-sankey-chart + #cashflow-preview", count: 1+ assert_select "#cashflow-preview[data-sankey-preview-sure-version-value=?]", Rails.root.join(".sure-version").read.stripassert_select "#cashflow-preview [data-controller='preview-sankey-chart']", count: 2assert_select "#cashflow-preview [data-cash-flow-url-value*='/dashboard/cash_flow?']", count: 1assert_equal legacy, css_select("[data-controller='sankey-chart']").map { |chart| chart["data-sankey-chart-data-value"] }@@ -82,6 +83,7 @@ class CashFlowPreviewTest < ActionDispatch::IntegrationTestRails.configuration.x.posthog.stubs(:development_enabled).returns(true)get root_pathassert_select "head script", text: /posthog.init\('configured-test-project'/+ assert_select "head script", text: /client.register\(\{ sure_version: #{Regexp.escape(Rails.root.join(".sure-version").read.strip.to_json)}/endtest "managed app and demo use the configured environment survey without the shared feedback client" dodiff --git a/test/javascript/utils/sankey_preview_analytics_test.mjs b/test/javascript/utils/sankey_preview_analytics_test.mjsindex c48643f869..b7ca17fd42 100644--- a/test/javascript/utils/sankey_preview_analytics_test.mjs+++ b/test/javascript/utils/sankey_preview_analytics_test.mjs@@ -55,19 +55,22 @@ test("routes managed environments to their existing project and self-hosting onltest("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 = {}; } };+ const properties = {};+ const client = { register(values) { Object.assign(properties, values); } };+ const sdk = { init(...args) { calls.push(args); args[1].loaded(client); this.sankeyFeedback = client; } };let readyClient;const ready = () => { readyClient = sdk.sankeyFeedback; };- initializeSelfHostedFeedback(sdk, "", "https://us.i.posthog.com", ready);+ initializeSelfHostedFeedback(sdk, "", "https://us.i.posthog.com", ready, "0.7.5-alpha.10");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);+ initializeSelfHostedFeedback(sdk, "public-feedback-token", "https://us.i.posthog.com", ready, "0.7.5-alpha.10");+ initializeSelfHostedFeedback(sdk, "public-feedback-token", "https://us.i.posthog.com", ready, "0.7.5-alpha.10");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.deepEqual(properties, { sure_version: "0.7.5-alpha.10" });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);});@@ -79,10 +82,10 @@ test("self-hosted feedback disables automatic collection and strips incidental Sassert.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",+ token: "public-project-token", distinct_id: "anonymous", sure_version: "0.7.5-alpha.10", 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.deepEqual(event.properties, { token: "public-project-token", distinct_id: "anonymous", sure_version: "0.7.5-alpha.10", preview_version: "cash_flow_v1", surface: "inline", state: "content", $geoip_disable: false, $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";@@ -98,7 +101,7 @@ test("comparison events send only the outcome and preview version", async () =>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 });+ assert.deepEqual(sanitized.properties, { preview_version: "cash_flow_v1", $geoip_disable: false, $process_person_profile: false });}});@@ -110,3 +113,26 @@ test("comparison waits for analytics and preserves invalid, opted-out and failedconst sdk = { __loaded: true, capture: () => assert.fail("must not capture") };assert.equal(captureSankeyComparison(sdk, null), false);});+++test("all allowed feedback events retain the registered Sure version and enable GeoIP", () => {+ let options;+ const registered = {};+ const client = {+ __loaded: true,+ register(properties) { Object.assign(registered, properties); },+ capture(event, properties) {+ return options.before_send({ event, properties: { ...registered, ...properties } });+ },+ };+ const sdk = { init(_key, config) { options = config; config.loaded(client); } };+ initializeSelfHostedFeedback(sdk, "public-token", "https://us.i.posthog.com", () => {}, "0.7.5-alpha.10");+ for (const name of ["sankey_preview_displayed", "sankey_preview_feedback_clicked", "new_sankey_match", "new_sankey_mismatch", "survey shown", "survey sent", "survey dismissed"]) {+ const event = client.capture(name, { $geoip_disable: true, $ip: "private", amount: 123 });+ assert.deepEqual(event.properties, {+ sure_version: "0.7.5-alpha.10",+ $geoip_disable: false,+ $process_person_profile: false,+ });+ }+});