Open source, privacy-first web analytics. Lightweight, cookie-free Google Analytics alternative. Self-hosted or cloud.
TypeScript analyticsanalytics-dashboardclickhouseelixirgoogle-analyticsmarketingopen-source-analyticsphoenixplausible-analyticspostgresqlprivacyprivacy-friendlyself-hostedsimple-analyticsstatisticstailwindcssweb-analyticswebsite-analyticswebsite-statswebsite-tracking
Add revenue and revenue per visitor to funnel steps with a revenue goal (#6644)
Sanne de Vries9236f41a00bb
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 1ec7e111a4..f64f34497f 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -18,7 +18,6 @@ All notable changes to this project will be documented in this file.- Add "Last 24 Hours" to dashboard time range picker and Stats API v2- Always compare against the same time range in comparisons with "Today"- Added vertical indicator line to graph to make it easier to see what's hovered / selected-- Added comparison support to funnels### Removed@@ -44,7 +43,6 @@ All notable changes to this project will be documented in this file.- Redesigned onboarding pages (add site, installation)- Moved tracking options (outbound links, file downloads, form submissions) from the installation page to the general site settings, where they can be toggled without going through the installation flow- Replaced HCaptcha with Friendly Captcha-- Redesigned funnel report on dashboard to be more consistent with the rest of the UI. It now includes a `Strict`/`Sequential` label, and percentage drop-off between individual funnel steps is now visible by default.- Team names are now limited to 50 characters and cannot contain URLs with an explicit scheme (e.g. `https://`)### Fixeddiff --git a/assets/js/dashboard/extra/funnel/index.tsx b/assets/js/dashboard/extra/funnel/index.tsxindex 2320b37573..17c661afe7 100644--- a/assets/js/dashboard/extra/funnel/index.tsx+++ b/assets/js/dashboard/extra/funnel/index.tsx@@ -13,7 +13,11 @@ import {MetricValueTooltipContent} from '../../stats/breakdowns'import { ChangeArrow } from '../../stats/reports/change-arrow'-import { numberLongFormatter, rateFormatter } from '../../util/number-formatter'+import { formatMoneyShort } from '../../util/money'+import {+ numberShortFormatter,+ rateFormatter+} from '../../util/number-formatter'import { Tooltip } from '../../util/tooltip'import { useDashboardStateContext } from '../../dashboard-state-context'import { useSiteContext } from '../../site-context'@@ -134,11 +138,23 @@ function PeriodStats({</span><spanclassName={classNames(- 'text-xs font-medium truncate',+ 'flex items-baseline gap-1 text-xs font-medium',!muted && 'text-gray-500 dark:text-gray-400')}>- {numberLongFormatter(values.visitors)} visitors+ <span className="min-w-0 truncate">+ {numberShortFormatter(values.visitors)} visitors+ </span>+ {values.revenue && (+ <>+ <span aria-hidden="true" className="shrink-0">+ •+ </span>+ <span className="min-w-0 truncate">+ {formatMoneyShort(values.revenue)}+ </span>+ </>+ )}</span></div>)diff --git a/assets/js/dashboard/extra/funnel/metrics.test.ts b/assets/js/dashboard/extra/funnel/metrics.test.tsindex 158ca78e88..c18cc81230 100644--- a/assets/js/dashboard/extra/funnel/metrics.test.ts+++ b/assets/js/dashboard/extra/funnel/metrics.test.ts@@ -31,7 +31,19 @@ const funnel: FunnelResponse = {dropoff: 45,dropoff_percentage: '75',conversion_rate: '15',- conversion_rate_step: '25'+ conversion_rate_step: '25',+ revenue: {+ short: '$1.2K',+ long: '$1,200.00',+ value: 1200,+ currency: 'USD'+ },+ revenue_per_visitor: {+ short: '$80.0',+ long: '$80.00',+ value: 80,+ currency: 'USD'+ }}]}@@ -65,7 +77,19 @@ const comparison: NonNullable<FunnelResponse['comparison']> = {dropoff: 32,dropoff_percentage: '80',conversion_rate: '10',- conversion_rate_step: '20'+ conversion_rate_step: '20',+ revenue: {+ short: '$800.0',+ long: '$800.00',+ value: 800,+ currency: 'USD'+ },+ revenue_per_visitor: {+ short: '$100.0',+ long: '$100.00',+ value: 100,+ currency: 'USD'+ }}]}@@ -127,13 +151,53 @@ describe('stepMetrics()', () => {visitors: 80,conversionRate: '100',continued: { visitors: 80, rate: '40' },- droppedOff: { visitors: 120, rate: '60' }+ droppedOff: { visitors: 120, rate: '60' },+ revenue: null,+ revenuePerVisitor: null})expect(thirdStep.comparison).toEqual({visitors: 8,conversionRate: '10',continued: { visitors: 8, rate: '20' },- droppedOff: { visitors: 32, rate: '80' }+ droppedOff: { visitors: 32, rate: '80' },+ revenue: {+ short: '$800.0',+ long: '$800.00',+ value: 800,+ currency: 'USD'+ },+ revenuePerVisitor: {+ short: '$100.0',+ long: '$100.00',+ value: 100,+ currency: 'USD'+ }+ })+ })++ it('gives no revenue for the steps that are not revenue goals', () => {+ const [firstStep, secondStep] = stepMetrics(funnel)++ expect([firstStep, secondStep].map(({ revenue }) => revenue)).toEqual([+ null,+ null+ ])+ })++ it('keeps the revenue of a step whose goal is a revenue goal', () => {+ const [, , thirdStep] = stepMetrics(funnel)++ expect(thirdStep.revenue).toEqual({+ short: '$1.2K',+ long: '$1,200.00',+ value: 1200,+ currency: 'USD'+ })+ expect(thirdStep.revenuePerVisitor).toEqual({+ short: '$80.0',+ long: '$80.00',+ value: 80,+ currency: 'USD'})})diff --git a/assets/js/dashboard/extra/funnel/metrics.ts b/assets/js/dashboard/extra/funnel/metrics.tsindex dbf76c1cdf..edd5b261fe 100644--- a/assets/js/dashboard/extra/funnel/metrics.ts+++ b/assets/js/dashboard/extra/funnel/metrics.ts@@ -1,3 +1,5 @@+import { RevenueMetricValue } from '../../api'+type FunnelStep = {label: stringvisitors: number@@ -5,6 +7,8 @@ type FunnelStep = {dropoff_percentage: stringconversion_rate: stringconversion_rate_step: string+ revenue?: RevenueMetricValue | null+ revenue_per_visitor?: RevenueMetricValue | null}type FunnelPeriod = {@@ -34,6 +38,8 @@ export type StepValues = {conversionRate: stringcontinued: StepOutcomedroppedOff: StepOutcome+ revenue: RevenueMetricValue | null+ revenuePerVisitor: RevenueMetricValue | null}export type StepMetrics = StepValues & {@@ -49,6 +55,8 @@ function stepValues(return {visitors: step.visitors,conversionRate: step.conversion_rate,+ revenue: step.revenue ?? null,+ revenuePerVisitor: step.revenue_per_visitor ?? null,continued:index === 0? {diff --git a/assets/js/dashboard/extra/funnel/outcome-box.tsx b/assets/js/dashboard/extra/funnel/outcome-box.tsxindex 854f3899d7..311af9659c 100644--- a/assets/js/dashboard/extra/funnel/outcome-box.tsx+++ b/assets/js/dashboard/extra/funnel/outcome-box.tsx@@ -1,6 +1,7 @@import React, { ReactNode, useLayoutEffect, useRef, useState } from 'react'import classNames from 'classnames'+import { formatMoneyLong } from '../../util/money'import { numberLongFormatter, rateFormatter } from '../../util/number-formatter'import { StepOutcome, StepValues } from './metrics'@@ -40,6 +41,30 @@ function outcome(}}+type RevenueFigure = {+ kind: 'total' | 'perVisitor'+ text: string+}++function stepRevenue(values: StepValues): RevenueFigure[] {+ if (!values.revenue) {+ return []+ }++ const figures: RevenueFigure[] = [+ { kind: 'total', text: `${formatMoneyLong(values.revenue)} revenue` }+ ]++ if (values.revenuePerVisitor) {+ figures.push({+ kind: 'perVisitor',+ text: `${formatMoneyLong(values.revenuePerVisitor)} per visitor`+ })+ }++ return figures+}+function stepOutcomes(values: StepValues,entryStep: boolean,@@ -156,9 +181,11 @@ export function StepOutcomes({const [open, setOpen] = useState(false)const outcomes = stepOutcomes(values, entryStep, finalStep)- const label = outcomes- .map(({ detail, count }) => `${detail} ${count}`)- .join(', ')+ const revenueFigures = stepRevenue(values)+ const label = [+ ...outcomes.map(({ detail, count }) => `${detail} ${count}`),+ ...revenueFigures.map(({ text }) => text)+ ].join(', ')const accessibleName = previousPeriod ? `Previous period: ${label}` : label@@ -201,6 +228,22 @@ export function StepOutcomes({{outcomes.map((outcome) => (<OutcomeText key={outcome.kind} outcome={outcome} detailed={true} />))}+ {revenueFigures.length > 0 && (+ <span className="shrink-0 h-px my-1 bg-gray-900/10 dark:bg-white/15" />+ )}+ {revenueFigures.map(({ kind, text }) => (+ <span+ key={kind}+ className={classNames(+ 'font-medium',+ kind === 'perVisitor'+ ? 'text-gray-500 dark:text-gray-400'+ : 'text-gray-900 dark:text-gray-100'+ )}+ >+ {text}+ </span>+ ))}</div></button>)diff --git a/extra/lib/plausible/stats/funnel.ex b/extra/lib/plausible/stats/funnel.exindex 3b8925bc4a..ef006aa2bb 100644--- a/extra/lib/plausible/stats/funnel.ex+++ b/extra/lib/plausible/stats/funnel.ex@@ -15,6 +15,7 @@ defmodule Plausible.Stats.Funnel doalias Plausible.ClickhouseRepoalias Plausible.Stats.{Base, Comparisons, DateTimeRange, Query}+ alias Plausible.Stats.Goal.Revenue@spec funnel(Plausible.Site.t(), Plausible.Stats.Query.t(), Funnel.t() | pos_integer()) ::{:ok, map()} | {:error, :funnel_not_found}@@ -28,17 +29,19 @@ defmodule Plausible.Stats.Funnel doendend- def funnel(_site, query, %Funnel{} = funnel) do+ def funnel(site, query, %Funnel{} = funnel) do+ revenue_steps = revenue_steps(site, funnel)+comparison =if query.comparison_utc_time_range doquery|> Comparisons.get_comparison_query()- |> compute(funnel)+ |> compute(funnel, revenue_steps)end{:ok,query- |> compute(funnel)+ |> compute(funnel, revenue_steps)|> Map.merge(%{name: funnel.name,strict_order: funnel.strict_order,@@ -51,28 +54,37 @@ defmodule Plausible.Stats.Funnel do})}end- defp compute(query, funnel) do+ defp revenue_steps(site, funnel) do+ if Revenue.available?(site) do+ Enum.reject(funnel.steps, &is_nil(&1.goal.currency))+ else+ []+ end+ end++ defp compute(query, funnel, revenue_steps) dogoals = Enum.map(funnel.steps, & &1.goal)funnel_data =query|> Query.set(preloaded_goals: %{all: [], matching_toplevel_filters: goals})|> Base.base_event_query()- |> funnel_query(funnel)+ |> funnel_query(funnel, revenue_steps)# We pass the query struct to record query metadata for# the CH debug console.|> ClickhouseRepo.all(query: query)+ visitors_by_step = Map.new(funnel_data, &{&1.step, &1.visitors})+# Funnel definition steps are 1-indexed, if there's index 0 in the resulting query,# it signifies the number of visitors that haven't entered the funnel.- not_entering_visitors =- case funnel_data do- [{0, count} | _] -> count- _ -> 0- end+ not_entering_visitors = Map.get(visitors_by_step, 0, 0)++ all_visitors = funnel_data |> Enum.map(& &1.visitors) |> Enum.sum()- all_visitors = Enum.reduce(funnel_data, 0, fn {_, n}, acc -> acc + n end)- steps = backfill_steps(funnel_data, funnel)+ revenue_totals_by_step = revenue_totals(funnel_data, revenue_steps)++ steps = backfill_steps(visitors_by_step, revenue_totals_by_step, funnel)visitors_at_first_step = List.first(steps).visitors@@ -86,7 +98,7 @@ defmodule Plausible.Stats.Funnel do}end- defp funnel_query(query, funnel_definition) do+ defp funnel_query(query, funnel_definition, revenue_steps) doq_events =from(e in query,select: %{user_id: e.user_id, _sample_factor: fragment("any(_sample_factor)")},@@ -95,11 +107,64 @@ defmodule Plausible.Stats.Funnel doorder_by: [desc: fragment("step")])|> select_funnel(funnel_definition)+ |> select_user_revenue(revenue_steps)from(f in subquery(q_events),- select: {f.step, total()},+ select: %{step: f.step, visitors: total()},group_by: f.step)+ |> select_revenue_totals(revenue_steps)+ end++ defp select_user_revenue(db_query, []), do: db_query++ defp select_user_revenue(db_query, revenue_steps) do+ sums =+ Map.new(revenue_steps, fn step ->+ goal_condition = Plausible.Stats.Goals.goal_condition(step.goal)++ {revenue_key(step),+ dynamic([e], fragment("sumIf(?, ?)", e.revenue_reporting_amount, ^goal_condition))}+ end)++ from(q in db_query, select_merge: ^sums)+ end++ defp select_revenue_totals(db_query, []), do: db_query++ defp select_revenue_totals(db_query, revenue_steps) do+ totals =+ Map.new(revenue_steps, fn step ->+ key = revenue_key(step)++ {key,+ dynamic(+ [f],+ fragment("toDecimal64(sum(?) * any(_sample_factor), 3)", field(f, ^key))+ )}+ end)++ from(q in db_query, select_merge: ^totals)+ end++ defp revenue_key(%{step_order: step_order}), do: :"revenue_#{step_order}"++ # The per-user sum runs for every buyer, even one that a strict order scored+ # below the step that holds their purchase. Such a buyer did not reach the step,+ # so the filter leaves their money out.+ defp revenue_totals(funnel_data, revenue_steps) do+ Map.new(revenue_steps, fn step ->+ key = revenue_key(step)++ total =+ funnel_data+ |> Enum.filter(&(&1.step >= step.step_order))+ |> Enum.reduce(Decimal.new(0), fn row, acc ->+ Decimal.add(acc, Map.get(row, key) || 0)+ end)++ {step.step_order, total}+ end)enddefp select_funnel(db_query, funnel_definition) do@@ -139,15 +204,14 @@ defmodule Plausible.Stats.Funnel do)end- defp backfill_steps(funnel_result, funnel) do- # Directly from ClickHouse we only get {step_idx(), visitor_count()} tuples.+ defp backfill_steps(visitors_by_step, revenue_by_step, funnel) do+ # Directly from ClickHouse we only get visitor counts per step index,# but no totals including previous steps are aggregated.# Hence we need to perform the appropriate backfill# and also calculate dropoff and conversion rate for each step.# In case ClickHouse returns 0-index funnel result, we're going to ignore it# anyway, since we fold over steps as per definition, that are always# indexed starting from 1.- funnel_result = Enum.into(funnel_result, %{})max_step = Enum.max_by(funnel.steps, & &1.step_order).step_orderfunnel@@ -157,7 +221,7 @@ defmodule Plausible.Stats.Funnel do# with each subsequent step needing to accumulate sum of the previous one(s)visitors_at_step =step.step_order..max_step- |> Enum.map(&Map.get(funnel_result, &1, 0))+ |> Enum.map(&Map.get(visitors_by_step, &1, 0))|> Enum.sum()# accumulate current_visitors for the next iteration@@ -175,21 +239,42 @@ defmodule Plausible.Stats.Funnel doconversion_rate = percentage(current_visitors, total_visitors)conversion_rate_step = percentage(current_visitors, visitors_at_previous)- step = %{- dropoff: dropoff,- dropoff_percentage: dropoff_percentage,- conversion_rate: conversion_rate,- conversion_rate_step: conversion_rate_step,- visitors: visitors_at_step,- label: to_string(step.goal)- }+ computed_step =+ %{+ dropoff: dropoff,+ dropoff_percentage: dropoff_percentage,+ conversion_rate: conversion_rate,+ conversion_rate_step: conversion_rate_step,+ visitors: visitors_at_step,+ label: to_string(step.goal)+ }+ |> Map.merge(revenue_metrics(step, revenue_by_step, visitors_at_step))- {total_visitors, current_visitors, [step | acc]}+ {total_visitors, current_visitors, [computed_step | acc]}end)|> elem(2)|> Enum.reverse()end+ defp revenue_metrics(step, revenue_by_step, visitors_at_step) do+ case Map.fetch(revenue_by_step, step.step_order) do+ {:ok, revenue} ->+ currency = step.goal.currency++ %{+ revenue: Revenue.format_revenue_metric(revenue, currency),+ revenue_per_visitor:+ Revenue.format_revenue_metric(per_visitor(revenue, visitors_at_step), currency)+ }++ :error ->+ %{}+ end+ end++ defp per_visitor(_revenue, 0), do: Decimal.new(0)+ defp per_visitor(revenue, visitors), do: revenue |> Decimal.div(visitors) |> Decimal.round(3)+defp tz_date_range(utc_time_range, timezone) dorange = DateTimeRange.to_date_range(utc_time_range, timezone)[range.first, range.last]diff --git a/test/plausible_web/controllers/api/stats_controller/funnels_test.exs b/test/plausible_web/controllers/api/stats_controller/funnels_test.exsindex 7070dbdde1..604a10444e 100644--- a/test/plausible_web/controllers/api/stats_controller/funnels_test.exs+++ b/test/plausible_web/controllers/api/stats_controller/funnels_test.exs@@ -547,6 +547,285 @@ defmodule PlausibleWeb.Api.StatsController.FunnelsTest doendend+ describe "GET /api/stats/funnel - revenue" do+ setup [:create_user, :log_in, :create_site]++ test "reports revenue on the step whose goal is a revenue goal", %{+ conn: conn,+ site: site+ } do+ {:ok, funnel} = setup_checkout_funnel(site)++ populate_stats(site, [+ build(:pageview, pathname: "/checkout", user_id: @user_id),+ build(:pageview, pathname: "/checkout", user_id: @other_user_id),+ purchase(@user_id, "100"),+ purchase(@other_user_id, "300")+ ])++ assert [checkout_step, purchase_step] = funnel_steps(conn, site, funnel)++ refute Map.has_key?(checkout_step, "revenue")+ refute Map.has_key?(checkout_step, "revenue_per_visitor")++ assert %{+ "visitors" => 2,+ "revenue" => %{+ "short" => "$400.0",+ "long" => "$400.00",+ "value" => 400.0,+ "currency" => "USD"+ },+ "revenue_per_visitor" => %{+ "short" => "$200.0",+ "long" => "$200.00",+ "value" => 200.0,+ "currency" => "USD"+ }+ } = purchase_step+ end++ test "divides the revenue by visitors, not by orders", %{conn: conn, site: site} do+ {:ok, funnel} = setup_checkout_funnel(site)++ populate_stats(site, [+ build(:pageview, pathname: "/checkout", user_id: @user_id),+ purchase(@user_id, "100"),+ purchase(@user_id, "300")+ ])++ assert [_checkout_step, purchase_step] = funnel_steps(conn, site, funnel)++ assert %{+ "visitors" => 1,+ "revenue" => %{"long" => "$400.00"},+ "revenue_per_visitor" => %{"long" => "$400.00"}+ } = purchase_step+ end++ test "counts the revenue of a mid-funnel step for everyone who reached it", %{+ conn: conn,+ site: site+ } do+ {:ok, [checkout, thanks]} =+ setup_goals(site, [{"page_path", "/checkout"}, {"page_path", "/thanks"}])++ purchase = insert(:goal, site: site, event_name: "Purchase", currency: "USD")+ {:ok, funnel} = funnel_with_goals(site, [checkout, purchase, thanks])++ populate_stats(site, [+ build(:pageview,+ pathname: "/checkout",+ user_id: @user_id,+ timestamp: ~N[2021-01-01 12:00:00]+ ),+ purchase(@user_id, "100", timestamp: ~N[2021-01-01 12:01:00]),+ build(:pageview,+ pathname: "/thanks",+ user_id: @user_id,+ timestamp: ~N[2021-01-01 12:02:00]+ ),+ build(:pageview,+ pathname: "/checkout",+ user_id: @other_user_id,+ timestamp: ~N[2021-01-01 13:00:00]+ ),+ purchase(@other_user_id, "300", timestamp: ~N[2021-01-01 13:01:00])+ ])++ assert [_checkout_step, purchase_step, thanks_step] =+ funnel_steps(conn, site, funnel, "period=day&date=2021-01-01")++ assert %{+ "visitors" => 2,+ "revenue" => %{"long" => "$400.00"},+ "revenue_per_visitor" => %{"long" => "$200.00"}+ } = purchase_step++ refute Map.has_key?(thanks_step, "revenue")+ end++ test "reports revenue for the comparison period", %{conn: conn, site: site} do+ {:ok, funnel} = setup_checkout_funnel(site)++ populate_stats(site, [+ build(:pageview,+ pathname: "/checkout",+ user_id: @user_id,+ timestamp: ~N[2021-01-02 12:00:00]+ ),+ purchase(@user_id, "100", timestamp: ~N[2021-01-02 12:01:00]),+ build(:pageview,+ pathname: "/checkout",+ user_id: @other_user_id,+ timestamp: ~N[2021-01-01 12:00:00]+ ),+ purchase(@other_user_id, "300", timestamp: ~N[2021-01-01 12:01:00])+ ])++ resp =+ conn+ |> get(+ "/api/stats/#{site.domain}/funnels/#{funnel.id}/?period=day&date=2021-01-02&comparison=previous_period"+ )+ |> json_response(200)++ assert %{+ "steps" => [+ _checkout_step,+ %{"revenue" => %{"long" => "$100.00"}}+ ],+ "comparison" => %{+ "steps" => [+ _previous_checkout_step,+ %{"revenue" => %{"long" => "$300.00"}}+ ]+ }+ } = resp+ end++ test "keeps every step in its own goal's currency", %{conn: conn, site: site} do+ donation = insert(:goal, site: site, event_name: "Donation", currency: "EUR")+ purchase = insert(:goal, site: site, event_name: "Purchase", currency: "USD")+ {:ok, funnel} = funnel_with_goals(site, [donation, purchase])++ populate_stats(site, [+ build(:event,+ name: "Donation",+ user_id: @user_id,+ revenue_reporting_amount: Decimal.new("10"),+ revenue_reporting_currency: "EUR",+ timestamp: ~N[2021-01-01 12:00:00]+ ),+ build(:event,+ name: "Donation",+ user_id: @other_user_id,+ revenue_reporting_amount: Decimal.new("20"),+ revenue_reporting_currency: "EUR",+ timestamp: ~N[2021-01-01 12:00:00]+ ),+ purchase(@user_id, "50", timestamp: ~N[2021-01-01 12:01:00])+ ])++ assert [donation_step, purchase_step] =+ funnel_steps(conn, site, funnel, "period=day&date=2021-01-01")++ assert %{"revenue" => %{"long" => "€30.00", "currency" => "EUR"}} = donation_step+ assert %{"revenue" => %{"long" => "$50.00", "currency" => "USD"}} = purchase_step+ end++ test "reports no revenue for a funnel without a revenue goal", %{conn: conn, site: site} do+ {:ok, funnel} = setup_funnel(site, @build_funnel_with)++ populate_stats(site, [+ build(:pageview, pathname: "/blog/announcement", user_id: @user_id),+ build(:event, name: "Signup", user_id: @user_id)+ ])++ for step <- funnel_steps(conn, site, funnel) do+ refute Map.has_key?(step, "revenue")+ refute Map.has_key?(step, "revenue_per_visitor")+ end+ end++ test "reports no revenue when the site has no access to revenue goals", %{+ conn: conn,+ site: site,+ user: user+ } do+ {:ok, funnel} = setup_checkout_funnel(site)++ site.team+ |> Plausible.Teams.Team.end_trial()+ |> Plausible.Repo.update!()++ subscribe_to_enterprise_plan(user, features: [Plausible.Billing.Feature.Funnels])++ populate_stats(site, [+ build(:pageview, pathname: "/checkout", user_id: @user_id),+ purchase(@user_id, "100")+ ])++ assert [_checkout_step, purchase_step] = funnel_steps(conn, site, funnel)++ refute Map.has_key?(purchase_step, "revenue")+ refute Map.has_key?(purchase_step, "revenue_per_visitor")+ end++ test "reports zero revenue when the payment does not follow the order of a strict-order funnel",+ %{+ conn: conn,+ site: site+ } do+ {:ok, [checkout, signup]} =+ setup_goals(site, [{"page_path", "/checkout"}, {"event_name", "Signup"}])++ purchase = insert(:goal, site: site, event_name: "Purchase", currency: "USD")+ {:ok, funnel} = funnel_with_goals(site, [checkout, signup, purchase], strict_order?: true)++ populate_stats(site, [+ build(:pageview,+ pathname: "/checkout",+ user_id: @user_id,+ timestamp: ~N[2021-01-01 12:00:00]+ ),+ purchase(@user_id, "100", timestamp: ~N[2021-01-01 12:01:00]),+ build(:event,+ name: "Signup",+ user_id: @user_id,+ timestamp: ~N[2021-01-01 12:02:00]+ )+ ])++ assert [_checkout_step, _signup_step, purchase_step] =+ funnel_steps(conn, site, funnel, "period=day&date=2021-01-01")++ assert %{+ "visitors" => 0,+ "revenue" => %{"long" => "$0.00"},+ "revenue_per_visitor" => %{"long" => "$0.00"}+ } = purchase_step+ end+ end++ defp setup_checkout_funnel(site) do+ {:ok, [checkout]} = setup_goals(site, [{"page_path", "/checkout"}])+ purchase = insert(:goal, site: site, event_name: "Purchase", currency: "USD")++ funnel_with_goals(site, [checkout, purchase])+ end++ defp funnel_with_goals(site, goals, opts \\ []) do+ Plausible.Funnels.create(+ site,+ "Test funnel",+ Enum.map(goals, &%{"goal_id" => &1.id}),+ opts+ )+ end++ defp purchase(user_id, amount, attrs \\ []) do+ build(+ :event,+ Keyword.merge(+ [+ name: "Purchase",+ user_id: user_id,+ revenue_reporting_amount: Decimal.new(amount),+ revenue_reporting_currency: "USD"+ ],+ attrs+ )+ )+ end++ defp funnel_steps(conn, site, funnel, params \\ "period=day") do+ conn+ |> get("/api/stats/#{site.domain}/funnels/#{funnel.id}/?#{params}")+ |> json_response(200)+ |> Map.fetch!("steps")+ end+defp setup_goals(site, goals) when is_list(goals) dogoals =Enum.map(goals, fn {type, value} ->@@ -560,12 +839,7 @@ defmodule PlausibleWeb.Api.StatsController.FunnelsTest dodefp setup_funnel(site, goal_names, opts \\ []) do{:ok, goals} = setup_goals(site, goal_names)- Plausible.Funnels.create(- site,- "Test funnel",- Enum.map(goals, &%{"goal_id" => &1.id}),- opts- )+ funnel_with_goals(site, goals, opts)endendend