Skip to content

Open source, privacy-first web analytics. Lightweight, cookie-free Google Analytics alternative. Self-hosted or cloud.

Goals with custom props (settings+filtering UI integration) (#5977)

Adam Rutkowski3355b5fb7482
diff --git a/lib/plausible/goal.ex b/lib/plausible/goal.ex
index 44ba3ae7cf..51fb732b89 100644
--- a/lib/plausible/goal.ex
+++ b/lib/plausible/goal.ex
@@ -71,6 +71,7 @@ defmodule Plausible.Goal do
message: "cannot co-exist with page_path"
)
|> maybe_drop_currency()
+ |> prevent_currency_change()
end
@spec display_name(t()) :: String.t()
@@ -87,6 +88,14 @@ defmodule Plausible.Goal do
end
end
+ @spec has_custom_props?(t()) :: boolean()
+ def has_custom_props?(%__MODULE__{custom_props: custom_props})
+ when map_size(custom_props) > 0 do
+ true
+ end
+
+ def has_custom_props?(_), do: false
+
defp update_leading_slash(changeset) do
case get_field(changeset, :page_path) do
"/" <> _ ->
@@ -160,6 +169,14 @@ defmodule Plausible.Goal do
end
end
+ defp prevent_currency_change(changeset) do
+ if (ee?() and changeset.data.id) && Map.has_key?(changeset.changes, :currency) do
+ add_error(changeset, :currency, "cannot change currency of existing goal")
+ else
+ changeset
+ end
+ end
+
defp maybe_put_display_name(changeset) do
clause =
Enum.map([:display_name, :page_path, :event_name], &get_field(changeset, &1))
diff --git a/lib/plausible/goals/goals.ex b/lib/plausible/goals/goals.ex
index 9f7af75431..d6d3db86a1 100644
--- a/lib/plausible/goals/goals.ex
+++ b/lib/plausible/goals/goals.ex
@@ -181,6 +181,13 @@ defmodule Plausible.Goals do
query
end
+ query =
+ if Keyword.get(opts, :include_goals_with_custom_props?, true) == false do
+ from g in query, where: g.custom_props == ^%{}
+ else
+ query
+ end
+
if ee?() and opts[:preload_funnels?] == true do
from(g in query,
left_join: assoc(g, :funnels),
diff --git a/lib/plausible/stats/filter_suggestions.ex b/lib/plausible/stats/filter_suggestions.ex
index dd1da7355b..e890c7f36b 100644
--- a/lib/plausible/stats/filter_suggestions.ex
+++ b/lib/plausible/stats/filter_suggestions.ex
@@ -148,8 +148,11 @@ defmodule Plausible.Stats.FilterSuggestions do
end
def filter_suggestions(site, _query, "goal", filter_search) do
+ site = Plausible.Repo.preload(site, :team)
+ props_available? = Plausible.Billing.Feature.Props.check_availability(site.team) == :ok
+
site
- |> Plausible.Goals.for_site()
+ |> Plausible.Goals.for_site(include_goals_with_custom_props?: props_available?)
|> Enum.map(& &1.display_name)
|> Enum.filter(fn goal ->
String.contains?(
diff --git a/lib/plausible/stats/goal_suggestions.ex b/lib/plausible/stats/goal_suggestions.ex
index 5ab861f405..397b6f78a7 100644
--- a/lib/plausible/stats/goal_suggestions.ex
+++ b/lib/plausible/stats/goal_suggestions.ex
@@ -1,6 +1,8 @@
defmodule Plausible.Stats.GoalSuggestions do
@moduledoc false
+ use Plausible.Stats.SQL.Fragments
+
alias Plausible.{Repo, ClickhouseRepo}
alias Plausible.Stats.{Query, QueryBuilder}
import Plausible.Stats.Base
@@ -93,6 +95,88 @@ defmodule Plausible.Stats.GoalSuggestions do
|> Enum.reject(&(String.length(&1) > Plausible.Goal.max_event_name_length()))
end
+ def suggest_custom_property_names(site, search_input, _opts \\ []) do
+ filter_query = if search_input == nil, do: "%", else: "%#{search_input}%"
+
+ query = custom_props_query_30d(site)
+
+ search_q =
+ from(e in base_event_query(query),
+ join: meta in "meta",
+ hints: "ARRAY",
+ on: true,
+ as: :meta,
+ select: meta.key,
+ where: fragment("? ilike ?", meta.key, ^filter_query),
+ group_by: meta.key,
+ order_by: [desc: fragment("count(*)")],
+ limit: 25
+ )
+
+ event_prop_names = ClickhouseRepo.all(search_q)
+
+ allowed_props = site.allowed_event_props || []
+
+ allowed_prop_names =
+ if search_input == nil or search_input == "" do
+ allowed_props
+ else
+ search_lower = String.downcase(search_input)
+
+ Enum.filter(allowed_props, fn prop ->
+ String.contains?(String.downcase(prop), search_lower)
+ end)
+ end
+
+ # Combine results, prioritizing event_prop_names (they have usage data),
+ # then append allowed_prop_names that aren't already in event_prop_names
+ event_prop_set = MapSet.new(event_prop_names)
+
+ allowed_only =
+ allowed_prop_names
+ |> Enum.reject(&MapSet.member?(event_prop_set, &1))
+
+ event_prop_names ++ Enum.sort(allowed_only)
+ end
+
+ def suggest_custom_property_values(site, prop_key, search_input) do
+ filter_query = if search_input == nil, do: "%", else: "%#{search_input}%"
+
+ query = custom_props_query_30d(site)
+
+ search_q =
+ from(e in base_event_query(query),
+ select: get_by_key(e, :meta, ^prop_key),
+ where:
+ has_key(e, :meta, ^prop_key) and
+ fragment(
+ "? ilike ?",
+ get_by_key(e, :meta, ^prop_key),
+ ^filter_query
+ ),
+ group_by: get_by_key(e, :meta, ^prop_key),
+ order_by: [desc: fragment("count(*)")],
+ limit: 25
+ )
+
+ ClickhouseRepo.all(search_q)
+ end
+
+ defp custom_props_query_30d(site) do
+ Plausible.Stats.Query.parse_and_build!(
+ site,
+ %{
+ "site_id" => site.domain,
+ "date_range" => [
+ Date.to_iso8601(Date.shift(Date.utc_today(), day: -30)),
+ Date.to_iso8601(Date.utc_today())
+ ],
+ "metrics" => ["pageviews"],
+ "include" => %{"imports" => true}
+ }
+ )
+ end
+
defp maybe_set_limit(q, :unlimited) do
q
end
diff --git a/lib/plausible/stats/goals.ex b/lib/plausible/stats/goals.ex
index d7f803f64e..806635f350 100644
--- a/lib/plausible/stats/goals.ex
+++ b/lib/plausible/stats/goals.ex
@@ -14,7 +14,9 @@ defmodule Plausible.Stats.Goals do
def preload_needed_goals(site, dimensions, filters) do
if Enum.member?(dimensions, "event:goal") or
Filters.filtering_on_dimension?(filters, "event:goal") do
- goals = Plausible.Goals.for_site(site)
+ site = Plausible.Repo.preload(site, :team)
+ props_available? = Plausible.Billing.Feature.Props.check_availability(site.team) == :ok
+ goals = Plausible.Goals.for_site(site, include_goals_with_custom_props?: props_available?)
%{
# When grouping by event:goal, later pipeline needs to know which goals match filters exactly.
@@ -200,7 +202,7 @@ defmodule Plausible.Stats.Goals do
defp goal_condition(:event, goal, _) do
name_condition = dynamic([e], e.name == ^goal.event_name)
- if map_size(goal.custom_props) > 0 do
+ if Plausible.Goal.has_custom_props?(goal) do
custom_props_condition = build_custom_props_condition(goal.custom_props)
dynamic([e], ^name_condition and ^custom_props_condition)
else
@@ -215,7 +217,14 @@ defmodule Plausible.Stats.Goals do
scroll_condition =
dynamic([e], e.scroll_depth <= 100 and e.scroll_depth >= ^goal.scroll_threshold)
- dynamic([e], ^pathname_condition and ^name_condition and ^scroll_condition)
+ base_condition = dynamic([e], ^pathname_condition and ^name_condition and ^scroll_condition)
+
+ if Plausible.Goal.has_custom_props?(goal) do
+ custom_props_condition = build_custom_props_condition(goal.custom_props)
+ dynamic([e], ^base_condition and ^custom_props_condition)
+ else
+ base_condition
+ end
end
defp goal_condition(:page, goal, true = _imported?) do
@@ -225,8 +234,14 @@ defmodule Plausible.Stats.Goals do
defp goal_condition(:page, goal, false = _imported?) do
name_condition = dynamic([e], e.name == "pageview")
pathname_condition = page_path_condition(goal.page_path, _imported? = false)
+ base_condition = dynamic([e], ^pathname_condition and ^name_condition)
- dynamic([e], ^pathname_condition and ^name_condition)
+ if Plausible.Goal.has_custom_props?(goal) do
+ custom_props_condition = build_custom_props_condition(goal.custom_props)
+ dynamic([e], ^base_condition and ^custom_props_condition)
+ else
+ base_condition
+ end
end
defp page_path_condition(page_path, imported?) do
diff --git a/lib/plausible_web/components/billing/billing.ex b/lib/plausible_web/components/billing/billing.ex
index 83e4732719..1afbe02501 100644
--- a/lib/plausible_web/components/billing/billing.ex
+++ b/lib/plausible_web/components/billing/billing.ex
@@ -11,6 +11,7 @@ defmodule PlausibleWeb.Components.Billing do
attr :current_user, Plausible.Auth.User, required: true
attr :current_team, :any, required: true
attr :locked?, :boolean, required: true
+ attr :link_class, :string, default: ""
slot :inner_block, required: true
def feature_gate(assigns) do
@@ -36,7 +37,11 @@ defmodule PlausibleWeb.Components.Billing do
class="max-w-sm sm:max-w-md mb-2 text-sm text-gray-600 dark:text-gray-100/60 leading-normal text-center"
>
To access this feature,
- <.upgrade_call_to_action current_user={@current_user} current_team={@current_team} />
+ <.upgrade_call_to_action
+ current_user={@current_user}
+ current_team={@current_team}
+ link_class={@link_class}
+ />
</span>
</div>
</div>
@@ -357,6 +362,10 @@ defmodule PlausibleWeb.Components.Billing do
defp change_plan_or_upgrade_text(_subscription), do: "Change plan"
+ attr :link_class, :string, default: ""
+ attr :current_team, :any, required: true
+ attr :current_user, :atom, required: true
+
def upgrade_call_to_action(assigns) do
user = assigns.current_user
site = assigns[:site]
@@ -394,7 +403,7 @@ defmodule PlausibleWeb.Components.Billing do
upgrade_assistance_required? ->
~H"""
contact
- <.styled_link href="mailto:[email protected]" class="font-medium">
+ <.styled_link href="mailto:[email protected]" class={"font-medium " <> @link_class}>
</.styled_link>
to upgrade your subscription.
@@ -403,7 +412,7 @@ defmodule PlausibleWeb.Components.Billing do
true ->
~H"""
<.styled_link
- class="inline-block font-medium"
+ class={"inline-block font-medium " <> @link_class}
href={Routes.billing_path(PlausibleWeb.Endpoint, :choose_plan)}
>
upgrade your subscription.
diff --git a/lib/plausible_web/components/generic.ex b/lib/plausible_web/components/generic.ex
index c4407ba585..3f14b6a693 100644
--- a/lib/plausible_web/components/generic.ex
+++ b/lib/plausible_web/components/generic.ex
@@ -438,7 +438,8 @@ defmodule PlausibleWeb.Components.Generic do
end
attr :id, :string, required: true
- attr :js_active_var, :string, required: true
+ attr :js_active_var, :string, default: nil
+ attr :checked, :boolean, default: nil
attr :id_suffix, :string, default: ""
attr :disabled, :boolean, default: false
@@ -446,17 +447,30 @@ defmodule PlausibleWeb.Components.Generic do
@doc """
Renders toggle input.
- Needs `:js_active_var` that controls toggle state.
- Set this outside this component with `x-data="{ <variable name>: <initial state> }"`.
- ### Examples
+ Can be used in two modes:
+
+ 1. Alpine JS mode: Pass `:js_active_var` to control toggle state via Alpine JS.
+ Set this outside this component with `x-data="{ <variable name>: <initial state> }"`.
+
+ 2. Server-side mode: Pass `:checked` boolean and `phx-click` event handler.
+
+ ### Examples - Alpine JS mode
```
<div x-data="{ showGoals: false }>
<.toggle_switch id="show_goals" js_active_var="showGoals" />
</div>
- ```
+ ```
+
+ ### Examples - Server-side mode
+ ```
+ <.toggle_switch id="my_toggle" checked={@my_toggle} phx-click="toggle-my-setting" phx-target={@myself} />
+ ```
"""
def toggle_switch(assigns) do
+ server_mode? = not is_nil(assigns.checked)
+ assigns = assign(assigns, :server_mode?, server_mode?)
+
~H"""
<button
id={"#{@id}-#{@id_suffix}"}
@@ -464,13 +478,34 @@ defmodule PlausibleWeb.Components.Generic do
aria-labelledby={@id}
role="switch"
type="button"
- x-on:click={"#{@js_active_var} = !#{@js_active_var}"}
- x-bind:aria-checked={@js_active_var}
+ x-on:click={if(!@server_mode? && @js_active_var, do: "#{@js_active_var} = !#{@js_active_var}")}
+ x-bind:aria-checked={if(!@server_mode? && @js_active_var, do: @js_active_var)}
+ aria-checked={if(@server_mode?, do: to_string(@checked))}
disabled={@disabled}
{@rest}
>
<span
- class="relative inline-flex h-6 w-11 shrink-0 rounded-full border-2 border-transparent transition-colors duration-200 ease-in-out focus:outline-hidden focus:ring-2 focus:ring-indigo-600 focus:ring-offset-2"
+ :if={@server_mode?}
+ class={[
+ "relative inline-flex h-6 w-11 shrink-0 rounded-full border-2 border-transparent transition-colors duration-200 ease-in-out focus:outline-hidden focus:ring-2 focus:ring-indigo-600 focus:ring-offset-2",
+ if(@checked, do: "bg-indigo-600", else: "dark:bg-gray-600 bg-gray-200"),
+ if(@disabled, do: "opacity-50")
+ ]}
+ >
+ <span
+ aria-hidden="true"
+ class={[
+ "pointer-events-none inline-block size-5 transform rounded-full bg-white shadow-sm ring-0 transition duration-200 ease-in-out",
+ if(@checked, do: "dark:bg-white translate-x-5", else: "dark:bg-white translate-x-0")
+ ]}
+ />
+ </span>
+ <span
+ :if={!@server_mode?}
+ class={[
+ "relative inline-flex h-6 w-11 shrink-0 rounded-full border-2 border-transparent transition-colors duration-200 ease-in-out focus:outline-hidden focus:ring-2 focus:ring-indigo-600 focus:ring-offset-2",
+ if(@disabled, do: "opacity-50")
+ ]}
x-bind:class={"#{@js_active_var} ? 'bg-indigo-600' : 'dark:bg-gray-600 bg-gray-200'"}
>
<span
@@ -582,12 +617,12 @@ defmodule PlausibleWeb.Components.Generic do
current_team={@current_team}
site={@site}
>
- <div class="p-6">
+ <div class="p-4 sm:p-6">
{render_slot(@inner_block)}
</div>
</PlausibleWeb.Components.Billing.feature_gate>
<% else %>
- <div class="p-6">
+ <div class="p-4 sm:p-6">
{render_slot(@inner_block)}
</div>
<% end %>
@@ -615,7 +650,7 @@ defmodule PlausibleWeb.Components.Generic do
"top-0",
"-translate-y-full",
"z-[1000]",
- "sm:max-w-72",
+ "sm:max-w-64",
"w-max"
]
@@ -653,7 +688,7 @@ defmodule PlausibleWeb.Components.Generic do
x-transition:leave-start="opacity-100"
x-transition:leave-end="opacity-0"
>
- <div class="bg-gray-800 text-white rounded-sm px-2.5 py-1.5 text-xs font-medium">
+ <div class="bg-gray-800 text-white rounded-sm px-2.5 py-1.5 text-xs font-medium whitespace-normal">
{render_slot(@tooltip_content)}
</div>
</div>
@@ -854,7 +889,7 @@ defmodule PlausibleWeb.Components.Generic do
class={
[
@height,
- "text-sm px-6 py-4 first:pl-0 last:pr-0 whitespace-nowrap",
+ "text-sm px-3 md:px-6 py-3 md:py-4 first:pl-0 last:pr-0 whitespace-nowrap",
# allow tooltips overflow cells vertically
"overflow-visible",
@truncate && "truncate",
@@ -1004,6 +1039,7 @@ defmodule PlausibleWeb.Components.Generic do
"dark:group-hover/button:" <> text.dark_hover,
"transition-colors",
"duration-150",
+ "group-disabled/button:opacity-50",
assigns.icon_class
]
@@ -1220,7 +1256,7 @@ defmodule PlausibleWeb.Components.Generic do
~H"""
<span
class={[
- "inline-flex items-center text-xs font-medium py-1 px-2 rounded-md",
+ "inline-flex items-center text-xs font-medium py-[3px] px-[7px] rounded-md",
@color_classes,
@class
]}
diff --git a/lib/plausible_web/controllers/api/external_stats_controller.ex b/lib/plausible_web/controllers/api/external_stats_controller.ex
index 6890d47058..0e69b0ab0c 100644
--- a/lib/plausible_web/controllers/api/external_stats_controller.ex
+++ b/lib/plausible_web/controllers/api/external_stats_controller.ex
@@ -336,9 +336,12 @@ defmodule PlausibleWeb.Api.ExternalStatsController do
end
defp validate_filter(site, [_type, "event:goal", goal_filter | _rest]) do
+ site = Plausible.Repo.preload(site, :team)
+ props_available? = Plausible.Billing.Feature.Props.check_availability(site.team) == :ok
+
configured_goals =
site
- |> Plausible.Goals.for_site()
+ |> Plausible.Goals.for_site(include_goals_with_custom_props?: props_available?)
|> Enum.map(& &1.display_name)
goals_in_filter = List.wrap(goal_filter)
diff --git a/lib/plausible_web/live/components/combo_box.ex b/lib/plausible_web/live/components/combo_box.ex
index 1ef4bd3420..37bf12667a 100644
--- a/lib/plausible_web/live/components/combo_box.ex
+++ b/lib/plausible_web/live/components/combo_box.ex
@@ -69,6 +69,8 @@ defmodule PlausibleWeb.Live.Components.ComboBox do
attr(:suggest_fun, :any, required: true)
attr(:suggestions_limit, :integer)
attr(:class, :string, default: "")
+ attr(:input_class, :string, default: "")
+ attr(:dropdown_class, :string, default: "")
attr(:required, :boolean, default: false)
attr(:creatable, :boolean, default: false)
attr(:errors, :list, default: [])
@@ -105,7 +107,10 @@ defmodule PlausibleWeb.Live.Components.ComboBox do
phx-target={@myself}
phx-debounce={200}
value={@display_value}
- class="text-sm [&.phx-change-loading+svg.spinner]:block border-none py-1.5 px-1.5 w-full inline-block rounded-md focus:outline-hidden focus:ring-0"
+ class={[
+ "text-sm [&.phx-change-loading+svg.spinner]:block border-none py-1.5 px-1.5 w-full inline-block rounded-md focus:outline-hidden focus:ring-0",
+ @input_class
+ ]}
style="background-color: inherit;"
required={@required}
/>
@@ -137,6 +142,7 @@ defmodule PlausibleWeb.Live.Components.ComboBox do
target={@myself}
creatable={@creatable}
display_value={@display_value}
+ dropdown_class={@dropdown_class}
/>
</div>
</div>
@@ -172,6 +178,7 @@ defmodule PlausibleWeb.Live.Components.ComboBox do
attr(:target, :any)
attr(:creatable, :boolean, required: true)
attr(:display_value, :string, required: true)
+ attr(:dropdown_class, :string, default: "")
def combo_dropdown(assigns) do
~H"""
@@ -180,7 +187,10 @@ defmodule PlausibleWeb.Live.Components.ComboBox do
id={"dropdown-#{@ref}"}
x-show="isOpen"
x-ref="suggestions"
- class="text-sm w-full dropdown z-50 absolute mt-1 max-h-60 overflow-auto rounded-md bg-white py-1 text-base shadow-lg ring-1/5 ring-black focus:outline-hidden dark:bg-gray-800"
+ class={[
+ "text-sm w-full dropdown z-50 absolute mt-1 max-h-60 overflow-auto rounded-md bg-white py-1 text-base shadow-lg ring-1/5 ring-black focus:outline-hidden dark:bg-gray-800",
+ @dropdown_class
+ ]}
style="display: none;"
>
<.option
@@ -248,11 +258,13 @@ defmodule PlausibleWeb.Live.Components.ComboBox do
<a
x-ref={"dropdown-#{@ref}-option-#{@idx}"}
x-on:click={not @creatable && "selectionInProgress = true"}
+ x-on:mouseenter="const isTruncated = $el.scrollWidth > $el.clientWidth; $el.title = isTruncated ? $el.dataset.displayValue : ''"
phx-click={select_option(@ref, @submit_value, @display_value)}
phx-value-submit-value={@submit_value}
phx-value-display-value={@display_value}
phx-target={@target}
class="block truncate py-2 px-3"
+ data-display-value={@display_value}
>
<%= if @creatable do %>
Create "{@display_value}"
@@ -261,9 +273,9 @@ defmodule PlausibleWeb.Live.Components.ComboBox do
<% end %>
</a>
</li>
- <div :if={@idx == @suggestions_limit} class="text-xs text-gray-500 relative py-2 px-3">
- Max results reached. Refine your search by typing.
- </div>
+ <li :if={@idx == @suggestions_limit} class="text-gray-500 relative py-2 px-3">
+ Max results reached, type to refine search.
+ </li>
"""
end
diff --git a/lib/plausible_web/live/goal_settings/form.ex b/lib/plausible_web/live/goal_settings/form.ex
index 716a7eb99e..d25c678e09 100644
--- a/lib/plausible_web/live/goal_settings/form.ex
+++ b/lib/plausible_web/live/goal_settings/form.ex
@@ -15,6 +15,9 @@ defmodule PlausibleWeb.Live.GoalSettings.Form do
has_access_to_revenue_goals? =
Plausible.Billing.Feature.RevenueGoals.check_availability(site.team) == :ok
+ has_access_to_props? =
+ Plausible.Billing.Feature.Props.check_availability(site.team) == :ok
+
form =
(assigns.goal || %Plausible.Goal{})
|> Plausible.Goal.changeset()
@@ -42,6 +45,13 @@ defmodule PlausibleWeb.Live.GoalSettings.Form do
Map.get(socket.assigns, :show_autoconfigure_modal?, false)
end
+ use_custom_props =
+ if Map.get(socket.assigns, :goal) == assigns.goal do
+ Map.get(socket.assigns, :use_custom_props, Plausible.Goal.has_custom_props?(assigns.goal))
+ else
+ Plausible.Goal.has_custom_props?(assigns.goal)
+ end
+
socket =
socket
|> assign(
@@ -56,12 +66,14 @@ defmodule PlausibleWeb.Live.GoalSettings.Form do
form_type: form_type,
site: site,
has_access_to_revenue_goals?: has_access_to_revenue_goals?,
+ has_access_to_props?: has_access_to_props?,
existing_goals: assigns.existing_goals,
on_save_goal: assigns.on_save_goal,
on_autoconfigure: assigns.on_autoconfigure,
goal: assigns.goal,
goal_type: assigns[:goal_type],
- show_autoconfigure_modal?: show_autoconfigure_modal?
+ show_autoconfigure_modal?: show_autoconfigure_modal?,
+ use_custom_props: use_custom_props
)
{:ok, socket}
@@ -96,6 +108,9 @@ defmodule PlausibleWeb.Live.GoalSettings.Form do
existing_goals={@existing_goals}
goal_options={@event_name_options}
has_access_to_revenue_goals?={@has_access_to_revenue_goals?}
+ has_access_to_props?={@has_access_to_props?}
+ myself={@myself}
+ use_custom_props={@use_custom_props}
/>
<.pageview_fields
:if={@form_type == "pageviews"}
@@ -103,6 +118,11 @@ defmodule PlausibleWeb.Live.GoalSettings.Form do
goal={@goal}
suffix={@context_unique_id}
site={@site}
+ current_user={@current_user}
+ site_team={@site_team}
+ has_access_to_props?={@has_access_to_props?}
+ myself={@myself}
+ use_custom_props={@use_custom_props}
/>
<.scroll_fields
:if={@form_type == "scroll"}
@@ -110,6 +130,11 @@ defmodule PlausibleWeb.Live.GoalSettings.Form do
goal={@goal}
suffix={@context_unique_id}
site={@site}
+ current_user={@current_user}
+ site_team={@site_team}
+ has_access_to_props?={@has_access_to_props?}
+ myself={@myself}
+ use_custom_props={@use_custom_props}
/>
<.button type="submit" class="w-full">
@@ -171,18 +196,31 @@ defmodule PlausibleWeb.Live.GoalSettings.Form do
existing_goals={@existing_goals}
goal_options={@event_name_options}
has_access_to_revenue_goals?={@has_access_to_revenue_goals?}
+ has_access_to_props?={@has_access_to_props?}
+ myself={@myself}
+ use_custom_props={@use_custom_props}
/>
<.pageview_fields
:if={@form_type == "pageviews"}
f={f}
suffix={@context_unique_id}
site={@site}
+ current_user={@current_user}
+ site_team={@site_team}
+ has_access_to_props?={@has_access_to_props?}
+ myself={@myself}
+ use_custom_props={@use_custom_props}
/>
<.scroll_fields
:if={@form_type == "scroll"}
f={f}
suffix={@context_unique_id}
site={@site}
+ current_user={@current_user}
+ site_team={@site_team}
+ has_access_to_props?={@has_access_to_props?}
+ myself={@myself}
+ use_custom_props={@use_custom_props}
/>
<.button type="submit" class="w-full">
@@ -196,11 +234,20 @@ defmodule PlausibleWeb.Live.GoalSettings.Form do
attr(:site, Plausible.Site)
attr(:suffix, :string)
attr(:goal, Plausible.Goal, default: nil)
+ attr(:myself, :any)
+ attr(:current_user, Plausible.Auth.User)
+ attr(:site_team, Plausible.Teams.Team)
+ attr(:has_access_to_props?, :boolean)
+ attr(:use_custom_props, :boolean, default: false)
attr(:rest, :global)
def pageview_fields(assigns) do
~H"""
- <div id="pageviews-form" class="py-2" {@rest}>
+ <div
+ id="pageviews-form"
+ class="py-2"
+ {@rest}
+ >
<div class="text-sm pb-6 text-gray-600 dark:text-gray-400 text-pretty">
Pageview goals allow you to measure how many people visit a specific page or section of your site.
<.styled_link
@@ -240,6 +287,18 @@ defmodule PlausibleWeb.Live.GoalSettings.Form do
x-data="{ firstFocus: true }"
x-on:focus="if (firstFocus) { $el.select(); firstFocus = false; }"
/>
+
+ <.custom_property_section
+ f={@f}
+ suffix={@suffix}
+ goal={@goal}
+ myself={@myself}
+ site={@site}
+ current_user={@current_user}
+ site_team={@site_team}
+ has_access_to_props?={@has_access_to_props?}
+ use_custom_props={@use_custom_props}
+ />
</div>
"""
end
@@ -248,6 +307,11 @@ defmodule PlausibleWeb.Live.GoalSettings.Form do
attr(:site, Plausible.Site)
attr(:suffix, :string)
attr(:goal, Plausible.Goal, default: nil)
+ attr(:myself, :any)
+ attr(:current_user, Plausible.Auth.User)
+ attr(:site_team, Plausible.Teams.Team)
+ attr(:has_access_to_props?, :boolean)
+ attr(:use_custom_props, :boolean, default: false)
attr(:rest, :global)
def scroll_fields(assigns) do
@@ -336,6 +400,18 @@ defmodule PlausibleWeb.Live.GoalSettings.Form do
x-data="{ firstFocus: true }"
x-on:focus="if (firstFocus) { $el.select(); firstFocus = false; }"
/>
+
+ <.custom_property_section
+ f={@f}
+ suffix={@suffix}
+ goal={@goal}
+ myself={@myself}
+ site={@site}
+ current_user={@current_user}
+ site_team={@site_team}
+ has_access_to_props?={@has_access_to_props?}
+ use_custom_props={@use_custom_props}
+ />
</div>
"""
end
@@ -349,12 +425,19 @@ defmodule PlausibleWeb.Live.GoalSettings.Form do
attr(:goal_options, :list)
attr(:goal, Plausible.Goal, default: nil)
attr(:has_access_to_revenue_goals?, :boolean)
+ attr(:has_access_to_props?, :boolean)
+ attr(:myself, :any)
+ attr(:use_custom_props, :boolean, default: false)
attr(:rest, :global)
def custom_event_fields(assigns) do
~H"""
- <div id="custom-events-form" class="py-2" {@rest}>
+ <div
+ id="custom-events-form"
+ class="py-2"
+ {@rest}
+ >
<div id="event-fields">
<div class="text-sm pb-6 text-gray-500 dark:text-gray-400 text-justify rounded-md">
Custom Events are not tracked by default - you have to configure them on your site to be sent to Plausible. See examples and learn more in <.styled_link
@@ -401,6 +484,18 @@ defmodule PlausibleWeb.Live.GoalSettings.Form do
/>
</div>
+ <.custom_property_section
+ f={@f}
+ suffix={@suffix}
+ goal={@goal}
+ myself={@myself}
+ site={@site}
+ current_user={@current_user}
+ site_team={@site_team}
+ has_access_to_props?={@has_access_to_props?}
+ use_custom_props={@use_custom_props}
+ />
+
<%= if ee?() and Plausible.Sites.regular?(@site) and not editing_non_revenue_goal?(assigns) do %>
<.revenue_goal_settings
f={@f}
@@ -419,6 +514,68 @@ defmodule PlausibleWeb.Live.GoalSettings.Form do
"""
end
+ attr(:suffix, :string, required: true)
+ attr(:myself, :any, required: true)
+ attr(:f, Phoenix.HTML.Form, required: true)
+ attr(:goal, Plausible.Goal, default: nil)
+ attr(:site, Plausible.Site, required: true)
+ attr(:current_user, Plausible.Auth.User, required: true)
+ attr(:site_team, Plausible.Teams.Team, required: true)
+ attr(:has_access_to_props?, :boolean, required: true)
+ attr(:use_custom_props, :boolean, default: false)
+
+ def custom_property_section(assigns) do
+ ~H"""
+ <div class="mt-6 mb-2 flex items-center justify-between">
+ <div class="flex items-center gap-2">
+ <span class="text-sm/6 font-medium text-gray-900 dark:text-gray-100">
+ {if @use_custom_props, do: "Custom properties", else: "Add custom property"}
+ </span>
+ <.link
+ :if={not @has_access_to_props? and not @use_custom_props}
+ href={Routes.billing_path(PlausibleWeb.Endpoint, :choose_plan)}
+ class="inline-block"
+ >
+ <.pill color={:indigo}>
+ Business
+ </.pill>
+ </.link>
+ </div>
+ <.tooltip enabled?={not @has_access_to_props?} centered?={true}>
+ <:tooltip_content>
+ To get access to this feature,
+ <PlausibleWeb.Components.Billing.upgrade_call_to_action
+ current_user={@current_user}
+ current_team={@site_team}
+ link_class="!inline !text-indigo-400 hover:!text-indigo-300"
+ />
+ </:tooltip_content>
+ <.toggle_switch
+ id="add-custom-property"
+ id_suffix={@suffix}
+ checked={@use_custom_props}
+ phx-click="toggle-custom-props"
+ phx-target={@myself}
+ disabled={not @has_access_to_props?}
+ />
+ </.tooltip>
+ </div>
+
+ <.error :for={msg <- Enum.map(@f[:custom_props].errors, &translate_error/1)}>
+ {msg}
+ </.error>
+
+ <div :if={@use_custom_props} class="space-y-3">
+ <.live_component
+ id={"property-pairs-#{@suffix}"}
+ module={PlausibleWeb.Live.GoalSettings.PropertyPairs}
+ site={@site}
+ goal={@goal}
+ />
+ </div>
+ """
+ end
+
def revenue_goal_settings(assigns) do
js_data =
Jason.encode!(%{
@@ -431,7 +588,7 @@ defmodule PlausibleWeb.Live.GoalSettings.Form do
~H"""
<div x-data={@js_data} data-test-id="revenue-goal-settings">
<%= if is_nil(@goal) do %>
- <div class="mt-6 mb-3">
+ <div class="mt-6 mb-2">
<.revenue_toggle {assigns} />
</div>
<% else %>
@@ -443,7 +600,9 @@ defmodule PlausibleWeb.Live.GoalSettings.Form do
</label>
<% end %>
<div class="mb-2" x-show="active" id={"revenue-input-#{@suffix}"}>
+ <.input :if={not is_nil(@goal)} type="text" field={@f[:currency]} disabled={true} mt?={false} />
<.live_component
+ :if={is_nil(@goal)}
id={"currency_input_#{@suffix}"}
submit_name={@f[:currency].name}
module={ComboBox}
@@ -466,7 +625,12 @@ defmodule PlausibleWeb.Live.GoalSettings.Form do
end
def handle_event("save-goal", %{"goal" => goal_params}, %{assigns: %{goal: nil}} = socket) do
- case Plausible.Goals.create(socket.assigns.site, goal_params) do
+ {:ok, transformed_params} =
+ goal_params
+ |> maybe_clear_custom_props(socket.assigns.use_custom_props)
+ |> transform_property_params()
+
+ case Plausible.Goals.create(socket.assigns.site, transformed_params) do
{:ok, goal} ->
socket =
goal
@@ -485,7 +649,12 @@ defmodule PlausibleWeb.Live.GoalSettings.Form do
%{"goal" => goal_params},
%{assigns: %{goal: %Plausible.Goal{} = goal}} = socket
) do
- case Plausible.Goals.update(goal, goal_params) do
+ {:ok, transformed_params} =
+ goal_params
+ |> maybe_clear_custom_props(socket.assigns.use_custom_props)
+ |> transform_property_params()
+
+ case Plausible.Goals.update(goal, transformed_params) do
{:ok, goal} ->
socket = socket.assigns.on_save_goal.(goal, socket)
@@ -496,6 +665,10 @@ defmodule PlausibleWeb.Live.GoalSettings.Form do
end
end
+ def handle_event("toggle-custom-props", _params, socket) do
+ {:noreply, assign(socket, use_custom_props: !socket.assigns.use_custom_props)}
+ end
+
def handle_event("autoconfigure", _params, socket) do
socket = assign(socket, show_autoconfigure_modal?: false)
{:noreply, socket.assigns.on_autoconfigure.(socket)}
@@ -542,34 +715,38 @@ defmodule PlausibleWeb.Live.GoalSettings.Form do
defp revenue_toggle(assigns) do
~H"""
- <.tooltip enabled?={not @has_access_to_revenue_goals?}>
- <:tooltip_content>
- <div class="text-xs">
- To get access to this feature
+ <div class="flex items-center justify-between">
+ <div class="flex items-center gap-2">
+ <span class="text-sm/6 font-medium text-gray-900 dark:text-gray-100">
+ Enable revenue tracking
+ </span>
+ <.link
+ :if={not @has_access_to_revenue_goals?}
+ href={Routes.billing_path(PlausibleWeb.Endpoint, :choose_plan)}
+ class="inline-block"
+ >
+ <.pill color={:indigo}>
+ Business
+ </.pill>
+ </.link>
+ </div>
+ <.tooltip enabled?={not @has_access_to_revenue_goals?} centered?={true}>
+ <:tooltip_content>
+ To get access to this feature,
<PlausibleWeb.Components.Billing.upgrade_call_to_action
current_user={@current_user}
current_team={@site_team}
- />.
- </div>
- </:tooltip_content>
- <div class="flex itemx-center mb-3">
+ link_class="!inline !text-indigo-400 hover:!text-indigo-300"
+ />
+ </:tooltip_content>
<PlausibleWeb.Components.Generic.toggle_switch
id="enable-revenue-tracking"
id_suffix={@suffix}
js_active_var="active"
disabled={not @has_access_to_revenue_goals?}
/>
- <span class={[
- "ml-3 text-sm/6 font-medium",
- if(@has_access_to_revenue_goals?,
- do: "text-gray-900 dark:text-gray-100",
- else: "text-gray-500 dark:text-gray-400"
- )
- ]}>
- Enable revenue tracking
- </span>
- </div>
- </.tooltip>
+ </.tooltip>
+ </div>
"""
end
@@ -582,4 +759,31 @@ defmodule PlausibleWeb.Live.GoalSettings.Form do
else
defp editing_non_revenue_goal?(_assigns), do: false
end
+
+ defp maybe_clear_custom_props(goal_params, true = _use_custom_props), do: goal_params
+
+ defp maybe_clear_custom_props(goal_params, false = _use_custom_props) do
+ Map.put(goal_params, "custom_props", %{})
+ end
+
+ defp transform_property_params(
+ %{"custom_props" => %{"keys" => prop_keys, "values" => prop_values}} = goal_params
+ )
+ when is_list(prop_keys) and is_list(prop_values) do
+ transformed =
+ goal_params
+ |> Map.put(
+ "custom_props",
+ prop_keys
+ |> Enum.zip(prop_values)
+ |> Enum.reject(fn {k, v} -> String.trim(k) == "" and String.trim(v) == "" end)
+ |> Enum.into(%{})
+ )
+
+ {:ok, transformed}
+ end
+
+ defp transform_property_params(goal_params) do
+ {:ok, goal_params}
+ end
end
diff --git a/lib/plausible_web/live/goal_settings/list.ex b/lib/plausible_web/live/goal_settings/list.ex
index 1a6b62c6a8..384dacbb00 100644
--- a/lib/plausible_web/live/goal_settings/list.ex
+++ b/lib/plausible_web/live/goal_settings/list.ex
@@ -3,6 +3,7 @@ defmodule PlausibleWeb.Live.GoalSettings.List do
Phoenix LiveComponent module that renders a list of goals
"""
use PlausibleWeb, :live_component
+ use Plausible
alias PlausibleWeb.Live.Components.Modal
alias PlausibleWeb.Components.PrimaDropdown
@@ -14,9 +15,13 @@ defmodule PlausibleWeb.Live.GoalSettings.List do
def render(assigns) do
revenue_goals_enabled? = Plausible.Billing.Feature.RevenueGoals.enabled?(assigns.site)
+ props_available? =
+ Plausible.Billing.Feature.Props.check_availability(assigns.site.team) == :ok
+
assigns =
assigns
|> assign(:revenue_goals_enabled?, revenue_goals_enabled?)
+ |> assign(:props_available?, props_available?)
|> assign(:searching?, String.trim(assigns.filter_text) != "")
~H"""
@@ -65,30 +70,31 @@ defmodule PlausibleWeb.Live.GoalSettings.List do
<.th hide_on_mobile>Type</.th>
</:thead>
<:tbody :let={goal}>
- <.td max_width="max-w-64" height="h-16">
- <%= if not @revenue_goals_enabled? && goal.currency do %>
- <div class="truncate">{goal}</div>
- <.tooltip>
+ <.td max_width="max-w-52 sm:max-w-64" height="h-16">
+ <% has_unavailable_revenue? = not @revenue_goals_enabled? and not is_nil(goal.currency) %>
+ <% has_unavailable_props? =
+ not @props_available? and Plausible.Goal.has_custom_props?(goal) %>
+ <.goal_name_with_icons goal={goal} />
+ <%= if has_unavailable_revenue? or has_unavailable_props? do %>
+ <.tooltip centered?={true}>
<:tooltip_content>
<p class="text-xs">
- Revenue Goals act like regular custom<br />
- events without a Business subscription<br />
+ <%= if has_unavailable_revenue? do %>
+ Revenue goals appear as regular goals on the dashboard. Upgrade to Business to see revenue data.
+ <% else %>
+ Upgrade to Business to show goals with custom properties on the dashboard.
+ <% end %>
</p>
</:tooltip_content>
- <span class="w-max flex items-center text-gray-500 italic text-sm">
- <Heroicons.lock_closed solid class="size-4 mr-1" /> Upgrade Required
- </span>
+ <.styled_link
+ class="w-max flex items-center text-sm"
+ href={Routes.billing_path(PlausibleWeb.Endpoint, :choose_plan)}
+ data-test-id="feature-unavailable-cta"
+ >
+ <Heroicons.lock_closed class="size-3.5 mr-1 stroke-2" /> Upgrade
+ </.styled_link>
</.tooltip>
<% else %>
- <div class="font-medium text-sm flex items-center gap-1.5">
- <span class="truncate">{goal}</span>
- <.tooltip :if={not Enum.empty?(goal.funnels)} centered?={true}>
- <:tooltip_content>
- Belongs to funnel
- </:tooltip_content>
- <Heroicons.funnel class="size-3.5 stroke-2 flex-shrink-0" />
- </.tooltip>
- </div>
<div class="truncate">
<.goal_description goal={goal} />
</div>
@@ -103,18 +109,21 @@ defmodule PlausibleWeb.Live.GoalSettings.List do
<.pill :if={goal.currency} color={:indigo}>Revenue Goal ({goal.currency})</.pill>
</.td>
<.td actions height="h-16">
+ <% goal_editable? = goal_editable?(goal, @revenue_goals_enabled?, @props_available?) %>
<.edit_button
- :if={!goal.currency || (goal.currency && @revenue_goals_enabled?)}
+ :if={goal_editable?}
x-data
x-on:click={Modal.JS.preopen("goals-form-modal")}
+ data-test-id="edit-goal-button"
phx-click="edit-goal"
phx-value-goal-id={goal.id}
class="mt-1"
id={"edit-goal-#{goal.id}"}
/>
<.edit_button
- :if={goal.currency && !@revenue_goals_enabled?}
+ :if={not goal_editable?}
id={"edit-goal-#{goal.id}-disabled"}
+ data-test-id="edit-goal-button"
disabled
class="cursor-not-allowed mt-1"
/>
@@ -257,4 +266,61 @@ defmodule PlausibleWeb.Live.GoalSettings.List do
"""
end
end
+
+ defp goal_name_with_icons(assigns) do
+ ~H"""
+ <div class="font-medium text-sm flex items-center gap-1.5">
+ <span class="truncate">{@goal}</span>
+ <.tooltip :if={not Enum.empty?(@goal.funnels)} centered?={true}>
+ <:tooltip_content>
+ Belongs to funnel
+ </:tooltip_content>
+ <Heroicons.funnel class="size-3.5 mt-px stroke-2 flex-shrink-0" />
+ </.tooltip>
+ <.tooltip :if={Plausible.Goal.has_custom_props?(@goal)} centered?={true}>
+ <:tooltip_content>
+ <div class="-mx-1 flex flex-col gap-1 text-xs">
+ <div :for={{key, value} <- @goal.custom_props} class="truncate">
+ <span class="bg-white/20 px-1 py-0.5 rounded-sm">{key}</span>
+ is <span class="bg-white/20 px-1 py-0.5 rounded-sm">{value}</span>
+ </div>
+ </div>
+ </:tooltip_content>
+ <svg
+ xmlns="http://www.w3.org/2000/svg"
+ viewBox="0 0 20 20"
+ class="size-3.5 mt-px flex-shrink-0"
+ >
+ <circle fill="currentColor" cx="7.25" cy="7.25" r="1.25" />
+ <path
+ fill="none"
+ stroke="currentColor"
+ stroke-linecap="round"
+ stroke-linejoin="round"
+ stroke-width="2"
+ d="M4 3h5.172a2 2 0 0 1 1.414.586l5.536 5.536a3 3 0 0 1 0 4.243l-2.757 2.757a3 3 0 0 1-4.243 0l-5.536-5.536A2 2 0 0 1 3 9.172V4a1 1 0 0 1 1-1Z"
+ />
+ </svg>
+ </.tooltip>
+ </div>
+ """
+ end
+
+ on_ee do
+ defp goal_editable?(goal, revenue_goals_enabled?, props_available?) do
+ revenue_ok? =
+ (Plausible.Goal.Revenue.revenue?(goal) and revenue_goals_enabled?) or
+ not Plausible.Goal.Revenue.revenue?(goal)
+
+ props_ok? =
+ (Plausible.Goal.has_custom_props?(goal) and props_available?) or
+ not Plausible.Goal.has_custom_props?(goal)
+
+ revenue_ok? and props_ok?
+ end
+ else
+ defp goal_editable?(_goal, _revenue_goals_enabled?, _props_available?) do
+ always(true)
+ end
+ end
end
diff --git a/lib/plausible_web/live/goal_settings/property_pair_input.ex b/lib/plausible_web/live/goal_settings/property_pair_input.ex
new file mode 100644
index 0000000000..6b10e1b2e9
--- /dev/null
+++ b/lib/plausible_web/live/goal_settings/property_pair_input.ex
@@ -0,0 +1,87 @@
+defmodule PlausibleWeb.Live.GoalSettings.PropertyPairInput do
+ @moduledoc """
+ LiveComponent for a property name + value ComboBox pair.
+
+ When a property name is selected, it notifies the value ComboBox
+ to update its suggestions based on the selected property.
+ """
+ use PlausibleWeb, :live_component
+
+ alias PlausibleWeb.Live.Components.ComboBox
+
+ def update(assigns, socket) do
+ socket =
+ socket
+ |> assign(assigns)
+ |> assign_new(:selected_property, fn -> assigns[:initial_prop_key] end)
+
+ {:ok, socket}
+ end
+
+ attr(:site, Plausible.Site)
+ attr(:initial_prop_key, :string, default: "")
+ attr(:initial_prop_value, :string, default: "")
+
+ def render(assigns) do
+ ~H"""
+ <div class="[container-type:inline-size] flex items-center gap-3" id={@id}>
+ <div class="flex-1">
+ <.live_component
+ id={"#{@id}_key"}
+ submit_name="goal[custom_props][keys][]"
+ placeholder="Select property"
+ module={ComboBox}
+ dropdown_class="left-0 w-max min-w-full max-w-[100cqw]"
+ suggest_fun={fn input, _options -> suggest_property_names(@site, input) end}
+ selected={if @initial_prop_key != "", do: @initial_prop_key, else: nil}
+ on_selection_made={
+ fn value, _by_id ->
+ send_update(__MODULE__,
+ id: @id,
+ selected_property: value
+ )
+ end
+ }
+ creatable
+ />
+ </div>
+
+ <span class="text-sm/6 font-medium text-gray-900 dark:text-gray-100">is</span>
+
+ <div class="flex-1">
+ <.live_component
+ id={"#{@id}_value"}
+ submit_name="goal[custom_props][values][]"
+ placeholder={if @selected_property, do: "Select value", else: "Select property first"}
+ module={ComboBox}
+ dropdown_class="right-0 w-max min-w-full max-w-[100cqw]"
+ suggest_fun={
+ fn input, _options ->
+ suggest_property_values(@site, input, @selected_property)
+ end
+ }
+ selected={if @initial_prop_value != "", do: @initial_prop_value, else: nil}
+ options={suggest_property_values(@site, "", @selected_property)}
+ creatable
+ />
+ </div>
+ </div>
+ """
+ end
+
+ defp suggest_property_names(_site, nil), do: []
+
+ defp suggest_property_names(site, input) do
+ suggestions = Plausible.Stats.GoalSuggestions.suggest_custom_property_names(site, input)
+ Enum.zip(suggestions, suggestions)
+ end
+
+ defp suggest_property_values(_site, _, nil), do: []
+
+ defp suggest_property_values(site, input, property_name) do
+ suggestions =
+ Plausible.Stats.GoalSuggestions.suggest_custom_property_values(site, property_name, input)
+
+ Enum.zip(suggestions, suggestions)
+ end
+end
diff --git a/lib/plausible_web/live/goal_settings/property_pairs.ex b/lib/plausible_web/live/goal_settings/property_pairs.ex
new file mode 100644
index 0000000000..555f4e1ad4
--- /dev/null
+++ b/lib/plausible_web/live/goal_settings/property_pairs.ex
@@ -0,0 +1,115 @@
+defmodule PlausibleWeb.Live.GoalSettings.PropertyPairs do
+ @moduledoc """
+ LiveComponent for managing multiple custom property name + value pairs
+ """
+ use PlausibleWeb, :live_component
+
+ alias PlausibleWeb.Live.GoalSettings.PropertyPairInput
+
+ def update(assigns, socket) do
+ socket =
+ socket
+ |> assign(assigns)
+ |> assign_new(:max_slots, fn -> Plausible.Goal.max_custom_props_per_goal() end)
+ |> assign_new(:slots, fn assigns ->
+ if Plausible.Goal.has_custom_props?(assigns[:goal]) do
+ to_list_with_ids(assigns.goal.custom_props)
+ else
+ to_list_with_ids(empty_row())
+ end
+ end)
+
+ {:ok, socket}
+ end
+
+ attr(:goal, Plausible.Goal, default: nil)
+ attr(:site, Plausible.Site)
+
+ def render(assigns) do
+ ~H"""
+ <div data-test-id="custom-property-pairs">
+ <div
+ :for={{id, {prop_key, prop_value}} <- @slots}
+ class="flex items-center gap-2 mb-2"
+ >
+ <div class="flex-1">
+ <.live_component
+ id={"property_pair_#{id}"}
+ module={PropertyPairInput}
+ site={@site}
+ initial_prop_key={prop_key}
+ initial_prop_value={prop_value}
+ />
+ </div>
+
+ <div
+ :if={length(@slots) > 1}
+ class="w-min inline-flex items-center align-middle"
+ >
+ <.remove_property_button
+ pair_id={id}
+ myself={@myself}
+ />
+ </div>
+ </div>
+
+ <a
+ :if={length(@slots) < @max_slots}
+ class="text-indigo-500 text-sm font-medium cursor-pointer"
+ phx-click="add-slot"
+ phx-target={@myself}
+ >
+ + Add another property
+ </a>
+ </div>
+ """
+ end
+
+ attr(:pair_id, :string, required: true)
+ attr(:myself, :any, required: true)
+
+ def remove_property_button(assigns) do
+ ~H"""
+ <div class="inline-flex items-center text-red-500" data-test-id={"remove-property-#{@pair_id}"}>
+ <svg
+ id={"remove-property-#{@pair_id}"}
+ class="feather feather-sm cursor-pointer"
+ xmlns="http://www.w3.org/2000/svg"
+ viewBox="0 0 24 24"
+ fill="none"
+ stroke="currentColor"
+ stroke-width="2"
+ stroke-linecap="round"
+ stroke-linejoin="round"
+ phx-click="remove-slot"
+ phx-value-pair-id={@pair_id}
+ phx-target={@myself}
+ >
+ <polyline points="3 6 5 6 21 6"></polyline>
+ <path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2">
+ </path>
+ <line x1="10" y1="11" x2="10" y2="17"></line>
+ <line x1="14" y1="11" x2="14" y2="17"></line>
+ </svg>
+ </div>
+ """
+ end
+
+ def handle_event("add-slot", _, socket) do
+ slots = socket.assigns.slots ++ to_list_with_ids(empty_row())
+ {:noreply, assign(socket, slots: slots)}
+ end
+
+ def handle_event("remove-slot", %{"pair-id" => id}, socket) do
+ slots = List.keydelete(socket.assigns.slots, id, 0)
+ {:noreply, assign(socket, slots: slots)}
+ end
+
+ defp to_list_with_ids(custom_props_map) do
+ Enum.into(custom_props_map, [], fn {k, v} -> {Ecto.UUID.generate(), {k, v}} end)
+ end
+
+ defp empty_row() do
+ %{"" => ""}
+ end
+end
diff --git a/lib/plausible_web/live/shared_link_settings.ex b/lib/plausible_web/live/shared_link_settings.ex
index 1592b7a390..ba87d3edd9 100644
--- a/lib/plausible_web/live/shared_link_settings.ex
+++ b/lib/plausible_web/live/shared_link_settings.ex
@@ -130,7 +130,7 @@ defmodule PlausibleWeb.Live.SharedLinkSettings do
<:tooltip_content>
Password protected
</:tooltip_content>
- <Heroicons.lock_closed class="feather ml-2 mb-0.5" />
+ <Heroicons.lock_closed class="size-3.5 mt-px ml-2 mb-0.5 stroke-2" />
</.tooltip>
<.tooltip
:if={!Plausible.Site.SharedLink.password_protected?(link)}
@@ -140,13 +140,13 @@ defmodule PlausibleWeb.Live.SharedLinkSettings do
<:tooltip_content>
No password protection
</:tooltip_content>
- <Heroicons.lock_open class="feather ml-2 mb-0.5" />
+ <Heroicons.lock_open class="size-3.5 mt-px ml-2 mb-0.5 stroke-2" />
</.tooltip>
<.tooltip :if={link.segment_id} enabled?={true} centered?={true}>
<:tooltip_content>
Limited to segment of data
</:tooltip_content>
- <Heroicons.eye_slash class="feather ml-1" />
+ <Heroicons.eye_slash class="size-3.5 mt-px ml-1 stroke-2" />
</.tooltip>
</div>
</.td>
diff --git a/priv/repo/seeds.exs b/priv/repo/seeds.exs
index 1522defcfc..1ef0801695 100644
--- a/priv/repo/seeds.exs
+++ b/priv/repo/seeds.exs
@@ -125,6 +125,20 @@ seeded_token = Plausible.Plugins.API.Token.generate("seed-token")
{:ok, _goal5} = Plausible.Goals.create(site, %{"page_path" => Enum.random(long_random_paths)})
{:ok, outbound} = Plausible.Goals.create(site, %{"event_name" => "Outbound Link: Click"})
+{:ok, goal6} =
+ Plausible.Goals.create(site, %{
+ "page_path" => "/",
+ "display_name" => "Anonymous visit to /",
+ "custom_props" => %{"logged_in" => "false"}
+ })
+
+{:ok, goal7} =
+ Plausible.Goals.create(site, %{
+ "page_path" => "/",
+ "display_name" => "Authenticated visit to /",
+ "custom_props" => %{"logged_in" => "true"}
+ })
+
if ee?() do
{:ok, _funnel} =
Plausible.Funnels.create(site, "From homepage to login", [
@@ -132,6 +146,20 @@ if ee?() do
%{"goal_id" => goal2.id},
%{"goal_id" => goal3.id}
])
+
+ {:ok, _funnel} =
+ Plausible.Funnels.create(site, "From anonymous homepage to login", [
+ %{"goal_id" => goal6.id},
+ %{"goal_id" => goal2.id},
+ %{"goal_id" => goal3.id}
+ ])
+
+ {:ok, _funnel} =
+ Plausible.Funnels.create(site, "From logged in homepage to Purchase", [
+ %{"goal_id" => goal6.id},
+ %{"goal_id" => goal2.id},
+ %{"goal_id" => revenue_goal.id}
+ ])
end
geolocations = [
diff --git a/test/plausible/goals_test.exs b/test/plausible/goals_test.exs
index 7568b23224..ddbb5301a8 100644
--- a/test/plausible/goals_test.exs
+++ b/test/plausible/goals_test.exs
@@ -377,6 +377,45 @@ defmodule Plausible.GoalsTest do
Goals.create(site, %{"event_name" => "Purchase", "currency" => "EUR"})
end
+ test "create/2 returns error when site does not have access to custom props on goals" do
+ user = new_user() |> subscribe_to_growth_plan()
+ site = new_site(owner: user)
+
+ {:error, :upgrade_required} =
+ Goals.create(site, %{"event_name" => "Signup", "custom_props" => %{"plan" => "premium"}})
+ end
+
+ test "for_site/2 with include_goals_with_custom_props?: false excludes goals with custom props" do
+ site = new_site()
+
+ _goal_with_props =
+ insert(:goal, site: site, event_name: "Purchase", custom_props: %{"product" => "Shirt"})
+
+ goal_without_props = insert(:goal, site: site, event_name: "Signup")
+
+ filtered = Goals.for_site(site, include_goals_with_custom_props?: false)
+
+ assert length(filtered) == 1
+ assert hd(filtered).id == goal_without_props.id
+ end
+
+ test "for_site/2 includes all goals by default (include_goals_with_custom_props? defaults to true)" do
+ user = new_user()
+ site = new_site(owner: user)
+
+ {:ok, _goal_with_props} =
+ Goals.create(site, %{
+ "event_name" => "Purchase",
+ "custom_props" => %{"product" => "Shirt"}
+ })
+
+ {:ok, _goal_without_props} = Goals.create(site, %{"event_name" => "Signup"})
+
+ all_goals = Goals.for_site(site)
+
+ assert length(all_goals) == 2
+ end
+
test "create/2 returns error when creating a revenue goal for consolidated view" do
user = new_user()
new_site(owner: user)
@@ -455,6 +494,14 @@ defmodule Plausible.GoalsTest do
end
on_ee do
+ test "update/2 prevents changing currency of existing revenue goal" do
+ site = new_site()
+ {:ok, goal} = Goals.create(site, %{"event_name" => "Purchase", "currency" => "EUR"})
+
+ assert {:error, changeset} = Goals.update(goal, %{"currency" => "USD"})
+ assert {"cannot change currency of existing goal", _} = changeset.errors[:currency]
+ end
+
test "list_revenue_goals/1 lists event_names and currencies for each revenue goal" do
site = new_site()
diff --git a/test/plausible/stats/goal_suggestions_test.exs b/test/plausible/stats/goal_suggestions_test.exs
index fec40f3a60..62b74cbb53 100644
--- a/test/plausible/stats/goal_suggestions_test.exs
+++ b/test/plausible/stats/goal_suggestions_test.exs
@@ -102,4 +102,407 @@ defmodule Plausible.Stats.GoalSuggestionsTest do
assert GoalSuggestions.suggest_event_names(site, "") == []
end
end
+
+ describe "suggest_custom_property_names/3" do
+ setup [:create_user, :create_site]
+
+ test "returns custom property names from the last 30 days, ordered by usage count", %{
+ site: site
+ } do
+ populate_stats(site, [
+ build(:event,
+ name: "Purchase",
+ "meta.key": ["amount", "plan"],
+ "meta.value": ["100", "business"],
+ timestamp: NaiveDateTime.utc_now() |> NaiveDateTime.shift(day: -1)
+ ),
+ build(:event,
+ name: "Purchase",
+ "meta.key": ["plan"],
+ "meta.value": ["enterprise"],
+ timestamp: NaiveDateTime.utc_now() |> NaiveDateTime.shift(day: -5)
+ ),
+ build(:event,
+ name: "Signup",
+ "meta.key": ["plan", "referrer"],
+ "meta.value": ["starter", "friend"],
+ timestamp: NaiveDateTime.utc_now() |> NaiveDateTime.shift(day: -10)
+ ),
+ build(:event,
+ name: "Click",
+ "meta.key": ["button_id"],
+ "meta.value": ["submit-btn"],
+ timestamp: NaiveDateTime.utc_now() |> NaiveDateTime.shift(day: -20)
+ )
+ ])
+
+ # "plan" appears 3 times, "amount" 1 time, "referrer" 1 time, "button_id" 1 time
+ assert GoalSuggestions.suggest_custom_property_names(site, "") == [
+ "plan",
+ "referrer",
+ "amount",
+ "button_id"
+ ]
+ end
+
+ test "filters property names by search input", %{site: site} do
+ populate_stats(site, [
+ build(:event,
+ name: "Purchase",
+ "meta.key": ["plan_type", "payment_method", "amount"],
+ "meta.value": ["business", "credit_card", "100"],
+ timestamp: NaiveDateTime.utc_now() |> NaiveDateTime.shift(day: -1)
+ ),
+ build(:event,
+ name: "Signup",
+ "meta.key": ["referrer", "plan_name"],
+ "meta.value": ["google", "starter"],
+ timestamp: NaiveDateTime.utc_now() |> NaiveDateTime.shift(day: -2)
+ )
+ ])
+
+ assert GoalSuggestions.suggest_custom_property_names(site, "plan") == [
+ "plan_name",
+ "plan_type"
+ ]
+ end
+
+ test "excludes events older than 30 days", %{site: site} do
+ populate_stats(site, [
+ build(:event,
+ name: "Purchase",
+ "meta.key": ["recent_prop"],
+ "meta.value": ["value1"],
+ timestamp: NaiveDateTime.utc_now() |> NaiveDateTime.shift(day: -29)
+ ),
+ build(:event,
+ name: "Purchase",
+ "meta.key": ["old_prop"],
+ "meta.value": ["value2"],
+ timestamp: NaiveDateTime.utc_now() |> NaiveDateTime.shift(day: -31)
+ )
+ ])
+
+ assert GoalSuggestions.suggest_custom_property_names(site, "") == ["recent_prop"]
+ assert GoalSuggestions.suggest_custom_property_names(site, "prop") == ["recent_prop"]
+ end
+
+ test "returns empty list when no custom properties exist", %{site: site} do
+ populate_stats(site, [
+ build(:event, name: "Purchase", timestamp: NaiveDateTime.utc_now())
+ ])
+
+ assert GoalSuggestions.suggest_custom_property_names(site, "") == []
+ end
+
+ test "handles nil search input", %{site: site} do
+ populate_stats(site, [
+ build(:event,
+ name: "Purchase",
+ "meta.key": ["plan"],
+ "meta.value": ["business"],
+ timestamp: NaiveDateTime.utc_now()
+ )
+ ])
+
+ assert GoalSuggestions.suggest_custom_property_names(site, nil) == ["plan"]
+ end
+
+ test "includes allowed_prop_names from site configuration when no event data exists", %{
+ site: site
+ } do
+ site =
+ site
+ |> Ecto.Changeset.change(allowed_event_props: ["prop_a", "prop_b", "prop_c"])
+ |> Repo.update!()
+
+ suggestions = GoalSuggestions.suggest_custom_property_names(site, "")
+
+ assert suggestions == ["prop_a", "prop_b", "prop_c"]
+ end
+
+ test "combines event_prop_names and allowed_prop_names, prioritizing event usage", %{
+ site: site
+ } do
+ site =
+ site
+ |> Ecto.Changeset.change(
+ allowed_event_props: ["allowed_prop", "shared_prop", "another_allowed"]
+ )
+ |> Repo.update!()
+
+ populate_stats(site, [
+ build(:event,
+ name: "Purchase",
+ "meta.key": ["event_prop"],
+ "meta.value": ["value1"],
+ timestamp: NaiveDateTime.utc_now() |> NaiveDateTime.shift(day: -1)
+ ),
+ build(:event,
+ name: "Purchase",
+ "meta.key": ["event_prop"],
+ "meta.value": ["value2"],
+ timestamp: NaiveDateTime.utc_now() |> NaiveDateTime.shift(day: -2)
+ ),
+ build(:event,
+ name: "Signup",
+ "meta.key": ["shared_prop"],
+ "meta.value": ["value3"],
+ timestamp: NaiveDateTime.utc_now() |> NaiveDateTime.shift(day: -3)
+ )
+ ])
+
+ suggestions = GoalSuggestions.suggest_custom_property_names(site, "")
+
+ assert suggestions == ["event_prop", "shared_prop", "allowed_prop", "another_allowed"]
+ end
+
+ test "filters allowed_prop_names by search input (case-insensitive)", %{
+ site: site
+ } do
+ site =
+ site
+ |> Ecto.Changeset.change(
+ allowed_event_props: ["plan_type", "user_plan", "payment_method", "amount"]
+ )
+ |> Repo.update!()
+
+ suggestions = GoalSuggestions.suggest_custom_property_names(site, "plan")
+
+ assert suggestions == ["plan_type", "user_plan"]
+ end
+
+ test "filters both event_prop_names and allowed_prop_names by search input", %{site: site} do
+ site =
+ site
+ |> Ecto.Changeset.change(allowed_event_props: ["plan_type", "user_plan", "amount"])
+ |> Repo.update!()
+
+ populate_stats(site, [
+ build(:event,
+ name: "Purchase",
+ "meta.key": ["plan_name", "payment_method"],
+ "meta.value": ["business", "credit_card"],
+ timestamp: NaiveDateTime.utc_now() |> NaiveDateTime.shift(day: -1)
+ )
+ ])
+
+ suggestions = GoalSuggestions.suggest_custom_property_names(site, "plan")
+
+ assert suggestions == ["plan_name", "plan_type", "user_plan"]
+ end
+
+ test "handles case-insensitive search matching for allowed_prop_names", %{site: site} do
+ site =
+ site
+ |> Ecto.Changeset.change(allowed_event_props: ["UserPlan", "PLAN_TYPE", "Payment_Method"])
+ |> Repo.update!()
+
+ suggestions = GoalSuggestions.suggest_custom_property_names(site, "plan")
+
+ assert suggestions == ["PLAN_TYPE", "UserPlan"]
+ end
+
+ test "deduplicates when property exists in both event_prop_names and allowed_prop_names", %{
+ site: site
+ } do
+ site =
+ site
+ |> Ecto.Changeset.change(allowed_event_props: ["plan", "amount", "referrer"])
+ |> Repo.update!()
+
+ populate_stats(site, [
+ build(:event,
+ name: "Purchase",
+ "meta.key": ["plan", "category"],
+ "meta.value": ["business", "software"],
+ timestamp: NaiveDateTime.utc_now() |> NaiveDateTime.shift(day: -1)
+ ),
+ build(:event,
+ name: "Purchase",
+ "meta.key": ["plan"],
+ "meta.value": ["enterprise"],
+ timestamp: NaiveDateTime.utc_now() |> NaiveDateTime.shift(day: -2)
+ )
+ ])
+
+ suggestions = GoalSuggestions.suggest_custom_property_names(site, "")
+
+ # plan appears only once
+ assert suggestions == ["plan", "category", "amount", "referrer"]
+ end
+
+ test "handles empty allowed_event_props gracefully", %{site: site} do
+ site =
+ site
+ |> Ecto.Changeset.change(allowed_event_props: [])
+ |> Repo.update!()
+
+ populate_stats(site, [
+ build(:event,
+ name: "Purchase",
+ "meta.key": ["plan"],
+ "meta.value": ["business"],
+ timestamp: NaiveDateTime.utc_now()
+ )
+ ])
+
+ suggestions = GoalSuggestions.suggest_custom_property_names(site, "")
+ assert suggestions == ["plan"]
+ end
+
+ test "handles nil allowed_event_props gracefully", %{site: site} do
+ site =
+ site
+ |> Ecto.Changeset.change(allowed_event_props: nil)
+ |> Repo.update!()
+
+ populate_stats(site, [
+ build(:event,
+ name: "Purchase",
+ "meta.key": ["plan"],
+ "meta.value": ["business"],
+ timestamp: NaiveDateTime.utc_now()
+ )
+ ])
+
+ suggestions = GoalSuggestions.suggest_custom_property_names(site, "")
+ assert suggestions == ["plan"]
+ end
+ end
+
+ describe "suggest_custom_property_values/3" do
+ setup [:create_user, :create_site]
+
+ test "returns custom property values for a given key from the last 30 days", %{site: site} do
+ populate_stats(site, [
+ build(:event,
+ name: "Purchase",
+ "meta.key": ["plan"],
+ "meta.value": ["business"],
+ timestamp: NaiveDateTime.utc_now() |> NaiveDateTime.shift(day: -1)
+ ),
+ build(:event,
+ name: "Purchase",
+ "meta.key": ["plan"],
+ "meta.value": ["business"],
+ timestamp: NaiveDateTime.utc_now() |> NaiveDateTime.shift(day: -2)
+ ),
+ build(:event,
+ name: "Purchase",
+ "meta.key": ["plan"],
+ "meta.value": ["enterprise"],
+ timestamp: NaiveDateTime.utc_now() |> NaiveDateTime.shift(day: -3)
+ ),
+ build(:event,
+ name: "Signup",
+ "meta.key": ["plan"],
+ "meta.value": ["starter"],
+ timestamp: NaiveDateTime.utc_now() |> NaiveDateTime.shift(day: -5)
+ )
+ ])
+
+ assert GoalSuggestions.suggest_custom_property_values(site, "plan", "") == [
+ "business",
+ "starter",
+ "enterprise"
+ ]
+ end
+
+ test "filters property values by search input", %{site: site} do
+ populate_stats(site, [
+ build(:event,
+ name: "Purchase",
+ "meta.key": ["plan"],
+ "meta.value": ["business_monthly"],
+ timestamp: NaiveDateTime.utc_now() |> NaiveDateTime.shift(day: -1)
+ ),
+ build(:event,
+ name: "Purchase",
+ "meta.key": ["plan"],
+ "meta.value": ["business_yearly"],
+ timestamp: NaiveDateTime.utc_now() |> NaiveDateTime.shift(day: -2)
+ ),
+ build(:event,
+ name: "Purchase",
+ "meta.key": ["plan"],
+ "meta.value": ["starter"],
+ timestamp: NaiveDateTime.utc_now() |> NaiveDateTime.shift(day: -3)
+ )
+ ])
+
+ assert GoalSuggestions.suggest_custom_property_values(site, "plan", "business") == [
+ "business_yearly",
+ "business_monthly"
+ ]
+ end
+
+ test "excludes events older than 30 days", %{site: site} do
+ populate_stats(site, [
+ build(:event,
+ name: "Purchase",
+ "meta.key": ["plan"],
+ "meta.value": ["recent_plan"],
+ timestamp: NaiveDateTime.utc_now() |> NaiveDateTime.shift(day: -29)
+ ),
+ build(:event,
+ name: "Purchase",
+ "meta.key": ["plan"],
+ "meta.value": ["old_plan"],
+ timestamp: NaiveDateTime.utc_now() |> NaiveDateTime.shift(day: -31)
+ )
+ ])
+
+ assert GoalSuggestions.suggest_custom_property_values(site, "plan", "") == [
+ "recent_plan"
+ ]
+ end
+
+ test "handles nil search input", %{site: site} do
+ populate_stats(site, [
+ build(:event,
+ name: "Purchase",
+ "meta.key": ["plan"],
+ "meta.value": ["business"],
+ timestamp: NaiveDateTime.utc_now()
+ )
+ ])
+
+ assert GoalSuggestions.suggest_custom_property_values(site, "plan", nil) == ["business"]
+ end
+
+ test "orders values by count", %{site: site} do
+ populate_stats(site, [
+ build(:event,
+ name: "Purchase",
+ "meta.key": ["plan"],
+ "meta.value": ["starter"],
+ timestamp: NaiveDateTime.utc_now()
+ ),
+ build(:event,
+ name: "Purchase",
+ "meta.key": ["plan"],
+ "meta.value": ["business"],
+ timestamp: NaiveDateTime.utc_now()
+ ),
+ build(:event,
+ name: "Purchase",
+ "meta.key": ["plan"],
+ "meta.value": ["business"],
+ timestamp: NaiveDateTime.utc_now()
+ ),
+ build(:event,
+ name: "Purchase",
+ "meta.key": ["plan"],
+ "meta.value": ["business"],
+ timestamp: NaiveDateTime.utc_now()
+ )
+ ])
+
+ assert GoalSuggestions.suggest_custom_property_values(site, "plan", "") == [
+ "business",
+ "starter"
+ ]
+ end
+ end
end
diff --git a/test/plausible_web/controllers/api/external_stats_controller/query_goal_custom_props_equivalence_test.exs b/test/plausible_web/controllers/api/external_stats_controller/query_goal_custom_props_equivalence_test.exs
new file mode 100644
index 0000000000..953815b750
--- /dev/null
+++ b/test/plausible_web/controllers/api/external_stats_controller/query_goal_custom_props_equivalence_test.exs
@@ -0,0 +1,261 @@
+defmodule PlausibleWeb.Api.ExternalStatsController.QueryGoalCustomPropsEquivalenceTest do
+ @moduledoc """
+ Tests that filtering by a goal with custom props produces the same results
+ as filtering by the goal without custom props AND a separate custom prop filter.
+
+ For example, these two queries should return identical results:
+ 1. Filter by goal "Visit /" with custom_props: {"browser_language" => "FR"}
+ 2. Filter by goal "Visit /" (no custom props) AND filter by event:props:browser_language = "FR"
+ """
+ use PlausibleWeb.ConnCase
+
+ setup [:create_user, :create_site, :create_api_key, :use_api_key]
+
+ alias Plausible.Goals
+
+ describe "goal with custom props equivalence" do
+ test "page goal with custom props equals page goal + separate prop filter", %{
+ conn: conn,
+ site: site
+ } do
+ {:ok, _goal_with_props} =
+ Goals.create(site, %{
+ "page_path" => "/landing",
+ "custom_props" => %{"browser_language" => "FR"}
+ })
+
+ {:ok, _goal_without_props} =
+ Goals.create(site, %{
+ "page_path" => "/landing",
+ "display_name" => "Visit /landing-no-props"
+ })
+
+ populate_stats(site, [
+ # Session 1 (FR): Has pageview with browser_language=FR
+ build(:pageview,
+ user_id: 1,
+ pathname: "/landing",
+ country_code: "FR",
+ "meta.key": ["browser_language"],
+ "meta.value": ["FR"],
+ timestamp: ~N[2021-01-01 00:00:00]
+ ),
+ # Session 2 (US): Has pageview with browser_language=EN
+ build(:pageview,
+ user_id: 2,
+ pathname: "/landing",
+ country_code: "US",
+ "meta.key": ["browser_language"],
+ "meta.value": ["EN"],
+ timestamp: ~N[2021-01-01 00:00:00]
+ ),
+ # Session 3 (GB): Has pageview with no props
+ build(:pageview,
+ user_id: 3,
+ pathname: "/landing",
+ country_code: "GB",
+ timestamp: ~N[2021-01-01 00:00:00]
+ )
+ ])
+
+ # Query 1: Page goal with custom props
+ conn1 =
+ post(conn, "/api/v2/query", %{
+ "site_id" => site.domain,
+ "date_range" => "all",
+ "metrics" => ["visitors", "visits", "events"],
+ "dimensions" => ["visit:country"],
+ "filters" => [["is", "event:goal", ["Visit /landing"]]]
+ })
+
+ result1 = json_response(conn1, 200)["results"]
+
+ # Query 2: Page goal without props + separate prop filter
+ conn2 =
+ post(conn, "/api/v2/query", %{
+ "site_id" => site.domain,
+ "date_range" => "all",
+ "metrics" => ["visitors", "visits", "events"],
+ "dimensions" => ["visit:country"],
+ "filters" => [
+ ["is", "event:goal", ["Visit /landing-no-props"]],
+ ["is", "event:props:browser_language", ["FR"]]
+ ]
+ })
+
+ result2 = json_response(conn2, 200)["results"]
+
+ # Both should return only FR
+ assert result1 == [%{"dimensions" => ["FR"], "metrics" => [1, 1, 1]}]
+ assert result2 == [%{"dimensions" => ["FR"], "metrics" => [1, 1, 1]}]
+ assert result1 == result2
+ end
+
+ test "event goal with custom props equals event goal + separate prop filter", %{
+ conn: conn,
+ site: site
+ } do
+ {:ok, _goal_with_props} =
+ Goals.create(site, %{
+ "event_name" => "Signup",
+ "custom_props" => %{"plan" => "premium"}
+ })
+
+ {:ok, _goal_without_props} =
+ Goals.create(site, %{
+ "display_name" => "SignupNoProps",
+ "event_name" => "Signup"
+ })
+
+ populate_stats(site, [
+ # Session 1 (US): Has correct event with plan=premium
+ build(:pageview,
+ user_id: 1,
+ country_code: "US",
+ timestamp: ~N[2021-01-01 00:00:00]
+ ),
+ build(:event,
+ user_id: 1,
+ name: "Signup",
+ "meta.key": ["plan"],
+ "meta.value": ["premium"],
+ timestamp: ~N[2021-01-01 00:00:01]
+ ),
+ # Session 2 (GB): Has event with plan=basic
+ build(:pageview,
+ user_id: 2,
+ country_code: "GB",
+ timestamp: ~N[2021-01-01 00:00:00]
+ ),
+ build(:event,
+ user_id: 2,
+ name: "Signup",
+ "meta.key": ["plan"],
+ "meta.value": ["basic"],
+ timestamp: ~N[2021-01-01 00:00:01]
+ ),
+ # Session 3 (CA): Has event but no props at all
+ build(:pageview,
+ user_id: 3,
+ country_code: "CA",
+ timestamp: ~N[2021-01-01 00:00:00]
+ ),
+ build(:event,
+ user_id: 3,
+ name: "Signup",
+ timestamp: ~N[2021-01-01 00:00:01]
+ )
+ ])
+
+ # Query 1: Event goal with custom props
+ conn1 =
+ post(conn, "/api/v2/query", %{
+ "site_id" => site.domain,
+ "date_range" => "all",
+ "metrics" => ["visitors", "visits", "events"],
+ "dimensions" => ["visit:country"],
+ "filters" => [["is", "event:goal", ["Signup"]]]
+ })
+
+ result1 = json_response(conn1, 200)["results"]
+
+ # Query 2: Event goal without props + separate prop filter
+ conn2 =
+ post(conn, "/api/v2/query", %{
+ "site_id" => site.domain,
+ "date_range" => "all",
+ "metrics" => ["visitors", "visits", "events"],
+ "dimensions" => ["visit:country"],
+ "filters" => [
+ ["is", "event:goal", ["SignupNoProps"]],
+ ["is", "event:props:plan", ["premium"]]
+ ]
+ })
+
+ result2 = json_response(conn2, 200)["results"]
+
+ # Both should return only US
+ assert result1 == [%{"dimensions" => ["US"], "metrics" => [1, 1, 1]}]
+ assert result2 == [%{"dimensions" => ["US"], "metrics" => [1, 1, 1]}]
+ assert result1 == result2
+ end
+
+ test "page goal with multiple custom props equals page goal + multiple separate prop filters",
+ %{conn: conn, site: site} do
+ {:ok, _goal_with_props} =
+ Goals.create(site, %{
+ "page_path" => "/checkout",
+ "custom_props" => %{"currency" => "EUR", "country" => "DE"}
+ })
+
+ {:ok, _goal_without_props} =
+ Goals.create(site, %{
+ "page_path" => "/checkout",
+ "display_name" => "Visit /checkout-no-props"
+ })
+
+ populate_stats(site, [
+ # Session 1 (DE): Has pageview with both props matching
+ build(:pageview,
+ user_id: 1,
+ pathname: "/checkout",
+ country_code: "DE",
+ "meta.key": ["currency", "country"],
+ "meta.value": ["EUR", "DE"],
+ timestamp: ~N[2021-01-01 00:00:00]
+ ),
+ # Session 2 (FR): Has pageview with only currency matching
+ build(:pageview,
+ user_id: 2,
+ pathname: "/checkout",
+ country_code: "FR",
+ "meta.key": ["currency", "country"],
+ "meta.value": ["EUR", "FR"],
+ timestamp: ~N[2021-01-01 00:00:00]
+ ),
+ # Session 3 (US): Has pageview with neither matching
+ build(:pageview,
+ user_id: 3,
+ pathname: "/checkout",
+ country_code: "US",
+ "meta.key": ["currency", "country"],
+ "meta.value": ["USD", "US"],
+ timestamp: ~N[2021-01-01 00:00:00]
+ )
+ ])
+
+ # Query 1: Page goal with multiple custom props
+ conn1 =
+ post(conn, "/api/v2/query", %{
+ "site_id" => site.domain,
+ "date_range" => "all",
+ "metrics" => ["visitors", "visits", "events"],
+ "dimensions" => ["visit:country"],
+ "filters" => [["is", "event:goal", ["Visit /checkout"]]]
+ })
+
+ result1 = json_response(conn1, 200)["results"]
+
+ # Query 2: Page goal without props + multiple separate prop filters
+ conn2 =
+ post(conn, "/api/v2/query", %{
+ "site_id" => site.domain,
+ "date_range" => "all",
+ "metrics" => ["visitors", "visits", "events"],
+ "dimensions" => ["visit:country"],
+ "filters" => [
+ ["is", "event:goal", ["Visit /checkout-no-props"]],
+ ["is", "event:props:currency", ["EUR"]],
+ ["is", "event:props:country", ["DE"]]
+ ]
+ })
+
+ result2 = json_response(conn2, 200)["results"]
+
+ # Both should return only DE (both props must match)
+ assert result1 == [%{"dimensions" => ["DE"], "metrics" => [1, 1, 1]}]
+ assert result2 == [%{"dimensions" => ["DE"], "metrics" => [1, 1, 1]}]
+ assert result1 == result2
+ end
+ end
+end
diff --git a/test/plausible_web/controllers/api/external_stats_controller/query_goal_custom_props_test.exs b/test/plausible_web/controllers/api/external_stats_controller/query_goal_custom_props_test.exs
index 2548053902..360e00a642 100644
--- a/test/plausible_web/controllers/api/external_stats_controller/query_goal_custom_props_test.exs
+++ b/test/plausible_web/controllers/api/external_stats_controller/query_goal_custom_props_test.exs
@@ -1,8 +1,6 @@
defmodule PlausibleWeb.Api.ExternalStatsController.QueryGoalCustomPropsTest do
use PlausibleWeb.ConnCase
- @user_id Enum.random(1000..9999)
-
setup [:create_user, :create_site, :create_api_key, :use_api_key]
alias Plausible.Goals
@@ -72,19 +70,19 @@ defmodule PlausibleWeb.Api.ExternalStatsController.QueryGoalCustomPropsTest do
name: "Purchase",
"meta.key": ["variant", "plan"],
"meta.value": ["A", "free"],
- user_id: @user_id
+ user_id: 1
),
build(:event,
name: "Purchase",
"meta.key": ["variant", "plan"],
"meta.value": ["B", "premium"],
- user_id: @user_id + 1
+ user_id: 2
),
build(:event,
name: "Purchase",
"meta.key": ["variant"],
"meta.value": ["A"],
- user_id: @user_id + 2
+ user_id: 3
)
])
@@ -149,19 +147,19 @@ defmodule PlausibleWeb.Api.ExternalStatsController.QueryGoalCustomPropsTest do
name: "Purchase A",
"meta.key": ["variant"],
"meta.value": ["A"],
- user_id: @user_id
+ user_id: 1
),
build(:event,
name: "Purchase A",
"meta.key": ["variant"],
"meta.value": ["A"],
- user_id: @user_id
+ user_id: 1
),
build(:event,
name: "Purchase B",
"meta.key": ["variant"],
"meta.value": ["B"],
- user_id: @user_id
+ user_id: 1
)
])
@@ -187,21 +185,21 @@ defmodule PlausibleWeb.Api.ExternalStatsController.QueryGoalCustomPropsTest do
})
populate_stats(site, [
- build(:pageview, user_id: @user_id),
+ build(:pageview, user_id: 1),
build(:event,
name: "Signup",
"meta.key": ["method"],
"meta.value": ["email"],
- user_id: @user_id
+ user_id: 1
),
- build(:pageview, user_id: @user_id + 1),
+ build(:pageview, user_id: 2),
build(:event,
name: "Signup",
"meta.key": ["method"],
"meta.value": ["google"],
- user_id: @user_id + 1
+ user_id: 2
),
- build(:pageview, user_id: @user_id + 2)
+ build(:pageview, user_id: 3)
])
conn =
@@ -237,13 +235,13 @@ defmodule PlausibleWeb.Api.ExternalStatsController.QueryGoalCustomPropsTest do
name: "Purchase",
"meta.key": ["variant", "plan"],
"meta.value": ["A", "free"],
- user_id: @user_id + 1
+ user_id: 2
),
build(:event,
name: "Purchase",
"meta.key": ["variant", "plan"],
"meta.value": ["B", "premium"],
- user_id: @user_id + 2
+ user_id: 3
)
])
@@ -329,21 +327,21 @@ defmodule PlausibleWeb.Api.ExternalStatsController.QueryGoalCustomPropsTest do
name: "Button Click",
"meta.key": ["color"],
"meta.value": ["red"],
- user_id: @user_id
+ user_id: 1
),
build(:event,
name: "Button Click",
"meta.key": ["color"],
"meta.value": ["red"],
- user_id: @user_id
+ user_id: 1
),
build(:event,
name: "Button Click",
"meta.key": ["color"],
"meta.value": ["blue"],
- user_id: @user_id + 1
+ user_id: 2
),
- build(:event, name: "Button Click", user_id: @user_id + 2)
+ build(:event, name: "Button Click", user_id: 3)
])
conn =
diff --git a/test/plausible_web/controllers/api/external_stats_controller/query_goal_custom_props_visit_dimensions_test.exs b/test/plausible_web/controllers/api/external_stats_controller/query_goal_custom_props_visit_dimensions_test.exs
new file mode 100644
index 0000000000..070d1bc124
--- /dev/null
+++ b/test/plausible_web/controllers/api/external_stats_controller/query_goal_custom_props_visit_dimensions_test.exs
@@ -0,0 +1,411 @@
+defmodule PlausibleWeb.Api.ExternalStatsController.QueryGoalCustomPropsVisitDimensionsTest do
+ use PlausibleWeb.ConnCase
+
+ setup [:create_user, :create_site, :create_api_key, :use_api_key]
+
+ alias Plausible.Goals
+
+ describe "visit dimensions filtered by goals with custom props" do
+ test "filters visit:country by goal with custom props correctly", %{conn: conn, site: site} do
+ {:ok, _goal} =
+ Goals.create(site, %{
+ "event_name" => "Signup",
+ "custom_props" => %{"plan" => "premium"}
+ })
+
+ populate_stats(site, [
+ # Session 1 (US): Has correct event (Signup with plan=premium)
+ build(:pageview,
+ user_id: 1,
+ country_code: "US",
+ timestamp: ~N[2021-01-01 00:00:00]
+ ),
+ build(:event,
+ user_id: 1,
+ name: "Signup",
+ "meta.key": ["plan"],
+ "meta.value": ["premium"],
+ timestamp: ~N[2021-01-01 00:00:01]
+ ),
+ # Session 2 (GB): Has wrong event (Signup with plan=basic)
+ build(:pageview,
+ user_id: 2,
+ country_code: "GB",
+ timestamp: ~N[2021-01-01 00:00:00]
+ ),
+ build(:event,
+ user_id: 2,
+ name: "Signup",
+ "meta.key": ["plan"],
+ "meta.value": ["basic"],
+ timestamp: ~N[2021-01-01 00:00:02]
+ ),
+ # Session 3 (CA): Has event with event name but no custom props
+ build(:pageview,
+ user_id: 3,
+ country_code: "CA",
+ timestamp: ~N[2021-01-01 00:00:00]
+ ),
+ build(:event,
+ user_id: 4,
+ name: "Signup",
+ timestamp: ~N[2021-01-01 00:00:03]
+ ),
+ # Session 4 (DE): Has no Signup event at all
+ build(:pageview,
+ user_id: 5,
+ country_code: "DE",
+ timestamp: ~N[2021-01-01 00:00:00]
+ )
+ ])
+
+ conn =
+ post(conn, "/api/v2/query", %{
+ "site_id" => site.domain,
+ "date_range" => "all",
+ "metrics" => ["visitors", "events"],
+ "dimensions" => ["visit:country"],
+ "filters" => [["is", "event:goal", ["Signup"]]]
+ })
+
+ resp = json_response(conn, 200)
+
+ # Only session 1 (US) should be included, as it's the only one with
+ # the correct event name AND matching custom props
+ assert resp["results"] == [
+ %{"dimensions" => ["US"], "metrics" => [1, 1]}
+ ]
+ end
+
+ test "filters visit:browser by goal with multiple custom props", %{conn: conn, site: site} do
+ {:ok, _goal} =
+ Goals.create(site, %{
+ "event_name" => "Purchase",
+ "custom_props" => %{"variant" => "A", "tier" => "gold"}
+ })
+
+ populate_stats(site, [
+ # Chrome - matches both props
+ build(:pageview,
+ user_id: 1,
+ browser: "Chrome",
+ timestamp: ~N[2021-01-01 00:00:00]
+ ),
+ build(:event,
+ user_id: 1,
+ name: "Purchase",
+ "meta.key": ["variant", "tier"],
+ "meta.value": ["A", "gold"],
+ timestamp: ~N[2021-01-01 00:00:01]
+ ),
+ # Firefox - matches only variant, not tier
+ build(:pageview,
+ user_id: 2,
+ browser: "Firefox",
+ timestamp: ~N[2021-01-01 00:00:00]
+ ),
+ build(:event,
+ user_id: 3,
+ name: "Purchase",
+ "meta.key": ["variant", "tier"],
+ "meta.value": ["A", "silver"],
+ timestamp: ~N[2021-01-01 00:00:02]
+ ),
+ # Safari - matches only tier, not variant
+ build(:pageview,
+ user_id: 4,
+ browser: "Safari",
+ timestamp: ~N[2021-01-01 00:00:00]
+ ),
+ build(:event,
+ user_id: 5,
+ name: "Purchase",
+ "meta.key": ["variant", "tier"],
+ "meta.value": ["B", "gold"],
+ timestamp: ~N[2021-01-01 00:00:03]
+ ),
+ # Edge - has event name but missing custom props entirely
+ build(:pageview,
+ user_id: 6,
+ browser: "Edge",
+ timestamp: ~N[2021-01-01 00:00:00]
+ ),
+ build(:event,
+ user_id: 7,
+ name: "Purchase",
+ timestamp: ~N[2021-01-01 00:00:04]
+ )
+ ])
+
+ conn =
+ post(conn, "/api/v2/query", %{
+ "site_id" => site.domain,
+ "date_range" => "all",
+ "metrics" => ["visitors", "events"],
+ "dimensions" => ["visit:browser"],
+ "filters" => [["is", "event:goal", ["Purchase"]]]
+ })
+
+ resp = json_response(conn, 200)
+
+ # Only session 1 (Chrome) should be included
+ assert resp["results"] == [
+ %{"dimensions" => ["Chrome"], "metrics" => [1, 1]}
+ ]
+ end
+
+ test "filters visit:city by goal with custom props", %{conn: conn, site: site} do
+ {:ok, _goal} =
+ Goals.create(site, %{
+ "event_name" => "Download",
+ "custom_props" => %{"file_type" => "pdf"}
+ })
+
+ populate_stats(site, [
+ # San Francisco - correct props
+ build(:pageview,
+ user_id: 1,
+ city_geoname_id: 5_391_959,
+ timestamp: ~N[2021-01-01 00:00:00]
+ ),
+ build(:event,
+ user_id: 1,
+ name: "Download",
+ "meta.key": ["file_type"],
+ "meta.value": ["pdf"],
+ timestamp: ~N[2021-01-01 00:00:01]
+ ),
+ # New York - wrong prop value
+ build(:pageview,
+ user_id: 2,
+ city_geoname_id: 5_128_581,
+ timestamp: ~N[2021-01-01 00:00:00]
+ ),
+ build(:event,
+ user_id: 3,
+ name: "Download",
+ "meta.key": ["file_type"],
+ "meta.value": ["docx"],
+ timestamp: ~N[2021-01-01 00:00:02]
+ )
+ ])
+
+ conn =
+ post(conn, "/api/v2/query", %{
+ "site_id" => site.domain,
+ "date_range" => "all",
+ "metrics" => ["visitors", "events"],
+ "dimensions" => ["visit:city"],
+ "filters" => [["is", "event:goal", ["Download"]]]
+ })
+
+ resp = json_response(conn, 200)
+
+ # Only San Francisco session should be included
+ assert length(resp["results"]) == 1
+ assert [%{"dimensions" => [5_391_959], "metrics" => [1, 1]}] = resp["results"]
+ end
+
+ test "filters visit:os by goal with custom prop containing special characters", %{
+ conn: conn,
+ site: site
+ } do
+ {:ok, _goal} =
+ Goals.create(site, %{
+ "event_name" => "Custom Event",
+ "custom_props" => %{"tag" => "test-value"}
+ })
+
+ populate_stats(site, [
+ # Mac - correct props
+ build(:pageview,
+ user_id: 1,
+ operating_system: "Mac",
+ timestamp: ~N[2021-01-01 00:00:00]
+ ),
+ build(:event,
+ user_id: 1,
+ name: "Custom Event",
+ "meta.key": ["tag"],
+ "meta.value": ["test-value"],
+ timestamp: ~N[2021-01-01 00:00:01]
+ ),
+ # Windows - wrong value
+ build(:pageview,
+ user_id: 2,
+ operating_system: "Windows",
+ timestamp: ~N[2021-01-01 00:00:00]
+ ),
+ build(:event,
+ user_id: 2,
+ name: "Custom Event",
+ "meta.key": ["tag"],
+ "meta.value": ["other-value"],
+ timestamp: ~N[2021-01-01 00:00:02]
+ )
+ ])
+
+ conn =
+ post(conn, "/api/v2/query", %{
+ "site_id" => site.domain,
+ "date_range" => "all",
+ "metrics" => ["visitors", "events"],
+ "dimensions" => ["visit:os"],
+ "filters" => [["is", "event:goal", ["Custom Event"]]]
+ })
+
+ resp = json_response(conn, 200)
+
+ # Only Mac session should be included
+ assert resp["results"] == [
+ %{"dimensions" => ["Mac"], "metrics" => [1, 1]}
+ ]
+ end
+
+ test "works with additional visit dimension filters combined", %{conn: conn, site: site} do
+ {:ok, _goal} =
+ Goals.create(site, %{
+ "event_name" => "Newsletter",
+ "custom_props" => %{"source" => "sidebar"}
+ })
+
+ populate_stats(site, [
+ # US/Chrome - correct props
+ build(:pageview,
+ user_id: 1,
+ country_code: "US",
+ browser: "Chrome",
+ timestamp: ~N[2021-01-01 00:00:00]
+ ),
+ build(:event,
+ user_id: 1,
+ name: "Newsletter",
+ "meta.key": ["source"],
+ "meta.value": ["sidebar"],
+ timestamp: ~N[2021-01-01 00:00:01]
+ ),
+ # US/Firefox - wrong props
+ build(:pageview,
+ user_id: 2,
+ country_code: "US",
+ browser: "Firefox",
+ timestamp: ~N[2021-01-01 00:00:00]
+ ),
+ build(:event,
+ user_id: 2,
+ name: "Newsletter",
+ "meta.key": ["source"],
+ "meta.value": ["footer"],
+ timestamp: ~N[2021-01-01 00:00:02]
+ ),
+ # GB/Chrome - correct props
+ build(:pageview,
+ user_id: 3,
+ country_code: "GB",
+ browser: "Chrome",
+ timestamp: ~N[2021-01-01 00:00:00]
+ ),
+ build(:event,
+ user_id: 3,
+ name: "Newsletter",
+ "meta.key": ["source"],
+ "meta.value": ["sidebar"],
+ timestamp: ~N[2021-01-01 00:00:03]
+ )
+ ])
+
+ # Filter by goal with custom props AND by country=US
+ conn =
+ post(conn, "/api/v2/query", %{
+ "site_id" => site.domain,
+ "date_range" => "all",
+ "metrics" => ["visitors", "events"],
+ "dimensions" => ["visit:browser"],
+ "filters" => [
+ ["is", "event:goal", ["Newsletter"]],
+ ["is", "visit:country", ["US"]]
+ ]
+ })
+
+ resp = json_response(conn, 200)
+
+ # Only session 1 (US/Chrome + correct props) should match
+ assert resp["results"] == [
+ %{"dimensions" => ["Chrome"], "metrics" => [1, 1]}
+ ]
+ end
+
+ test "handles multiple goal filters with different custom props", %{conn: conn, site: site} do
+ {:ok, _goal1} =
+ Goals.create(site, %{
+ "event_name" => "Action A",
+ "custom_props" => %{"type" => "alpha"}
+ })
+
+ {:ok, _goal2} =
+ Goals.create(site, %{
+ "event_name" => "Action B",
+ "custom_props" => %{"type" => "beta"}
+ })
+
+ populate_stats(site, [
+ build(:pageview,
+ user_id: 1,
+ country_code: "US",
+ timestamp: ~N[2021-01-01 00:00:00]
+ ),
+ build(:event,
+ user_id: 1,
+ name: "Action A",
+ "meta.key": ["type"],
+ "meta.value": ["alpha"],
+ timestamp: ~N[2021-01-01 00:00:01]
+ ),
+ build(:pageview,
+ user_id: 2,
+ country_code: "GB",
+ timestamp: ~N[2021-01-01 00:00:00]
+ ),
+ build(:event,
+ user_id: 2,
+ name: "Action B",
+ "meta.key": ["type"],
+ "meta.value": ["beta"],
+ timestamp: ~N[2021-01-01 00:00:02]
+ ),
+ build(:pageview,
+ user_id: 3,
+ country_code: "CA",
+ timestamp: ~N[2021-01-01 00:00:00]
+ ),
+ build(:event,
+ user_id: 3,
+ name: "Action A",
+ "meta.key": ["type"],
+ "meta.value": ["gamma"],
+ timestamp: ~N[2021-01-01 00:00:03]
+ )
+ ])
+
+ # Query for both goals (OR logic)
+ conn =
+ post(conn, "/api/v2/query", %{
+ "site_id" => site.domain,
+ "date_range" => "all",
+ "metrics" => ["visitors", "events"],
+ "dimensions" => ["visit:country"],
+ "filters" => [["is", "event:goal", ["Action A", "Action B"]]]
+ })
+
+ resp = json_response(conn, 200)
+
+ # Should match sessions 1 and 2 (both with correct props), but not 3
+ assert length(resp["results"]) == 2
+
+ assert Enum.sort(resp["results"]) == [
+ %{"dimensions" => ["GB"], "metrics" => [1, 1]},
+ %{"dimensions" => ["US"], "metrics" => [1, 1]}
+ ]
+ end
+ end
+end
diff --git a/test/plausible_web/controllers/api/stats_controller/conversions_test.exs b/test/plausible_web/controllers/api/stats_controller/conversions_test.exs
index 2adcf23417..5a2f8cc829 100644
--- a/test/plausible_web/controllers/api/stats_controller/conversions_test.exs
+++ b/test/plausible_web/controllers/api/stats_controller/conversions_test.exs
@@ -461,6 +461,68 @@ defmodule PlausibleWeb.Api.StatsController.ConversionsTest do
]
end
+ @tag :ee_only
+ test "excludes goals with custom props when Props feature is unavailable", %{
+ conn: conn,
+ site: site,
+ user: user
+ } do
+ user
+ |> team_of()
+ |> Plausible.Teams.Team.end_trial()
+ |> Plausible.Repo.update!()
+
+ populate_stats(site, [
+ build(:event, name: "Signup"),
+ build(:event, name: "Signup"),
+ build(:event, name: "Signup")
+ ])
+
+ {:ok, _goal_with_props} =
+ Plausible.Goals.create(site, %{
+ "event_name" => "Purchase",
+ "custom_props" => %{"product" => "Shirt"}
+ })
+
+ insert(:goal, %{site: site, event_name: "Signup"})
+
+ conn = get(conn, "/api/stats/#{site.domain}/conversions?period=day")
+
+ assert json_response(conn, 200)["results"] == [
+ %{
+ "name" => "Signup",
+ "visitors" => 3,
+ "events" => 3,
+ "conversion_rate" => 100.0
+ }
+ ]
+ end
+
+ @tag :ee_only
+ test "includes goals with custom props when Props feature is available", %{
+ conn: conn,
+ site: site
+ } do
+ populate_stats(site, [
+ build(:event, name: "Purchase", "meta.key": ["product"], "meta.value": ["Shirt"]),
+ build(:event, name: "Purchase", "meta.key": ["product"], "meta.value": ["Shirt"])
+ ])
+
+ {:ok, _goal_with_props} =
+ Plausible.Goals.create(site, %{
+ "event_name" => "Purchase",
+ "custom_props" => %{"product" => "Shirt"}
+ })
+
+ conn = get(conn, "/api/stats/#{site.domain}/conversions?period=day")
+
+ results = json_response(conn, 200)["results"]
+
+ assert length(results) == 1
+ assert hd(results)["name"] == "Purchase"
+ assert hd(results)["visitors"] == 2
+ end
+
@tag :ee_only
test "returns revenue metrics as nil for non-revenue goals", %{
conn: conn,
diff --git a/test/plausible_web/controllers/api/stats_controller/suggestions_test.exs b/test/plausible_web/controllers/api/stats_controller/suggestions_test.exs
index e05ffd3d1a..bc368d252a 100644
--- a/test/plausible_web/controllers/api/stats_controller/suggestions_test.exs
+++ b/test/plausible_web/controllers/api/stats_controller/suggestions_test.exs
@@ -73,6 +73,53 @@ defmodule PlausibleWeb.Api.StatsController.SuggestionsTest do
assert json_response(conn, 200) == [%{"label" => "Signup", "value" => "Signup"}]
end
+ @tag :ee_only
+ test "excludes goals with custom props when Props feature is unavailable", %{
+ conn: conn,
+ site: site,
+ user: user
+ } do
+ user
+ |> team_of()
+ |> Plausible.Teams.Team.end_trial()
+ |> Plausible.Repo.update!()
+
+ {:ok, _goal_with_props} =
+ Plausible.Goals.create(site, %{
+ "event_name" => "Purchase",
+ "custom_props" => %{"product" => "Shirt"}
+ })
+
+ {:ok, _goal_without_props} =
+ Plausible.Goals.create(site, %{"event_name" => "Signup"})
+
+ conn = get(conn, "/api/stats/#{site.domain}/suggestions/goal?period=day&q=")
+
+ assert json_response(conn, 200) == [%{"label" => "Signup", "value" => "Signup"}]
+ end
+
+ @tag :ee_only
+ test "includes goals with custom props when Props feature is available", %{
+ conn: conn,
+ site: site
+ } do
+ {:ok, _goal_with_props} =
+ Plausible.Goals.create(site, %{
+ "event_name" => "Purchase",
+ "custom_props" => %{"product" => "Shirt"}
+ })
+
+ {:ok, _goal_without_props} =
+ Plausible.Goals.create(site, %{"event_name" => "Signup"})
+
+ conn = get(conn, "/api/stats/#{site.domain}/suggestions/goal?period=day&q=")
+
+ suggestions = json_response(conn, 200)
+ assert length(suggestions) == 2
+ assert %{"label" => "Purchase", "value" => "Purchase"} in suggestions
+ assert %{"label" => "Signup", "value" => "Signup"} in suggestions
+ end
+
test "returns suggestions for sources", %{conn: conn, site: site} do
populate_stats(site, [
build(:pageview, timestamp: ~N[2019-01-01 23:00:00], referrer_source: "Bing"),
diff --git a/test/plausible_web/live/goal_settings/form_test.exs b/test/plausible_web/live/goal_settings/form_test.exs
index 42506abf20..630f330c19 100644
--- a/test/plausible_web/live/goal_settings/form_test.exs
+++ b/test/plausible_web/live/goal_settings/form_test.exs
@@ -63,17 +63,13 @@ defmodule PlausibleWeb.Live.GoalSettings.FormTest do
input_names = html |> find("#custom-events-form input") |> Enum.map(&name_of/1)
- assert input_names ==
- [
- "display-event_name_input_modalseq0",
- "goal[event_name]",
- "goal[display_name]",
- "display-currency_input_modalseq0",
- "goal[currency]"
- ]
+ assert "goal[event_name]" in input_names
+ assert "goal[display_name]" in input_names
+ assert "display-currency_input_modalseq0" in input_names
+
+ assert html =~ "Add custom property"
end
- @tag :ee_only
test "renders form fields for pageview", %{conn: conn, site: site} do
lv = get_liveview(conn, site) |> open_modal_with_goal_type("pageviews")
@@ -83,11 +79,11 @@ defmodule PlausibleWeb.Live.GoalSettings.FormTest do
input_names = html |> find("#pageviews-form input") |> Enum.map(&name_of/1)
- assert input_names == [
- "display-page_path_input_modalseq0",
- "goal[page_path]",
- "goal[display_name]"
- ]
+ assert "display-page_path_input_modalseq0" in input_names
+ assert "goal[page_path]" in input_names
+ assert "goal[display_name]" in input_names
+
+ assert html =~ "Add custom property"
end
@tag :ce_build_only
@@ -100,12 +96,11 @@ defmodule PlausibleWeb.Live.GoalSettings.FormTest do
input_names = html |> find("#custom-events-form input") |> Enum.map(&name_of/1)
- assert input_names ==
- [
- "display-event_name_input_modalseq0",
- "goal[event_name]",
- "goal[display_name]"
- ]
+ assert "goal[event_name]" in input_names
+ assert "goal[display_name]" in input_names
+ refute "display-currency_input_modalseq0" in input_names
+
+ assert html =~ "Add custom property"
end
test "renders error on empty submission", %{conn: conn, site: site} do
@@ -278,7 +273,7 @@ defmodule PlausibleWeb.Live.GoalSettings.FormTest do
end
@tag :ee_only
- test "updates a revenue goal", %{conn: conn, site: site} do
+ test "updates a revenue goal event_name but not currency", %{conn: conn, site: site} do
{:ok, [_, _, g]} = setup_goals(site)
lv = get_liveview(conn, site)
@@ -286,22 +281,36 @@ defmodule PlausibleWeb.Live.GoalSettings.FormTest do
html = render(lv)
assert element_exists?(html, "#event_name_input_modalseq0[value=Purchase]")
- assert element_exists?(html, ~s/#currency_input_modalseq0[value="EUR - Euro"]/)
lv
|> element("#goals-form-modalseq0 form")
- |> render_submit(%{goal: %{event_name: "Updated", currency: "USD"}})
+ |> render_submit(%{goal: %{event_name: "Updated"}})
_html = render(lv)
updated = Plausible.Goals.get(site, g.id)
assert updated.event_name == "Updated"
assert updated.display_name == "Purchase"
- assert updated.currency == :USD
- assert updated.currency != g.currency
+ assert updated.currency == :EUR
assert updated.id == g.id
end
+ @tag :ee_only
+ test "currency field is displayed as disabled text input when editing revenue goal", %{
+ conn: conn,
+ site: site
+ } do
+ {:ok, [_, _, revenue_goal]} = setup_goals(site)
+ lv = get_liveview(conn, site)
+
+ lv |> element(~s/button#edit-goal-#{revenue_goal.id}/) |> render_click()
+
+ html = render(lv)
+
+ assert element_exists?(html, ~s/input[name="goal[currency]"][disabled]/)
+ refute element_exists?(html, ~s/#currency_input_modalseq0/)
+ end
+
test "updates a pageview", %{conn: conn, site: site} do
{:ok, [g, _, _]} = setup_goals(site)
lv = get_liveview(conn, site)
@@ -340,6 +349,152 @@ defmodule PlausibleWeb.Live.GoalSettings.FormTest do
assert html =~ "has already been taken"
end
+
+ test "hides 'Add custom property' toggle when editing goal with custom props", %{
+ conn: conn,
+ site: site
+ } do
+ {:ok, goal} =
+ Plausible.Goals.create(site, %{
+ "event_name" => "Purchase",
+ "custom_props" => %{"product" => "Shirt", "color" => "Blue"}
+ })
+
+ lv = get_liveview(conn, site)
+ lv |> element(~s/button#edit-goal-#{goal.id}/) |> render_click()
+
+ html = render(lv)
+
+ refute html =~ "Add custom property"
+ assert html =~ "Custom properties"
+ end
+
+ test "shows 'Add custom property' toggle when editing goal without custom props", %{
+ conn: conn,
+ site: site
+ } do
+ {:ok, goal} = Plausible.Goals.create(site, %{"event_name" => "Signup"})
+
+ lv = get_liveview(conn, site)
+ lv |> element(~s/button#edit-goal-#{goal.id}/) |> render_click()
+
+ html = render(lv)
+
+ assert html =~ "Add custom property"
+ refute html =~ "Custom properties"
+ end
+
+ test "property pairs section is visible when editing goal with custom props", %{
+ conn: conn,
+ site: site
+ } do
+ {:ok, goal} =
+ Plausible.Goals.create(site, %{
+ "event_name" => "Purchase",
+ "custom_props" => %{"product" => "Shirt"}
+ })
+
+ lv = get_liveview(conn, site)
+ lv |> element(~s/button#edit-goal-#{goal.id}/) |> render_click()
+
+ html = render(lv)
+
+ assert html =~ "Custom properties"
+ assert element_exists?(html, ~s/[data-test-id="custom-property-pairs"]/)
+ end
+
+ test "toggle can be clicked to show/hide custom props section", %{conn: conn, site: site} do
+ lv = get_liveview(conn, site) |> open_modal_with_goal_type("custom_events")
+
+ html = render(lv)
+ assert html =~ "Add custom property"
+ refute element_exists?(html, ~s/[data-test-id="custom-property-pairs"]/)
+
+ lv |> element(~s/button[phx-click="toggle-custom-props"]/) |> render_click()
+ html = render(lv)
+
+ assert html =~ "Custom properties"
+ assert element_exists?(html, ~s/[data-test-id="custom-property-pairs"]/)
+
+ lv |> element(~s/button[phx-click="toggle-custom-props"]/) |> render_click()
+ html = render(lv)
+
+ assert html =~ "Add custom property"
+ refute element_exists?(html, ~s/[data-test-id="custom-property-pairs"]/)
+ end
+
+ test "disabling custom props toggle clears custom props on save", %{conn: conn, site: site} do
+ {:ok, goal} =
+ Plausible.Goals.create(site, %{
+ "event_name" => "Purchase",
+ "custom_props" => %{"product" => "Shirt", "color" => "Blue"}
+ })
+
+ assert Plausible.Goal.has_custom_props?(goal)
+
+ lv = get_liveview(conn, site)
+ lv |> element(~s/button#edit-goal-#{goal.id}/) |> render_click()
+
+ html = render(lv)
+ assert html =~ "Custom properties"
+
+ lv |> element(~s/button[phx-click="toggle-custom-props"]/) |> render_click()
+ html = render(lv)
+
+ assert html =~ "Add custom property"
+ refute element_exists?(html, ~s/[data-test-id="custom-property-pairs"]/)
+
+ lv
+ |> element("#goals-form-modalseq0 form")
+ |> render_submit(%{goal: %{event_name: "Purchase"}})
+
+ updated_goal = Plausible.Goals.get(site, goal.id)
+ refute Plausible.Goal.has_custom_props?(updated_goal)
+ assert updated_goal.custom_props == %{}
+ end
+
+ @tag :ee_only
+ test "custom props toggle is disabled when Props feature is unavailable", %{
+ conn: conn,
+ user: user,
+ site: site
+ } do
+ user
+ |> team_of()
+ |> Plausible.Teams.Team.end_trial()
+ |> Plausible.Repo.update!()
+
+ lv = get_liveview(conn, site) |> open_modal_with_goal_type("custom_events")
+
+ html = render(lv)
+
+ assert element_exists?(
+ html,
+ ~s/button[role="switch"][disabled]#add-custom-property-modalseq0/
+ )
+
+ assert html =~ "To get access to this feature"
+ end
+
+ @tag :ee_only
+ test "custom props toggle is enabled when user has Business plan", %{
+ conn: conn,
+ user: user,
+ site: site
+ } do
+ subscribe_to_business_plan(user)
+
+ lv = get_liveview(conn, site) |> open_modal_with_goal_type("custom_events")
+
+ html = render(lv)
+
+ refute element_exists?(
+ html,
+ ~s/button[role="switch"][disabled]#add-custom-property-modalseq0/
+ )
+
+ assert element_exists?(html, ~s/button[role="switch"]#add-custom-property-modalseq0/)
+ end
end
describe "Combos integration" do
diff --git a/test/plausible_web/live/goal_settings/property_pair_input_test.exs b/test/plausible_web/live/goal_settings/property_pair_input_test.exs
new file mode 100644
index 0000000000..603425fb4a
--- /dev/null
+++ b/test/plausible_web/live/goal_settings/property_pair_input_test.exs
@@ -0,0 +1,192 @@
+defmodule PlausibleWeb.Live.GoalSettings.PropertyPairInputTest do
+ use PlausibleWeb.ConnCase, async: true
+ import Phoenix.LiveViewTest
+
+ alias PlausibleWeb.Live.GoalSettings.PropertyPairInput
+
+ describe "static rendering" do
+ setup [:create_user, :create_site]
+
+ test "renders both property name and value comboboxes", %{site: site} do
+ doc = render_pair_component(site, "test-pair")
+
+ assert element_exists?(
+ doc,
+ ~s/input#test-pair_key[name="display-test-pair_key"][phx-change="search"]/
+ )
+
+ assert element_exists?(
+ doc,
+ ~s/input#test-pair_value[name="display-test-pair_value"][phx-change="search"]/
+ )
+ end
+
+ test "property value combobox shows 'Select property first' when no property selected", %{
+ site: site
+ } do
+ doc = render_pair_component(site, "test-pair")
+
+ assert element_exists?(
+ doc,
+ ~s/input#test-pair_value[placeholder="Select property first"]/
+ )
+ end
+
+ test "property value combobox shows 'Select value' when property is selected", %{site: site} do
+ doc = render_pair_component(site, "test-pair", selected_property: "product")
+
+ assert element_exists?(
+ doc,
+ ~s/input#test-pair_value[placeholder="Select value"]/
+ )
+ end
+
+ test "both comboboxes have correct submit names", %{site: site} do
+ doc = render_pair_component(site, "test-pair")
+
+ assert element_exists?(
+ doc,
+ ~s/input[type="hidden"][name="goal[custom_props][keys][]"]/
+ )
+
+ assert element_exists?(
+ doc,
+ ~s/input[type="hidden"][name="goal[custom_props][values][]"]/
+ )
+ end
+
+ test "renders wrapper div with correct ID", %{site: site} do
+ doc = render_pair_component(site, "my-custom-id")
+
+ assert element_exists?(doc, ~s/div#my-custom-id/)
+ end
+
+ test "both comboboxes are marked as creatable", %{site: site} do
+ doc = render_pair_component(site, "test-pair")
+
+ assert text_of_element(doc, "#dropdown-test-pair_key") =~ "Create an item by typing."
+ assert text_of_element(doc, "#dropdown-test-pair_value") =~ "Create an item by typing."
+ end
+
+ test "pre-populates property key when initial_prop_key is provided", %{site: site} do
+ doc = render_pair_component(site, "test-pair", initial_prop_key: "product")
+
+ assert element_exists?(
+ doc,
+ ~s/input#test-pair_key[name="display-test-pair_key"][value="product"]/
+ )
+ end
+
+ test "pre-populates property value when initial_prop_value is provided", %{site: site} do
+ doc = render_pair_component(site, "test-pair", initial_prop_value: "Shirt")
+
+ assert element_exists?(
+ doc,
+ ~s/input#test-pair_value[name="display-test-pair_value"][value="Shirt"]/
+ )
+ end
+
+ test "pre-populates both property key and value when both are provided", %{site: site} do
+ doc =
+ render_pair_component(site, "test-pair",
+ initial_prop_key: "product",
+ initial_prop_value: "Shirt"
+ )
+
+ assert element_exists?(
+ doc,
+ ~s/input#test-pair_key[name="display-test-pair_key"][value="product"]/
+ )
+
+ assert element_exists?(
+ doc,
+ ~s/input#test-pair_value[name="display-test-pair_value"][value="Shirt"]/
+ )
+ end
+
+ test "value combobox shows 'Select value' when property is pre-populated", %{site: site} do
+ doc = render_pair_component(site, "test-pair", initial_prop_key: "product")
+
+ assert element_exists?(
+ doc,
+ ~s/input#test-pair_value[placeholder="Select value"]/
+ )
+ end
+ end
+
+ describe "integration with live view" do
+ setup [:create_user, :create_site]
+
+ defmodule TestLiveView do
+ use Phoenix.LiveView
+
+ def render(assigns) do
+ ~H"""
+ <div>
+ <.live_component
+ id="test-property-pair"
+ module={PlausibleWeb.Live.GoalSettings.PropertyPairInput}
+ site={@site}
+ />
+ </div>
+ """
+ end
+
+ def mount(_params, %{"site" => site}, socket) do
+ {:ok, assign(socket, site: site)}
+ end
+ end
+
+ test "selecting property value based on name selection", %{conn: conn, site: site} do
+ populate_stats(site, [
+ build(:event,
+ name: "Purchase",
+ "meta.key": ["product"],
+ "meta.value": ["Shirt"]
+ )
+ ])
+
+ {:ok, lv, html} = live_isolated(conn, TestLiveView, session: %{"site" => site})
+
+ assert html =~ "Select property first"
+
+ html = type_into_combo(lv, "test-property-pair_key", "zzz")
+ refute element_exists?(html, "li#dropdown-test-property-pair_key-option-1 a")
+
+ type_into_combo(lv, "test-property-pair_key", "duct")
+
+ lv
+ |> element("li#dropdown-test-property-pair_key-option-1 a")
+ |> render_click()
+
+ html = render(lv)
+
+ refute html =~ "Select property first"
+ assert html =~ "Select value"
+
+ html = type_into_combo(lv, "test-property-pair_value", "zzz")
+ refute html =~ "Shirt"
+
+ html = type_into_combo(lv, "test-property-pair_value", "irt")
+ assert html =~ "Shirt"
+
+ lv
+ |> element("li#dropdown-test-property-pair_value-option-1 a")
+ |> render_click()
+ end
+ end
+
+ defp render_pair_component(site, id, extra_opts \\ []) do
+ opts = Keyword.merge([id: id, site: site], extra_opts)
+ render_component(PropertyPairInput, opts)
+ end
+
+ defp type_into_combo(lv, id, text) do
+ lv
+ |> element("input##{id}")
+ |> render_change(%{
+ "_target" => ["display-#{id}"],
+ "display-#{id}" => "#{text}"
+ })
+ end
+end
diff --git a/test/plausible_web/live/goal_settings/property_pairs_test.exs b/test/plausible_web/live/goal_settings/property_pairs_test.exs
new file mode 100644
index 0000000000..16a2b8940f
--- /dev/null
+++ b/test/plausible_web/live/goal_settings/property_pairs_test.exs
@@ -0,0 +1,169 @@
+defmodule PlausibleWeb.Live.GoalSettings.PropertyPairsTest do
+ use PlausibleWeb.ConnCase, async: true
+ import Phoenix.LiveViewTest
+
+ alias PlausibleWeb.Live.GoalSettings.PropertyPairs
+
+ describe "static rendering" do
+ setup [:create_user, :create_site]
+
+ test "renders empty property pair by default", %{site: site} do
+ doc = render_pairs_component(site)
+
+ assert element_exists?(doc, ~s/div[data-test-id="custom-property-pairs"]/)
+ assert element_exists?(doc, ~s/div[id^="property_pair_"]/)
+ assert element_exists?(doc, ~s/input[name="goal[custom_props][keys][]"]/)
+ assert element_exists?(doc, ~s/input[name="goal[custom_props][values][]"]/)
+ end
+
+ test "renders 'Add another property' link when slots are below max", %{site: site} do
+ doc = render_pairs_component(site)
+ assert text_of_element(doc, ~s/a[phx-click="add-slot"]/) == "+ Add another property"
+ end
+
+ test "does not render 'Add another property' link when slots are at max", %{site: site} do
+ {:ok, goal} =
+ Plausible.Goals.create(site, %{
+ "event_name" => "TestEvent",
+ "custom_props" => %{"prop1" => "val1", "prop2" => "val2", "prop3" => "val3"}
+ })
+
+ doc = render_pairs_component(site, goal: goal)
+
+ refute element_exists?(doc, ~s/a[phx-click="add-slot"]/)
+ refute doc =~ "+ Add another property"
+ end
+
+ test "does not show remove button when only one slot exists", %{site: site} do
+ doc = render_pairs_component(site)
+ refute element_exists?(doc, ~s/div[data-test-id^="remove-property-"]/)
+ end
+
+ test "shows remove button when multiple slots exist", %{site: site} do
+ {:ok, goal} =
+ Plausible.Goals.create(site, %{
+ "event_name" => "TestEvent",
+ "custom_props" => %{"prop1" => "val1", "prop2" => "val2"}
+ })
+
+ doc = render_pairs_component(site, goal: goal)
+
+ assert element_exists?(doc, ~s/div[data-test-id^="remove-property-"]/)
+ end
+
+ test "renders property pairs for goal with existing custom props", %{site: site} do
+ {:ok, goal} =
+ Plausible.Goals.create(site, %{
+ "event_name" => "Purchase",
+ "custom_props" => %{"product" => "Shirt", "color" => "Blue"}
+ })
+
+ doc = render_pairs_component(site, goal: goal)
+
+ assert element_exists?(doc, ~s/input[value="product"]/)
+ assert element_exists?(doc, ~s/input[value="Shirt"]/)
+ assert element_exists?(doc, ~s/input[value="color"]/)
+ assert element_exists?(doc, ~s/input[value="Blue"]/)
+ end
+
+ test "pre-populates property pairs when editing goal with custom props", %{site: site} do
+ {:ok, goal} =
+ Plausible.Goals.create(site, %{
+ "event_name" => "Signup",
+ "custom_props" => %{"tier" => "Premium"}
+ })
+
+ doc = render_pairs_component(site, goal: goal)
+
+ assert element_exists?(doc, ~s/input[value="tier"]/)
+ assert element_exists?(doc, ~s/input[value="Premium"]/)
+ end
+ end
+
+ describe "integration with live view" do
+ setup [:create_user, :create_site]
+
+ defmodule TestLiveView do
+ use Phoenix.LiveView
+
+ def render(assigns) do
+ ~H"""
+ <div>
+ <.live_component
+ id="test-property-pairs"
+ module={PlausibleWeb.Live.GoalSettings.PropertyPairs}
+ site={@site}
+ goal={@goal}
+ />
+ </div>
+ """
+ end
+
+ def mount(_params, session, socket) do
+ {:ok, assign(socket, site: session["site"], goal: session["goal"])}
+ end
+ end
+
+ test "adds new slot when 'Add another property' is clicked", %{conn: conn, site: site} do
+ {:ok, lv, html} =
+ live_isolated(conn, TestLiveView, session: %{"site" => site, "goal" => nil})
+
+ assert elem_count(html, ~s/div[id^="property_pair_"]/) == 1
+
+ lv
+ |> element("a[phx-click='add-slot']")
+ |> render_click()
+
+ html = render(lv)
+
+ assert elem_count(html, ~s/div[id^="property_pair_"]/) == 2
+ end
+
+ test "removes slot when remove button is clicked", %{conn: conn, site: site} do
+ {:ok, goal} =
+ Plausible.Goals.create(site, %{
+ "event_name" => "TestEvent",
+ "custom_props" => %{"prop1" => "val1", "prop2" => "val2"}
+ })
+
+ {:ok, lv, html} =
+ live_isolated(conn, TestLiveView, session: %{"site" => site, "goal" => goal})
+
+ assert elem_count(html, ~s/div[id^="property_pair_"]/) == 2
+
+ first_remove_button =
+ html
+ |> find(~s/div[data-test-id^="remove-property-"] [phx-click="remove-slot"]/)
+ |> Enum.at(0)
+ |> text_of_attr("id")
+
+ lv
+ |> element("##{first_remove_button}")
+ |> render_click()
+
+ html = render(lv)
+
+ assert elem_count(html, ~s/div[id^="property_pair_"]/) == 1
+ end
+
+ test "does not add more slots when at max capacity", %{conn: conn, site: site} do
+ {:ok, goal} =
+ Plausible.Goals.create(site, %{
+ "event_name" => "TestEvent",
+ "custom_props" => %{"prop1" => "val1", "prop2" => "val2", "prop3" => "val3"}
+ })
+
+ {:ok, _lv, html} =
+ live_isolated(conn, TestLiveView, session: %{"site" => site, "goal" => goal})
+
+ assert elem_count(html, ~s/div[id^="property_pair_"]/) == 3
+ assert elem_count(html, ~s/[phx-click="remove-slot"]/) == 3
+ refute element_exists?(html, ~s/a[phx-click="add-slot"]/)
+ end
+ end
+
+ defp render_pairs_component(site, extra_opts \\ []) do
+ opts = Keyword.merge([id: "test-pairs", site: site], extra_opts)
+ render_component(PropertyPairs, opts)
+ end
+end
diff --git a/test/plausible_web/live/goal_settings_test.exs b/test/plausible_web/live/goal_settings_test.exs
index 36ebb8f7b0..191ad702b3 100644
--- a/test/plausible_web/live/goal_settings_test.exs
+++ b/test/plausible_web/live/goal_settings_test.exs
@@ -45,11 +45,39 @@ defmodule PlausibleWeb.Live.GoalSettingsTest do
assert g3.currency
assert resp =~ to_string(g3)
- assert resp =~ "Upgrade Required"
+ assert text_of_element(resp, ~s/[data-test-id="feature-unavailable-cta"]/) =~ "Upgrade"
- refute element_exists?(
+ assert element_exists?(
+ resp,
+ ~s/button[data-test-id="edit-goal-button"][disabled]/
+ )
+ end
+
+ @tag :ee_only
+ test "lists goals with custom props with feature availability annotation if the plan does not cover them",
+ %{conn: conn, user: user, site: site} do
+ {:ok, goal_with_props} =
+ Plausible.Goals.create(site, %{
+ "event_name" => "Signup",
+ "custom_props" => %{"plan" => "premium"}
+ })
+
+ user
+ |> team_of()
+ |> Plausible.Teams.Team.end_trial()
+ |> Plausible.Repo.update!()
+
+ conn = get(conn, "/#{site.domain}/settings/goals")
+
+ resp = html_response(conn, 200)
+
+ assert Plausible.Goal.has_custom_props?(goal_with_props)
+ assert resp =~ to_string(goal_with_props)
+ assert text_of_element(resp, ~s/[data-test-id="feature-unavailable-cta"]/) =~ "Upgrade"
+
+ assert element_exists?(
resp,
- ~s/button[phx-click="edit-goal"][phx-value-goal-id="#{g3.id}"][disabled]#edit-goal-#{g3.id}/
+ ~s/button[data-test-id="edit-goal-button"][disabled]/
)
end
@@ -66,7 +94,7 @@ defmodule PlausibleWeb.Live.GoalSettingsTest do
assert element_exists?(
resp,
- ~s/button[phx-click="edit-goal"][phx-value-goal-id="#{g.id}"]#edit-goal-#{g.id}/
+ ~s/button[data-test-id="edit-goal-button"][phx-click="edit-goal"][phx-value-goal-id="#{g.id}"]:not([disabled])#edit-goal-#{g.id}/
)
end
end