From ba19f9530e8f338943a33365c36ae87f19901d0c Mon Sep 17 00:00:00 2001 From: RobertJoonas <56999674+RobertJoonas@users.noreply.github.com> Date: Tue, 13 Jun 2023 09:16:38 +0300 Subject: [PATCH] UI groundwork: Conversions to Behaviors (#3005) * copy relevant files from b2ace16540ebb435b2b5ba2a2ad0604345488a81 * make it work and set site.funnels to empty list * make Behaviours a functional component * add UI for a setup hint and always display conversions by default * cherry-pick migration commit * update site schema with new fields * backend: implement disable-feature action * switch between tabs in the behaviors section Introduces template components to build props and funnels on. Both only show a setup notice atm, and both are behind feature flags. * extend API for disabling props and funnels * render feature setup note directly from the Behaviours component * fix UI behavior when features are hidden * update setup notices * add conversions feature switch to Site Settings > Goals * mix format * remove IO.inspect * change setup notice - use buttons + popup confirmation * optimize for light mode * restrict access to setup notices * some styling improvements * allow super-admins to enable/disable features * only show conversions (last 30min) in realtime mode * use shorter display names for tabs * optimize for mobile screens * note about sending custom events * changelog update + fix CI * change HTTP verb for the disable-feature action * change UI label for show/hide goals --- CHANGELOG.md | 1 + assets/js/dashboard/api.js | 8 + assets/js/dashboard/components/notice.js | 56 ++++ assets/js/dashboard/historical.js | 16 +- assets/js/dashboard/mount.js | 4 + assets/js/dashboard/realtime.js | 17 +- .../index.js => behaviours/conversions.js} | 14 +- .../js/dashboard/stats/behaviours/funnel.js | 4 + assets/js/dashboard/stats/behaviours/index.js | 250 ++++++++++++++++++ .../prop-breakdown.js | 0 lib/plausible/site.ex | 11 + .../controllers/api/internal_controller.ex | 25 +- .../controllers/site_controller.ex | 28 ++ .../controllers/stats_controller.ex | 9 +- lib/plausible_web/router.ex | 3 + .../templates/site/new_goal.html.eex | 5 + .../templates/site/settings_goals.html.eex | 20 +- .../templates/stats/stats.html.eex | 4 + .../api/internal_controller_test.exs | 88 ++++++ .../controllers/site_controller_test.exs | 103 ++++++++ 20 files changed, 626 insertions(+), 40 deletions(-) create mode 100644 assets/js/dashboard/components/notice.js rename assets/js/dashboard/stats/{conversions/index.js => behaviours/conversions.js} (93%) create mode 100644 assets/js/dashboard/stats/behaviours/funnel.js create mode 100644 assets/js/dashboard/stats/behaviours/index.js rename assets/js/dashboard/stats/{conversions => behaviours}/prop-breakdown.js (100%) diff --git a/CHANGELOG.md b/CHANGELOG.md index 680196652..e575e36d6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,7 @@ All notable changes to this project will be documented in this file. ## Unreleased ### Added +- Call to action for tracking Goal Conversions and an option to hide the section from the dashboard - Add support for `with_imported=true` in Stats API aggregate endpoint - Ability to use '--' instead of '=' sign in the `tagged-events` classnames - 'Last updated X seconds ago' info to 'current visitors' tooltips diff --git a/assets/js/dashboard/api.js b/assets/js/dashboard/api.js index 165ca0838..158f9a60f 100644 --- a/assets/js/dashboard/api.js +++ b/assets/js/dashboard/api.js @@ -71,3 +71,11 @@ export function get(url, query={}, ...extraQuery) { return response.json() }) } + +export function put(url, body) { + return fetch(url, { + method: "PUT", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify(body) + }) +} diff --git a/assets/js/dashboard/components/notice.js b/assets/js/dashboard/components/notice.js new file mode 100644 index 000000000..fd2d9876a --- /dev/null +++ b/assets/js/dashboard/components/notice.js @@ -0,0 +1,56 @@ +import React from "react" +import { sectionTitles } from "../stats/behaviours" +import * as api from '../api' + +export function FeatureSetupNotice({ site, feature, shortFeatureName, title, info, settingsLink, onHideAction }) { + const sectionTitle = sectionTitles[feature] + + const requestHideSection = () => { + if (window.confirm(`Are you sure you want to hide ${sectionTitle}? You can make it visible again in your site settings later.`)) { + api.put(`/api/${encodeURIComponent(site.domain)}/disable-feature`, { feature: feature }) + .then(response => { + if (response.ok) { onHideAction() } + }) + } + } + + function setupButton() { + return ( + +

Set up {shortFeatureName}

+ + + +
+ ) + } + + function hideButton() { + return ( + + ) + } + + return ( +
+
+
+ {title} +
+ +
+ {info} +
+ +
+ {hideButton()} + {setupButton()} +
+
+
+ ) +} \ No newline at end of file diff --git a/assets/js/dashboard/historical.js b/assets/js/dashboard/historical.js index 524bcbab5..8f6dcdb90 100644 --- a/assets/js/dashboard/historical.js +++ b/assets/js/dashboard/historical.js @@ -9,25 +9,13 @@ import Sources from './stats/sources' import Pages from './stats/pages' import Locations from './stats/locations'; import Devices from './stats/devices' -import Conversions from './stats/conversions' +import Behaviours from './stats/behaviours' import ComparisonInput from './comparison-input' import { withPinnedHeader } from './pinned-header-hoc'; function Historical(props) { const tooltipBoundary = React.useRef(null) - function renderConversions() { - if (props.site.hasGoals) { - return ( -
- -
- ) - } - - return null - } - return (
@@ -51,7 +39,7 @@ function Historical(props) {
- { renderConversions() } + ) } diff --git a/assets/js/dashboard/mount.js b/assets/js/dashboard/mount.js index 9c923a88b..2f867b563 100644 --- a/assets/js/dashboard/mount.js +++ b/assets/js/dashboard/mount.js @@ -16,6 +16,10 @@ if (container) { domain: container.dataset.domain, offset: container.dataset.offset, hasGoals: container.dataset.hasGoals === 'true', + conversionsEnabled: container.dataset.conversionsEnabled === 'true', + funnelsEnabled: container.dataset.funnelsEnabled === 'true', + propsEnabled: container.dataset.propsEnabled === 'true', + funnels: JSON.parse(container.dataset.funnels), statsBegin: container.dataset.statsBegin, nativeStatsBegin: container.dataset.nativeStatsBegin, embedded: container.dataset.embedded, diff --git a/assets/js/dashboard/realtime.js b/assets/js/dashboard/realtime.js index 1c85f8b8c..ea1a283ef 100644 --- a/assets/js/dashboard/realtime.js +++ b/assets/js/dashboard/realtime.js @@ -8,22 +8,10 @@ import Sources from './stats/sources' import Pages from './stats/pages' import Locations from './stats/locations' import Devices from './stats/devices' -import Conversions from './stats/conversions' +import Behaviours from './stats/behaviours' import { withPinnedHeader } from './pinned-header-hoc'; class Realtime extends React.Component { - renderConversions() { - if (this.props.site.hasGoals) { - return ( -
- -
- ) - } - - return null - } - render() { const navClass = this.props.site.embedded ? 'relative' : 'sticky' @@ -48,8 +36,7 @@ class Realtime extends React.Component { - - { this.renderConversions() } + ) } diff --git a/assets/js/dashboard/stats/conversions/index.js b/assets/js/dashboard/stats/behaviours/conversions.js similarity index 93% rename from assets/js/dashboard/stats/conversions/index.js rename to assets/js/dashboard/stats/behaviours/conversions.js index 4b0976803..36a843b8b 100644 --- a/assets/js/dashboard/stats/conversions/index.js +++ b/assets/js/dashboard/stats/behaviours/conversions.js @@ -2,7 +2,6 @@ import React from 'react'; import { Link } from 'react-router-dom' import FlipMove from 'react-flip-move' - import Bar from '../bar' import PropBreakdown from './prop-breakdown' import numberFormatter from '../../util/number-formatter' @@ -100,7 +99,6 @@ export default class Conversions extends React.Component { } else if (this.state.goals) { return ( -

{this.props.title || "Goal Conversions"}

Goal
@@ -117,11 +115,19 @@ export default class Conversions extends React.Component { } } - render() { + renderConversions() { return ( - + { this.renderInner() } ) } + + render() { + return ( +
+ { this.renderConversions() } +
+ ) + } } diff --git a/assets/js/dashboard/stats/behaviours/funnel.js b/assets/js/dashboard/stats/behaviours/funnel.js new file mode 100644 index 000000000..4d0ad135b --- /dev/null +++ b/assets/js/dashboard/stats/behaviours/funnel.js @@ -0,0 +1,4 @@ +export default function Funnel(_props) { + // TODO + return null +} \ No newline at end of file diff --git a/assets/js/dashboard/stats/behaviours/index.js b/assets/js/dashboard/stats/behaviours/index.js new file mode 100644 index 000000000..d5eabf5fe --- /dev/null +++ b/assets/js/dashboard/stats/behaviours/index.js @@ -0,0 +1,250 @@ +import React, { Fragment, useState, useEffect } from 'react' +import { Menu, Transition } from '@headlessui/react' +import { ChevronDownIcon } from '@heroicons/react/20/solid' +import classNames from 'classnames' +import * as storage from '../../util/storage' + +import Conversions from './conversions' +import Funnel from './funnel' +import { FeatureSetupNotice } from '../../components/notice' + +const ACTIVE_CLASS = 'inline-block h-5 text-indigo-700 dark:text-indigo-500 font-bold active-prop-heading truncate text-left' +const DEFAULT_CLASS = 'hover:text-indigo-600 cursor-pointer truncate text-left' + +export const CONVERSIONS = 'conversions' +export const FUNNELS = 'funnels' +export const PROPS = 'props' + +export const sectionTitles = { + [CONVERSIONS]: 'Goal Conversions', + [FUNNELS]: 'Funnels', + [PROPS]: 'Custom Properties' +} + +export default function Behaviours(props) { + const site = props.site + const adminAccess = ['owner', 'admin', 'super_admin'].includes(props.currentUserRole) + const tabKey = `behavioursTab__${site.domain}` + const funnelKey = `behavioursTabFunnel__${site.domain}` + const [enabledModes, setEnabledModes] = useState(getEnabledModes()) + const [mode, setMode] = useState(defaultMode()) + + const [funnelNames, _setFunnelNames] = useState(site.funnels.map(({ name }) => name)) + const [selectedFunnel, setSelectedFunnel] = useState(storage.getItem(funnelKey)) + + useEffect(() => { + setMode(defaultMode()) + }, [enabledModes]) + + function disableMode(mode) { + setEnabledModes(enabledModes.filter((m) => { return m !== mode })) + } + + function setFunnel(selectedFunnel) { + return () => { + storage.setItem(tabKey, FUNNELS) + storage.setItem(funnelKey, selectedFunnel) + setMode(FUNNELS) + setSelectedFunnel(selectedFunnel) + } + } + + function hasFunnels() { + return site.funnels.length > 0 + } + + function tabFunnelPicker() { + return +
+ + Funnels + +
+ + + +
+ {funnelNames.map((funnelName) => { + return ( + + {({ active }) => ( + + {funnelName} + + )} + + ) + })} +
+
+
+
+ } + + function tabSwitcher(toMode, displayName) { + const className = classNames({ [ACTIVE_CLASS]: mode == toMode, [DEFAULT_CLASS]: mode !== toMode }) + const setTab = () => { + storage.setItem(tabKey, toMode) + setMode(toMode) + } + + return ( +
+ {displayName} +
+ ) + } + + function tabs() { + return ( +
+ {isEnabled(CONVERSIONS) && tabSwitcher(CONVERSIONS, 'Goals')} + {isEnabled(FUNNELS) && (hasFunnels() ? tabFunnelPicker() : tabSwitcher(FUNNELS, 'Funnels'))} + {isEnabled(PROPS) && tabSwitcher(PROPS, 'Properties')} +
+ ) + } + + function renderConversions() { + if (site.hasGoals) { return } + else if (adminAccess) { + return ( + + ) + } + else { return noDataYet() } + } + + function renderFunnels() { + if (selectedFunnel) { return } + else if (adminAccess) { + return ( + + ) + } + else { return noDataYet() } + } + + function renderProps() { + if (adminAccess) { + return ( + + ) + } else { return noDataYet() } + } + + function noDataYet() { + return ( +
+ No data yet +
+ ) + } + + function onHideAction(mode) { + return () => { disableMode(mode) } + } + + function renderContent() { + switch (mode) { + case CONVERSIONS: + return renderConversions() + case FUNNELS: + return renderFunnels() + case PROPS: + return renderProps() + } + } + + function defaultMode() { + if (enabledModes.length === 0) { return null } + + const storedMode = storage.getItem(tabKey) + if (storedMode && enabledModes.includes(storedMode)) { return storedMode } + + if (enabledModes.includes(CONVERSIONS)) { return CONVERSIONS } + if (enabledModes.includes(FUNNELS)) { return FUNNELS } + return PROPS + } + + function getEnabledModes() { + let enabledModes = [] + + if (site.conversionsEnabled) { + enabledModes.push(CONVERSIONS) + } + if (site.funnelsEnabled && !isRealtime() && site.flags.funnels) { + enabledModes.push(FUNNELS) + } + if (site.propsEnabled && !isRealtime() && site.flags.props) { + enabledModes.push(PROPS) + } + return enabledModes + } + + function isEnabled(mode) { + return enabledModes.includes(mode) + } + + function isRealtime() { + return props.query.period === 'realtime' + } + + if (mode) { + return ( +
+
+
+

+ {sectionTitles[mode] + (isRealtime() ? ' (last 30min)' : '')} +

+ {tabs()} +
+ {renderContent()} +
+
+ ) + } else { + return null + } +} diff --git a/assets/js/dashboard/stats/conversions/prop-breakdown.js b/assets/js/dashboard/stats/behaviours/prop-breakdown.js similarity index 100% rename from assets/js/dashboard/stats/conversions/prop-breakdown.js rename to assets/js/dashboard/stats/behaviours/prop-breakdown.js diff --git a/lib/plausible/site.ex b/lib/plausible/site.ex index 513a20fd8..d51d7e19d 100644 --- a/lib/plausible/site.ex +++ b/lib/plausible/site.ex @@ -18,6 +18,9 @@ defmodule Plausible.Site do field :stats_start_date, :date field :native_stats_start_at, :naive_datetime field :allowed_event_props, {:array, :string} + field :conversions_enabled, :boolean + field :props_enabled, :boolean + field :funnels_enabled, :boolean field :ingest_rate_limit_scale_seconds, :integer, default: 60 # default is set via changeset/2 @@ -166,6 +169,14 @@ defmodule Plausible.Site do change(site, allowed_event_props: list) end + def disable_feature(site, "conversions"), do: change(site, conversions_enabled: false) + def disable_feature(site, "funnels"), do: change(site, funnels_enabled: false) + def disable_feature(site, "props"), do: change(site, props_enabled: false) + + def enable_feature(site, "conversions"), do: change(site, conversions_enabled: true) + def enable_feature(site, "funnels"), do: change(site, funnels_enabled: true) + def enable_feature(site, "props"), do: change(site, props_enabled: true) + def remove_imported_data(site) do change(site, imported_data: nil) end diff --git a/lib/plausible_web/controllers/api/internal_controller.ex b/lib/plausible_web/controllers/api/internal_controller.ex index 40ea59b92..751fcb6fc 100644 --- a/lib/plausible_web/controllers/api/internal_controller.ex +++ b/lib/plausible_web/controllers/api/internal_controller.ex @@ -2,9 +2,11 @@ defmodule PlausibleWeb.Api.InternalController do use PlausibleWeb, :controller use Plausible.Repo alias Plausible.Stats.Clickhouse, as: Stats + alias Plausible.{Sites, Site, Auth} + alias Plausible.Auth.User def domain_status(conn, %{"domain" => domain}) do - site = Plausible.Sites.get_by_domain(domain) + site = Sites.get_by_domain(domain) if Stats.has_pageviews?(site) do json(conn, "READY") @@ -30,11 +32,28 @@ defmodule PlausibleWeb.Api.InternalController do end end + def disable_feature(conn, %{"domain" => domain, "feature" => feature}) do + with %User{id: user_id} <- conn.assigns[:current_user], + site <- Sites.get_by_domain(domain), + true <- Sites.has_admin_access?(user_id, site) || Auth.is_super_admin?(user_id) do + Site.disable_feature(site, feature) + |> Repo.update() + + json(conn, "ok") + else + _ -> + PlausibleWeb.Api.Helpers.unauthorized( + conn, + "You need to be logged in as the owner or admin account of this site" + ) + end + end + defp sites_for(user, params) do Repo.paginate( from( - s in Plausible.Site, - join: sm in Plausible.Site.Membership, + s in Site, + join: sm in Site.Membership, on: sm.site_id == s.id, where: sm.user_id == ^user.id, order_by: s.domain diff --git a/lib/plausible_web/controllers/site_controller.ex b/lib/plausible_web/controllers/site_controller.ex index 6de9010ec..2ee92f949 100644 --- a/lib/plausible_web/controllers/site_controller.ex +++ b/lib/plausible_web/controllers/site_controller.ex @@ -171,6 +171,34 @@ defmodule PlausibleWeb.SiteController do end end + def set_feature_status(conn, %{"action" => action, "feature" => feature}) do + site = conn.assigns[:site] + + report_title = + case feature do + "conversions" -> "Goals" + "funnels" -> "Funnels" + "props" -> "Properties" + end + + {change, flash_msg} = + case action do + "enable" -> + {Plausible.Site.enable_feature(site, feature), + "#{report_title} are now visible again on your dashboard"} + + "disable" -> + {Plausible.Site.disable_feature(site, feature), + "#{report_title} are now hidden from your dashboard"} + end + + Repo.update(change) + + conn + |> put_flash(:success, flash_msg) + |> redirect(to: Routes.site_path(conn, :settings_goals, conn.assigns[:site].domain)) + end + def settings(conn, %{"website" => website}) do redirect(conn, to: Routes.site_path(conn, :settings_general, website)) end diff --git a/lib/plausible_web/controllers/stats_controller.ex b/lib/plausible_web/controllers/stats_controller.ex index ad93738fb..b32d8c8d3 100644 --- a/lib/plausible_web/controllers/stats_controller.ex +++ b/lib/plausible_web/controllers/stats_controller.ex @@ -64,6 +64,7 @@ defmodule PlausibleWeb.StatsController do |> render("stats.html", site: site, has_goals: Plausible.Sites.has_goals?(site), + funnels: [], stats_start_date: stats_start_date, native_stats_start_date: NaiveDateTime.to_date(site.native_stats_start_at), title: "Plausible · " <> site.domain, @@ -291,6 +292,7 @@ defmodule PlausibleWeb.StatsController do |> render("stats.html", site: shared_link.site, has_goals: Sites.has_goals?(shared_link.site), + funnels: [], stats_start_date: shared_link.site.stats_start_date, native_stats_start_date: NaiveDateTime.to_date(shared_link.site.native_stats_start_at), title: "Plausible · " <> shared_link.site.domain, @@ -324,8 +326,11 @@ defmodule PlausibleWeb.StatsController do defp shared_link_cookie_name(slug), do: "shared-link-" <> slug - defp get_flags(_user) do - %{} + defp get_flags(user) do + %{ + funnels: FunWithFlags.enabled?(:funnels, for: user), + props: FunWithFlags.enabled?(:props, for: user) + } end defp is_dbip() do diff --git a/lib/plausible_web/router.ex b/lib/plausible_web/router.ex index cd93e5fde..7ef5d2352 100644 --- a/lib/plausible_web/router.ex +++ b/lib/plausible_web/router.ex @@ -117,6 +117,8 @@ defmodule PlausibleWeb.Router do post "/paddle/webhook", Api.PaddleController, :webhook get "/:domain/status", Api.InternalController, :domain_status + put "/:domain/disable-feature", Api.InternalController, :disable_feature + get "/sites", Api.InternalController, :sites end @@ -251,6 +253,7 @@ defmodule PlausibleWeb.Router do get "/:website/goals/new", SiteController, :new_goal post "/:website/goals", SiteController, :create_goal delete "/:website/goals/:id", SiteController, :delete_goal + put "/:website/settings/features/:action/:feature", SiteController, :set_feature_status put "/:website/settings", SiteController, :update_settings put "/:website/settings/google", SiteController, :update_google_auth delete "/:website/settings/google-search", SiteController, :delete_google_auth diff --git a/lib/plausible_web/templates/site/new_goal.html.eex b/lib/plausible_web/templates/site/new_goal.html.eex index 0417c5a30..0dae3ce57 100644 --- a/lib/plausible_web/templates/site/new_goal.html.eex +++ b/lib/plausible_web/templates/site/new_goal.html.eex @@ -7,6 +7,11 @@
+
+ Custom events are not tracked by default - you have to configure them on your site to be sent to Plausible. See examples and learn more in + our docs. +
+
<%= label f, :event_name, class: "block text-sm font-bold dark:text-gray-100" %> <%= text_input f, :event_name, class: "transition mt-3 bg-gray-100 dark:bg-gray-900 outline-none appearance-none border border-transparent rounded w-full p-2 text-gray-700 dark:text-gray-300 leading-normal focus:outline-none focus:bg-white dark:focus:bg-gray-800 focus:border-gray-300 dark:focus:border-gray-500", placeholder: "Signup" %> diff --git a/lib/plausible_web/templates/site/settings_goals.html.eex b/lib/plausible_web/templates/site/settings_goals.html.eex index 9235dd5d2..17630e120 100644 --- a/lib/plausible_web/templates/site/settings_goals.html.eex +++ b/lib/plausible_web/templates/site/settings_goals.html.eex @@ -2,11 +2,26 @@

Goals

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

+ <%= link(to: "https://plausible.io/docs/goal-conversions", target: "_blank", rel: "noreferrer") do %> <% end %> + +
+ <%= if @site.conversions_enabled do %> + <%= button(to: "/#{URI.encode_www_form(@site.domain)}/settings/features/disable/conversions", method: :put, class: "bg-indigo-600 relative inline-flex flex-shrink-0 h-6 w-11 border-2 border-transparent rounded-full cursor-pointer transition-colors ease-in-out duration-200 focus:outline-none focus:ring") do %> + + <% end %> + <% else %> + <%= button(to: "/#{URI.encode_www_form(@site.domain)}/settings/features/enable/conversions", method: :put, class: "bg-gray-200 dark:bg-gray-700 relative inline-flex flex-shrink-0 h-6 w-11 border-2 border-transparent rounded-full cursor-pointer transition-colors ease-in-out duration-200 focus:outline-none focus:ring") do %> + + <% end %> + <% end %> + Show goals in the dashboard +
+ <%= if @site.conversions_enabled do %> <%= if Enum.count(@goals) > 0 do %>
<%= for goal <- @goals do %> @@ -19,8 +34,9 @@ <% end %>
<% else %> -
No goals configured for this site yet
+
No goals configured for this site yet
<% end %> - <%= link("+ Add goal", to: "/#{URI.encode_www_form(@site.domain)}/goals/new", class: "button mt-6") %> + <%= link("+ Add goal", to: "/#{URI.encode_www_form(@site.domain)}/goals/new", class: "button mt-6") %> + <% end %>
diff --git a/lib/plausible_web/templates/stats/stats.html.eex b/lib/plausible_web/templates/stats/stats.html.eex index 2d8d4c65c..6f57a5cd7 100644 --- a/lib/plausible_web/templates/stats/stats.html.eex +++ b/lib/plausible_web/templates/stats/stats.html.eex @@ -18,6 +18,10 @@ data-domain="<%= @site.domain %>" data-offset="<%= Plausible.Site.tz_offset(@site) %>" data-has-goals="<%= @has_goals %>" + data-conversions-enabled="<%= @site.conversions_enabled %>" + data-funnels-enabled="<%= @site.funnels_enabled %>" + data-props-enabled="<%= @site.props_enabled %>" + data-funnels="<%= Jason.encode!(@funnels) %>" data-logged-in="<%= !!@conn.assigns[:current_user] %>" data-stats-begin="<%= @stats_start_date %>" data-native-stats-begin="<%= @native_stats_start_date %>" diff --git a/test/plausible_web/controllers/api/internal_controller_test.exs b/test/plausible_web/controllers/api/internal_controller_test.exs index 0c8b35721..c7ce0800e 100644 --- a/test/plausible_web/controllers/api/internal_controller_test.exs +++ b/test/plausible_web/controllers/api/internal_controller_test.exs @@ -45,4 +45,92 @@ defmodule PlausibleWeb.Api.InternalControllerTest do } end end + + describe "PUT /api/:domain/disable-feature" do + setup [:create_user, :log_in] + + test "when the logged-in user is an admin of the site", %{conn: conn, user: user} do + site = insert(:site) + insert(:site_membership, user: user, site: site, role: :admin) + + conn = put(conn, "/api/#{site.domain}/disable-feature", %{"feature" => "conversions"}) + + assert json_response(conn, 200) == "ok" + assert %{conversions_enabled: false} = Plausible.Sites.get_by_domain(site.domain) + end + + test "can disable conversions, funnels, and props with admin access", %{ + conn: conn, + user: user + } do + site = insert(:site) + insert(:site_membership, user: user, site: site, role: :admin) + + put(conn, "/api/#{site.domain}/disable-feature", %{"feature" => "conversions"}) + put(conn, "/api/#{site.domain}/disable-feature", %{"feature" => "funnels"}) + put(conn, "/api/#{site.domain}/disable-feature", %{"feature" => "props"}) + + assert %{conversions_enabled: false, funnels_enabled: false, props_enabled: false} = + Plausible.Sites.get_by_domain(site.domain) + end + + test "when the logged-in user is an owner of the site", %{conn: conn, user: user} do + site = insert(:site) + insert(:site_membership, user: user, site: site, role: :owner) + + conn = put(conn, "/api/#{site.domain}/disable-feature", %{"feature" => "conversions"}) + + assert json_response(conn, 200) == "ok" + assert %{conversions_enabled: false} = Plausible.Sites.get_by_domain(site.domain) + end + + test "when the logged-in user is an super-admin", %{conn: conn, user: user} do + site = insert(:site) + patch_env(:super_admin_user_ids, [user.id]) + + conn = put(conn, "/api/#{site.domain}/disable-feature", %{"feature" => "conversions"}) + + assert json_response(conn, 200) == "ok" + assert %{conversions_enabled: false} = Plausible.Sites.get_by_domain(site.domain) + end + + test "returns 401 when the logged-in user is a viewer of the site", %{conn: conn, user: user} do + site = insert(:site) + insert(:site_membership, user: user, site: site, role: :viewer) + + conn = put(conn, "/api/#{site.domain}/disable-feature", %{"feature" => "conversions"}) + + assert json_response(conn, 401) == %{ + "error" => "You need to be logged in as the owner or admin account of this site" + } + + assert %{conversions_enabled: true} = Plausible.Sites.get_by_domain(site.domain) + end + + test "returns 401 when the logged-in user doesn't have site access at all", %{conn: conn} do + site = insert(:site) + + conn = put(conn, "/api/#{site.domain}/disable-feature", %{"feature" => "conversions"}) + + assert json_response(conn, 401) == %{ + "error" => "You need to be logged in as the owner or admin account of this site" + } + + assert %{conversions_enabled: true} = Plausible.Sites.get_by_domain(site.domain) + end + end + + describe "PUT /api/:domain/disable-feature - user not logged in" do + test "returns 401 unauthorized", %{conn: conn} do + site = insert(:site) + + conn = put(conn, "/api/#{site.domain}/disable-feature", %{"feature" => "conversions"}) + + assert json_response(conn, 401) == %{ + "error" => "You need to be logged in as the owner or admin account of this site" + } + + assert %{conversions_enabled: true} = Plausible.Sites.get_by_domain(site.domain) + end + end end diff --git a/test/plausible_web/controllers/site_controller_test.exs b/test/plausible_web/controllers/site_controller_test.exs index 6c1e1338f..bd8075ade 100644 --- a/test/plausible_web/controllers/site_controller_test.exs +++ b/test/plausible_web/controllers/site_controller_test.exs @@ -739,6 +739,109 @@ defmodule PlausibleWeb.SiteControllerTest do end end + describe "PUT /:website/settings/features/:action/:feature" do + setup [:create_user, :log_in] + + test "can disable conversions, funnels, and props with admin access", %{ + conn: conn, + user: user + } do + site = insert(:site) + insert(:site_membership, user: user, site: site, role: :admin) + + conn1 = put(conn, "/#{site.domain}/settings/features/disable/conversions") + conn2 = put(conn, "/#{site.domain}/settings/features/disable/funnels") + conn3 = put(conn, "/#{site.domain}/settings/features/disable/props") + + assert %{conversions_enabled: false, funnels_enabled: false, props_enabled: false} = + Plausible.Sites.get_by_domain(site.domain) + + assert Phoenix.Flash.get(conn1.assigns.flash, :success) == + "Goals are now hidden from your dashboard" + + assert Phoenix.Flash.get(conn2.assigns.flash, :success) == + "Funnels are now hidden from your dashboard" + + assert Phoenix.Flash.get(conn3.assigns.flash, :success) == + "Properties are now hidden from your dashboard" + + assert redirected_to(conn1, 302) =~ "/#{site.domain}/settings/goals" + end + + test "can enable conversions, funnels, and props with admin access", %{ + conn: conn, + user: user + } do + site = + insert(:site, conversions_enabled: false, funnels_enabled: false, props_enabled: false) + + insert(:site_membership, user: user, site: site, role: :owner) + + conn1 = put(conn, "/#{site.domain}/settings/features/enable/conversions") + conn2 = put(conn, "/#{site.domain}/settings/features/enable/funnels") + conn3 = put(conn, "/#{site.domain}/settings/features/enable/props") + + assert %{conversions_enabled: true, funnels_enabled: true, props_enabled: true} = + Plausible.Sites.get_by_domain(site.domain) + + assert Phoenix.Flash.get(conn1.assigns.flash, :success) == + "Goals are now visible again on your dashboard" + + assert Phoenix.Flash.get(conn2.assigns.flash, :success) == + "Funnels are now visible again on your dashboard" + + assert Phoenix.Flash.get(conn3.assigns.flash, :success) == + "Properties are now visible again on your dashboard" + + assert redirected_to(conn3, 302) =~ "/#{site.domain}/settings/goals" + end + + test "can enable and disable with super-admin access", %{ + conn: conn, + user: user + } do + site = insert(:site) + patch_env(:super_admin_user_ids, [user.id]) + + conn1 = put(conn, "/#{site.domain}/settings/features/disable/funnels") + assert %{funnels_enabled: false} = Plausible.Sites.get_by_domain(site.domain) + + assert Phoenix.Flash.get(conn1.assigns.flash, :success) == + "Funnels are now hidden from your dashboard" + + conn2 = put(conn, "/#{site.domain}/settings/features/enable/funnels") + assert %{funnels_enabled: true} = Plausible.Sites.get_by_domain(site.domain) + + assert Phoenix.Flash.get(conn2.assigns.flash, :success) == + "Funnels are now visible again on your dashboard" + + assert redirected_to(conn1, 302) =~ "/#{site.domain}/settings/goals" + assert redirected_to(conn2, 302) =~ "/#{site.domain}/settings/goals" + end + + test "fails to set feature status with viewer access", %{ + conn: conn, + user: user + } do + site = insert(:site) + insert(:site_membership, user: user, site: site, role: :viewer) + + conn = put(conn, "/#{site.domain}/settings/features/disable/conversions") + + assert %{conversions_enabled: true} = Plausible.Sites.get_by_domain(site.domain) + assert conn.status == 404 + end + + test "fails to set feature status for a foreign site", %{conn: conn} do + site = insert(:site) + + conn = put(conn, "/#{site.domain}/settings/features/disable/conversions") + + assert %{conversions_enabled: true} = Plausible.Sites.get_by_domain(site.domain) + assert conn.status == 404 + end + end + describe "POST /sites/:website/weekly-report/enable" do setup [:create_user, :log_in, :create_site]