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
Display premium features tabs on the dashboard (#3646)
Vinicius Brasil9e5d63ed96a7
diff --git a/assets/js/dashboard.js b/assets/js/dashboard.jsindex e4e2fbcc75..c733c0905c 100644--- a/assets/js/dashboard.js+++ b/assets/js/dashboard.js@@ -16,10 +16,12 @@ 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',hasProps: container.dataset.hasProps === 'true',+ funnelsAvailable: container.dataset.funnelsAvailable === 'true',+ propsAvailable: container.dataset.propsAvailable === 'true',+ conversionsOptedOut: container.dataset.conversionsOptedOut === 'true',+ funnelsOptedOut: container.dataset.funnelsOptedOut === 'true',+ propsOptedOut: container.dataset.propsOptedOut === 'true',funnels: JSON.parse(container.dataset.funnels),statsBegin: container.dataset.statsBegin,nativeStatsBegin: container.dataset.nativeStatsBegin,diff --git a/assets/js/dashboard/components/notice.js b/assets/js/dashboard/components/notice.jsindex fd2d9876a6..656c7abbea 100644--- a/assets/js/dashboard/components/notice.js+++ b/assets/js/dashboard/components/notice.js@@ -2,7 +2,7 @@ import React from "react"import { sectionTitles } from "../stats/behaviours"import * as api from '../api'-export function FeatureSetupNotice({ site, feature, shortFeatureName, title, info, settingsLink, onHideAction }) {+export function FeatureSetupNotice({ site, feature, title, info, callToAction, onHideAction }) {const sectionTitle = sectionTitles[feature]const requestHideSection = () => {@@ -14,10 +14,10 @@ export function FeatureSetupNotice({ site, feature, shortFeatureName, title, inf}}- function setupButton() {+ function renderCallToAction() {return (- <a href={settingsLink} className="ml-2 sm:ml-4 button px-2 sm:px-4">- <p className="flex flex-col justify-center text-xs sm:text-sm">Set up {shortFeatureName}</p>+ <a href={callToAction.link} className="ml-2 sm:ml-4 button px-2 sm:px-4">+ <p className="flex flex-col justify-center text-xs sm:text-sm">{callToAction.action}</p><svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" strokeWidth={1.5} stroke="currentColor" className="ml-2 w-5 h-5"><path strokeLinecap="round" strokeLinejoin="round" d="M4.5 12h15m0 0l-6.75-6.75M19.5 12l-6.75 6.75" /></svg>@@ -25,7 +25,7 @@ export function FeatureSetupNotice({ site, feature, shortFeatureName, title, inf)}- function hideButton() {+ function renderHideButton() {return (<buttononClick={requestHideSection}@@ -47,8 +47,8 @@ export function FeatureSetupNotice({ site, feature, shortFeatureName, title, inf</div><div className="text-xs sm:text-sm flex my-6 justify-center">- {hideButton()}- {setupButton()}+ {renderHideButton()}+ {renderCallToAction()}</div></div></div>diff --git a/assets/js/dashboard/stats/behaviours/index.js b/assets/js/dashboard/stats/behaviours/index.jsindex 9f574c6ae9..8c26ed5a6b 100644--- a/assets/js/dashboard/stats/behaviours/index.js+++ b/assets/js/dashboard/stats/behaviours/index.js@@ -43,7 +43,7 @@ export default function Behaviours(props) {const [mode, setMode] = useState(defaultMode())const [funnelNames, _setFunnelNames] = useState(site.funnels.map(({ name }) => name))- const [selectedFunnel, setSelectedFunnel] = useState(storage.getItem(funnelKey))+ const [selectedFunnel, setSelectedFunnel] = useState(defaultSelectedFunnel())const [showingPropsForGoalFilter, setShowingPropsForGoalFilter] = useState(false)@@ -83,8 +83,22 @@ export default function Behaviours(props) {}}+ function defaultSelectedFunnel() {+ const stored = storage.getItem(funnelKey)+ const storedExists = stored && site.funnels.some((f) => f.name === stored)++ if (storedExists) {+ return stored+ } else if (site.funnels.length > 0) {+ const firstAvailable = site.funnels[0].name++ storage.setItem(funnelKey, firstAvailable)+ return firstAvailable+ }+ }+function hasFunnels() {- return site.funnels.length > 0+ return site.funnels.length > 0 && site.funnelsAvailable}function tabFunnelPicker() {@@ -164,10 +178,12 @@ export default function Behaviours(props) {<FeatureSetupNoticesite={site}feature={CONVERSIONS}- shortFeatureName={'goals'}title={'Measure how often visitors complete specific actions'}info={'Goals allow you to track registrations, button clicks, form completions, external link clicks, file downloads, 404 error pages and more.'}- settingsLink={`/${encodeURIComponent(site.domain)}/settings/goals`}+ callToAction={{+ action: "Set up goals",+ link: `/${encodeURIComponent(site.domain)}/settings/goals`+ }}onHideAction={onHideAction(CONVERSIONS)}/>)@@ -179,18 +195,25 @@ export default function Behaviours(props) {if (Funnel === null) {return featureUnavailable()}- else if (Funnel && selectedFunnel) {+ else if (Funnel && selectedFunnel && site.funnelsAvailable) {return <Funnel site={site} query={query} funnelName={selectedFunnel} />}else if (Funnel && adminAccess) {+ let callToAction++ if (site.funnelsAvailable) {+ callToAction = {action: 'Set up funnels', link: `/${encodeURIComponent(site.domain)}/settings/funnels`}+ } else {+ callToAction = {action: 'Upgrade', link: '/billing/choose-plan'}+ }+return (<FeatureSetupNoticesite={site}feature={FUNNELS}- shortFeatureName={'funnels'}title={'Follow the visitor journey from entry to conversion'}info={'Funnels allow you to analyze the user flow through your website, uncover possible issues, optimize your site and increase the conversion rate.'}- settingsLink={`/${encodeURIComponent(site.domain)}/settings/funnels`}+ callToAction={callToAction}onHideAction={onHideAction(FUNNELS)}/>)@@ -199,17 +222,24 @@ export default function Behaviours(props) {}function renderProps() {- if (site.hasProps) {+ if (site.hasProps && site.propsAvailable) {return <Properties site={site} query={query} />} else if (adminAccess) {+ let callToAction++ if (site.propsAvailable) {+ callToAction = {action: 'Set up props', link: `/${encodeURIComponent(site.domain)}/settings/properties`}+ } else {+ callToAction = {action: 'Upgrade', link: '/billing/choose-plan'}+ }+return (<FeatureSetupNoticesite={site}feature={PROPS}- shortFeatureName={'props'}- title={'No custom properties found'}+ title={'Send custom data to create your own metrics'}info={'You can attach custom properties when sending a pageview or event. This allows you to create custom metrics and analyze stats we don\'t track automatically.'}- settingsLink={`/${encodeURIComponent(site.domain)}/settings/properties`}+ callToAction={callToAction}onHideAction={onHideAction(PROPS)}/>)@@ -261,15 +291,20 @@ export default function Behaviours(props) {function getEnabledModes() {let enabledModes = []- if (site.conversionsEnabled) {- enabledModes.push(CONVERSIONS)- }- if (site.propsEnabled) {- enabledModes.push(PROPS)- }- if (site.funnelsEnabled && !isRealtime()) {- enabledModes.push(FUNNELS)+ for (const feature of Object.keys(sectionTitles)) {+ const isOptedOut = site[feature + 'OptedOut']+ const isAvailable = site[feature + 'Available'] !== false++ // If the feature is not supported by the site owner's subscription,+ // it only makes sense to display the feature tab to the owner itself+ // as only they can upgrade to make the feature available.+ const callToActionIsMissing = !isAvailable && currentUserRole !== 'owner'++ if (!isOptedOut && !callToActionIsMissing) {+ enabledModes.push(feature)+ }}+return enabledModes}diff --git a/lib/plausible/billing/feature.ex b/lib/plausible/billing/feature.exindex d3dcd7f2f2..420084deb8 100644--- a/lib/plausible/billing/feature.ex+++ b/lib/plausible/billing/feature.ex@@ -56,6 +56,13 @@ defmodule Plausible.Billing.Feature do"""@callback enabled?(Plausible.Site.t()) :: boolean()+ @doc """+ Returns whether the site explicitly opted out of the feature. This function+ is different from enabled/1, because enabled/1 returns false when the site+ owner does not have access to the feature.+ """+ @callback opted_out?(Plausible.Site.t()) :: boolean()+@doc """Checks whether the site owner or the user plan includes the given feature."""@@ -101,12 +108,12 @@ defmodule Plausible.Billing.Feature do@impl truedef enabled?(%Plausible.Site{} = site) dosite = Plausible.Repo.preload(site, :owner)+ check_availability(site.owner) == :ok && !opted_out?(site)+ end- cond do- check_availability(site.owner) !== :ok -> false- is_nil(toggle_field()) -> true- true -> Map.fetch!(site, toggle_field())- end+ @impl true+ def opted_out?(%Plausible.Site{} = site) do+ if is_nil(toggle_field()), do: false, else: !Map.fetch!(site, toggle_field())end@impl true@@ -120,18 +127,23 @@ defmodule Plausible.Billing.Feature do@impl truedef toggle(%Plausible.Site{} = site, opts \\ []) do- with key when not is_nil(key) <- toggle_field(),- site <- Plausible.Repo.preload(site, :owner),- :ok <- check_availability(site.owner) do- override = Keyword.get(opts, :override)- toggle = if is_boolean(override), do: override, else: !Map.fetch!(site, toggle_field())-- site- |> Ecto.Changeset.change(%{toggle_field() => toggle})- |> Plausible.Repo.update()- else- nil = _feature_not_togglable -> :ok- {:error, :upgrade_required} -> {:error, :upgrade_required}+ if toggle_field(), do: do_toggle(site, opts), else: :ok+ end++ defp do_toggle(%Plausible.Site{} = site, opts) do+ site = Plausible.Repo.preload(site, :owner)+ override = Keyword.get(opts, :override)+ toggle = if is_boolean(override), do: override, else: !Map.fetch!(site, toggle_field())+ availability = if toggle, do: check_availability(site.owner), else: :ok++ case availability do+ :ok ->+ site+ |> Ecto.Changeset.change(%{toggle_field() => toggle})+ |> Plausible.Repo.update()++ error ->+ errorendenddiff --git a/lib/plausible_web/controllers/stats_controller.ex b/lib/plausible_web/controllers/stats_controller.exindex e0e5fda39b..284de41d41 100644--- a/lib/plausible_web/controllers/stats_controller.ex+++ b/lib/plausible_web/controllers/stats_controller.ex@@ -308,6 +308,8 @@ defmodule PlausibleWeb.StatsController dodefp render_shared_link(conn, shared_link) docond do!shared_link.site.locked ->+ shared_link = Plausible.Repo.preload(shared_link, site: :owner)+conn|> put_resp_header("x-robots-tag", "noindex, nofollow")|> delete_resp_header("x-frame-options")diff --git a/lib/plausible_web/templates/stats/stats.html.eex b/lib/plausible_web/templates/stats/stats.html.eexindex 8e2927311a..0a7f8b8eff 100644--- a/lib/plausible_web/templates/stats/stats.html.eex+++ b/lib/plausible_web/templates/stats/stats.html.eex@@ -18,9 +18,11 @@data-domain="<%= @site.domain %>"data-offset="<%= Plausible.Site.tz_offset(@site) %>"data-has-goals="<%= @has_goals %>"- data-conversions-enabled="<%= Plausible.Billing.Feature.Goals.enabled?(@site) %>"- data-funnels-enabled="<%= Plausible.Billing.Feature.Funnels.enabled?(@site) %>"- data-props-enabled="<%= Plausible.Billing.Feature.Props.enabled?(@site) %>"+ data-conversions-opted-out="<%= Plausible.Billing.Feature.Goals.opted_out?(@site) %>"+ data-funnels-opted-out="<%= Plausible.Billing.Feature.Funnels.opted_out?(@site) %>"+ data-props-opted-out="<%= Plausible.Billing.Feature.Props.opted_out?(@site) %>"+ data-funnels-available="<%= Plausible.Billing.Feature.Funnels.check_availability(@site.owner) == :ok %>"+ data-props-available="<%= Plausible.Billing.Feature.Props.check_availability(@site.owner) == :ok %>"data-funnels="<%= Jason.encode!(@funnels) %>"data-has-props="<%= @has_props %>"data-logged-in="<%= [email protected][:current_user] %>"diff --git a/test/plausible/billing/feature_test.exs b/test/plausible/billing/feature_test.exsindex 845a0b7f46..6de9fc11d7 100644--- a/test/plausible/billing/feature_test.exs+++ b/test/plausible/billing/feature_test.exs@@ -112,10 +112,12 @@ defmodule Plausible.Billing.FeatureTest do{:ok, site} = unquote(mod).toggle(site)assert Map.get(site, unquote(property))assert unquote(mod).enabled?(site)+ refute unquote(mod).opted_out?(site){:ok, site} = unquote(mod).toggle(site)refute Map.get(site, unquote(property))refute unquote(mod).enabled?(site)+ assert unquote(mod).opted_out?(site)endtest "#{mod}.toggle/2 accepts an override option" do@@ -126,12 +128,19 @@ defmodule Plausible.Billing.FeatureTest dorefute unquote(mod).enabled?(site)end- test "#{mod}.toggle/2 errors when site owner does not have access to the feature" do+ test "#{mod}.toggle/2 errors when enabling a feature the site owner does not have access to the feature" douser = insert(:user, subscription: build(:growth_subscription))site = insert(:site, [{:members, [user]}, {unquote(property), false}]){:error, :upgrade_required} = unquote(mod).toggle(site)refute unquote(mod).enabled?(site)end++ test "#{mod}.toggle/2 does not error when disabling a feature the site owner does not have access to" do+ user = insert(:user, subscription: build(:growth_subscription))+ site = insert(:site, [{:members, [user]}, {unquote(property), true}])+ {:ok, site} = unquote(mod).toggle(site)+ assert unquote(mod).opted_out?(site)+ endendtest "Plausible.Billing.Feature.Goals.toggle/2 toggles conversions_enabled on and off" do@@ -140,10 +149,12 @@ defmodule Plausible.Billing.FeatureTest do{:ok, site} = Plausible.Billing.Feature.Goals.toggle(site)assert Map.get(site, :conversions_enabled)assert Plausible.Billing.Feature.Goals.enabled?(site)+ refute Plausible.Billing.Feature.Goals.opted_out?(site){:ok, site} = Plausible.Billing.Feature.Goals.toggle(site)refute Map.get(site, :conversions_enabled)refute Plausible.Billing.Feature.Goals.enabled?(site)+ assert Plausible.Billing.Feature.Goals.opted_out?(site)endfor mod <- [Plausible.Billing.Feature.Funnels, Plausible.Billing.Feature.Props] do@@ -152,5 +163,11 @@ defmodule Plausible.Billing.FeatureTest dosite = insert(:site, [{:members, [user]}, {unquote(mod).toggle_field(), true}])refute unquote(mod).enabled?(site)end++ test "#{mod}.opted_out?/1 returns false when feature toggle is enabled even when user does not have access to the feature" do+ user = insert(:user, subscription: build(:growth_subscription))+ site = insert(:site, [{:members, [user]}, {unquote(mod).toggle_field(), true}])+ refute unquote(mod).opted_out?(site)+ endendend