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
CRM: Allow manual subscriptions for enterprise plans (#6735)
Adam85129a6671b6
diff --git a/extra/lib/plausible/help_scout.ex b/extra/lib/plausible/help_scout.exindex c205e4c57d..6a5844d6d5 100644--- a/extra/lib/plausible/help_scout.ex+++ b/extra/lib/plausible/help_scout.ex@@ -22,6 +22,8 @@ defmodule Plausible.HelpScout do@excluded_email_domains ["paddle.com"]+ @manual_plan_id Subscription.manual_plan_id()+@type signature_error() :: unquote(Enum.reduce(@signature_errors, &{:|, [], [&1, &2]}))def signature_errors(), do: @signature_errors@@ -183,6 +185,9 @@ defmodule Plausible.HelpScout dodefp plan_link(nil), do: "#"+ # Subscriptions outside of Paddle (manual, free_10k) have nothing to link to+ defp plan_link(%{paddle_subscription_id: nil}), do: "#"+defp plan_link(%{paddle_subscription_id: paddle_id}) doPath.join([Billing.PaddleApi.vendors_domain(),@@ -251,6 +256,15 @@ defmodule Plausible.HelpScout do"#{quota} Plan (#{price} #{interval})"end+ # Manually invoiced, so there's no Paddle price to fetch+ defp plan_label(+ %Subscription{paddle_plan_id: @manual_plan_id} = subscription,+ %Billing.EnterprisePlan{} = plan+ ) do+ quota = PlausibleWeb.AuthView.subscription_quota(subscription, [])+ "#{quota} Enterprise Plan (manual, #{plan.billing_interval})"+ end+defp plan_label(subscription, %Billing.EnterprisePlan{} = plan) doquota = PlausibleWeb.AuthView.subscription_quota(subscription, [])price_amount = Billing.Plans.get_price_for(plan, "127.0.0.1")@@ -310,7 +324,7 @@ defmodule Plausible.HelpScout dodefp get_emails_with_customer_mapping(customer_id) do# We want to explicitly reject customer emails from HS which- # are in one of excluded domains. That's why we fetch+ # are in one of excluded domains. That's why we fetch# emails from HS first before checking the mapping.case fetch_customer_emails(customer_id) do{:ok, emails} ->diff --git a/extra/lib/plausible_web/live/customer_support/team.ex b/extra/lib/plausible_web/live/customer_support/team.exindex 66b2b397f0..8c0684cdd5 100644--- a/extra/lib/plausible_web/live/customer_support/team.ex+++ b/extra/lib/plausible_web/live/customer_support/team.ex@@ -307,20 +307,26 @@ defmodule PlausibleWeb.Live.CustomerSupport.Team dodefp subscription_plan(team) dosubscription = team.subscription- if Plausible.Billing.Subscription.Status.active?(subscription) &&- subscription.paddle_subscription_id do- quota = PlausibleWeb.AuthView.subscription_quota(subscription)- interval = PlausibleWeb.AuthView.subscription_interval(subscription)-- assigns = %{quota: quota, interval: interval, subscription: subscription}-- ~H"""- <.styled_link new_tab={true} href={manage_url(@subscription)}>- {@quota} ({@interval})- </.styled_link>- """- else- "--"+ cond do+ Plausible.Billing.Subscription.Status.active?(subscription) &&+ subscription.paddle_subscription_id ->+ quota = PlausibleWeb.AuthView.subscription_quota(subscription)+ interval = PlausibleWeb.AuthView.subscription_interval(subscription)++ assigns = %{quota: quota, interval: interval, subscription: subscription}++ ~H"""+ <.styled_link new_tab={true} href={manage_url(@subscription)}>+ {@quota} ({@interval})+ </.styled_link>+ """++ Plausible.Billing.Subscription.Status.active?(subscription) &&+ Plausible.Billing.Subscription.manual_subscription?(subscription) ->+ "Manually billed enterprise"++ true ->+ "--"endenddiff --git a/extra/lib/plausible_web/live/customer_support/team/components/billing.ex b/extra/lib/plausible_web/live/customer_support/team/components/billing.exindex 3a482b9d59..93d96acf01 100644--- a/extra/lib/plausible_web/live/customer_support/team/components/billing.ex+++ b/extra/lib/plausible_web/live/customer_support/team/components/billing.ex@@ -24,7 +24,7 @@ defmodule PlausibleWeb.CustomerSupport.Team.Components.Billing doplan = Plans.get_subscription_plan(team.subscription)attrs = get_plan_attrs(plan)- plan_form = to_form(EnterprisePlan.changeset(%EnterprisePlan{}, attrs))+ plan_form = to_form(EnterprisePlan.create_changeset(%EnterprisePlan{}, attrs)){:ok,assign(socket,@@ -70,7 +70,19 @@ defmodule PlausibleWeb.CustomerSupport.Team.Components.Billing do</div><div class="mt-4 mb-4 text-gray-900 dark:text-gray-400">- <h1 class="text-xs font-semibold">Usage</h1>+ <.title :if={@team.subscription} class="mb-2">Subscription</.title>+ <.table :if={@team.subscription} rows={[@team.subscription]}>+ <:thead>+ <.th>Last bill date</.th>+ <.th>Next bill date</.th>+ </:thead>+ <:tbody :let={subscription}>+ <.td data-test-id="last-bill-date">{format_bill_date(subscription.last_bill_date)}</.td>+ <.td data-test-id="next-bill-date">{format_bill_date(subscription.next_bill_date)}</.td>+ </:tbody>+ </.table>++ <.title class="mt-8 mb-2">Usage</.title><.table rows={monthly_pageviews_usage(@usage.monthly_pageviews, @limits.monthly_pageviews)}><:thead><.th invisible>Cycle</.th>@@ -90,16 +102,14 @@ defmodule PlausibleWeb.CustomerSupport.Team.Components.Billing do</:tbody></.table>- <p :if={@usage.features != []} class="mt-6 mb-4">- <h1 class="text-xs font-semibold">Features Used</h1>+ <%= if @usage.features != [] do %>+ <.title class="mt-8 mb-2">Features Used</.title><span class="text-sm">{@usage.features |> Enum.map(& &1.display_name()) |> Enum.join(", ")}</span>- </p>+ <% end %>- <h1 :if={!@show_plan_form? and @plans != []} class="mt-8 text-xs font-semibold">- Custom Plans- </h1>+ <.title :if={!@show_plan_form? and @plans != []} class="mt-8 mb-2">Custom Plans</.title><.table :if={!@show_plan_form?} rows={@plans}><:thead><.th invisible>Interval</.th>@@ -114,6 +124,20 @@ defmodule PlausibleWeb.CustomerSupport.Team.Components.Billing do</.td><.td class="align-top" data-test-id={"plan-entry-#{plan.paddle_plan_id}"}>{plan.paddle_plan_id}+ <br />++ <.button+ :if={not current_plan?(@team, plan.paddle_plan_id)}+ id={"manual-subscribe-#{plan.paddle_plan_id}"}+ theme="secondary"+ size="sm"+ data-confirm={manual_subscribe_confirmation()}+ phx-click="manual-subscribe"+ phx-value-id={plan.id}+ phx-target={@myself}+ >+ Manual Subscribe+ </.button><span:if={current_plan?(@team, plan.paddle_plan_id)}@@ -121,6 +145,15 @@ defmodule PlausibleWeb.CustomerSupport.Team.Components.Billing do>CURRENT</span>+ <span+ :if={+ current_plan?(@team, plan.paddle_plan_id) and+ Plausible.Billing.Subscription.manual_subscription?(@team.subscription)+ }+ class="inline-flex items-center px-2 py-0.5 rounded text-xs font-xs bg-green-100 text-green-800"+ >+ MANUAL SUBSCRIPTION+ </span></.td><.td max_width="max-w-40"><.table rows={[@@ -161,7 +194,12 @@ defmodule PlausibleWeb.CustomerSupport.Team.Components.Billing dophx-target={@myself}phx-change="estimate-cost">- <.input field={f[:paddle_plan_id]} label="Paddle Plan ID" autocomplete="off" />+ <.input+ field={f[:paddle_plan_id]}+ label="Paddle Plan ID"+ autocomplete="off"+ readonly={not is_nil(@editing_plan)}+ /><.inputtype="select"options={["monthly", "yearly"]}@@ -250,7 +288,58 @@ defmodule PlausibleWeb.CustomerSupport.Team.Components.Billing doenddef handle_event("show-plan-form", _, socket) do- {:noreply, assign(socket, show_plan_form?: true, editing_plan: nil)}+ if Plausible.Billing.Subscription.manual_subscription?(socket.assigns.team.subscription) do+ failure(+ "Creating a new plan is prohibited due to a manual subscription. Edit the existing enterprise plan instead."+ )++ {:noreply, socket}+ else+ {:noreply, assign(socket, show_plan_form?: true, editing_plan: nil)}+ end+ end++ def handle_event("manual-subscribe", %{"id" => plan_id}, socket) do+ %{team: team, plans: plans} = socket.assigns+ plan = Enum.find(plans, &(&1.id == String.to_integer(plan_id)))++ if plan && not current_plan?(team, plan.paddle_plan_id) do+ case Plausible.Billing.create_manual_subscription(team, plan) do+ {:ok, _team} ->+ # Reload the whole page, so that e.g. the subscription status in the header updates too+ navigate_with_success(+ ~p"/cs/teams/team/#{team.id}?tab=billing",+ "Subscription created (manual)"+ )++ {:noreply, socket}++ {:error, :already_manual} ->+ failure("A team can only have one manual subscription")+ {:noreply, socket}++ {:error, :active_subscription} ->+ failure("The team has an active Paddle subscription. Cancel it in Paddle first.")+ {:noreply, socket}++ {:error, :not_latest_plan} ->+ failure("Only the latest enterprise plan can get a manual subscription")+ {:noreply, socket}++ {:error, :not_yearly} ->+ failure(+ "Manual subscriptions are only possible for yearly plans. Change the plan's billing interval to yearly first."+ )++ {:noreply, socket}++ {:error, changeset} ->+ failure("Error saving subscription: #{inspect(changeset.errors)}")+ {:noreply, socket}+ end+ else+ {:noreply, socket}+ endenddef handle_event("edit-plan", %{"id" => plan_id}, socket) do@@ -258,7 +347,7 @@ defmodule PlausibleWeb.CustomerSupport.Team.Components.Billing doplan = Enum.find(socket.assigns.plans, &(&1.id == plan_id))if plan do- plan_form = to_form(EnterprisePlan.changeset(plan, %{}))+ plan_form = to_form(EnterprisePlan.update_changeset(plan)){:noreply, assign(socket, show_plan_form?: true, editing_plan: plan, plan_form: plan_form)}else{:noreply, socket}@@ -282,7 +371,7 @@ defmodule PlausibleWeb.CustomerSupport.Team.Components.Billing dodef handle_event("estimate-cost", %{"enterprise_plan" => params}, socket) doparams = update_features_to_list(params)- form = to_form(EnterprisePlan.changeset(%EnterprisePlan{}, params))+ form = to_form(EnterprisePlan.create_changeset(%EnterprisePlan{}, params))params = sanitize_params(params)@@ -302,7 +391,9 @@ defmodule PlausibleWeb.CustomerSupport.Team.Components.Billing dodef handle_event("save-plan", %{"enterprise_plan" => params}, socket) doparams = params |> update_features_to_list() |> sanitize_params()- changeset = EnterprisePlan.changeset(%EnterprisePlan{team_id: socket.assigns.team.id}, params)++ changeset =+ EnterprisePlan.create_changeset(%EnterprisePlan{team_id: socket.assigns.team.id}, params)case Plausible.Repo.insert(changeset) do{:ok, _plan} ->@@ -325,7 +416,7 @@ defmodule PlausibleWeb.CustomerSupport.Team.Components.Billing dodef handle_event("update-plan", %{"enterprise_plan" => params}, socket) doparams = params |> update_features_to_list() |> sanitize_params()- changeset = EnterprisePlan.changeset(socket.assigns.editing_plan, params)+ changeset = EnterprisePlan.update_changeset(socket.assigns.editing_plan, params)case Plausible.Repo.update(changeset) do{:ok, _plan} ->@@ -387,6 +478,9 @@ defmodule PlausibleWeb.CustomerSupport.Team.Components.Billing do)end+ defp format_bill_date(nil), do: "--"+ defp format_bill_date(date), do: PlausibleWeb.TextHelpers.format_date(date)+defp number_format(unlimited) when unlimited in [-1, "unlimited", :unlimited] do"unlimited"end@@ -456,6 +550,18 @@ defmodule PlausibleWeb.CustomerSupport.Team.Components.Billing do"""end+ defp manual_subscribe_confirmation() do+ """+ Manually subscribe the customer to this enterprise plan?++ This creates a subscription outside of Paddle, which will have no information about it. \+ Use it only when the customer pays by bank transfer against an invoice.++ The plan's Paddle Plan ID will be replaced with "manual-subscription". \+ The subscription will be valid for one year starting today.+ """+ end+defp current_plan?(%{subscription: %{paddle_plan_id: id}}, id), do: truedefp current_plan?(_, _), do: falseenddiff --git a/lib/plausible/billing/billing.ex b/lib/plausible/billing/billing.exindex 88859273e0..0a3b5f868c 100644--- a/lib/plausible/billing/billing.ex+++ b/lib/plausible/billing/billing.ex@@ -1,14 +1,14 @@defmodule Plausible.Billing do@moduledoc """- Handles Plausible billing subscription lifecycle events (creation, update, cancellation, payment success),- Paddle API, team assignment, and notification logic. Provides helpers for formatting prices,+ Handles Plausible billing subscription lifecycle events (creation, update, cancellation, payment success),+ Paddle API, team assignment, and notification logic. Provides helpers for formatting prices,managing subscription status, and updating team-related billing state."""use Plausibleuse Plausible.Repoalias Plausible.Auth- alias Plausible.Billing.Subscription+ alias Plausible.Billing.{EnterprisePlan, Subscription, Subscriptions}alias Plausible.TeamDeletionSchedulesalias Plausible.Teams@@ -38,6 +38,66 @@ defmodule Plausible.Billing doend)end+ @doc """+ Creates a subscription for a custom plan without Paddle checkout (for example, paid by bank transfer).++ The enterprise plan's `paddle_plan_id` is rewritten to a conventional+ `manual-subscription` ID, which is also what the subscription gets, so the two+ stay linked. `paddle_subscription_id` is left empty. See+ `Subscription.manual_changeset/2` for the remaining values.++ ## Limitations for creating a manual subscription:++ * Only the team's latest enterprise plan can be manually subscribed to+ * A team can only have one manual subscription+ * Teams with a resumable (active, past due or paused) Paddle subscription must have it cancelled first.+ * The enterprise plan must have yearly billing+ """+ def create_manual_subscription(team, %{id: plan_id} = enterprise_plan) do+ subscription =+ Repo.one(from(s in Teams.last_subscription_query(), where: s.team_id == ^team.id))++ already_manual? = Subscription.manual_subscription?(subscription)++ already_subscriber? =+ Subscriptions.resumable?(subscription) and subscription.paddle_plan_id != "free_10k"++ latest_plan? = match?(%{id: ^plan_id}, latest_enterprise_plan(team))++ cond do+ already_manual? -> {:error, :already_manual}+ already_subscriber? -> {:error, :active_subscription}+ not latest_plan? -> {:error, :not_latest_plan}+ enterprise_plan.billing_interval != :yearly -> {:error, :not_yearly}+ true -> do_create_manual_subscription(team, enterprise_plan)+ end+ end++ defp do_create_manual_subscription(team, enterprise_plan) do+ Repo.transaction(fn ->+ with {:ok, _plan} <-+ Repo.update(EnterprisePlan.manual_subscription_changeset(enterprise_plan)),+ {:ok, subscription} <- Repo.insert(Subscription.manual_changeset(team)) do+ after_subscription_update(subscription)+ else+ {:error, changeset} -> Repo.rollback(changeset)+ end+ end)+ end++ @doc """+ Returns the team's most recently created enterprise plan, or `nil` if it has none.+ """+ def latest_enterprise_plan(team) do+ Repo.one(+ from(ep in Plausible.Billing.EnterprisePlan,+ where: ep.team_id == ^team.id,+ order_by: [desc: ep.inserted_at, desc: ep.id],+ limit: 1+ )+ )+ end+def change_plan_preview(subscription, new_plan_id) docase paddle_api().update_subscription_preview(subscription.paddle_subscription_id,diff --git a/lib/plausible/billing/enterprise_plan.ex b/lib/plausible/billing/enterprise_plan.exindex 608f6ea08b..a49fef25dc 100644--- a/lib/plausible/billing/enterprise_plan.ex+++ b/lib/plausible/billing/enterprise_plan.ex@@ -32,12 +32,42 @@ defmodule Plausible.Billing.EnterprisePlan do@max round(:math.pow(2, 31))- def changeset(model, attrs \\ %{}) do+ def create_changeset(model, attrs \\ %{}) domodel|> cast(attrs, @required_fields)+ |> validate()+ end++ @doc """+ Updates an existing plan. `paddle_plan_id` is never changed, because+ subscriptions are linked to the plan by it.+ """+ def update_changeset(plan, attrs \\ %{}) do+ plan+ |> cast(attrs, List.delete(@required_fields, :paddle_plan_id))+ |> validate()+ end++ @doc """+ Marks the plan as manually subscribed to, see+ `Plausible.Billing.create_manual_subscription/2`.+ """+ def manual_subscription_changeset(plan) do+ plan+ |> change(paddle_plan_id: Plausible.Billing.Subscription.manual_plan_id())+ |> unique_paddle_plan_id_constraint()+ end++ defp validate(changeset) do+ changeset|> validate_number(:monthly_pageview_limit, less_than: @max)|> validate_number(:site_limit, less_than: @max)|> validate_number(:hourly_api_request_limit, less_than: @max)|> validate_required(@required_fields)+ |> unique_paddle_plan_id_constraint()+ end++ defp unique_paddle_plan_id_constraint(changeset) do+ unique_constraint(changeset, [:team_id, :paddle_plan_id], error_key: :paddle_plan_id)endenddiff --git a/lib/plausible/billing/subscription.ex b/lib/plausible/billing/subscription.exindex 545066620e..003540deca 100644--- a/lib/plausible/billing/subscription.ex+++ b/lib/plausible/billing/subscription.ex@@ -50,6 +50,36 @@ defmodule Plausible.Billing.Subscription do|> unique_constraint(:paddle_subscription_id)end+ @manual_plan_id "manual-subscription"++ @doc """+ The plan ID marking a custom plan as manually subscribed (outside of Paddle).+ """+ def manual_plan_id(), do: @manual_plan_id++ def manual_subscription?(%__MODULE__{paddle_plan_id: @manual_plan_id}), do: true+ def manual_subscription?(_), do: false++ @doc """+ Builds a subscription created manually from the CRM, outside of Paddle.++ There is no known price, so `next_bill_amount` is a `-1` placeholder and+ the UI doesn't present it. The subscription is considered paid today and+ renews in a year.+ """+ def manual_changeset(team, today \\ Date.utc_today()) do+ %__MODULE__{+ paddle_plan_id: @manual_plan_id,+ status: Subscription.Status.active(),+ currency_code: "XXX",+ next_bill_amount: "-1",+ last_bill_date: today,+ next_bill_date: Date.shift(today, year: 1)+ }+ |> change()+ |> put_assoc(:team, team)+ end+def free(team, attrs \\ %{}) do%__MODULE__{paddle_plan_id: "free_10k",diff --git a/lib/plausible/teams/billing.ex b/lib/plausible/teams/billing.exindex a49854bd40..30079dd71d 100644--- a/lib/plausible/teams/billing.ex+++ b/lib/plausible/teams/billing.ex@@ -93,19 +93,6 @@ defmodule Plausible.Teams.Billing do|> Repo.exists?()end- def latest_enterprise_plan_with_price(team, customer_ip) do- enterprise_plan =- Repo.one!(- from(e in EnterprisePlan,- where: e.team_id == ^team.id,- order_by: [desc: e.inserted_at],- limit: 1- )- )-- {enterprise_plan, Plausible.Billing.Plans.get_price_for(enterprise_plan, customer_ip)}- end-def has_active_subscription?(nil), do: falsedef has_active_subscription?(team) dodiff --git a/lib/plausible_web/controllers/billing_controller.ex b/lib/plausible_web/controllers/billing_controller.exindex a85a53c9ac..3451437eaa 100644--- a/lib/plausible_web/controllers/billing_controller.ex+++ b/lib/plausible_web/controllers/billing_controller.ex@@ -3,11 +3,10 @@ defmodule PlausibleWeb.BillingController douse Plausible.Reporequire Logger- require Plausible.Billing.Subscription.Statusrequire Plausible.Billingalias Plausible.Billing- alias Plausible.Billing.Subscription+ alias Plausible.Billing.{Plans, Subscription, Subscriptions}plug PlausibleWeb.RequireAccountPlug@@ -38,31 +37,27 @@ defmodule PlausibleWeb.BillingController dodef upgrade_to_enterprise_plan(conn, _params) doteam = conn.assigns.current_teamsubscription = Plausible.Teams.Billing.get_subscription(team)+ latest_enterprise_plan = Billing.latest_enterprise_plan(team)- {latest_enterprise_plan, price} =- Plausible.Teams.Billing.latest_enterprise_plan_with_price(- team,- PlausibleWeb.RemoteIP.get(conn)- )-- subscription_resumable? =- Plausible.Billing.Subscriptions.resumable?(subscription)+ subscription_resumable? = Subscriptions.resumable?(subscription)subscribed_to_latest? =- subscription_resumable? &&+ subscription_resumable? and not is_nil(latest_enterprise_plan) andsubscription.paddle_plan_id == latest_enterprise_plan.paddle_plan_idcond do- Subscription.Status.in?(subscription, [- Subscription.Status.past_due(),- Subscription.Status.paused()- ]) ->+ is_nil(latest_enterprise_plan) ->+ redirect(conn, to: ~p"/billing/choose-plan")++ Subscriptions.halted?(subscription) ->redirect(conn, to: ~p"/settings/billing/subscription")- subscribed_to_latest? ->+ subscribed_to_latest? or Subscription.manual_subscription?(subscription) ->render(conn, "change_enterprise_plan_contact_us.html", skip_plausible_tracking: true)true ->+ price = Plans.get_price_for(latest_enterprise_plan, PlausibleWeb.RemoteIP.get(conn))+render(conn, "upgrade_to_enterprise_plan.html",latest_enterprise_plan: latest_enterprise_plan,price: price,diff --git a/lib/plausible_web/live/subscription_settings.ex b/lib/plausible_web/live/subscription_settings.exindex 889b0d53ba..5b0434a5d2 100644--- a/lib/plausible_web/live/subscription_settings.ex+++ b/lib/plausible_web/live/subscription_settings.ex@@ -109,12 +109,18 @@ defmodule PlausibleWeb.Live.SubscriptionSettings do<p class="text-sm text-gray-600 dark:text-gray-400">Up to {PlausibleWeb.AuthView.subscription_quota(@subscription)} monthly pageviews</p>- <%= if @subscription.next_bill_amount && @subscription.next_bill_date do %>- <p class="text-sm text-gray-600 dark:text-gray-400">- {PlausibleWeb.BillingView.present_currency(@subscription.currency_code)}{@subscription.next_bill_amount} / {present_subscription_interval(- @subscription- )} • Renews on {Calendar.strftime(@subscription.next_bill_date, "%b %-d, %Y")}- </p>+ <%= cond do %>+ <% Plausible.Billing.Subscription.manual_subscription?(@subscription) && @subscription.next_bill_date -> %>+ <p class="text-sm text-gray-600 dark:text-gray-400">+ Paid until {Calendar.strftime(@subscription.next_bill_date, "%b %-d, %Y")}+ </p>+ <% @subscription.next_bill_amount && @subscription.next_bill_date -> %>+ <p class="text-sm text-gray-600 dark:text-gray-400">+ {PlausibleWeb.BillingView.present_currency(@subscription.currency_code)}{@subscription.next_bill_amount} / {present_subscription_interval(+ @subscription+ )} • Renews on {Calendar.strftime(@subscription.next_bill_date, "%b %-d, %Y")}+ </p>+ <% true -> %><% end %></div><div class="flex gap-2">diff --git a/test/plausible/billing/billing_test.exs b/test/plausible/billing/billing_test.exsindex 92bf4de6c0..c4319ec4a6 100644--- a/test/plausible/billing/billing_test.exs+++ b/test/plausible/billing/billing_test.exs@@ -364,6 +364,181 @@ defmodule Plausible.BillingTest doendend+ describe "latest_enterprise_plan" do+ test "returns the most recently created enterprise plan of the team" do+ now = NaiveDateTime.utc_now()+ {:ok, team} = Plausible.Teams.get_or_create(new_user())++ insert(:enterprise_plan, team: team, paddle_plan_id: "123", inserted_at: now)++ insert(:enterprise_plan,+ team: team,+ paddle_plan_id: "456",+ inserted_at: NaiveDateTime.shift(now, hour: -10)+ )++ insert(:enterprise_plan,+ team: team,+ paddle_plan_id: "789",+ inserted_at: NaiveDateTime.shift(now, minute: -2)+ )++ assert Billing.latest_enterprise_plan(team).paddle_plan_id == "123"+ end++ test "returns nil when the team has no enterprise plans" do+ {:ok, team} = Plausible.Teams.get_or_create(new_user())+ {:ok, other_team} = Plausible.Teams.get_or_create(new_user())+ insert(:enterprise_plan, team: other_team)++ refute Billing.latest_enterprise_plan(team)+ end+ end++ describe "create_manual_subscription" do+ @describetag :ee_only++ test "creates an active subscription outside of Paddle and relabels the plan" do+ {:ok, team} = Plausible.Teams.get_or_create(new_user())++ plan =+ insert(:enterprise_plan,+ team_id: team.id,+ paddle_plan_id: "123456",+ billing_interval: :yearly+ )++ assert {:ok, _} = Billing.create_manual_subscription(team, plan)++ subscription = Repo.get_by!(Subscription, team_id: team.id)+ today = Date.utc_today()++ assert Subscription.manual_subscription?(subscription)+ assert subscription.status == :active+ assert subscription.paddle_plan_id == "manual-subscription"+ assert is_nil(subscription.paddle_subscription_id)+ assert is_nil(subscription.update_url)+ assert is_nil(subscription.cancel_url)+ assert subscription.currency_code == "XXX"+ assert subscription.next_bill_amount == "-1"+ assert subscription.last_bill_date == today+ assert subscription.next_bill_date == Date.shift(today, year: 1)++ assert Repo.reload!(plan).paddle_plan_id == "manual-subscription"+ assert Plausible.Billing.Plans.get_subscription_plan(subscription).id == plan.id+ end++ test "refuses to subscribe to a plan that is not the latest one" do+ {:ok, team} = Plausible.Teams.get_or_create(new_user())++ older_plan =+ insert(:enterprise_plan,+ team_id: team.id,+ inserted_at: NaiveDateTime.shift(NaiveDateTime.utc_now(), day: -1)+ )++ insert(:enterprise_plan, team_id: team.id)++ assert {:error, :not_latest_plan} = Billing.create_manual_subscription(team, older_plan)++ refute Repo.get_by(Subscription, team_id: team.id)+ refute Repo.reload!(older_plan).paddle_plan_id == "manual-subscription"+ end++ test "returns an error when another plan of the team already has the manual plan ID" do+ {:ok, team} = Plausible.Teams.get_or_create(new_user())++ insert(:enterprise_plan,+ team_id: team.id,+ paddle_plan_id: "manual-subscription",+ inserted_at: NaiveDateTime.shift(NaiveDateTime.utc_now(), day: -1)+ )++ plan = insert(:enterprise_plan, team_id: team.id, billing_interval: :yearly)++ assert {:error, changeset} = Billing.create_manual_subscription(team, plan)+ assert {"has already been taken", _} = changeset.errors[:paddle_plan_id]++ refute Repo.get_by(Subscription, team_id: team.id)+ refute Repo.reload!(plan).paddle_plan_id == "manual-subscription"+ end++ test "refuses to subscribe to a monthly plan" do+ {:ok, team} = Plausible.Teams.get_or_create(new_user())+ plan = insert(:enterprise_plan, team_id: team.id, billing_interval: :monthly)++ assert {:error, :not_yearly} = Billing.create_manual_subscription(team, plan)++ refute Repo.get_by(Subscription, team_id: team.id)+ refute Repo.reload!(plan).paddle_plan_id == "manual-subscription"+ end++ test "refuses to create a second manual subscription" do+ {:ok, team} = Plausible.Teams.get_or_create(new_user())++ # Intentionally preload and make it stale. The function under test+ # should not use the preloaded value as it might be outdated.+ team = Plausible.Teams.with_subscription(team)++ plan = insert(:enterprise_plan, team_id: team.id, billing_interval: :yearly)++ assert {:ok, _} = Billing.create_manual_subscription(team, plan)++ assert {:error, :already_manual} =+ Billing.create_manual_subscription(team, Repo.reload!(plan))++ assert Repo.aggregate(from(s in Subscription, where: s.team_id == ^team.id), :count) == 1+ end++ for status <- [:active, :past_due, :paused] do+ test "refuses when the team has a #{status} Paddle subscription" do+ team = new_user() |> subscribe_to_growth_plan(status: unquote(status)) |> team_of()+ plan = insert(:enterprise_plan, team_id: team.id)++ assert {:error, :active_subscription} = Billing.create_manual_subscription(team, plan)++ refute Subscription.manual_subscription?(Repo.get_by!(Subscription, team_id: team.id))+ refute Repo.reload!(plan).paddle_plan_id == "manual-subscription"+ end+ end++ test "allows replacing a cancelled Paddle subscription" do+ team =+ new_user()+ |> subscribe_to_growth_plan(+ status: :deleted,+ inserted_at: NaiveDateTime.shift(NaiveDateTime.utc_now(), day: -1)+ )+ |> team_of()++ plan = insert(:enterprise_plan, team_id: team.id, billing_interval: :yearly)++ assert {:ok, _} = Billing.create_manual_subscription(team, plan)++ assert Subscription.manual_subscription?(+ Plausible.Teams.with_subscription(team).subscription+ )+ end++ test "allows replacing a legacy free subscription" do+ {:ok, team} = Plausible.Teams.get_or_create(new_user())++ insert(:subscription,+ team: team,+ paddle_plan_id: "free_10k",+ inserted_at: NaiveDateTime.shift(NaiveDateTime.utc_now(), day: -1)+ )++ plan = insert(:enterprise_plan, team_id: team.id, billing_interval: :yearly)++ assert {:ok, _} = Billing.create_manual_subscription(team, plan)++ assert Subscription.manual_subscription?(+ Plausible.Teams.with_subscription(team).subscription+ )+ end+ end+describe "subscription_updated" dotest "updates an existing subscription" douser = new_user()diff --git a/test/plausible/billing/enterprise_plan_test.exs b/test/plausible/billing/enterprise_plan_test.exsindex 288aa03e85..57243c636b 100644--- a/test/plausible/billing/enterprise_plan_test.exs+++ b/test/plausible/billing/enterprise_plan_test.exs@@ -2,14 +2,14 @@ defmodule Plausible.Billing.EnterprisePlanTest douse Plausible.DataCasealias Plausible.Billing.EnterprisePlan- test "changeset/2 loads and dumps the list of features" do+ test "create_changeset/2 loads and dumps the list of features" doteam = new_user(trial_expiry_date: Date.utc_today()) |> team_of()plan = build(:enterprise_plan, team_id: team.id)attrs = %{features: ["props", "stats_api"]}assert {:ok, enterprise_plan} =plan- |> EnterprisePlan.changeset(attrs)+ |> EnterprisePlan.create_changeset(attrs)|> Plausible.Repo.insert()assert %EnterprisePlan{@@ -21,28 +21,28 @@ defmodule Plausible.Billing.EnterprisePlanTest do} = Plausible.Repo.get(EnterprisePlan, enterprise_plan.id)end- test "changeset/2 fails when feature does not exist" do+ test "create_changeset/2 fails when feature does not exist" doteam = new_user(trial_expiry_date: Date.utc_today()) |> team_of()plan = build(:enterprise_plan, team_id: team.id)attrs = %{features: ["ga4_import"]}assert {:error, changeset} =plan- |> EnterprisePlan.changeset(attrs)+ |> EnterprisePlan.create_changeset(attrs)|> Plausible.Repo.insert()assert {"is invalid", [type: {:array, Plausible.Billing.Ecto.Feature}, validation: :cast]} ==changeset.errors[:features]end- test "changeset/2 loads and dumps limits" do+ test "create_changeset/2 loads and dumps limits" doteam = new_user(trial_expiry_date: Date.utc_today()) |> team_of()plan = build(:enterprise_plan, team_id: team.id)attrs = %{team_member_limit: :unlimited, monthly_pageview_limit: 10_000}assert {:ok, enterprise_plan} =plan- |> EnterprisePlan.changeset(attrs)+ |> EnterprisePlan.create_changeset(attrs)|> Plausible.Repo.insert()assert %EnterprisePlan{team_member_limit: :unlimited, monthly_pageview_limit: 10_000} =@@ -51,4 +51,33 @@ defmodule Plausible.Billing.EnterprisePlanTest doassert %EnterprisePlan{team_member_limit: :unlimited, monthly_pageview_limit: 10_000} =Plausible.Repo.get(EnterprisePlan, enterprise_plan.id)end++ test "update_changeset/2 leaves paddle_plan_id unchanged" do+ team = new_user(trial_expiry_date: Date.utc_today()) |> team_of()+ plan = insert(:enterprise_plan, team_id: team.id, paddle_plan_id: "123")++ assert {:ok, %EnterprisePlan{paddle_plan_id: "123", site_limit: 50}} =+ plan+ |> EnterprisePlan.update_changeset(%{paddle_plan_id: "456", site_limit: 50})+ |> Plausible.Repo.update()+ end++ test "create_changeset/2 refuses a duplicate paddle_plan_id within a team" do+ team = new_user(trial_expiry_date: Date.utc_today()) |> team_of()+ other_team = new_user(trial_expiry_date: Date.utc_today()) |> team_of()++ insert(:enterprise_plan, team_id: team.id, paddle_plan_id: "123")++ assert {:error, changeset} =+ build(:enterprise_plan, team_id: team.id)+ |> EnterprisePlan.create_changeset(%{paddle_plan_id: "123"})+ |> Plausible.Repo.insert()++ assert {"has already been taken", _} = changeset.errors[:paddle_plan_id]++ assert {:ok, _} =+ build(:enterprise_plan, team_id: other_team.id)+ |> EnterprisePlan.create_changeset(%{paddle_plan_id: "123"})+ |> Plausible.Repo.insert()+ endenddiff --git a/test/plausible/billing/plans_test.exs b/test/plausible/billing/plans_test.exsindex 569f5d7743..1c17b2e898 100644--- a/test/plausible/billing/plans_test.exs+++ b/test/plausible/billing/plans_test.exs@@ -151,34 +151,11 @@ defmodule Plausible.Billing.PlansTest doassert %{growth: [_ | _], business: [_ | _]} = Plans.available_plans_for(subscription)end- test "latest_enterprise_plan_with_price/1" do- now = NaiveDateTime.utc_now()- user = new_user(trial_expiry_date: Date.utc_today())- team = team_of(user)-- subscribe_to_enterprise_plan(user,- paddle_plan_id: "123",- inserted_at: now,- subscription?: false- )-- subscribe_to_enterprise_plan(user,- paddle_plan_id: "456",- inserted_at: NaiveDateTime.shift(now, hour: -10),- subscription?: false- )-- subscribe_to_enterprise_plan(user,- paddle_plan_id: "789",- inserted_at: NaiveDateTime.shift(now, minute: -2),- subscription?: false- )-- {enterprise_plan, price} =- Plausible.Teams.Billing.latest_enterprise_plan_with_price(team, "127.0.0.1")-- assert enterprise_plan.paddle_plan_id == "123"- assert price == Money.new(:EUR, "123.00")+ test "get_price_for/2 returns the Paddle price of an enterprise plan" do+ team = new_user(trial_expiry_date: Date.utc_today()) |> team_of()+ enterprise_plan = insert(:enterprise_plan, team: team, paddle_plan_id: "123")++ assert Plans.get_price_for(enterprise_plan, "127.0.0.1") == Money.new(:EUR, "123.00")endenddiff --git a/test/plausible/help_scout_test.exs b/test/plausible/help_scout_test.exsindex eb8ed8dde4..1d2de2c3ad 100644--- a/test/plausible/help_scout_test.exs+++ b/test/plausible/help_scout_test.exs@@ -147,10 +147,10 @@ defmodule Plausible.HelpScoutTest do}} = HelpScout.get_details_for_customer("500", "1000")end- test "returns for user with paid subscription on free 10k plan" do+ test "returns for user with a subscription on free 10k plan" douser = %{email: email} = new_user(trial_expiry_date: Date.add(Date.utc_today(), -1))- subscribe_to_plan(user, "free_10k")+ subscribe_to_plan(user, "free_10k", paddle_subscription_id: nil)stub_help_scout_requests(email)@@ -158,7 +158,7 @@ defmodule Plausible.HelpScoutTest do%{status_link: _,status_label: "Paid",- plan_link: _,+ plan_link: "#",plan_label: "Free 10k"}} = HelpScout.get_details_for_customer("500", "1000")end@@ -200,6 +200,22 @@ defmodule Plausible.HelpScoutTest do}} = HelpScout.get_details_for_customer("500", "1000")end+ test "returns for user with manual subscription on yearly enterprise plan" do+ user = %{email: email} = new_user(trial_expiry_date: Date.add(Date.utc_today(), -1))+ team = team_of(user)+ plan = insert(:enterprise_plan, team: team, billing_interval: :yearly)+ {:ok, _} = Plausible.Billing.create_manual_subscription(team, plan)++ stub_help_scout_requests(email)++ assert {:ok,+ %{+ status_label: "Paid",+ plan_link: "#",+ plan_label: "1M Enterprise Plan (manual, yearly)"+ }} = HelpScout.get_details_for_customer("500", "1000")+ end+test "returns for user with subscription pending cancellation" douser = %{email: email} = new_user(trial_expiry_date: Date.add(Date.utc_today(), -1))diff --git a/test/plausible_web/controllers/billing_controller_test.exs b/test/plausible_web/controllers/billing_controller_test.exsindex af8444bb97..55bb295e65 100644--- a/test/plausible_web/controllers/billing_controller_test.exs+++ b/test/plausible_web/controllers/billing_controller_test.exs@@ -118,6 +118,15 @@ defmodule PlausibleWeb.BillingControllerTest do@configured_enterprise_plan_paddle_plan_id "123"+ describe "GET /upgrade-to-enterprise-plan (no enterprise plan configured)" do+ setup [:create_user, :log_in, :create_team]++ test "redirects to the choose plan page", %{conn: conn} do+ conn = get(conn, ~p"/billing/upgrade-to-enterprise-plan")+ assert redirected_to(conn) == ~p"/billing/choose-plan"+ end+ end+describe "GET /upgrade-to-enterprise-plan (no existing subscription)" dosetup [:create_user, :log_in, :configure_enterprise_plan]@@ -266,6 +275,23 @@ defmodule PlausibleWeb.BillingControllerTest doendend+ describe "GET /upgrade-to-enterprise-plan (manual subscription)" do+ setup [:create_user, :log_in, :create_team]++ @tag :ee_only+ test "renders contact note", %{conn: conn, team: team} do+ plan = insert(:enterprise_plan, team: team, billing_interval: :yearly)+ {:ok, _} = Plausible.Billing.create_manual_subscription(team, plan)++ doc =+ conn+ |> get(~p"/billing/upgrade-to-enterprise-plan")+ |> html_response(200)++ assert doc =~ "Looking to adjust your plan?"+ end+ end+describe "GET /upgrade-to-enterprise-plan (subscription past_due or paused)" dosetup [:create_user, :log_in, :configure_enterprise_plan]diff --git a/test/plausible_web/controllers/settings_controller_test.exs b/test/plausible_web/controllers/settings_controller_test.exsindex bfdd0609f5..0452a66c24 100644--- a/test/plausible_web/controllers/settings_controller_test.exs+++ b/test/plausible_web/controllers/settings_controller_test.exs@@ -63,6 +63,30 @@ defmodule PlausibleWeb.SettingsControllerTest doassert html_response(conn, 200) =~ "/ year"end+ @tag :ee_only+ test "shows manual subscription without currency and price", %{conn: conn, user: user} do+ configure_enterprise_plan(user,+ paddle_plan_id: "manual-subscription",+ subscription: [+ paddle_subscription_id: nil,+ update_url: nil,+ cancel_url: nil,+ currency_code: "EUR",+ next_bill_amount: "-1",+ next_bill_date: ~D[2027-10-05]+ ]+ )++ html = conn |> get(~p"/settings/billing/subscription") |> html_response(200)++ assert html =~ "20M monthly pageviews"+ assert html =~ "Paid until Oct 5, 2027"+ refute html =~ "Renews on"+ refute html =~ "€"+ refute html =~ "-1 /"+ refute html =~ "/ year"+ end+@tag :ee_onlytest "shows current enterprise plan subscription when user has a new one to upgrade to", %{conn: conn,diff --git a/test/plausible_web/live/customer_support/teams_test.exs b/test/plausible_web/live/customer_support/teams_test.exsindex bbeabfd107..ea6cdb8672 100644--- a/test/plausible_web/live/customer_support/teams_test.exs+++ b/test/plausible_web/live/customer_support/teams_test.exs@@ -836,7 +836,7 @@ defmodule PlausibleWeb.Live.CustomerSupport.TeamsTest do|> element(~s|form#save-plan|)|> render_change(%{"enterprise_plan" => %{- "paddle_plan_id" => "updated-plan-456",+ "paddle_plan_id" => "original-plan","billing_interval" => "yearly","monthly_pageview_limit" => "15000000","site_limit" => "500",@@ -862,7 +862,7 @@ defmodule PlausibleWeb.Live.CustomerSupport.TeamsTest doassert text(html) =~ "Plan updated"updated_plan = Plausible.Repo.reload!(plan)- assert updated_plan.paddle_plan_id == "updated-plan-456"+ assert updated_plan.paddle_plan_id == "original-plan"assert updated_plan.billing_interval == :yearlyassert updated_plan.monthly_pageview_limit == 15_000_000assert updated_plan.site_limit == 500@@ -876,7 +876,7 @@ defmodule PlausibleWeb.Live.CustomerSupport.TeamsTest dorefute element_exists?(html, ~s|form#save-plan|)- assert text(html) =~ "updated-plan-456"+ assert text(html) =~ "original-plan"assert text(html) =~ "yearly"assert text(html) =~ "15,000,000"assert text(html) =~ "500"@@ -908,9 +908,9 @@ defmodule PlausibleWeb.Live.CustomerSupport.TeamsTest do|> element(~s|form#save-plan|)|> render_submit(%{"enterprise_plan" => %{- "paddle_plan_id" => "",+ "paddle_plan_id" => "valid-plan","billing_interval" => "monthly",- "monthly_pageview_limit" => "1000000",+ "monthly_pageview_limit" => "","site_limit" => "100","team_member_limit" => "10","hourly_api_request_limit" => "1000"@@ -923,7 +923,7 @@ defmodule PlausibleWeb.Live.CustomerSupport.TeamsTest doassert element_exists?(html, ~s|form#save-plan|)unchanged_plan = Plausible.Repo.reload!(plan)- assert unchanged_plan.paddle_plan_id == "valid-plan"+ assert unchanged_plan.monthly_pageview_limit == 1_000_000endtest "cancel edit returns to plan list", %{conn: conn, user: user} do@@ -1068,6 +1068,96 @@ defmodule PlausibleWeb.Live.CustomerSupport.TeamsTest dorefute element_exists?(html, ~s|[data-test-id="plan-entry-plan-another"]|)end+ test "plan can be manually subscribed with a single confirmed click", %{+ conn: conn,+ user: user+ } do+ team = team_of(user)++ plan =+ insert(:enterprise_plan,+ team: team,+ paddle_plan_id: "plan-original",+ billing_interval: :yearly,+ monthly_pageview_limit: 1_000_000+ )++ {:ok, lv, html} = live(conn, open_team(team.id, tab: :billing))++ button = ~s|button[phx-click="manual-subscribe"][phx-value-id="#{plan.id}"]|+ assert element_exists?(html, button)+ assert text_of_attr(html, button, "data-confirm") =~ "outside of Paddle"+ refute element_exists?(html, "form#manual-subscribe")++ assert text(html) =~ "Subscription statusOn trial"++ lv |> element(button) |> render_click()++ flash = assert_redirect(lv, open_team(team.id, tab: :billing))+ assert flash["success"] == "Subscription created (manual)"++ {:ok, _lv, html} = live(conn, open_team(team.id, tab: :billing))++ plan = Plausible.Repo.reload!(plan)+ assert plan.paddle_plan_id == "manual-subscription"++ subscription = Plausible.Repo.get_by!(Plausible.Billing.Subscription, team_id: team.id)+ assert subscription.paddle_plan_id == plan.paddle_plan_id+ assert subscription.currency_code == "XXX"+ assert subscription.next_bill_amount == "-1"+ assert subscription.last_bill_date == Date.utc_today()+ assert subscription.next_bill_date == Date.shift(Date.utc_today(), year: 1)+ assert is_nil(subscription.paddle_subscription_id)++ assert text(html) =~ "Subscription statusActive"+ assert text(html) =~ "Subscription planManually billed enterprise"+ assert html =~ "MANUAL SUBSCRIPTION"+ refute element_exists?(html, button)++ assert text_of_element(html, ~s|[data-test-id="last-bill-date"]|) ==+ PlausibleWeb.TextHelpers.format_date(subscription.last_bill_date)++ assert text_of_element(html, ~s|[data-test-id="next-bill-date"]|) ==+ PlausibleWeb.TextHelpers.format_date(subscription.next_bill_date)+ end++ test "new plan can't be created while on a manual subscription", %{conn: conn, user: user} do+ team = team_of(user)+ plan = insert(:enterprise_plan, team: team, billing_interval: :yearly)+ {:ok, _} = Plausible.Billing.create_manual_subscription(team, plan)++ {:ok, lv, _html} = live(conn, open_team(team.id, tab: :billing))++ lv |> element("button#new-custom-plan") |> render_click()+ html = render(lv)++ assert text(html) =~+ "Creating a new plan is prohibited due to a manual subscription. Edit the existing enterprise plan instead."++ refute element_exists?(html, ~s|form[phx-submit="save-plan"]|)+ end++ test "only the latest plan can be manually subscribed to", %{conn: conn, user: user} do+ team = team_of(user)++ older_plan =+ insert(:enterprise_plan,+ team: team,+ inserted_at: NaiveDateTime.shift(NaiveDateTime.utc_now(), day: -1)+ )++ insert(:enterprise_plan, team: team)++ {:ok, lv, _html} = live(conn, open_team(team.id, tab: :billing))++ lv+ |> element(~s|button[phx-click="manual-subscribe"][phx-value-id="#{older_plan.id}"]|)+ |> render_click()++ assert text(render(lv)) =~ "Only the latest enterprise plan can get a manual subscription"+ refute Plausible.Repo.get_by(Plausible.Billing.Subscription, team_id: team.id)+ end+defp open_custom_plan(conn, team) do{:ok, lv, _html} = live(conn, open_team(team.id, tab: :billing))render(lv)