Skip to content

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

Expose goals w/ custom props through Sites/Plugins API (#5952)

Adam Rutkowski99fd33522dda
diff --git a/extra/lib/plausible_web/controllers/api/external_sites_controller.ex b/extra/lib/plausible_web/controllers/api/external_sites_controller.ex
index 8e5e76f6a7..985d96cbe7 100644
--- a/extra/lib/plausible_web/controllers/api/external_sites_controller.ex
+++ b/extra/lib/plausible_web/controllers/api/external_sites_controller.ex
@@ -98,7 +98,8 @@ defmodule PlausibleWeb.Api.ExternalSitesController do
display_name: goal.display_name,
goal_type: Goal.type(goal),
event_name: goal.event_name,
- page_path: goal.page_path
+ page_path: goal.page_path,
+ custom_props: goal.custom_props
}
end),
meta: pagination_meta(page.metadata)
@@ -413,6 +414,12 @@ defmodule PlausibleWeb.Api.ExternalSitesController do
H.bad_request(conn, message)
+ {:error, :upgrade_required} ->
+ H.payment_required(
+ conn,
+ "Your current subscription plan does not include Custom Properties"
+ )
+
e ->
H.bad_request(conn, "Something went wrong: #{inspect(e)}")
end
diff --git a/lib/plausible/goal.ex b/lib/plausible/goal.ex
index df78c4e029..44ba3ae7cf 100644
--- a/lib/plausible/goal.ex
+++ b/lib/plausible/goal.ex
@@ -54,13 +54,7 @@ defmodule Plausible.Goal do
|> validate_event_name_and_page_path()
|> validate_page_path_for_scroll_goal()
|> maybe_put_display_name()
- |> validate_change(:custom_props, fn :custom_props, custom_props ->
- if map_size(custom_props) > @max_custom_props_per_goal do
- [custom_props: "use at most #{@max_custom_props_per_goal} properties per goal"]
- else
- []
- end
- end)
+ |> validate_change(:custom_props, &validate_custom_props/2)
|> unique_constraint(:display_name, name: :goals_display_name_unique)
|> unique_constraint(:event_name, name: :goals_event_config_unique)
|> unique_constraint([:page_path, :scroll_threshold],
@@ -183,6 +177,35 @@ defmodule Plausible.Goal do
|> update_change(:display_name, &String.trim/1)
|> validate_required(:display_name)
end
+
+ defp validate_custom_props(:custom_props, custom_props) when is_map(custom_props) do
+ cond do
+ map_size(custom_props) > @max_custom_props_per_goal ->
+ [custom_props: "use at most #{@max_custom_props_per_goal} properties per goal"]
+
+ not Enum.all?(custom_props, fn {k, v} ->
+ is_binary(k) and is_binary(v)
+ end) ->
+ [custom_props: "must be a map with string keys and string values"]
+
+ Enum.any?(custom_props, fn {k, _v} ->
+ String.length(k) not in 1..Plausible.Props.max_prop_key_length()
+ end) ->
+ [
+ custom_props: "key length is 1..#{Plausible.Props.max_prop_key_length()} characters"
+ ]
+
+ Enum.any?(custom_props, fn {_k, v} ->
+ String.length(v) not in 1..Plausible.Props.max_prop_value_length()
+ end) ->
+ [
+ custom_props: "value length is 1..#{Plausible.Props.max_prop_value_length()} characters"
+ ]
+
+ true ->
+ []
+ end
+ end
end
defimpl Jason.Encoder, for: Plausible.Goal do
@@ -191,7 +214,7 @@ defimpl Jason.Encoder, for: Plausible.Goal do
value
|> Map.put(:goal_type, Plausible.Goal.type(value))
- |> Map.take([:id, :goal_type, :event_name, :page_path])
+ |> Map.take([:id, :goal_type, :event_name, :page_path, :custom_props])
|> Map.put(:domain, domain)
|> Map.put(:display_name, value.display_name)
|> Jason.Encode.map(opts)
diff --git a/lib/plausible/goals/goals.ex b/lib/plausible/goals/goals.ex
index c3853c5e05..9f7af75431 100644
--- a/lib/plausible/goals/goals.ex
+++ b/lib/plausible/goals/goals.ex
@@ -387,6 +387,12 @@ defmodule Plausible.Goals do
end
defp maybe_check_feature_access(site, changeset) do
+ with :ok <- revenue_goals_access_check(site, changeset) do
+ custom_props_goals_access_check(site, changeset)
+ end
+ end
+
+ defp revenue_goals_access_check(site, changeset) do
if Changeset.get_field(changeset, :currency) do
site = Plausible.Repo.preload(site, :team)
Plausible.Billing.Feature.RevenueGoals.check_availability(site.team)
@@ -395,6 +401,15 @@ defmodule Plausible.Goals do
end
end
+ defp custom_props_goals_access_check(site, changeset) do
+ if map_size(Changeset.get_field(changeset, :custom_props)) > 0 do
+ site = Plausible.Repo.preload(site, :team)
+ Plausible.Billing.Feature.Props.check_availability(site.team)
+ else
+ :ok
+ end
+ end
+
defp check_goals_limit(site, changeset, opts) do
if upsert?(opts) and goal_exists_for_upsert?(site, changeset) do
:ok
diff --git a/lib/plausible/plugins/api/goals.ex b/lib/plausible/plugins/api/goals.ex
index c1240131f3..37c6a7ff0a 100644
--- a/lib/plausible/plugins/api/goals.ex
+++ b/lib/plausible/plugins/api/goals.ex
@@ -51,16 +51,42 @@ defmodule Plausible.Plugins.API.Goals do
:ok
end
+ defp convert_to_create_params(%CreateRequest.CustomEvent{
+ goal: %{event_name: event_name, custom_props: custom_props}
+ })
+ when is_map(custom_props) do
+ %{"goal_type" => "event", "event_name" => event_name, "custom_props" => custom_props}
+ end
+
defp convert_to_create_params(%CreateRequest.CustomEvent{goal: %{event_name: event_name}}) do
%{"goal_type" => "event", "event_name" => event_name}
end
+ defp convert_to_create_params(%CreateRequest.Revenue{
+ goal: %{event_name: event_name, currency: currency, custom_props: custom_props}
+ })
+ when is_map(custom_props) do
+ %{
+ "goal_type" => "event",
+ "event_name" => event_name,
+ "currency" => currency,
+ "custom_props" => custom_props
+ }
+ end
+
defp convert_to_create_params(%CreateRequest.Revenue{
goal: %{event_name: event_name, currency: currency}
}) do
%{"goal_type" => "event", "event_name" => event_name, "currency" => currency}
end
+ defp convert_to_create_params(%CreateRequest.Pageview{
+ goal: %{path: page_path, custom_props: custom_props}
+ })
+ when is_map(custom_props) do
+ %{"goal_type" => "page", "page_path" => page_path, "custom_props" => custom_props}
+ end
+
defp convert_to_create_params(%CreateRequest.Pageview{goal: %{path: page_path}}) do
%{"goal_type" => "page", "page_path" => page_path}
end
@@ -73,6 +99,9 @@ defmodule Plausible.Plugins.API.Goals do
{:ok, goal} ->
goal
+ {:error, :upgrade_required} ->
+ Repo.rollback(:upgrade_required)
+
{:error, changeset} ->
Repo.rollback(changeset)
end
diff --git a/lib/plausible_web/plugins/api/schemas/goal/create_request/custom_event.ex b/lib/plausible_web/plugins/api/schemas/goal/create_request/custom_event.ex
index 758a428cdb..5c9491c88e 100644
--- a/lib/plausible_web/plugins/api/schemas/goal/create_request/custom_event.ex
+++ b/lib/plausible_web/plugins/api/schemas/goal/create_request/custom_event.ex
@@ -5,6 +5,8 @@ defmodule PlausibleWeb.Plugins.API.Schemas.Goal.CreateRequest.CustomEvent do
use PlausibleWeb, :open_api_schema
+ alias Schemas.Goal.CustomProps
+
OpenApiSpex.schema(%{
title: "Goal.CreateRequest.CustomEvent",
description: "Custom Event Goal creation params",
@@ -20,7 +22,8 @@ defmodule PlausibleWeb.Plugins.API.Schemas.Goal.CreateRequest.CustomEvent do
type: :object,
required: [:event_name],
properties: %{
- event_name: %Schema{type: :string}
+ event_name: %Schema{type: :string},
+ custom_props: CustomProps.request_schema()
}
}
},
diff --git a/lib/plausible_web/plugins/api/schemas/goal/create_request/pageview.ex b/lib/plausible_web/plugins/api/schemas/goal/create_request/pageview.ex
index 2b224dcc9f..e1ff2f3359 100644
--- a/lib/plausible_web/plugins/api/schemas/goal/create_request/pageview.ex
+++ b/lib/plausible_web/plugins/api/schemas/goal/create_request/pageview.ex
@@ -5,6 +5,8 @@ defmodule PlausibleWeb.Plugins.API.Schemas.Goal.CreateRequest.Pageview do
use PlausibleWeb, :open_api_schema
+ alias Schemas.Goal.CustomProps
+
OpenApiSpex.schema(%{
title: "Goal.CreateRequest.Pageview",
description: "Pageview Goal creation params",
@@ -20,7 +22,8 @@ defmodule PlausibleWeb.Plugins.API.Schemas.Goal.CreateRequest.Pageview do
type: :object,
required: [:path],
properties: %{
- path: %Schema{type: :string}
+ path: %Schema{type: :string},
+ custom_props: CustomProps.request_schema()
}
}
},
diff --git a/lib/plausible_web/plugins/api/schemas/goal/create_request/revenue.ex b/lib/plausible_web/plugins/api/schemas/goal/create_request/revenue.ex
index 4b8f413769..b464309b9f 100644
--- a/lib/plausible_web/plugins/api/schemas/goal/create_request/revenue.ex
+++ b/lib/plausible_web/plugins/api/schemas/goal/create_request/revenue.ex
@@ -5,6 +5,8 @@ defmodule PlausibleWeb.Plugins.API.Schemas.Goal.CreateRequest.Revenue do
use PlausibleWeb, :open_api_schema
+ alias Schemas.Goal.CustomProps
+
OpenApiSpex.schema(%{
title: "Goal.CreateRequest.Revenue",
description: "Revenue Goal creation params",
@@ -21,7 +23,8 @@ defmodule PlausibleWeb.Plugins.API.Schemas.Goal.CreateRequest.Revenue do
required: [:event_name, :currency],
properties: %{
event_name: %Schema{type: :string},
- currency: %Schema{type: :string}
+ currency: %Schema{type: :string},
+ custom_props: CustomProps.request_schema()
}
}
},
diff --git a/lib/plausible_web/plugins/api/schemas/goal/custom_event.ex b/lib/plausible_web/plugins/api/schemas/goal/custom_event.ex
index fac4d810cd..3e98cef14a 100644
--- a/lib/plausible_web/plugins/api/schemas/goal/custom_event.ex
+++ b/lib/plausible_web/plugins/api/schemas/goal/custom_event.ex
@@ -4,6 +4,8 @@ defmodule PlausibleWeb.Plugins.API.Schemas.Goal.CustomEvent do
"""
use PlausibleWeb, :open_api_schema
+ alias Schemas.Goal.CustomProps
+
OpenApiSpex.schema(%{
description: "Custom Event Goal object",
title: "Goal.CustomEvent",
@@ -20,7 +22,8 @@ defmodule PlausibleWeb.Plugins.API.Schemas.Goal.CustomEvent do
properties: %{
id: %Schema{type: :integer, description: "Goal ID", readOnly: true},
display_name: %Schema{type: :string, description: "Display name", readOnly: true},
- event_name: %Schema{type: :string, description: "Event Name"}
+ event_name: %Schema{type: :string, description: "Event Name"},
+ custom_props: CustomProps.response_schema()
}
}
}
diff --git a/lib/plausible_web/plugins/api/schemas/goal/custom_props.ex b/lib/plausible_web/plugins/api/schemas/goal/custom_props.ex
new file mode 100644
index 0000000000..d1524c2f67
--- /dev/null
+++ b/lib/plausible_web/plugins/api/schemas/goal/custom_props.ex
@@ -0,0 +1,25 @@
+defmodule PlausibleWeb.Plugins.API.Schemas.Goal.CustomProps do
+ @moduledoc """
+ Reusable OpenAPI schema definitions for Custom Properties in Goals
+ """
+
+ alias OpenApiSpex.Schema
+
+ def response_schema do
+ %Schema{
+ type: :object,
+ description: "Custom properties (string keys and values)",
+ additionalProperties: %Schema{type: :string},
+ readOnly: true
+ }
+ end
+
+ def request_schema do
+ %Schema{
+ type: :object,
+ description: "Custom properties (max 3, string keys and values)",
+ additionalProperties: %Schema{type: :string},
+ maxProperties: 3
+ }
+ end
+end
diff --git a/lib/plausible_web/plugins/api/schemas/goal/pageview.ex b/lib/plausible_web/plugins/api/schemas/goal/pageview.ex
index d68a0a47ef..d7d5f1e3d7 100644
--- a/lib/plausible_web/plugins/api/schemas/goal/pageview.ex
+++ b/lib/plausible_web/plugins/api/schemas/goal/pageview.ex
@@ -4,6 +4,8 @@ defmodule PlausibleWeb.Plugins.API.Schemas.Goal.Pageview do
"""
use PlausibleWeb, :open_api_schema
+ alias Schemas.Goal.CustomProps
+
OpenApiSpex.schema(%{
description: "Pageview Goal object",
title: "Goal.Pageview",
@@ -20,7 +22,8 @@ defmodule PlausibleWeb.Plugins.API.Schemas.Goal.Pageview do
properties: %{
id: %Schema{type: :integer, description: "Goal ID", readOnly: true},
display_name: %Schema{type: :string, description: "Display name", readOnly: true},
- path: %Schema{type: :string, description: "Page Path"}
+ path: %Schema{type: :string, description: "Page Path"},
+ custom_props: CustomProps.response_schema()
}
}
}
diff --git a/lib/plausible_web/plugins/api/schemas/goal/revenue.ex b/lib/plausible_web/plugins/api/schemas/goal/revenue.ex
index c254064893..580c9bb7d8 100644
--- a/lib/plausible_web/plugins/api/schemas/goal/revenue.ex
+++ b/lib/plausible_web/plugins/api/schemas/goal/revenue.ex
@@ -4,6 +4,8 @@ defmodule PlausibleWeb.Plugins.API.Schemas.Goal.Revenue do
"""
use PlausibleWeb, :open_api_schema
+ alias Schemas.Goal.CustomProps
+
OpenApiSpex.schema(%{
description: "Revenue Goal object",
title: "Goal.Revenue",
@@ -21,7 +23,8 @@ defmodule PlausibleWeb.Plugins.API.Schemas.Goal.Revenue do
id: %Schema{type: :integer, description: "Goal ID", readOnly: true},
display_name: %Schema{type: :string, description: "Display name", readOnly: true},
event_name: %Schema{type: :string, description: "Event Name"},
- currency: %Schema{type: :string, description: "Currency"}
+ currency: %Schema{type: :string, description: "Currency"},
+ custom_props: CustomProps.response_schema()
}
}
}
diff --git a/lib/plausible_web/plugins/api/views/goal.ex b/lib/plausible_web/plugins/api/views/goal.ex
index cc5d31c6e4..07e5a6f010 100644
--- a/lib/plausible_web/plugins/api/views/goal.ex
+++ b/lib/plausible_web/plugins/api/views/goal.ex
@@ -35,7 +35,8 @@ defmodule PlausibleWeb.Plugins.API.Views.Goal do
goal: %{
id: pageview.id,
display_name: pageview.display_name,
- path: pageview.page_path
+ path: pageview.page_path,
+ custom_props: pageview.custom_props || %{}
}
}
end
@@ -48,7 +49,8 @@ defmodule PlausibleWeb.Plugins.API.Views.Goal do
goal: %{
id: custom_event.id,
display_name: custom_event.display_name,
- event_name: custom_event.event_name
+ event_name: custom_event.event_name,
+ custom_props: custom_event.custom_props || %{}
}
}
end
@@ -63,7 +65,8 @@ defmodule PlausibleWeb.Plugins.API.Views.Goal do
id: revenue_goal.id,
display_name: revenue_goal.display_name,
event_name: revenue_goal.event_name,
- currency: revenue_goal.currency
+ currency: revenue_goal.currency,
+ custom_props: revenue_goal.custom_props || %{}
}
}
end
diff --git a/test/plausible/goals_test.exs b/test/plausible/goals_test.exs
index 7dfa079df6..3a5de96254 100644
--- a/test/plausible/goals_test.exs
+++ b/test/plausible/goals_test.exs
@@ -169,6 +169,62 @@ defmodule Plausible.GoalsTest do
assert {"use at most 3 properties per goal", _} = changeset.errors[:custom_props]
end
+ test "create/3 fails to create a goal with non-string custom prop values" do
+ site = new_site()
+
+ {:error, changeset} =
+ Goals.create(site, %{
+ "event_name" => "Purchase",
+ "custom_props" => %{"count" => 42}
+ })
+
+ assert {"must be a map with string keys and string values" <> _, _} =
+ changeset.errors[:custom_props]
+ end
+
+ test "create/3 fails to create a goal with null custom prop values" do
+ site = new_site()
+
+ {:error, changeset} =
+ Goals.create(site, %{
+ "event_name" => "Purchase",
+ "custom_props" => %{"product" => nil}
+ })
+
+ assert {"must be a map with string keys and string values", _} =
+ changeset.errors[:custom_props]
+ end
+
+ test "create/3 fails to create custom prop with key over #{Plausible.Props.max_prop_key_length()}" do
+ site = new_site()
+
+ {:error, changeset} =
+ Goals.create(site, %{
+ "event_name" => "Purchase",
+ "custom_props" => %{
+ :binary.copy("a", Plausible.Props.max_prop_key_length() + 1) => "value"
+ }
+ })
+
+ assert {"key length is 1..300 characters", _} =
+ changeset.errors[:custom_props]
+ end
+
+ test "create/3 fails to create custom prop with value over #{Plausible.Props.max_prop_value_length()}" do
+ site = new_site()
+
+ {:error, changeset} =
+ Goals.create(site, %{
+ "event_name" => "Purchase",
+ "custom_props" => %{
+ "key" => :binary.copy("a", Plausible.Props.max_prop_value_length() + 1)
+ }
+ })
+
+ assert {"value length is 1..2000 characters", _} =
+ changeset.errors[:custom_props]
+ end
+
test "create/2 succeeds to create the same custom event twice with different props and different display names each" do
site = new_site()
diff --git a/test/plausible_web/controllers/api/external_sites_controller_test.exs b/test/plausible_web/controllers/api/external_sites_controller_test.exs
index 4c019f046a..50a1827183 100644
--- a/test/plausible_web/controllers/api/external_sites_controller_test.exs
+++ b/test/plausible_web/controllers/api/external_sites_controller_test.exs
@@ -131,7 +131,6 @@ defmodule PlausibleWeb.Api.ExternalSitesControllerTest do
subscribe_to_enterprise_plan(user,
features: [
Plausible.Billing.Feature.SharedLinks,
- Plausible.Billing.Feature.StatsAPI,
Plausible.Billing.Feature.SitesAPI
]
)
@@ -286,7 +285,6 @@ defmodule PlausibleWeb.Api.ExternalSitesControllerTest do
subscribe_to_enterprise_plan(user,
features: [
Plausible.Billing.Feature.Props,
- Plausible.Billing.Feature.StatsAPI,
Plausible.Billing.Feature.SitesAPI
]
)
@@ -449,7 +447,7 @@ defmodule PlausibleWeb.Api.ExternalSitesControllerTest do
setup %{user: user} do
subscribe_to_enterprise_plan(user,
- features: [Plausible.Billing.Feature.StatsAPI, Plausible.Billing.Feature.SitesAPI]
+ features: [Plausible.Billing.Feature.SitesAPI]
)
:ok
@@ -463,12 +461,17 @@ defmodule PlausibleWeb.Api.ExternalSitesControllerTest do
event_name: "Signup"
})
- res = json_response(conn, 200)
+ resp = json_response(conn, 200)
- assert res["goal_type"] == "event"
- assert res["display_name"] == "Signup"
- assert res["event_name"] == "Signup"
- assert res["domain"] == site.domain
+ assert_matches ^strict_map(%{
+ "custom_props" => ^strict_map(%{}),
+ "display_name" => "Signup",
+ "domain" => ^site.domain,
+ "event_name" => "Signup",
+ "goal_type" => "event",
+ "id" => ^any(:integer),
+ "page_path" => nil
+ }) = resp
end
test "can add a goal as page to a site", %{conn: conn, site: site} do
@@ -479,11 +482,17 @@ defmodule PlausibleWeb.Api.ExternalSitesControllerTest do
page_path: "/signup"
})
- res = json_response(conn, 200)
- assert res["goal_type"] == "page"
- assert res["page_path"] == "/signup"
- assert res["display_name"] == "Visit /signup"
- assert res["domain"] == site.domain
+ resp = json_response(conn, 200)
+
+ assert_matches ^strict_map(%{
+ "custom_props" => ^strict_map(%{}),
+ "display_name" => "Visit /signup",
+ "domain" => ^site.domain,
+ "event_name" => nil,
+ "goal_type" => "page",
+ "id" => ^any(:integer),
+ "page_path" => "/signup"
+ }) = resp
end
test "can add a goal using old site_id after domain change", %{conn: conn, site: site} do
@@ -665,6 +674,102 @@ defmodule PlausibleWeb.Api.ExternalSitesControllerTest do
assert res["error"] =~ "Maximum number of goals reached"
end
+
+ test "can create a goal with custom_props", %{conn: conn, site: site, user: user} do
+ subscribe_to_enterprise_plan(user,
+ features: [Plausible.Billing.Feature.SitesAPI, Plausible.Billing.Feature.Props]
+ )
+
+ conn =
+ put(conn, "/api/v1/sites/goals", %{
+ site_id: site.domain,
+ goal_type: "event",
+ event_name: "Purchase",
+ custom_props: %{"product" => "enterprise", "tier" => "premium"}
+ })
+
+ res = json_response(conn, 200)
+ assert res["goal_type"] == "event"
+ assert res["event_name"] == "Purchase"
+ assert res["custom_props"] == %{"product" => "enterprise", "tier" => "premium"}
+ end
+
+ test "custom_props defaults to empty map if not provided", %{conn: conn, site: site} do
+ conn =
+ put(conn, "/api/v1/sites/goals", %{
+ site_id: site.domain,
+ goal_type: "event",
+ event_name: "Signup"
+ })
+
+ res = json_response(conn, 200)
+ assert res["custom_props"] == %{}
+ end
+
+ test "fails when custom_props exceeds max of 3", %{conn: conn, site: site, user: user} do
+ subscribe_to_enterprise_plan(user,
+ features: [Plausible.Billing.Feature.SitesAPI, Plausible.Billing.Feature.Props]
+ )
+
+ conn =
+ put(conn, "/api/v1/sites/goals", %{
+ site_id: site.domain,
+ goal_type: "event",
+ event_name: "Purchase",
+ custom_props: %{"a" => "1", "b" => "2", "c" => "3", "d" => "4"}
+ })
+
+ res = json_response(conn, 400)
+ assert res["error"] =~ "use at most 3 properties per goal"
+ end
+
+ test "fails when custom_props has null values", %{conn: conn, site: site, user: user} do
+ subscribe_to_enterprise_plan(user,
+ features: [Plausible.Billing.Feature.SitesAPI, Plausible.Billing.Feature.Props]
+ )
+
+ conn =
+ put(conn, "/api/v1/sites/goals", %{
+ site_id: site.domain,
+ goal_type: "event",
+ event_name: "Purchase",
+ custom_props: %{"product" => nil}
+ })
+
+ res = json_response(conn, 400)
+ assert res["error"] =~ "must be a map with string keys and string values"
+ end
+
+ test "fails when custom_props has non-string values", %{conn: conn, site: site, user: user} do
+ subscribe_to_enterprise_plan(user,
+ features: [Plausible.Billing.Feature.SitesAPI, Plausible.Billing.Feature.Props]
+ )
+
+ conn =
+ put(conn, "/api/v1/sites/goals", %{
+ site_id: site.domain,
+ goal_type: "event",
+ event_name: "Purchase",
+ custom_props: %{"count" => 42}
+ })
+
+ res = json_response(conn, 400)
+ assert res["error"] =~ "must be a map with string keys and string values"
+ end
+
+ @tag :ee_only
+ test "fails without Props feature when custom_props is non-empty", %{conn: conn, site: site} do
+ conn =
+ put(conn, "/api/v1/sites/goals", %{
+ site_id: site.domain,
+ goal_type: "event",
+ event_name: "Purchase",
+ custom_props: %{"product" => "enterprise"}
+ })
+
+ res = json_response(conn, 402)
+ assert res["error"] == "Your current subscription plan does not include Custom Properties"
+ end
end
describe "DELETE /api/v1/sites/custom-props/:property" do
@@ -674,7 +779,6 @@ defmodule PlausibleWeb.Api.ExternalSitesControllerTest do
subscribe_to_enterprise_plan(user,
features: [
Plausible.Billing.Feature.Props,
- Plausible.Billing.Feature.StatsAPI,
Plausible.Billing.Feature.SitesAPI
]
)
@@ -821,7 +925,6 @@ defmodule PlausibleWeb.Api.ExternalSitesControllerTest do
setup %{user: user} do
subscribe_to_enterprise_plan(user,
features: [
- Plausible.Billing.Feature.StatsAPI,
Plausible.Billing.Feature.SitesAPI
]
)
@@ -1048,7 +1151,6 @@ defmodule PlausibleWeb.Api.ExternalSitesControllerTest do
setup %{user: user} do
subscribe_to_enterprise_plan(user,
features: [
- Plausible.Billing.Feature.StatsAPI,
Plausible.Billing.Feature.SitesAPI
]
)
@@ -1165,7 +1267,7 @@ defmodule PlausibleWeb.Api.ExternalSitesControllerTest do
describe "DELETE /api/v1/sites/guests" do
setup %{user: user} do
subscribe_to_enterprise_plan(user,
- features: [Plausible.Billing.Feature.StatsAPI, Plausible.Billing.Feature.SitesAPI]
+ features: [Plausible.Billing.Feature.SitesAPI]
)
:ok
@@ -1376,21 +1478,24 @@ defmodule PlausibleWeb.Api.ExternalSitesControllerTest do
"display_name" => "Purchase",
"goal_type" => "event",
"event_name" => "Purchase",
- "page_path" => nil
+ "page_path" => nil,
+ "custom_props" => %{}
},
%{
"id" => goal2.id,
"display_name" => "Signup",
"goal_type" => "event",
"event_name" => "Signup",
- "page_path" => nil
+ "page_path" => nil,
+ "custom_props" => %{}
},
%{
"id" => goal1.id,
"display_name" => "Visit /login",
"goal_type" => "page",
"event_name" => nil,
- "page_path" => "/login"
+ "page_path" => "/login",
+ "custom_props" => %{}
}
],
"meta" => %{
@@ -1401,6 +1506,28 @@ defmodule PlausibleWeb.Api.ExternalSitesControllerTest do
}
end
+ test "returns goals with custom_props", %{conn: conn, site: site} do
+ goal =
+ insert(:goal, %{
+ site: site,
+ event_name: "Purchase",
+ custom_props: %{"product" => "enterprise", "tier" => "premium"}
+ })
+
+ conn = get(conn, "/api/v1/sites/goals?site_id=" <> site.domain)
+
+ goal_id = goal.id
+
+ assert %{
+ "goals" => [
+ %{
+ "id" => ^goal_id,
+ "custom_props" => %{"product" => "enterprise", "tier" => "premium"}
+ }
+ ]
+ } = json_response(conn, 200)
+ end
+
@tag :capture_log
test "returns goals for site where user is viewer", %{site: site} do
viewer = new_user()
diff --git a/test/plausible_web/plugins/api/controllers/goals_test.exs b/test/plausible_web/plugins/api/controllers/goals_test.exs
index 47b08c49ae..df2e7c089a 100644
--- a/test/plausible_web/plugins/api/controllers/goals_test.exs
+++ b/test/plausible_web/plugins/api/controllers/goals_test.exs
@@ -52,8 +52,7 @@ defmodule PlausibleWeb.Plugins.API.Controllers.GoalsTest do
token: token,
conn: conn
} do
- [owner | _] = Plausible.Repo.preload(site, :owners).owners
- subscribe_to_growth_plan(owner)
+ subscribe_to_growth_plan(site.team)
url = Routes.plugins_api_goals_url(PlausibleWeb.Endpoint, :create)
@@ -78,8 +77,7 @@ defmodule PlausibleWeb.Plugins.API.Controllers.GoalsTest do
token: token,
conn: conn
} do
- [owner | _] = Plausible.Repo.preload(site, :owners).owners
- subscribe_to_growth_plan(owner)
+ subscribe_to_growth_plan(site.team)
url = Routes.plugins_api_goals_url(PlausibleWeb.Endpoint, :create)
@@ -110,6 +108,158 @@ defmodule PlausibleWeb.Plugins.API.Controllers.GoalsTest do
end
describe "put /goals - create a single goal" do
+ test "creates a custom event goal with custom props", %{conn: conn, token: token, site: site} do
+ subscribe_to_business_plan(site.team)
+
+ url = Routes.plugins_api_goals_url(PlausibleWeb.Endpoint, :create)
+
+ payload = %{
+ goal_type: "Goal.CustomEvent",
+ goal: %{event_name: "Signup", custom_props: %{"tier" => "premium", "source" => "landing"}}
+ }
+
+ assert_request_schema(payload, "Goal.CreateRequest.CustomEvent", spec())
+
+ conn =
+ conn
+ |> authenticate(site.domain, token)
+ |> put_req_header("content-type", "application/json")
+ |> put(url, payload)
+
+ resp = json_response(conn, 201)
+
+ schema = assert_schema(resp, "Goal.ListResponse", spec())
+
+ resp
+ |> Map.fetch!("goals")
+ |> List.first()
+ |> assert_schema("Goal.CustomEvent", spec())
+
+ [location] = get_resp_header(conn, "location")
+
+ assert location ==
+ Routes.plugins_api_goals_url(
+ PlausibleWeb.Endpoint,
+ :get,
+ List.first(schema.goals).goal.id
+ )
+
+ [goal] = Plausible.Goals.for_site(site)
+ assert goal.event_name == "Signup"
+ assert goal.custom_props == %{"tier" => "premium", "source" => "landing"}
+
+ first_goal = List.first(resp["goals"])
+ assert first_goal["goal"]["custom_props"] == %{"tier" => "premium", "source" => "landing"}
+ end
+
+ test "fails to create goal with custom prop having invalid value", %{
+ conn: conn,
+ token: token,
+ site: site
+ } do
+ subscribe_to_business_plan(site.team)
+
+ url = Routes.plugins_api_goals_url(PlausibleWeb.Endpoint, :create)
+
+ payload = %{
+ goal_type: "Goal.CustomEvent",
+ goal: %{event_name: "Signup", custom_props: %{"count" => 5}}
+ }
+
+ resp =
+ conn
+ |> authenticate(site.domain, token)
+ |> put_req_header("content-type", "application/json")
+ |> put(url, payload)
+ |> json_response(422)
+ |> assert_schema("UnprocessableEntityError", spec())
+
+ assert Enum.any?(resp.errors, &(&1.detail == "Invalid string. Got: integer"))
+ end
+
+ test "fails to create goal with more than 3 custom props", %{
+ conn: conn,
+ token: token,
+ site: site
+ } do
+ subscribe_to_business_plan(site.team)
+
+ url = Routes.plugins_api_goals_url(PlausibleWeb.Endpoint, :create)
+
+ payload = %{
+ goal_type: "Goal.CustomEvent",
+ goal: %{
+ event_name: "Signup",
+ custom_props: %{"a" => "1", "b" => "2", "c" => "3", "d" => "4"}
+ }
+ }
+
+ resp =
+ conn
+ |> authenticate(site.domain, token)
+ |> put_req_header("content-type", "application/json")
+ |> put(url, payload)
+ |> json_response(422)
+ |> assert_schema("UnprocessableEntityError", spec())
+
+ assert Enum.any?(
+ resp.errors,
+ &(&1.detail == "Object property count 4 is greater than maxProperties: 3")
+ )
+ end
+
+ test "fails to create goal with null custom props values", %{
+ conn: conn,
+ token: token,
+ site: site
+ } do
+ subscribe_to_business_plan(site.team)
+
+ url = Routes.plugins_api_goals_url(PlausibleWeb.Endpoint, :create)
+
+ payload = %{
+ goal_type: "Goal.CustomEvent",
+ goal: %{event_name: "Signup", custom_props: %{"tier" => nil}}
+ }
+
+ resp =
+ conn
+ |> authenticate(site.domain, token)
+ |> put_req_header("content-type", "application/json")
+ |> put(url, payload)
+ |> json_response(422)
+ |> assert_schema("UnprocessableEntityError", spec())
+
+ assert Enum.any?(resp.errors, &(&1.detail == "null value where string expected"))
+ end
+
+ @tag :ee_only
+ test "fails without Props feature when custom props is non-empty", %{
+ conn: conn,
+ token: token,
+ site: site
+ } do
+ site = Plausible.Repo.preload(site, :team)
+ # End trial to ensure team doesn't have access to Props feature
+ site.team
+ |> Ecto.Changeset.change(%{trial_expiry_date: Date.add(Date.utc_today(), -1)})
+ |> Plausible.Repo.update!()
+
+ url = Routes.plugins_api_goals_url(PlausibleWeb.Endpoint, :create)
+
+ payload = %{
+ goal_type: "Goal.CustomEvent",
+ goal: %{event_name: "Signup", custom_props: %{"tier" => "premium"}}
+ }
+
+ conn
+ |> authenticate(site.domain, token)
+ |> put_req_header("content-type", "application/json")
+ |> put(url, payload)
+ |> json_response(402)
+ |> assert_schema("PaymentRequiredError", spec())
+ end
+
test "validates input according to the schema", %{conn: conn, token: token, site: site} do
url = Routes.plugins_api_goals_url(PlausibleWeb.Endpoint, :create)
@@ -547,7 +697,11 @@ defmodule PlausibleWeb.Plugins.API.Controllers.GoalsTest do
end
test "retrieves custom event goal by ID", %{conn: conn, site: site, token: token} do
- {:ok, goal} = Plausible.Goals.create(site, %{"event_name" => "Signup"})
+ {:ok, goal} =
+ Plausible.Goals.create(site, %{
+ "event_name" => "Signup",
+ "custom_props" => %{"tier" => "premium"}
+ })
url = Routes.plugins_api_goals_url(PlausibleWeb.Endpoint, :get, goal.id)
@@ -563,10 +717,39 @@ defmodule PlausibleWeb.Plugins.API.Controllers.GoalsTest do
assert schema.goal.id == goal.id
assert schema.goal_type == "Goal.CustomEvent"
assert schema.goal.display_name == "Signup"
+ assert schema.goal.custom_props == %{"tier" => "premium"}
end
end
describe "get /goals" do
+ test "returns goals with custom props in response", %{conn: conn, site: site, token: token} do
+ {:ok, _g1} =
+ Plausible.Goals.create(site, %{
+ "event_name" => "Signup",
+ "custom_props" => %{"tier" => "premium"}
+ })
+
+ {:ok, _g2} =
+ Plausible.Goals.create(site, %{"page_path" => "/checkout", "custom_props" => %{}})
+
+ url = Routes.plugins_api_goals_url(PlausibleWeb.Endpoint, :index)
+
+ resp =
+ conn
+ |> authenticate(site.domain, token)
+ |> get(url)
+ |> json_response(200)
+ |> assert_schema("Goal.ListResponse", spec())
+
+ [checkout, signup] = resp.goals
+
+ assert signup.goal.event_name == "Signup"
+ assert signup.goal.custom_props == %{"tier" => "premium"}
+
+ assert checkout.goal.path == "/checkout"
+ assert checkout.goal.custom_props == %{}
+ end
+
test "returns an empty goals list if there's none", %{
conn: conn,
token: token,
diff --git a/test/support/teams/test.ex b/test/support/teams/test.ex
index d4c699889d..7f3b71ad28 100644
--- a/test/support/teams/test.ex
+++ b/test/support/teams/test.ex
@@ -248,21 +248,35 @@ defmodule Plausible.Teams.Test do
user
end
- def subscribe_to_growth_plan(user, attrs \\ []) do
+ def subscribe_to_growth_plan(user_or_team, attrs \\ [])
+
+ def subscribe_to_growth_plan(%Plausible.Auth.User{} = user, attrs) do
{:ok, team} = Teams.get_or_create(user)
attrs = Keyword.merge([team: team], attrs)
- insert(:growth_subscription, attrs)
+ subscribe_to_growth_plan(team, attrs)
user
end
- def subscribe_to_business_plan(user) do
+ def subscribe_to_growth_plan(%Plausible.Teams.Team{} = team, attrs) do
+ attrs = Keyword.merge([team: team], attrs)
+
+ insert(:growth_subscription, attrs)
+ team
+ end
+
+ def subscribe_to_business_plan(%Plausible.Auth.User{} = user) do
{:ok, team} = Teams.get_or_create(user)
+ subscribe_to_business_plan(team)
- insert(:business_subscription, team: team)
user
end
+ def subscribe_to_business_plan(%Plausible.Teams.Team{} = team) do
+ insert(:business_subscription, team: team)
+ team
+ end
+
def subscribe_to_plan(user, paddle_plan_id, attrs \\ []) do
{:ok, team} = Teams.get_or_create(user)
attrs = Keyword.merge([team: team, paddle_plan_id: paddle_plan_id], attrs)