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
Plugins API: 2nd pass with Goals resource + SharedLinks schema changes (#3396)
hq10007c0c1086d
diff --git a/lib/plausible/goal/schema.ex b/lib/plausible/goal/schema.exindex d4dee4a6c1..7ab88dbccf 100644--- a/lib/plausible/goal/schema.ex+++ b/lib/plausible/goal/schema.ex@@ -117,9 +117,13 @@ defimpl String.Chars, for: Plausible.Goal do"Visit " <> page_pathend- def to_string(%{event_name: name}) when is_binary(name) do+ def to_string(%{event_name: name, currency: nil}) when is_binary(name) donameend++ def to_string(%{event_name: name, currency: currency}) when is_binary(name) do+ name <> " (#{currency})"+ endenddefimpl Phoenix.HTML.Safe, for: Plausible.Goal dodiff --git a/lib/plausible/goals.ex b/lib/plausible/goals.exindex 1d5cfebcc3..fc8fb9d3d1 100644--- a/lib/plausible/goals.ex+++ b/lib/plausible/goals.ex@@ -11,69 +11,76 @@ defmodule Plausible.Goals doIf the created goal is a revenue goal, it sets site.updated_at to berefreshed by the sites cache, as revenue goals are used during ingestion."""- def create(site, params, now \\ DateTime.utc_now()) do- params = Map.merge(params, %{"site_id" => site.id})-- Ecto.Multi.new()- |> Ecto.Multi.insert(:goal, Goal.changeset(%Goal{}, params))- |> Ecto.Multi.run(:site, fn repo, %{goal: goal} ->- if Goal.revenue?(goal) do- now =- now- |> DateTime.truncate(:second)- |> DateTime.to_naive()-- site- |> Ecto.Changeset.change(updated_at: now)- |> repo.update()- else- {:ok, site}+ def create(site, params, opts \\ []) do+ now = Keyword.get(opts, :now, DateTime.utc_now())+ upsert? = Keyword.get(opts, :upsert?, false)++ Repo.transaction(fn ->+ case insert_goal(site, params, upsert?) do+ {:ok, :insert, goal} ->+ # credo:disable-for-next-line Credo.Check.Refactor.Nesting+ if Goal.revenue?(goal) do+ Plausible.Site.Cache.touch_site!(site, now)+ end++ Repo.preload(goal, :site)++ {:ok, :upsert, goal} ->+ Repo.preload(goal, :site)++ {:error, changeset} ->+ Repo.rollback(changeset)endend)- |> Repo.transaction()- |> case do- {:ok, %{goal: goal}} -> {:ok, Repo.preload(goal, :site)}- {:error, _failed_operation, failed_value, _changes_so_far} -> {:error, failed_value}- endend- def find_or_create(site, %{"goal_type" => "event", "event_name" => event_name}) do- query =- from g in Goal,- inner_join: assoc(g, :site),- where: g.site_id == ^site.id,- where: g.event_name == ^event_name,- preload: [:site]-- goal = Repo.one(query)+ def find_or_create(site, %{+ "goal_type" => "event",+ "event_name" => event_name,+ "currency" => currency+ })+ when is_binary(event_name) and is_binary(currency) do+ params = %{"event_name" => event_name, "currency" => currency}++ with {:ok, goal} <- create(site, params, upsert?: true) do+ if to_string(goal.currency) == currency do+ {:ok, goal}+ else+ # we must disallow creation of the same goal name with different currency+ changeset =+ goal+ |> Goal.changeset()+ |> Ecto.Changeset.add_error(+ :event_name,+ "'#{goal.event_name}' (with currency: #{goal.currency}) has already been taken"+ )- case goal do- nil -> create(site, %{"event_name" => event_name})- goal -> {:ok, goal}+ {:error, changeset}+ endendend+ def find_or_create(site, %{"goal_type" => "event", "event_name" => event_name})+ when is_binary(event_name) do+ create(site, %{"event_name" => event_name}, upsert?: true)+ end+def find_or_create(_, %{"goal_type" => "event"}), do: {:missing, "event_name"}def find_or_create(site, %{"goal_type" => "page", "page_path" => page_path}) do- query =- from g in Goal,- inner_join: assoc(g, :site),- where: g.site_id == ^site.id,- where: g.page_path == ^page_path,- preload: [:site]-- goal = Repo.one(query)-- case goal do- nil -> create(site, %{"page_path" => page_path})- goal -> {:ok, goal}- end+ create(site, %{"page_path" => page_path}, upsert?: true)enddef find_or_create(_, %{"goal_type" => "page"}), do: {:missing, "page_path"}def for_site(site, opts \\ []) do+ site+ |> for_site_query(opts)+ |> Repo.all()+ |> Enum.map(&maybe_trim/1)+ end++ def for_site_query(site, opts \\ []) doquery =from g in Goal,inner_join: assoc(g, :site),@@ -81,30 +88,15 @@ defmodule Plausible.Goals doorder_by: [desc: g.id],preload: [:site]- query =- if opts[:preload_funnels?] do- from g in query,- left_join: assoc(g, :funnels),- group_by: g.id,- preload: [:funnels]- else- query- end-- query =- if opts[:preload_funnels?] do- from(g in query,- left_join: assoc(g, :funnels),- group_by: g.id,- preload: [:funnels]- )- else- query- end-- query- |> Repo.all()- |> Enum.map(&maybe_trim/1)+ if opts[:preload_funnels?] do+ from(g in query,+ left_join: assoc(g, :funnels),+ group_by: g.id,+ preload: [:funnels]+ )+ else+ query+ endend@doc """@@ -188,6 +180,35 @@ defmodule Plausible.Goals do)end+ defp insert_goal(site, params, upsert?) do+ params = Map.delete(params, "site_id")++ insert_opts =+ if upsert? do+ [on_conflict: :nothing]+ else+ []+ end++ changeset = Goal.changeset(%Goal{site_id: site.id}, params)++ with {:ok, goal} <- Repo.insert(changeset, insert_opts) do+ # Upsert with `on_conflict: :nothing` strategy+ # will result in goal struct missing primary key field+ # which is generated by the database.+ if goal.id do+ {:ok, :insert, goal}+ else+ get_params =+ goal+ |> Map.take([:site_id, :event_name, :page_path])+ |> Enum.reject(fn {_, value} -> is_nil(value) end)++ {:ok, :upsert, Repo.get_by!(Goal, get_params)}+ end+ end+ end+defp maybe_trim(%Goal{} = goal) do# we make sure that even if we saved goals erroneously with trailing# space, it's removed during fetchdiff --git a/lib/plausible/plugins/api/goals.ex b/lib/plausible/plugins/api/goals.exnew file mode 100644index 0000000000..93372c2c37--- /dev/null+++ b/lib/plausible/plugins/api/goals.ex@@ -0,0 +1,77 @@+defmodule Plausible.Plugins.API.Goals do+ @moduledoc """+ Plugins API context module for Goals.+ All high level Goal operations should be implemented here.+ """++ import Ecto.Query+ import Plausible.Plugins.API.Pagination++ alias Plausible.Repo+ alias PlausibleWeb.Plugins.API.Schemas.Goal.CreateRequest++ @type create_request() ::+ CreateRequest.CustomEvent.t()+ | CreateRequest.Revenue.t()+ | CreateRequest.Pageview.t()++ @spec create(+ Plausible.Site.t(),+ create_request() | list(create_request())+ ) :: {:ok, list(Plausible.Goal.t())} | {:error, Ecto.Changeset.t()}+ def create(site, goal_or_goals) do+ Repo.transaction(fn -> find_or_create(site, goal_or_goals) end)+ end++ @spec get_goals(Plausible.Site.t(), map()) :: {:ok, Paginator.Page.t()}+ def get_goals(site, params) do+ query = Plausible.Goals.for_site_query(site, preload_funnels?: true)++ {:ok, paginate(query, params, cursor_fields: [{:id, :desc}])}+ end++ @spec get(Plausible.Site.t(), pos_integer()) :: nil | Plausible.Goal.t()+ def get(site, id) when is_integer(id) do+ site+ |> get_query()+ |> where([g], g.id == ^id)+ |> Repo.one()+ end++ defp get_query(site) do+ from g in Plausible.Goal,+ where: g.site_id == ^site.id,+ order_by: [desc: g.id],+ left_join: assoc(g, :funnels),+ group_by: g.id,+ preload: [:funnels]+ 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}+ }) do+ %{"goal_type" => "event", "event_name" => event_name, "currency" => currency}+ end++ defp convert_to_create_params(%CreateRequest.Pageview{goal: %{path: page_path}}) do+ %{"goal_type" => "page", "page_path" => page_path}+ end++ defp find_or_create(site, goal_or_goals) do+ goal_or_goals+ |> List.wrap()+ |> Enum.map(fn goal ->+ case Plausible.Goals.find_or_create(site, convert_to_create_params(goal)) do+ {:ok, goal} ->+ goal++ {:error, changeset} ->+ Repo.rollback(changeset)+ end+ end)+ end+enddiff --git a/lib/plausible/plugins/api/context/shared_links.ex b/lib/plausible/plugins/api/shared_links.exsimilarity index 93%rename from lib/plausible/plugins/api/context/shared_links.exrename to lib/plausible/plugins/api/shared_links.exindex 0fc1f73348..d9f33cd3bc 100644--- a/lib/plausible/plugins/api/context/shared_links.ex+++ b/lib/plausible/plugins/api/shared_links.ex@@ -1,6 +1,6 @@-defmodule Plausible.Plugins.API.Context.SharedLinks do+defmodule Plausible.Plugins.API.SharedLinks do@moduledoc """- Plugins API Context module for Shared Links.+ Plugins API context module for Shared Links.All high level Shared Links operations should be implemented here."""import Ecto.Querydiff --git a/lib/plausible/plugins/api/tokens.ex b/lib/plausible/plugins/api/tokens.exindex 821ef36879..b5ab19a689 100644--- a/lib/plausible/plugins/api/tokens.ex+++ b/lib/plausible/plugins/api/tokens.ex@@ -10,7 +10,7 @@ defmodule Plausible.Plugins.API.Tokens doimport Ecto.Query@spec create(Site.t(), String.t()) ::- {:ok, Token.t(), String.t(), String.t()} | {:error, Ecto.Changeset.t()}+ {:ok, Token.t(), String.t()} | {:error, Ecto.Changeset.t()}def create(%Site{} = site, description, generated_token \\ Token.generate()) dowith changeset <- Token.insert_changeset(site, generated_token, %{description: description}),{:ok, saved_token} <- Repo.insert(changeset) dodiff --git a/lib/plausible/site/cache.ex b/lib/plausible/site/cache.exindex 8c62675c68..42cd6c2d45 100644--- a/lib/plausible/site/cache.ex+++ b/lib/plausible/site/cache.ex@@ -209,6 +209,18 @@ defmodule Plausible.Site.Cache do[:plausible, :cache, cache_name, :refresh, mode]end+ @spec touch_site!(Site.t(), DateTime.t()) :: Site.t()+ def touch_site!(site, now) do+ now =+ now+ |> DateTime.truncate(:second)+ |> DateTime.to_naive()++ site+ |> Ecto.Changeset.change(updated_at: now)+ |> Plausible.Repo.update!()+ end+def enabled?() doApplication.fetch_env!(:plausible, :sites_by_domain_cache_enabled) == trueenddiff --git a/lib/plausible_web.ex b/lib/plausible_web.exindex 4c6f9d8dc7..4c2cb6b4b0 100644--- a/lib/plausible_web.ex+++ b/lib/plausible_web.ex@@ -52,7 +52,8 @@ defmodule PlausibleWeb doalias PlausibleWeb.Plugins.API.Schemasalias PlausibleWeb.Plugins.API.Views- alias Plausible.Plugins.API.Context+ alias PlausibleWeb.Plugins.API.Errors+ alias Plausible.Plugins.APIplug(OpenApiSpex.Plug.CastAndValidate, json_render_error_v2: true, replace_params: false)diff --git a/lib/plausible_web/live/goal_settings/list.ex b/lib/plausible_web/live/goal_settings/list.exindex 00fdabee7e..1dbdfb7194 100644--- a/lib/plausible_web/live/goal_settings/list.ex+++ b/lib/plausible_web/live/goal_settings/list.ex@@ -58,7 +58,7 @@ defmodule PlausibleWeb.Live.GoalSettings.List do<span :if={goal.page_path}>Pageview</span><span :if={goal.event_name && !goal.currency}>Custom Event</span><span :if={goal.currency}>- Revenue Goal: <%= goal.currency %>+ Revenue Goal</span><span :if={not Enum.empty?(goal.funnels)}> - belongs to funnel(s)</span></span>diff --git a/lib/plausible_web/plugins/api/controllers/goals.ex b/lib/plausible_web/plugins/api/controllers/goals.exnew file mode 100644index 0000000000..7e9b2738c2--- /dev/null+++ b/lib/plausible_web/plugins/api/controllers/goals.ex@@ -0,0 +1,160 @@+defmodule PlausibleWeb.Plugins.API.Controllers.Goals do+ @moduledoc """+ Controller for the Goal resource under Plugins API+ """+ use PlausibleWeb, :plugins_api_controller++ operation(:index,+ summary: "Retrieve Goals",+ parameters: [+ limit: [in: :query, type: :integer, description: "Maximum entries per page", example: 10],+ after: [+ in: :query,+ type: :string,+ description: "Cursor value to seek after - generated internally"+ ],+ before: [+ in: :query,+ type: :string,+ description: "Cursor value to seek before - generated internally"+ ]+ ],+ responses: %{+ ok: {"Goals response", "application/json", Schemas.Goal.ListResponse},+ unauthorized: {"Unauthorized", "application/json", Schemas.Unauthorized}+ }+ )++ operation(:create,+ id: "Goal.GetOrCreate",+ summary: "Get or create Goal",+ request_body: {"Goal params", "application/json", Schemas.Goal.CreateRequest},+ responses: %{+ created:+ {"Goal", "application/json",+ %OpenApiSpex.Schema{+ oneOf: [Schemas.Goal.ListResponse, Schemas.Goal]+ }},+ unauthorized: {"Unauthorized", "application/json", Schemas.Unauthorized},+ unprocessable_entity:+ {"Unprocessable entity", "application/json", Schemas.UnprocessableEntity}+ }+ )++ @spec create(Plug.Conn.t(), map()) :: Plug.Conn.t()+ def create(+ %{private: %{open_api_spex: %{body_params: %{goal: _} = goal}}} = conn,+ _params+ ) do+ site = conn.assigns.authorized_site++ case API.Goals.create(site, goal) do+ {:ok, [goal]} ->+ conn+ |> put_view(Views.Goal)+ |> put_status(:created)+ |> put_resp_header("location", goals_url(base_uri(), :get, goal.id))+ |> render("goal.json", goal: goal, authorized_site: site)++ {:error, changeset} ->+ Errors.error(conn, 422, changeset)+ end+ end++ def create(+ %{private: %{open_api_spex: %{body_params: %{goals: goals}}}} = conn,+ _params+ ) do+ site = conn.assigns.authorized_site++ case API.Goals.create(site, goals) do+ {:ok, goals} ->+ location_headers = Enum.map(goals, &{"location", goals_url(base_uri(), :get, &1.id)})++ conn+ |> prepend_resp_headers(location_headers)+ |> put_view(Views.Goal)+ |> put_status(:created)+ |> render("index.json", goals: goals, authorized_site: site)++ {:error, changeset} ->+ Errors.error(conn, 422, changeset)+ end+ end++ @spec index(Plug.Conn.t(), %{}) :: Plug.Conn.t()+ def index(conn, _params) do+ {:ok, pagination} = API.Goals.get_goals(conn.assigns.authorized_site, conn.query_params)++ conn+ |> put_view(Views.Goal)+ |> render("index.json", %{pagination: pagination})+ end++ operation(:get,+ summary: "Retrieve Goal by ID",+ parameters: [+ id: [+ in: :path,+ type: :integer,+ description: "Goal ID",+ example: 123,+ required: true+ ]+ ],+ responses: %{+ ok: {"Goal", "application/json", Schemas.Goal},+ not_found: {"NotFound", "application/json", Schemas.NotFound},+ unauthorized: {"Unauthorized", "application/json", Schemas.Unauthorized},+ unprocessable_entity:+ {"Unprocessable entity", "application/json", Schemas.UnprocessableEntity}+ }+ )++ @spec get(Plug.Conn.t(), map()) :: Plug.Conn.t()+ def get(%{private: %{open_api_spex: %{params: %{id: id}}}} = conn, _params) do+ site = conn.assigns.authorized_site++ case API.Goals.get(site, id) do+ nil ->+ conn+ |> put_view(Views.Error)+ |> put_status(:not_found)+ |> render("404.json")++ goal ->+ conn+ |> put_view(Views.Goal)+ |> put_status(:ok)+ |> render("goal.json", goal: goal, authorized_site: site)+ end+ end++ operation(:delete,+ summary: "Delete Goal by ID",+ parameters: [+ id: [+ in: :path,+ type: :integer,+ description: "Goal ID",+ example: 123,+ required: true+ ]+ ],+ responses: %{+ no_content: {"NoContent", nil, nil},+ unauthorized: {"Unauthorized", "application/json", Schemas.Unauthorized}+ }+ )++ @spec delete(Plug.Conn.t(), map()) :: Plug.Conn.t()+ def delete(%{private: %{open_api_spex: %{params: %{id: id}}}} = conn, _params) do+ case Plausible.Goals.delete(id, conn.assigns.authorized_site) do+ :ok ->+ send_resp(conn, :no_content, "")++ {:error, :not_found} ->+ send_resp(conn, :no_content, "")+ end+ end+enddiff --git a/lib/plausible_web/plugins/api/controllers/shared_links.ex b/lib/plausible_web/plugins/api/controllers/shared_links.exindex a344b7e38b..84b59d03bb 100644--- a/lib/plausible_web/plugins/api/controllers/shared_links.ex+++ b/lib/plausible_web/plugins/api/controllers/shared_links.ex@@ -28,7 +28,7 @@ defmodule PlausibleWeb.Plugins.API.Controllers.SharedLinks do@spec index(Plug.Conn.t(), %{}) :: Plug.Conn.t()def index(conn, _params) do{:ok, pagination} =- Context.SharedLinks.get_shared_links(conn.assigns.authorized_site, conn.query_params)+ API.SharedLinks.get_shared_links(conn.assigns.authorized_site, conn.query_params)conn|> put_view(Views.SharedLink)@@ -36,7 +36,7 @@ defmodule PlausibleWeb.Plugins.API.Controllers.SharedLinks doendoperation(:create,- summary: "Create Shared Link",+ summary: "Get or create Shared Link",request_body: {"Shared Link params", "application/json", Schemas.SharedLink.CreateRequest},responses: %{created: {"Shared Link", "application/json", Schemas.SharedLink},@@ -51,7 +51,9 @@ defmodule PlausibleWeb.Plugins.API.Controllers.SharedLinks do%{private: %{open_api_spex: %{- body_params: %Schemas.SharedLink.CreateRequest{name: name, password: password}+ body_params: %Schemas.SharedLink.CreateRequest{+ shared_link: %{name: name} = shared_link+ }}}} = conn,@@ -59,7 +61,7 @@ defmodule PlausibleWeb.Plugins.API.Controllers.SharedLinks do) dosite = conn.assigns.authorized_site- {:ok, shared_link} = Context.SharedLinks.get_or_create(site, name, password)+ {:ok, shared_link} = API.SharedLinks.get_or_create(site, name, shared_link[:password])conn|> put_view(Views.SharedLink)@@ -92,7 +94,7 @@ defmodule PlausibleWeb.Plugins.API.Controllers.SharedLinks dodef get(%{private: %{open_api_spex: %{params: %{id: id}}}} = conn, _params) dosite = conn.assigns.authorized_site- case Context.SharedLinks.get(site, id) do+ case API.SharedLinks.get(site, id) donil ->conn|> put_view(Views.Error)diff --git a/lib/plausible_web/plugins/api/errors.ex b/lib/plausible_web/plugins/api/errors.exindex 5c3a0980a7..530b299197 100644--- a/lib/plausible_web/plugins/api/errors.ex+++ b/lib/plausible_web/plugins/api/errors.ex@@ -4,6 +4,7 @@ defmodule PlausibleWeb.Plugins.API.Errors do"""import Plug.Conn+ import Plausible.ChangesetHelpers@spec unauthorized(Plug.Conn.t()) :: Plug.Conn.t()def unauthorized(conn) do@@ -12,15 +13,36 @@ defmodule PlausibleWeb.Plugins.API.Errors do|> error(:unauthorized, "Plugins API: unauthorized")end- @spec error(Plug.Conn.t(), Plug.Conn.status(), String.t() | [String.t()]) :: Plug.Conn.t()+ @spec error(+ Plug.Conn.t(),+ Plug.Conn.status(),+ String.t() | [String.t()] | Ecto.Changeset.t() | [Ecto.Changeset.t()]+ ) ::+ Plug.Conn.t()def error(conn, status, message) when is_binary(message) doerror(conn, status, [message])end+ def error(conn, status, message) when is_map(message) do+ error(conn, status, [message])+ end+def error(conn, status, messages) when is_list(messages) doresponse =Jason.encode!(%{- errors: Enum.map(messages, &%{detail: &1})+ errors:+ Enum.map(messages, fn+ message when is_binary(message) ->+ %{detail: message}++ %Ecto.Changeset{} = changeset ->+ changeset+ |> traverse_errors()+ |> Enum.map(fn {key, message} ->+ %{detail: "#{key}: #{message}"}+ end)+ end)+ |> List.flatten()})conndiff --git a/lib/plausible_web/plugins/api/router.ex b/lib/plausible_web/plugins/api/router.exindex 2ab4fdc0fc..88abc4a2d5 100644--- a/lib/plausible_web/plugins/api/router.ex+++ b/lib/plausible_web/plugins/api/router.ex@@ -21,6 +21,11 @@ defmodule PlausibleWeb.Plugins.API.Router doget("/shared_links", SharedLinks, :index)get("/shared_links/:id", SharedLinks, :get)- post("/shared_links", SharedLinks, :create)+ put("/shared_links", SharedLinks, :create)++ get("/goals", Goals, :index)+ get("/goals/:id", Goals, :get)+ put("/goals", Goals, :create)+ delete("/goals/:id", Goals, :delete)endenddiff --git a/lib/plausible_web/plugins/api/schemas/goal.ex b/lib/plausible_web/plugins/api/schemas/goal.exnew file mode 100644index 0000000000..060c72efe9--- /dev/null+++ b/lib/plausible_web/plugins/api/schemas/goal.ex@@ -0,0 +1,32 @@+defmodule PlausibleWeb.Plugins.API.Schemas.Goal do+ @moduledoc """+ OpenAPI schema for Goal+ """+ use PlausibleWeb, :open_api_schema++ OpenApiSpex.schema(%{+ title: "Goal",+ description: "Goal object",+ type: :object,+ discriminator: %OpenApiSpex.Discriminator{+ propertyName: "goal_type",+ mapping: %{+ "Goal.CustomEvent" => Schemas.Goal.CustomEvent,+ "Goal.Pageview" => Schemas.Goal.Pageview,+ "Goal.Revenue" => Schemas.Goal.Revenue+ }+ },+ oneOf: [+ Schemas.Goal.CustomEvent,+ Schemas.Goal.Revenue,+ Schemas.Goal.Pageview+ ],+ example: %{+ goal_type: "Goal.Revenue",+ goal: %{+ currency: "EUR",+ event_name: "Purchase"+ }+ }+ })+enddiff --git a/lib/plausible_web/plugins/api/schemas/goal/create_request.ex b/lib/plausible_web/plugins/api/schemas/goal/create_request.exnew file mode 100644index 0000000000..b3ca009252--- /dev/null+++ b/lib/plausible_web/plugins/api/schemas/goal/create_request.ex@@ -0,0 +1,38 @@+defmodule PlausibleWeb.Plugins.API.Schemas.Goal.CreateRequest do+ @moduledoc """+ OpenAPI schema for Goal creation request+ """+ use Plausible.Funnel+ use PlausibleWeb, :open_api_schema++ OpenApiSpex.schema(%{+ title: "Goal.CreateRequest",+ description: "Goal creation params",+ type: :object,+ oneOf: [+ %Schema{+ title: "Goal.CreateRequest.BulkGetOrCreate",+ type: :object,+ description: "Bulk goal creation request",+ required: [:goals],+ properties: %{+ goals: %Schema{+ type: :array,+ minItems: 1,+ maxItems: Funnel.max_steps(),+ items: %Schema{+ oneOf: [+ Schemas.Goal.CreateRequest.CustomEvent,+ Schemas.Goal.CreateRequest.Revenue,+ Schemas.Goal.CreateRequest.Pageview+ ]+ }+ }+ }+ },+ Schemas.Goal.CreateRequest.CustomEvent,+ Schemas.Goal.CreateRequest.Revenue,+ Schemas.Goal.CreateRequest.Pageview+ ]+ })+enddiff --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.exnew file mode 100644index 0000000000..758a428cdb--- /dev/null+++ b/lib/plausible_web/plugins/api/schemas/goal/create_request/custom_event.ex@@ -0,0 +1,34 @@+defmodule PlausibleWeb.Plugins.API.Schemas.Goal.CreateRequest.CustomEvent do+ @moduledoc """+ OpenAPI schema for Custom Event Goal creation request+ """++ use PlausibleWeb, :open_api_schema++ OpenApiSpex.schema(%{+ title: "Goal.CreateRequest.CustomEvent",+ description: "Custom Event Goal creation params",+ type: :object,+ required: [:goal, :goal_type],+ properties: %{+ goal_type: %Schema{+ type: :string,+ enum: ["Goal.CustomEvent"],+ default: "Goal.CustomEvent"+ },+ goal: %Schema{+ type: :object,+ required: [:event_name],+ properties: %{+ event_name: %Schema{type: :string}+ }+ }+ },+ example: %{+ goal_type: "Goal.CustomEvent",+ goal: %{+ event_name: "Signup"+ }+ }+ })+enddiff --git a/lib/plausible_web/plugins/api/schemas/goal/create_request/pageview.ex b/lib/plausible_web/plugins/api/schemas/goal/create_request/pageview.exnew file mode 100644index 0000000000..2b224dcc9f--- /dev/null+++ b/lib/plausible_web/plugins/api/schemas/goal/create_request/pageview.ex@@ -0,0 +1,34 @@+defmodule PlausibleWeb.Plugins.API.Schemas.Goal.CreateRequest.Pageview do+ @moduledoc """+ OpenAPI schema for Pageview Goal creation request+ """++ use PlausibleWeb, :open_api_schema++ OpenApiSpex.schema(%{+ title: "Goal.CreateRequest.Pageview",+ description: "Pageview Goal creation params",+ type: :object,+ required: [:goal, :goal_type],+ properties: %{+ goal_type: %Schema{+ type: :string,+ enum: ["Goal.Pageview"],+ default: "Goal.Pageview"+ },+ goal: %Schema{+ type: :object,+ required: [:path],+ properties: %{+ path: %Schema{type: :string}+ }+ }+ },+ example: %{+ goal_type: "Goal.Pageview",+ goal: %{+ path: "/checkout"+ }+ }+ })+enddiff --git a/lib/plausible_web/plugins/api/schemas/goal/create_request/revenue.ex b/lib/plausible_web/plugins/api/schemas/goal/create_request/revenue.exnew file mode 100644index 0000000000..4b8f413769--- /dev/null+++ b/lib/plausible_web/plugins/api/schemas/goal/create_request/revenue.ex@@ -0,0 +1,36 @@+defmodule PlausibleWeb.Plugins.API.Schemas.Goal.CreateRequest.Revenue do+ @moduledoc """+ OpenAPI schema for Custom Event Goal creation request+ """++ use PlausibleWeb, :open_api_schema++ OpenApiSpex.schema(%{+ title: "Goal.CreateRequest.Revenue",+ description: "Revenue Goal creation params",+ type: :object,+ required: [:goal, :goal_type],+ properties: %{+ goal_type: %Schema{+ type: :string,+ enum: ["Goal.Revenue"],+ default: "Goal.Revenue"+ },+ goal: %Schema{+ type: :object,+ required: [:event_name, :currency],+ properties: %{+ event_name: %Schema{type: :string},+ currency: %Schema{type: :string}+ }+ }+ },+ example: %{+ goal_type: "Goal.Revenue",+ goal: %{+ event_name: "Purchase",+ currency: "EUR"+ }+ }+ })+enddiff --git a/lib/plausible_web/plugins/api/schemas/goal/custom_event.ex b/lib/plausible_web/plugins/api/schemas/goal/custom_event.exnew file mode 100644index 0000000000..fac4d810cd--- /dev/null+++ b/lib/plausible_web/plugins/api/schemas/goal/custom_event.ex@@ -0,0 +1,30 @@+defmodule PlausibleWeb.Plugins.API.Schemas.Goal.CustomEvent do+ @moduledoc """+ OpenAPI schema for Custom Event Goal object+ """+ use PlausibleWeb, :open_api_schema++ OpenApiSpex.schema(%{+ description: "Custom Event Goal object",+ title: "Goal.CustomEvent",+ type: :object,+ allOf: [+ Schemas.Goal.Type,+ %Schema{+ type: :object,+ required: [:goal],+ properties: %{+ goal: %Schema{+ type: :object,+ required: [:id, :display_name, :event_name],+ 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"}+ }+ }+ }+ }+ ]+ })+enddiff --git a/lib/plausible_web/plugins/api/schemas/goal/list_response.ex b/lib/plausible_web/plugins/api/schemas/goal/list_response.exnew file mode 100644index 0000000000..b458d64d30--- /dev/null+++ b/lib/plausible_web/plugins/api/schemas/goal/list_response.ex@@ -0,0 +1,29 @@+defmodule PlausibleWeb.Plugins.API.Schemas.Goal.ListResponse do+ @moduledoc """+ OpenAPI schema for Goals list response+ """+ use PlausibleWeb, :open_api_schema++ OpenApiSpex.schema(%{+ title: "Goal.ListResponse",+ description: "Goals list response",+ type: :object,+ required: [:goals, :meta],+ properties: %{+ goals: %Schema{+ items: Schemas.Goal,+ type: :array+ },+ meta: %OpenApiSpex.Schema{+ required: [:pagination],+ properties: %{+ pagination: %OpenApiSpex.Reference{+ "$ref": "#/components/schemas/PaginationMetadata"+ }+ },+ type: :object,+ items: Schemas.PaginationMetadata+ }+ }+ })+enddiff --git a/lib/plausible_web/plugins/api/schemas/goal/pageview.ex b/lib/plausible_web/plugins/api/schemas/goal/pageview.exnew file mode 100644index 0000000000..d68a0a47ef--- /dev/null+++ b/lib/plausible_web/plugins/api/schemas/goal/pageview.ex@@ -0,0 +1,30 @@+defmodule PlausibleWeb.Plugins.API.Schemas.Goal.Pageview do+ @moduledoc """+ OpenAPI schema for Pageview Goal object+ """+ use PlausibleWeb, :open_api_schema++ OpenApiSpex.schema(%{+ description: "Pageview Goal object",+ title: "Goal.Pageview",+ type: :object,+ allOf: [+ Schemas.Goal.Type,+ %Schema{+ type: :object,+ required: [:goal],+ properties: %{+ goal: %Schema{+ type: :object,+ required: [:id, :display_name, :path],+ 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"}+ }+ }+ }+ }+ ]+ })+enddiff --git a/lib/plausible_web/plugins/api/schemas/goal/revenue.ex b/lib/plausible_web/plugins/api/schemas/goal/revenue.exnew file mode 100644index 0000000000..c254064893--- /dev/null+++ b/lib/plausible_web/plugins/api/schemas/goal/revenue.ex@@ -0,0 +1,31 @@+defmodule PlausibleWeb.Plugins.API.Schemas.Goal.Revenue do+ @moduledoc """+ OpenAPI schema for Revenue Goal object+ """+ use PlausibleWeb, :open_api_schema++ OpenApiSpex.schema(%{+ description: "Revenue Goal object",+ title: "Goal.Revenue",+ type: :object,+ allOf: [+ Schemas.Goal.Type,+ %Schema{+ type: :object,+ required: [:goal],+ properties: %{+ goal: %Schema{+ type: :object,+ required: [:id, :display_name, :event_name, :currency],+ 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"},+ currency: %Schema{type: :string, description: "Currency"}+ }+ }+ }+ }+ ]+ })+enddiff --git a/lib/plausible_web/plugins/api/schemas/goal/type.ex b/lib/plausible_web/plugins/api/schemas/goal/type.exnew file mode 100644index 0000000000..ebc41b0e97--- /dev/null+++ b/lib/plausible_web/plugins/api/schemas/goal/type.ex@@ -0,0 +1,18 @@+defmodule PlausibleWeb.Plugins.API.Schemas.Goal.Type do+ @moduledoc """+ OpenAPI schema for common Goal Type++ Future-proof: funnels etc.+ """+ use PlausibleWeb, :open_api_schema++ OpenApiSpex.schema(%{+ title: "Goal.Type",+ description: "Properties common to all Goals",+ type: :object,+ properties: %{+ goal_type: %Schema{type: :string}+ },+ required: [:goal_type]+ })+enddiff --git a/lib/plausible_web/plugins/api/schemas/shared_link.ex b/lib/plausible_web/plugins/api/schemas/shared_link.exindex 81ecff96f9..a7dec09402 100644--- a/lib/plausible_web/plugins/api/schemas/shared_link.ex+++ b/lib/plausible_web/plugins/api/schemas/shared_link.ex@@ -7,9 +7,9 @@ defmodule PlausibleWeb.Plugins.API.Schemas.SharedLink doOpenApiSpex.schema(%{description: "Shared Link object",type: :object,- required: [:data],+ required: [:shared_link],properties: %{- data: %Schema{+ shared_link: %Schema{type: :object,required: [:id, :name, :password_protected, :href],properties: %{@@ -22,6 +22,14 @@ defmodule PlausibleWeb.Plugins.API.Schemas.SharedLink dohref: %Schema{type: :string, description: "Shared Link URL"}}}+ },+ example: %{+ shared_link: %{+ id: 1024,+ name: "Public Dashboard",+ password_protected: false,+ href: "https://example.com"+ }}})enddiff --git a/lib/plausible_web/plugins/api/schemas/shared_link/create_request.ex b/lib/plausible_web/plugins/api/schemas/shared_link/create_request.exindex 65e5754e13..0b6b3726fd 100644--- a/lib/plausible_web/plugins/api/schemas/shared_link/create_request.ex+++ b/lib/plausible_web/plugins/api/schemas/shared_link/create_request.ex@@ -8,13 +8,19 @@ defmodule PlausibleWeb.Plugins.API.Schemas.SharedLink.CreateRequest dotitle: "SharedLink.CreateRequest",description: "Shared Links creation params",type: :object,- required: [:name],+ required: [:shared_link],properties: %{- name: %Schema{description: "Shared Link Name", type: :string},- password: %Schema{description: "Shared Link Password", type: :string}+ shared_link: %Schema{+ type: :object,+ required: [:name],+ properties: %{+ name: %Schema{description: "Shared Link Name", type: :string},+ password: %Schema{description: "Shared Link Password", type: :string}+ }+ }},example: %{- name: "My Shared Dashboard"+ shared_link: %{name: "My Shared Dashboard"}}})enddiff --git a/lib/plausible_web/plugins/api/schemas/shared_link/list_response.ex b/lib/plausible_web/plugins/api/schemas/shared_link/list_response.exindex 66ebc70bb8..87464c4638 100644--- a/lib/plausible_web/plugins/api/schemas/shared_link/list_response.ex+++ b/lib/plausible_web/plugins/api/schemas/shared_link/list_response.ex@@ -8,9 +8,9 @@ defmodule PlausibleWeb.Plugins.API.Schemas.SharedLink.ListResponse dotitle: "SharedLink.ListResponse",description: "Shared Links list response",type: :object,- required: [:data, :meta],+ required: [:shared_links, :meta],properties: %{- data: %Schema{+ shared_links: %Schema{items: Schemas.SharedLink,type: :array},diff --git a/lib/plausible_web/plugins/api/views/goal.ex b/lib/plausible_web/plugins/api/views/goal.exnew file mode 100644index 0000000000..ab7b32254e--- /dev/null+++ b/lib/plausible_web/plugins/api/views/goal.ex@@ -0,0 +1,70 @@+defmodule PlausibleWeb.Plugins.API.Views.Goal do+ @moduledoc """+ View for rendering Goals in the Plugins API+ """++ use PlausibleWeb, :plugins_api_view++ def render("index.json", %{+ pagination: %{entries: goals, metadata: metadata},+ authorized_site: site,+ conn: conn+ }) do+ %{+ goals: render_many(goals, __MODULE__, "goal.json", authorized_site: site),+ meta: render_metadata_links(metadata, :goals_url, :index, conn.query_params)+ }+ end++ def render("index.json", %{+ goals: goals,+ authorized_site: site,+ conn: conn+ }) do+ %{+ goals: render_many(goals, __MODULE__, "goal.json", authorized_site: site),+ meta: render_metadata_links(%{}, :goals_url, :index, conn.query_params)+ }+ end++ def render("goal.json", %{+ goal: %{event_name: nil} = pageview+ }) do+ %{+ goal_type: "Goal.Pageview",+ goal: %{+ id: pageview.id,+ display_name: to_string(pageview),+ path: pageview.page_path+ }+ }+ end++ def render("goal.json", %{+ goal: %{page_path: nil, currency: nil} = custom_event+ }) do+ %{+ goal_type: "Goal.CustomEvent",+ goal: %{+ id: custom_event.id,+ display_name: to_string(custom_event),+ event_name: custom_event.event_name+ }+ }+ end++ def render("goal.json", %{+ goal: %{page_path: nil, currency: currency} = revenue_goal+ })+ when is_atom(currency) do+ %{+ goal_type: "Goal.Revenue",+ goal: %{+ id: revenue_goal.id,+ display_name: to_string(revenue_goal),+ event_name: revenue_goal.event_name,+ currency: revenue_goal.currency+ }+ }+ end+enddiff --git a/lib/plausible_web/plugins/api/views/shared_link.ex b/lib/plausible_web/plugins/api/views/shared_link.exindex e3b5ed2a30..bd5a71ebd1 100644--- a/lib/plausible_web/plugins/api/views/shared_link.ex+++ b/lib/plausible_web/plugins/api/views/shared_link.ex@@ -11,7 +11,8 @@ defmodule PlausibleWeb.Plugins.API.Views.SharedLink doconn: conn}) do%{- data: render_many(shared_links, __MODULE__, "shared_link.json", authorized_site: site),+ shared_links:+ render_many(shared_links, __MODULE__, "shared_link.json", authorized_site: site),meta: render_metadata_links(metadata, :shared_links_url, :index, conn.query_params)}end@@ -21,7 +22,7 @@ defmodule PlausibleWeb.Plugins.API.Views.SharedLink doauthorized_site: site}) do%{- data: %{+ shared_link: %{id: shared_link.id,name: shared_link.name,password_protected: is_binary(shared_link.password_hash),diff --git a/test/plausible/goals_test.exs b/test/plausible/goals_test.exsindex 6fdba92d3a..98c7ab4f0d 100644--- a/test/plausible/goals_test.exs+++ b/test/plausible/goals_test.exs@@ -38,6 +38,16 @@ defmodule Plausible.GoalsTest doassert {"has already been taken", _} = changeset.errors[:event_name]end+ test "create/2 fails to create the same currency goal twice" do+ site = insert(:site)+ {:ok, _} = Goals.create(site, %{"event_name" => "foo bar", "currency" => "EUR"})++ assert {:error, changeset} =+ Goals.create(site, %{"event_name" => "foo bar", "currency" => "EUR"})++ assert {"has already been taken", _} = changeset.errors[:event_name]+ end+test "create/2 sets site.updated_at for revenue goal" dosite_1 = insert(:site, updated_at: DateTime.add(DateTime.utc_now(), -3600)){:ok, _goal_1} = Goals.create(site_1, %{"event_name" => "Checkout", "currency" => "BRL"})diff --git a/test/plausible/site/cache_test.exs b/test/plausible/site/cache_test.exsindex 99205b12e3..4e67f2f89a 100644--- a/test/plausible/site/cache_test.exs+++ b/test/plausible/site/cache_test.exs@@ -97,7 +97,10 @@ defmodule Plausible.Site.CacheTest do# the site was added yesterday so full refresh will pick it up%{id: site_id} = site = insert(:site, domain: "site1.example.com", updated_at: yesterday)# the goal was added yesterday so full refresh will pick it up- Plausible.Goals.create(site, %{"event_name" => "Purchase", "currency" => :BRL}, yesterday)+ Plausible.Goals.create(site, %{"event_name" => "Purchase", "currency" => :BRL},+ now: yesterday+ )+# this goal is added "just now"Plausible.Goals.create(site, %{"event_name" => "Add to Cart", "currency" => :USD})# and this one does not matter@@ -110,7 +113,7 @@ defmodule Plausible.Site.CacheTest doPlausible.Goals.create(site,%{"event_name" => "Purchase2", "currency" => :BRL},- DateTime.add(DateTime.utc_now(), -70)+ now: DateTime.add(DateTime.utc_now(), -70)):ok = Cache.refresh_updated_recently(cache_name: test)diff --git a/test/plausible_web/live/goal_settings/form_test.exs b/test/plausible_web/live/goal_settings/form_test.exsindex 9a6d7c8011..17bf7a9099 100644--- a/test/plausible_web/live/goal_settings/form_test.exs+++ b/test/plausible_web/live/goal_settings/form_test.exs@@ -75,8 +75,8 @@ defmodule PlausibleWeb.Live.GoalSettings.FormTest dorefute render(parent) =~ "Foo"lv |> element("form") |> render_submit(%{goal: %{event_name: "Foo", currency: "EUR"}})parent_html = render(parent)- assert parent_html =~ "Foo"- assert parent_html =~ "Revenue Goal: EUR"+ assert parent_html =~ "Foo (EUR)"+ assert parent_html =~ "Revenue Goal"endtest "creates a pageview goal", %{conn: conn, site: site} dodiff --git a/test/plausible_web/live/goal_settings_test.exs b/test/plausible_web/live/goal_settings_test.exsindex d301aec1c5..a0d6134987 100644--- a/test/plausible_web/live/goal_settings_test.exs+++ b/test/plausible_web/live/goal_settings_test.exs@@ -21,7 +21,7 @@ defmodule PlausibleWeb.Live.GoalSettingsTest doassert resp =~ to_string(g2)assert resp =~ "Custom Event"assert resp =~ to_string(g3)- assert resp =~ "Revenue Goal: EUR"+ assert resp =~ "Revenue Goal"endtest "lists goals with delete actions", %{conn: conn, site: site} dodiff --git a/test/plausible_web/plugins/api/controllers/goals_test.exs b/test/plausible_web/plugins/api/controllers/goals_test.exsnew file mode 100644index 0000000000..a63edd8f3c--- /dev/null+++ b/test/plausible_web/plugins/api/controllers/goals_test.exs@@ -0,0 +1,546 @@+defmodule PlausibleWeb.Plugins.API.Controllers.GoalsTest do+ use PlausibleWeb.PluginsAPICase, async: true+ alias PlausibleWeb.Plugins.API.Schemas++ describe "examples" do+ test "Goal.CreateRequest.Revenue" do+ assert_schema(+ Schemas.Goal.CreateRequest.Revenue.schema().example,+ "Goal.CreateRequest.Revenue",+ spec()+ )+ end++ test "Goal.CreateRequest.Pageview" do+ assert_schema(+ Schemas.Goal.CreateRequest.Pageview.schema().example,+ "Goal.CreateRequest.Pageview",+ spec()+ )+ end++ test "Goal.CreateRequest.CustomEvent" do+ assert_schema(+ Schemas.Goal.CreateRequest.CustomEvent.schema().example,+ "Goal.CreateRequest.CustomEvent",+ spec()+ )+ end+ end++ describe "unauthorized calls" do+ for {method, url} <- [+ {:get, Routes.goals_url(base_uri(), :index)},+ {:get, Routes.goals_url(base_uri(), :get, 1)},+ {:put, Routes.goals_url(base_uri(), :create, %{})},+ {:delete, Routes.goals_url(base_uri(), :delete, 1)}+ ] do+ test "unauthorized call: #{method} #{url}", %{conn: conn} do+ conn+ |> unquote(method)(unquote(url))+ |> json_response(401)+ |> assert_schema("UnauthorizedError", spec())+ end+ end+ end++ describe "put /goals - create a single goal" do+ test "validates input according to the schema", %{conn: conn, token: token, site: site} do+ url = Routes.goals_url(base_uri(), :create)++ conn+ |> authenticate(site.domain, token)+ |> put_req_header("content-type", "application/json")+ |> put(url, %{goal_type: "Goal.SomeTypo", goal: %{event_name: "Signup"}})+ |> json_response(422)+ |> assert_schema("UnprocessableEntityError", spec())+ end++ test "creates a custom event goal", %{conn: conn, token: token, site: site} do+ url = Routes.goals_url(base_uri(), :create)++ payload = %{goal_type: "Goal.CustomEvent", goal: %{event_name: "Signup"}}++ 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 =+ conn+ |> json_response(201)+ |> assert_schema("Goal", spec())+ |> assert_schema("Goal.CustomEvent", spec())++ [location] = get_resp_header(conn, "location")++ assert location ==+ Routes.goals_url(base_uri(), :get, resp.goal.id)++ assert [%{event_name: "Signup"}] = Plausible.Goals.for_site(site)+ end++ test "creates a revenue goal", %{conn: conn, token: token, site: site} do+ url = Routes.goals_url(base_uri(), :create)++ payload = %{+ goal_type: "Goal.Revenue",+ goal: %{event_name: "Purchase", currency: "EUR"}+ }++ assert_request_schema(payload, "Goal.CreateRequest.Revenue", spec())++ conn =+ conn+ |> authenticate(site.domain, token)+ |> put_req_header("content-type", "application/json")+ |> put(url, payload)++ resp =+ conn+ |> json_response(201)+ |> assert_schema("Goal", spec())+ |> assert_schema("Goal.Revenue", spec())++ [location] = get_resp_header(conn, "location")++ assert location ==+ Routes.goals_url(base_uri(), :get, resp.goal.id)++ assert [%{event_name: "Purchase", currency: :EUR}] = Plausible.Goals.for_site(site)+ end++ test "fails to create a revenue goal with unknown currency", %{+ conn: conn,+ token: token,+ site: site+ } do+ url = Routes.goals_url(base_uri(), :create)++ payload = %{+ goal_type: "Goal.Revenue",+ goal: %{event_name: "Purchase", currency: "DFJKHJESFHYU"}+ }++ assert_request_schema(payload, "Goal.CreateRequest.Revenue", spec())++ conn =+ conn+ |> authenticate(site.domain, token)+ |> put_req_header("content-type", "application/json")+ |> put(url, payload)++ resp =+ conn+ |> json_response(422)+ |> assert_schema("UnprocessableEntityError", spec())++ assert [%{detail: "currency: is invalid"}] = resp.errors+ end++ test "edge case - revenue goal exists under the same name and different currency", %{+ conn: conn,+ token: token,+ site: site+ } do+ url = Routes.goals_url(base_uri(), :create)++ {:ok, _} = Plausible.Goals.create(site, %{"event_name" => "Purchase", "currency" => "USD"})++ conn =+ conn+ |> authenticate(site.domain, token)+ |> put_req_header("content-type", "application/json")+ |> put(url, %{goal_type: "Goal.Revenue", goal: %{event_name: "Purchase", currency: "EUR"}})++ resp =+ conn+ |> json_response(422)+ |> assert_schema("UnprocessableEntityError", spec())++ assert [%{detail: "event_name: 'Purchase' (with currency: USD) has already been taken"}] =+ resp.errors+ end++ test "creates a pageview goal", %{conn: conn, token: token, site: site} do+ url = Routes.goals_url(base_uri(), :create)++ payload = %{goal_type: "Goal.Pageview", goal: %{path: "/checkout"}}+ assert_request_schema(payload, "Goal.CreateRequest.Pageview", spec())++ conn =+ conn+ |> authenticate(site.domain, token)+ |> put_req_header("content-type", "application/json")+ |> put(url, payload)++ resp =+ conn+ |> json_response(201)+ |> assert_schema("Goal", spec())+ |> assert_schema("Goal.Pageview", spec())++ [location] = get_resp_header(conn, "location")++ assert location ==+ Routes.goals_url(base_uri(), :get, resp.goal.id)++ assert [%{page_path: "/checkout"}] = Plausible.Goals.for_site(site)+ end++ test "is idempotent", %{conn: conn, token: token, site: site} do+ url = Routes.goals_url(base_uri(), :create)++ initial_conn =+ conn+ |> authenticate(site.domain, token)+ |> put_req_header("content-type", "application/json")++ resp1 =+ initial_conn+ |> put(url, %{goal_type: "Goal.Pageview", goal: %{path: "/checkout"}})+ |> json_response(201)+ |> assert_schema("Goal.Pageview", spec())++ assert initial_conn+ |> put(url, %{goal_type: "Goal.Pageview", goal: %{path: "/checkout"}})+ |> json_response(201)+ |> assert_schema("Goal.Pageview", spec()) == resp1+ end+ end++ describe "put /goals - bulk creation" do+ test "creates a goal of each type", %{conn: conn, token: token, site: site} do+ url = Routes.goals_url(base_uri(), :create)++ payload = %{+ goals: [+ %{+ goal_type: "Goal.CustomEvent",+ goal: %{event_name: "Signup"}+ },+ %{+ goal_type: "Goal.Revenue",+ goal: %{event_name: "Purchase", currency: "EUR"}+ },+ %{+ goal_type: "Goal.Pageview",+ goal: %{path: "/checkout"}+ }+ ]+ }++ assert_request_schema(payload, "Goal.CreateRequest.BulkGetOrCreate", spec())++ conn =+ conn+ |> authenticate(site.domain, token)+ |> put_req_header("content-type", "application/json")+ |> put(url, payload)++ resp =+ conn+ |> json_response(201)+ |> assert_schema("Goal.ListResponse", spec())++ [l1, l2, l3] = get_resp_header(conn, "location")++ assert l1 == Routes.goals_url(base_uri(), :get, Enum.at(resp.goals, 0).goal.id)+ assert l2 == Routes.goals_url(base_uri(), :get, Enum.at(resp.goals, 1).goal.id)+ assert l3 == Routes.goals_url(base_uri(), :get, Enum.at(resp.goals, 2).goal.id)++ assert Enum.count(resp.goals) == 3++ assert [+ %{page_path: "/checkout"},+ %{event_name: "Purchase", currency: :EUR},+ %{event_name: "Signup"}+ ] = Plausible.Goals.for_site(site)+ end++ test "no more than 8 goals can be created in bulk", %{conn: conn, token: token, site: site} do+ # if this test fails due to implementation change, consider what to do with the pagination meta+ # object returned in the response and also revise how funnels are created based on a list of goals+ # - the funnels creation endpoint will likely reuse this schema's constraints+ url = Routes.goals_url(base_uri(), :create)++ payload =+ Enum.map(1..9, fn i ->+ %{goal_type: "Goal.CustomEvent", goal: %{event_name: "Bulk Goal ##{i}"}}+ end)++ resp =+ conn+ |> authenticate(site.domain, token)+ |> put_req_header("content-type", "application/json")+ |> put(url, %{+ goals: payload+ })+ |> json_response(422)+ |> assert_schema("UnprocessableEntityError", spec())++ assert %Schemas.Error{+ detail: "Array length 9 is larger than maxItems: 8"+ } in resp.errors+ end++ test "is idempotent", %{conn: conn, token: token, site: site} do+ url = Routes.goals_url(base_uri(), :create)++ initial_conn =+ conn+ |> authenticate(site.domain, token)+ |> put_req_header("content-type", "application/json")++ payload = [+ %{+ goal_type: "Goal.CustomEvent",+ goal: %{event_name: "Signup"}+ },+ %{+ goal_type: "Goal.Revenue",+ goal: %{event_name: "Purchase", currency: "EUR"}+ },+ %{+ goal_type: "Goal.Pageview",+ goal: %{path: "/checkout"}+ }+ ]++ initial_conn+ |> put(url, %{goals: payload})+ |> json_response(201)+ |> assert_schema("Goal.ListResponse", spec())++ initial_conn+ |> put(url, %{goals: payload})+ |> json_response(201)+ |> assert_schema("Goal.ListResponse", spec())+ end++ test "edge case - revenue goals exist under the same name and different currency", %{+ conn: conn,+ token: token,+ site: site+ } do+ url = Routes.goals_url(base_uri(), :create)++ initial_conn =+ conn+ |> authenticate(site.domain, token)+ |> put_req_header("content-type", "application/json")++ payload1 = [%{goal_type: "Goal.Revenue", goal: %{event_name: "Purchase", currency: "EUR"}}]+ payload2 = [%{goal_type: "Goal.Revenue", goal: %{event_name: "Purchase", currency: "USD"}}]++ initial_conn+ |> put(url, %{goals: payload1})+ |> json_response(201)+ |> assert_schema("Goal.ListResponse", spec())++ resp =+ initial_conn+ |> put(url, %{goals: payload2})+ |> json_response(422)+ |> assert_schema("UnprocessableEntityError", spec())++ assert [%{detail: "event_name: 'Purchase' (with currency: EUR) has already been taken"}] =+ resp.errors+ end+ end++ describe "get /goals/:id" do+ test "validates input out of the box", %{conn: conn, token: token, site: site} do+ url = Routes.goals_url(base_uri(), :get, "hello")++ resp =+ conn+ |> authenticate(site.domain, token)+ |> get(url)+ |> json_response(422)+ |> assert_schema("UnprocessableEntityError", spec())++ assert %{errors: [%{detail: "Invalid integer. Got: string"}]} = resp+ end++ test "retrieves revenue goal by ID", %{conn: conn, site: site, token: token} do+ {:ok, goal} =+ Plausible.Goals.create(site, %{"event_name" => "Purchase", "currency" => "EUR"})++ url = Routes.goals_url(base_uri(), :get, goal.id)++ resp =+ conn+ |> authenticate(site.domain, token)+ |> get(url)+ |> json_response(200)+ |> assert_schema("Goal", spec())+ |> assert_schema("Goal.Revenue", spec())++ assert resp.goal.id == goal.id+ assert resp.goal_type == "Goal.Revenue"+ assert resp.goal.display_name == "Purchase (EUR)"+ end++ test "retrieves pageview goal by ID", %{conn: conn, site: site, token: token} do+ {:ok, goal} = Plausible.Goals.create(site, %{"page_path" => "/checkout"})++ url = Routes.goals_url(base_uri(), :get, goal.id)++ resp =+ conn+ |> authenticate(site.domain, token)+ |> get(url)+ |> json_response(200)+ |> assert_schema("Goal", spec())+ |> assert_schema("Goal.Pageview", spec())++ assert resp.goal.id == goal.id+ assert resp.goal_type == "Goal.Pageview"+ assert resp.goal.display_name == "Visit /checkout"+ end++ test "retrieves custom event goal by ID", %{conn: conn, site: site, token: token} do+ {:ok, goal} = Plausible.Goals.create(site, %{"event_name" => "Signup"})++ url = Routes.goals_url(base_uri(), :get, goal.id)++ resp =+ conn+ |> authenticate(site.domain, token)+ |> get(url)+ |> json_response(200)+ |> assert_schema("Goal", spec())+ |> assert_schema("Goal.CustomEvent", spec())++ assert resp.goal.id == goal.id+ assert resp.goal_type == "Goal.CustomEvent"+ assert resp.goal.display_name == "Signup"+ end+ end++ describe "get /goals" do+ test "returns an empty goals list if there's none", %{+ conn: conn,+ token: token,+ site: site+ } do+ url = Routes.goals_url(base_uri(), :index)++ resp =+ conn+ |> authenticate(site.domain, token)+ |> get(url)+ |> json_response(200)+ |> assert_schema("Goal.ListResponse", spec())++ assert resp.goals == []+ assert resp.meta.pagination.has_next_page == false+ assert resp.meta.pagination.has_prev_page == false+ assert resp.meta.pagination.links == %{}+ end++ test "returns a list of goals of each possible goal type", %{+ conn: conn,+ site: site,+ token: token+ } do+ {:ok, g1} = Plausible.Goals.create(site, %{"event_name" => "Signup"})+ {:ok, g2} = Plausible.Goals.create(site, %{"event_name" => "Purchase", "currency" => "EUR"})+ {:ok, g3} = Plausible.Goals.create(site, %{"page_path" => "/checkout"})++ url = Routes.goals_url(base_uri(), :index)++ resp =+ conn+ |> authenticate(site.domain, token)+ |> get(url)+ |> json_response(200)+ |> assert_schema("Goal.ListResponse", spec())++ assert [checkout, purchase, signup] = resp.goals+ assert checkout.goal.display_name == "Visit /checkout"+ assert checkout.goal.path == "/checkout"+ assert checkout.goal.id == g3.id+ assert checkout.goal_type == "Goal.Pageview"++ assert purchase.goal.display_name == "Purchase (EUR)"+ assert purchase.goal.currency == "EUR"+ assert purchase.goal.event_name == "Purchase"+ assert purchase.goal.id == g2.id+ assert purchase.goal_type == "Goal.Revenue"++ assert signup.goal.display_name == "Signup"+ assert signup.goal.event_name == "Signup"+ assert signup.goal.id == g1.id+ assert signup.goal_type == "Goal.CustomEvent"+ end++ test "returns a list of goals with pagination", %{conn: conn, site: site, token: token} do+ for i <- 1..5 do+ insert(:goal, site: site, event_name: "Goal #{i}")+ end++ url = Routes.goals_url(base_uri(), :index, limit: 2)++ initial_conn = authenticate(conn, site.domain, token)++ page1 =+ initial_conn+ |> get(url)+ |> json_response(200)+ |> assert_schema("Goal.ListResponse", spec())++ assert [%{goal: %{event_name: "Goal 5"}}, %{goal: %{event_name: "Goal 4"}}] = page1.goals+ assert page1.meta.pagination.has_next_page == true+ assert page1.meta.pagination.has_prev_page == false+ assert page1.meta.pagination.links.next+ refute page1.meta.pagination.links[:prev]++ page2 =+ initial_conn+ |> get(page1.meta.pagination.links.next.url)+ |> json_response(200)+ |> assert_schema("Goal.ListResponse", spec())++ assert [%{goal: %{event_name: "Goal 3"}}, %{goal: %{event_name: "Goal 2"}}] = page2.goals++ assert page2.meta.pagination.has_next_page == true+ assert page2.meta.pagination.has_prev_page == true+ assert page2.meta.pagination.links.next+ assert page2.meta.pagination.links.prev++ assert ^page1 =+ initial_conn+ |> get(page2.meta.pagination.links.prev.url)+ |> json_response(200)+ |> assert_schema("Goal.ListResponse", spec())+ end+ end++ describe "delete /goals/:id" do+ test "deletes goal by id", %{conn: conn, site: site, token: token} do+ {:ok, %{id: goal_id}} =+ Plausible.Goals.create(site, %{"event_name" => "Purchase", "currency" => "USD"})++ url = Routes.goals_url(base_uri(), :delete, goal_id)++ conn+ |> authenticate(site.domain, token)+ |> delete(url)+ |> response(204)+ end++ test "is idempotent", %{conn: conn, site: site, token: token} do+ url = Routes.goals_url(base_uri(), :delete, 666)++ conn+ |> authenticate(site.domain, token)+ |> delete(url)+ |> response(204)+ end+ end+enddiff --git a/test/plausible_web/plugins/api/controllers/shared_links_test.exs b/test/plausible_web/plugins/api/controllers/shared_links_test.exsindex 6e73365b4d..437ade37c7 100644--- a/test/plausible_web/plugins/api/controllers/shared_links_test.exs+++ b/test/plausible_web/plugins/api/controllers/shared_links_test.exs@@ -1,23 +1,23 @@defmodule PlausibleWeb.Plugins.API.Controllers.SharedLinksTest douse PlausibleWeb.PluginsAPICase, async: true- setup %{test: test} do- site = insert(:site)- {:ok, _token, raw_token} = Plausible.Plugins.API.Tokens.create(site, Atom.to_string(test))-- {:ok,- %{- site: site,- token: raw_token- }}+ describe "examples" do+ test "SharedLink" do+ assert_schema(+ Schemas.SharedLink.schema().example,+ "SharedLink",+ spec()+ )+ endend- describe "unathorized calls" do+ describe "unauthorized calls" dofor {method, url} <- [{:get, Routes.shared_links_url(base_uri(), :get, 1)},- {:post, Routes.shared_links_url(base_uri(), :create)}+ {:put, Routes.shared_links_url(base_uri(), :create)},+ {:get, Routes.shared_links_url(base_uri(), :index)}] do- test "unauthorized call to #{url}", %{conn: conn} do+ test "unauthorized call: #{method} #{url}", %{conn: conn} doconn|> unquote(method)(unquote(url))|> json_response(401)@@ -52,12 +52,12 @@ defmodule PlausibleWeb.Plugins.API.Controllers.SharedLinksTest do|> json_response(200)|> assert_schema("SharedLink", spec())- assert resp.data.href ==+ assert resp.shared_link.href =="http://localhost:8000/share/#{site.domain}?auth=#{shared_link.slug}"- assert resp.data.id == shared_link.id- assert resp.data.password_protected == false- assert resp.data.name == "Some Link Name"+ assert resp.shared_link.id == shared_link.id+ assert resp.shared_link.password_protected == false+ assert resp.shared_link.name == "Some Link Name"endtest "fails to retrieve non-existing link", %{conn: conn, site: site, token: token} do@@ -82,7 +82,7 @@ defmodule PlausibleWeb.Plugins.API.Controllers.SharedLinksTest doendend- describe "post /shared_links" do+ describe "put /shared_links" dotest "successfully creates a shared link with the location header", %{conn: conn,site: site,@@ -95,8 +95,10 @@ defmodule PlausibleWeb.Plugins.API.Controllers.SharedLinksTest doconn =initial_conn|> put_req_header("content-type", "application/json")- |> post(url, %{- name: "My Shared Link"+ |> put(url, %{+ shared_link: %{+ name: "My Shared Link"+ }})resp =@@ -104,13 +106,13 @@ defmodule PlausibleWeb.Plugins.API.Controllers.SharedLinksTest do|> json_response(201)|> assert_schema("SharedLink", spec())- assert resp.data.name == "My Shared Link"- assert resp.data.href =~ "http://localhost:8000/share/#{site.domain}?auth="+ assert resp.shared_link.name == "My Shared Link"+ assert resp.shared_link.href =~ "http://localhost:8000/share/#{site.domain}?auth="[location] = get_resp_header(conn, "location")assert location ==- Routes.shared_links_url(base_uri(), :get, resp.data.id)+ Routes.shared_links_url(base_uri(), :get, resp.shared_link.id)assert ^resp =initial_conn@@ -131,8 +133,10 @@ defmodule PlausibleWeb.Plugins.API.Controllers.SharedLinksTest docreate = fn ->initial_conn|> put_req_header("content-type", "application/json")- |> post(url, %{- name: "My Shared Link"+ |> put(url, %{+ shared_link: %{+ name: "My Shared Link"+ }})end@@ -143,14 +147,14 @@ defmodule PlausibleWeb.Plugins.API.Controllers.SharedLinksTest do|> json_response(201)|> assert_schema("SharedLink", spec())- id = resp.data.id+ id = resp.shared_link.idconn = create.()assert ^id =conn|> json_response(201)- |> Map.fetch!("data")+ |> Map.fetch!("shared_link")|> Map.fetch!("id")end@@ -161,11 +165,11 @@ defmodule PlausibleWeb.Plugins.API.Controllers.SharedLinksTest doconn|> authenticate(site.domain, token)|> put_req_header("content-type", "application/json")- |> post(url, %{})+ |> put(url, %{})|> json_response(422)|> assert_schema("UnprocessableEntityError", spec())- assert %{errors: [%{detail: "Missing field: name"}]} = resp+ assert %{errors: [%{detail: "Missing field: shared_link"}]} = respendend@@ -184,7 +188,7 @@ defmodule PlausibleWeb.Plugins.API.Controllers.SharedLinksTest do|> json_response(200)|> assert_schema("SharedLink.ListResponse", spec())- assert resp.data == []+ assert resp.shared_links == []assert resp.meta.pagination.has_next_page == falseassert resp.meta.pagination.has_prev_page == falseassert resp.meta.pagination.links == %{}@@ -209,7 +213,9 @@ defmodule PlausibleWeb.Plugins.API.Controllers.SharedLinksTest do|> json_response(200)|> assert_schema("SharedLink.ListResponse", spec())- assert [%{data: %{name: "Shared Link 5"}}, %{data: %{name: "Shared Link 4"}}] = page1.data+ assert [%{shared_link: %{name: "Shared Link 5"}}, %{shared_link: %{name: "Shared Link 4"}}] =+ page1.shared_links+assert page1.meta.pagination.has_next_page == trueassert page1.meta.pagination.has_prev_page == falseassert page1.meta.pagination.links.next@@ -221,7 +227,8 @@ defmodule PlausibleWeb.Plugins.API.Controllers.SharedLinksTest do|> json_response(200)|> assert_schema("SharedLink.ListResponse", spec())- assert [%{data: %{name: "Shared Link 3"}}, %{data: %{name: "Shared Link 2"}}] = page2.data+ assert [%{shared_link: %{name: "Shared Link 3"}}, %{shared_link: %{name: "Shared Link 2"}}] =+ page2.shared_linksassert page2.meta.pagination.has_next_page == trueassert page2.meta.pagination.has_prev_page == truediff --git a/test/plausible_web/plugins/api/errors_test.exs b/test/plausible_web/plugins/api/errors_test.exsindex 344b607081..61fceefe46 100644--- a/test/plausible_web/plugins/api/errors_test.exs+++ b/test/plausible_web/plugins/api/errors_test.exs@@ -37,5 +37,37 @@ defmodule PlausibleWeb.Plugins.API.ErrorsTest do"errors" => [%{"detail" => "Some message"}]}end++ defmodule Example do+ use Ecto.Schema+ import Ecto.Changeset++ schema "" do+ field(:name)+ field(:email)+ field(:age, :integer)+ end++ def changeset(example, params \\ %{}) do+ example+ |> cast(params, [:name, :email, :age])+ |> validate_required([:name, :email])+ |> validate_format(:email, ~r/@/)+ |> validate_inclusion(:age, 18..100)+ end+ end++ test "formats changeset errors" do+ changeset = Example.changeset(%Example{}, %{email: "foo", age: 101})++ assert Plug.Test.conn(:get, "/")+ |> Errors.error(:bad_request, changeset)+ |> json_response(400)+ |> Map.fetch!("errors") == [+ %{"detail" => "age: is invalid"},+ %{"detail" => "email: has invalid format"},+ %{"detail" => "name: can't be blank"}+ ]+ endendenddiff --git a/test/support/plugins_api_case.ex b/test/support/plugins_api_case.exindex 21ce095fbc..3a9eff2715 100644--- a/test/support/plugins_api_case.ex+++ b/test/support/plugins_api_case.ex@@ -17,11 +17,13 @@ defmodule PlausibleWeb.PluginsAPICase doimport Phoenix.ConnTestimport PlausibleWeb.Plugins.API, only: [base_uri: 0]import PlausibleWeb.Plugins.API.Spec, only: [spec: 0]- alias PlausibleWeb.Plugins.API.Router.Helpers, as: Routesimport Plausible.Factoryimport OpenApiSpex.TestAssertions+ alias PlausibleWeb.Plugins.API.Router.Helpers, as: Routes+ alias PlausibleWeb.Plugins.API.Schemas+def authenticate(conn, domain, raw_token) doconn|> Plug.Conn.put_req_header(@@ -32,7 +34,8 @@ defmodule PlausibleWeb.PluginsAPICase doendend- setup tags do+ setup %{test: test} = tags do+ import Plausible.Factory:ok = Ecto.Adapters.SQL.Sandbox.checkout(Plausible.Repo)unless tags[:async] do@@ -41,6 +44,9 @@ defmodule PlausibleWeb.PluginsAPICase doconn = Phoenix.ConnTest.build_conn()- {:ok, conn: conn}+ site = insert(:site)+ {:ok, _token, raw_token} = Plausible.Plugins.API.Tokens.create(site, Atom.to_string(test))++ {:ok, conn: conn, site: site, token: raw_token}endend