Open source, privacy-first web analytics. Lightweight, cookie-free Google Analytics alternative. Self-hosted or cloud.
TypeScript analyticsanalytics-dashboardclickhouseelixirgoogle-analyticsmarketingopen-source-analyticsphoenixplausible-analyticspostgresqlprivacyprivacy-friendlyself-hostedsimple-analyticsstatisticstailwindcssweb-analyticswebsite-analyticswebsite-statswebsite-tracking
Create props settings page (#3191)
Vini Brasild49d68af8fda
diff --git a/assets/js/dashboard/stats/behaviours/index.js b/assets/js/dashboard/stats/behaviours/index.jsindex c38f5921d0..2f1210376b 100644--- a/assets/js/dashboard/stats/behaviours/index.js+++ b/assets/js/dashboard/stats/behaviours/index.js@@ -169,7 +169,7 @@ export default function Behaviours(props) {shortFeatureName={'props'}title={'No custom properties found'}info={'You can attach custom properties when sending a pageview or event. This allows you to create custom metrics and analyze stats we don\'t track automatically.'}- settingsLink={`/${encodeURIComponent(site.domain)}/settings/props`}+ settingsLink={`/${encodeURIComponent(site.domain)}/settings/properties`}onHideAction={onHideAction(PROPS)}/>)diff --git a/assets/js/liveview/suggestions_dropdown.js b/assets/js/liveview/suggestions_dropdown.jsindex 73cb0bb64c..e189992351 100644--- a/assets/js/liveview/suggestions_dropdown.js+++ b/assets/js/liveview/suggestions_dropdown.js@@ -22,7 +22,10 @@ let suggestionsDropdown = function(id) {focusNext() {const nextIndex = this.focus + 1const total = this.$refs.suggestions?.childElementCount ?? 0- if (this.isOpen && nextIndex < total) {++ if (!this.isOpen) this.open()++ if (nextIndex < total) {this.setFocus(nextIndex)this.scrollTo(nextIndex);}diff --git a/lib/plausible/ingestion/request.ex b/lib/plausible/ingestion/request.exindex 1ef7a7c20f..d220067a60 100644--- a/lib/plausible/ingestion/request.ex+++ b/lib/plausible/ingestion/request.ex@@ -200,8 +200,8 @@ defmodule Plausible.Ingestion.Request do|> validate_props()end- @max_prop_key_length 300- @max_prop_value_length 2000+ @max_prop_key_length Plausible.Props.max_prop_key_length()+ @max_prop_value_length Plausible.Props.max_prop_value_length()defp validate_props(changeset) docase Changeset.get_field(changeset, :props) doprops ->diff --git a/lib/plausible/props.ex b/lib/plausible/props.exnew file mode 100644index 0000000000..8d8ed29f72--- /dev/null+++ b/lib/plausible/props.ex@@ -0,0 +1,106 @@+defmodule Plausible.Props do+ @moduledoc """+ Context module for handling custom event props.+ """++ import Ecto.Query++ @type prop :: String.t()++ @max_props 300+ def max_props, do: @max_props++ @max_prop_key_length 300+ def max_prop_key_length, do: @max_prop_key_length++ @max_prop_value_length 2000+ def max_prop_value_length, do: @max_prop_value_length++ @spec allow(Plausible.Site.t(), [prop()] | prop()) ::+ {:ok, Plausible.Site.t()} | {:error, Ecto.Changeset.t()}+ def allow(site, prop_or_props) do+ site+ |> allow_changeset(prop_or_props)+ |> Plausible.Repo.update()+ end++ def allow_changeset(site, prop_or_props) do+ old_props = site.allowed_event_props || []+ new_props = List.wrap(prop_or_props) ++ old_props++ changeset(site, new_props)+ end++ @spec disallow(Plausible.Site.t(), prop()) ::+ {:ok, Plausible.Site.t()} | {:error, Ecto.Changeset.t()}+ def disallow(site, prop) do+ allowed_event_props = site.allowed_event_props || []++ site+ |> changeset(allowed_event_props -- [prop])+ |> Plausible.Repo.update()+ end++ defp changeset(site, props) do+ props =+ props+ |> Enum.map(&String.trim/1)+ |> Enum.uniq()++ site+ |> Ecto.Changeset.change(allowed_event_props: props)+ |> Ecto.Changeset.validate_length(:allowed_event_props, max: @max_props)+ |> Ecto.Changeset.validate_change(:allowed_event_props, fn field, allowed_props ->+ if Enum.all?(allowed_props, &valid?/1),+ do: [],+ else: [{field, "must be between 1 and #{@max_prop_key_length} characters"}]+ end)+ end++ @spec allow_existing_props(Plausible.Site.t()) :: {:ok, Plausible.Site.t()}+ @doc """+ Allows the #{@max_props} most frequent props keys for a specific site over+ the past 6 months.+ """+ def allow_existing_props(%Plausible.Site{} = site) do+ props_to_allow =+ site+ |> suggest_keys_to_allow()+ |> Enum.filter(&valid?/1)++ allow(site, props_to_allow)+ end++ @spec suggest_keys_to_allow(Plausible.Site.t(), non_neg_integer()) :: [String.t()]+ @doc """+ Queries the events table to fetch the #{@max_props} most frequent prop keys+ for a specific site over the past 6 months, excluding keys that are already+ allowed.+ """+ def suggest_keys_to_allow(%Plausible.Site{} = site, limit \\ @max_props) do+ allowed_event_props = site.allowed_event_props || []++ unnested_keys =+ from e in Plausible.ClickhouseEventV2,+ where: e.site_id == ^site.id,+ where: fragment("? > (NOW() - INTERVAL 6 MONTH)", e.timestamp),+ select: %{key: fragment("arrayJoin(?)", field(e, :"meta.key"))}++ Plausible.ClickhouseRepo.all(+ from uk in subquery(unnested_keys),+ where: uk.key not in ^allowed_event_props,+ group_by: uk.key,+ select: uk.key,+ order_by: {:desc, count(uk.key)},+ limit: ^limit+ )+ end++ def enabled_for?(%Plausible.Auth.User{} = user) do+ FunWithFlags.enabled?(:props, for: user)+ end++ defp valid?(key) do+ String.length(key) in 1..@max_prop_key_length+ end+enddiff --git a/lib/plausible_web/components/generic.ex b/lib/plausible_web/components/generic.exindex 069027fecf..dbef2a4196 100644--- a/lib/plausible_web/components/generic.ex+++ b/lib/plausible_web/components/generic.ex@@ -11,7 +11,7 @@ defmodule PlausibleWeb.Components.Generic dodef notice(assigns) do~H"""<div class={[- "rounded-md bg-yellow-50 p-4 dark:bg-transparent dark:border border-yellow-200",+ "rounded-md bg-yellow-50 dark:bg-yellow-100 p-4",@class]}><div class="flex">@@ -30,8 +30,8 @@ defmodule PlausibleWeb.Components.Generic do</svg></div><div class="ml-3">- <h3 class="text-sm font-medium text-yellow-800 dark:text-yellow-400"><%= @title %></h3>- <div class="mt-2 text-sm text-yellow-700 dark:text-gray-400">+ <h3 class="text-sm font-medium text-yellow-800 dark:text-yellow-900"><%= @title %></h3>+ <div class="mt-2 text-sm text-yellow-700 dark:text-yellow-800"><p><%= render_slot(@inner_block) %></p>diff --git a/lib/plausible_web/controllers/site_controller.ex b/lib/plausible_web/controllers/site_controller.exindex ff00e70185..d0c9dc0a9f 100644--- a/lib/plausible_web/controllers/site_controller.ex+++ b/lib/plausible_web/controllers/site_controller.ex@@ -292,6 +292,19 @@ defmodule PlausibleWeb.SiteController doendend+ def settings_props(conn, _params) do+ if Plausible.Props.enabled_for?(conn.assigns.current_user) do+ conn+ |> assign(:skip_plausible_tracking, true)+ |> render("settings_props.html",+ site: conn.assigns.site,+ layout: {PlausibleWeb.LayoutView, "site_settings.html"}+ )+ else+ conn |> Plug.Conn.put_status(401) |> Plug.Conn.halt()+ end+ end+def settings_search_console(conn, _params) dosite =conn.assigns[:site]diff --git a/lib/plausible_web/live/components/combo_box.ex b/lib/plausible_web/live/components/combo_box.exindex 2e747658d0..2267d66be3 100644--- a/lib/plausible_web/live/components/combo_box.ex+++ b/lib/plausible_web/live/components/combo_box.ex@@ -58,10 +58,11 @@ defmodule PlausibleWeb.Live.Components.ComboBox doid={"input-picker-main-#{@id}"}class={@class}x-data={"window.suggestionsDropdown('#{@id}')"}- x-on:keydown.arrow-up="focusPrev"- x-on:keydown.arrow-down="focusNext"- x-on:keydown.enter="select()"+ x-on:keydown.arrow-up.prevent="focusPrev"+ x-on:keydown.arrow-down.prevent="focusNext"+ x-on:keydown.enter.prevent="select"x-on:keydown.tab="close"+ x-on:keydown.escape="close"><div class="relative w-full"><div@@ -144,7 +145,7 @@ defmodule PlausibleWeb.Live.Components.ComboBox doid={"dropdown-#{@ref}"}x-show="isOpen"x-ref="suggestions"- class="dropdown z-50 absolute mt-1 max-h-60 overflow-auto rounded-md bg-white py-1 text-base shadow-lg ring-1 ring-black ring-opacity-5 focus:outline-none sm:text-sm dark:bg-gray-900"+ class="max-w-xs md:max-w-md lg:max-w-lg dropdown z-50 absolute mt-1 max-h-60 overflow-auto rounded-md bg-white py-1 text-base shadow-lg ring-1 ring-black ring-opacity-5 focus:outline-none sm:text-sm dark:bg-gray-900"><.option:for={@@ -204,15 +205,13 @@ defmodule PlausibleWeb.Live.Components.ComboBox dophx-click={select_option(@ref, @submit_value, @display_value)}phx-value-display-value={@display_value}phx-target={@target}- class="block py-2 px-3"+ class="block truncate py-2 px-3">- <span class="block truncate">- <%= if @creatable do %>- Create "<%= @display_value %>"- <% else %>- <%= @display_value %>- <% end %>- </span>+ <%= if @creatable do %>+ Create "<%= @display_value %>"+ <% else %>+ <%= @display_value %>+ <% end %></a></li><li :if={@idx == @suggestions_limit - 1} class="text-xs text-gray-500 relative py-2 px-3">diff --git a/lib/plausible_web/live/props_settings.ex b/lib/plausible_web/live/props_settings.exnew file mode 100644index 0000000000..efd1e1ca54--- /dev/null+++ b/lib/plausible_web/live/props_settings.ex@@ -0,0 +1,180 @@+defmodule PlausibleWeb.Live.PropsSettings do+ @moduledoc """+ LiveView allowing listing, allowing and disallowing custom event properties.+ """++ use Phoenix.LiveView+ use Phoenix.HTML+ alias PlausibleWeb.Live.Components.ComboBox++ def mount(+ _params,+ %{"site_id" => _site_id, "domain" => domain, "current_user_id" => user_id},+ socket+ ) do+ true = Plausible.Props.enabled_for?(%Plausible.Auth.User{id: user_id})++ site =+ if Plausible.Auth.is_super_admin?(user_id) do+ Plausible.Sites.get_by_domain(domain)+ else+ Plausible.Sites.get_for_user!(user_id, domain, [:owner, :admin])+ end++ suggestions =+ site+ |> Plausible.Props.suggest_keys_to_allow()+ |> Enum.map(&{&1, &1})++ {:ok,+ assign(socket,+ site: site,+ current_user_id: user_id,+ form: new_form(site),+ suggestions: suggestions+ )}+ end++ def render(assigns) do+ ~H"""+ <section id="props-settings-main">+ <.live_component id="embedded_liveview_flash" module={PlausibleWeb.Live.Flash} flash={@flash} />++ <h1 class="text-normal leading-6 font-medium text-gray-900 dark:text-gray-100">+ Configured properties+ </h1>++ <h2 class="mt-1 text-sm leading-5 text-gray-500 dark:text-gray-400">+ In order for the properties to show up on your dashboard, you need to+ explicitly add them below first+ </h2>++ <.form :let={f} for={@form} id="props-form" phx-submit="allow" class="mt-5">+ <div class="flex space-x-2">+ <.live_component+ id={:prop_input}+ submit_name="prop"+ class="flex-1"+ module={ComboBox}+ suggest_mod={ComboBox.StaticSearch}+ options={@suggestions}+ required+ creatable+ />++ <button id="allow" type="submit" class="button">+ Add</button>+ </div>++ <div :if={length(f[:allowed_event_props].errors) > 0} id="prop-errors" role="alert">+ <%= PlausibleWeb.ErrorHelpers.error_tag(f, :allowed_event_props) %>+ </div>+ </.form>++ <button+ :if={length(@suggestions) > 0}+ title="Use this to add any existing properties from your past events into your settings. This allows you to set up properties without having to manually enter each item."+ class="mt-1 text-sm hover:underline text-indigo-600 dark:text-indigo-400"+ phx-click="allow-existing-props"+ >+ Already sending custom properties? Click to add all existing properties+ </button>++ <div class="mt-5">+ <%= if is_list(@site.allowed_event_props) && length(@site.allowed_event_props) > 0 do %>+ <ul id="allowed-props" class="divide-gray-200 divide-y dark:divide-gray-600">+ <li+ :for={{prop, index} <- Enum.with_index(@site.allowed_event_props)}+ id={"prop-#{index}"}+ class="flex py-4"+ >+ <span class="flex-1 truncate font-medium text-sm text-gray-800 dark:text-gray-200">+ <%= prop %>+ </span>+ <button+ data-confirm={"Are you sure you want to remove property '#{prop}'? This will just affect the UI, all of your analytics data will stay intact."}+ phx-click="disallow"+ phx-value-prop={prop}+ class="w-4 h-4 text-red-600 hover:text-red-700"+ aria-label={"Remove #{prop} property"}+ >+ <svg+ 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"+ aria-hidden="true"+ focusable="false"+ >+ <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>+ </button>+ </li>+ </ul>+ <% else %>+ <p class="text-sm text-gray-800 dark:text-gray-200">+ No properties configured for this site yet+ </p>+ <% end %>+ </div>+ </section>+ """+ end++ def handle_event("allow", %{"prop" => prop}, socket) do+ case Plausible.Props.allow(socket.assigns.site, prop) do+ {:ok, site} ->+ send_update(ComboBox, id: :prop_input, display_value: "", submit_value: "")++ {:noreply,+ assign(socket,+ site: site,+ form: new_form(site),+ suggestions: rebuild_suggestions(socket.assigns.suggestions, site.allowed_event_props)+ )}++ {:error, changeset} ->+ {:noreply,+ assign(socket,+ form: to_form(Map.put(changeset, :action, :validate))+ )}+ end+ end++ def handle_event("disallow", %{"prop" => prop}, socket) do+ {:ok, site} = Plausible.Props.disallow(socket.assigns.site, prop)+ {:noreply, assign(socket, site: site)}+ end++ def handle_event("allow-existing-props", _params, socket) do+ {:ok, site} = Plausible.Props.allow_existing_props(socket.assigns.site)++ {:noreply,+ assign(socket,+ site: site,+ suggestions: rebuild_suggestions(socket.assigns.suggestions, site.allowed_event_props)+ )}+ end++ defp rebuild_suggestions(suggestions, allowed_event_props) do+ allowed_event_props = allowed_event_props || []++ suggestions =+ for {suggestion, _} <- suggestions,+ suggestion not in allowed_event_props,+ do: {suggestion, suggestion}++ send_update(ComboBox, id: :prop_input, suggestions: suggestions)+ suggestions+ end++ defp new_form(site) do+ to_form(Plausible.Props.allow_changeset(site, []))+ end+enddiff --git a/lib/plausible_web/router.ex b/lib/plausible_web/router.exindex 3929dc1109..badb271473 100644--- a/lib/plausible_web/router.ex+++ b/lib/plausible_web/router.ex@@ -259,6 +259,7 @@ defmodule PlausibleWeb.Router doget "/:website/settings/people", SiteController, :settings_peopleget "/:website/settings/visibility", SiteController, :settings_visibilityget "/:website/settings/goals", SiteController, :settings_goals+ get "/:website/settings/properties", SiteController, :settings_propsget "/:website/settings/search-console", SiteController, :settings_search_consoleget "/:website/settings/email-reports", SiteController, :settings_email_reportsdiff --git a/lib/plausible_web/templates/site/settings_funnels.html.heex b/lib/plausible_web/templates/site/settings_funnels.html.heexindex 5ac5032bc0..b814742f3f 100644--- a/lib/plausible_web/templates/site/settings_funnels.html.heex+++ b/lib/plausible_web/templates/site/settings_funnels.html.heex@@ -1,45 +1,47 @@-<div class="shadow bg-white dark:bg-gray-800 sm:rounded-md sm:overflow-hidden py-6 px-4 sm:p-6">- <header class="relative">- <h2 class="text-lg leading-6 font-medium text-gray-900 dark:text-gray-100">Funnels</h2>- <p class="mt-1 text-sm leading-5 text-gray-500 dark:text-gray-200">- Compose goals into funnels- </p>+<section class="shadow bg-white dark:bg-gray-800 sm:rounded-md sm:overflow-hidden">+ <PlausibleWeb.Components.Generic.notice class="rounded-t-md rounded-b-none">+ Funnels is an upcoming premium feature that's free-to-use+ during the private preview. Pricing will be announced soon. See+ examples and learn more in <a+ class="font-medium text-yellow underline hover:text-yellow-600"+ href="https://plausible.io/docs/funnel-analysis"+ >our docs</a>.+ </PlausibleWeb.Components.Generic.notice>- <%= link(to: "https://plausible.io/docs/funnel-analysis", target: "_blank", rel: "noreferrer") do %>- <svg- class="w-6 h-6 absolute top-0 right-0 text-gray-400"- fill="currentColor"- viewBox="0 0 20 20"- xmlns="http://www.w3.org/2000/svg"- >- <path- fill-rule="evenodd"- d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a1 1 0 000 2v3a1 1 0 001 1h1a1 1 0 100-2v-3a1 1 0 00-1-1H9z"- clip-rule="evenodd"- >- </path>- </svg>- <% end %>- </header>+ <div class="py-6 px-4 sm:p-6">+ <header class="relative">+ <h2 class="text-lg leading-6 font-medium text-gray-900 dark:text-gray-100">Funnels</h2>+ <p class="mt-1 text-sm leading-5 text-gray-500 dark:text-gray-200">+ Compose goals into funnels+ </p>- <PlausibleWeb.Components.Site.Feature.toggle- site={@site}- setting={:funnels_enabled}- label="Show funnels in the dashboard"- conn={@conn}- >- <PlausibleWeb.Components.Generic.notice>- Funnels is an upcoming premium feature that's free-to-use- during the private preview. Pricing will be announced soon. See- examples and learn more in <a- class="font-medium text-yellow underline hover:text-yellow-600"- href="https://plausible.io/docs/funnel-analysis"- >our docs</a>.- </PlausibleWeb.Components.Generic.notice>+ <%= link(to: "https://plausible.io/docs/funnel-analysis", target: "_blank", rel: "noreferrer") do %>+ <svg+ class="w-6 h-6 absolute top-0 right-0 text-gray-400"+ fill="currentColor"+ viewBox="0 0 20 20"+ xmlns="http://www.w3.org/2000/svg"+ >+ <path+ fill-rule="evenodd"+ d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a1 1 0 000 2v3a1 1 0 001 1h1a1 1 0 100-2v-3a1 1 0 00-1-1H9z"+ clip-rule="evenodd"+ >+ </path>+ </svg>+ <% end %>+ </header>- <%= live_render(@conn, PlausibleWeb.Live.FunnelSettings,- session: %{"site_id" => @site.id, "domain" => @site.domain},- router: PlausibleWeb.Router- ) %>- </PlausibleWeb.Components.Site.Feature.toggle>-</div>+ <PlausibleWeb.Components.Site.Feature.toggle+ site={@site}+ setting={:funnels_enabled}+ label="Show funnels in the dashboard"+ conn={@conn}+ >+ <%= live_render(@conn, PlausibleWeb.Live.FunnelSettings,+ session: %{"site_id" => @site.id, "domain" => @site.domain},+ router: PlausibleWeb.Router+ ) %>+ </PlausibleWeb.Components.Site.Feature.toggle>+ </div>+</section>diff --git a/lib/plausible_web/templates/site/settings_props.html.heex b/lib/plausible_web/templates/site/settings_props.html.heexnew file mode 100644index 0000000000..16b90f2756--- /dev/null+++ b/lib/plausible_web/templates/site/settings_props.html.heex@@ -0,0 +1,59 @@+<section class="shadow bg-white dark:bg-gray-800 sm:rounded-md sm:overflow-hidden">+ <PlausibleWeb.Components.Generic.notice class="rounded-t-md rounded-b-none">+ Properties is an upcoming premium feature that's free-to-use during the+ private preview. Pricing will be announced soon. See examples and learn+ more in <.link+ class="font-medium text-yellow underline hover:text-yellow-600"+ href="https://plausible.io/docs/custom-pageview-props"+ target="_blank"+ rel="noreferrer"+ >our docs</.link>.+ </PlausibleWeb.Components.Generic.notice>++ <div class="py-6 px-4 sm:p-6">+ <header class="w-full flex">+ <span class="flex-1">+ <h1 class="text-lg leading-6 font-medium text-gray-900 dark:text-gray-100">+ Properties+ </h1>++ <h2 class="mt-1 text-sm leading-5 text-gray-500 dark:text-gray-400">+ Attach custom properties when sending a pageview or an event to+ create custom metrics+ </h2>+ </span>++ <.link+ href="https://plausible.io/docs/custom-pageview-props"+ target="_blank"+ rel="noreferrer"+ >+ <svg+ class="w-6 h-6 text-gray-400"+ fill="currentColor"+ viewBox="0 0 20 20"+ xmlns="http://www.w3.org/2000/svg"+ >+ <path+ fill-rule="evenodd"+ d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a1 1 0 000 2v3a1 1 0 001 1h1a1 1 0 100-2v-3a1 1 0 00-1-1H9z"+ clip-rule="evenodd"+ >+ </path>+ </svg>+ </.link>+ </header>++ <PlausibleWeb.Components.Site.Feature.toggle+ site={@site}+ setting={:props_enabled}+ label="Show properties in the dashboard"+ conn={@conn}+ >+ <%= live_render(@conn, PlausibleWeb.Live.PropsSettings,+ id: "props-form",+ session: %{"site_id" => @site.id, "domain" => @site.domain}+ ) %>+ </PlausibleWeb.Components.Site.Feature.toggle>+ </div>+</section>diff --git a/lib/plausible_web/views/error_helpers.ex b/lib/plausible_web/views/error_helpers.exindex 5500b77814..c6b6d9d1b9 100644--- a/lib/plausible_web/views/error_helpers.ex+++ b/lib/plausible_web/views/error_helpers.ex@@ -3,7 +3,7 @@ defmodule PlausibleWeb.ErrorHelpers dodef error_tag(%Phoenix.HTML.Form{} = form, field) doEnum.map(Keyword.get_values(form.errors, field), fn error ->- content_tag(:div, elem(error, 0), class: "mt-2 text-sm text-red-600")+ content_tag(:div, translate_error(error), class: "mt-2 text-sm text-red-600")end)end@@ -14,4 +14,10 @@ defmodule PlausibleWeb.ErrorHelpers docontent_tag(:div, error, class: "mt-2 text-sm text-red-600")endend++ def translate_error({msg, opts}) do+ Enum.reduce(opts, msg, fn {key, value}, acc ->+ String.replace(acc, "%{#{key}}", fn _ -> to_string(value) end)+ end)+ endenddiff --git a/lib/plausible_web/views/layout_view.ex b/lib/plausible_web/views/layout_view.exindex bb2ee92176..dd4eca7612 100644--- a/lib/plausible_web/views/layout_view.ex+++ b/lib/plausible_web/views/layout_view.ex@@ -30,6 +30,9 @@ defmodule PlausibleWeb.LayoutView doif Plausible.Funnels.enabled_for?(conn.assigns[:current_user]) do[key: "Funnels", value: "funnels"]end,+ if Plausible.Props.enabled_for?(conn.assigns[:current_user]) do+ [key: "Properties", value: "properties"]+ end,[key: "Search Console", value: "search-console"],[key: "Email reports", value: "email-reports"],if !is_selfhost() && conn.assigns[:site].custom_domain dodiff --git a/priv/repo/migrations/20230724131709_change_allowed_event_props_type.exs b/priv/repo/migrations/20230724131709_change_allowed_event_props_type.exsnew file mode 100644index 0000000000..1c99fdbbaa--- /dev/null+++ b/priv/repo/migrations/20230724131709_change_allowed_event_props_type.exs@@ -0,0 +1,11 @@+defmodule Plausible.Repo.Migrations.ChangeAllowedEventPropsType do+ use Ecto.Migration++ def change do+ alter table("sites") do+ modify :allowed_event_props, {:array, :"varchar(300)"},+ null: true,+ from: {{:array, :string}, null: true}+ end+ end+enddiff --git a/priv/repo/seeds.exs b/priv/repo/seeds.exsindex da65256295..964b0d95f4 100644--- a/priv/repo/seeds.exs+++ b/priv/repo/seeds.exs@@ -13,6 +13,7 @@user = Plausible.Factory.insert(:user, email: "[email protected]", password: "plausible")FunWithFlags.enable(:funnels)+FunWithFlags.enable(:props)native_stats_range =Date.range(diff --git a/test/plausible/props_test.exs b/test/plausible/props_test.exsnew file mode 100644index 0000000000..0e914c4861--- /dev/null+++ b/test/plausible/props_test.exs@@ -0,0 +1,194 @@+defmodule Plausible.PropsTest do+ use Plausible.DataCase++ test "allow/2 adds props to the array" do+ site = insert(:site)++ assert {:ok, site} = Plausible.Props.allow(site, "my-prop-1")+ assert {:ok, site} = Plausible.Props.allow(site, "my-prop-2")++ assert %Plausible.Site{allowed_event_props: ["my-prop-2", "my-prop-1"]} =+ Plausible.Repo.reload!(site)+ end++ test "allow/2 takes a single prop or multiple" do+ site = insert(:site)++ assert {:ok, site} = Plausible.Props.allow(site, "my-prop-1")+ assert {:ok, site} = Plausible.Props.allow(site, ["my-prop-3", "my-prop-2"])++ assert %Plausible.Site{allowed_event_props: ["my-prop-3", "my-prop-2", "my-prop-1"]} =+ Plausible.Repo.reload!(site)+ end++ test "allow/2 trims trailing whitespaces" do+ site = insert(:site)++ assert {:ok, site} = Plausible.Props.allow(site, " my-prop-1 ")+ assert %Plausible.Site{allowed_event_props: ["my-prop-1"]} = Plausible.Repo.reload!(site)+ end++ test "allow/2 fails when prop list is too long" do+ site = insert(:site)+ props = for i <- 1..300, do: "my-prop-#{i}"++ assert {:ok, site} = Plausible.Props.allow(site, props)+ assert {:error, changeset} = Plausible.Props.allow(site, "my-prop-301")++ assert {"should have at most %{count} item(s)",+ [count: 300, validation: :length, kind: :max, type: :list]} ==+ changeset.errors[:allowed_event_props]+ end++ test "allow/2 fails when prop key is too long" do+ site = insert(:site)++ long_prop = String.duplicate("a", 301)+ assert {:error, changeset} = Plausible.Props.allow(site, long_prop)+ assert {"must be between 1 and 300 characters", []} == changeset.errors[:allowed_event_props]+ end++ test "allow/2 fails when prop key is empty" do+ site = insert(:site)++ assert {:error, changeset} = Plausible.Props.allow(site, "")+ assert {"must be between 1 and 300 characters", []} == changeset.errors[:allowed_event_props]++ assert {:error, changeset} = Plausible.Props.allow(site, " ")+ assert {"must be between 1 and 300 characters", []} == changeset.errors[:allowed_event_props]+ end++ test "allow/2 does not fail when prop key is already in the list" do+ site = insert(:site)++ assert {:ok, site} = Plausible.Props.allow(site, "my-prop-1")+ assert {:ok, site} = Plausible.Props.allow(site, "my-prop-1")+ assert %Plausible.Site{allowed_event_props: ["my-prop-1"]} = Plausible.Repo.reload!(site)+ end++ test "disallow/2 removes the prop from the array" do+ site = insert(:site)++ assert {:ok, site} = Plausible.Props.allow(site, "my-prop-1")+ assert {:ok, site} = Plausible.Props.allow(site, "my-prop-2")+ assert {:ok, site} = Plausible.Props.disallow(site, "my-prop-2")+ assert %Plausible.Site{allowed_event_props: ["my-prop-1"]} = Plausible.Repo.reload!(site)+ end++ test "disallow/2 does not fail when prop is not in the list" do+ site = insert(:site)++ assert {:ok, site} = Plausible.Props.allow(site, "my-prop-1")+ assert {:ok, site} = Plausible.Props.disallow(site, "my-prop-2")+ assert %Plausible.Site{allowed_event_props: ["my-prop-1"]} = Plausible.Repo.reload!(site)+ end++ test "allow_existing_props/1 saves the most frequent prop keys" do+ site = insert(:site)++ populate_stats(site, [+ build(:event,+ name: "Payment",+ "meta.key": ["amount"],+ "meta.value": ["500"]+ ),+ build(:event,+ name: "Payment",+ "meta.key": ["amount", "logged_in"],+ "meta.value": ["100", "false"]+ ),+ build(:event,+ name: "Payment",+ "meta.key": ["amount", "is_customer"],+ "meta.value": ["100", "false"]+ )+ ])++ {:ok, site} = Plausible.Props.allow_existing_props(site)++ assert %Plausible.Site{allowed_event_props: ["amount", "logged_in", "is_customer"]} =+ Plausible.Repo.reload!(site)+ end++ test "allow_existing_props/1 skips invalid keys" do+ site = insert(:site)++ populate_stats(site, [+ build(:event,+ name: "Payment",+ "meta.key": ["amount", String.duplicate("a", 301)],+ "meta.value": ["500", "true"]+ ),+ build(:event,+ name: "Payment",+ "meta.key": ["amount", "logged_in"],+ "meta.value": ["100", "false"]+ ),+ build(:event,+ name: "Payment",+ "meta.key": ["amount", "is_customer"],+ "meta.value": ["100", "false"]+ )+ ])++ {:ok, site} = Plausible.Props.allow_existing_props(site)++ assert %Plausible.Site{allowed_event_props: ["amount", "logged_in", "is_customer"]} =+ Plausible.Repo.reload!(site)+ end++ test "allow_existing_props/1 can be run multiple times" do+ site = insert(:site)++ populate_stats(site, [+ build(:event,+ name: "Payment",+ "meta.key": ["amount"],+ "meta.value": ["500"]+ ),+ build(:event,+ name: "Payment",+ "meta.key": ["amount", "logged_in"],+ "meta.value": ["100", "false"]+ ),+ build(:event,+ name: "Payment",+ "meta.key": ["amount", "is_customer"],+ "meta.value": ["100", "false"]+ )+ ])++ {:ok, %Plausible.Site{allowed_event_props: ["amount", "logged_in", "is_customer"]}} =+ Plausible.Props.allow_existing_props(site)++ populate_stats(site, [+ build(:event,+ name: "Payment",+ "meta.key": ["amount", "os"],+ "meta.value": ["500", "Windows"]+ ),+ build(:event,+ name: "Payment",+ "meta.key": ["amount", "logged_in", "with_error"],+ "meta.value": ["100", "false", "true"]+ ),+ build(:event,+ name: "Payment",+ "meta.key": ["amount", "is_customer", "first_time_customer"],+ "meta.value": ["100", "false", "true"]+ )+ ])++ {:ok,+ %Plausible.Site{+ allowed_event_props: [+ "amount",+ "logged_in",+ "is_customer",+ "os",+ "with_error",+ "first_time_customer"+ ]+ }} = Plausible.Props.allow_existing_props(site)+ end+enddiff --git a/test/plausible_web/live/components/combo_box_test.exs b/test/plausible_web/live/components/combo_box_test.exsindex 5f40277163..c2f834ae4d 100644--- a/test/plausible_web/live/components/combo_box_test.exs+++ b/test/plausible_web/live/components/combo_box_test.exs@@ -70,9 +70,9 @@ defmodule PlausibleWeb.Live.Components.ComboBoxTest do|> render_sample_component()|> find("div#input-picker-main-test-component")- assert text_of_attr(main, "x-on:keydown.arrow-up") == "focusPrev"- assert text_of_attr(main, "x-on:keydown.arrow-down") == "focusNext"- assert text_of_attr(main, "x-on:keydown.enter") == "select()"+ assert text_of_attr(main, "x-on:keydown.arrow-up.prevent") == "focusPrev"+ assert text_of_attr(main, "x-on:keydown.arrow-down.prevent") == "focusNext"+ assert text_of_attr(main, "x-on:keydown.enter.prevent") == "select"endtest "Alpine.js: component sets up close on click-away" dodiff --git a/test/plausible_web/live/props_settings_test.exs b/test/plausible_web/live/props_settings_test.exsnew file mode 100644index 0000000000..4dd048734c--- /dev/null+++ b/test/plausible_web/live/props_settings_test.exs@@ -0,0 +1,202 @@+defmodule PlausibleWeb.Live.PropsSettings.FormTest do+ use PlausibleWeb.ConnCase, async: true+ import Phoenix.LiveViewTest+ import Plausible.Test.Support.HTML++ defp seed(%{site: site}) do+ populate_stats(site, [+ build(:event,+ name: "Payment",+ "meta.key": ["amount"],+ "meta.value": ["500"]+ ),+ build(:event,+ name: "Payment",+ "meta.key": ["amount", "logged_in"],+ "meta.value": ["100", "false"]+ ),+ build(:event,+ name: "Payment",+ "meta.key": ["amount", "is_customer"],+ "meta.value": ["100", "false"]+ )+ ])++ :ok+ end++ setup [:create_user, :log_in, :create_site, :seed]++ test "shows message when site has no allowed properties", %{conn: conn, site: site} do+ {:ok, _lv, doc} = get_liveview(conn, site)+ assert doc =~ "No properties configured for this site yet"+ end++ test "renders dropdown with suggestions", %{conn: conn, site: site} do+ {:ok, _lv, doc} = get_liveview(conn, site)++ assert text_of_element(doc, ~s/ul#dropdown-prop_input li#dropdown-prop_input-option-0/) ==+ "amount"++ assert text_of_element(doc, ~s/ul#dropdown-prop_input li#dropdown-prop_input-option-1/) ==+ "logged_in"++ assert text_of_element(doc, ~s/ul#dropdown-prop_input li#dropdown-prop_input-option-2/) ==+ "is_customer"+ end++ test "input is a required field", %{conn: conn, site: site} do+ {:ok, _lv, doc} = get_liveview(conn, site)+ assert element_exists?(doc, ~s/input#prop_input[required]/)+ end++ test "clicking suggestion fills out input", %{conn: conn, site: site} do+ {:ok, lv, _doc} = get_liveview(conn, site)++ doc =+ lv+ |> element(~s/ul#dropdown-prop_input li#dropdown-prop_input-option-0 a/)+ |> render_click()++ assert element_exists?(doc, ~s/input[type="hidden"][value="amount"]/)+ end++ test "saving from suggestion adds to the list", %{conn: conn, site: site} do+ {:ok, lv, _doc} = get_liveview(conn, site)++ doc = select_and_submit(lv, 0)++ assert text_of_element(doc, ~s/ul#allowed-props li#prop-0 span/) == "amount"+ refute doc =~ "No properties configured for this site yet"+ end++ test "saving from manual input adds to the list", %{conn: conn, site: site} do+ {:ok, lv, _doc} = get_liveview(conn, site)++ type_into_combo(lv, "Operating System")++ doc =+ lv+ |> form("#props-form")+ |> render_submit()++ assert text_of_element(doc, ~s/ul#allowed-props li#prop-0 span/) == "Operating System"+ refute doc =~ "No properties configured for this site yet"+ end++ test "shows error when input is invalid", %{conn: conn, site: site} do+ {:ok, lv, _doc} = get_liveview(conn, site)++ type_into_combo(lv, " ")+ doc = lv |> form("#props-form") |> render_submit()++ assert text_of_element(doc, ~s/div#prop-errors div/) == "must be between 1 and 300 characters"+ assert doc =~ "No properties configured for this site yet"+ end++ test "shows error when reached prop limit", %{conn: conn, site: site} do+ props = for i <- 1..300, do: "my-prop-#{i}"+ {:ok, site} = Plausible.Props.allow(site, props)+ {:ok, lv, _doc} = get_liveview(conn, site)++ type_into_combo(lv, "my-prop-301")+ doc = lv |> form("#props-form") |> render_submit()++ assert text_of_element(doc, ~s/div#prop-errors div/) == "should have at most 300 item(s)"+ end++ test "clears error message when user fixes input", %{conn: conn, site: site} do+ {:ok, lv, _doc} = get_liveview(conn, site)++ type_into_combo(lv, " ")+ doc = lv |> form("#props-form") |> render_submit()+ assert text_of_element(doc, ~s/div#prop-errors div/) == "must be between 1 and 300 characters"++ type_into_combo(lv, "my-prop")+ doc = lv |> form("#props-form") |> render_submit()+ refute element_exists?(doc, ~s/div#prop-errors/)+ end++ test "clicking remove button removes from the list", %{conn: conn, site: site} do+ {:ok, site} = Plausible.Props.allow(site, "my-prop")+ {:ok, lv, doc} = get_liveview(conn, site)++ assert text_of_element(doc, ~s/ul#allowed-props li#prop-0 span/) == "my-prop"++ doc =+ lv+ |> element(~s/ul#allowed-props li#prop-0 button[phx-click="disallow"]/)+ |> render_click()++ refute element_exists?(doc, ~s/ul#allowed-props li#prop-0 span/)+ assert doc =~ "No properties configured for this site yet"+ end++ test "remove button shows a confirmation popup", %{conn: conn, site: site} do+ {:ok, site} = Plausible.Props.allow(site, "my-prop")+ {:ok, _lv, doc} = get_liveview(conn, site)++ assert "Are you sure you want to remove property 'my-prop'? This will just affect the UI, all of your analytics data will stay intact." ==+ doc+ |> Floki.find(~s/ul#allowed-props li#prop-0 button[phx-click="disallow"]/)+ |> text_of_attr("data-confirm")+ end++ test "clicking allow existing props button saves props from events", %{conn: conn, site: site} do+ {:ok, lv, _doc} = get_liveview(conn, site)++ doc =+ lv+ |> element(~s/button[phx-click="allow-existing-props"]/)+ |> render_click()++ assert text_of_element(doc, ~s/ul#allowed-props li#prop-0 span/) == "amount"+ assert text_of_element(doc, ~s/ul#allowed-props li#prop-1 span/) == "logged_in"+ assert text_of_element(doc, ~s/ul#allowed-props li#prop-2 span/) == "is_customer"+ end++ test "does not show allow existing props button when there are no events with props", %{+ conn: conn,+ user: user+ } do+ {:ok, _lv, doc} = get_liveview(conn, insert(:site, members: [user]))+ refute element_exists?(doc, ~s/button[phx-click="allow-existing-props"]/)+ end++ test "does not show allow existing props button after adding all suggestions", %{+ conn: conn,+ site: site+ } do+ {:ok, lv, _doc} = get_liveview(conn, site)++ _doc = select_and_submit(lv, 0)+ _doc = select_and_submit(lv, 0)+ doc = select_and_submit(lv, 0)++ refute element_exists?(doc, ~s/button[phx-click="allow-existing-props"]/)+ end++ defp get_liveview(conn, site) do+ conn = assign(conn, :live_module, PlausibleWeb.Live.PropsSettings)+ {:ok, _lv, _doc} = live(conn, "/#{site.domain}/settings/properties")+ end++ defp select_and_submit(lv, suggestion_index) do+ lv+ |> element(~s/ul#dropdown-prop_input li#dropdown-prop_input-option-#{suggestion_index} a/)+ |> render_click()++ lv+ |> form("#props-form")+ |> render_submit()+ end++ defp type_into_combo(lv, input) do+ lv+ |> element("input#prop_input")+ |> render_change(%{+ "_target" => ["display-prop_input"],+ "display-prop_input" => input+ })+ end+end