File size: 9,772 Bytes
3e21b19 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 | 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,
managing subscription status, and updating team-related billing state.
"""
use Plausible
use Plausible.Repo
alias Plausible.Auth
alias Plausible.Billing.Subscription
alias Plausible.Teams
defmacro allowed_roles(), do: [:owner, :billing]
def subscription_created(params) do
Repo.transaction(fn ->
handle_subscription_created(params)
end)
end
def subscription_updated(params) do
Repo.transaction(fn ->
handle_subscription_updated(params)
end)
end
def subscription_cancelled(params) do
Repo.transaction(fn ->
handle_subscription_cancelled(params)
end)
end
def subscription_payment_succeeded(params) do
Repo.transaction(fn ->
handle_subscription_payment_succeeded(params)
end)
end
def change_plan_preview(subscription, new_plan_id) do
case paddle_api().update_subscription_preview(
subscription.paddle_subscription_id,
new_plan_id
) do
{:ok, response} ->
{:ok, response}
{:error, reason} ->
{:error, reason}
end
end
defp handle_subscription_created(params) do
team = get_team!(params)
subscription_params =
params
|> format_subscription()
|> add_last_bill_date(params)
changeset = Subscription.create_changeset(team, subscription_params)
case Repo.insert(changeset,
on_conflict: :nothing,
conflict_target: :paddle_subscription_id
) do
{:ok, %{id: nil}} ->
handle_conflict(
"subscription_created",
subscription_params.paddle_subscription_id,
changeset
)
{:ok, subscription} ->
after_subscription_update(subscription)
end
end
defp handle_subscription_updated(params) do
subscription = Repo.get_by(Subscription, paddle_subscription_id: params["subscription_id"])
# In a situation where the subscription is paused and a payment succeeds, we
# get notified of two "subscription_updated" webhook alerts from Paddle at the
# same time.
#
# * one with an `old_status` of "paused", and a `status` of "past_due"
# * the other with an `old_status` of "past_due", and a `status` of "active"
#
# https://developer.paddle.com/classic/guides/zg9joji1mzu0mduy-payment-failures
#
# Relying on the time when the webhooks are sent has caused issues where
# subscriptions have ended up `past_due` after a successful payment. Therefore,
# we're now explicitly ignoring the first webhook (with the update that's not
# relevant to us).
irrelevant? = params["old_status"] == "paused" && params["status"] == "past_due"
if subscription && not irrelevant? do
params = format_subscription(params)
subscription
|> Subscription.changeset(params)
|> Repo.update!()
|> after_subscription_update()
end
end
defp handle_subscription_cancelled(params) do
subscription =
Subscription
|> Repo.get_by(paddle_subscription_id: params["subscription_id"])
|> Repo.preload(team: [:owners, :billing_members])
if subscription do
changeset =
Subscription.changeset(subscription, %{
status: params["status"]
})
updated = Repo.update!(changeset)
for recipient <- subscription.team.owners ++ subscription.team.billing_members do
recipient
|> PlausibleWeb.Email.cancellation_email()
|> Plausible.Mailer.send()
end
updated
end
end
defp handle_subscription_payment_succeeded(params) do
subscription = Repo.get_by(Subscription, paddle_subscription_id: params["subscription_id"])
if subscription do
{:ok, api_subscription} = paddle_api().get_subscription(subscription.paddle_subscription_id)
amount =
:erlang.float_to_binary(api_subscription["next_payment"]["amount"] / 1, decimals: 2)
subscription =
subscription
|> Subscription.changeset(%{
next_bill_amount: amount,
next_bill_date: api_subscription["next_payment"]["date"],
last_bill_date: api_subscription["last_payment"]["date"]
})
|> Repo.update!()
|> Repo.preload(:team)
Plausible.Teams.update_accept_traffic_until(subscription.team)
subscription
end
end
defp get_team!(%{"passthrough" => passthrough}) do
case parse_passthrough!(passthrough) do
{:team_id, team_id} ->
Teams.get!(team_id)
{:user_id, user_id} ->
# Given a guest or non-owner member user initiates the new subscription payment
# and becomes an owner of an existing team already with a subscription in between,
# this could result in assigning this new subscription to the newly owned team,
# effectively "shadowing" any old one.
#
# That's why we are always defaulting to creating a new "My Personal Sites" team regardless
# if they were owner of one before or not.
Auth.User
|> Repo.get!(user_id)
|> Teams.force_create_my_team()
end
end
defp get_team!(_params) do
raise "Missing passthrough"
end
defp parse_passthrough!(passthrough) do
{user_id, team_id} =
case String.split(to_string(passthrough), ";") do
["ee:true", "user:" <> user_id, "team:" <> team_id] ->
{user_id, team_id}
["ee:true", "user:" <> user_id] ->
{user_id, "0"}
_ ->
raise "Invalid passthrough sent via Paddle: #{inspect(passthrough)}"
end
case {Integer.parse(user_id), Integer.parse(team_id)} do
{{user_id, ""}, {0, ""}} when user_id > 0 ->
{:user_id, user_id}
{{_user_id, ""}, {team_id, ""}} when team_id > 0 ->
{:team_id, team_id}
_ ->
raise "Invalid passthrough sent via Paddle: #{inspect(passthrough)}"
end
end
defp format_subscription(params) do
%{
paddle_subscription_id: params["subscription_id"],
paddle_plan_id: params["subscription_plan_id"],
cancel_url: params["cancel_url"],
update_url: params["update_url"],
status: params["status"],
next_bill_date: params["next_bill_date"],
next_bill_amount: params["unit_price"] || params["new_unit_price"],
currency_code: params["currency"]
}
end
defp add_last_bill_date(subscription_params, paddle_params) do
with datetime_str when is_binary(datetime_str) <- paddle_params["event_time"],
{:ok, datetime} <- NaiveDateTime.from_iso8601(datetime_str),
date <- NaiveDateTime.to_date(datetime) do
Map.put(subscription_params, :last_bill_date, date)
else
_ -> subscription_params
end
end
@spec format_price(Money.t()) :: String.t()
def format_price(money) do
Money.to_string!(money, fractional_digits: 2, no_fraction_if_integer: true)
end
def paddle_api(), do: Application.fetch_env!(:plausible, :paddle_api)
def cancelled_subscription_notice_dismiss_id(id) do
"subscription_cancelled__#{id}"
end
defp after_subscription_update(subscription) do
team =
Teams.Team
|> Repo.get!(subscription.team_id)
|> Teams.with_subscription()
|> Repo.preload(:owners)
if subscription.id != team.subscription.id do
Sentry.capture_message("Susbscription ID mismatch",
extra: %{subscription: inspect(subscription), team_id: team.id}
)
end
team
|> Plausible.Teams.update_accept_traffic_until()
|> Plausible.Teams.remove_grace_period()
|> Plausible.Teams.maybe_reset_next_upgrade_override()
|> tap(&Plausible.Billing.SiteLocker.update_for/1)
|> maybe_adjust_api_key_limits()
end
defp maybe_adjust_api_key_limits(team) do
plan =
Repo.get_by(Plausible.Billing.EnterprisePlan,
team_id: team.id,
paddle_plan_id: team.subscription.paddle_plan_id
)
if plan do
Repo.update_all(
from(t in Teams.Team, where: t.id == ^team.id),
set: [hourly_api_request_limit: plan.hourly_api_request_limit]
)
end
team
end
defp handle_conflict(webhook_type, paddle_subscription_id, changeset) do
existing =
Repo.get_by!(Subscription,
paddle_subscription_id: paddle_subscription_id
)
diff = changeset_diff(changeset, existing)
if diff != %{} do
Sentry.capture_message(
"Duplicate #{webhook_type} webhook for paddle_subscription_id=#{existing.paddle_subscription_id}.",
extra: %{
paddle_subscription_id: existing.paddle_subscription_id,
team_id: existing.team_id,
diff: diff
}
)
end
existing
end
defp changeset_diff(%Ecto.Changeset{changes: changes}, existing) do
for {key, incoming_val} <- changes,
not is_struct(incoming_val, Ecto.Changeset),
existing_val = Map.get(existing, key),
existing_val != incoming_val,
into: %{},
do: {key, %{existing: existing_val, incoming: incoming_val}}
end
def dashboard_locked_notice_title(), do: "Dashboard locked"
def active_grace_period_notice_title(), do: "You have outgrown your Plausible subscription tier"
def subscription_cancelled_notice_title(), do: "Subscription cancelled"
def subscription_past_due_notice_title(), do: "Payment failed"
def subscription_paused_notice_title(), do: "Subscription paused"
def upgrade_ineligible_notice_title(), do: "No sites owned"
def pending_site_ownerships_notice_title(), do: "Pending ownership transfers"
end
|