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
Implement Site Segments billing feature (#5129)
Artur Pata47b8553ca119
diff --git a/assets/js/dashboard/components/popover.tsx b/assets/js/dashboard/components/popover.tsxindex 5ceac56d88..0d9d859dff 100644--- a/assets/js/dashboard/components/popover.tsx+++ b/assets/js/dashboard/components/popover.tsx@@ -29,7 +29,7 @@ const toggleButton = {shadow:'bg-white dark:bg-gray-800 shadow text-gray-800 dark:text-gray-200 hover:bg-gray-200 dark:hover:bg-gray-900',ghost:- 'text-gray-500 hover:text-gray-800 hover:bg-gray-200 dark:hover:text-gray-200 dark:hover:bg-gray-900',+ 'text-gray-700 dark:text-gray-100 hover:bg-gray-200 dark:hover:bg-gray-900',truncatedText: 'truncate block font-medium'}}diff --git a/assets/js/dashboard/nav-menu/filter-menu.tsx b/assets/js/dashboard/nav-menu/filter-menu.tsxindex f3fd7455e1..f4580d4712 100644--- a/assets/js/dashboard/nav-menu/filter-menu.tsx+++ b/assets/js/dashboard/nav-menu/filter-menu.tsx@@ -7,7 +7,7 @@ import {} from '../util/filters'import { PlausibleSite, useSiteContext } from '../site-context'import { filterRoute } from '../router'-import { PlusIcon } from '@heroicons/react/20/solid'+import { MagnifyingGlassIcon } from '@heroicons/react/24/outline'import { Popover, Transition } from '@headlessui/react'import { popover } from '../components/popover'import classNames from 'classnames'@@ -59,11 +59,11 @@ const FilterMenuItems = ({ closeDropdown }: { closeDropdown: () => void }) => {ref={buttonRef}className={classNames(popover.toggleButton.classNames.rounded,- popover.toggleButton.classNames.shadow,+ popover.toggleButton.classNames.ghost,'justify-center gap-1 px-3')}>- <PlusIcon className="block h-4 w-4" />+ <MagnifyingGlassIcon className="block h-4 w-4" /><span className={popover.toggleButton.classNames.truncatedText}>Filter</span>diff --git a/assets/js/dashboard/segments/routeless-segment-modals.tsx b/assets/js/dashboard/segments/routeless-segment-modals.tsxindex 7b2ecd2cbe..7ffaad8cc6 100644--- a/assets/js/dashboard/segments/routeless-segment-modals.tsx+++ b/assets/js/dashboard/segments/routeless-segment-modals.tsx@@ -159,7 +159,10 @@ export const RoutelessSegmentModals = () => {siteSegmentsAvailable={site.siteSegmentsAvailable}segment={expandedSegment}namePlaceholder={getSegmentNamePlaceholder(query)}- onClose={() => setModal(null)}+ onClose={() => {+ setModal(null)+ patchSegment.reset()+ }}onSave={({ id, name, type }) =>patchSegment.mutate({id,@@ -182,7 +185,10 @@ export const RoutelessSegmentModals = () => {siteSegmentsAvailable={site.siteSegmentsAvailable}namePlaceholder={getSegmentNamePlaceholder(query)}segment={expandedSegment ?? undefined}- onClose={() => setModal(null)}+ onClose={() => {+ setModal(null)+ createSegment.reset()+ }}onSave={({ name, type }) =>createSegment.mutate({name,@@ -201,7 +207,10 @@ export const RoutelessSegmentModals = () => {{modal === 'delete' && expandedSegment && (<DeleteSegmentModalsegment={expandedSegment}- onClose={() => setModal(null)}+ onClose={() => {+ setModal(null)+ deleteSegment.reset()+ }}onSave={({ id }) => deleteSegment.mutate({ id })}status={deleteSegment.status}error={deleteSegment.error}diff --git a/lib/plausible/billing/feature.ex b/lib/plausible/billing/feature.exindex a34926273e..9606abe6f8 100644--- a/lib/plausible/billing/feature.ex+++ b/lib/plausible/billing/feature.ex@@ -75,7 +75,8 @@ defmodule Plausible.Billing.Feature doPlausible.Billing.Feature.StatsAPI,Plausible.Billing.Feature.Props,Plausible.Billing.Feature.Funnels,- Plausible.Billing.Feature.RevenueGoals+ Plausible.Billing.Feature.RevenueGoals,+ Plausible.Billing.Feature.SiteSegments]# Generate a union type for features@@ -196,6 +197,13 @@ defmodule Plausible.Billing.Feature.Props dotoggle_field: :props_enabledend+defmodule Plausible.Billing.Feature.SiteSegments do+ @moduledoc false+ use Plausible.Billing.Feature,+ name: :site_segments,+ display_name: "Shared Segments"+end+defmodule Plausible.Billing.Feature.StatsAPI douse Plausiblediff --git a/lib/plausible/crm_extensions.ex b/lib/plausible/crm_extensions.exindex c0aa28760e..7210afdadc 100644--- a/lib/plausible/crm_extensions.ex+++ b/lib/plausible/crm_extensions.ex@@ -78,7 +78,7 @@ defmodule Plausible.CrmExtensions doif (teamPicker) {teamPicker.style.display = "none";}- const teamIdField = document.querySelector("#enterprise_plan_team_id") ||+ const teamIdField = document.querySelector("#enterprise_plan_team_id") ||document.querySelector("#team_id")const teamIdLabel = document.querySelector("label[for=enterprise_plan_team_id]")const dataList = document.createElement("datalist")@@ -202,7 +202,7 @@ defmodule Plausible.CrmExtensions dofield.dispatchEvent(new Event("change"))});- ['stats_api', 'props', 'funnels', 'revenue_goals'].forEach(feature => {+ ['stats_api', 'props', 'funnels', 'revenue_goals', 'site_segments'].forEach(feature => {const checked = result.features.includes(feature)const field = document.querySelector(`input[type=checkbox][value=${feature}]`)if (field) {diff --git a/lib/plausible/segments/segments.ex b/lib/plausible/segments/segments.exindex 5588b94b1a..184e44c2be 100644--- a/lib/plausible/segments/segments.ex+++ b/lib/plausible/segments/segments.ex@@ -11,6 +11,11 @@ defmodule Plausible.Segments do@type error_not_enough_permissions() :: {:error, :not_enough_permissions}@type error_segment_not_found() :: {:error, :segment_not_found}+ @type error_segment_limit_reached() :: {:error, :segment_limit_reached}+ @type error_invalid_segment() :: {:error, {:invalid_segment, Keyword.t()}}+ @type unknown_error() :: {:error, any()}++ @max_segments 500@spec index(pos_integer() | nil, Plausible.Site.t(), atom()) ::{:ok, [Segment.t()]} | error_not_enough_permissions()@@ -73,6 +78,13 @@ defmodule Plausible.Segments doendend+ @spec insert_one(pos_integer(), Plausible.Site.t(), atom(), map()) ::+ {:ok, Segment.t()}+ | error_not_enough_permissions()+ | error_invalid_segment()+ | error_segment_limit_reached()+ | unknown_error()+def insert_one(user_id,%Plausible.Site{} = site,@@ -100,6 +112,12 @@ defmodule Plausible.Segments doendend+ @spec update_one(pos_integer(), Plausible.Site.t(), atom(), pos_integer(), map()) ::+ {:ok, Segment.t()}+ | error_not_enough_permissions()+ | error_invalid_segment()+ | unknown_error()+def update_one(user_id,%Plausible.Site{} = site,@@ -301,6 +319,9 @@ defmodule Plausible.Segments dodefp can_insert_one?(%Plausible.Site{} = site, site_role, params) docond do+ count_segments(site.id) >= @max_segments ->+ {:error, :segment_limit_reached}+params["type"] == "site" and site_role in roles_with_maybe_site_segments() andsite_segments_available?(site) ->:ok@@ -314,11 +335,18 @@ defmodule Plausible.Segments doendend+ defp count_segments(site_id) do+ from(segment in Segment,+ where: segment.site_id == ^site_id+ )+ |> Repo.aggregate(:count, :id)+ end+def roles_with_personal_segments(), do: [:viewer, :editor, :admin, :owner, :super_admin]def roles_with_maybe_site_segments(), do: [:editor, :admin, :owner, :super_admin]def site_segments_available?(%Plausible.Site{} = site),- do: Plausible.Billing.Feature.Props.check_availability(site.team) == :ok+ do: Plausible.Billing.Feature.SiteSegments.check_availability(site.team) == :ok@spec get_public_site_segments(pos_integer(), list(atom())) :: [Segment.t()]defp get_public_site_segments(site_id, fields) do@@ -375,7 +403,17 @@ defmodule Plausible.Segments doThis function enriches the segment with site, without actually querying the database for the site again.Needed for Plausible.Segments.Segment custom JSON serialization."""+ @spec enrich_with_site(Segment.t(), Plausible.Site.t()) :: Segment.t()def enrich_with_site(%Segment{} = segment, %Plausible.Site{} = site) doMap.put(segment, :site, site)end++ @spec get_site_segments_usage_query(list(pos_integer())) :: Ecto.Query.t()+ def get_site_segments_usage_query(site_ids) do+ from(segment in Segment,+ as: :segment,+ where: segment.type == :site,+ where: segment.site_id in ^site_ids+ )+ endenddiff --git a/lib/plausible/teams/billing.ex b/lib/plausible/teams/billing.exindex ba356601d4..49f9e25190 100644--- a/lib/plausible/teams/billing.ex+++ b/lib/plausible/teams/billing.ex@@ -510,7 +510,8 @@ defmodule Plausible.Teams.Billing do[{Feature.Props, props_usage_q},{Feature.Funnels, funnels_usage_q},- {Feature.RevenueGoals, revenue_goals_usage_q}+ {Feature.RevenueGoals, revenue_goals_usage_q},+ {Feature.SiteSegments, Plausible.Segments.get_site_segments_usage_query(site_ids)}]else[diff --git a/lib/plausible_web/controllers/api/internal/segments_controller.ex b/lib/plausible_web/controllers/api/internal/segments_controller.exindex 8d0fbf7230..25454e980d 100644--- a/lib/plausible_web/controllers/api/internal/segments_controller.ex+++ b/lib/plausible_web/controllers/api/internal/segments_controller.ex@@ -75,6 +75,9 @@ defmodule PlausibleWeb.Api.Internal.SegmentsController do{:error, :not_enough_permissions} ->H.not_enough_permissions(conn, "Not enough permissions to create segment")+ {:error, :segment_limit_reached} ->+ H.not_enough_permissions(conn, "Segment limit reached")+{:error, {:invalid_segment, errors}} when is_list(errors) ->conn|> put_status(400)diff --git a/lib/plausible_web/live/choose_plan.ex b/lib/plausible_web/live/choose_plan.exindex dde36eb2e9..a53e724f41 100644--- a/lib/plausible_web/live/choose_plan.ex+++ b/lib/plausible_web/live/choose_plan.ex@@ -82,8 +82,26 @@ defmodule PlausibleWeb.Live.ChoosePlan dobusiness_plan_to_render =assigns.selected_business_plan || List.last(assigns.available_plans.business)- growth_benefits = PlanBenefits.for_growth(growth_plan_to_render)- business_benefits = PlanBenefits.for_business(business_plan_to_render, growth_benefits)+ saved_segments_enabled? =+ FunWithFlags.enabled?(:saved_segments, for: assigns.current_user)++ growth_benefits =+ PlanBenefits.for_growth(growth_plan_to_render) +++ if(saved_segments_enabled?, do: ["Segments"], else: [])++ business_benefits =+ PlanBenefits.for_business(+ if(saved_segments_enabled?,+ do: business_plan_to_render,+ else:+ struct!(business_plan_to_render,+ features:+ business_plan_to_render.features -- [Plausible.Billing.Feature.SiteSegments]+ )+ ),+ growth_benefits+ )+enterprise_benefits = PlanBenefits.for_enterprise(business_benefits)assigns =diff --git a/lib/plausible_web/plugins/api/schemas/capabilities.ex b/lib/plausible_web/plugins/api/schemas/capabilities.exindex 3f9c75474b..e66ed83366 100644--- a/lib/plausible_web/plugins/api/schemas/capabilities.ex+++ b/lib/plausible_web/plugins/api/schemas/capabilities.ex@@ -32,7 +32,8 @@ defmodule PlausibleWeb.Plugins.API.Schemas.Capabilities doGoals: true,Props: false,RevenueGoals: false,- StatsAPI: false+ StatsAPI: false,+ SiteSegments: false}}})diff --git a/lib/plausible_web/templates/stats/stats.html.heex b/lib/plausible_web/templates/stats/stats.html.heexindex 5cb64d4c73..abd70d64da 100644--- a/lib/plausible_web/templates/stats/stats.html.heex+++ b/lib/plausible_web/templates/stats/stats.html.heex@@ -28,7 +28,7 @@to_string(Plausible.Billing.Feature.Props.check_availability(@site.team) == :ok)}data-site-segments-available={- to_string(Plausible.Billing.Feature.Props.check_availability(@site.team) == :ok)+ to_string(Plausible.Billing.Feature.SiteSegments.check_availability(@site.team) == :ok)}data-revenue-goals={Jason.encode!(@revenue_goals)}data-funnels={Jason.encode!(@funnels)}diff --git a/priv/plans_v3.json b/priv/plans_v3.jsonindex e0d2485732..8e5618aea6 100644--- a/priv/plans_v3.json+++ b/priv/plans_v3.json@@ -87,7 +87,7 @@"yearly_product_id":"857482","site_limit":50,"team_member_limit":"unlimited",- "features":["goals","props","revenue_goals","funnels","stats_api"]+ "features":["goals","props","revenue_goals","funnels","stats_api","site_segments"]},{"kind":"business",@@ -97,7 +97,7 @@"yearly_product_id":"857484","site_limit":50,"team_member_limit":"unlimited",- "features":["goals","props","revenue_goals","funnels","stats_api"]+ "features":["goals","props","revenue_goals","funnels","stats_api","site_segments"]},{"kind":"business",@@ -107,7 +107,7 @@"yearly_product_id":"857487","site_limit":50,"team_member_limit":"unlimited",- "features":["goals","props","revenue_goals","funnels","stats_api"]+ "features":["goals","props","revenue_goals","funnels","stats_api","site_segments"]},{"kind":"business",@@ -117,7 +117,7 @@"yearly_product_id":"857491","site_limit":50,"team_member_limit":"unlimited",- "features":["goals","props","revenue_goals","funnels","stats_api"]+ "features":["goals","props","revenue_goals","funnels","stats_api","site_segments"]},{"kind":"business",@@ -127,7 +127,7 @@"yearly_product_id":"857494","site_limit":50,"team_member_limit":"unlimited",- "features":["goals","props","revenue_goals","funnels","stats_api"]+ "features":["goals","props","revenue_goals","funnels","stats_api","site_segments"]},{"kind":"business",@@ -137,7 +137,7 @@"yearly_product_id":"857496","site_limit":50,"team_member_limit":"unlimited",- "features":["goals","props","revenue_goals","funnels","stats_api"]+ "features":["goals","props","revenue_goals","funnels","stats_api","site_segments"]},{"kind":"business",@@ -147,7 +147,7 @@"yearly_product_id":"857500","site_limit":50,"team_member_limit":"unlimited",- "features":["goals","props","revenue_goals","funnels","stats_api"]+ "features":["goals","props","revenue_goals","funnels","stats_api","site_segments"]},{"kind":"business",@@ -157,6 +157,6 @@"yearly_product_id":"857502","site_limit":50,"team_member_limit":"unlimited",- "features":["goals","props","revenue_goals","funnels","stats_api"]+ "features":["goals","props","revenue_goals","funnels","stats_api","site_segments"]}]diff --git a/priv/plans_v4.json b/priv/plans_v4.jsonindex c40343a230..ce6acde7ef 100644--- a/priv/plans_v4.json+++ b/priv/plans_v4.json@@ -95,7 +95,7 @@"yearly_product_id":"857087","site_limit":50,"team_member_limit":10,- "features":["goals","props","revenue_goals","funnels","stats_api"],+ "features":["goals","props","revenue_goals","funnels","stats_api","site_segments"],"data_retention_in_years": 5},{@@ -106,7 +106,7 @@"yearly_product_id":"857088","site_limit":50,"team_member_limit":10,- "features":["goals","props","revenue_goals","funnels","stats_api"],+ "features":["goals","props","revenue_goals","funnels","stats_api","site_segments"],"data_retention_in_years": 5},{@@ -117,7 +117,7 @@"yearly_product_id":"857089","site_limit":50,"team_member_limit":10,- "features":["goals","props","revenue_goals","funnels","stats_api"],+ "features":["goals","props","revenue_goals","funnels","stats_api","site_segments"],"data_retention_in_years": 5},{@@ -128,7 +128,7 @@"yearly_product_id":"857090","site_limit":50,"team_member_limit":10,- "features":["goals","props","revenue_goals","funnels","stats_api"],+ "features":["goals","props","revenue_goals","funnels","stats_api","site_segments"],"data_retention_in_years": 5},{@@ -139,7 +139,7 @@"yearly_product_id":"857091","site_limit":50,"team_member_limit":10,- "features":["goals","props","revenue_goals","funnels","stats_api"],+ "features":["goals","props","revenue_goals","funnels","stats_api","site_segments"],"data_retention_in_years": 5},{@@ -150,7 +150,7 @@"yearly_product_id":"857092","site_limit":50,"team_member_limit":10,- "features":["goals","props","revenue_goals","funnels","stats_api"],+ "features":["goals","props","revenue_goals","funnels","stats_api","site_segments"],"data_retention_in_years": 5},{@@ -161,7 +161,7 @@"yearly_product_id":"857093","site_limit":50,"team_member_limit":10,- "features":["goals","props","revenue_goals","funnels","stats_api"],+ "features":["goals","props","revenue_goals","funnels","stats_api","site_segments"],"data_retention_in_years": 5},{@@ -172,7 +172,7 @@"yearly_product_id":"857094","site_limit":50,"team_member_limit":10,- "features":["goals","props","revenue_goals","funnels","stats_api"],+ "features":["goals","props","revenue_goals","funnels","stats_api","site_segments"],"data_retention_in_years": 5}]diff --git a/priv/sandbox_plans.json b/priv/sandbox_plans.jsonindex b25134a3f0..de1aa0bc26 100644--- a/priv/sandbox_plans.json+++ b/priv/sandbox_plans.json@@ -92,7 +92,7 @@"yearly_product_id":"63867","site_limit":50,"team_member_limit":"unlimited",- "features":["goals","props", "revenue_goals", "funnels","stats_api"]+ "features":["goals","props","revenue_goals","funnels","stats_api","site_segments"]},{"kind":"business",@@ -102,7 +102,7 @@"yearly_product_id":"63868","site_limit":50,"team_member_limit":"unlimited",- "features":["goals","props", "revenue_goals", "funnels","stats_api"]+ "features":["goals","props","revenue_goals","funnels","stats_api","site_segments"]},{"kind":"business",@@ -112,7 +112,7 @@"yearly_product_id":"63869","site_limit":50,"team_member_limit":"unlimited",- "features":["goals","props", "revenue_goals", "funnels","stats_api"]+ "features":["goals","props","revenue_goals","funnels","stats_api","site_segments"]},{"kind":"business",@@ -122,7 +122,7 @@"yearly_product_id":"63870","site_limit":50,"team_member_limit":10,- "features":["goals","props", "revenue_goals", "funnels","stats_api"],+ "features":["goals","props","revenue_goals","funnels","stats_api","site_segments"],"data_retention_in_years": 5},{@@ -133,7 +133,7 @@"yearly_product_id":"63871","site_limit":50,"team_member_limit":10,- "features":["goals","props", "revenue_goals", "funnels","stats_api"],+ "features":["goals","props","revenue_goals","funnels","stats_api","site_segments"],"data_retention_in_years": 5},{@@ -144,7 +144,7 @@"yearly_product_id":"63872","site_limit":50,"team_member_limit":10,- "features":["goals","props", "revenue_goals", "funnels","stats_api"],+ "features":["goals","props","revenue_goals","funnels","stats_api","site_segments"],"data_retention_in_years": 5},{@@ -155,7 +155,7 @@"yearly_product_id":"63873","site_limit":50,"team_member_limit":10,- "features":["goals","props", "revenue_goals", "funnels","stats_api"],+ "features":["goals","props","revenue_goals","funnels","stats_api","site_segments"],"data_retention_in_years": 5},{@@ -166,7 +166,7 @@"yearly_product_id":"63874","site_limit":50,"team_member_limit":10,- "features":["goals","props", "revenue_goals", "funnels","stats_api"],+ "features":["goals","props","revenue_goals","funnels","stats_api","site_segments"],"data_retention_in_years": 5}]diff --git a/test/plausible_web/controllers/api/internal_controller/segments_controller_test.exs b/test/plausible_web/controllers/api/internal_controller/segments_controller_test.exsindex 0e849e8485..f76dad4ada 100644--- a/test/plausible_web/controllers/api/internal_controller/segments_controller_test.exs+++ b/test/plausible_web/controllers/api/internal_controller/segments_controller_test.exs@@ -357,6 +357,27 @@ defmodule PlausibleWeb.Api.Internal.SegmentsControllerTest do}end+ test "returns error when segment limit is reached", %{conn: conn, user: user, site: site} do+ insert_list(500, :segment, site: site, owner: user, type: :personal, name: "a segment")++ conn =+ post(conn, "/api/#{site.domain}/segments", %{+ "type" => "personal",+ "segment_data" => %{"filters" => [["is", "visit:entry_page", ["/blog"]]]},+ "name" => "any name"+ })++ assert json_response(conn, 403) == %{+ "error" => "Segment limit reached"+ }++ assert Repo.aggregate(+ from(segment in Plausible.Segments.Segment, where: segment.site_id == ^site.id),+ :count,+ :id+ ) == 500+ end+for %{role: role, type: type} <- [%{role: :viewer, type: :personal},%{role: :editor, type: :personal},diff --git a/test/plausible_web/plugins/api/controllers/capabilities_test.exs b/test/plausible_web/plugins/api/controllers/capabilities_test.exsindex dc32d73d03..bba3247fa7 100644--- a/test/plausible_web/plugins/api/controllers/capabilities_test.exs+++ b/test/plausible_web/plugins/api/controllers/capabilities_test.exs@@ -29,7 +29,8 @@ defmodule PlausibleWeb.Plugins.API.Controllers.CapabilitiesTest do"Goals" => false,"Props" => false,"RevenueGoals" => false,- "StatsAPI" => false+ "StatsAPI" => false,+ "SiteSegments" => false}}@@ -53,7 +54,8 @@ defmodule PlausibleWeb.Plugins.API.Controllers.CapabilitiesTest do"Goals" => false,"Props" => false,"RevenueGoals" => false,- "StatsAPI" => false+ "StatsAPI" => false,+ "SiteSegments" => false}}@@ -79,7 +81,8 @@ defmodule PlausibleWeb.Plugins.API.Controllers.CapabilitiesTest do"Goals" => true,"Props" => true,"RevenueGoals" => true,- "StatsAPI" => true+ "StatsAPI" => true,+ "SiteSegments" => true}}@@ -107,7 +110,8 @@ defmodule PlausibleWeb.Plugins.API.Controllers.CapabilitiesTest do"Goals" => true,"Props" => false,"RevenueGoals" => false,- "StatsAPI" => false+ "StatsAPI" => false,+ "SiteSegments" => false}}