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
Signify Paddle Classic usage (first stage) (#6814)
Adamedde0a081b99
diff --git a/config/config.exs b/config/config.exsindex 6a049100b1..45b1efeacd 100644--- a/config/config.exs+++ b/config/config.exs@@ -49,7 +49,7 @@ config :ref_inspector,database_path: "priv/ref_inspector"config :plausible,- paddle_api: Plausible.Billing.PaddleApi,+ paddle_classic_api: Plausible.Billing.PaddleClassic.Api,google_api: Plausible.Google.API,verification_checks_mod: Plausible.InstallationSupport.Verification.Checksdiff --git a/config/dev.exs b/config/dev.exsindex ebeca6945c..7f3deba9bf 100644--- a/config/dev.exs+++ b/config/dev.exs@@ -28,7 +28,7 @@ config :plausible, PlausibleWeb.Endpoint,]config :plausible,- paddle_api: Plausible.Billing.DevPaddleApiMock,+ paddle_classic_api: Plausible.Billing.PaddleClassic.DevApiMock,verification_checks_mod: Plausible.InstallationSupport.Verification.ChecksMockconfig :phoenix, :stacktrace_depth, 20diff --git a/config/e2e_test.exs b/config/e2e_test.exsindex dada94766e..e43d69e48c 100644--- a/config/e2e_test.exs+++ b/config/e2e_test.exs@@ -5,7 +5,7 @@ config :plausible, PlausibleWeb.Endpoint,check_origin: falseconfig :plausible,- paddle_api: Plausible.Billing.DevPaddleApiMock,+ paddle_classic_api: Plausible.Billing.PaddleClassic.DevApiMock,google_api: Plausible.Google.API.Mock,verification_checks_mod: Plausible.InstallationSupport.Verification.ChecksMockdiff --git a/config/runtime.exs b/config/runtime.exsindex 610b537a8a..d16b986089 100644--- a/config/runtime.exs+++ b/config/runtime.exs@@ -250,8 +250,8 @@ runtime_metadata = [config :plausible, :runtime_metadata, runtime_metadatasentry_dsn = get_var_from_path_or_env(config_dir, "SENTRY_DSN")-paddle_auth_code = get_var_from_path_or_env(config_dir, "PADDLE_VENDOR_AUTH_CODE")-paddle_vendor_id = get_var_from_path_or_env(config_dir, "PADDLE_VENDOR_ID")+paddle_classic_auth_code = get_var_from_path_or_env(config_dir, "PADDLE_VENDOR_AUTH_CODE")+paddle_classic_vendor_id = get_var_from_path_or_env(config_dir, "PADDLE_VENDOR_ID")google_cid = get_var_from_path_or_env(config_dir, "GOOGLE_CLIENT_ID")google_secret = get_var_from_path_or_env(config_dir, "GOOGLE_CLIENT_SECRET")postmark_api_key = get_var_from_path_or_env(config_dir, "POSTMARK_API_KEY")@@ -605,9 +605,9 @@ config :sentry,send_max_attempts: 1,before_send: {Plausible.SentryFilter, :before_send}-config :plausible, :paddle,- vendor_auth_code: paddle_auth_code,- vendor_id: paddle_vendor_id+config :plausible, :paddle_classic,+ vendor_auth_code: paddle_classic_auth_code,+ vendor_id: paddle_classic_vendor_idconfig :plausible, :google,client_id: google_cid,diff --git a/config/test.exs b/config/test.exsindex 108ae3fde3..9b2586ff7d 100644--- a/config/test.exs+++ b/config/test.exs@@ -19,7 +19,7 @@ config :plausible, Plausible.ClickhouseRepo,config :plausible, Plausible.Mailer, adapter: Bamboo.TestAdapterconfig :plausible,- paddle_api: Plausible.Billing.TestPaddleApiMock,+ paddle_classic_api: Plausible.Billing.PaddleClassic.TestApiMock,google_api: Plausible.Google.API.Mockconfig :bamboo, :refute_timeout, 10diff --git a/extra/lib/plausible/help_scout.ex b/extra/lib/plausible/help_scout.exindex 6a5844d6d5..33ce77b054 100644--- a/extra/lib/plausible/help_scout.ex+++ b/extra/lib/plausible/help_scout.ex@@ -190,7 +190,7 @@ defmodule Plausible.HelpScout dodefp plan_link(%{paddle_subscription_id: paddle_id}) doPath.join([- Billing.PaddleApi.vendors_domain(),+ Billing.PaddleClassic.Api.vendors_domain(),"/subscriptions/customers/manage/",paddle_id])diff --git a/extra/lib/plausible_web/live/customer_support/team.ex b/extra/lib/plausible_web/live/customer_support/team.exindex 8c0684cdd5..e3d6cc1fec 100644--- a/extra/lib/plausible_web/live/customer_support/team.ex+++ b/extra/lib/plausible_web/live/customer_support/team.ex@@ -300,7 +300,7 @@ defmodule PlausibleWeb.Live.CustomerSupport.Team doenddefp manage_url(%{paddle_subscription_id: paddle_id} = _subscription) do- Plausible.Billing.PaddleApi.vendors_domain() <>+ Plausible.Billing.PaddleClassic.Api.vendors_domain() <>"/subscriptions/customers/manage/" <> paddle_idenddiff --git a/lib/mix/tasks/create_paddle_prod_plans.ex b/lib/mix/tasks/paddle_classic/create_prod_plans.exsimilarity index 99%rename from lib/mix/tasks/create_paddle_prod_plans.exrename to lib/mix/tasks/paddle_classic/create_prod_plans.exindex 3375f48276..4e5bebacc0 100644--- a/lib/mix/tasks/create_paddle_prod_plans.ex+++ b/lib/mix/tasks/paddle_classic/create_prod_plans.ex@@ -1,4 +1,4 @@-defmodule Mix.Tasks.CreatePaddleProdPlans do+defmodule Mix.Tasks.PaddleClassic.CreateProdPlans do@moduledoc """## Utility for creating Paddle plans for production use.@@ -31,7 +31,7 @@ defmodule Mix.Tasks.CreatePaddleProdPlans do## Usage example:```- mix create_paddle_prod_plans input_plans_v5.json+ mix paddle_classic.create_prod_plans input_plans_v5.json```## Requirement 1: Replace the curl commanddiff --git a/lib/mix/tasks/create_paddle_sandbox_plans.ex b/lib/mix/tasks/paddle_classic/create_sandbox_plans.exsimilarity index 90%rename from lib/mix/tasks/create_paddle_sandbox_plans.exrename to lib/mix/tasks/paddle_classic/create_sandbox_plans.exindex cc2fb2dcd5..8072d2abef 100644--- a/lib/mix/tasks/create_paddle_sandbox_plans.ex+++ b/lib/mix/tasks/paddle_classic/create_sandbox_plans.ex@@ -1,10 +1,10 @@-defmodule Mix.Tasks.CreatePaddleSandboxPlans do+defmodule Mix.Tasks.PaddleClassic.CreateSandboxPlans do@moduledoc """Utility for creating Sandbox plans that are used on staging. The product ofthis task is a `sandbox_plans_v*.json` file matching with the productionplans, just with the monthly/yearly product_id's of the sandbox plans.- In principle, this task works like `Mix.Tasks.CreatePaddleProdPlans`, with+ In principle, this task works like `Mix.Tasks.PaddleClassic.CreateProdPlans`, withthe following differences:* The `filename` argument should be the name of the JSON file containing the@@ -13,7 +13,7 @@ defmodule Mix.Tasks.CreatePaddleSandboxPlans do* To copy the curl command from the browser, you need to add a plan fromhttps://sandbox-vendors.paddle.com/subscriptions/plans. Everything else is- the same - please see `create_paddle_prod_plans.ex` for instructions.+ the same - please see `create_prod_plans.ex` for instructions.* This task can be executed multiple times in a row - it will not createduplicates in Sandbox Paddle. On staging we can use a specific plan-naming@@ -25,11 +25,11 @@ defmodule Mix.Tasks.CreatePaddleSandboxPlans do## Usage example:```- mix create_paddle_sandbox_plans plans_v5.json+ mix paddle_classic.create_sandbox_plans plans_v5.json```"""- alias Mix.Tasks.CreatePaddleProdPlans+ alias Mix.Tasks.PaddleClassic.CreateProdPlansuse Mix.Task@requirements ["app.config"]@@ -95,7 +95,7 @@ defmodule Mix.Tasks.CreatePaddleSandboxPlans do--data-raw '_token=#{your_unique_token}&plan-id=&default-curr=USD&tmpicon=false&name=#{name}&checkout_custom_message=&taxable_type=standard&interval=#{interval_index}&period=1&type=#{type}&trial_length=&price_USD=#{price}&active_EUR=on&price_EUR=#{price}&active_GBP=on&price_GBP=#{price}'"""- case CreatePaddleProdPlans.curl_quietly(curl_command) do+ case CreateProdPlans.curl_quietly(curl_command) do:ok ->IO.puts("✅ Created #{name}")@@ -108,14 +108,14 @@ defmodule Mix.Tasks.CreatePaddleSandboxPlans dodefp fetch_all_sandbox_plans() dourl = "https://sandbox-vendors.paddle.com/api/2.0/subscription/plans"- paddle_config = Application.get_env(:plausible, :paddle)+ paddle_config = Application.get_env(:plausible, :paddle_classic)paddle_credentials = %{vendor_id: paddle_config[:vendor_id],vendor_auth_code: paddle_config[:vendor_auth_code]}- CreatePaddleProdPlans.fetch_all_paddle_plans(url, paddle_credentials)+ CreateProdPlans.fetch_all_paddle_plans(url, paddle_credentials)end@paddle_interval_indexes %{"monthly" => 2, "yearly" => 5}@@ -154,7 +154,7 @@ defmodule Mix.Tasks.CreatePaddleSandboxPlans do"monthly_product_id" => to_string(sandbox_monthly_product_id),"yearly_product_id" => to_string(sandbox_yearly_product_id)})- |> CreatePaddleProdPlans.order_keys()+ |> CreateProdPlans.order_keys()end)content = Jason.encode!(sandbox_plans, pretty: true)diff --git a/lib/mix/tasks/pull_sandbox_subscription.ex b/lib/mix/tasks/paddle_classic/pull_sandbox_subscription.exsimilarity index 87%rename from lib/mix/tasks/pull_sandbox_subscription.exrename to lib/mix/tasks/paddle_classic/pull_sandbox_subscription.exindex d9139b5db8..effcd418de 100644--- a/lib/mix/tasks/pull_sandbox_subscription.ex+++ b/lib/mix/tasks/paddle_classic/pull_sandbox_subscription.ex@@ -1,4 +1,4 @@-defmodule Mix.Tasks.PullSandboxSubscription do+defmodule Mix.Tasks.PaddleClassic.PullSandboxSubscription do@moduledoc """Mix task for creating subscriptions in dev environment via Paddle API."""@@ -17,7 +17,7 @@ defmodule Mix.Tasks.PullSandboxSubscription do# https://sandbox-vendors.paddle.com/subscriptions/customers## 3) run from command line:- # mix pull_sandbox_subscription <subscription_ID>+ # mix paddle_classic.pull_sandbox_subscription <subscription_ID>@headers [{"Content-type", "application/json"},@@ -27,9 +27,10 @@ defmodule Mix.Tasks.PullSandboxSubscription dodef run([paddle_subscription_id]) doMix.Task.run("app.start")- config = Application.get_env(:plausible, :paddle)+ config = Application.get_env(:plausible, :paddle_classic)- endpoint = Plausible.Billing.PaddleApi.vendors_domain() <> "/api/2.0/subscription/users"+ endpoint =+ Plausible.Billing.PaddleClassic.Api.vendors_domain() <> "/api/2.0/subscription/users"params = %{vendor_id: config[:vendor_id],diff --git a/lib/plausible/application.ex b/lib/plausible/application.exindex 9cf02cd280..fde540325d 100644--- a/lib/plausible/application.ex+++ b/lib/plausible/application.ex@@ -326,12 +326,12 @@ defmodule Plausible.Application doenddefp maybe_add_paddle_pool(pool_config, default) do- paddle_conf = Application.get_env(:plausible, :paddle)+ paddle_conf = Application.get_env(:plausible, :paddle_classic)if paddle_conf[:vendor_id] && paddle_conf[:vendor_auth_code] doMap.put(pool_config,- Plausible.Billing.PaddleApi.vendors_domain(),+ Plausible.Billing.PaddleClassic.Api.vendors_domain(),Config.Reader.merge(default, conn_opts: [transport_opts: [timeout: 15_000]]))elsediff --git a/lib/plausible/billing/billing.ex b/lib/plausible/billing/billing.exindex 0a3b5f868c..9618ea1eac 100644--- a/lib/plausible/billing/billing.ex+++ b/lib/plausible/billing/billing.ex@@ -1,43 +1,24 @@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.+ Billing facade: manual subscriptions, plan change previews, enterprise plan lookup,+ price formatting and notice titles. Subscription lifecycle events coming from the payment+ provider are applied through `Plausible.Billing.SubscriptionState`."""use Plausibleuse Plausible.Repo- alias Plausible.Auth- alias Plausible.Billing.{EnterprisePlan, Subscription, Subscriptions}- alias Plausible.TeamDeletionSchedules+ alias Plausible.Billing.{+ EnterprisePlan,+ PaddleClassic,+ Subscription,+ Subscriptions,+ SubscriptionState+ }+alias Plausible.Teamsdefmacro 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-@doc """Creates a subscription for a custom plan without Paddle checkout (for example, paid by bank transfer).@@ -78,7 +59,7 @@ defmodule Plausible.Billing dowith {:ok, _plan} <-Repo.update(EnterprisePlan.manual_subscription_changeset(enterprise_plan)),{:ok, subscription} <- Repo.insert(Subscription.manual_changeset(team)) do- after_subscription_update(subscription)+ SubscriptionState.apply_subscription_state(subscription)else{:error, changeset} -> Repo.rollback(changeset)end@@ -99,7 +80,7 @@ defmodule Plausible.Billing doenddef change_plan_preview(subscription, new_plan_id) do- case paddle_api().update_subscription_preview(+ case PaddleClassic.api().update_subscription_preview(subscription.paddle_subscription_id,new_plan_id) do@@ -111,262 +92,15 @@ defmodule Plausible.Billing doendend- 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)- TeamDeletionSchedules.cancel_for_team(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) doMoney.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)- |> tap(&TeamDeletionSchedules.cancel_for_team/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"diff --git a/lib/plausible/billing/paddle_classic.ex b/lib/plausible/billing/paddle_classic.exnew file mode 100644index 0000000000..3fbfa80715--- /dev/null+++ b/lib/plausible/billing/paddle_classic.ex@@ -0,0 +1,14 @@+defmodule Plausible.Billing.PaddleClassic do+ @moduledoc """+ Entry point to the Paddle Classic integration: the HTTP client, webhook+ handling and the mix tasks that talk to Classic all live under this namespace.++ To be deleted after the Paddle Billing migration.+ """++ @doc """+ Returns the configured Paddle Classic API client module. Swapped for+ mocks in dev, test and e2e environments.+ """+ def api(), do: Application.fetch_env!(:plausible, :paddle_classic_api)+enddiff --git a/lib/plausible/billing/paddle_api.ex b/lib/plausible/billing/paddle_classic/api.exsimilarity index 98%rename from lib/plausible/billing/paddle_api.exrename to lib/plausible/billing/paddle_classic/api.exindex 5857ae1b39..1a4e1c9ba6 100644--- a/lib/plausible/billing/paddle_api.ex+++ b/lib/plausible/billing/paddle_classic/api.ex@@ -1,4 +1,4 @@-defmodule Plausible.Billing.PaddleApi do+defmodule Plausible.Billing.PaddleClassic.Api do@moduledoc """Paddle API HTTP client."""@@ -175,7 +175,7 @@ defmodule Plausible.Billing.PaddleApi doenddefp get_config() do- Application.get_env(:plausible, :paddle)+ Application.get_env(:plausible, :paddle_classic)enddefp invoices_url() dodiff --git a/lib/plausible/billing/paddle_classic/webhooks.ex b/lib/plausible/billing/paddle_classic/webhooks.exnew file mode 100644index 0000000000..64845f3d61--- /dev/null+++ b/lib/plausible/billing/paddle_classic/webhooks.ex@@ -0,0 +1,168 @@+defmodule Plausible.Billing.PaddleClassic.Webhooks do+ @moduledoc """+ Handles Paddle Classic webhook alerts: parses the payloads into subscription+ attributes and hands them to `Plausible.Billing.SubscriptionState`.++ To be deleted after the Paddle Billing migration.+ """+ use Plausible.Repo++ alias Plausible.Auth+ alias Plausible.Billing.{PaddleClassic, Subscription, SubscriptionState}+ alias Plausible.Teams++ 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++ defp handle_subscription_created(params) do+ team = get_team!(params)++ subscription_params =+ params+ |> format_subscription()+ |> add_last_bill_date(params)++ SubscriptionState.create(team, subscription_params)+ 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+ SubscriptionState.update(subscription, format_subscription(params))+ end+ end++ defp handle_subscription_cancelled(params) do+ subscription = Repo.get_by(Subscription, paddle_subscription_id: params["subscription_id"])++ if subscription do+ SubscriptionState.cancel(subscription, %{status: params["status"]})+ 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} =+ PaddleClassic.api().get_subscription(subscription.paddle_subscription_id)++ amount =+ :erlang.float_to_binary(api_subscription["next_payment"]["amount"] / 1, decimals: 2)++ SubscriptionState.record_payment(subscription, %{+ next_bill_amount: amount,+ next_bill_date: api_subscription["next_payment"]["date"],+ last_bill_date: api_subscription["last_payment"]["date"]+ })+ 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+enddiff --git a/lib/plausible/billing/plans.ex b/lib/plausible/billing/plans.exindex 6d6583779f..48a893a1b9 100644--- a/lib/plausible/billing/plans.ex+++ b/lib/plausible/billing/plans.ex@@ -169,7 +169,7 @@ defmodule Plausible.Billing.Plans dodef with_prices([_ | _] = plans, customer_ip \\ "127.0.0.1") doproduct_ids = Enum.flat_map(plans, &[&1.monthly_product_id, &1.yearly_product_id])- case Plausible.Billing.paddle_api().fetch_prices(product_ids, customer_ip) do+ case Plausible.Billing.PaddleClassic.api().fetch_prices(product_ids, customer_ip) do{:ok, prices} ->Enum.map(plans, fn plan ->plan@@ -195,7 +195,7 @@ defmodule Plausible.Billing.Plans doenddef get_price_for(%EnterprisePlan{paddle_plan_id: product_id}, customer_ip) do- case Plausible.Billing.paddle_api().fetch_prices([product_id], customer_ip) do+ case Plausible.Billing.PaddleClassic.api().fetch_prices([product_id], customer_ip) do{:ok, prices} -> Map.fetch!(prices, product_id){:error, :api_error} -> nilenddiff --git a/lib/plausible/billing/subscription_state.ex b/lib/plausible/billing/subscription_state.exnew file mode 100644index 0000000000..8dcd797ee9--- /dev/null+++ b/lib/plausible/billing/subscription_state.ex@@ -0,0 +1,158 @@+defmodule Plausible.Billing.SubscriptionState do+ @moduledoc """+ Provider-independent application of subscription state changes.++ Payment providers (currently Paddle Classic, later Paddle Billing) parse+ their own webhook payloads into plain subscription attributes and call the+ functions here to persist them and bring the team's state in line: traffic+ acceptance, grace period, site locking, scheduled deletion and API limits.++ The functions expect to be called inside a transaction opened by the caller.+ """+ use Plausible.Repo++ alias Plausible.Billing.{EnterprisePlan, SiteLocker, Subscription}+ alias Plausible.TeamDeletionSchedules+ alias Plausible.Teams++ @doc """+ Inserts a new subscription for the team and applies the resulting state.++ When a subscription with the same `paddle_subscription_id` already exists+ (a duplicate delivery), nothing is inserted and the existing subscription is+ returned, after reporting to Sentry if the incoming data differs from it.+ """+ def create(team, attrs) do+ changeset = Subscription.create_changeset(team, attrs)++ case Repo.insert(changeset,+ on_conflict: :nothing,+ conflict_target: :paddle_subscription_id+ ) do+ {:ok, %{id: nil}} ->+ handle_conflict("subscription_created", attrs.paddle_subscription_id, changeset)++ {:ok, subscription} ->+ apply_subscription_state(subscription)+ end+ end++ @doc """+ Updates an existing subscription and applies the resulting state.+ """+ def update(subscription, attrs) do+ subscription+ |> Subscription.changeset(attrs)+ |> Repo.update!()+ |> apply_subscription_state()+ end++ @doc """+ Records the subscription's cancellation (the `status` in `attrs`) and+ notifies the team's owners and billing members. Nothing is locked or+ limited here: the team keeps the plan until `next_bill_date`.+ """+ def cancel(subscription, attrs) do+ subscription = Repo.preload(subscription, team: [:owners, :billing_members])++ updated =+ subscription+ |> Subscription.changeset(attrs)+ |> Repo.update!()++ for recipient <- subscription.team.owners ++ subscription.team.billing_members do+ recipient+ |> PlausibleWeb.Email.cancellation_email()+ |> Plausible.Mailer.send()+ end++ updated+ end++ @doc """+ Records the billing dates and amount after a successful payment, and makes+ sure the team accepts traffic and isn't scheduled for deletion.+ """+ def record_payment(subscription, attrs) do+ subscription =+ subscription+ |> Subscription.changeset(attrs)+ |> Repo.update!()+ |> Repo.preload(:team)++ Teams.update_accept_traffic_until(subscription.team)+ TeamDeletionSchedules.cancel_for_team(subscription.team)++ subscription+ end++ @doc """+ Brings the team's state in line with its current subscription. Returns the team.+ """+ def apply_subscription_state(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+ |> Teams.update_accept_traffic_until()+ |> Teams.remove_grace_period()+ |> Teams.maybe_reset_next_upgrade_override()+ |> tap(&SiteLocker.update_for/1)+ |> tap(&TeamDeletionSchedules.cancel_for_team/1)+ |> maybe_adjust_api_key_limits()+ end++ defp maybe_adjust_api_key_limits(team) do+ plan =+ Repo.get_by(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+enddiff --git a/lib/plausible/teams/billing.ex b/lib/plausible/teams/billing.exindex 30079dd71d..1edb24e24e 100644--- a/lib/plausible/teams/billing.ex+++ b/lib/plausible/teams/billing.ex@@ -65,9 +65,12 @@ defmodule Plausible.Teams.Billing dodefp do_change_plan(subscription, new_plan_id) dores =- Plausible.Billing.paddle_api().update_subscription(subscription.paddle_subscription_id, %{- plan_id: new_plan_id- })+ Plausible.Billing.PaddleClassic.api().update_subscription(+ subscription.paddle_subscription_id,+ %{+ plan_id: new_plan_id+ }+ )case res do{:ok, response} ->diff --git a/lib/plausible_web/components/billing/billing.ex b/lib/plausible_web/components/billing/billing.exindex 399eb348e6..dfd1403601 100644--- a/lib/plausible_web/components/billing/billing.ex+++ b/lib/plausible_web/components/billing/billing.ex@@ -384,7 +384,7 @@ defmodule PlausibleWeb.Components.Billing doPaddle.Environment.set('sandbox')</script><script>- Paddle.Setup({vendor: <%= Application.get_env(:plausible, :paddle) |> Keyword.fetch!(:vendor_id) %> })+ Paddle.Setup({vendor: <%= Application.get_env(:plausible, :paddle_classic) |> Keyword.fetch!(:vendor_id) %> })</script>"""enddiff --git a/lib/plausible_web/controllers/api/paddle_controller.ex b/lib/plausible_web/controllers/api/paddle_classic_controller.exsimilarity index 87%rename from lib/plausible_web/controllers/api/paddle_controller.exrename to lib/plausible_web/controllers/api/paddle_classic_controller.exindex 132c0df283..610969d895 100644--- a/lib/plausible_web/controllers/api/paddle_controller.ex+++ b/lib/plausible_web/controllers/api/paddle_classic_controller.ex@@ -1,4 +1,4 @@-defmodule PlausibleWeb.Api.PaddleController do+defmodule PlausibleWeb.Api.PaddleClassicController douse PlausibleWeb, :controlleruse Plausible.Reporequire Logger@@ -6,22 +6,22 @@ defmodule PlausibleWeb.Api.PaddleController doplug :verify_signature when action in [:webhook]def webhook(conn, %{"alert_name" => "subscription_created"} = params) do- Plausible.Billing.subscription_created(params)+ Plausible.Billing.PaddleClassic.Webhooks.subscription_created(params)|> webhook_response(conn, params)enddef webhook(conn, %{"alert_name" => "subscription_updated"} = params) do- Plausible.Billing.subscription_updated(params)+ Plausible.Billing.PaddleClassic.Webhooks.subscription_updated(params)|> webhook_response(conn, params)enddef webhook(conn, %{"alert_name" => "subscription_cancelled"} = params) do- Plausible.Billing.subscription_cancelled(params)+ Plausible.Billing.PaddleClassic.Webhooks.subscription_cancelled(params)|> webhook_response(conn, params)enddef webhook(conn, %{"alert_name" => "subscription_payment_succeeded"} = params) do- Plausible.Billing.subscription_payment_succeeded(params)+ Plausible.Billing.PaddleClassic.Webhooks.subscription_payment_succeeded(params)|> webhook_response(conn, params)end@@ -37,7 +37,7 @@ defmodule PlausibleWeb.Api.PaddleController doresult =Plausible.Cache.Adapter.fetch(:customer_currency, {plan_id, customer_ip}, fn ->- case Plausible.Billing.PaddleApi.fetch_prices([plan_id], customer_ip) do+ case Plausible.Billing.PaddleClassic.Api.fetch_prices([plan_id], customer_ip) do{:ok, %{^plan_id => money}} ->{:ok, money.currency}diff --git a/lib/plausible_web/live/subscription_settings.ex b/lib/plausible_web/live/subscription_settings.exindex 62297105df..b641d09ab9 100644--- a/lib/plausible_web/live/subscription_settings.ex+++ b/lib/plausible_web/live/subscription_settings.ex@@ -19,7 +19,7 @@ defmodule PlausibleWeb.Live.SubscriptionSettings do{:ok, redirect(socket, to: ~p"/sites")}elsesubscription = Teams.Billing.get_subscription(team)- invoices = Plausible.Billing.paddle_api().get_invoices(subscription)+ invoices = Plausible.Billing.PaddleClassic.api().get_invoices(subscription)pageview_usage = Teams.Billing.monthly_pageview_usage(team)site_usage = Teams.Billing.site_usage(team)team_member_usage = Teams.Billing.team_member_usage(team)diff --git a/lib/plausible_web/router.ex b/lib/plausible_web/router.exindex f59bbc911a..fcee0cc3d1 100644--- a/lib/plausible_web/router.ex+++ b/lib/plausible_web/router.ex@@ -430,8 +430,8 @@ defmodule PlausibleWeb.Router dopost "/postmark/webhook", Api.PostmarkController, :webhookend- post "/paddle/webhook", Api.PaddleController, :webhook- get "/paddle/currency", Api.PaddleController, :currency+ post "/paddle/webhook", Api.PaddleClassicController, :webhook+ get "/paddle/currency", Api.PaddleClassicController, :currencyput "/:domain/disable-feature", Api.InternalController, :disable_featureput "/:domain/complete-onboarding", Api.InternalController, :complete_onboardingdiff --git a/test/plausible/billing/billing_test.exs b/test/plausible/billing/billing_test.exsindex c4319ec4a6..0e130b6089 100644--- a/test/plausible/billing/billing_test.exs+++ b/test/plausible/billing/billing_test.exs@@ -115,255 +115,6 @@ defmodule Plausible.BillingTest doendend- @subscription_id "subscription-123"- @plan_id_10k "654177"- @plan_id_100k "654178"-- @subscription_created_params %{- "event_time" => "2019-05-01 01:03:52",- "alert_name" => "subscription_created",- "passthrough" => "",- "email" => "",- "subscription_id" => @subscription_id,- "subscription_plan_id" => @plan_id_10k,- "update_url" => "update_url.com",- "cancel_url" => "cancel_url.com",- "status" => "active",- "next_bill_date" => "2019-06-01",- "unit_price" => "6.00",- "currency" => "EUR"- }-- @subscription_updated_params %{- "alert_name" => "subscription_updated",- "passthrough" => "",- "subscription_id" => "",- "subscription_plan_id" => @plan_id_10k,- "update_url" => "update_url.com",- "cancel_url" => "cancel_url.com",- "old_status" => "active",- "status" => "active",- "next_bill_date" => "2019-06-01",- "new_unit_price" => "12.00",- "currency" => "EUR"- }-- describe "subscription_created" do- test "fails on callback without passthrough" do- _user = new_user()-- assert_raise RuntimeError, ~r/Missing passthrough/, fn ->- @subscription_created_params- |> Map.delete("passthrough")- |> Billing.subscription_created()- end- end-- test "fails on callback without valid passthrough" do- _user = new_user()-- assert_raise RuntimeError, ~r/Invalid passthrough sent via Paddle/, fn ->- %{@subscription_created_params | "passthrough" => "invalid"}- |> Billing.subscription_created()- end-- assert_raise RuntimeError, ~r/Invalid passthrough sent via Paddle/, fn ->- %{@subscription_created_params | "passthrough" => "ee:true;user:invalid"}- |> Billing.subscription_created()- end-- assert_raise RuntimeError, ~r/Invalid passthrough sent via Paddle/, fn ->- %{@subscription_created_params | "passthrough" => "ee:true;user:123;team:invalid"}- |> Billing.subscription_created()- end-- assert_raise RuntimeError, ~r/Invalid passthrough sent via Paddle/, fn ->- %{- @subscription_created_params- | "passthrough" => "ee:true;user:123;team:456;some:invalid"- }- |> Billing.subscription_created()- end- end-- test "fails on callback with non-existent user" do- user = new_user()- Repo.delete!(user)-- assert_raise Ecto.NoResultsError, fn ->- %{@subscription_created_params | "passthrough" => "ee:true;user:#{user.id}"}- |> Billing.subscription_created()- end- end-- test "fails on callback with non-existent team" do- user = new_user()- {:ok, team} = Plausible.Teams.get_or_create(user)- Repo.delete!(team)-- assert_raise Ecto.NoResultsError, fn ->- %{- @subscription_created_params- | "passthrough" => "ee:true;user:#{user.id};team:#{team.id}"- }- |> Billing.subscription_created()- end- end-- test "creates a subscription with teams passthrough" do- user = new_user()- {:ok, team} = Plausible.Teams.get_or_create(user)-- %{@subscription_created_params | "passthrough" => "ee:true;user:#{user.id};team:#{team.id}"}- |> Billing.subscription_created()-- subscription =- user |> team_of() |> Plausible.Teams.with_subscription() |> Map.fetch!(:subscription)-- assert subscription.paddle_subscription_id == @subscription_id- assert subscription.next_bill_date == ~D[2019-06-01]- assert subscription.last_bill_date == ~D[2019-05-01]- assert subscription.next_bill_amount == "6.00"- assert subscription.currency_code == "EUR"- end-- test "identical notification sent twice is ignored at 2nd try" do- user = new_user()- {:ok, team} = Plausible.Teams.get_or_create(user)-- Plausible.Test.Support.Sentry.setup(self())-- Billing.subscription_created(%{- @subscription_created_params- | "passthrough" => "ee:true;user:#{user.id};team:#{team.id}"- })-- Billing.subscription_created(%{- @subscription_created_params- | "passthrough" => "ee:true;user:#{user.id};team:#{team.id}"- })-- subscription =- user |> team_of() |> Plausible.Teams.with_subscription() |> Map.fetch!(:subscription)-- assert subscription.paddle_subscription_id == @subscription_id- assert subscription.next_bill_date == ~D[2019-06-01]- assert subscription.last_bill_date == ~D[2019-05-01]- assert subscription.next_bill_amount == "6.00"- assert subscription.currency_code == "EUR"-- assert [] = Sentry.Test.pop_sentry_reports()- end-- test "secondary notification sent logs diff" do- user = new_user()- {:ok, team} = Plausible.Teams.get_or_create(user)-- Plausible.Test.Support.Sentry.setup(self())-- Billing.subscription_created(%{- @subscription_created_params- | "passthrough" => "ee:true;user:#{user.id};team:#{team.id}"- })-- Billing.subscription_created(%{- @subscription_created_params- | "subscription_plan_id" => "9999",- "currency" => "USD",- "passthrough" => "ee:true;user:#{user.id};team:#{team.id}"- })-- assert [report] = Sentry.Test.pop_sentry_reports()-- assert report.message.formatted =~- "Duplicate subscription_created webhook for paddle_subscription_id=subscription-123"-- assert report.extra.paddle_subscription_id == @subscription_id- assert report.extra.team_id == team.id- assert report.extra.diff.paddle_plan_id == %{existing: "654177", incoming: "9999"}- assert report.extra.diff.currency_code == %{existing: "EUR", incoming: "USD"}-- subscription =- user |> team_of() |> Plausible.Teams.with_subscription() |> Map.fetch!(:subscription)-- assert subscription.paddle_subscription_id == @subscription_id- assert subscription.currency_code == "EUR"- end-- test "supports user without a team case" do- user = new_user()-- %{@subscription_created_params | "passthrough" => "ee:true;user:#{user.id}"}- |> Billing.subscription_created()-- subscription =- user |> team_of() |> Plausible.Teams.with_subscription() |> Map.fetch!(:subscription)-- assert subscription.paddle_subscription_id == @subscription_id- assert subscription.next_bill_date == ~D[2019-06-01]- assert subscription.last_bill_date == ~D[2019-05-01]- assert subscription.next_bill_amount == "6.00"- assert subscription.currency_code == "EUR"- end-- test "unlocks sites if user has any locked sites" do- user = new_user()- site = new_site(owner: user)- site.team |> Ecto.Changeset.change(locked: true) |> Repo.update!()- team = team_of(user)-- %{@subscription_created_params | "passthrough" => "ee:true;user:#{user.id};team:#{team.id}"}- |> Billing.subscription_created()-- refute Repo.reload!(team).locked- end-- @tag :ee_only- test "updates accept_traffic_until" do- user = new_user()- new_site(owner: user)- team = team_of(user)-- %{@subscription_created_params | "passthrough" => "ee:true;user:#{user.id};team:#{team.id}"}- |> Billing.subscription_created()-- next_bill = Date.from_iso8601!(@subscription_created_params["next_bill_date"])-- assert Repo.reload!(team_of(user)).accept_traffic_until ==- Date.add(next_bill, 30)- end-- test "sets user.allow_next_upgrade_override field to false" do- user = new_user(team: [allow_next_upgrade_override: true])- team = team_of(user)-- %{@subscription_created_params | "passthrough" => "ee:true;user:#{user.id};team:#{team.id}"}- |> Billing.subscription_created()-- refute Repo.reload!(team_of(user)).allow_next_upgrade_override- end-- test "if user upgraded to an enterprise plan, their API key limits are automatically adjusted" do- user = new_user()-- subscribe_to_enterprise_plan(user,- hourly_api_request_limit: 10_000,- paddle_plan_id: @plan_id_10k- )-- team = team_of(user)-- _api_key = insert(:api_key, user: user)-- assert team.hourly_api_request_limit != 10_000-- %{@subscription_created_params | "passthrough" => "ee:true;user:#{user.id};team:#{team.id}"}- |> Billing.subscription_created()-- assert Repo.reload!(team).hourly_api_request_limit == 10_000- end- end-describe "latest_enterprise_plan" dotest "returns the most recently created enterprise plan of the team" donow = NaiveDateTime.utc_now()@@ -539,332 +290,6 @@ defmodule Plausible.BillingTest doendend- describe "subscription_updated" do- test "updates an existing subscription" do- user = new_user()- subscribe_to_growth_plan(user)- team = team_of(user)-- @subscription_updated_params- |> Map.merge(%{- "subscription_id" => subscription_of(user).paddle_subscription_id,- "passthrough" => "ee:true;user:#{user.id};team:#{team.id}"- })- |> Billing.subscription_updated()-- subscription = subscription_of(user)- assert subscription.paddle_plan_id == @plan_id_10k- assert subscription.next_bill_amount == "12.00"- end-- test "updates subscription with user/team passthrough" do- user = new_user()- subscribe_to_growth_plan(user)- team = team_of(user)-- subscription_id = subscription_of(user).paddle_subscription_id-- @subscription_updated_params- |> Map.merge(%{- "next_bill_date" => "2021-01-01",- "subscription_id" => subscription_id,- "passthrough" => "ee:true;user:#{user.id};team:#{team.id}"- })- |> Billing.subscription_updated()-- subscription =- user |> team_of() |> Plausible.Teams.with_subscription() |> Map.fetch!(:subscription)-- assert subscription.next_bill_date == ~D[2021-01-01]- end-- test "status update from 'paused' to 'past_due' is ignored" do- user = new_user()- subscribe_to_growth_plan(user, status: Subscription.Status.paused())- team = team_of(user)-- %{@subscription_updated_params | "old_status" => "paused", "status" => "past_due"}- |> Map.merge(%{- "subscription_id" => subscription_of(user).paddle_subscription_id,- "passthrough" => "ee:true;user:#{user.id};team:#{team.id}"- })- |> Billing.subscription_updated()-- assert subscription_of(user).status == Subscription.Status.paused()- end-- test "unlocks sites if subscription is changed from past_due to active" do- user = new_user()- subscribe_to_growth_plan(user, status: Subscription.Status.past_due())- site = new_site(owner: user)- site.team |> Ecto.Changeset.change(locked: true) |> Repo.update!()- team = team_of(user)-- @subscription_updated_params- |> Map.merge(%{- "subscription_id" => subscription_of(user).paddle_subscription_id,- "passthrough" => "ee:true;user:#{user.id};team:#{team.id}",- "old_status" => "past_due"- })- |> Billing.subscription_updated()-- refute Repo.reload!(team).locked- end-- test "cancels a pending team deletion schedule if subscription is changed from past_due to active" do- user = new_user()- subscribe_to_growth_plan(user, status: Subscription.Status.past_due())- team = team_of(user)- schedule = insert(:team_deletion_schedule, team: team, status: :first_notice_sent)-- @subscription_updated_params- |> Map.merge(%{- "subscription_id" => subscription_of(user).paddle_subscription_id,- "passthrough" => "ee:true;user:#{user.id};team:#{team.id}",- "old_status" => "past_due"- })- |> Billing.subscription_updated()-- assert Repo.reload!(schedule).status == :cancelled- end-- test "does not cancel a pending team deletion schedule if the update doesn't make the subscription active" do- user = new_user()- subscribe_to_growth_plan(user, status: Subscription.Status.past_due())- team = team_of(user)- schedule = insert(:team_deletion_schedule, team: team, status: :first_notice_sent)-- %{@subscription_updated_params | "old_status" => "past_due", "status" => "paused"}- |> Map.merge(%{- "subscription_id" => subscription_of(user).paddle_subscription_id,- "passthrough" => "ee:true;user:#{user.id};team:#{team.id}"- })- |> Billing.subscription_updated()-- assert Repo.reload!(schedule).status == :first_notice_sent- end-- @tag :ee_only- test "updates accept_traffic_until" do- user = new_user() |> subscribe_to_growth_plan()- team = team_of(user)-- @subscription_updated_params- |> Map.merge(%{- "subscription_id" => subscription_of(user).paddle_subscription_id,- "passthrough" => "ee:true;user:#{user.id};team:#{team.id}"- })- |> Billing.subscription_updated()-- next_bill = Date.from_iso8601!(@subscription_updated_params["next_bill_date"])-- assert Repo.reload!(team_of(user)).accept_traffic_until ==- Date.add(next_bill, 30)- end-- test "sets user.allow_next_upgrade_override field to false" do- user = new_user(team: [allow_next_upgrade_override: true])- subscribe_to_growth_plan(user)- team = team_of(user)-- assert Repo.reload!(team_of(user)).allow_next_upgrade_override-- subscription_id = subscription_of(user).paddle_subscription_id-- @subscription_updated_params- |> Map.merge(%{- "subscription_id" => subscription_id,- "passthrough" => "ee:true;user:#{user.id};team:#{team.id}"- })- |> Billing.subscription_updated()-- refute Repo.reload!(team_of(user)).allow_next_upgrade_override- end-- test "if user upgraded to an enterprise plan, their API key limits are automatically adjusted" do- user =- new_user()- |> subscribe_to_enterprise_plan(- paddle_plan_id: "new-plan-id",- hourly_api_request_limit: 10_000- )-- team = team_of(user)-- _api_key = insert(:api_key, user: user)-- assert team.hourly_api_request_limit != 10_000-- @subscription_updated_params- |> Map.merge(%{- "subscription_id" => subscription_of(user).paddle_subscription_id,- "passthrough" => "ee:true;user:#{user.id};team:#{team.id}",- "subscription_plan_id" => "new-plan-id"- })- |> Billing.subscription_updated()-- assert Repo.reload!(team).hourly_api_request_limit == 10_000- end-- test "if teams's grace period has ended, upgrading will unlock sites and remove grace period" do- grace_period = %Plausible.Teams.GracePeriod{- end_date: Date.shift(Date.utc_today(), day: -1)- }-- user = new_user(team: [grace_period: grace_period])-- subscribe_to_growth_plan(user)-- team = team_of(user)-- site = new_site(owner: user)- site.team |> Ecto.Changeset.change(locked: true) |> Repo.update!()-- subscription_id = subscription_of(user).paddle_subscription_id-- @subscription_updated_params- |> Map.merge(%{- "subscription_id" => subscription_id,- "passthrough" => "ee:true;user:#{user.id};team:#{team.id}",- "subscription_plan_id" => @plan_id_100k- })- |> Billing.subscription_updated()-- assert Repo.reload!(team).locked == false- assert Repo.reload!(team).grace_period == nil- end-- test "ignores if subscription cannot be found" do- user = insert(:user)- _site = new_site(owner: user)- team = team_of(user)-- res =- @subscription_updated_params- |> Map.merge(%{- "subscription_id" => "666",- "passthrough" => "ee:true;user:#{user.id};team:#{team.id}"- })- |> Billing.subscription_updated()-- assert {:ok, nil} = res- end- end-- describe "subscription_cancelled" do- test "sets the status to deleted" do- user = new_user()- subscribe_to_growth_plan(user, status: Subscription.Status.active())-- subscription_id = subscription_of(user).paddle_subscription_id-- Billing.subscription_cancelled(%{- "alert_name" => "subscription_cancelled",- "subscription_id" => subscription_id,- "status" => "deleted"- })-- assert user- |> team_of()- |> Repo.reload!()- |> Plausible.Teams.with_subscription()- |> Map.fetch!(:subscription)- |> Subscription.Status.deleted?()- end-- test "ignores if the subscription cannot be found" do- res =- Billing.subscription_cancelled(%{- "alert_name" => "subscription_cancelled",- "subscription_id" => "some_nonexistent_id",- "status" => "deleted"- })-- assert res == {:ok, nil}- end-- test "sends an email to confirm cancellation" do- user = new_user()- subscribe_to_growth_plan(user, status: Subscription.Status.active())-- team = team_of(user)- billing_member = new_user()- add_member(team, user: billing_member, role: :billing)-- Billing.subscription_cancelled(%{- "alert_name" => "subscription_cancelled",- "subscription_id" => subscription_of(user).paddle_subscription_id,- "status" => "deleted"- })-- assert_email_delivered_with(- to: [nil: user.email],- subject: "Where did Plausible fall short?"- )-- assert_email_delivered_with(- to: [nil: billing_member.email],- subject: "Where did Plausible fall short?"- )- end- end-- describe "subscription_payment_succeeded" do- @tag :ee_only- test "updates accept_traffic_until" do- user = new_user() |> subscribe_to_growth_plan()-- subscription_id = subscription_of(user).paddle_subscription_id-- Billing.subscription_payment_succeeded(%{- "alert_name" => "subscription_payment_succeeded",- "subscription_id" => subscription_id- })-- team = user |> team_of() |> Repo.reload!() |> Plausible.Teams.with_subscription()- assert team.accept_traffic_until == Date.add(team.subscription.next_bill_date, 30)- end-- test "sets the next bill amount and date, last bill date" do- user = new_user() |> subscribe_to_growth_plan()-- Billing.subscription_payment_succeeded(%{- "alert_name" => "subscription_payment_succeeded",- "subscription_id" => subscription_of(user).paddle_subscription_id- })-- subscription = subscription_of(user)- assert subscription.next_bill_date == ~D[2019-07-10]- assert subscription.next_bill_amount == "6.00"- assert subscription.last_bill_date == ~D[2019-06-10]- end-- test "ignores if the subscription cannot be found" do- res =- Billing.subscription_payment_succeeded(%{- "alert_name" => "subscription_payment_succeeded",- "subscription_id" => "nonexistent_subscription_id",- "next_bill_date" => Date.shift(Date.utc_today(), day: 30),- "unit_price" => "12.00"- })-- assert res == {:ok, nil}- end-- test "cancels a pending team deletion schedule" do- user = new_user() |> subscribe_to_growth_plan()- team = team_of(user)- schedule = insert(:team_deletion_schedule, team: team, status: :first_notice_sent)-- Billing.subscription_payment_succeeded(%{- "alert_name" => "subscription_payment_succeeded",- "subscription_id" => subscription_of(user).paddle_subscription_id- })-- assert Repo.reload!(schedule).status == :cancelled- end- end-describe "change_plan" dotest "sets the next bill amount and date" doteam = new_user() |> subscribe_to_growth_plan() |> team_of()diff --git a/test/plausible/billing/paddle_api_test.exs b/test/plausible/billing/paddle_classic/api_test.exssimilarity index 91%rename from test/plausible/billing/paddle_api_test.exsrename to test/plausible/billing/paddle_classic/api_test.exsindex c3983c818f..4532f1875b 100644--- a/test/plausible/billing/paddle_api_test.exs+++ b/test/plausible/billing/paddle_classic/api_test.exs@@ -1,4 +1,4 @@-defmodule Plausible.Billing.PaddleApiTest do+defmodule Plausible.Billing.PaddleClassic.ApiTest douse Plausible.DataCaseimport Mox@@ -25,7 +25,7 @@ defmodule Plausible.Billing.PaddleApiTest doend)- assert Plausible.Billing.PaddleApi.fetch_prices(+ assert Plausible.Billing.PaddleClassic.Api.fetch_prices(["19878", "20127", "20657", "20658"],"127.0.0.1") ==diff --git a/test/plausible/billing/paddle_classic/webhooks_test.exs b/test/plausible/billing/paddle_classic/webhooks_test.exsnew file mode 100644index 0000000000..e21b312d29--- /dev/null+++ b/test/plausible/billing/paddle_classic/webhooks_test.exs@@ -0,0 +1,583 @@+defmodule Plausible.Billing.PaddleClassic.WebhooksTest do+ use Plausible.DataCase+ use Bamboo.Test, shared: true+ require Plausible.Billing.Subscription.Status+ alias Plausible.Billing.PaddleClassic.Webhooks+ alias Plausible.Billing.Subscription+ alias Plausible.Repo++ @subscription_id "subscription-123"+ @plan_id_10k "654177"+ @plan_id_100k "654178"++ @subscription_created_params %{+ "event_time" => "2019-05-01 01:03:52",+ "alert_name" => "subscription_created",+ "passthrough" => "",+ "email" => "",+ "subscription_id" => @subscription_id,+ "subscription_plan_id" => @plan_id_10k,+ "update_url" => "update_url.com",+ "cancel_url" => "cancel_url.com",+ "status" => "active",+ "next_bill_date" => "2019-06-01",+ "unit_price" => "6.00",+ "currency" => "EUR"+ }++ @subscription_updated_params %{+ "alert_name" => "subscription_updated",+ "passthrough" => "",+ "subscription_id" => "",+ "subscription_plan_id" => @plan_id_10k,+ "update_url" => "update_url.com",+ "cancel_url" => "cancel_url.com",+ "old_status" => "active",+ "status" => "active",+ "next_bill_date" => "2019-06-01",+ "new_unit_price" => "12.00",+ "currency" => "EUR"+ }++ describe "subscription_created" do+ test "fails on callback without passthrough" do+ _user = new_user()++ assert_raise RuntimeError, ~r/Missing passthrough/, fn ->+ @subscription_created_params+ |> Map.delete("passthrough")+ |> Webhooks.subscription_created()+ end+ end++ test "fails on callback without valid passthrough" do+ _user = new_user()++ assert_raise RuntimeError, ~r/Invalid passthrough sent via Paddle/, fn ->+ %{@subscription_created_params | "passthrough" => "invalid"}+ |> Webhooks.subscription_created()+ end++ assert_raise RuntimeError, ~r/Invalid passthrough sent via Paddle/, fn ->+ %{@subscription_created_params | "passthrough" => "ee:true;user:invalid"}+ |> Webhooks.subscription_created()+ end++ assert_raise RuntimeError, ~r/Invalid passthrough sent via Paddle/, fn ->+ %{@subscription_created_params | "passthrough" => "ee:true;user:123;team:invalid"}+ |> Webhooks.subscription_created()+ end++ assert_raise RuntimeError, ~r/Invalid passthrough sent via Paddle/, fn ->+ %{+ @subscription_created_params+ | "passthrough" => "ee:true;user:123;team:456;some:invalid"+ }+ |> Webhooks.subscription_created()+ end+ end++ test "fails on callback with non-existent user" do+ user = new_user()+ Repo.delete!(user)++ assert_raise Ecto.NoResultsError, fn ->+ %{@subscription_created_params | "passthrough" => "ee:true;user:#{user.id}"}+ |> Webhooks.subscription_created()+ end+ end++ test "fails on callback with non-existent team" do+ user = new_user()+ {:ok, team} = Plausible.Teams.get_or_create(user)+ Repo.delete!(team)++ assert_raise Ecto.NoResultsError, fn ->+ %{+ @subscription_created_params+ | "passthrough" => "ee:true;user:#{user.id};team:#{team.id}"+ }+ |> Webhooks.subscription_created()+ end+ end++ test "creates a subscription with teams passthrough" do+ user = new_user()+ {:ok, team} = Plausible.Teams.get_or_create(user)++ %{@subscription_created_params | "passthrough" => "ee:true;user:#{user.id};team:#{team.id}"}+ |> Webhooks.subscription_created()++ subscription =+ user |> team_of() |> Plausible.Teams.with_subscription() |> Map.fetch!(:subscription)++ assert subscription.paddle_subscription_id == @subscription_id+ assert subscription.next_bill_date == ~D[2019-06-01]+ assert subscription.last_bill_date == ~D[2019-05-01]+ assert subscription.next_bill_amount == "6.00"+ assert subscription.currency_code == "EUR"+ end++ test "identical notification sent twice is ignored at 2nd try" do+ user = new_user()+ {:ok, team} = Plausible.Teams.get_or_create(user)++ Plausible.Test.Support.Sentry.setup(self())++ Webhooks.subscription_created(%{+ @subscription_created_params+ | "passthrough" => "ee:true;user:#{user.id};team:#{team.id}"+ })++ Webhooks.subscription_created(%{+ @subscription_created_params+ | "passthrough" => "ee:true;user:#{user.id};team:#{team.id}"+ })++ subscription =+ user |> team_of() |> Plausible.Teams.with_subscription() |> Map.fetch!(:subscription)++ assert subscription.paddle_subscription_id == @subscription_id+ assert subscription.next_bill_date == ~D[2019-06-01]+ assert subscription.last_bill_date == ~D[2019-05-01]+ assert subscription.next_bill_amount == "6.00"+ assert subscription.currency_code == "EUR"++ assert [] = Sentry.Test.pop_sentry_reports()+ end++ test "secondary notification sent logs diff" do+ user = new_user()+ {:ok, team} = Plausible.Teams.get_or_create(user)++ Plausible.Test.Support.Sentry.setup(self())++ Webhooks.subscription_created(%{+ @subscription_created_params+ | "passthrough" => "ee:true;user:#{user.id};team:#{team.id}"+ })++ Webhooks.subscription_created(%{+ @subscription_created_params+ | "subscription_plan_id" => "9999",+ "currency" => "USD",+ "passthrough" => "ee:true;user:#{user.id};team:#{team.id}"+ })++ assert [report] = Sentry.Test.pop_sentry_reports()++ assert report.message.formatted =~+ "Duplicate subscription_created webhook for paddle_subscription_id=subscription-123"++ assert report.extra.paddle_subscription_id == @subscription_id+ assert report.extra.team_id == team.id+ assert report.extra.diff.paddle_plan_id == %{existing: "654177", incoming: "9999"}+ assert report.extra.diff.currency_code == %{existing: "EUR", incoming: "USD"}++ subscription =+ user |> team_of() |> Plausible.Teams.with_subscription() |> Map.fetch!(:subscription)++ assert subscription.paddle_subscription_id == @subscription_id+ assert subscription.currency_code == "EUR"+ end++ test "supports user without a team case" do+ user = new_user()++ %{@subscription_created_params | "passthrough" => "ee:true;user:#{user.id}"}+ |> Webhooks.subscription_created()++ subscription =+ user |> team_of() |> Plausible.Teams.with_subscription() |> Map.fetch!(:subscription)++ assert subscription.paddle_subscription_id == @subscription_id+ assert subscription.next_bill_date == ~D[2019-06-01]+ assert subscription.last_bill_date == ~D[2019-05-01]+ assert subscription.next_bill_amount == "6.00"+ assert subscription.currency_code == "EUR"+ end++ test "unlocks sites if user has any locked sites" do+ user = new_user()+ site = new_site(owner: user)+ site.team |> Ecto.Changeset.change(locked: true) |> Repo.update!()+ team = team_of(user)++ %{@subscription_created_params | "passthrough" => "ee:true;user:#{user.id};team:#{team.id}"}+ |> Webhooks.subscription_created()++ refute Repo.reload!(team).locked+ end++ @tag :ee_only+ test "updates accept_traffic_until" do+ user = new_user()+ new_site(owner: user)+ team = team_of(user)++ %{@subscription_created_params | "passthrough" => "ee:true;user:#{user.id};team:#{team.id}"}+ |> Webhooks.subscription_created()++ next_bill = Date.from_iso8601!(@subscription_created_params["next_bill_date"])++ assert Repo.reload!(team_of(user)).accept_traffic_until ==+ Date.add(next_bill, 30)+ end++ test "sets user.allow_next_upgrade_override field to false" do+ user = new_user(team: [allow_next_upgrade_override: true])+ team = team_of(user)++ %{@subscription_created_params | "passthrough" => "ee:true;user:#{user.id};team:#{team.id}"}+ |> Webhooks.subscription_created()++ refute Repo.reload!(team_of(user)).allow_next_upgrade_override+ end++ test "if user upgraded to an enterprise plan, their API key limits are automatically adjusted" do+ user = new_user()++ subscribe_to_enterprise_plan(user,+ hourly_api_request_limit: 10_000,+ paddle_plan_id: @plan_id_10k+ )++ team = team_of(user)++ _api_key = insert(:api_key, user: user)++ assert team.hourly_api_request_limit != 10_000++ %{@subscription_created_params | "passthrough" => "ee:true;user:#{user.id};team:#{team.id}"}+ |> Webhooks.subscription_created()++ assert Repo.reload!(team).hourly_api_request_limit == 10_000+ end+ end++ describe "subscription_updated" do+ test "updates an existing subscription" do+ user = new_user()+ subscribe_to_growth_plan(user)+ team = team_of(user)++ @subscription_updated_params+ |> Map.merge(%{+ "subscription_id" => subscription_of(user).paddle_subscription_id,+ "passthrough" => "ee:true;user:#{user.id};team:#{team.id}"+ })+ |> Webhooks.subscription_updated()++ subscription = subscription_of(user)+ assert subscription.paddle_plan_id == @plan_id_10k+ assert subscription.next_bill_amount == "12.00"+ end++ test "updates subscription with user/team passthrough" do+ user = new_user()+ subscribe_to_growth_plan(user)+ team = team_of(user)++ subscription_id = subscription_of(user).paddle_subscription_id++ @subscription_updated_params+ |> Map.merge(%{+ "next_bill_date" => "2021-01-01",+ "subscription_id" => subscription_id,+ "passthrough" => "ee:true;user:#{user.id};team:#{team.id}"+ })+ |> Webhooks.subscription_updated()++ subscription =+ user |> team_of() |> Plausible.Teams.with_subscription() |> Map.fetch!(:subscription)++ assert subscription.next_bill_date == ~D[2021-01-01]+ end++ test "status update from 'paused' to 'past_due' is ignored" do+ user = new_user()+ subscribe_to_growth_plan(user, status: Subscription.Status.paused())+ team = team_of(user)++ %{@subscription_updated_params | "old_status" => "paused", "status" => "past_due"}+ |> Map.merge(%{+ "subscription_id" => subscription_of(user).paddle_subscription_id,+ "passthrough" => "ee:true;user:#{user.id};team:#{team.id}"+ })+ |> Webhooks.subscription_updated()++ assert subscription_of(user).status == Subscription.Status.paused()+ end++ test "unlocks sites if subscription is changed from past_due to active" do+ user = new_user()+ subscribe_to_growth_plan(user, status: Subscription.Status.past_due())+ site = new_site(owner: user)+ site.team |> Ecto.Changeset.change(locked: true) |> Repo.update!()+ team = team_of(user)++ @subscription_updated_params+ |> Map.merge(%{+ "subscription_id" => subscription_of(user).paddle_subscription_id,+ "passthrough" => "ee:true;user:#{user.id};team:#{team.id}",+ "old_status" => "past_due"+ })+ |> Webhooks.subscription_updated()++ refute Repo.reload!(team).locked+ end++ test "cancels a pending team deletion schedule if subscription is changed from past_due to active" do+ user = new_user()+ subscribe_to_growth_plan(user, status: Subscription.Status.past_due())+ team = team_of(user)+ schedule = insert(:team_deletion_schedule, team: team, status: :first_notice_sent)++ @subscription_updated_params+ |> Map.merge(%{+ "subscription_id" => subscription_of(user).paddle_subscription_id,+ "passthrough" => "ee:true;user:#{user.id};team:#{team.id}",+ "old_status" => "past_due"+ })+ |> Webhooks.subscription_updated()++ assert Repo.reload!(schedule).status == :cancelled+ end++ test "does not cancel a pending team deletion schedule if the update doesn't make the subscription active" do+ user = new_user()+ subscribe_to_growth_plan(user, status: Subscription.Status.past_due())+ team = team_of(user)+ schedule = insert(:team_deletion_schedule, team: team, status: :first_notice_sent)++ %{@subscription_updated_params | "old_status" => "past_due", "status" => "paused"}+ |> Map.merge(%{+ "subscription_id" => subscription_of(user).paddle_subscription_id,+ "passthrough" => "ee:true;user:#{user.id};team:#{team.id}"+ })+ |> Webhooks.subscription_updated()++ assert Repo.reload!(schedule).status == :first_notice_sent+ end++ @tag :ee_only+ test "updates accept_traffic_until" do+ user = new_user() |> subscribe_to_growth_plan()+ team = team_of(user)++ @subscription_updated_params+ |> Map.merge(%{+ "subscription_id" => subscription_of(user).paddle_subscription_id,+ "passthrough" => "ee:true;user:#{user.id};team:#{team.id}"+ })+ |> Webhooks.subscription_updated()++ next_bill = Date.from_iso8601!(@subscription_updated_params["next_bill_date"])++ assert Repo.reload!(team_of(user)).accept_traffic_until ==+ Date.add(next_bill, 30)+ end++ test "sets user.allow_next_upgrade_override field to false" do+ user = new_user(team: [allow_next_upgrade_override: true])+ subscribe_to_growth_plan(user)+ team = team_of(user)++ assert Repo.reload!(team_of(user)).allow_next_upgrade_override++ subscription_id = subscription_of(user).paddle_subscription_id++ @subscription_updated_params+ |> Map.merge(%{+ "subscription_id" => subscription_id,+ "passthrough" => "ee:true;user:#{user.id};team:#{team.id}"+ })+ |> Webhooks.subscription_updated()++ refute Repo.reload!(team_of(user)).allow_next_upgrade_override+ end++ test "if user upgraded to an enterprise plan, their API key limits are automatically adjusted" do+ user =+ new_user()+ |> subscribe_to_enterprise_plan(+ paddle_plan_id: "new-plan-id",+ hourly_api_request_limit: 10_000+ )++ team = team_of(user)++ _api_key = insert(:api_key, user: user)++ assert team.hourly_api_request_limit != 10_000++ @subscription_updated_params+ |> Map.merge(%{+ "subscription_id" => subscription_of(user).paddle_subscription_id,+ "passthrough" => "ee:true;user:#{user.id};team:#{team.id}",+ "subscription_plan_id" => "new-plan-id"+ })+ |> Webhooks.subscription_updated()++ assert Repo.reload!(team).hourly_api_request_limit == 10_000+ end++ test "if teams's grace period has ended, upgrading will unlock sites and remove grace period" do+ grace_period = %Plausible.Teams.GracePeriod{+ end_date: Date.shift(Date.utc_today(), day: -1)+ }++ user = new_user(team: [grace_period: grace_period])++ subscribe_to_growth_plan(user)++ team = team_of(user)++ site = new_site(owner: user)+ site.team |> Ecto.Changeset.change(locked: true) |> Repo.update!()++ subscription_id = subscription_of(user).paddle_subscription_id++ @subscription_updated_params+ |> Map.merge(%{+ "subscription_id" => subscription_id,+ "passthrough" => "ee:true;user:#{user.id};team:#{team.id}",+ "subscription_plan_id" => @plan_id_100k+ })+ |> Webhooks.subscription_updated()++ assert Repo.reload!(team).locked == false+ assert Repo.reload!(team).grace_period == nil+ end++ test "ignores if subscription cannot be found" do+ user = insert(:user)+ _site = new_site(owner: user)+ team = team_of(user)++ res =+ @subscription_updated_params+ |> Map.merge(%{+ "subscription_id" => "666",+ "passthrough" => "ee:true;user:#{user.id};team:#{team.id}"+ })+ |> Webhooks.subscription_updated()++ assert {:ok, nil} = res+ end+ end++ describe "subscription_cancelled" do+ test "sets the status to deleted" do+ user = new_user()+ subscribe_to_growth_plan(user, status: Subscription.Status.active())++ subscription_id = subscription_of(user).paddle_subscription_id++ Webhooks.subscription_cancelled(%{+ "alert_name" => "subscription_cancelled",+ "subscription_id" => subscription_id,+ "status" => "deleted"+ })++ assert user+ |> team_of()+ |> Repo.reload!()+ |> Plausible.Teams.with_subscription()+ |> Map.fetch!(:subscription)+ |> Subscription.Status.deleted?()+ end++ test "ignores if the subscription cannot be found" do+ res =+ Webhooks.subscription_cancelled(%{+ "alert_name" => "subscription_cancelled",+ "subscription_id" => "some_nonexistent_id",+ "status" => "deleted"+ })++ assert res == {:ok, nil}+ end++ test "sends an email to confirm cancellation" do+ user = new_user()+ subscribe_to_growth_plan(user, status: Subscription.Status.active())++ team = team_of(user)+ billing_member = new_user()+ add_member(team, user: billing_member, role: :billing)++ Webhooks.subscription_cancelled(%{+ "alert_name" => "subscription_cancelled",+ "subscription_id" => subscription_of(user).paddle_subscription_id,+ "status" => "deleted"+ })++ assert_email_delivered_with(+ to: [nil: user.email],+ subject: "Where did Plausible fall short?"+ )++ assert_email_delivered_with(+ to: [nil: billing_member.email],+ subject: "Where did Plausible fall short?"+ )+ end+ end++ describe "subscription_payment_succeeded" do+ @tag :ee_only+ test "updates accept_traffic_until" do+ user = new_user() |> subscribe_to_growth_plan()++ subscription_id = subscription_of(user).paddle_subscription_id++ Webhooks.subscription_payment_succeeded(%{+ "alert_name" => "subscription_payment_succeeded",+ "subscription_id" => subscription_id+ })++ team = user |> team_of() |> Repo.reload!() |> Plausible.Teams.with_subscription()+ assert team.accept_traffic_until == Date.add(team.subscription.next_bill_date, 30)+ end++ test "sets the next bill amount and date, last bill date" do+ user = new_user() |> subscribe_to_growth_plan()++ Webhooks.subscription_payment_succeeded(%{+ "alert_name" => "subscription_payment_succeeded",+ "subscription_id" => subscription_of(user).paddle_subscription_id+ })++ subscription = subscription_of(user)+ assert subscription.next_bill_date == ~D[2019-07-10]+ assert subscription.next_bill_amount == "6.00"+ assert subscription.last_bill_date == ~D[2019-06-10]+ end++ test "ignores if the subscription cannot be found" do+ res =+ Webhooks.subscription_payment_succeeded(%{+ "alert_name" => "subscription_payment_succeeded",+ "subscription_id" => "nonexistent_subscription_id",+ "next_bill_date" => Date.shift(Date.utc_today(), day: 30),+ "unit_price" => "12.00"+ })++ assert res == {:ok, nil}+ end++ test "cancels a pending team deletion schedule" do+ user = new_user() |> subscribe_to_growth_plan()+ team = team_of(user)+ schedule = insert(:team_deletion_schedule, team: team, status: :first_notice_sent)++ Webhooks.subscription_payment_succeeded(%{+ "alert_name" => "subscription_payment_succeeded",+ "subscription_id" => subscription_of(user).paddle_subscription_id+ })++ assert Repo.reload!(schedule).status == :cancelled+ end+ end+enddiff --git a/test/plausible_web/controllers/api/paddle_controller_test.exs b/test/plausible_web/controllers/api/paddle_classic_controller_test.exssimilarity index 99%rename from test/plausible_web/controllers/api/paddle_controller_test.exsrename to test/plausible_web/controllers/api/paddle_classic_controller_test.exsindex d712711286..768c8fe645 100644--- a/test/plausible_web/controllers/api/paddle_controller_test.exs+++ b/test/plausible_web/controllers/api/paddle_classic_controller_test.exs@@ -1,4 +1,4 @@-defmodule PlausibleWeb.Api.PaddleControllerTest do+defmodule PlausibleWeb.Api.PaddleClassicControllerTest douse PlausibleWeb.ConnCase, async: trueuse Plausible.Repodiff --git a/test/support/dev/billing/dev_subscriptions.ex b/test/support/dev/billing/dev_subscriptions.exindex d18c5c0db4..e06ee71246 100644--- a/test/support/dev/billing/dev_subscriptions.ex+++ b/test/support/dev/billing/dev_subscriptions.ex@@ -11,7 +11,8 @@ defmodule Plausible.Billing.DevSubscriptions doimport Ecto.Queryalias Plausible.{Repo, Billing}- alias Plausible.Billing.{Plan, EnterprisePlan, DevPaddleApiMock}+ alias Plausible.Billing.{Plan, EnterprisePlan}+ alias Plausible.Billing.PaddleClassic.DevApiMockdef create(team_id, plan_id, opts \\ []) doplan_or_enterprise_plan = get_plan_or_enterprise_plan(plan_id)@@ -32,10 +33,10 @@ defmodule Plausible.Billing.DevSubscriptions do"cancel_url" => ~p"/dev/billing/cancel-subscription-form","status" => "active","next_bill_date" => next_bill_date(plan_or_enterprise_plan, plan_id),- "unit_price" => "#{to_string(DevPaddleApiMock.all_prices()[plan_id])}.00",+ "unit_price" => "#{to_string(DevApiMock.all_prices()[plan_id])}.00","currency" => "EUR"}- |> Plausible.Billing.subscription_created()+ |> Plausible.Billing.PaddleClassic.Webhooks.subscription_created(){:ok, Repo.reload(get_team_subscription(team_id))}else@@ -63,10 +64,10 @@ defmodule Plausible.Billing.DevSubscriptions do"old_status" => to_string(subscription.status),"status" => new_status,"next_bill_date" => next_bill_date,- "new_unit_price" => "#{to_string(DevPaddleApiMock.all_prices()[current_plan_id])}.00",+ "new_unit_price" => "#{to_string(DevApiMock.all_prices()[current_plan_id])}.00","currency" => "EUR"}- |> Plausible.Billing.subscription_updated()+ |> Plausible.Billing.PaddleClassic.Webhooks.subscription_updated():okelse@@ -95,7 +96,7 @@ defmodule Plausible.Billing.DevSubscriptions doif subscription = get_team_subscription(team_id) do%{"subscription_id" => subscription.paddle_subscription_id, "status" => "deleted"}- |> Billing.subscription_cancelled()+ |> Plausible.Billing.PaddleClassic.Webhooks.subscription_cancelled()subscription = Repo.reload!(subscription)diff --git a/test/support/dev/billing/dev_paddle_api_mock.ex b/test/support/dev/billing/paddle_classic/dev_api_mock.exsimilarity index 94%rename from test/support/dev/billing/dev_paddle_api_mock.exrename to test/support/dev/billing/paddle_classic/dev_api_mock.exindex fab1b154f2..8606d894e2 100644--- a/test/support/dev/billing/dev_paddle_api_mock.ex+++ b/test/support/dev/billing/paddle_classic/dev_api_mock.ex@@ -1,4 +1,4 @@-defmodule Plausible.Billing.DevPaddleApiMock do+defmodule Plausible.Billing.PaddleClassic.DevApiMock do@moduledoc """This module mocks API requests made to Paddle in the :dev environment.@@ -25,7 +25,7 @@ defmodule Plausible.Billing.DevPaddleApiMock doend@doc """- Mocks the real `Plausible.Billing.PaddleApi.fetch_prices`, but:+ Mocks the real `Plausible.Billing.PaddleClassic.Api.fetch_prices`, but:1. instead of filtering by a list of product IDs simply returns the prices forall plansdiff --git a/test/support/test_paddle_api_mock.ex b/test/support/paddle_classic/test_api_mock.exsimilarity index 92%rename from test/support/test_paddle_api_mock.exrename to test/support/paddle_classic/test_api_mock.exindex bd7f5de446..6d86cef120 100644--- a/test/support/test_paddle_api_mock.ex+++ b/test/support/paddle_classic/test_api_mock.ex@@ -1,4 +1,4 @@-defmodule Plausible.Billing.TestPaddleApiMock do+defmodule Plausible.Billing.PaddleClassic.TestApiMock do@moduledoc falsedef get_subscription(_) do@@ -75,6 +75,6 @@ defmodule Plausible.Billing.TestPaddleApiMock doenddef fetch_prices(product_ids, customer_ip) do- Plausible.Billing.DevPaddleApiMock.fetch_prices(product_ids, customer_ip)+ Plausible.Billing.PaddleClassic.DevApiMock.fetch_prices(product_ids, customer_ip)endend