From b9ec38038cec090cb2b16eb4aa062430e8b42b41 Mon Sep 17 00:00:00 2001 From: hq1 Date: Mon, 20 Nov 2023 12:52:20 +0100 Subject: [PATCH] Add small build option (#3536) * Update applications * Clone community config * Move modules to experimental dir * Update runtime config * Apply first set of compile-time conditionals * Move funnel schemas to experimental * Make funnel schema-less build compile * Use experimental/lib for elixir code * Move JS funnels to experimental * Clean up conditional rendering * Tidy up the pipeline * Make two builds pass tests without warnings * Reuse existing dotenvs * Do a bunch of renames * Clean up naming * Run secondary CI * Update router * Remove RewriteFunnelDupes migration Tests were disabled already and it was a one-off shot * Fixup quota mixins * Add moduledoc * Change MIX_ENV for seconary test run * Skip crm on small * !fixup * Exclude flags pipeline * Update lib/plausible_web/controllers/stats_controller.ex Co-authored-by: Adrian Gruntkowski --------- Co-authored-by: Adrian Gruntkowski --- .github/workflows/elixir.yml | 2 + .../behaviours => extra}/funnel-tooltip.js | 0 .../{stats/behaviours => extra}/funnel.js | 10 +- assets/js/dashboard/stats/behaviours/index.js | 32 +- config/config.exs | 2 +- config/runtime.exs | 56 +- config/small.exs | 11 + config/small_test.exs | 3 + {lib => extra/lib}/plausible/funnel.ex | 0 {lib => extra/lib}/plausible/funnel/step.ex | 0 {lib => extra/lib}/plausible/funnels.ex | 0 {lib => extra/lib}/plausible/stats/funnel.ex | 0 .../plausible_web/live/funnel_settings.ex | 0 .../live/funnel_settings/form.ex | 0 .../live/funnel_settings/list.ex | 0 lib/plausible.ex | 47 +- lib/plausible/billing/quota.ex | 42 +- .../data_migration/rewrite_funnel_dupes.ex | 191 ----- lib/plausible/funnel/const.ex | 26 + lib/plausible/goal/schema.ex | 9 +- lib/plausible/goals.ex | 30 +- lib/plausible/plugins/api/goals.ex | 26 +- .../site/memberships/accept_invitation.ex | 4 +- lib/plausible/stats.ex | 11 +- .../controllers/api/stats_controller.ex | 89 +-- .../controllers/stats_controller.ex | 18 +- lib/plausible_web/endpoint.ex | 15 +- lib/plausible_web/live/goal_settings.ex | 2 - lib/plausible_web/live/goal_settings/list.ex | 2 - lib/plausible_web/live/props_settings/list.ex | 2 - .../api/schemas/goal/create_request.ex | 4 +- lib/plausible_web/router.ex | 43 +- .../templates/site/settings_goals.html.heex | 2 +- lib/plausible_web/views/layout_view.ex | 6 +- lib/plausible_web/views/site_view.ex | 2 +- mix.exs | 33 +- test/plausible/billing/quota_test.exs | 81 +- .../rewrite_funnel_dupes_test.exs | 128 ---- test/plausible/funnels_test.exs | 694 +++++++++--------- test/plausible/goals_test.exs | 149 ++-- .../memberships/accept_invitation_test.exs | 127 ++-- .../api/stats_controller/funnels_test.exs | 598 +++++++-------- .../live/funnel_settings/form_test.exs | 2 + .../live/funnel_settings_test.exs | 535 +++++++------- .../plausible_web/live/goal_settings_test.exs | 1 + test/support/html.ex | 2 + test/test_helper.exs | 7 +- 47 files changed, 1493 insertions(+), 1551 deletions(-) rename assets/js/dashboard/{stats/behaviours => extra}/funnel-tooltip.js (100%) rename assets/js/dashboard/{stats/behaviours => extra}/funnel.js (97%) create mode 100644 config/small.exs create mode 100644 config/small_test.exs rename {lib => extra/lib}/plausible/funnel.ex (100%) rename {lib => extra/lib}/plausible/funnel/step.ex (100%) rename {lib => extra/lib}/plausible/funnels.ex (100%) rename {lib => extra/lib}/plausible/stats/funnel.ex (100%) rename {lib => extra/lib}/plausible_web/live/funnel_settings.ex (100%) rename {lib => extra/lib}/plausible_web/live/funnel_settings/form.ex (100%) rename {lib => extra/lib}/plausible_web/live/funnel_settings/list.ex (100%) delete mode 100644 lib/plausible/data_migration/rewrite_funnel_dupes.ex create mode 100644 lib/plausible/funnel/const.ex delete mode 100644 test/plausible/data_migration/rewrite_funnel_dupes_test.exs diff --git a/.github/workflows/elixir.yml b/.github/workflows/elixir.yml index 874846d69..80675c63b 100644 --- a/.github/workflows/elixir.yml +++ b/.github/workflows/elixir.yml @@ -76,6 +76,8 @@ jobs: run: mix credo diff --from-git-merge-base origin/master - name: Run tests run: mix test --include slow --max-failures 1 --warnings-as-errors + - name: Run tests (small build) + run: MIX_ENV=small_test mix test --include slow --max-failures 1 --warnings-as-errors - name: Check Dialyzer run: mix dialyzer env: diff --git a/assets/js/dashboard/stats/behaviours/funnel-tooltip.js b/assets/js/dashboard/extra/funnel-tooltip.js similarity index 100% rename from assets/js/dashboard/stats/behaviours/funnel-tooltip.js rename to assets/js/dashboard/extra/funnel-tooltip.js diff --git a/assets/js/dashboard/stats/behaviours/funnel.js b/assets/js/dashboard/extra/funnel.js similarity index 97% rename from assets/js/dashboard/stats/behaviours/funnel.js rename to assets/js/dashboard/extra/funnel.js index e044422f3..2f598cdaf 100644 --- a/assets/js/dashboard/stats/behaviours/funnel.js +++ b/assets/js/dashboard/extra/funnel.js @@ -3,13 +3,13 @@ import FlipMove from 'react-flip-move'; import Chart from 'chart.js/auto' import FunnelTooltip from './funnel-tooltip.js' import ChartDataLabels from 'chartjs-plugin-datalabels' -import numberFormatter from '../../util/number-formatter' -import Bar from '../bar' +import numberFormatter from '../util/number-formatter' +import Bar from '../stats/bar' -import RocketIcon from '../modals/rocket-icon' +import RocketIcon from '../stats/modals/rocket-icon' -import * as api from '../../api' -import LazyLoader from '../../components/lazy-loader' +import * as api from '../api' +import LazyLoader from '../components/lazy-loader' export default function Funnel(props) { diff --git a/assets/js/dashboard/stats/behaviours/index.js b/assets/js/dashboard/stats/behaviours/index.js index d50a6129d..9f574c6ae 100644 --- a/assets/js/dashboard/stats/behaviours/index.js +++ b/assets/js/dashboard/stats/behaviours/index.js @@ -6,10 +6,21 @@ import * as storage from '../../util/storage' import GoalConversions, { specialTitleWhenGoalFilter } from './goal-conversions' import Properties from './props' -import Funnel from './funnel' import { FeatureSetupNotice } from '../../components/notice' import { SPECIAL_GOALS } from './goal-conversions' +/*global BUILD_EXTRA*/ +/*global require*/ +function maybeRequire() { + if (BUILD_EXTRA) { + return require('../../extra/funnel') + } else { + return { default: null } + } +} + +const Funnel = maybeRequire().default + const ACTIVE_CLASS = 'inline-block h-5 text-indigo-700 dark:text-indigo-500 font-bold active-prop-heading truncate text-left' const DEFAULT_CLASS = 'hover:text-indigo-600 cursor-pointer truncate text-left' @@ -139,7 +150,7 @@ export default function Behaviours(props) {
{isEnabled(CONVERSIONS) && tabSwitcher(CONVERSIONS, 'Goals')} {isEnabled(PROPS) && tabSwitcher(PROPS, 'Properties')} - {isEnabled(FUNNELS) && (hasFunnels() ? tabFunnelPicker() : tabSwitcher(FUNNELS, 'Funnels'))} + {isEnabled(FUNNELS) && Funnel && (hasFunnels() ? tabFunnelPicker() : tabSwitcher(FUNNELS, 'Funnels'))}
) } @@ -165,8 +176,13 @@ export default function Behaviours(props) { } function renderFunnels() { - if (selectedFunnel) { return } - else if (adminAccess) { + if (Funnel === null) { + return featureUnavailable() + } + else if (Funnel && selectedFunnel) { + return + } + else if (Funnel && adminAccess) { return ( + This feature is unavailable + + ) + } + function onHideAction(mode) { return () => { disableMode(mode) } } diff --git a/config/config.exs b/config/config.exs index 1bd85b9e4..65c37c127 100644 --- a/config/config.exs +++ b/config/config.exs @@ -20,7 +20,7 @@ config :esbuild, version: "0.17.11", default: [ args: - ~w(js/app.js js/dashboard.js js/embed.host.js js/embed.content.js --bundle --target=es2017 --loader:.js=jsx --outdir=../priv/static/js), + ~w(js/app.js js/dashboard.js js/embed.host.js js/embed.content.js --bundle --target=es2017 --loader:.js=jsx --outdir=../priv/static/js --define:BUILD_EXTRA=true), cd: Path.expand("../assets", __DIR__), env: %{"NODE_PATH" => Path.expand("../deps", __DIR__)} ] diff --git a/config/runtime.exs b/config/runtime.exs index 424496ea9..3c10b4237 100644 --- a/config/runtime.exs +++ b/config/runtime.exs @@ -6,6 +6,14 @@ if config_env() in [:dev, :test] do Envy.load(["config/.env.#{config_env()}"]) end +if config_env() == :small do + Envy.load(["config/.env.dev"]) +end + +if config_env() == :small_test do + Envy.load(["config/.env.test"]) +end + config_dir = System.get_env("CONFIG_DIR", "/run/secrets") log_format = @@ -549,32 +557,34 @@ config :ua_inspector, config :hammer, backend: {Hammer.Backend.ETS, [expiry_ms: 60_000 * 60 * 4, cleanup_interval_ms: 60_000 * 10]} -config :kaffy, - otp_app: :plausible, - ecto_repo: Plausible.Repo, - router: PlausibleWeb.Router, - admin_title: "Plausible Admin", - resources: [ - auth: [ - resources: [ - user: [schema: Plausible.Auth.User, admin: Plausible.Auth.UserAdmin], - api_key: [schema: Plausible.Auth.ApiKey, admin: Plausible.Auth.ApiKeyAdmin] - ] - ], - sites: [ - resources: [ - site: [schema: Plausible.Site, admin: Plausible.SiteAdmin] - ] - ], - billing: [ - resources: [ - enterprise_plan: [ - schema: Plausible.Billing.EnterprisePlan, - admin: Plausible.Billing.EnterprisePlanAdmin +if config_env() in [:dev, :staging, :prod] do + config :kaffy, + otp_app: :plausible, + ecto_repo: Plausible.Repo, + router: PlausibleWeb.Router, + admin_title: "Plausible Admin", + resources: [ + auth: [ + resources: [ + user: [schema: Plausible.Auth.User, admin: Plausible.Auth.UserAdmin], + api_key: [schema: Plausible.Auth.ApiKey, admin: Plausible.Auth.ApiKeyAdmin] + ] + ], + sites: [ + resources: [ + site: [schema: Plausible.Site, admin: Plausible.SiteAdmin] + ] + ], + billing: [ + resources: [ + enterprise_plan: [ + schema: Plausible.Billing.EnterprisePlan, + admin: Plausible.Billing.EnterprisePlanAdmin + ] ] ] ] - ] +end geo_opts = cond do diff --git a/config/small.exs b/config/small.exs new file mode 100644 index 000000000..eaa8a34e6 --- /dev/null +++ b/config/small.exs @@ -0,0 +1,11 @@ +import Config + +import_config "dev.exs" + +config :esbuild, + default: [ + args: + ~w(js/app.js js/dashboard.js js/embed.host.js js/embed.content.js --bundle --target=es2017 --loader:.js=jsx --outdir=../priv/static/js --define:BUILD_EXTRA=false), + cd: Path.expand("../assets", __DIR__), + env: %{"NODE_PATH" => Path.expand("../deps", __DIR__)} + ] diff --git a/config/small_test.exs b/config/small_test.exs new file mode 100644 index 000000000..a7cc8c8bc --- /dev/null +++ b/config/small_test.exs @@ -0,0 +1,3 @@ +import Config + +import_config "test.exs" diff --git a/lib/plausible/funnel.ex b/extra/lib/plausible/funnel.ex similarity index 100% rename from lib/plausible/funnel.ex rename to extra/lib/plausible/funnel.ex diff --git a/lib/plausible/funnel/step.ex b/extra/lib/plausible/funnel/step.ex similarity index 100% rename from lib/plausible/funnel/step.ex rename to extra/lib/plausible/funnel/step.ex diff --git a/lib/plausible/funnels.ex b/extra/lib/plausible/funnels.ex similarity index 100% rename from lib/plausible/funnels.ex rename to extra/lib/plausible/funnels.ex diff --git a/lib/plausible/stats/funnel.ex b/extra/lib/plausible/stats/funnel.ex similarity index 100% rename from lib/plausible/stats/funnel.ex rename to extra/lib/plausible/stats/funnel.ex diff --git a/lib/plausible_web/live/funnel_settings.ex b/extra/lib/plausible_web/live/funnel_settings.ex similarity index 100% rename from lib/plausible_web/live/funnel_settings.ex rename to extra/lib/plausible_web/live/funnel_settings.ex diff --git a/lib/plausible_web/live/funnel_settings/form.ex b/extra/lib/plausible_web/live/funnel_settings/form.ex similarity index 100% rename from lib/plausible_web/live/funnel_settings/form.ex rename to extra/lib/plausible_web/live/funnel_settings/form.ex diff --git a/lib/plausible_web/live/funnel_settings/list.ex b/extra/lib/plausible_web/live/funnel_settings/list.ex similarity index 100% rename from lib/plausible_web/live/funnel_settings/list.ex rename to extra/lib/plausible_web/live/funnel_settings/list.ex diff --git a/lib/plausible.ex b/lib/plausible.ex index ebdaaaaed..facf81cf2 100644 --- a/lib/plausible.ex +++ b/lib/plausible.ex @@ -1,9 +1,46 @@ defmodule Plausible do @moduledoc """ - Plausible keeps the contexts that define your domain - and business logic. - - Contexts are also responsible for managing your data, regardless - if it comes from the database, an external API or others. + Build-related macros """ + + @small_builds [:small, :small_test] + + defmacro __using__(_) do + quote do + require Plausible + import Plausible + end + end + + defmacro on_small_build(do: block) do + if Mix.env() in @small_builds do + quote do + unquote(block) + end + end + end + + defmacro on_full_build(do: block) do + if Mix.env() not in @small_builds do + quote do + unquote(block) + end + end + end + + defmacro full_build?() do + full_build? = Mix.env() not in @small_builds + + quote do + unquote(full_build?) + end + end + + defmacro small_build?() do + small_build? = Mix.env() in @small_builds + + quote do + unquote(small_build?) + end + end end diff --git a/lib/plausible/billing/quota.ex b/lib/plausible/billing/quota.ex index 31b17ee43..4b360ef7b 100644 --- a/lib/plausible/billing/quota.ex +++ b/lib/plausible/billing/quota.ex @@ -3,6 +3,7 @@ defmodule Plausible.Billing.Quota do This module provides functions to work with plans usage and limits. """ + use Plausible import Ecto.Query alias Plausible.Auth.User alias Plausible.Site @@ -193,11 +194,6 @@ defmodule Plausible.Billing.Quota do on: s.id == os.site_id, where: fragment("cardinality(?) > 0", s.allowed_event_props) - funnels_usage_query = - from f in Plausible.Funnel, - inner_join: os in subquery(owned_sites_query(user)), - on: f.site_id == os.site_id - revenue_goals_usage = from g in Plausible.Goal, inner_join: os in subquery(owned_sites_query(user)), @@ -206,12 +202,26 @@ defmodule Plausible.Billing.Quota do stats_api_usage = from a in Plausible.Auth.ApiKey, where: a.user_id == ^user.id - queries = [ - {Props, props_usage_query}, - {Funnels, funnels_usage_query}, - {RevenueGoals, revenue_goals_usage}, - {StatsAPI, stats_api_usage} - ] + queries = + if Plausible.Release.selfhost?() do + [ + {Props, props_usage_query}, + {RevenueGoals, revenue_goals_usage}, + {StatsAPI, stats_api_usage} + ] + else + funnels_usage_query = + from f in "funnels", + inner_join: os in subquery(owned_sites_query(user)), + on: f.site_id == os.site_id + + [ + {Props, props_usage_query}, + {Funnels, funnels_usage_query}, + {RevenueGoals, revenue_goals_usage}, + {StatsAPI, stats_api_usage} + ] + end Enum.reduce(queries, [], fn {feature, query}, acc -> if Plausible.Repo.exists?(query), do: acc ++ [feature], else: acc @@ -221,8 +231,14 @@ defmodule Plausible.Billing.Quota do def features_usage(%Site{} = site) do props_exist = is_list(site.allowed_event_props) && site.allowed_event_props != [] - funnels_exist = - Plausible.Repo.exists?(from f in Plausible.Funnel, where: f.site_id == ^site.id) + on_full_build do + funnels_exist = + Plausible.Repo.exists?(from f in Plausible.Funnel, where: f.site_id == ^site.id) + end + + on_small_build do + funnels_exist = false + end revenue_goals_exist = Plausible.Repo.exists?( diff --git a/lib/plausible/data_migration/rewrite_funnel_dupes.ex b/lib/plausible/data_migration/rewrite_funnel_dupes.ex deleted file mode 100644 index 52db56d34..000000000 --- a/lib/plausible/data_migration/rewrite_funnel_dupes.ex +++ /dev/null @@ -1,191 +0,0 @@ -defmodule Plausible.DataMigration.RewriteFunnelDupes do - @moduledoc """ - A data fix migration that seeks funnels having steps - whose goals are equally named. - It then tries to rewrite the duplicate goals using the - oldest goal available. In extreme cases, e.g. when multiple - duplicates are found for a single funnel, it will either - reduce or completely remove the funnel. - This enables us to run a migration later on that will - delete duplicate goals and enforce goal uniqueness at the - database level via a CHECK constraint. - - To run, just call the `run` function. - """ - use Plausible.DataMigration, dir: "FunnelDupeGoals", repo: Plausible.Repo - import Ecto.Query - - def run(_ \\ []) do - {:ok, %{rows: rows}} = run_sql("list-funnels-with-dupe-goal-ids") - data = Enum.map(rows, &to_map/1) - - by_site_id = Enum.group_by(data, & &1.site_id) - - Enum.into(by_site_id, %{}, fn {site_id, data} -> - site_meta = - %{} - |> Map.put(:domain, List.first(data).domain) - |> Map.put(:site_id, site_id) - |> Map.put( - :changes, - Enum.map( - data, - fn d -> - %{ - site_id: site_id, - og_goal_id: d.goal_id, - goal_name: d.goal_name, - funnel_name: d.funnel_name, - funnel_id: d.funnel_id, - funnel_step_id: d.funnel_step_id, - to: Enum.min(d.dupe_goal_ids), - og_steps_count: length(d.all_goal_ids) - } - end - ) - |> Enum.group_by(& &1.funnel_id) - ) - - {site_id, site_meta} - end) - |> translate_to_db_ops() - |> execute() - end - - def execute(data) do - Plausible.Repo.transaction(fn -> - for {site_id, meta} <- data do - IO.puts("\n\nProcessing site ID: #{site_id} (#{meta.domain}):") - - for {funnel_id, changes} <- meta.changes do - IO.puts( - "\nProcessing changes for funnel ID: #{funnel_id} - '#{Enum.at(changes, 0).funnel_name}'" - ) - - Enum.each(changes, fn change -> - apply_change(funnel_id, change) - end) - end - - IO.puts("\nFinished processing site ID: #{site_id} (#{meta.domain}).") - end - end) - end - - def apply_change(funnel_id, %{update_type: :delete_whole_funnel} = change) do - IO.puts( - "Deleting whole funnel '#{change.funnel_name}', there is no way to make it functional without duplicates" - ) - - Plausible.Repo.delete_all( - from(f in Plausible.Funnel, - where: f.site_id == ^change.site_id, - where: f.id == ^funnel_id - ) - ) - end - - def apply_change(funnel_id, %{update_type: :delete_step} = change) do - IO.puts( - "Deleting step ID:#{change.funnel_step_id} '#{change.goal_name}' - otherwise there will be duplicates in the funnel." - ) - - step = - Plausible.Repo.get_by!(Plausible.Funnel.Step, - funnel_id: funnel_id, - id: change.funnel_step_id - ) - - {:ok, _} = Plausible.Repo.delete(step) - end - - def apply_change( - _funnel_id, - %{update_type: :update_step, og_goal_id: goal_id, to: goal_id} = change - ) do - IO.puts( - "Doing nothing for step '#{change.goal_name}' - the duplicate goal exists, but the update is no-op" - ) - - :ok - end - - def apply_change(funnel_id, %{update_type: :update_step} = change) do - IO.puts( - "Updating step '#{change.goal_name}' from goal_id:#{change.og_goal_id} to goal_id:#{change.to}" - ) - - step = - Plausible.Repo.get_by!(Plausible.Funnel.Step, - funnel_id: funnel_id, - id: change.funnel_step_id - ) - - change = Ecto.Changeset.change(step, goal_id: change.to) - {:ok, _} = Plausible.Repo.update(change) - end - - def translate_to_db_ops(data) do - for {site, meta} <- data do - {site, to_db_ops(meta)} - end - end - - def to_db_ops(meta) do - new_changes = - for {funnel_id, changes} <- meta.changes do - safe_step_updates = changes |> Enum.uniq_by(& &1.to) - - steps_to_delete = changes -- safe_step_updates - - safe_step_updates = - safe_step_updates - |> Enum.map(&Map.put(&1, :update_type, :update_step)) - - changes = - Enum.map(steps_to_delete, &Map.put(&1, :update_type, :delete_step)) ++ safe_step_updates - - og_steps_count = Enum.at(changes, 0).og_steps_count - - steps_after_changes = og_steps_count - Enum.count(steps_to_delete) - - if steps_after_changes >= 2 do - {funnel_id, changes} - else - {funnel_id, - [ - Enum.at(changes, 0) - |> Map.put(:update_type, :delete_whole_funnel) - ]} - end - end - - Map.put(meta, :changes, new_changes) - end - - def to_map(row) do - [ - domain, - site_id, - funnel_name, - funnel_id, - funnel_step_id, - goal_id, - goal_name, - dupe_goal_ids, - all_goal_ids - ] = row - - %{ - domain: domain, - site_id: site_id, - funnel_name: funnel_name, - funnel_id: funnel_id, - funnel_step_id: funnel_step_id, - goal_id: goal_id, - goal_name: goal_name, - dupe_goal_ids: dupe_goal_ids, - all_goal_ids: all_goal_ids - } - end -end diff --git a/lib/plausible/funnel/const.ex b/lib/plausible/funnel/const.ex new file mode 100644 index 000000000..b010d82ce --- /dev/null +++ b/lib/plausible/funnel/const.ex @@ -0,0 +1,26 @@ +defmodule Plausible.Funnel.Const do + @moduledoc """ + Compile-time convience constants for funnel characteristics. + """ + @min_steps 2 + @max_steps 8 + + defmacro min_steps() do + quote do + unquote(@min_steps) + end + end + + defmacro max_steps() do + quote do + unquote(@max_steps) + end + end + + defmacro __using__(_opts \\ []) do + quote do + require Plausible.Funnel.Const + alias Plausible.Funnel + end + end +end diff --git a/lib/plausible/goal/schema.ex b/lib/plausible/goal/schema.ex index 7ab88dbcc..9f96c42b2 100644 --- a/lib/plausible/goal/schema.ex +++ b/lib/plausible/goal/schema.ex @@ -1,4 +1,5 @@ defmodule Plausible.Goal do + use Plausible use Ecto.Schema import Ecto.Changeset @@ -9,7 +10,13 @@ defmodule Plausible.Goal do field :page_path, :string field :currency, Ecto.Enum, values: Money.Currency.known_current_currencies() - many_to_many :funnels, Plausible.Funnel, join_through: Plausible.Funnel.Step + on_full_build do + many_to_many :funnels, Plausible.Funnel, join_through: Plausible.Funnel.Step + end + + on_small_build do + field :funnels, {:array, :map}, virtual: true, default: [] + end belongs_to :site, Plausible.Site diff --git a/lib/plausible/goals.ex b/lib/plausible/goals.ex index 170ae0ee2..f6702286c 100644 --- a/lib/plausible/goals.ex +++ b/lib/plausible/goals.ex @@ -1,9 +1,10 @@ defmodule Plausible.Goals do + use Plausible use Plausible.Repo alias Plausible.Goal alias Ecto.Multi - use Plausible.Funnel + use Plausible.Funnel.Const @spec create(Plausible.Site.t(), map(), Keyword.t()) :: {:ok, Goal.t()} | {:error, Ecto.Changeset.t()} | {:error, :upgrade_required} @@ -90,7 +91,7 @@ defmodule Plausible.Goals do order_by: [desc: g.id], preload: [:site] - if opts[:preload_funnels?] do + if opts[:preload_funnels?] == true and full_build?() do from(g in query, left_join: assoc(g, :funnels), group_by: g.id, @@ -117,15 +118,28 @@ defmodule Plausible.Goals do end def delete(id, site_id) do - result = - Multi.new() - |> Multi.one( - :goal, + on_full_build do + goal_query = from(g in Goal, where: g.id == ^id, where: g.site_id == ^site_id, preload: [funnels: :steps] ) + end + + on_small_build do + goal_query = + from(g in Goal, + where: g.id == ^id, + where: g.site_id == ^site_id + ) + end + + result = + Multi.new() + |> Multi.one( + :goal, + goal_query ) |> Multi.run(:funnel_ids_to_wipe, fn _, %{goal: nil} -> @@ -137,7 +151,7 @@ defmodule Plausible.Goals do _, %{goal: %{funnels: funnels}} -> funnels_to_wipe = funnels - |> Enum.filter(&(Enum.count(&1.steps) == Funnel.min_steps())) + |> Enum.filter(&(Enum.count(&1.steps) == Funnel.Const.min_steps())) |> Enum.map(& &1.id) {:ok, funnels_to_wipe} @@ -150,7 +164,7 @@ defmodule Plausible.Goals do Ecto.Multi.new() |> Multi.delete_all( :delete_funnels, - from(f in Funnel, + from(f in "funnels", where: f.id in ^funnel_ids ) ) diff --git a/lib/plausible/plugins/api/goals.ex b/lib/plausible/plugins/api/goals.ex index a5746323f..f20e93b2d 100644 --- a/lib/plausible/plugins/api/goals.ex +++ b/lib/plausible/plugins/api/goals.ex @@ -3,6 +3,7 @@ defmodule Plausible.Plugins.API.Goals do Plugins API context module for Goals. All high level Goal operations should be implemented here. """ + use Plausible import Ecto.Query import Plausible.Pagination @@ -41,13 +42,24 @@ defmodule Plausible.Plugins.API.Goals do |> Repo.one() end - defp get_query(site) do - from g in Plausible.Goal, - where: g.site_id == ^site.id, - order_by: [desc: g.id], - left_join: assoc(g, :funnels), - group_by: g.id, - preload: [:funnels] + on_full_build do + defp get_query(site) do + from g in Plausible.Goal, + where: g.site_id == ^site.id, + order_by: [desc: g.id], + left_join: assoc(g, :funnels), + group_by: g.id, + preload: [:funnels] + end + end + + on_small_build do + defp get_query(site) do + from g in Plausible.Goal, + where: g.site_id == ^site.id, + order_by: [desc: g.id], + group_by: g.id + end end defp convert_to_create_params(%CreateRequest.CustomEvent{goal: %{event_name: event_name}}) do diff --git a/lib/plausible/site/memberships/accept_invitation.ex b/lib/plausible/site/memberships/accept_invitation.ex index 35e49e37d..4ba1720a1 100644 --- a/lib/plausible/site/memberships/accept_invitation.ex +++ b/lib/plausible/site/memberships/accept_invitation.ex @@ -1,4 +1,6 @@ defmodule Plausible.Site.Memberships.AcceptInvitation do + use Plausible + @moduledoc """ Service for accepting invitations, including ownership transfers. @@ -25,7 +27,7 @@ defmodule Plausible.Site.Memberships.AcceptInvitation do @spec transfer_ownership(Site.t(), Auth.User.t(), Keyword.t()) :: {:ok, Site.Membership.t()} | {:error, Ecto.Changeset.t()} def transfer_ownership(site, user, opts \\ []) do - selfhost? = Keyword.get(opts, :selfhost?, Plausible.Release.selfhost?()) + selfhost? = Keyword.get(opts, :selfhost?, small_build?()) membership = get_or_create_owner_membership(site, user) multi = add_and_transfer_ownership(site, membership, user, selfhost?) diff --git a/lib/plausible/stats.ex b/lib/plausible/stats.ex index 91c42de20..b37e8fe77 100644 --- a/lib/plausible/stats.ex +++ b/lib/plausible/stats.ex @@ -1,10 +1,11 @@ defmodule Plausible.Stats do + use Plausible + alias Plausible.Stats.{ Breakdown, Aggregate, Timeseries, CurrentVisitors, - Funnel, FilterSuggestions } @@ -30,9 +31,11 @@ defmodule Plausible.Stats do CurrentVisitors.current_visitors(site) end - def funnel(site, query, funnel) do - include_sentry_replay_info() - Funnel.funnel(site, query, funnel) + on_full_build do + def funnel(site, query, funnel) do + include_sentry_replay_info() + Plausible.Stats.Funnel.funnel(site, query, funnel) + end end def filter_suggestions(site, query, filter_name, filter_search) do diff --git a/lib/plausible_web/controllers/api/stats_controller.ex b/lib/plausible_web/controllers/api/stats_controller.ex index bdd1299b7..ba4899040 100644 --- a/lib/plausible_web/controllers/api/stats_controller.ex +++ b/lib/plausible_web/controllers/api/stats_controller.ex @@ -1,4 +1,5 @@ defmodule PlausibleWeb.Api.StatsController do + use Plausible use PlausibleWeb, :controller use Plausible.Repo use Plug.ErrorHandler @@ -492,56 +493,58 @@ defmodule PlausibleWeb.Api.StatsController do end end - def funnel(conn, %{"id" => funnel_id} = params) do - site = Plausible.Repo.preload(conn.assigns.site, :owner) - - with :ok <- Plausible.Billing.Feature.Funnels.check_availability(site.owner), - :ok <- validate_params(site, params), - query <- Query.from(site, params) |> Filters.add_prefix(), - :ok <- validate_funnel_query(query), - {funnel_id, ""} <- Integer.parse(funnel_id), - {:ok, funnel} <- Stats.funnel(site, query, funnel_id) do - json(conn, funnel) - else - {:error, {:invalid_funnel_query, due_to}} -> - bad_request( - conn, - "We are unable to show funnels when the dashboard is filtered by #{due_to}", - %{ - level: :normal - } - ) + on_full_build do + def funnel(conn, %{"id" => funnel_id} = params) do + site = Plausible.Repo.preload(conn.assigns.site, :owner) - {:error, :funnel_not_found} -> - conn - |> put_status(404) - |> json(%{error: "Funnel not found"}) - |> halt() - - {:error, :upgrade_required} -> - H.payment_required( - conn, - "#{Plausible.Billing.Feature.Funnels.display_name()} is part of the Plausible Business plan. To get access to this feature, please upgrade your account." - ) + with :ok <- Plausible.Billing.Feature.Funnels.check_availability(site.owner), + :ok <- validate_params(site, params), + query <- Query.from(site, params) |> Filters.add_prefix(), + :ok <- validate_funnel_query(query), + {funnel_id, ""} <- Integer.parse(funnel_id), + {:ok, funnel} <- Stats.funnel(site, query, funnel_id) do + json(conn, funnel) + else + {:error, {:invalid_funnel_query, due_to}} -> + bad_request( + conn, + "We are unable to show funnels when the dashboard is filtered by #{due_to}", + %{ + level: :normal + } + ) + + {:error, :funnel_not_found} -> + conn + |> put_status(404) + |> json(%{error: "Funnel not found"}) + |> halt() + + {:error, :upgrade_required} -> + H.payment_required( + conn, + "#{Plausible.Billing.Feature.Funnels.display_name()} is part of the Plausible Business plan. To get access to this feature, please upgrade your account." + ) - _ -> - bad_request(conn, "There was an error with your request") + _ -> + bad_request(conn, "There was an error with your request") + end end - end - defp validate_funnel_query(query) do - case query do - _ when is_map_key(query.filters, "event:goal") -> - {:error, {:invalid_funnel_query, "goals"}} + defp validate_funnel_query(query) do + case query do + _ when is_map_key(query.filters, "event:goal") -> + {:error, {:invalid_funnel_query, "goals"}} - _ when is_map_key(query.filters, "event:page") -> - {:error, {:invalid_funnel_query, "pages"}} + _ when is_map_key(query.filters, "event:page") -> + {:error, {:invalid_funnel_query, "pages"}} - _ when query.period == "realtime" -> - {:error, {:invalid_funnel_query, "realtime period"}} + _ when query.period == "realtime" -> + {:error, {:invalid_funnel_query, "realtime period"}} - _ -> - :ok + _ -> + :ok + end end end diff --git a/lib/plausible_web/controllers/stats_controller.ex b/lib/plausible_web/controllers/stats_controller.ex index 9ddd276c8..25595c278 100644 --- a/lib/plausible_web/controllers/stats_controller.ex +++ b/lib/plausible_web/controllers/stats_controller.ex @@ -1,4 +1,6 @@ defmodule PlausibleWeb.StatsController do + use Plausible + @moduledoc """ This controller is responsible for rendering stats dashboards. @@ -65,7 +67,7 @@ defmodule PlausibleWeb.StatsController do |> render("stats.html", site: site, has_goals: Plausible.Sites.has_goals?(site), - funnels: Plausible.Funnels.list(site), + funnels: list_funnels(site), has_props: Plausible.Props.configured?(site), stats_start_date: stats_start_date, native_stats_start_date: NaiveDateTime.to_date(site.native_stats_start_at), @@ -90,6 +92,18 @@ defmodule PlausibleWeb.StatsController do end end + on_full_build do + defp list_funnels(site) do + Plausible.Funnels.list(site) + end + end + + on_small_build do + defp list_funnels(_site) do + [] + end + end + @doc """ The export is limited to 300 entries for other reports and 100 entries for pages because bigger result sets start causing failures. Since we request data like time on page or bounce_rate for pages in a separate query @@ -308,7 +322,7 @@ defmodule PlausibleWeb.StatsController do |> render("stats.html", site: shared_link.site, has_goals: Sites.has_goals?(shared_link.site), - funnels: Plausible.Funnels.list(shared_link.site), + funnels: list_funnels(shared_link.site), has_props: Plausible.Props.configured?(shared_link.site), stats_start_date: shared_link.site.stats_start_date, native_stats_start_date: NaiveDateTime.to_date(shared_link.site.native_stats_start_at), diff --git a/lib/plausible_web/endpoint.ex b/lib/plausible_web/endpoint.ex index e3f96937d..c4a1fa247 100644 --- a/lib/plausible_web/endpoint.ex +++ b/lib/plausible_web/endpoint.ex @@ -1,4 +1,5 @@ defmodule PlausibleWeb.Endpoint do + use Plausible use Sentry.PlugCapture use Phoenix.Endpoint, otp_app: :plausible @@ -34,12 +35,14 @@ defmodule PlausibleWeb.Endpoint do only: ~w(css js images favicon.ico robots.txt) ) - plug(Plug.Static, - at: "/kaffy", - from: :kaffy, - gzip: false, - only: ~w(assets) - ) + on_full_build do + plug(Plug.Static, + at: "/kaffy", + from: :kaffy, + gzip: false, + only: ~w(assets) + ) + end # Code reloading can be explicitly enabled under the # :code_reloader configuration of your endpoint. diff --git a/lib/plausible_web/live/goal_settings.ex b/lib/plausible_web/live/goal_settings.ex index 0bf8b1b22..6a9bef179 100644 --- a/lib/plausible_web/live/goal_settings.ex +++ b/lib/plausible_web/live/goal_settings.ex @@ -6,8 +6,6 @@ defmodule PlausibleWeb.Live.GoalSettings do use Phoenix.HTML use PlausibleWeb.Live.Flash - use Plausible.Funnel - alias Plausible.{Sites, Goals} def mount( diff --git a/lib/plausible_web/live/goal_settings/list.ex b/lib/plausible_web/live/goal_settings/list.ex index efb947dba..f57fe9183 100644 --- a/lib/plausible_web/live/goal_settings/list.ex +++ b/lib/plausible_web/live/goal_settings/list.ex @@ -5,8 +5,6 @@ defmodule PlausibleWeb.Live.GoalSettings.List do use Phoenix.LiveComponent use Phoenix.HTML - use Plausible.Funnel - attr(:goals, :list, required: true) attr(:domain, :string, required: true) attr(:filter_text, :string) diff --git a/lib/plausible_web/live/props_settings/list.ex b/lib/plausible_web/live/props_settings/list.ex index 2777ca19f..4840d6999 100644 --- a/lib/plausible_web/live/props_settings/list.ex +++ b/lib/plausible_web/live/props_settings/list.ex @@ -5,8 +5,6 @@ defmodule PlausibleWeb.Live.PropsSettings.List do use Phoenix.LiveComponent use Phoenix.HTML - use Plausible.Funnel - attr(:props, :list, required: true) attr(:domain, :string, required: true) attr(:filter_text, :string) diff --git a/lib/plausible_web/plugins/api/schemas/goal/create_request.ex b/lib/plausible_web/plugins/api/schemas/goal/create_request.ex index b3ca00925..409a9231f 100644 --- a/lib/plausible_web/plugins/api/schemas/goal/create_request.ex +++ b/lib/plausible_web/plugins/api/schemas/goal/create_request.ex @@ -2,7 +2,7 @@ defmodule PlausibleWeb.Plugins.API.Schemas.Goal.CreateRequest do @moduledoc """ OpenAPI schema for Goal creation request """ - use Plausible.Funnel + use Plausible.Funnel.Const use PlausibleWeb, :open_api_schema OpenApiSpex.schema(%{ @@ -19,7 +19,7 @@ defmodule PlausibleWeb.Plugins.API.Schemas.Goal.CreateRequest do goals: %Schema{ type: :array, minItems: 1, - maxItems: Funnel.max_steps(), + maxItems: Funnel.Const.max_steps(), items: %Schema{ oneOf: [ Schemas.Goal.CreateRequest.CustomEvent, diff --git a/lib/plausible_web/router.ex b/lib/plausible_web/router.ex index 3ccb6673c..206184aa8 100644 --- a/lib/plausible_web/router.ex +++ b/lib/plausible_web/router.ex @@ -1,5 +1,6 @@ defmodule PlausibleWeb.Router do use PlausibleWeb, :router + use Plausible import Phoenix.LiveView.Router @two_weeks_in_seconds 60 * 60 * 24 * 14 @@ -50,25 +51,32 @@ defmodule PlausibleWeb.Router do plug :accepts, ["json"] end - pipeline :flags do - plug :accepts, ["html"] - plug :put_secure_browser_headers - plug PlausibleWeb.Plugs.NoRobots - plug :fetch_session - plug PlausibleWeb.CRMAuthPlug + on_full_build do + pipeline :flags do + plug :accepts, ["html"] + plug :put_secure_browser_headers + plug PlausibleWeb.Plugs.NoRobots + plug :fetch_session + + plug PlausibleWeb.CRMAuthPlug + end end if Mix.env() == :dev do forward "/sent-emails", Bamboo.SentEmailViewerPlug end - use Kaffy.Routes, - scope: "/crm", - pipe_through: [PlausibleWeb.Plugs.NoRobots, PlausibleWeb.CRMAuthPlug] + on_full_build do + use Kaffy.Routes, + scope: "/crm", + pipe_through: [PlausibleWeb.Plugs.NoRobots, PlausibleWeb.CRMAuthPlug] + end - scope path: "/flags" do - pipe_through :flags - forward "/", FunWithFlags.UI.Router, namespace: "flags" + on_full_build do + scope path: "/flags" do + pipe_through :flags + forward "/", FunWithFlags.UI.Router, namespace: "flags" + end end scope path: "/api/plugins" do @@ -77,7 +85,11 @@ defmodule PlausibleWeb.Router do scope "/api/stats", PlausibleWeb.Api do pipe_through :internal_stats_api - get "/:domain/funnels/:id", StatsController, :funnel + + on_full_build do + get "/:domain/funnels/:id", StatsController, :funnel + end + get "/:domain/current-visitors", StatsController, :current_visitors get "/:domain/main-graph", StatsController, :main_graph get "/:domain/top-stats", StatsController, :top_stats @@ -291,7 +303,10 @@ defmodule PlausibleWeb.Router do get "/:website/settings/visibility", SiteController, :settings_visibility get "/:website/settings/goals", SiteController, :settings_goals get "/:website/settings/properties", SiteController, :settings_props - get "/:website/settings/funnels", SiteController, :settings_funnels + + on_full_build do + get "/:website/settings/funnels", SiteController, :settings_funnels + end get "/:website/settings/email-reports", SiteController, :settings_email_reports get "/:website/settings/custom-domain", SiteController, :settings_custom_domain diff --git a/lib/plausible_web/templates/site/settings_goals.html.heex b/lib/plausible_web/templates/site/settings_goals.html.heex index d987e95c0..8cc16afd2 100644 --- a/lib/plausible_web/templates/site/settings_goals.html.heex +++ b/lib/plausible_web/templates/site/settings_goals.html.heex @@ -4,7 +4,7 @@

Define actions that you want your users to take, like visiting a certain page, submitting a form, etc.

-

+

You can also 4.1"}, {:bcrypt_elixir, "~> 3.0"}, - {:bypass, "~> 2.1", only: [:dev, :test]}, + {:bypass, "~> 2.1", only: [:dev, :test, :small_test]}, {:cachex, "~> 3.4"}, {:ecto_ch, "~> 0.1.10"}, {:combination, "~> 0.0.3"}, @@ -68,14 +74,14 @@ defmodule Plausible.MixProject do {:credo, "~> 1.5", only: [:dev, :test], runtime: false}, {:csv, "~> 2.3"}, {:dialyxir, "~> 1.0", only: [:dev, :test], runtime: false}, - {:double, "~> 0.8.0", only: :test}, + {:double, "~> 0.8.0", only: [:test, :small_test]}, {:ecto, "~> 3.10.0"}, {:ecto_sql, "~> 3.10.0"}, {:envy, "~> 1.1.1"}, - {:ex_machina, "~> 2.3", only: [:dev, :test]}, + {:ex_machina, "~> 2.3", only: [:dev, :test, :small, :small_test]}, {:excoveralls, "~> 0.10", only: :test}, {:finch, "~> 0.16.0"}, - {:floki, "~> 0.34.3", only: [:dev, :test]}, + {:floki, "~> 0.34.3", only: [:dev, :test, :small, :small_test]}, {:fun_with_flags, "~> 1.9.0"}, {:fun_with_flags_ui, "~> 0.8"}, {:locus, "~> 2.3"}, @@ -84,9 +90,9 @@ defmodule Plausible.MixProject do {:hammer, "~> 6.0"}, {:httpoison, "~> 1.4"}, {:jason, "~> 1.3"}, - {:kaffy, "~> 0.10.2"}, + {:kaffy, "~> 0.10.2", only: [:dev, :test, :staging, :prod]}, {:location, git: "https://github.com/plausible/location.git"}, - {:mox, "~> 1.0", only: :test}, + {:mox, "~> 1.0", only: [:test, :small_test]}, {:nanoid, "~> 2.0.2"}, {:oauther, "~> 1.3"}, {:oban, "~> 2.12.0"}, @@ -101,7 +107,7 @@ defmodule Plausible.MixProject do {:phoenix_view, "~> 2.0"}, {:phoenix_ecto, "~> 4.0"}, {:phoenix_html, "~> 3.3", override: true}, - {:phoenix_live_reload, "~> 1.2", only: :dev}, + {:phoenix_live_reload, "~> 1.2", only: [:dev, :small]}, {:phoenix_pubsub, "~> 2.0"}, {:phoenix_live_view, "~> 0.18"}, {:php_serializer, "~> 2.0"}, @@ -125,8 +131,8 @@ defmodule Plausible.MixProject do {:joken, "~> 2.5"}, {:paginator, git: "https://github.com/duffelhq/paginator.git"}, {:scrivener_ecto, "~> 2.0"}, - {:esbuild, "~> 0.7", runtime: Mix.env() == :dev}, - {:tailwind, "~> 0.2.0", runtime: Mix.env() == :dev}, + {:esbuild, "~> 0.7", runtime: Mix.env() in [:dev, :small]}, + {:tailwind, "~> 0.2.0", runtime: Mix.env() in [:dev, :small]}, {:ex_json_logger, "~> 1.3.0"} ] end @@ -139,7 +145,10 @@ defmodule Plausible.MixProject do test: ["ecto.create --quiet", "ecto.migrate", "test", "clean_clickhouse"], sentry_recompile: ["compile", "deps.compile sentry --force"], "assets.setup": ["tailwind.install --if-missing", "esbuild.install --if-missing"], - "assets.build": ["tailwind default", "esbuild default"], + "assets.build": [ + "tailwind default", + "esbuild default" + ], "assets.deploy": ["tailwind default --minify", "esbuild default --minify", "phx.digest"] ] end diff --git a/test/plausible/billing/quota_test.exs b/test/plausible/billing/quota_test.exs index 47e7a0057..a7bff83a0 100644 --- a/test/plausible/billing/quota_test.exs +++ b/test/plausible/billing/quota_test.exs @@ -1,7 +1,12 @@ defmodule Plausible.Billing.QuotaTest do use Plausible.DataCase, async: true + use Plausible alias Plausible.Billing.{Quota, Plans} - alias Plausible.Billing.Feature.{Goals, RevenueGoals, Funnels, Props, StatsAPI} + alias Plausible.Billing.Feature.{Goals, RevenueGoals, Props, StatsAPI} + + on_full_build do + alias Plausible.Billing.Feature.Funnels + end @legacy_plan_id "558746" @v1_plan_id "558018" @@ -443,16 +448,18 @@ defmodule Plausible.Billing.QuotaTest do assert [Props] == Quota.features_usage(user) end - test "returns [Funnels] when user/site uses funnels" do - user = insert(:user) - site = insert(:site, memberships: [build(:site_membership, user: user, role: :owner)]) + on_full_build do + test "returns [Funnels] when user/site uses funnels" do + user = insert(:user) + site = insert(:site, memberships: [build(:site_membership, user: user, role: :owner)]) - goals = insert_list(3, :goal, site: site, event_name: fn -> Ecto.UUID.generate() end) - steps = Enum.map(goals, &%{"goal_id" => &1.id}) - Plausible.Funnels.create(site, "dummy", steps) + goals = insert_list(3, :goal, site: site, event_name: fn -> Ecto.UUID.generate() end) + steps = Enum.map(goals, &%{"goal_id" => &1.id}) + Plausible.Funnels.create(site, "dummy", steps) - assert [Funnels] == Quota.features_usage(site) - assert [Funnels] == Quota.features_usage(user) + assert [Funnels] == Quota.features_usage(site) + assert [Funnels] == Quota.features_usage(user) + end end test "returns [RevenueGoals] when user/site uses revenue goals" do @@ -471,23 +478,25 @@ defmodule Plausible.Billing.QuotaTest do assert [StatsAPI] == Quota.features_usage(user) end - test "returns multiple features" do - user = insert(:user) + on_full_build do + test "returns multiple features" do + user = insert(:user) - site = - insert(:site, - allowed_event_props: ["dummy"], - memberships: [build(:site_membership, user: user, role: :owner)] - ) + site = + insert(:site, + allowed_event_props: ["dummy"], + memberships: [build(:site_membership, user: user, role: :owner)] + ) - insert(:goal, currency: :USD, site: site, event_name: "Purchase") + insert(:goal, currency: :USD, site: site, event_name: "Purchase") - goals = insert_list(3, :goal, site: site, event_name: fn -> Ecto.UUID.generate() end) - steps = Enum.map(goals, &%{"goal_id" => &1.id}) - Plausible.Funnels.create(site, "dummy", steps) + goals = insert_list(3, :goal, site: site, event_name: fn -> Ecto.UUID.generate() end) + steps = Enum.map(goals, &%{"goal_id" => &1.id}) + Plausible.Funnels.create(site, "dummy", steps) - assert [Props, Funnels, RevenueGoals] == Quota.features_usage(site) - assert [Props, Funnels, RevenueGoals] == Quota.features_usage(user) + assert [Props, Funnels, RevenueGoals] == Quota.features_usage(site) + assert [Props, Funnels, RevenueGoals] == Quota.features_usage(user) + end end test "accounts only for sites the user owns" do @@ -518,22 +527,24 @@ defmodule Plausible.Billing.QuotaTest do assert [Goals, Props, StatsAPI] == Quota.allowed_features_for(user) end - test "returns the enterprise plan features" do - user = insert(:user) + on_full_build do + test "returns the enterprise plan features" do + user = insert(:user) - enterprise_plan = - insert(:enterprise_plan, - user_id: user.id, - monthly_pageview_limit: 100_000, - site_limit: 500, - features: [Plausible.Billing.Feature.StatsAPI, Plausible.Billing.Feature.Funnels] - ) + enterprise_plan = + insert(:enterprise_plan, + user_id: user.id, + monthly_pageview_limit: 100_000, + site_limit: 500, + features: [Plausible.Billing.Feature.StatsAPI, Plausible.Billing.Feature.Funnels] + ) - _subscription = - insert(:subscription, user_id: user.id, paddle_plan_id: enterprise_plan.paddle_plan_id) + _subscription = + insert(:subscription, user_id: user.id, paddle_plan_id: enterprise_plan.paddle_plan_id) - assert [Plausible.Billing.Feature.StatsAPI, Plausible.Billing.Feature.Funnels] == - Quota.allowed_features_for(user) + assert [Plausible.Billing.Feature.StatsAPI, Plausible.Billing.Feature.Funnels] == + Quota.allowed_features_for(user) + end end test "returns all features when user in on trial" do diff --git a/test/plausible/data_migration/rewrite_funnel_dupes_test.exs b/test/plausible/data_migration/rewrite_funnel_dupes_test.exs deleted file mode 100644 index 5938dac4b..000000000 --- a/test/plausible/data_migration/rewrite_funnel_dupes_test.exs +++ /dev/null @@ -1,128 +0,0 @@ -defmodule Plausible.DataMigration.RewriteFunnelDupesTest do - use Plausible.DataCase, async: true - - alias Plausible.DataMigration.RewriteFunnelDupes - - import ExUnit.CaptureIO - - for goal_type <- ["event_name", "page_path"] do - @tag :skip - test "deletes a funnel that cannot be cleaned up from dupe goals (#{goal_type})" do - site = insert(:site) - - goals = - setup_goals!(site, [ - %{unquote(goal_type) => "/AAA"}, - %{unquote(goal_type) => "/AAA"}, - %{unquote(goal_type) => "/AAA"} - ]) - - funnel = setup_funnel!(site, "test", goals) - - io = assert capture_io(fn -> RewriteFunnelDupes.run() end) - assert io =~ "Processing site ID: #{site.id}" - assert io =~ "Deleting whole funnel" - - refute Repo.reload(funnel) - end - - @tag :skip - test "reduces a funnel if possible (#{goal_type})" do - site = insert(:site) - - goals = - setup_goals!(site, [ - %{unquote(goal_type) => "/AAA"}, - %{unquote(goal_type) => "/BBB"}, - %{unquote(goal_type) => "/AAA"}, - %{unquote(goal_type) => "/CCC"} - ]) - - funnel = setup_funnel!(site, "test", goals) - - io = assert capture_io(fn -> RewriteFunnelDupes.run() end) - assert io =~ "Processing site ID: #{site.id}" - assert io =~ "Deleting step" - - assert_funnel(site.id, funnel.id, [ - %{unquote(goal_type) => "/AAA"}, - %{unquote(goal_type) => "/BBB"}, - %{unquote(goal_type) => "/CCC"} - ]) - end - end - - @tag :skip - test "dupe names in mixed goal types don't matter" do - site = insert(:site) - - gs = [ - %{"event_name" => "/AAA"}, - %{"page_path" => "/AAA"}, - %{"event_name" => "/foo"}, - %{"page_path" => "/foo"} - ] - - goals = setup_goals!(site, gs) - - funnel = setup_funnel!(site, "test", goals) - - capture_io(fn -> RewriteFunnelDupes.run() end) - - assert_funnel(site.id, funnel.id, gs) - end - - @tag :skip - test "goals across multiple funnels" do - site = insert(:site) - - goals = [ - %{"event_name" => "/AAA"}, - %{"event_name" => "/AAA"}, - %{"page_path" => "/foo"}, - %{"event_name" => "/AAA"} - ] - - [g1, g2, g3, g4] = setup_goals!(site, goals) - - funnel1 = setup_funnel!(site, "test1", [g1, g2, g3, g4]) - funnel2 = setup_funnel!(site, "test2", [g2, g1, g3, g4]) - funnel3 = setup_funnel!(site, "test3", [g2, g3]) - funnel4 = setup_funnel!(site, "test4", [g2, g1]) - - capture_io(fn -> RewriteFunnelDupes.run() end) - - assert_funnel(site.id, funnel1.id, [%{"event_name" => "/AAA"}, %{"page_path" => "/foo"}]) - assert_funnel(site.id, funnel2.id, [%{"event_name" => "/AAA"}, %{"page_path" => "/foo"}]) - assert_funnel(site.id, funnel3.id, [%{"event_name" => "/AAA"}, %{"page_path" => "/foo"}]) - - refute Plausible.Funnels.get(site.id, funnel4.id) - end - - defp setup_goals!(site, goals) do - for goal <- goals do - {:ok, g} = Plausible.Goals.create(site, goal) - g - end - end - - def setup_funnel!(site, name, goals) do - {:ok, funnel} = Plausible.Funnels.create(site, name, Enum.map(goals, &%{"goal_id" => &1.id})) - funnel - end - - def assert_funnel(site_id, funnel_id, goals) do - funnel_goals = - Plausible.Funnels.get(site_id, funnel_id) - |> Map.fetch!(:steps) - |> Enum.map(& &1.goal) - - assert Enum.count(funnel_goals) == Enum.count(goals) - - Enum.zip(funnel_goals, goals) - |> Enum.each(fn {funnel_goal, expect} -> - key = Map.keys(expect) |> List.first() |> String.to_existing_atom() - assert Map.fetch!(funnel_goal, key) == Map.values(expect) |> List.first() - end) - end -end diff --git a/test/plausible/funnels_test.exs b/test/plausible/funnels_test.exs index 32bfae900..4273c64e9 100644 --- a/test/plausible/funnels_test.exs +++ b/test/plausible/funnels_test.exs @@ -1,355 +1,363 @@ defmodule Plausible.FunnelsTest do use Plausible.DataCase - - alias Plausible.Goals - alias Plausible.Funnels - alias Plausible.Stats - - setup do - site = insert(:site) - - {:ok, g1} = Goals.create(site, %{"page_path" => "/go/to/blog/**"}) - {:ok, g2} = Goals.create(site, %{"event_name" => "Signup"}) - {:ok, g3} = Goals.create(site, %{"page_path" => "/checkout"}) - {:ok, g4} = Goals.create(site, %{"event_name" => "Leave feedback"}) - {:ok, g5} = Goals.create(site, %{"page_path" => "/recommend"}) - {:ok, g6} = Goals.create(site, %{"event_name" => "Extra event"}) - {:ok, g7} = Goals.create(site, %{"event_name" => "Extra event 2"}) - {:ok, g8} = Goals.create(site, %{"event_name" => "Extra event 3"}) - {:ok, g9} = Goals.create(site, %{"event_name" => "Extra event 4"}) - - {:ok, - %{ - site: site, - goals: [g1, g2, g3], - steps: [g1, g2, g3, g4, g5, g6, g7, g8, g9] |> Enum.map(&%{"goal_id" => &1.id}) - }} - end - - describe "Common context" do - test "create and store a funnel given a set of goals", %{site: site, steps: [g1, g2, g3 | _]} do - {:ok, funnel} = - Funnels.create( - site, - "From blog to signup and purchase", - [g1, g2, g3] - ) - - assert funnel.inserted_at - assert funnel.name == "From blog to signup and purchase" - assert [fg1, fg2, fg3] = funnel.steps - - assert fg1.goal_id == g1["goal_id"] - assert fg2.goal_id == g2["goal_id"] - assert fg3.goal_id == g3["goal_id"] - - assert fg1.step_order == 1 - assert fg2.step_order == 2 - assert fg3.step_order == 3 - end - - test "retrieve a funnel by id and site, get steps in order", %{ - site: site, - steps: [g1, g2, g3 | _] - } do - {:ok, funnel} = - Funnels.create( - site, - "Lorem ipsum", - [g3, g1, g2] - ) - - assert funnel = Funnels.get(site, funnel.id) - assert funnel.name == "Lorem ipsum" - assert [%{step_order: 1}, %{step_order: 2}, %{step_order: 3}] = funnel.steps - end - - test "funnels can be deleted by id and a site", %{site: site, steps: [g1, g2 | _]} do - {:ok, funnel} = - Funnels.create( - site, - "Sample funnel", - [g1, g2] - ) - - assert :ok = Funnels.delete(site, funnel.id) - # deletion is idempotent - assert :ok = Funnels.delete(site, funnel.id) - refute Funnels.get(site, funnel.id) - end - - test "a funnel cannot be made of < 2 steps", %{site: site, steps: [g1 | _]} do - assert {:error, :invalid_funnel_size} = - Funnels.create( - site, - "Lorem ipsum", - [g1] - ) + @moduletag :full_build_only + + use Plausible + + on_full_build do + alias Plausible.Goals + alias Plausible.Funnels + alias Plausible.Stats + + setup do + site = insert(:site) + + {:ok, g1} = Goals.create(site, %{"page_path" => "/go/to/blog/**"}) + {:ok, g2} = Goals.create(site, %{"event_name" => "Signup"}) + {:ok, g3} = Goals.create(site, %{"page_path" => "/checkout"}) + {:ok, g4} = Goals.create(site, %{"event_name" => "Leave feedback"}) + {:ok, g5} = Goals.create(site, %{"page_path" => "/recommend"}) + {:ok, g6} = Goals.create(site, %{"event_name" => "Extra event"}) + {:ok, g7} = Goals.create(site, %{"event_name" => "Extra event 2"}) + {:ok, g8} = Goals.create(site, %{"event_name" => "Extra event 3"}) + {:ok, g9} = Goals.create(site, %{"event_name" => "Extra event 4"}) + + {:ok, + %{ + site: site, + goals: [g1, g2, g3], + steps: [g1, g2, g3, g4, g5, g6, g7, g8, g9] |> Enum.map(&%{"goal_id" => &1.id}) + }} end - test "a funnel can be made of 8 steps maximum", %{site: site, steps: too_many_steps} do - assert {:ok, _} = - Funnels.create( - site, - "Lorem ipsum", - Enum.take(too_many_steps, 8) - ) - - assert {:error, :invalid_funnel_size} = - Funnels.create( - site, - "Lorem ipsum", - too_many_steps - ) + describe "Common context" do + test "create and store a funnel given a set of goals", %{ + site: site, + steps: [g1, g2, g3 | _] + } do + {:ok, funnel} = + Funnels.create( + site, + "From blog to signup and purchase", + [g1, g2, g3] + ) + + assert funnel.inserted_at + assert funnel.name == "From blog to signup and purchase" + assert [fg1, fg2, fg3] = funnel.steps + + assert fg1.goal_id == g1["goal_id"] + assert fg2.goal_id == g2["goal_id"] + assert fg3.goal_id == g3["goal_id"] + + assert fg1.step_order == 1 + assert fg2.step_order == 2 + assert fg3.step_order == 3 + end + + test "retrieve a funnel by id and site, get steps in order", %{ + site: site, + steps: [g1, g2, g3 | _] + } do + {:ok, funnel} = + Funnels.create( + site, + "Lorem ipsum", + [g3, g1, g2] + ) + + assert funnel = Funnels.get(site, funnel.id) + assert funnel.name == "Lorem ipsum" + assert [%{step_order: 1}, %{step_order: 2}, %{step_order: 3}] = funnel.steps + end + + test "funnels can be deleted by id and a site", %{site: site, steps: [g1, g2 | _]} do + {:ok, funnel} = + Funnels.create( + site, + "Sample funnel", + [g1, g2] + ) + + assert :ok = Funnels.delete(site, funnel.id) + # deletion is idempotent + assert :ok = Funnels.delete(site, funnel.id) + refute Funnels.get(site, funnel.id) + end + + test "a funnel cannot be made of < 2 steps", %{site: site, steps: [g1 | _]} do + assert {:error, :invalid_funnel_size} = + Funnels.create( + site, + "Lorem ipsum", + [g1] + ) + end + + test "a funnel can be made of 8 steps maximum", %{site: site, steps: too_many_steps} do + assert {:ok, _} = + Funnels.create( + site, + "Lorem ipsum", + Enum.take(too_many_steps, 8) + ) + + assert {:error, :invalid_funnel_size} = + Funnels.create( + site, + "Lorem ipsum", + too_many_steps + ) + end + + test "a goal can only appear once in a funnel", %{steps: [g1 | _], site: site} do + {:error, _changeset} = + Funnels.create( + site, + "Lorem ipsum", + [g1, g1] + ) + end + + test "funnels can be listed per site, starting from most recently added", %{ + site: site, + steps: [g1, g2, g3 | _] + } do + Funnels.create(site, "Funnel 1", [g3, g1]) + Funnels.create(site, "Funnel 2", [g2, g1, g3]) + + funnels_list = Funnels.list(site) + + assert [%{name: "Funnel 2", steps_count: 3}, %{name: "Funnel 1", steps_count: 2}] = + funnels_list + end end - test "a goal can only appear once in a funnel", %{steps: [g1 | _], site: site} do - {:error, _changeset} = - Funnels.create( - site, - "Lorem ipsum", - [g1, g1] - ) - end - - test "funnels can be listed per site, starting from most recently added", %{ - site: site, - steps: [g1, g2, g3 | _] - } do - Funnels.create(site, "Funnel 1", [g3, g1]) - Funnels.create(site, "Funnel 2", [g2, g1, g3]) - - funnels_list = Funnels.list(site) - - assert [%{name: "Funnel 2", steps_count: 3}, %{name: "Funnel 1", steps_count: 2}] = - funnels_list - end - end - - describe "Plausible.Stats.Funnel" do - test "funnels can be evaluated per site within a time range against an ephemeral definition", - %{ - site: site, - goals: [g1, g2, g3 | _] - } do - funnel_definition = - Funnels.ephemeral_definition( - site, - "From blog to signup and purchase", - [ - %{ - "goal_id" => "#{g1.id}", - "goal" => %{ - "id" => "#{g1.id}", - "event_name" => g1.event_name, - "page_path" => g1.page_path - } - }, - %{ - "goal_id" => g2.id, - "goal" => %{ - "id" => g2.id, - "event_name" => g2.event_name, - "page_path" => g2.page_path - } - }, - %{ - "goal_id" => g3.id, - "goal" => %{ - "id" => g3.id, - "event_name" => g3.event_name, - "page_path" => g3.page_path - } - } - ] - ) - - populate_stats(site, [ - build(:pageview, pathname: "/irrelevant/page/not/in/funnel", user_id: 999), - build(:pageview, pathname: "/go/to/blog/foo", user_id: 123), - build(:event, name: "Signup", user_id: 123), - build(:pageview, pathname: "/checkout", user_id: 123), - build(:pageview, pathname: "/go/to/blog/bar", user_id: 666), - build(:event, name: "Signup", user_id: 666) - ]) - - query = Plausible.Stats.Query.from(site, %{"period" => "all"}) - - funnel_data = Stats.funnel(site, query, funnel_definition) - - assert {:ok, + describe "Plausible.Stats.Funnel" do + test "funnels can be evaluated per site within a time range against an ephemeral definition", + %{ + site: site, + goals: [g1, g2, g3 | _] + } do + funnel_definition = + Funnels.ephemeral_definition( + site, + "From blog to signup and purchase", + [ %{ - all_visitors: 3, - entering_visitors: 2, - entering_visitors_percentage: "66.67", - never_entering_visitors: 1, - never_entering_visitors_percentage: "33.33", - steps: [ - %{ - label: "Visit /go/to/blog/**", - visitors: 2, - conversion_rate: "100", - conversion_rate_step: "0", - dropoff: 0, - dropoff_percentage: "0" - }, - %{ - label: "Signup", - visitors: 2, - conversion_rate: "100", - conversion_rate_step: "100", - dropoff: 0, - dropoff_percentage: "0" - }, - %{ - label: "Visit /checkout", - visitors: 1, - conversion_rate: "50", - conversion_rate_step: "50", - dropoff: 1, - dropoff_percentage: "50" - } - ] - }} = funnel_data - end - - test "funnels can be evaluated per site within a time range", %{ - site: site, - steps: [g1, g2, g3 | _] - } do - {:ok, funnel} = - Funnels.create( - site, - "From blog to signup and purchase", - [g1, g2, g3] - ) - - populate_stats(site, [ - build(:pageview, pathname: "/go/to/blog/foo", user_id: 123), - build(:event, name: "Signup", user_id: 123), - build(:pageview, pathname: "/checkout", user_id: 123), - build(:pageview, pathname: "/go/to/blog/bar", user_id: 666), - build(:event, name: "Signup", user_id: 666) - ]) - - query = Plausible.Stats.Query.from(site, %{"period" => "all"}) - - funnel_data = Stats.funnel(site, query, funnel.id) - - assert {:ok, + "goal_id" => "#{g1.id}", + "goal" => %{ + "id" => "#{g1.id}", + "event_name" => g1.event_name, + "page_path" => g1.page_path + } + }, %{ - all_visitors: 2, - entering_visitors: 2, - entering_visitors_percentage: "100", - never_entering_visitors: 0, - never_entering_visitors_percentage: "0", - steps: [ - %{ - label: "Visit /go/to/blog/**", - visitors: 2, - conversion_rate: "100", - conversion_rate_step: "0", - dropoff: 0 - }, - %{ - label: "Signup", - visitors: 2, - conversion_rate: "100", - conversion_rate_step: "100", - dropoff: 0, - dropoff_percentage: "0" - }, - %{ - label: "Visit /checkout", - visitors: 1, - conversion_rate: "50", - conversion_rate_step: "50", - dropoff: 1, - dropoff_percentage: "50" - } - ] - }} = funnel_data - end - - test "funnels can be evaluated even where there are no visits yet", %{ - site: site, - steps: [g1, g2, g3 | _] - } do - {:ok, funnel} = - Funnels.create( - site, - "From blog to signup and purchase", - [g1, g2, g3] - ) - - query = Plausible.Stats.Query.from(site, %{"period" => "all"}) - - funnel_data = Stats.funnel(site, query, funnel.id) - - assert {:ok, + "goal_id" => g2.id, + "goal" => %{ + "id" => g2.id, + "event_name" => g2.event_name, + "page_path" => g2.page_path + } + }, %{ - all_visitors: 0, - entering_visitors: 0, - entering_visitors_percentage: "0", - never_entering_visitors: 0, - never_entering_visitors_percentage: "0", - steps: [ - %{ - label: "Visit /go/to/blog/**", - visitors: 0, - conversion_rate: "0", - conversion_rate_step: "0", - dropoff: 0, - dropoff_percentage: "0" - }, - %{ - label: "Signup", - visitors: 0, - conversion_rate: "0", - conversion_rate_step: "0", - dropoff: 0, - dropoff_percentage: "0" - }, - %{ - label: "Visit /checkout", - visitors: 0, - conversion_rate: "0", - conversion_rate_step: "0", - dropoff: 0, - dropoff_percentage: "0" - } - ] - }} = funnel_data - end - - @tag :slow - test "sampling", %{site: site, steps: [g1, g2, g3 | _]} do - {:ok, funnel} = - Funnels.create( - site, - "From blog to signup and purchase", - [g1, g2, g3] - ) - - stats = - 1..50_000 - |> Enum.flat_map(fn _ -> - user_id = SipHash.hash!("0123456789ABCDEF", :crypto.strong_rand_bytes(64)) - - [ - build(:pageview, pathname: "/go/to/blog/foo", user_id: user_id), - build(:event, name: "Signup", user_id: user_id), - build(:pageview, pathname: "/checkout", user_id: user_id) - ] - end) - - populate_stats(site, stats) - - query = - Plausible.Stats.Query.from(site, %{"period" => "all", "sample_threshold" => "10000"}) - - {:ok, funnel_data} = Stats.funnel(site, query, funnel.id) - assert_in_delta funnel_data[:all_visitors], 50_000, 5000 + "goal_id" => g3.id, + "goal" => %{ + "id" => g3.id, + "event_name" => g3.event_name, + "page_path" => g3.page_path + } + } + ] + ) + + populate_stats(site, [ + build(:pageview, pathname: "/irrelevant/page/not/in/funnel", user_id: 999), + build(:pageview, pathname: "/go/to/blog/foo", user_id: 123), + build(:event, name: "Signup", user_id: 123), + build(:pageview, pathname: "/checkout", user_id: 123), + build(:pageview, pathname: "/go/to/blog/bar", user_id: 666), + build(:event, name: "Signup", user_id: 666) + ]) + + query = Plausible.Stats.Query.from(site, %{"period" => "all"}) + + funnel_data = Stats.funnel(site, query, funnel_definition) + + assert {:ok, + %{ + all_visitors: 3, + entering_visitors: 2, + entering_visitors_percentage: "66.67", + never_entering_visitors: 1, + never_entering_visitors_percentage: "33.33", + steps: [ + %{ + label: "Visit /go/to/blog/**", + visitors: 2, + conversion_rate: "100", + conversion_rate_step: "0", + dropoff: 0, + dropoff_percentage: "0" + }, + %{ + label: "Signup", + visitors: 2, + conversion_rate: "100", + conversion_rate_step: "100", + dropoff: 0, + dropoff_percentage: "0" + }, + %{ + label: "Visit /checkout", + visitors: 1, + conversion_rate: "50", + conversion_rate_step: "50", + dropoff: 1, + dropoff_percentage: "50" + } + ] + }} = funnel_data + end + + test "funnels can be evaluated per site within a time range", %{ + site: site, + steps: [g1, g2, g3 | _] + } do + {:ok, funnel} = + Funnels.create( + site, + "From blog to signup and purchase", + [g1, g2, g3] + ) + + populate_stats(site, [ + build(:pageview, pathname: "/go/to/blog/foo", user_id: 123), + build(:event, name: "Signup", user_id: 123), + build(:pageview, pathname: "/checkout", user_id: 123), + build(:pageview, pathname: "/go/to/blog/bar", user_id: 666), + build(:event, name: "Signup", user_id: 666) + ]) + + query = Plausible.Stats.Query.from(site, %{"period" => "all"}) + + funnel_data = Stats.funnel(site, query, funnel.id) + + assert {:ok, + %{ + all_visitors: 2, + entering_visitors: 2, + entering_visitors_percentage: "100", + never_entering_visitors: 0, + never_entering_visitors_percentage: "0", + steps: [ + %{ + label: "Visit /go/to/blog/**", + visitors: 2, + conversion_rate: "100", + conversion_rate_step: "0", + dropoff: 0 + }, + %{ + label: "Signup", + visitors: 2, + conversion_rate: "100", + conversion_rate_step: "100", + dropoff: 0, + dropoff_percentage: "0" + }, + %{ + label: "Visit /checkout", + visitors: 1, + conversion_rate: "50", + conversion_rate_step: "50", + dropoff: 1, + dropoff_percentage: "50" + } + ] + }} = funnel_data + end + + test "funnels can be evaluated even where there are no visits yet", %{ + site: site, + steps: [g1, g2, g3 | _] + } do + {:ok, funnel} = + Funnels.create( + site, + "From blog to signup and purchase", + [g1, g2, g3] + ) + + query = Plausible.Stats.Query.from(site, %{"period" => "all"}) + + funnel_data = Stats.funnel(site, query, funnel.id) + + assert {:ok, + %{ + all_visitors: 0, + entering_visitors: 0, + entering_visitors_percentage: "0", + never_entering_visitors: 0, + never_entering_visitors_percentage: "0", + steps: [ + %{ + label: "Visit /go/to/blog/**", + visitors: 0, + conversion_rate: "0", + conversion_rate_step: "0", + dropoff: 0, + dropoff_percentage: "0" + }, + %{ + label: "Signup", + visitors: 0, + conversion_rate: "0", + conversion_rate_step: "0", + dropoff: 0, + dropoff_percentage: "0" + }, + %{ + label: "Visit /checkout", + visitors: 0, + conversion_rate: "0", + conversion_rate_step: "0", + dropoff: 0, + dropoff_percentage: "0" + } + ] + }} = funnel_data + end + + @tag :slow + test "sampling", %{site: site, steps: [g1, g2, g3 | _]} do + {:ok, funnel} = + Funnels.create( + site, + "From blog to signup and purchase", + [g1, g2, g3] + ) + + stats = + 1..50_000 + |> Enum.flat_map(fn _ -> + user_id = SipHash.hash!("0123456789ABCDEF", :crypto.strong_rand_bytes(64)) + + [ + build(:pageview, pathname: "/go/to/blog/foo", user_id: user_id), + build(:event, name: "Signup", user_id: user_id), + build(:pageview, pathname: "/checkout", user_id: user_id) + ] + end) + + populate_stats(site, stats) + + query = + Plausible.Stats.Query.from(site, %{"period" => "all", "sample_threshold" => "10000"}) + + {:ok, funnel_data} = Stats.funnel(site, query, funnel.id) + assert_in_delta funnel_data[:all_visitors], 50_000, 5000 + end end end end diff --git a/test/plausible/goals_test.exs b/test/plausible/goals_test.exs index b312f3dc8..4959ab732 100644 --- a/test/plausible/goals_test.exs +++ b/test/plausible/goals_test.exs @@ -1,5 +1,6 @@ defmodule Plausible.GoalsTest do use Plausible.DataCase + use Plausible alias Plausible.Goals test "create/2 creates goals and trims input" do @@ -132,79 +133,81 @@ defmodule Plausible.GoalsTest do assert [] = Goals.for_site(site) end - test "goals can be fetched with funnel count preloaded" do - site = insert(:site) - - goals = - Enum.map(1..4, fn i -> - {:ok, g} = Goals.create(site, %{"page_path" => "/#{i}"}) - g - end) - - {:ok, %{id: funnel_id1}} = - Plausible.Funnels.create( - site, - "Funnel1", - [ - %{"goal_id" => Enum.at(goals, 1).id}, - %{"goal_id" => Enum.at(goals, 2).id}, - %{"goal_id" => Enum.at(goals, 3).id} - ] - ) - - {:ok, %{id: funnel_id2}} = - Plausible.Funnels.create( - site, - "Funnel2", - [ - %{"goal_id" => Enum.at(goals, 1).id}, - %{"goal_id" => Enum.at(goals, 3).id} - ] - ) - - assert [goal, _, _, _] = Goals.for_site(site, preload_funnels?: false) - assert %Ecto.Association.NotLoaded{} = goal.funnels - - assert [goal, _, _, _] = Goals.for_site(site, preload_funnels?: true) - assert [%{id: ^funnel_id1}, %{id: ^funnel_id2}] = goal.funnels - end - - test "deleting goals with funnels triggers funnel reduction" do - site = insert(:site) - {:ok, g1} = Goals.create(site, %{"page_path" => "/1"}) - {:ok, g2} = Goals.create(site, %{"page_path" => "/2"}) - {:ok, g3} = Goals.create(site, %{"page_path" => "/3"}) - - {:ok, f1} = - Plausible.Funnels.create( - site, - "Funnel 3 steps", - [ - %{"goal_id" => g1.id}, - %{"goal_id" => g2.id}, - %{"goal_id" => g3.id} - ] - ) - - {:ok, f2} = - Plausible.Funnels.create( - site, - "Funnel 2 steps", - [ - %{"goal_id" => g1.id}, - %{"goal_id" => g2.id} - ] - ) - - :ok = Goals.delete(g1.id, site) - - assert f1 = Plausible.Funnels.get(site.id, f1.id) - assert Enum.count(f1.steps) == 2 - - refute Plausible.Funnels.get(site.id, f2.id) - assert Repo.all(from(fs in Plausible.Funnel.Step, where: fs.funnel_id == ^f2.id)) == [] - - assert [^g3, ^g2] = Goals.for_site(site) + on_full_build do + test "goals can be fetched with funnel count preloaded" do + site = insert(:site) + + goals = + Enum.map(1..4, fn i -> + {:ok, g} = Goals.create(site, %{"page_path" => "/#{i}"}) + g + end) + + {:ok, %{id: funnel_id1}} = + Plausible.Funnels.create( + site, + "Funnel1", + [ + %{"goal_id" => Enum.at(goals, 1).id}, + %{"goal_id" => Enum.at(goals, 2).id}, + %{"goal_id" => Enum.at(goals, 3).id} + ] + ) + + {:ok, %{id: funnel_id2}} = + Plausible.Funnels.create( + site, + "Funnel2", + [ + %{"goal_id" => Enum.at(goals, 1).id}, + %{"goal_id" => Enum.at(goals, 3).id} + ] + ) + + assert [goal, _, _, _] = Goals.for_site(site, preload_funnels?: false) + assert %Ecto.Association.NotLoaded{} = goal.funnels + + assert [goal, _, _, _] = Goals.for_site(site, preload_funnels?: true) + assert [%{id: ^funnel_id1}, %{id: ^funnel_id2}] = goal.funnels + end + + test "deleting goals with funnels triggers funnel reduction" do + site = insert(:site) + {:ok, g1} = Goals.create(site, %{"page_path" => "/1"}) + {:ok, g2} = Goals.create(site, %{"page_path" => "/2"}) + {:ok, g3} = Goals.create(site, %{"page_path" => "/3"}) + + {:ok, f1} = + Plausible.Funnels.create( + site, + "Funnel 3 steps", + [ + %{"goal_id" => g1.id}, + %{"goal_id" => g2.id}, + %{"goal_id" => g3.id} + ] + ) + + {:ok, f2} = + Plausible.Funnels.create( + site, + "Funnel 2 steps", + [ + %{"goal_id" => g1.id}, + %{"goal_id" => g2.id} + ] + ) + + :ok = Goals.delete(g1.id, site) + + assert f1 = Plausible.Funnels.get(site.id, f1.id) + assert Enum.count(f1.steps) == 2 + + refute Plausible.Funnels.get(site.id, f2.id) + assert Repo.all(from(fs in Plausible.Funnel.Step, where: fs.funnel_id == ^f2.id)) == [] + + assert [^g3, ^g2] = Goals.for_site(site) + end end test "must be either page_path or event_name" do diff --git a/test/plausible/site/memberships/accept_invitation_test.exs b/test/plausible/site/memberships/accept_invitation_test.exs index 27425a296..c7fdaa25c 100644 --- a/test/plausible/site/memberships/accept_invitation_test.exs +++ b/test/plausible/site/memberships/accept_invitation_test.exs @@ -1,4 +1,5 @@ defmodule Plausible.Site.Memberships.AcceptInvitationTest do + use Plausible use Plausible.DataCase, async: true use Bamboo.Test @@ -66,20 +67,22 @@ defmodule Plausible.Site.Memberships.AcceptInvitationTest do assert Repo.reload!(owner).trial_expiry_date == nil end - test "locks the site if the new owner has no active subscription or trial" do - existing_owner = insert(:user) + on_full_build do + test "locks the site if the new owner has no active subscription or trial" do + existing_owner = insert(:user) - site = - insert(:site, - locked: false, - memberships: [build(:site_membership, user: existing_owner, role: :owner)] - ) + site = + insert(:site, + locked: false, + memberships: [build(:site_membership, user: existing_owner, role: :owner)] + ) - new_owner = insert(:user, trial_expiry_date: Date.add(Date.utc_today(), -1)) + new_owner = insert(:user, trial_expiry_date: Date.add(Date.utc_today(), -1)) - assert {:ok, _membership} = AcceptInvitation.transfer_ownership(site, new_owner) + assert {:ok, _membership} = AcceptInvitation.transfer_ownership(site, new_owner) - assert Repo.reload!(site).locked + assert Repo.reload!(site).locked + end end test "does not lock the site or set trial expiry date if the instance is selfhosted" do @@ -100,74 +103,80 @@ defmodule Plausible.Site.Memberships.AcceptInvitationTest do refute Repo.reload!(site).locked end - test "ends trial of the new owner immediately" do - existing_owner = insert(:user) + on_full_build do + test "ends trial of the new owner immediately" do + existing_owner = insert(:user) - site = - insert(:site, - locked: false, - memberships: [build(:site_membership, user: existing_owner, role: :owner)] - ) + site = + insert(:site, + locked: false, + memberships: [build(:site_membership, user: existing_owner, role: :owner)] + ) - new_owner = insert(:user, trial_expiry_date: Date.add(Date.utc_today(), 7)) + new_owner = insert(:user, trial_expiry_date: Date.add(Date.utc_today(), 7)) - assert {:ok, _membership} = AcceptInvitation.transfer_ownership(site, new_owner) + assert {:ok, _membership} = AcceptInvitation.transfer_ownership(site, new_owner) - assert Repo.reload!(new_owner).trial_expiry_date == Date.add(Date.utc_today(), -1) - assert Repo.reload!(site).locked + assert Repo.reload!(new_owner).trial_expiry_date == Date.add(Date.utc_today(), -1) + assert Repo.reload!(site).locked + end end - test "sets user's trial expiry date to yesterday if they don't have one" do - existing_owner = insert(:user) + on_full_build do + test "sets user's trial expiry date to yesterday if they don't have one" do + existing_owner = insert(:user) - site = - insert(:site, - locked: false, - memberships: [build(:site_membership, user: existing_owner, role: :owner)] - ) + site = + insert(:site, + locked: false, + memberships: [build(:site_membership, user: existing_owner, role: :owner)] + ) - new_owner = insert(:user, trial_expiry_date: nil) + new_owner = insert(:user, trial_expiry_date: nil) - assert {:ok, _membership} = AcceptInvitation.transfer_ownership(site, new_owner) + assert {:ok, _membership} = AcceptInvitation.transfer_ownership(site, new_owner) - assert Repo.reload!(new_owner).trial_expiry_date == Date.add(Date.utc_today(), -1) - assert Repo.reload!(site).locked + assert Repo.reload!(new_owner).trial_expiry_date == Date.add(Date.utc_today(), -1) + assert Repo.reload!(site).locked + end end - test "ends grace period and sends an email about it if new owner is past grace period" do - existing_owner = insert(:user) + on_full_build do + test "ends grace period and sends an email about it if new owner is past grace period" do + existing_owner = insert(:user) - site = - insert(:site, - locked: false, - memberships: [build(:site_membership, user: existing_owner, role: :owner)] - ) + site = + insert(:site, + locked: false, + memberships: [build(:site_membership, user: existing_owner, role: :owner)] + ) - new_owner = insert(:user, trial_expiry_date: Date.add(Date.utc_today(), -1)) - insert(:subscription, user: new_owner, next_bill_date: Timex.today()) + new_owner = insert(:user, trial_expiry_date: Date.add(Date.utc_today(), -1)) + insert(:subscription, user: new_owner, next_bill_date: Timex.today()) - new_owner = - new_owner - |> Plausible.Auth.GracePeriod.start_changeset(100) - |> then(fn changeset -> - grace_period = - changeset - |> get_field(:grace_period) - |> Map.put(:end_date, Date.add(Date.utc_today(), -1)) + new_owner = + new_owner + |> Plausible.Auth.GracePeriod.start_changeset(100) + |> then(fn changeset -> + grace_period = + changeset + |> get_field(:grace_period) + |> Map.put(:end_date, Date.add(Date.utc_today(), -1)) - change(changeset, grace_period: grace_period) - end) - |> Repo.update!() + change(changeset, grace_period: grace_period) + end) + |> Repo.update!() - assert {:ok, _membership} = AcceptInvitation.transfer_ownership(site, new_owner) + assert {:ok, _membership} = AcceptInvitation.transfer_ownership(site, new_owner) - assert Repo.reload!(new_owner).grace_period.is_over - assert Repo.reload!(site).locked + assert Repo.reload!(new_owner).grace_period.is_over + assert Repo.reload!(site).locked - assert_email_delivered_with( - to: [{"Jane Smith", new_owner.email}], - subject: "[Action required] Your Plausible dashboard is now locked" - ) + assert_email_delivered_with( + to: [{"Jane Smith", new_owner.email}], + subject: "[Action required] Your Plausible dashboard is now locked" + ) + end end end diff --git a/test/plausible_web/controllers/api/stats_controller/funnels_test.exs b/test/plausible_web/controllers/api/stats_controller/funnels_test.exs index 1224b8315..f73a3f728 100644 --- a/test/plausible_web/controllers/api/stats_controller/funnels_test.exs +++ b/test/plausible_web/controllers/api/stats_controller/funnels_test.exs @@ -1,308 +1,314 @@ defmodule PlausibleWeb.Api.StatsController.FunnelsTest do use PlausibleWeb.ConnCase, async: true - - @user_id 123 - @other_user_id 456 - - @build_funnel_with [ - {"page_path", "/blog/announcement"}, - {"event_name", "Signup"}, - {"page_path", "/cart/add/product"}, - {"event_name", "Purchase"} - ] - - describe "GET /api/stats/funnel - default" do - setup [:create_user, :log_in, :create_new_site] - - test "computes funnel for a day", %{conn: conn, site: site} do - {:ok, funnel} = setup_funnel(site, @build_funnel_with) - - populate_stats(site, [ - build(:pageview, pathname: "/some/irrelevant", user_id: 9_999_999), - build(:pageview, pathname: "/blog/announcement", user_id: @user_id), - build(:pageview, pathname: "/blog/announcement", user_id: @other_user_id), - build(:event, name: "Signup", user_id: @user_id), - build(:event, name: "Signup", user_id: @other_user_id), - build(:pageview, pathname: "/cart/add/product", user_id: @user_id), - build(:event, name: "Purchase", user_id: @user_id) - ]) - - resp = - conn - |> get("/api/stats/#{site.domain}/funnels/#{funnel.id}/?period=day") - |> json_response(200) - - assert %{ - "name" => "Test funnel", - "all_visitors" => 3, - "entering_visitors" => 2, - "entering_visitors_percentage" => "66.67", - "never_entering_visitors" => 1, - "never_entering_visitors_percentage" => "33.33", - "steps" => [ - %{ - "conversion_rate" => "100", - "conversion_rate_step" => "0", - "dropoff" => 0, - "dropoff_percentage" => "0", - "label" => "Visit /blog/announcement", - "visitors" => 2 - }, - %{ - "conversion_rate" => "100", - "conversion_rate_step" => "100", - "dropoff" => 0, - "dropoff_percentage" => "0", - "label" => "Signup", - "visitors" => 2 - }, - %{ - "conversion_rate" => "50", - "conversion_rate_step" => "50", - "dropoff" => 1, - "dropoff_percentage" => "50", - "label" => "Visit /cart/add/product", - "visitors" => 1 - }, - %{ - "conversion_rate" => "50", - "conversion_rate_step" => "100", - "dropoff" => 0, - "dropoff_percentage" => "0", - "label" => "Purchase", - "visitors" => 1 - } - ] - } = resp - end - - test "404 for unknown funnel", %{site: site, conn: conn} do - resp = - conn - |> get("/api/stats/#{site.domain}/funnels/122873/?period=day") - |> json_response(404) - - assert resp == %{"error" => "Funnel not found"} - end - - test "400 for bad funnel ID", %{site: site, conn: conn} do - resp = - conn - |> get("/api/stats/#{site.domain}/funnels/foobar/?period=day") - |> json_response(400) - - assert resp == %{"error" => "There was an error with your request"} + use Plausible + @moduletag :full_build_only + + on_full_build do + @user_id 123 + @other_user_id 456 + + @build_funnel_with [ + {"page_path", "/blog/announcement"}, + {"event_name", "Signup"}, + {"page_path", "/cart/add/product"}, + {"event_name", "Purchase"} + ] + + describe "GET /api/stats/funnel - default" do + setup [:create_user, :log_in, :create_new_site] + + test "computes funnel for a day", %{conn: conn, site: site} do + {:ok, funnel} = setup_funnel(site, @build_funnel_with) + + populate_stats(site, [ + build(:pageview, pathname: "/some/irrelevant", user_id: 9_999_999), + build(:pageview, pathname: "/blog/announcement", user_id: @user_id), + build(:pageview, pathname: "/blog/announcement", user_id: @other_user_id), + build(:event, name: "Signup", user_id: @user_id), + build(:event, name: "Signup", user_id: @other_user_id), + build(:pageview, pathname: "/cart/add/product", user_id: @user_id), + build(:event, name: "Purchase", user_id: @user_id) + ]) + + resp = + conn + |> get("/api/stats/#{site.domain}/funnels/#{funnel.id}/?period=day") + |> json_response(200) + + assert %{ + "name" => "Test funnel", + "all_visitors" => 3, + "entering_visitors" => 2, + "entering_visitors_percentage" => "66.67", + "never_entering_visitors" => 1, + "never_entering_visitors_percentage" => "33.33", + "steps" => [ + %{ + "conversion_rate" => "100", + "conversion_rate_step" => "0", + "dropoff" => 0, + "dropoff_percentage" => "0", + "label" => "Visit /blog/announcement", + "visitors" => 2 + }, + %{ + "conversion_rate" => "100", + "conversion_rate_step" => "100", + "dropoff" => 0, + "dropoff_percentage" => "0", + "label" => "Signup", + "visitors" => 2 + }, + %{ + "conversion_rate" => "50", + "conversion_rate_step" => "50", + "dropoff" => 1, + "dropoff_percentage" => "50", + "label" => "Visit /cart/add/product", + "visitors" => 1 + }, + %{ + "conversion_rate" => "50", + "conversion_rate_step" => "100", + "dropoff" => 0, + "dropoff_percentage" => "0", + "label" => "Purchase", + "visitors" => 1 + } + ] + } = resp + end + + test "404 for unknown funnel", %{site: site, conn: conn} do + resp = + conn + |> get("/api/stats/#{site.domain}/funnels/122873/?period=day") + |> json_response(404) + + assert resp == %{"error" => "Funnel not found"} + end + + test "400 for bad funnel ID", %{site: site, conn: conn} do + resp = + conn + |> get("/api/stats/#{site.domain}/funnels/foobar/?period=day") + |> json_response(400) + + assert resp == %{"error" => "There was an error with your request"} + end + + test "computes all-time funnel with filters", %{conn: conn, user: user} do + site = insert(:site, stats_start_date: ~D[2020-01-01], members: [user]) + {:ok, funnel} = setup_funnel(site, @build_funnel_with) + + populate_stats(site, [ + build(:pageview, pathname: "/blog/announcement", user_id: @user_id), + build(:pageview, + pathname: "/blog/announcement", + user_id: @other_user_id, + utm_medium: "social", + timestamp: ~N[2021-01-01 12:00:00] + ), + build(:event, name: "Signup", user_id: @user_id), + build(:event, + name: "Signup", + user_id: @other_user_id, + utm_medium: "social", + timestamp: ~N[2021-01-01 12:01:00] + ), + build(:pageview, pathname: "/cart/add/product", user_id: @user_id), + build(:event, name: "Purchase", user_id: @user_id) + ]) + + filters = Jason.encode!(%{utm_medium: "social"}) + + resp = + conn + |> get("/api/stats/#{site.domain}/funnels/#{funnel.id}/?period=all&filters=#{filters}") + |> json_response(200) + + assert %{ + "name" => "Test funnel", + "all_visitors" => 1, + "entering_visitors" => 1, + "entering_visitors_percentage" => "100", + "never_entering_visitors" => 0, + "never_entering_visitors_percentage" => "0", + "steps" => [ + %{ + "conversion_rate" => "100", + "conversion_rate_step" => "0", + "dropoff" => 0, + "dropoff_percentage" => "0", + "label" => "Visit /blog/announcement", + "visitors" => 1 + }, + %{ + "conversion_rate" => "100", + "conversion_rate_step" => "100", + "dropoff" => 0, + "dropoff_percentage" => "0", + "label" => "Signup", + "visitors" => 1 + }, + %{ + "conversion_rate" => "0", + "conversion_rate_step" => "0", + "dropoff" => 1, + "dropoff_percentage" => "100", + "label" => "Visit /cart/add/product", + "visitors" => 0 + }, + %{ + "conversion_rate" => "0", + "conversion_rate_step" => "0", + "dropoff" => 0, + "dropoff_percentage" => "0", + "label" => "Purchase", + "visitors" => 0 + } + ] + } = resp + end + + test "computes an empty funnel", %{conn: conn, site: site} do + {:ok, funnel} = setup_funnel(site, @build_funnel_with) + + resp = + conn + |> get("/api/stats/#{site.domain}/funnels/#{funnel.id}/?period=day") + |> json_response(200) + + assert %{ + "name" => "Test funnel", + "all_visitors" => 0, + "entering_visitors" => 0, + "entering_visitors_percentage" => "0", + "never_entering_visitors" => 0, + "never_entering_visitors_percentage" => "0", + "steps" => [ + %{ + "conversion_rate" => "0", + "conversion_rate_step" => "0", + "dropoff" => 0, + "dropoff_percentage" => "0", + "label" => "Visit /blog/announcement", + "visitors" => 0 + }, + %{ + "conversion_rate" => "0", + "conversion_rate_step" => "0", + "dropoff" => 0, + "dropoff_percentage" => "0", + "label" => "Signup", + "visitors" => 0 + }, + %{ + "conversion_rate" => "0", + "conversion_rate_step" => "0", + "dropoff" => 0, + "dropoff_percentage" => "0", + "label" => "Visit /cart/add/product", + "visitors" => 0 + }, + %{ + "conversion_rate" => "0", + "conversion_rate_step" => "0", + "dropoff" => 0, + "dropoff_percentage" => "0", + "label" => "Purchase", + "visitors" => 0 + } + ] + } = resp + end + + test "returns HTTP 402 when site owner is on a growth plan", %{ + conn: conn, + user: user, + site: site + } do + insert(:growth_subscription, user: user) + {:ok, funnel} = setup_funnel(site, @build_funnel_with) + + resp = + conn + |> get("/api/stats/#{site.domain}/funnels/#{funnel.id}/?period=day") + |> json_response(402) + + assert %{ + "error" => + "Funnels is part of the Plausible Business plan. To get access to this feature, please upgrade your account." + } == resp + end end - test "computes all-time funnel with filters", %{conn: conn, user: user} do - site = insert(:site, stats_start_date: ~D[2020-01-01], members: [user]) - {:ok, funnel} = setup_funnel(site, @build_funnel_with) - - populate_stats(site, [ - build(:pageview, pathname: "/blog/announcement", user_id: @user_id), - build(:pageview, - pathname: "/blog/announcement", - user_id: @other_user_id, - utm_medium: "social", - timestamp: ~N[2021-01-01 12:00:00] - ), - build(:event, name: "Signup", user_id: @user_id), - build(:event, - name: "Signup", - user_id: @other_user_id, - utm_medium: "social", - timestamp: ~N[2021-01-01 12:01:00] - ), - build(:pageview, pathname: "/cart/add/product", user_id: @user_id), - build(:event, name: "Purchase", user_id: @user_id) - ]) - - filters = Jason.encode!(%{utm_medium: "social"}) - - resp = - conn - |> get("/api/stats/#{site.domain}/funnels/#{funnel.id}/?period=all&filters=#{filters}") - |> json_response(200) - - assert %{ - "name" => "Test funnel", - "all_visitors" => 1, - "entering_visitors" => 1, - "entering_visitors_percentage" => "100", - "never_entering_visitors" => 0, - "never_entering_visitors_percentage" => "0", - "steps" => [ - %{ - "conversion_rate" => "100", - "conversion_rate_step" => "0", - "dropoff" => 0, - "dropoff_percentage" => "0", - "label" => "Visit /blog/announcement", - "visitors" => 1 - }, - %{ - "conversion_rate" => "100", - "conversion_rate_step" => "100", - "dropoff" => 0, - "dropoff_percentage" => "0", - "label" => "Signup", - "visitors" => 1 - }, - %{ - "conversion_rate" => "0", - "conversion_rate_step" => "0", - "dropoff" => 1, - "dropoff_percentage" => "100", - "label" => "Visit /cart/add/product", - "visitors" => 0 - }, - %{ - "conversion_rate" => "0", - "conversion_rate_step" => "0", - "dropoff" => 0, - "dropoff_percentage" => "0", - "label" => "Purchase", - "visitors" => 0 - } - ] - } = resp + describe "GET /api/stats/funnel - disallowed filters" do + setup [:create_user, :log_in, :create_new_site] + + test "event:page", %{conn: conn, site: site} do + {:ok, funnel} = setup_funnel(site, @build_funnel_with) + + filters = Jason.encode!(%{page: "/pageA"}) + + resp = + conn + |> get("/api/stats/#{site.domain}/funnels/#{funnel.id}/?period=day&filters=#{filters}") + |> json_response(400) + + assert resp == %{ + "error" => + "We are unable to show funnels when the dashboard is filtered by pages", + "level" => "normal" + } + end + + test "event:goal", %{conn: conn, site: site} do + {:ok, funnel} = setup_funnel(site, @build_funnel_with) + + filters = Jason.encode!(%{goal: "Signup", page: "/pageA"}) + + resp = + conn + |> get("/api/stats/#{site.domain}/funnels/#{funnel.id}/?period=day&filters=#{filters}") + |> json_response(400) + + assert resp == %{ + "error" => + "We are unable to show funnels when the dashboard is filtered by goals", + "level" => "normal" + } + end + + test "period: realtime", %{conn: conn, site: site} do + {:ok, funnel} = setup_funnel(site, @build_funnel_with) + + resp = + conn + |> get("/api/stats/#{site.domain}/funnels/#{funnel.id}/?period=realtime") + |> json_response(400) + + assert resp == %{ + "error" => + "We are unable to show funnels when the dashboard is filtered by realtime period", + "level" => "normal" + } + end end - test "computes an empty funnel", %{conn: conn, site: site} do - {:ok, funnel} = setup_funnel(site, @build_funnel_with) - - resp = - conn - |> get("/api/stats/#{site.domain}/funnels/#{funnel.id}/?period=day") - |> json_response(200) - - assert %{ - "name" => "Test funnel", - "all_visitors" => 0, - "entering_visitors" => 0, - "entering_visitors_percentage" => "0", - "never_entering_visitors" => 0, - "never_entering_visitors_percentage" => "0", - "steps" => [ - %{ - "conversion_rate" => "0", - "conversion_rate_step" => "0", - "dropoff" => 0, - "dropoff_percentage" => "0", - "label" => "Visit /blog/announcement", - "visitors" => 0 - }, - %{ - "conversion_rate" => "0", - "conversion_rate_step" => "0", - "dropoff" => 0, - "dropoff_percentage" => "0", - "label" => "Signup", - "visitors" => 0 - }, - %{ - "conversion_rate" => "0", - "conversion_rate_step" => "0", - "dropoff" => 0, - "dropoff_percentage" => "0", - "label" => "Visit /cart/add/product", - "visitors" => 0 - }, - %{ - "conversion_rate" => "0", - "conversion_rate_step" => "0", - "dropoff" => 0, - "dropoff_percentage" => "0", - "label" => "Purchase", - "visitors" => 0 - } - ] - } = resp - end + defp setup_goals(site, goals) when is_list(goals) do + goals = + Enum.map(goals, fn {type, value} -> + {:ok, g} = Plausible.Goals.create(site, %{type => value}) + g + end) - test "returns HTTP 402 when site owner is on a growth plan", %{ - conn: conn, - user: user, - site: site - } do - insert(:growth_subscription, user: user) - {:ok, funnel} = setup_funnel(site, @build_funnel_with) - - resp = - conn - |> get("/api/stats/#{site.domain}/funnels/#{funnel.id}/?period=day") - |> json_response(402) - - assert %{ - "error" => - "Funnels is part of the Plausible Business plan. To get access to this feature, please upgrade your account." - } == resp + {:ok, goals} end - end - - describe "GET /api/stats/funnel - disallowed filters" do - setup [:create_user, :log_in, :create_new_site] - - test "event:page", %{conn: conn, site: site} do - {:ok, funnel} = setup_funnel(site, @build_funnel_with) - filters = Jason.encode!(%{page: "/pageA"}) - - resp = - conn - |> get("/api/stats/#{site.domain}/funnels/#{funnel.id}/?period=day&filters=#{filters}") - |> json_response(400) - - assert resp == %{ - "error" => "We are unable to show funnels when the dashboard is filtered by pages", - "level" => "normal" - } + defp setup_funnel(site, goal_names) do + {:ok, goals} = setup_goals(site, goal_names) + Plausible.Funnels.create(site, "Test funnel", Enum.map(goals, &%{"goal_id" => &1.id})) end - - test "event:goal", %{conn: conn, site: site} do - {:ok, funnel} = setup_funnel(site, @build_funnel_with) - - filters = Jason.encode!(%{goal: "Signup", page: "/pageA"}) - - resp = - conn - |> get("/api/stats/#{site.domain}/funnels/#{funnel.id}/?period=day&filters=#{filters}") - |> json_response(400) - - assert resp == %{ - "error" => "We are unable to show funnels when the dashboard is filtered by goals", - "level" => "normal" - } - end - - test "period: realtime", %{conn: conn, site: site} do - {:ok, funnel} = setup_funnel(site, @build_funnel_with) - - resp = - conn - |> get("/api/stats/#{site.domain}/funnels/#{funnel.id}/?period=realtime") - |> json_response(400) - - assert resp == %{ - "error" => - "We are unable to show funnels when the dashboard is filtered by realtime period", - "level" => "normal" - } - end - end - - defp setup_goals(site, goals) when is_list(goals) do - goals = - Enum.map(goals, fn {type, value} -> - {:ok, g} = Plausible.Goals.create(site, %{type => value}) - g - end) - - {:ok, goals} - end - - defp setup_funnel(site, goal_names) do - {:ok, goals} = setup_goals(site, goal_names) - Plausible.Funnels.create(site, "Test funnel", Enum.map(goals, &%{"goal_id" => &1.id})) end end diff --git a/test/plausible_web/live/funnel_settings/form_test.exs b/test/plausible_web/live/funnel_settings/form_test.exs index 34854a216..9a1dbc729 100644 --- a/test/plausible_web/live/funnel_settings/form_test.exs +++ b/test/plausible_web/live/funnel_settings/form_test.exs @@ -1,5 +1,7 @@ defmodule PlausibleWeb.Live.FunnelSettings.FormTest do use PlausibleWeb.ConnCase, async: true + @moduletag :full_build_only + import Phoenix.LiveViewTest import Plausible.Test.Support.HTML diff --git a/test/plausible_web/live/funnel_settings_test.exs b/test/plausible_web/live/funnel_settings_test.exs index a1b73901f..00f2624c3 100644 --- a/test/plausible_web/live/funnel_settings_test.exs +++ b/test/plausible_web/live/funnel_settings_test.exs @@ -1,328 +1,333 @@ defmodule PlausibleWeb.Live.FunnelSettingsTest do use PlausibleWeb.ConnCase, async: true - import Phoenix.LiveViewTest - import Plausible.Test.Support.HTML - - describe "GET /:website/settings/funnels" do - setup [:create_user, :log_in, :create_site] - - test "lists funnels for the site and renders help link", %{conn: conn, site: site} do - {:ok, _} = setup_funnels(site) - conn = get(conn, "/#{site.domain}/settings/funnels") - - resp = html_response(conn, 200) - assert resp =~ "Compose Goals into Funnels" - assert resp =~ "From blog to signup" - assert resp =~ "From signup to blog" - assert element_exists?(resp, "a[href=\"https://plausible.io/docs/funnel-analysis\"]") - end - - test "search funnels input is rendered", %{conn: conn, site: site} do - setup_goals(site) - conn = get(conn, "/#{site.domain}/settings/funnels") - resp = html_response(conn, 200) - assert element_exists?(resp, ~s/input[type="text"]#filter-text/) - assert element_exists?(resp, ~s/form[phx-change="filter"]#filter-form/) - end - - test "lists funnels with delete actions", %{conn: conn, site: site} do - {:ok, [f1_id, f2_id]} = setup_funnels(site) - conn = get(conn, "/#{site.domain}/settings/funnels") - - resp = html_response(conn, 200) - - assert element_exists?( - resp, - ~s/button[phx-click="delete-funnel"][phx-value-funnel-id=#{f1_id}]#delete-funnel-#{f1_id}/ - ) - - assert element_exists?( - resp, - ~s/button[phx-click="delete-funnel"][phx-value-funnel-id=#{f2_id}]#delete-funnel-#{f2_id}/ - ) - end - - test "if goals are present, Add Funnel button is rendered", %{conn: conn, site: site} do - {:ok, _} = setup_funnels(site) - conn = get(conn, "/#{site.domain}/settings/funnels") - resp = conn |> html_response(200) - assert element_exists?(resp, ~S/button[phx-click="add-funnel"]/) + use Plausible + @moduletag :full_build_only + + on_full_build do + import Phoenix.LiveViewTest + import Plausible.Test.Support.HTML + + describe "GET /:website/settings/funnels" do + setup [:create_user, :log_in, :create_site] + + test "lists funnels for the site and renders help link", %{conn: conn, site: site} do + {:ok, _} = setup_funnels(site) + conn = get(conn, "/#{site.domain}/settings/funnels") + + resp = html_response(conn, 200) + assert resp =~ "Compose Goals into Funnels" + assert resp =~ "From blog to signup" + assert resp =~ "From signup to blog" + assert element_exists?(resp, "a[href=\"https://plausible.io/docs/funnel-analysis\"]") + end + + test "search funnels input is rendered", %{conn: conn, site: site} do + setup_goals(site) + conn = get(conn, "/#{site.domain}/settings/funnels") + resp = html_response(conn, 200) + assert element_exists?(resp, ~s/input[type="text"]#filter-text/) + assert element_exists?(resp, ~s/form[phx-change="filter"]#filter-form/) + end + + test "lists funnels with delete actions", %{conn: conn, site: site} do + {:ok, [f1_id, f2_id]} = setup_funnels(site) + conn = get(conn, "/#{site.domain}/settings/funnels") + + resp = html_response(conn, 200) + + assert element_exists?( + resp, + ~s/button[phx-click="delete-funnel"][phx-value-funnel-id=#{f1_id}]#delete-funnel-#{f1_id}/ + ) + + assert element_exists?( + resp, + ~s/button[phx-click="delete-funnel"][phx-value-funnel-id=#{f2_id}]#delete-funnel-#{f2_id}/ + ) + end + + test "if goals are present, Add Funnel button is rendered", %{conn: conn, site: site} do + {:ok, _} = setup_funnels(site) + conn = get(conn, "/#{site.domain}/settings/funnels") + resp = conn |> html_response(200) + assert element_exists?(resp, ~S/button[phx-click="add-funnel"]/) + end + + test "if not enough goals are present, renders a hint to create goals + no search", %{ + conn: conn, + site: site + } do + {:ok, _} = Plausible.Goals.create(site, %{"page_path" => "/go/to/blog/**"}) + conn = get(conn, "/#{site.domain}/settings/funnels") + + doc = conn |> html_response(200) + assert Floki.text(doc) =~ "You need to define at least two goals to create a funnel." + + add_goals_path = Routes.site_path(conn, :settings_goals, site.domain) + assert element_exists?(doc, ~s/a[href="#{add_goals_path}"]/) + + refute element_exists?(doc, ~s/input[type="text"]#filter-text/) + refute element_exists?(doc, ~s/form[phx-change="filter"]#filter-form/) + end end - test "if not enough goals are present, renders a hint to create goals + no search", %{ - conn: conn, - site: site - } do - {:ok, _} = Plausible.Goals.create(site, %{"page_path" => "/go/to/blog/**"}) - conn = get(conn, "/#{site.domain}/settings/funnels") - - doc = conn |> html_response(200) - assert Floki.text(doc) =~ "You need to define at least two goals to create a funnel." + describe "FunnelSettings live view" do + setup [:create_user, :log_in, :create_site] - add_goals_path = Routes.site_path(conn, :settings_goals, site.domain) - assert element_exists?(doc, ~s/a[href="#{add_goals_path}"]/) + test "allows list filtering / search", %{conn: conn, site: site} do + {:ok, _} = setup_funnels(site, ["Funnel One", "Search Me"]) + {lv, html} = get_liveview(conn, site, with_html?: true) - refute element_exists?(doc, ~s/input[type="text"]#filter-text/) - refute element_exists?(doc, ~s/form[phx-change="filter"]#filter-form/) - end - end + assert html =~ "Funnel One" + assert html =~ "Search Me" - describe "FunnelSettings live view" do - setup [:create_user, :log_in, :create_site] + html = type_into_search(lv, "search") - test "allows list filtering / search", %{conn: conn, site: site} do - {:ok, _} = setup_funnels(site, ["Funnel One", "Search Me"]) - {lv, html} = get_liveview(conn, site, with_html?: true) + refute html =~ "Funnel One" + assert html =~ "Search Me" + end - assert html =~ "Funnel One" - assert html =~ "Search Me" + test "allows resetting filter text via backspace icon", %{conn: conn, site: site} do + {:ok, _} = setup_funnels(site, ["Funnel One", "Another"]) + {lv, html} = get_liveview(conn, site, with_html?: true) - html = type_into_search(lv, "search") + refute element_exists?(html, ~s/svg[phx-click="reset-filter-text"]#reset-filter/) - refute html =~ "Funnel One" - assert html =~ "Search Me" - end + html = type_into_search(lv, "one") + refute html =~ "Another" - test "allows resetting filter text via backspace icon", %{conn: conn, site: site} do - {:ok, _} = setup_funnels(site, ["Funnel One", "Another"]) - {lv, html} = get_liveview(conn, site, with_html?: true) + assert element_exists?(html, ~s/svg[phx-click="reset-filter-text"]#reset-filter/) - refute element_exists?(html, ~s/svg[phx-click="reset-filter-text"]#reset-filter/) + html = lv |> element(~s/svg#reset-filter/) |> render_click() - html = type_into_search(lv, "one") - refute html =~ "Another" + assert html =~ "Funnel One" + assert html =~ "Another" + end - assert element_exists?(html, ~s/svg[phx-click="reset-filter-text"]#reset-filter/) + test "allows resetting filter text via no match link", %{conn: conn, site: site} do + {:ok, _} = setup_funnels(site) + lv = get_liveview(conn, site) + html = type_into_search(lv, "Definitely this is not going to render any matches") - html = lv |> element(~s/svg#reset-filter/) |> render_click() + assert html =~ "No funnels found for this site. Please refine or" + assert html =~ "reset your search" - assert html =~ "Funnel One" - assert html =~ "Another" - end - - test "allows resetting filter text via no match link", %{conn: conn, site: site} do - {:ok, _} = setup_funnels(site) - lv = get_liveview(conn, site) - html = type_into_search(lv, "Definitely this is not going to render any matches") - - assert html =~ "No funnels found for this site. Please refine or" - assert html =~ "reset your search" - - assert element_exists?(html, ~s/a[phx-click="reset-filter-text"]#reset-filter-hint/) - html = lv |> element(~s/a#reset-filter-hint/) |> render_click() - - refute html =~ "No funnels found for this site. Please refine or" - end + assert element_exists?(html, ~s/a[phx-click="reset-filter-text"]#reset-filter-hint/) + html = lv |> element(~s/a#reset-filter-hint/) |> render_click() - test "allows to delete funnels", %{conn: conn, site: site} do - {:ok, [f1_id, _f2_id]} = setup_funnels(site) + refute html =~ "No funnels found for this site. Please refine or" + end - {lv, html} = get_liveview(conn, site, with_html?: true) + test "allows to delete funnels", %{conn: conn, site: site} do + {:ok, [f1_id, _f2_id]} = setup_funnels(site) - assert html =~ "From blog to signup" - assert html =~ "From signup to blog" + {lv, html} = get_liveview(conn, site, with_html?: true) - html = lv |> element(~s/button#delete-funnel-#{f1_id}/) |> render_click() + assert html =~ "From blog to signup" + assert html =~ "From signup to blog" - refute html =~ "From blog to signup" - assert html =~ "From signup to blog" + html = lv |> element(~s/button#delete-funnel-#{f1_id}/) |> render_click() - html = get(conn, "/#{site.domain}/settings/funnels") |> html_response(200) + refute html =~ "From blog to signup" + assert html =~ "From signup to blog" - refute html =~ "From blog to signup" - assert html =~ "From signup to blog" - end + html = get(conn, "/#{site.domain}/settings/funnels") |> html_response(200) - test "renders the funnel form on clicking 'Add Funnel' button", %{conn: conn, site: site} do - setup_goals(site) - lv = get_liveview(conn, site) - doc = render_click(lv, "add-funnel") + refute html =~ "From blog to signup" + assert html =~ "From signup to blog" + end - assert element_exists?( - doc, - ~s/form[phx-change="validate"][phx-submit="save"][phx-click-away="cancel-add-funnel"]/ - ) + test "renders the funnel form on clicking 'Add Funnel' button", %{conn: conn, site: site} do + setup_goals(site) + lv = get_liveview(conn, site) + doc = render_click(lv, "add-funnel") - assert element_exists?(doc, ~s/form input[type="text"][name="funnel[name]"]/) + assert element_exists?( + doc, + ~s/form[phx-change="validate"][phx-submit="save"][phx-click-away="cancel-add-funnel"]/ + ) - assert element_exists?( - doc, - ~s/input[type="hidden"][name="funnel[steps][][goal_id]"]#submit-step-1/ - ) + assert element_exists?(doc, ~s/form input[type="text"][name="funnel[name]"]/) - step_setup_controls = [ - ~s/input[type="hidden"][name="funnel[steps][][goal_id]"]#submit-step-1/, - ~s/input[type="hidden"][name="funnel[steps][][goal_id]"]#submit-step-2/, - ~s/input[type="text"][name="display-step-1"]#step-1/, - ~s/input[type="text"][name="display-step-2"]#step-2/, - ~s/a[phx-click="add-step"]/ - ] + assert element_exists?( + doc, + ~s/input[type="hidden"][name="funnel[steps][][goal_id]"]#submit-step-1/ + ) - Enum.each(step_setup_controls, &assert(element_exists?(doc, &1))) - end + step_setup_controls = [ + ~s/input[type="hidden"][name="funnel[steps][][goal_id]"]#submit-step-1/, + ~s/input[type="hidden"][name="funnel[steps][][goal_id]"]#submit-step-2/, + ~s/input[type="text"][name="display-step-1"]#step-1/, + ~s/input[type="text"][name="display-step-2"]#step-2/, + ~s/a[phx-click="add-step"]/ + ] - test "clicking 'Add another step' adds a pair of inputs and renders remove step buttons", %{ - conn: conn, - site: site - } do - setup_goals(site) - lv = get_liveview(conn, site) + Enum.each(step_setup_controls, &assert(element_exists?(doc, &1))) + end - lv |> element(~s/button[phx-click="add-funnel"]/) |> render_click() + test "clicking 'Add another step' adds a pair of inputs and renders remove step buttons", %{ + conn: conn, + site: site + } do + setup_goals(site) + lv = get_liveview(conn, site) - assert lv = find_live_child(lv, "funnels-form") - lv |> element("form") |> render_change(%{funnel: %{name: "My test funnel"}}) - doc = lv |> element(~s/a[phx-click="add-step"]/) |> render_click() + lv |> element(~s/button[phx-click="add-funnel"]/) |> render_click() - assert element_exists?( - doc, - ~s/input[type="hidden"][name="funnel[steps][][goal_id]"]#submit-step-3/ - ) + assert lv = find_live_child(lv, "funnels-form") + lv |> element("form") |> render_change(%{funnel: %{name: "My test funnel"}}) + doc = lv |> element(~s/a[phx-click="add-step"]/) |> render_click() - assert element_exists?(doc, ~s/input[type="text"][name="display-step-1"]#step-1/) + assert element_exists?( + doc, + ~s/input[type="hidden"][name="funnel[steps][][goal_id]"]#submit-step-3/ + ) - assert element_exists?( - doc, - ~s/svg#remove-step-1[phx-click="remove-step"][phx-value-step-idx="1"]/ - ) + assert element_exists?(doc, ~s/input[type="text"][name="display-step-1"]#step-1/) - assert element_exists?( - doc, - ~s/svg#remove-step-2[phx-click="remove-step"][phx-value-step-idx="2"]/ - ) + assert element_exists?( + doc, + ~s/svg#remove-step-1[phx-click="remove-step"][phx-value-step-idx="1"]/ + ) - assert element_exists?( - doc, - ~s/svg#remove-step-3[phx-click="remove-step"][phx-value-step-idx="3"]/ - ) - end + assert element_exists?( + doc, + ~s/svg#remove-step-2[phx-click="remove-step"][phx-value-step-idx="2"]/ + ) - test "clicking the 'remove step' button removes a step", %{site: site, conn: conn} do - setup_goals(site) - lv = get_liveview(conn, site) + assert element_exists?( + doc, + ~s/svg#remove-step-3[phx-click="remove-step"][phx-value-step-idx="3"]/ + ) + end - lv |> element(~s/button[phx-click="add-funnel"]/) |> render_click() - assert lv = find_live_child(lv, "funnels-form") - lv |> element("form") |> render_change(%{funnel: %{name: "My test funnel"}}) - lv |> element(~s/a[phx-click="add-step"]/) |> render_click() + test "clicking the 'remove step' button removes a step", %{site: site, conn: conn} do + setup_goals(site) + lv = get_liveview(conn, site) - doc = lv |> element(~s/#remove-step-2/) |> render_click() + lv |> element(~s/button[phx-click="add-funnel"]/) |> render_click() + assert lv = find_live_child(lv, "funnels-form") + lv |> element("form") |> render_change(%{funnel: %{name: "My test funnel"}}) + lv |> element(~s/a[phx-click="add-step"]/) |> render_click() - assert element_exists?(doc, ~s/input#step-1/) - assert element_exists?(doc, ~s/input#step-3/) - refute element_exists?(doc, ~s/input#step-2/) - end + doc = lv |> element(~s/#remove-step-2/) |> render_click() - test "save button becomes active once at least two steps are selected", %{ - conn: conn, - site: site - } do - setup_goals(site) - lv = get_liveview(conn, site) - lv |> element(~s/button[phx-click="add-funnel"]/) |> render_click() + assert element_exists?(doc, ~s/input#step-1/) + assert element_exists?(doc, ~s/input#step-3/) + refute element_exists?(doc, ~s/input#step-2/) + end - assert lv = find_live_child(lv, "funnels-form") + test "save button becomes active once at least two steps are selected", %{ + conn: conn, + site: site + } do + setup_goals(site) + lv = get_liveview(conn, site) + lv |> element(~s/button[phx-click="add-funnel"]/) |> render_click() - lv - |> element("li#dropdown-step-1-option-1 a") - |> render_click() + assert lv = find_live_child(lv, "funnels-form") - doc = lv - |> element("li#dropdown-step-2-option-1 a") + |> element("li#dropdown-step-1-option-1 a") |> render_click() - assert element_exists?(doc, ~s/form button#save:disabled/) - - doc = - lv - |> element("form") - |> render_change(%{ - funnel: %{ - name: "My test funnel", - steps: [ - %{goal_id: 1}, - %{goal_id: 2} - ] - } - }) - - assert element_exists?(doc, ~s/form button#save/) - refute element_exists?(doc, ~s/form button#save:disabled/) + doc = + lv + |> element("li#dropdown-step-2-option-1 a") + |> render_click() + + assert element_exists?(doc, ~s/form button#save:disabled/) + + doc = + lv + |> element("form") + |> render_change(%{ + funnel: %{ + name: "My test funnel", + steps: [ + %{goal_id: 1}, + %{goal_id: 2} + ] + } + }) + + assert element_exists?(doc, ~s/form button#save/) + refute element_exists?(doc, ~s/form button#save:disabled/) + end + + @tag :slow + test "funnel gets evaluated on every select, assuming a second has passed between selections", + %{ + conn: conn, + site: site + } do + setup_goals(site) + lv = get_liveview(conn, site) + lv |> element(~s/button[phx-click="add-funnel"]/) |> render_click() + + assert lv = find_live_child(lv, "funnels-form") + + lv |> element("li#dropdown-step-1-option-1 a") |> render_click() + + :timer.sleep(1001) + + lv |> element("li#dropdown-step-2-option-1 a") |> render_click() + + doc = lv |> element("#step-eval-0") |> render() + assert text_of_element(doc, ~s/#step-eval-0/) =~ "Entering Visitors: 0" + + doc = lv |> element("#step-eval-1") |> render() + assert text_of_element(doc, ~s/#step-eval-1/) =~ "Dropoff: 0%" + + doc = lv |> element("#funnel-eval") |> render() + assert text_of_element(doc, ~s/#funnel-eval/) =~ "Last month conversion rate: 0%" + end end - @tag :slow - test "funnel gets evaluated on every select, assuming a second has passed between selections", - %{ - conn: conn, - site: site - } do - setup_goals(site) - lv = get_liveview(conn, site) - lv |> element(~s/button[phx-click="add-funnel"]/) |> render_click() - - assert lv = find_live_child(lv, "funnels-form") - - lv |> element("li#dropdown-step-1-option-1 a") |> render_click() - - :timer.sleep(1001) - - lv |> element("li#dropdown-step-2-option-1 a") |> render_click() + defp setup_funnels(site, names \\ []) do + {:ok, [g1, g2]} = setup_goals(site) - doc = lv |> element("#step-eval-0") |> render() - assert text_of_element(doc, ~s/#step-eval-0/) =~ "Entering Visitors: 0" + {:ok, f1} = + Plausible.Funnels.create( + site, + Enum.at(names, 0) || "From blog to signup", + [%{"goal_id" => g1.id}, %{"goal_id" => g2.id}] + ) - doc = lv |> element("#step-eval-1") |> render() - assert text_of_element(doc, ~s/#step-eval-1/) =~ "Dropoff: 0%" + {:ok, f2} = + Plausible.Funnels.create( + site, + Enum.at(names, 1) || "From signup to blog", + [%{"goal_id" => g2.id}, %{"goal_id" => g1.id}] + ) - doc = lv |> element("#funnel-eval") |> render() - assert text_of_element(doc, ~s/#funnel-eval/) =~ "Last month conversion rate: 0%" + {:ok, [f1.id, f2.id]} end - end - - defp setup_funnels(site, names \\ []) do - {:ok, [g1, g2]} = setup_goals(site) - - {:ok, f1} = - Plausible.Funnels.create( - site, - Enum.at(names, 0) || "From blog to signup", - [%{"goal_id" => g1.id}, %{"goal_id" => g2.id}] - ) - {:ok, f2} = - Plausible.Funnels.create( - site, - Enum.at(names, 1) || "From signup to blog", - [%{"goal_id" => g2.id}, %{"goal_id" => g1.id}] - ) + defp setup_goals(site) do + {:ok, g1} = Plausible.Goals.create(site, %{"page_path" => "/go/to/blog/**"}) + {:ok, g2} = Plausible.Goals.create(site, %{"event_name" => "Signup"}) + {:ok, [g1, g2]} + end - {:ok, [f1.id, f2.id]} - end + defp get_liveview(conn, site, opts \\ []) do + conn = assign(conn, :live_module, PlausibleWeb.Live.FunnelSettings) + {:ok, lv, html} = live(conn, "/#{site.domain}/settings/funnels") - defp setup_goals(site) do - {:ok, g1} = Plausible.Goals.create(site, %{"page_path" => "/go/to/blog/**"}) - {:ok, g2} = Plausible.Goals.create(site, %{"event_name" => "Signup"}) - {:ok, [g1, g2]} - end - - defp get_liveview(conn, site, opts \\ []) do - conn = assign(conn, :live_module, PlausibleWeb.Live.FunnelSettings) - {:ok, lv, html} = live(conn, "/#{site.domain}/settings/funnels") + if Keyword.get(opts, :with_html?) do + {lv, html} + else + lv + end + end - if Keyword.get(opts, :with_html?) do - {lv, html} - else + defp type_into_search(lv, text) do lv + |> element("form#filter-form") + |> render_change(%{ + "_target" => ["filter-text"], + "filter-text" => "#{text}" + }) end end - - defp type_into_search(lv, text) do - lv - |> element("form#filter-form") - |> render_change(%{ - "_target" => ["filter-text"], - "filter-text" => "#{text}" - }) - end end diff --git a/test/plausible_web/live/goal_settings_test.exs b/test/plausible_web/live/goal_settings_test.exs index a0d613498..f97d76ec4 100644 --- a/test/plausible_web/live/goal_settings_test.exs +++ b/test/plausible_web/live/goal_settings_test.exs @@ -6,6 +6,7 @@ defmodule PlausibleWeb.Live.GoalSettingsTest do describe "GET /:website/settings/goals" do setup [:create_user, :log_in, :create_site] + @tag :full_build_only test "lists goals for the site and renders links", %{conn: conn, site: site} do {:ok, [g1, g2, g3]} = setup_goals(site) conn = get(conn, "/#{site.domain}/settings/goals") diff --git a/test/support/html.ex b/test/support/html.ex index 357f53459..7d6eda93d 100644 --- a/test/support/html.ex +++ b/test/support/html.ex @@ -1,4 +1,6 @@ defmodule Plausible.Test.Support.HTML do + Code.ensure_compiled!(Floki) + @moduledoc """ Floki wrappers to help make assertions about HTML/DOM structures """ diff --git a/test/test_helper.exs b/test/test_helper.exs index 822e02d9e..68ecf5e1c 100644 --- a/test/test_helper.exs +++ b/test/test_helper.exs @@ -4,4 +4,9 @@ Application.ensure_all_started(:double) FunWithFlags.enable(:business_tier) FunWithFlags.enable(:window_time_on_page) Ecto.Adapters.SQL.Sandbox.mode(Plausible.Repo, :manual) -ExUnit.configure(exclude: [:slow]) + +if Mix.env() == :small_test do + ExUnit.configure(exclude: [:slow, :full_build_only]) +else + ExUnit.configure(exclude: [:slow, :small_build_only]) +end