Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby
26.7 KB
Raw Blame
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, "cashflow_preview_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)
    @child, @account = child, account
  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?'))")
    # A label hidden to avoid a collision can sit over another node; it must
    # not catch that node's clicks.
    assert page.evaluate_script(<<~JS)
      Array.from(document.querySelectorAll("#cashflow-preview svg text"))
        .filter(text => text.style.opacity === "0")
        .every(text => getComputedStyle(text).pointerEvents === "none")
    JS
    within "#cashflow-preview" do
      click_button "Expand", enable_aria_label: true
    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()")
    chart.find("g[role='button'][aria-label^='Sankey Shopping,']").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 "a category without subcategories stays in the category column" do
    rent = @user.family.categories.create!(name: "Sankey Rent", color: "#654321")
    create_transaction(account: @account, category: rent, amount: 80, date: @month)
    # Wide enough for the dashboard chart to keep its subcategory column.
    page.current_window.resize_to(1920, 1400)
    sign_in @user
    assert_selector "#cashflow-preview svg .sankey-link"
    assert_selector "#cashflow-sankey-chart svg .sankey-link"

    # By datum: the label rule can hide a bar's label at this width. The
    # first chart of each is the inline one, not the dialog's copy.
    columns = page.evaluate_script(<<~JS)
      ["#cashflow-preview [data-controller='preview-sankey-chart']", "#cashflow-sankey-chart [data-controller='sankey-chart']"].map((chart) => {
        const bars = Array.from(document.querySelector(chart).querySelectorAll("svg g > path:not(.sankey-link)"));
        const x = (name) => bars.find((bar) => bar.__data__?.name === name)?.__data__.x0;
        return [x("Sankey Rent"), x("Sankey Shopping"), x("Sankey Groceries")];
      })
    JS
    columns.each do |rent_x, category_x, subcategory_x|
      assert_equal category_x, rent_x
      assert_operator rent_x, :<, subcategory_x
    end
  end

  test "bars labels Enter and Space share zoom and transaction actions" do
    # With the assistant panel open the chart is ~500px wide, and Sankey
    # Shopping's label would cover Cash Flow's, so it yields; give it room.
    @user.update!(show_ai_sidebar: false)
    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 [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)
        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 [data-sankey-preview-target='expandButton']:focus"
      assert_selector "[data-section-key='cashflow_sankey'][draggable='true']"
    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 "both charts come back with their controls after a morph refresh" do
    sign_in @user
    assert_selector "#cashflow-preview svg .sankey-link"
    assert_selector "#cashflow-sankey-chart svg .sankey-link"
    within "#cashflow-preview" do
      click_button "Largest first"
    end
    assert_selector "#cashflow-preview button[data-sort-order='descending'][aria-pressed='true']"
    assert_selector "#cashflow-preview svg[data-sort-order='descending'] .sankey-link"
    # By datum rather than label: the label rule can hide a bar's label at
    # this width, and the legacy chart has no accessible node names.
    page.execute_script(<<~JS)
      Array.from(document.querySelectorAll("#cashflow-sankey-chart svg g > path"))
        .find((bar) => bar.__data__?.name === "Sankey Shopping")
        .dispatchEvent(new MouseEvent("click", { bubbles: true }));
    JS
    assert_selector "#cashflow-sankey-chart [data-sankey-chart-target='zoomOutButton']:not([hidden])"
    # The zoomed view keeps the category and its subcategory: one flow.
    assert_selector "#cashflow-sankey-chart svg .sankey-link", count: 1

    # The sync toast refreshes the page this way once a background sync
    # finishes. The morph keeps the chart elements and their controllers but
    # puts the server markup back around them: no drawing, the controls in
    # their default state, and the tooltips gone from the body. Both redraws
    # above have settled, so only the morph can replace the marked drawings.
    page.execute_script(<<~JS)
      window.sankeyMorphs = 0;
      document.addEventListener("turbo:morph", () => { window.sankeyMorphs += 1; });
      document.querySelectorAll("#cashflow-sankey-chart svg, #cashflow-preview svg")
        .forEach((svg) => svg.setAttribute("data-stale", ""));
      Turbo.visit(window.location.href, { action: "replace" });
    JS
    assert_selector "body" do
      page.evaluate_script("window.sankeyMorphs") == 1
    end
    assert_no_selector "#cashflow-sankey-chart svg[data-stale], #cashflow-preview svg[data-stale]"
    assert_selector "#cashflow-sankey-chart svg:not([data-stale]) .sankey-link"
    assert_selector "#cashflow-preview svg:not([data-stale]) .sankey-link"
    assert_selector "#cashflow-sankey-chart [data-sankey-chart-target='zoomOutButton']:not([hidden])"
    assert_selector "#cashflow-preview button[data-sort-order='descending'][aria-pressed='true']"

    find("#cashflow-sankey-chart svg text", text: "Sankey Groceries", match: :first).hover
    assert_selector ".chart-tooltip:not(.ph-no-capture)", text: "Sankey Groceries"

    # Tracking stopped when the page was cached for the visit and must be
    # live again: the graph fetched after the morph counts as a display.
    install_posthog_fake
    find("#cashflow-preview").scroll_to(:center)
    assert_event_count "sankey_preview_displayed", 1
  end

  test "the preview tooltip comes back after a broadcast refresh" do
    sign_in @user
    assert_selector "#cashflow-preview svg .sankey-link"

    # A family broadcast_refresh (e.g. at the end of a SimpleFIN sync) arrives
    # as a refresh stream: Turbo morphs the page without caching it first, so
    # turbo:before-cache never clears the chart, and the morph drops the
    # tooltip it appended to the body.
    page.execute_script(<<~JS)
      window.sankeyMorphs = 0;
      document.addEventListener("turbo:morph", () => { window.sankeyMorphs += 1; });
      document.querySelectorAll("#cashflow-preview svg").forEach((svg) => svg.setAttribute("data-stale", ""));
      Turbo.session.refresh(window.location.href);
    JS
    assert_selector "body" do
      page.evaluate_script("window.sankeyMorphs") == 1
    end
    assert_selector "#cashflow-preview svg:not([data-stale]) .sankey-link"

    find("#cashflow-preview g[aria-label^='Sankey Shopping,'] path", match: :first).hover
    assert_selector ".chart-tooltip.ph-no-capture", text: "Sankey Shopping"
  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", enable_aria_label: true
    end
    assert_selector "#cashflow-preview-expanded-dialog[open] svg .sankey-link"
    assert_selector "[data-section-key='cashflow_sankey'][draggable='false']"
    assert_event_count "sankey_preview_displayed", 2
    within "#cashflow-preview-expanded-dialog" do
      find("button[data-action='DS--dialog#close']").click
    end
    assert_selector "[data-section-key='cashflow_sankey'][draggable='true']"

    [ "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", enable_aria_label: true).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 g[aria-label^='Sankey Shopping,'] path", 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", 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
      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

  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"))
    add_refunded_subcategory
    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
    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
    add_refunded_subcategory
    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
      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

    # A subcategory refunded beyond its spending nests under its parent in the
    # new graph but links straight to Cash Flow in the original, so they differ.
    def add_refunded_subcategory
      create_transaction(account: @account, category: @child, amount: -80, date: @month)
    end
end