Skip to content

Commit a147c8f

Browse files
Add subscription upsert to finalize checkout (#1472)
1 parent 9ff59be commit a147c8f

File tree

2 files changed

+34
-5
lines changed

2 files changed

+34
-5
lines changed

apps/core/lib/core/services/payments.ex

Lines changed: 13 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -212,8 +212,9 @@ defmodule Core.Services.Payments do
212212
end
213213
end
214214

215-
def finalize_checkout(%Stripe.Checkout.Session{customer: cus_id, subscription: sub_id}, %User{} = user) when is_binary(cus_id) and is_binary(sub_id) do
216-
%{account: account} = Repo.preload(user, [:account])
215+
def finalize_checkout(%Stripe.Checkout.Session{customer: cus_id, subscription: sub_id}, %User{} = user)
216+
when is_binary(cus_id) and is_binary(sub_id) do
217+
%{account: account} = Repo.preload(user, [account: :subscription])
217218
start_transaction()
218219
|> add_operation(:account, fn _ ->
219220
account
@@ -222,9 +223,16 @@ defmodule Core.Services.Payments do
222223
end)
223224
|> add_operation(:subscription, fn _ ->
224225
plan = pro_plan!()
225-
%PlatformSubscription{account_id: account.id}
226-
|> PlatformSubscription.changeset(%{external_id: sub_id, plan_id: plan.id, billing_version: 1})
227-
|> Core.Repo.insert()
226+
case account.subscription do
227+
%PlatformSubscription{} = sub -> sub
228+
nil -> %PlatformSubscription{account_id: account.id}
229+
end
230+
|> PlatformSubscription.changeset(%{
231+
external_id: sub_id,
232+
plan_id: plan.id,
233+
billing_version: 1
234+
})
235+
|> Core.Repo.insert_or_update()
228236
end)
229237
|> execute(extract: :subscription)
230238
end

apps/core/test/services/payments_test.exs

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1080,6 +1080,27 @@ defmodule Core.Services.PaymentsTest do
10801080

10811081
assert account.billing_customer_id == "cus_id"
10821082
end
1083+
1084+
test "it will finalize even if a subscription exists" do
1085+
account = insert(:account)
1086+
user = insert(:user, account: account)
1087+
insert(:platform_subscription, account: account)
1088+
plan = pro_plan()
1089+
expect(Stripe.Checkout.Session, :retrieve, fn "session_id" ->
1090+
{:ok, %Stripe.Checkout.Session{customer: "cus_id", subscription: "sub_id"}}
1091+
end)
1092+
1093+
{:ok, subscription} = Payments.finalize_checkout("session_id", user)
1094+
1095+
assert subscription.account_id == account.id
1096+
assert subscription.external_id == "sub_id"
1097+
assert subscription.plan_id == plan.id
1098+
assert subscription.billing_version == 1
1099+
1100+
%{account: account} = Repo.preload(subscription, [:account])
1101+
1102+
assert account.billing_customer_id == "cus_id"
1103+
end
10831104
end
10841105

10851106
describe "#backfill_subscription/3" do

0 commit comments

Comments
 (0)