Refactor Plausible.Billing.Plans module (#3249)

This commit introduces a series of improvements on the Plans module including function renaming, documentation and readability. This is the groundwork for billing plans.

There should be no actual changes with this commit, therefore no changes in tests either.
pull/3255/head r2023.08.09-165
Vini Brasil 3 years ago committed by GitHub
parent ec747ad401
commit 059df171bc
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -17,19 +17,19 @@ defmodule Mix.Tasks.AnalyzePlans do
res =
Enum.map(res, fn {plan_id, count} ->
plan = Plausible.Billing.Plans.for_product_id(plan_id)
plan = Plausible.Billing.Plans.find(plan_id)
if plan do
is_monthly = plan_id == plan[:monthly_product_id]
is_monthly = plan_id == plan.monthly_product_id
monthly_revenue =
if is_monthly do
price(plan[:monthly_cost])
price(plan.monthly_cost)
else
price(plan[:yearly_cost]) / 12
price(plan.yearly_cost) / 12
end
{PlausibleWeb.StatsView.large_number_format(plan[:limit]), monthly_revenue, count}
{PlausibleWeb.StatsView.large_number_format(plan.limit), monthly_revenue, count}
end
end)
|> Enum.filter(& &1)

@ -1,80 +1,98 @@
defmodule Plausible.Billing.Plans do
use Plausible.Repo
defmodule Plausible.Billing.Plan do
@moduledoc false
@unlisted_plans_v1 [
%{limit: 150_000_000, yearly_product_id: "648089", yearly_cost: "$4800"}
]
@unlisted_plans_v2 [
%{limit: 10_000_000, monthly_product_id: "655350", monthly_cost: "$250"}
]
@sandbox_plans [
%{
limit: 10_000,
monthly_product_id: "19878",
yearly_product_id: "20127",
monthly_cost: "$6",
yearly_cost: "$60"
},
%{
limit: 100_000,
monthly_product_id: "20657",
yearly_product_id: "20658",
monthly_cost: "$12.34",
yearly_cost: "$120.34"
}
]
@type plan() ::
%{
@derive Jason.Encoder
@enforce_keys ~w(limit volume monthly_cost yearly_cost monthly_product_id yearly_product_id)a
defstruct @enforce_keys
@type t() ::
%__MODULE__{
limit: non_neg_integer(),
monthly_product_id: String.t(),
yearly_product_id: String.t(),
monthly_cost: String.t(),
yearly_cost: String.t()
volume: String.t(),
monthly_cost: String.t() | nil,
yearly_cost: String.t() | nil,
monthly_product_id: String.t() | nil,
yearly_product_id: String.t() | nil
}
| :enterprise
end
defmodule Plausible.Billing.Plans do
use Plausible.Repo
for f <- [
:plans_v1,
:plans_v2,
:plans_v3,
:unlisted_plans_v1,
:unlisted_plans_v2,
:sandbox_plans
] do
path = Application.app_dir(:plausible, ["priv", "#{f}.json"])
contents =
path
|> File.read!()
|> Jason.decode!(keys: :atoms!)
|> Enum.map(&Map.put(&1, :volume, PlausibleWeb.StatsView.large_number_format(&1.limit)))
|> Enum.map(&struct!(Plausible.Billing.Plan, &1))
Module.put_attribute(__MODULE__, f, contents)
Module.put_attribute(__MODULE__, :external_resource, path)
end
@spec for_user(Plausible.Auth.User.t()) :: [Plausible.Billing.Plan.t()]
@doc """
Returns a list of plans available for the user to choose.
def plans_for(user) do
As new versions of plans are introduced, users who were on old plans can
still choose from old plans.
"""
def for_user(user) do
user = Plausible.Users.with_subscription(user)
sandbox_plans = plans_sandbox()
v1_plans = plans_v1()
v2_plans = plans_v2()
v3_plans = plans_v3()
raw_plans =
cond do
contains?(v1_plans, user.subscription) ->
v1_plans
contains?(v2_plans, user.subscription) ->
v2_plans
contains?(v3_plans, user.subscription) ->
v3_plans
contains?(sandbox_plans, user.subscription) ->
sandbox_plans
true ->
cond do
Application.get_env(:plausible, :environment) == "dev" -> sandbox_plans
Timex.before?(user.inserted_at, ~D[2022-01-01]) -> v2_plans
true -> v3_plans
end
end
Enum.map(raw_plans, fn plan -> Map.put(plan, :volume, number_format(plan[:limit])) end)
cond do
find(user.subscription, @plans_v1) -> @plans_v1
find(user.subscription, @plans_v2) -> @plans_v2
find(user.subscription, @plans_v3) -> @plans_v3
find(user.subscription, plans_sandbox()) -> plans_sandbox()
Application.get_env(:plausible, :environment) == "dev" -> plans_sandbox()
Timex.before?(user.inserted_at, ~D[2022-01-01]) -> @plans_v2
true -> @plans_v3
end
end
def all_yearly_plan_ids do
Enum.map(all_plans(), fn plan -> plan[:yearly_product_id] end)
@spec yearly_product_ids() :: [String.t()]
@doc """
List yearly plans product IDs.
"""
def yearly_product_ids do
for %{yearly_product_id: yearly_product_id} <- all(),
is_binary(yearly_product_id),
do: yearly_product_id
end
def for_product_id(product_id) do
Enum.find(all_plans(), fn plan ->
product_id in [plan[:monthly_product_id], plan[:yearly_product_id]]
@spec find(String.t() | Plausible.Billing.Subscription.t(), [Plausible.Billing.Plan.t()]) ::
Plausible.Billing.Plan.t() | nil
@spec find(nil, any()) :: nil
@doc """
Finds a plan by product ID.
Returns nil when plan can't be found.
"""
def find(product_id_or_subscription, scope \\ all())
def find(nil, _scope) do
nil
end
def find(%Plausible.Billing.Subscription{} = subscription, scope) do
find(subscription.paddle_plan_id, scope)
end
def find(product_id, scope) do
Enum.find(scope, fn plan ->
product_id in [plan.monthly_product_id, plan.yearly_product_id]
end)
end
@ -82,14 +100,14 @@ defmodule Plausible.Billing.Plans do
do: "N/A"
def subscription_interval(subscription) do
case for_product_id(subscription.paddle_plan_id) do
case find(subscription.paddle_plan_id) do
nil ->
enterprise_plan = get_enterprise_plan(subscription)
enterprise_plan && enterprise_plan.billing_interval
plan ->
if subscription.paddle_plan_id == plan[:monthly_product_id] do
if subscription.paddle_plan_id == plan.monthly_product_id do
"monthly"
else
"yearly"
@ -100,7 +118,7 @@ defmodule Plausible.Billing.Plans do
def allowance(%Plausible.Billing.Subscription{paddle_plan_id: "free_10k"}), do: 10_000
def allowance(subscription) do
found = for_product_id(subscription.paddle_plan_id)
found = find(subscription.paddle_plan_id)
if found do
Map.fetch!(found, :limit)
@ -127,46 +145,29 @@ defmodule Plausible.Billing.Plans do
end
@enterprise_level_usage 10_000_000
@spec suggested_plan(Plausible.Auth.User.t(), non_neg_integer()) :: plan()
def suggested_plan(user, usage_during_cycle) do
@spec suggest(Plausible.Auth.User.t(), non_neg_integer()) :: Plausible.Billing.Plan.t()
@doc """
Returns the most appropriate plan for a user based on their usage during a
given cycle.
If the usage during the cycle exceeds the enterprise-level threshold, or if
the user already belongs to an enterprise plan, it suggests the :enterprise
plan.
Otherwise, it recommends the plan where the cycle usage falls just under the
plan's limit from the available options for the user.
"""
def suggest(user, usage_during_cycle) do
cond do
usage_during_cycle > @enterprise_level_usage -> :enterprise
Plausible.Auth.enterprise?(user) -> :enterprise
true -> Enum.find(plans_for(user), fn plan -> usage_during_cycle < plan[:limit] end)
true -> Enum.find(for_user(user), &(usage_during_cycle < &1.limit))
end
end
defp contains?(_plans, nil), do: false
defp contains?(plans, subscription) do
Enum.any?(plans, fn plan ->
plan[:monthly_product_id] == subscription.paddle_plan_id ||
plan[:yearly_product_id] == subscription.paddle_plan_id
end)
end
defp number_format(num) do
PlausibleWeb.StatsView.large_number_format(num)
end
defp all_plans() do
plans_v1() ++
@unlisted_plans_v1 ++ plans_v2() ++ @unlisted_plans_v2 ++ plans_v3() ++ plans_sandbox()
end
defp plans_v1() do
File.read!(Application.app_dir(:plausible) <> "/priv/plans_v1.json")
|> Jason.decode!(keys: :atoms)
end
defp plans_v2() do
File.read!(Application.app_dir(:plausible) <> "/priv/plans_v2.json")
|> Jason.decode!(keys: :atoms)
end
defp plans_v3() do
File.read!(Application.app_dir(:plausible) <> "/priv/plans_v3.json")
|> Jason.decode!(keys: :atoms)
defp all() do
@plans_v1 ++
@unlisted_plans_v1 ++ @plans_v2 ++ @unlisted_plans_v2 ++ @plans_v3 ++ plans_sandbox()
end
defp plans_sandbox() do

@ -42,7 +42,7 @@ defmodule Plausible.Billing.SiteLocker do
defp send_grace_period_end_email(user) do
{_, last_cycle} = Plausible.Billing.last_two_billing_cycles(user)
{_, last_cycle_usage} = Plausible.Billing.last_two_billing_months_usage(user)
suggested_plan = Plausible.Billing.Plans.suggested_plan(user, last_cycle_usage)
suggested_plan = Plausible.Billing.Plans.suggest(user, last_cycle_usage)
template =
PlausibleWeb.Email.dashboard_locked(

@ -79,7 +79,7 @@ defmodule PlausibleWeb.Email do
end
def trial_upgrade_email(user, day, {pageviews, custom_events}) do
suggested_plan = Plausible.Billing.Plans.suggested_plan(user, pageviews + custom_events)
suggested_plan = Plausible.Billing.Plans.suggest(user, pageviews + custom_events)
base_email()
|> to(user)

@ -1,7 +1,7 @@
<tr @click="volume = '<%= @plan[:volume] %>'" :class="{'border-2 border-green-300 bg-opacity-20 bg-green-300': volume === '<%= @plan[:volume] %>', 'border-b border-gray-200 cursor-pointer': volume !== '<%= @plan[:volume] %>'}">
<td class="px-6 py-4 text-sm leading-5 dark:text-gray-100" :class="{'font-bold': volume === '<%= @plan[:volume] %>'}"><%= @plan[:volume] %></td>
<td class="px-6 py-4 text-sm leading-5 dark:text-gray-100" :class="{'font-bold': volume === '<%= @plan[:volume] %>'}">
<span x-show="billingCycle === 'monthly'"><span x-text="priceFor(<%= @plan[:monthly_product_id] %>)"></span> / mo</span>
<span x-cloak x-show="billingCycle === 'yearly'"><span x-text="priceFor(<%= @plan[:yearly_product_id] %>)"></span> / yr</span>
<tr @click="volume = '<%= @plan.volume %>'" :class="{'border-2 border-green-300 bg-opacity-20 bg-green-300': volume === '<%= @plan.volume %>', 'border-b border-gray-200 cursor-pointer': volume !== '<%= @plan.volume %>'}">
<td class="px-6 py-4 text-sm leading-5 dark:text-gray-100" :class="{'font-bold': volume === '<%= @plan.volume %>'}"><%= @plan.volume %></td>
<td class="px-6 py-4 text-sm leading-5 dark:text-gray-100" :class="{'font-bold': volume === '<%= @plan.volume %>'}">
<span x-show="billingCycle === 'monthly'"><span x-text="priceFor(<%= @plan.monthly_product_id %>)"></span> / mo</span>
<span x-cloak x-show="billingCycle === 'yearly'"><span x-text="priceFor(<%= @plan.yearly_product_id %>)"></span> / yr</span>
</td>
</tr>

@ -2,7 +2,7 @@
<script>
plans = function() {
return {
rawPlans: <%= raw Jason.encode!(Plausible.Billing.Plans.plans_for(@conn.assigns[:current_user])) %>,
rawPlans: <%= raw Jason.encode!(Plausible.Billing.Plans.for_user(@conn.assigns[:current_user])) %>,
localizedPlans: null,
volume: '10k',
billingCycle: 'monthly',
@ -88,7 +88,7 @@
</tr>
</thead>
<tbody class="bg-white dark:bg-gray-800">
<%= for plan <- Plausible.Billing.Plans.plans_for(@conn.assigns[:current_user]) do %>
<%= for plan <- Plausible.Billing.Plans.for_user(@conn.assigns[:current_user]) do %>
<%= render("_plan_option.html", plan: plan) %>
<% end %>
</tbody>

@ -2,7 +2,7 @@
<script>
plans = function() {
return {
rawPlans: <%= raw Jason.encode!(Plausible.Billing.Plans.plans_for(@user)) %>,
rawPlans: <%= raw Jason.encode!(Plausible.Billing.Plans.for_user(@user)) %>,
localizedPlans: null,
volume: '10k',
billingCycle: 'monthly',
@ -85,7 +85,7 @@
</tr>
</thead>
<tbody class="bg-white dark:bg-gray-800">
<%= for plan <- Plausible.Billing.Plans.plans_for(@user) do %>
<%= for plan <- Plausible.Billing.Plans.for_user(@user) do %>
<%= render("_plan_option.html", plan: plan) %>
<% end %>
</tbody>

@ -6,7 +6,7 @@ In the last billing cycle (<%= date_format(@last_cycle.first) %> to <%= date_for
<%= if @suggested_plan == :enterprise do %>
This is more than our standard plans, so please reply back to this email to get a quote for your volume.
<% else %>
Based on that we recommend you select the <%= @suggested_plan[:volume] %>/mo plan.
Based on that we recommend you select the <%= @suggested_plan.volume %>/mo plan.
<br /><br />
<a href="https://plausible.io/settings">Click here</a> to go to your account settings. You can upgrade your subscription tier by clicking the 'Change plan' link.
<% end %>

@ -8,7 +8,7 @@ In the last billing cycle (<%= date_format(@last_cycle.first) %> to <%= date_for
<%= if @suggested_plan == :enterprise do %>
This is more than our standard plans, so please reply back to this email to get a quote for your volume.
<% else %>
Based on that we recommend you select the <%= @suggested_plan[:volume] %>/mo plan.
Based on that we recommend you select the <%= @suggested_plan.volume %>/mo plan.
<br /><br />
You can upgrade your subscription using our self-serve platform. The new charge will be prorated to reflect the amount you have already paid and the time until your current subscription is supposed to expire.
<br /><br />

@ -2,7 +2,7 @@ Thanks for exploring Plausible, a simple and privacy-friendly alternative to Goo
<br /><br />
In the last month, your account has used <%= PlausibleWeb.AuthView.delimit_integer(@usage) %> billable pageviews<%= if @custom_events > 0, do: " and custom events in total", else: "" %>.
<%= if @usage <= 10_000_000 do %>
Based on that we recommend you select the <%= @suggested_plan[:volume] %>/mo plan.
Based on that we recommend you select the <%= @suggested_plan.volume %>/mo plan.
<br /><br />
<%= link("Upgrade now", to: "#{plausible_url()}/billing/upgrade") %>
<br /><br />

@ -90,7 +90,7 @@ defmodule Plausible.Workers.CheckUsage do
defp check_regular_subscriber(subscriber, billing_mod) do
case check_pageview_limit(subscriber, billing_mod) do
{:over_limit, {last_cycle, last_cycle_usage}} ->
suggested_plan = Plausible.Billing.Plans.suggested_plan(subscriber, last_cycle_usage)
suggested_plan = Plausible.Billing.Plans.suggest(subscriber, last_cycle_usage)
template =
PlausibleWeb.Email.over_limit_email(

@ -2,7 +2,7 @@ defmodule Plausible.Workers.NotifyAnnualRenewal do
use Plausible.Repo
use Oban.Worker, queue: :notify_annual_renewal
@yearly_plans Plausible.Billing.Plans.all_yearly_plan_ids()
@yearly_plans Plausible.Billing.Plans.yearly_product_ids()
@impl Oban.Worker
@doc """

@ -0,0 +1,16 @@
[
{
"limit":10000,
"monthly_product_id":"19878",
"yearly_product_id":"20127",
"monthly_cost":"$6",
"yearly_cost":"$60"
},
{
"limit":100000,
"monthly_product_id":"20657",
"yearly_product_id":"20658",
"monthly_cost":"$12.34",
"yearly_cost":"$120.34"
}
]

@ -0,0 +1,9 @@
[
{
"limit":150000000,
"yearly_product_id":"648089",
"yearly_cost":"$4800",
"monthly_product_id":null,
"monthly_cost":null
}
]

@ -0,0 +1,9 @@
[
{
"limit":10000000,
"monthly_product_id":"655350",
"monthly_cost":"$250",
"yearly_product_id":null,
"yearly_cost":null
}
]

@ -6,29 +6,29 @@ defmodule Plausible.Billing.PlansTest do
@v2_plan_id "654177"
@v3_plan_id "749342"
describe "plans_for" do
describe "for_user" do
test "shows v1 pricing for users who are already on v1 pricing" do
user = insert(:user, subscription: build(:subscription, paddle_plan_id: @v1_plan_id))
assert List.first(Plans.plans_for(user))[:monthly_product_id] == @v1_plan_id
assert List.first(Plans.for_user(user)).monthly_product_id == @v1_plan_id
end
test "shows v2 pricing for users who are already on v2 pricing" do
user = insert(:user, subscription: build(:subscription, paddle_plan_id: @v2_plan_id))
assert List.first(Plans.plans_for(user))[:monthly_product_id] == @v2_plan_id
assert List.first(Plans.for_user(user)).monthly_product_id == @v2_plan_id
end
test "shows v2 pricing for users who signed up in 2021" do
user = insert(:user, inserted_at: ~N[2021-12-31 00:00:00])
assert List.first(Plans.plans_for(user))[:monthly_product_id] == @v2_plan_id
assert List.first(Plans.for_user(user)).monthly_product_id == @v2_plan_id
end
test "shows v3 pricing for everyone else" do
user = insert(:user)
assert List.first(Plans.plans_for(user))[:monthly_product_id] == @v3_plan_id
assert List.first(Plans.for_user(user)).monthly_product_id == @v3_plan_id
end
end
@ -87,34 +87,70 @@ defmodule Plausible.Billing.PlansTest do
test "returns suggested plan based on usage" do
user = insert(:user, subscription: build(:subscription, paddle_plan_id: @v1_plan_id))
assert %{
assert %Plausible.Billing.Plan{
limit: 100_000,
monthly_cost: "$12",
monthly_product_id: "558745",
volume: "100k",
yearly_cost: "$96",
yearly_product_id: "590752"
} == Plans.suggested_plan(user, 10_000)
} == Plans.suggest(user, 10_000)
assert %{
assert %Plausible.Billing.Plan{
limit: 200_000,
monthly_cost: "$18",
monthly_product_id: "597485",
volume: "200k",
yearly_cost: "$144",
yearly_product_id: "597486"
} == Plans.suggested_plan(user, 100_000)
} == Plans.suggest(user, 100_000)
end
test "returns nil when user has enterprise-level usage" do
user = insert(:user, subscription: build(:subscription, paddle_plan_id: @v1_plan_id))
assert :enterprise == Plans.suggested_plan(user, 100_000_000)
assert :enterprise == Plans.suggest(user, 100_000_000)
end
test "returns nil when user is on an enterprise plan" do
user = insert(:user, subscription: build(:subscription, paddle_plan_id: @v1_plan_id))
_enterprise_plan = insert(:enterprise_plan, user_id: user.id, billing_interval: :yearly)
assert :enterprise == Plans.suggested_plan(user, 10_000)
assert :enterprise == Plans.suggest(user, 10_000)
end
end
describe "yearly_product_ids/0" do
test "lists yearly plan ids" do
assert [
"572810",
"590752",
"597486",
"597488",
"597643",
"597310",
"597312",
"642354",
"642356",
"650653",
"648089",
"653232",
"653234",
"653236",
"653239",
"653242",
"653254",
"653256",
"653257",
"653258",
"653259",
"749343",
"749345",
"749347",
"749349",
"749352",
"749355",
"749357",
"749359"
] == Plans.yearly_product_ids()
end
end
end

Loading…
Cancel
Save