1 import { ContainerRegistrationKeys } from "@medusajs/framework/utils"
2 import { medusaIntegrationTestRunner } from "@medusajs/test-utils"
3 import {
4 adminHeaders,
5 createAdminUser,
6 generatePublishableKey,
7 generateStoreHeaders,
8 } from "../../../../helpers/create-admin-user"
9 import { getProductFixture } from "../../../../helpers/fixtures"
10 import { createAuthenticatedCustomer } from "../../../../modules/helpers/create-authenticated-customer"
11
12 jest.setTimeout(60000)
13
14 // pp_account-holder_test.createAccountHolder returns { id: customer.id }, so
15 // repeated inits for the same customer resolve to the same
16 // (provider_id, external_id) - mirroring a provider whose create is idempotent
17 // (e.g. Stripe). Its initiatePayment fails when the session data carries
18 // `fail: true`, letting us drive a workflow rollback after the account holder
19 // has been created and linked.
20 const providerId = "pp_account-holder_test"
21
22 medusaIntegrationTestRunner({
23 testSuite: ({ dbConnection, getContainer, api }) => {
24 let storeHeadersWithCustomer
25 let customer
26 let region
27 let salesChannel
28 let product
29
30 const fetchAccountHolders = async () => {
31 const query = getContainer().resolve(ContainerRegistrationKeys.QUERY)
32 const {
33 data: [result],
34 } = await query.graph({
35 entity: "customer",
36 fields: [
37 "id",
38 "account_holders.id",
39 "account_holders.provider_id",
40 "account_holders.external_id",
41 ],
42 filters: { id: customer.id },
43 })
44
45 return result?.account_holders ?? []
46 }
47
48 const createPaymentCollection = async () => {
49 const cart = (
50 await api.post(
51 "/store/carts",
52 {
53 region_id: region.id,
54 items: [{ variant_id: product.variants[0].id, quantity: 1 }],
55 sales_channel_id: salesChannel.id,
56 },
57 storeHeadersWithCustomer
58 )
59 ).data.cart
60
61 return (
62 await api.post(
63 "/store/payment-collections",
64 { cart_id: cart.id },
65 storeHeadersWithCustomer
66 )
67 ).data.payment_collection
68 }
69
70 beforeEach(async () => {
71 const container = getContainer()
72 const publishableKey = await generatePublishableKey(container)
73 const storeHeaders = generateStoreHeaders({ publishableKey })
74 await createAdminUser(dbConnection, adminHeaders, container)
75
76 const result = await createAuthenticatedCustomer(api, storeHeaders, {
77 first_name: "tony",
78 last_name: "stark",
79 email: "tony@stark-industries.com",
80 })
81 customer = result.customer
82
83 storeHeadersWithCustomer = {
84 headers: {
85 ...storeHeaders.headers,
86 authorization: `Bearer ${result.jwt}`,
87 },
88 }
89
90 region = (
91 await api.post(
92 "/admin/regions",
93 {
94 payment_providers: ["pp_system_default", "pp_account-holder_test"],
95 name: "United States",
96 currency_code: "usd",
97 countries: ["us"],
98 },
99 adminHeaders
100 )
101 ).data.region
102
103 salesChannel = (
104 await api.post("/admin/sales-channels", { name: "Web" }, adminHeaders)
105 ).data.sales_channel
106
107 const shippingProfile = (
108 await api.post(
109 `/admin/shipping-profiles`,
110 { name: "Test", type: "default" },
111 adminHeaders
112 )
113 ).data.shipping_profile
114
115 product = (
116 await api.post(
117 "/admin/products",
118 getProductFixture({
119 title: "test",
120 status: "published",
121 shipping_profile_id: shippingProfile.id,
122 variants: [
123 {
124 title: "Test variant",
125 manage_inventory: false,
126 prices: [
127 {
128 amount: 150,
129 currency_code: "usd",
130 rules: { region_id: region.id },
131 },
132 ],
133 },
134 ],
135 }),
136 adminHeaders
137 )
138 ).data.product
139 })
140
141 describe("POST /store/payment-collections/:id/payment-sessions (account holder)", () => {
142 it("reuses the account holder after a failed init instead of colliding on the unique index", async () => {
143 const paymentCollection = await createPaymentCollection()
144
145 // First init fails inside the workflow, after createPaymentAccountHolderStep
146 // has created the holder and createRemoteLinkStep has linked it to the
147 // customer. The provider rejects the session (data.fail), so the workflow
148 // rolls back.
149 await expect(
150 api.post(
151 `/store/payment-collections/${paymentCollection.id}/payment-sessions`,
152 { provider_id: providerId, data: { fail: true } },
153 storeHeadersWithCustomer
154 )
155 ).rejects.toThrow()
156
157 // The customer link to the holder must survive the rollback
158 // (createRemoteLinkStep runs with noCompensation). Without it the holder
159 // is orphaned - present in the DB but unreachable through
160 // customer.account_holders - so the next init re-creates the same
161 // provider customer and collides on the unique (provider_id, external_id).
162 const holdersAfterFailure = await fetchAccountHolders()
163 expect(holdersAfterFailure).toHaveLength(1)
164 expect(holdersAfterFailure[0]).toEqual(
165 expect.objectContaining({
166 provider_id: providerId,
167 external_id: customer.id,
168 })
169 )
170
171 // Second init succeeds: the linked holder short-circuits the provider
172 // create, so there is no insert to collide and no "already exists" error.
173 const {
174 data: { payment_collection },
175 } = await api.post(
176 `/store/payment-collections/${paymentCollection.id}/payment-sessions`,
177 { provider_id: providerId },
178 storeHeadersWithCustomer
179 )
180
181 expect(payment_collection.payment_sessions).toEqual([
182 expect.objectContaining({
183 provider_id: providerId,
184 status: "pending",
185 amount: 150,
186 }),
187 ])
188
189 // Still exactly one holder - the orphan was reused, not duplicated.
190 const holdersAfterSuccess = await fetchAccountHolders()
191 expect(holdersAfterSuccess).toHaveLength(1)
192 expect(holdersAfterSuccess[0].id).toBe(holdersAfterFailure[0].id)
193 })
194 })
195 },
196 })