From 2fc18fa53846affac7ef55d1504ab6c714f5f69e Mon Sep 17 00:00:00 2001 From: Andrew Dryga Date: Tue, 2 Apr 2024 12:30:44 -0600 Subject: [PATCH] Add ops script to sync all subscription plans This is helpful when we update a plan limits and want to pull them to all the accounts --- elixir/apps/domain/lib/domain/billing.ex | 5 +++++ .../lib/domain/billing/stripe/api_client.ex | 21 +++++++++++++++++++ elixir/apps/domain/lib/domain/ops.ex | 15 +++++++++++++ 3 files changed, 41 insertions(+) diff --git a/elixir/apps/domain/lib/domain/billing.ex b/elixir/apps/domain/lib/domain/billing.ex index 636a96c47..206eadc82 100644 --- a/elixir/apps/domain/lib/domain/billing.ex +++ b/elixir/apps/domain/lib/domain/billing.ex @@ -190,6 +190,11 @@ defmodule Domain.Billing do end end + def list_all_subscriptions do + secret_key = fetch_config!(:secret_key) + APIClient.list_all_subscriptions(secret_key) + end + def create_subscription(%Accounts.Account{} = account) do secret_key = fetch_config!(:secret_key) default_price_id = fetch_config!(:default_price_id) diff --git a/elixir/apps/domain/lib/domain/billing/stripe/api_client.ex b/elixir/apps/domain/lib/domain/billing/stripe/api_client.ex index 9ec7d0650..3a1343792 100644 --- a/elixir/apps/domain/lib/domain/billing/stripe/api_client.ex +++ b/elixir/apps/domain/lib/domain/billing/stripe/api_client.ex @@ -58,6 +58,27 @@ defmodule Domain.Billing.Stripe.APIClient do request(api_token, :get, "customers/#{customer_id}", "") end + def list_all_subscriptions(api_token, page_after \\ nil, acc \\ []) do + query_params = + if page_after do + "?starting_after=#{page_after}" + else + "" + end + + case request(api_token, :get, "subscriptions#{query_params}", "") do + {:ok, %{"has_more" => true, "data" => data}} -> + page_after = List.last(data)["id"] + list_all_subscriptions(api_token, page_after, acc ++ data) + + {:ok, %{"has_more" => false, "data" => data}} -> + {:ok, acc ++ data} + + {:error, reason} -> + {:error, reason} + end + end + def fetch_product(api_token, product_id) do request(api_token, :get, "products/#{product_id}", "") end diff --git a/elixir/apps/domain/lib/domain/ops.ex b/elixir/apps/domain/lib/domain/ops.ex index f69a703c5..becfc8382 100644 --- a/elixir/apps/domain/lib/domain/ops.ex +++ b/elixir/apps/domain/lib/domain/ops.ex @@ -68,4 +68,19 @@ defmodule Domain.Ops do {actor, identity} end) end + + def sync_pricing_plans do + {:ok, subscriptions} = Domain.Billing.list_all_subscriptions() + + Enum.each(subscriptions, fn subscription -> + %{ + "object" => "event", + "data" => %{ + "object" => subscription + }, + "type" => "customer.subscription.updated" + } + |> Domain.Billing.EventHandler.handle_event() + end) + end end