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
feat: CRM page listing trial prospects by MRR potential (#6589)
Uku Tahtb4f640192720
diff --git a/extra/lib/plausible/customer_support/trial_prospects.ex b/extra/lib/plausible/customer_support/trial_prospects.exindex cef3ad79ab..998ed274a1 100644--- a/extra/lib/plausible/customer_support/trial_prospects.ex+++ b/extra/lib/plausible/customer_support/trial_prospects.ex@@ -1,9 +1,15 @@defmodule Plausible.CustomerSupport.TrialProspects do@moduledoc """- Pure scoring logic for ranking trial teams by revenue potential. Turns a- team's partial traffic sample and premium-feature usage into an estimated MRR.+ Scoring logic for ranking trial teams by revenue potential. Turns a team's+ partial traffic sample and premium-feature usage into an estimated MRR, and+ serves the ranked listing back to the customer support UI."""+ import Ecto.Query++ alias Plausible.CustomerSupport.TrialProspect+ alias Plausible.Repo+# Static reference pricing (EUR/mo) + pageview ladder. Hand-maintained; keep in sync when public pricing changes.@pricing_path Application.app_dir(:plausible, ["priv", "trial_prospect_pricing.json"])@external_resource @pricing_path@@ -37,6 +43,82 @@ defmodule Plausible.CustomerSupport.TrialProspects do@kind_rank %{starter: 0, growth: 1, business: 2}+ @page_size 100+ @sortable_columns ~w(mrr trial_start)+ @max_expired_days 30++ @spec sortable_columns() :: [String.t()]+ def sortable_columns, do: @sortable_columns++ @doc """+ Teams worth scoring and showing: on a trial (or expired within the last+ #{@max_expired_days} days) and not yet subscribed.+ """+ @spec population_query() :: Ecto.Query.t()+ def population_query do+ cutoff = Date.add(Date.utc_today(), -@max_expired_days)++ from(t in Plausible.Teams.Team,+ as: :team,+ left_join: s in assoc(t, :subscription),+ where: not is_nil(t.trial_expiry_date),+ where: is_nil(s.id),+ where: t.trial_expiry_date >= ^cutoff+ )+ end++ @spec list(String.t(), :asc | :desc, pos_integer()) :: %{+ prospects: [TrialProspect.t()],+ page_number: pos_integer(),+ total_pages: pos_integer(),+ total_entries: non_neg_integer()+ }+ def list(sort_by, sort_direction, page) do+ base = listing_query()++ total_entries = Repo.aggregate(base, :count)+ total_pages = max(1, ceil(total_entries / @page_size))+ page_number = min(page, total_pages)++ prospects =+ base+ |> preload_team()+ |> order_prospects(sort_by, sort_direction)+ |> limit(^@page_size)+ |> offset(^((page_number - 1) * @page_size))+ |> Repo.all()++ %{+ prospects: prospects,+ page_number: page_number,+ total_pages: total_pages,+ total_entries: total_entries+ }+ end++ defp listing_query do+ from(p in TrialProspect,+ join: t in subquery(population_query()),+ as: :team,+ on: t.id == p.team_id+ )+ end++ defp preload_team(q) do+ owners = from(u in Plausible.Auth.User, select: struct(u, [:id, :email]))++ from([team: t] in q, preload: [team: {t, owners: ^owners}])+ end++ defp order_prospects(q, "trial_start", direction) do+ order_by(q, [team: t], [{^direction, t.inserted_at}])+ end++ # Over-the-top-tier (Custom/Enterprise) prospects rank first+ defp order_prospects(q, "mrr", direction) do+ order_by(q, [p], [{^direction, p.over_top_tier}, {^direction, p.estimated_mrr}])+ end+@doc """Combines feature usage, site/member counts + a monthly estimate into thepersisted scoring fields: `kind`, `forced_by`, `pageview_limit`,diff --git a/extra/lib/plausible/workers/score_trial_prospects.ex b/extra/lib/plausible/workers/score_trial_prospects.exindex ca2ef831ca..0a47f6d583 100644--- a/extra/lib/plausible/workers/score_trial_prospects.ex+++ b/extra/lib/plausible/workers/score_trial_prospects.ex@@ -14,12 +14,10 @@ defmodule Plausible.Workers.ScoreTrialProspects doalias Plausible.Teamsalias Plausible.CustomerSupport.{TrialProspect, TrialProspects}- @max_expired_days 30-@impl Oban.Workerdef perform(_job) do- Date.utc_today()- |> trial_population()+ TrialProspects.population_query()+ |> Repo.all()|> Enum.each(&score_and_persist/1):ok@@ -39,18 +37,6 @@ defmodule Plausible.Workers.ScoreTrialProspects doendend- defp trial_population(today) do- cutoff = Date.add(today, -@max_expired_days)-- Repo.all(- from t in Teams.Team,- left_join: s in assoc(t, :subscription),- where: not is_nil(t.trial_expiry_date),- where: is_nil(s.id),- where: t.trial_expiry_date >= ^cutoff- )- end-defp score_team(team) dosite_ids = Teams.owned_sites_ids(team)diff --git a/extra/lib/plausible_web/live/customer_support/components/layout.ex b/extra/lib/plausible_web/live/customer_support/components/layout.exindex 0b5f05234a..c6bcc3693e 100644--- a/extra/lib/plausible_web/live/customer_support/components/layout.ex+++ b/extra/lib/plausible_web/live/customer_support/components/layout.ex@@ -102,6 +102,12 @@ defmodule PlausibleWeb.CustomerSupport.Components.Layout doπ¬ Customer Support</.link></h2>+ <.styled_link+ class="text-sm flex-shrink-0"+ patch={Routes.customer_support_trial_prospects_path(PlausibleWeb.Endpoint, :index)}+ >+ π₯ Trial prospects+ </.styled_link></div>"""enddiff --git a/extra/lib/plausible_web/live/customer_support/live.ex b/extra/lib/plausible_web/live/customer_support/live.exindex fecf2f8b77..61ca979f93 100644--- a/extra/lib/plausible_web/live/customer_support/live.ex+++ b/extra/lib/plausible_web/live/customer_support/live.ex@@ -4,7 +4,7 @@ defmodule PlausibleWeb.CustomerSupport.Live doProvides:- Standard mount/3 and handle_info/2 implementations- - Tab navigation components and routing utilities+ - Tab navigation components and routing utilities- Common aliases and imports for Customer Support LiveViews- Convenience API for flashes and redirects"""@@ -92,6 +92,27 @@ defmodule PlausibleWeb.CustomerSupport.Live do"""end+ attr :active, :boolean, required: true+ attr :direction, :atom, required: true++ def sort_arrow(%{active: false} = assigns) do+ ~H"""+ <span class="opacity-30">β</span>+ """+ end++ def sort_arrow(%{direction: :asc} = assigns) do+ ~H"""+ <span>β</span>+ """+ end++ def sort_arrow(assigns) do+ ~H"""+ <span>β</span>+ """+ end+attr :tab, :string, required: trueattr :extra_classes, :string, default: ""slot :tabs, required: truediff --git a/extra/lib/plausible_web/live/customer_support/team/components/sites.ex b/extra/lib/plausible_web/live/customer_support/team/components/sites.exindex 920457cff4..09a7b2c254 100644--- a/extra/lib/plausible_web/live/customer_support/team/components/sites.ex+++ b/extra/lib/plausible_web/live/customer_support/team/components/sites.ex@@ -5,6 +5,7 @@ defmodule PlausibleWeb.CustomerSupport.Team.Components.Sites douse PlausibleWeb, :live_componentimport Ecto.Query, except: [update: 2, update: 3]+ import PlausibleWeb.CustomerSupport.Live, only: [sort_arrow: 1]import PlausibleWeb.Live.Components.Paginationalias Plausible.Repo@@ -221,25 +222,4 @@ defmodule PlausibleWeb.CustomerSupport.Team.Components.Sites dodefp flip_direction(:asc), do: :descdefp flip_direction(:desc), do: :asc-- attr :active, :boolean, required: true- attr :direction, :atom, required: true-- defp sort_arrow(%{active: false} = assigns) do- ~H"""- <span class="opacity-30">β</span>- """- end-- defp sort_arrow(%{direction: :asc} = assigns) do- ~H"""- <span>β</span>- """- end-- defp sort_arrow(assigns) do- ~H"""- <span>β</span>- """- endenddiff --git a/extra/lib/plausible_web/live/customer_support/trial_prospects.ex b/extra/lib/plausible_web/live/customer_support/trial_prospects.exnew file mode 100644index 0000000000..872bb02553--- /dev/null+++ b/extra/lib/plausible_web/live/customer_support/trial_prospects.ex@@ -0,0 +1,188 @@+defmodule PlausibleWeb.Live.CustomerSupport.TrialProspects do+ @moduledoc """+ Customer Support page listing active trials. Reads the+ cached `trial_prospects` table populated daily by+ `Plausible.Workers.ScoreTrialProspects`.+ """+ use PlausibleWeb.CustomerSupport.Live++ import PlausibleWeb.Live.Components.Pagination++ alias Plausible.CustomerSupport.TrialProspects+ alias PlausibleWeb.StatsView+ alias PlausibleWeb.TextHelpers++ def handle_params(params, _uri, socket) do+ sort_by =+ if params["sort_by"] in TrialProspects.sortable_columns(),+ do: params["sort_by"],+ else: "mrr"++ sort_direction =+ case params["sort_direction"] do+ "asc" -> :asc+ _ -> :desc+ end++ socket =+ socket+ |> assign(sort_by: sort_by, sort_direction: sort_direction)+ |> assign(TrialProspects.list(sort_by, sort_direction, parse_page(params["page"])))++ {:noreply, socket}+ end++ def render(assigns) do+ ~H"""+ <Layout.layout show_search={false} flash={@flash}>+ <div class="flex items-center justify-between">+ <h2 class="text-xl font-bold sm:text-2xl">π₯ Trial prospects</h2>+ <p class="text-sm text-gray-500 dark:text-gray-400">+ {@total_entries} prospects+ </p>+ </div>++ <div class="mt-4">+ <.table rows={@prospects}>+ <:thead>+ <.th>Team</.th>+ <.sort_th+ label="MRR potential"+ by="mrr"+ sort_by={@sort_by}+ sort_direction={@sort_direction}+ />+ <.th>Feature tier</.th>+ <.th>Forced by</.th>+ <.th>Traffic estimate</.th>+ <.sort_th+ label="Trial start"+ by="trial_start"+ sort_by={@sort_by}+ sort_direction={@sort_direction}+ />+ <.th>Trial expiry</.th>+ </:thead>+ <:tbody :let={p}>+ <.td>+ <.styled_link patch={+ Routes.customer_support_team_path(PlausibleWeb.Endpoint, :show, p.team.id)+ }>+ {p.team.name}+ </.styled_link>+ <div :if={owner_email(p.team)} class="text-xs text-gray-500 dark:text-gray-400">+ {owner_email(p.team)}+ </div>+ </.td>+ <.td>+ <span class="font-semibold">{mrr_label(p)}</span>+ </.td>+ <.td>+ <.pill color={kind_color(p.kind)} class="capitalize">{p.kind}</.pill>+ </.td>+ <.td>+ <div class="flex flex-wrap gap-1">+ <span :if={p.forced_by == []} class="text-gray-400 dark:text-gray-500">β</span>+ <.pill :for={gate <- p.forced_by} color={:gray}>{gate_label(gate)}</.pill>+ </div>+ </.td>+ <.td>{StatsView.large_number_format(p.estimated_monthly)}</.td>+ <.td>{format_date(trial_start(p.team))}</.td>+ <.td>{format_date(p.team.trial_expiry_date)}</.td>+ </:tbody>+ </.table>++ <.pagination+ :if={@total_pages > 1}+ id="trial-prospects-pagination"+ uri={+ URI.new!(+ Routes.customer_support_trial_prospects_path(PlausibleWeb.Endpoint, :index,+ sort_by: @sort_by,+ sort_direction: @sort_direction,+ page: @page_number+ )+ )+ }+ page_number={@page_number}+ total_pages={@total_pages}+ >+ Total of <span class="font-medium">{@total_entries}</span>+ trials. Page {@page_number} of {@total_pages}+ </.pagination>++ <p :if={@prospects == []} class="text-sm text-gray-500 dark:text-gray-400">+ No trial prospects have been scored yet.+ </p>+ </div>+ </Layout.layout>+ """+ end++ attr :label, :string, required: true+ attr :by, :string, required: true+ attr :sort_by, :string, required: true+ attr :sort_direction, :atom, required: true++ defp sort_th(assigns) do+ active = assigns.sort_by == assigns.by+ assigns = assign(assigns, active: active, next_direction: next_direction(assigns, active))++ ~H"""+ <.th>+ <.link+ patch={+ Routes.customer_support_trial_prospects_path(PlausibleWeb.Endpoint, :index,+ sort_by: @by,+ sort_direction: @next_direction+ )+ }+ class="cursor-pointer select-none inline-flex items-center gap-1 hover:text-indigo-600 dark:hover:text-indigo-400"+ >+ {@label}+ <.sort_arrow active={@active} direction={@sort_direction} />+ </.link>+ </.th>+ """+ end++ defp next_direction(%{sort_direction: :desc}, true), do: :asc+ defp next_direction(_assigns, _active), do: :desc++ defp parse_page(page) do+ case Integer.parse(page || "") do+ {n, _} when n > 0 -> n+ _ -> 1+ end+ end++ defp trial_start(team), do: NaiveDateTime.to_date(team.inserted_at)++ defp owner_email(team) do+ case team.owners do+ [owner | _] -> owner.email+ _ -> nil+ end+ end++ defp kind_color(:business), do: :indigo+ defp kind_color(:growth), do: :green+ defp kind_color(_), do: :gray++ defp gate_label("site_limit"), do: "Site limit"+ defp gate_label("team_member_limit"), do: "Team members"++ defp gate_label(feature) do+ case Plausible.Billing.Ecto.Feature.cast(feature) do+ {:ok, mod} -> mod.display_name()+ :error -> feature+ end+ end++ defp mrr_label(%{over_top_tier: true}), do: "Custom / Enterprise"+ defp mrr_label(%{estimated_mrr: nil}), do: "β"+ defp mrr_label(%{estimated_mrr: mrr}), do: "β¬#{TextHelpers.number_format(mrr)}/mo"++ defp format_date(nil), do: "β"+ defp format_date(date), do: TextHelpers.format_date(date)+enddiff --git a/lib/plausible_web/router.ex b/lib/plausible_web/router.exindex 812b308967..f2474fcec1 100644--- a/lib/plausible_web/router.ex+++ b/lib/plausible_web/router.ex@@ -117,6 +117,10 @@ defmodule PlausibleWeb.Router dopipe_through [:browser, :csrf, :app_layout, :flags]live "/cs", CustomerSupport, :index, as: :customer_support++ live "/cs/trial-prospects", CustomerSupport.TrialProspects, :index,+ as: :customer_support_trial_prospects+live "/cs/teams/team/:id", CustomerSupport.Team, :show, as: :customer_support_teamlive "/cs/users/user/:id", CustomerSupport.User, :show, as: :customer_support_userlive "/cs/sites/site/:id", CustomerSupport.Site, :show, as: :customer_support_sitediff --git a/test/plausible_web/live/customer_support/trial_prospects_test.exs b/test/plausible_web/live/customer_support/trial_prospects_test.exsnew file mode 100644index 0000000000..ace311724a--- /dev/null+++ b/test/plausible_web/live/customer_support/trial_prospects_test.exs@@ -0,0 +1,174 @@+defmodule PlausibleWeb.Live.CustomerSupport.TrialProspectsTest do+ use PlausibleWeb.ConnCase, async: false+ @moduletag :ee_only++ on_ee do+ import Phoenix.LiveViewTest++ alias Plausible.Repo+ alias Plausible.CustomerSupport.TrialProspect++ defp open_prospects(qs \\ []) do+ Routes.customer_support_trial_prospects_path(PlausibleWeb.Endpoint, :index, qs)+ end++ setup [:create_user, :log_in]++ setup %{user: user} do+ patch_env(:super_admin_user_ids, [user.id])+ end++ defp prospect(team, attrs) do+ defaults = %{+ team_id: team.id,+ estimated_monthly: 50_000,+ observed_days: 10,+ first_data_day: ~D[2026-06-01],+ kind: :starter,+ forced_by: [],+ pageview_limit: 100_000,+ over_top_tier: false,+ estimated_mrr: 19,+ computed_at: ~U[2026-06-20 00:00:00Z]+ }++ Repo.insert!(struct!(TrialProspect, Map.merge(defaults, Map.new(attrs))))+ end++ test "renders trials ranked by MRR potential by default", %{conn: conn} do+ small = insert(:team, name: "Small Co")+ big = insert(:team, name: "Big Co")++ prospect(small, estimated_mrr: 19, kind: :starter)++ prospect(big,+ estimated_mrr: 339,+ kind: :business,+ forced_by: ["funnels", "team_member_limit"]+ )++ {:ok, _lv, html} = live(conn, open_prospects())+ text = text(html)++ assert text =~ "Trial prospects"+ assert text =~ "Feature tier"+ assert text =~ "Forced by"+ assert text =~ "Big Co"+ assert text =~ "Small Co"+ assert text =~ "β¬339/mo"++ # forced_by gates are labelled in the "Forced by" column+ assert text =~ "Funnels and user journeys"+ assert text =~ "Team members"++ # Big Co (higher MRR) is listed first+ assert text_of_element(html, "tbody tr:first-child") =~ "Big Co"+ end++ test "labels every forced_by gate in the Forced by column", %{conn: conn} do+ team = insert(:team, name: "Everything Co")++ gates = [+ {"site_limit", "Site limit"},+ {"team_member_limit", "Team members"},+ {"stats_api", "Stats API"},+ {"props", "Custom Properties"},+ {"revenue_goals", "Revenue Goals"},+ {"shared_links", "Shared Links"},+ {"site_segments", "Shared Segments"},+ {"site_annotations", "Shared Annotations"},+ {"funnels", "Funnels and user journeys"}+ ]++ prospect(team,+ estimated_mrr: 339,+ kind: :business,+ forced_by: Enum.map(gates, &elem(&1, 0))+ )++ {:ok, _lv, html} = live(conn, open_prospects())+ text = text(html)++ for {_gate, label} <- gates do+ assert text =~ label+ end+ end++ test "over-top-tier prospects sort above concrete MRR values", %{conn: conn} do+ enterprise = insert(:team, name: "Enterprise Co")+ business = insert(:team, name: "Business Co")++ prospect(business, estimated_mrr: 339, kind: :business, over_top_tier: false)++ prospect(enterprise,+ estimated_mrr: nil,+ kind: :business,+ over_top_tier: true,+ pageview_limit: nil+ )++ {:ok, _lv, html} = live(conn, open_prospects())++ assert text(html) =~ "Custom / Enterprise"+ assert text_of_element(html, "tbody tr:first-child") =~ "Enterprise Co"+ end++ test "can re-order by trial start date", %{conn: conn} do+ older = insert(:team, name: "Older Co", inserted_at: ~N[2026-01-01 00:00:00])+ newer = insert(:team, name: "Newer Co", inserted_at: ~N[2026-06-01 00:00:00])++ prospect(older, estimated_mrr: 9)+ prospect(newer, estimated_mrr: 339)++ # ascending: oldest trial start first+ {:ok, _lv, html} =+ live(conn, open_prospects(sort_by: "trial_start", sort_direction: "asc"))++ assert text_of_element(html, "tbody tr:first-child") =~ "Older Co"+ end++ test "excludes rows left behind for teams no longer on a trial", %{conn: conn} do+ live_team = insert(:team, name: "Live Co")+ prospect(live_team, estimated_mrr: 19)++ long_expired =+ insert(:team, name: "Long Expired Co", trial_expiry_date: Date.add(Date.utc_today(), -90))++ prospect(long_expired, estimated_mrr: 999)++ converted = insert(:team, name: "Converted Co")+ insert(:subscription, team: converted)+ prospect(converted, estimated_mrr: 999)++ {:ok, _lv, html} = live(conn, open_prospects())+ text = text(html)++ assert text =~ "Live Co"+ assert text =~ "1 prospects"+ refute text =~ "Long Expired Co"+ refute text =~ "Converted Co"+ end++ test "renders the owner email alongside the team", %{conn: conn} do+ team = new_user(email: "[email protected]", team: [name: "Owned Co"]) |> team_of()+ prospect(team, estimated_mrr: 99)++ {:ok, _lv, html} = live(conn, open_prospects())++ assert text_of_element(html, "tbody tr:first-child") =~ "[email protected]"+ end++ test "links each row to the team CS page", %{conn: conn} do+ team = insert(:team, name: "Linked Co")+ prospect(team, estimated_mrr: 99)++ {:ok, lv, _html} = live(conn, open_prospects())++ assert lv+ |> element(+ ~s|a[href="#{Routes.customer_support_team_path(PlausibleWeb.Endpoint, :show, team.id)}"]|+ )+ |> has_element?()+ end+ end+end