1 import { refundPaymentsWorkflow } from "@medusajs/core-flows"
2 import { medusaIntegrationTestRunner } from "@medusajs/test-utils"
3 import { ClaimType, Modules } from "@medusajs/utils"
4 import {
5 adminHeaders,
6 createAdminUser,
7 } from "../../../../helpers/create-admin-user"
8 import { createOrderSeeder } from "../../fixtures/order"
9
10 jest.setTimeout(50000)
11
12 medusaIntegrationTestRunner({
13 testSuite: ({ dbConnection, getContainer, api, dbUtils }) => {
14 let container
15 let order
16 let adminUser
17
18 const createClaim = async ({ order }) => {
19 const claim = (
20 await api.post(
21 "/admin/claims",
22 {
23 order_id: order.id,
24 type: ClaimType.REPLACE,
25 description: "Base claim",
26 },
27 adminHeaders
28 )
29 ).data.claim
30
31 await api.post(
32 `/admin/claims/${claim.id}/inbound/items`,
33 { items: [{ id: order.items[0].id, quantity: 1 }] },
34 adminHeaders
35 )
36
37 const createdClaim = await api.post(
38 `/admin/claims/${claim.id}/request`,
39 {},
40 adminHeaders
41 )
42
43 const returnOrder = createdClaim.data.return
44 const returnId = returnOrder.id
45 await api.post(`/admin/returns/${returnId}/receive`, {}, adminHeaders)
46
47 let lineItem = returnOrder.items[0].item
48 await api.post(
49 `/admin/returns/${returnId}/receive-items`,
50 {
51 items: [
52 {
53 id: lineItem.id,
54 quantity: returnOrder.items[0].quantity,
55 },
56 ],
57 },
58 adminHeaders
59 )
60
61 await api.post(
62 `/admin/returns/${returnId}/receive/confirm`,
63 {},
64 adminHeaders
65 )
66 }
67
68 beforeAll(async () => {
69 container = getContainer()
70 ;({ user: adminUser } = await createAdminUser(
71 dbConnection,
72 adminHeaders,
73 container
74 ))
75
76 const inventoryItemOverride = (
77 await api.post(
78 `/admin/inventory-items`,
79 { sku: "test-variant", requires_shipping: false },
80 adminHeaders
81 )
82 ).data.inventory_item
83
84 const seeders = await createOrderSeeder({
85 api,
86 container,
87 inventoryItemOverride,
88 withoutShipping: true,
89 })
90
91 order = seeders.order
92
93 await api.post(
94 `/admin/orders/${order.id}/fulfillments`,
95 { items: [{ id: order.items[0].id, quantity: 1 }] },
96 adminHeaders
97 )
98
99 await dbUtils.snapshot()
100 })
101
102 describe("with outstanding amount due to claim", () => {
103 it("should capture an authorized payment", async () => {
104 const payment = order.payment_collections[0].payments[0]
105
106 const response = await api.post(
107 `/admin/payments/${payment.id}/capture?fields=+captures.created_by`,
108 undefined,
109 adminHeaders
110 )
111
112 expect(response.data.payment).toEqual(
113 expect.objectContaining({
114 id: payment.id,
115 captured_at: expect.any(String),
116 captures: [
117 expect.objectContaining({
118 id: expect.any(String),
119 amount: 100,
120 created_by: adminUser.id,
121 }),
122 ],
123 refunds: [],
124 amount: 100,
125 })
126 )
127 expect(response.status).toEqual(200)
128 })
129
130 it("should throw if capture amount is greater than authorized amount", async () => {
131 const payment = order.payment_collections[0].payments[0]
132
133 const response = await api.post(
134 `/admin/payments/${payment.id}/capture`,
135 { amount: 75 },
136 adminHeaders
137 )
138
139 expect(response.data.payment).toEqual(
140 expect.objectContaining({
141 id: payment.id,
142 captured_at: null, // not fully captured yet
143 captures: [
144 expect.objectContaining({
145 id: expect.any(String),
146 amount: 75,
147 }),
148 ],
149 refunds: [],
150 amount: 100,
151 })
152 )
153 expect(response.status).toEqual(200)
154
155 const errResponse = await api
156 .post(
157 `/admin/payments/${payment.id}/capture`,
158 { amount: 75 },
159 adminHeaders
160 )
161 .catch((e) => e)
162
163 expect(errResponse.response.data.message).toEqual(
164 "You cannot capture more than the authorized amount substracted by what is already captured."
165 )
166 })
167
168 it("should return payment if payment is already fully captured", async () => {
169 const payment = order.payment_collections[0].payments[0]
170
171 const response = await api.post(
172 `/admin/payments/${payment.id}/capture`,
173 undefined,
174 adminHeaders
175 )
176
177 expect(response.data.payment).toEqual(
178 expect.objectContaining({
179 id: payment.id,
180 captured_at: expect.any(String),
181 captures: [
182 expect.objectContaining({
183 id: expect.any(String),
184 amount: 100,
185 }),
186 ],
187 refunds: [],
188 amount: 100,
189 })
190 )
191 expect(response.status).toEqual(200)
192
193 const anotherResponse = await api.post(
194 `/admin/payments/${payment.id}/capture`,
195 undefined,
196 adminHeaders
197 )
198
199 expect(anotherResponse.data.payment).toEqual(
200 expect.objectContaining({
201 id: payment.id,
202 captured_at: expect.any(String),
203 captures: [
204 expect.objectContaining({
205 id: expect.any(String),
206 amount: 100,
207 }),
208 ],
209 refunds: [],
210 amount: 100,
211 })
212 )
213 expect(anotherResponse.status).toEqual(200)
214 })
215
216 it("should refund a captured payment", async () => {
217 const payment = order.payment_collections[0].payments[0]
218
219 await api.post(
220 `/admin/payments/${payment.id}/capture`,
221 undefined,
222 adminHeaders
223 )
224
225 await createClaim({ order })
226
227 const refundReason = (
228 await api.post(
229 `/admin/refund-reasons`,
230 { label: "test", code: "test" },
231 adminHeaders
232 )
233 ).data.refund_reason
234
235 // BREAKING: reason is now refund_reason_id
236 const response = await api.post(
237 `/admin/payments/${payment.id}/refund`,
238 {
239 amount: 50,
240 refund_reason_id: refundReason.id,
241 note: "Do not like it",
242 },
243 adminHeaders
244 )
245
246 // BREAKING: Response was `data.refund` in V1 with payment ID, reason, and amount
247 expect(response.status).toEqual(200)
248 expect(response.data.payment).toEqual(
249 expect.objectContaining({
250 id: payment.id,
251 captured_at: expect.any(String),
252 captures: [
253 expect.objectContaining({
254 id: expect.any(String),
255 amount: 100,
256 }),
257 ],
258 refunds: [
259 expect.objectContaining({
260 id: expect.any(String),
261 amount: 50,
262 note: "Do not like it",
263 refund_reason_id: refundReason.id,
264 refund_reason: expect.objectContaining({
265 label: "test",
266 code: "test",
267 }),
268 }),
269 ],
270 amount: 100,
271 })
272 )
273 })
274
275 it("should forward a caller-supplied idempotency key to the provider", async () => {
276 const paymentModule = container.resolve(Modules.PAYMENT)
277 const payment = order.payment_collections[0].payments[0]
278
279 await api.post(
280 `/admin/payments/${payment.id}/capture`,
281 undefined,
282 adminHeaders
283 )
284
285 const providerRefundSpy = jest.spyOn(
286 (paymentModule as any).paymentProviderService_,
287 "refundPayment"
288 )
289
290 const response = await api.post(
291 `/admin/payments/${payment.id}/refund`,
292 { amount: 50, idempotency_key: "rma_42_refund" },
293 adminHeaders
294 )
295
296 expect(response.status).toEqual(200)
297 expect(providerRefundSpy.mock.calls[0][1].context.idempotency_key).toEqual(
298 "rma_42_refund"
299 )
300
301 const refunds = await paymentModule.listRefunds({
302 payment_id: payment.id,
303 })
304 expect(refunds).toHaveLength(1)
305 expect(refunds[0].idempotency_key).toEqual("rma_42_refund")
306
307 jest.restoreAllMocks()
308 })
309
310 it("should not refund twice when the same idempotency key is replayed", async () => {
311 const paymentModule = container.resolve(Modules.PAYMENT)
312 const payment = order.payment_collections[0].payments[0]
313
314 await api.post(
315 `/admin/payments/${payment.id}/capture`,
316 undefined,
317 adminHeaders
318 )
319
320 const providerRefundSpy = jest.spyOn(
321 (paymentModule as any).paymentProviderService_,
322 "refundPayment"
323 )
324
325 const body = { amount: 50, idempotency_key: "rma_42_refund" }
326
327 await api.post(`/admin/payments/${payment.id}/refund`, body, adminHeaders)
328 const replay = await api.post(
329 `/admin/payments/${payment.id}/refund`,
330 body,
331 adminHeaders
332 )
333
334 expect(replay.status).toEqual(200)
335 expect(providerRefundSpy).toHaveBeenCalledTimes(1)
336 expect(replay.data.payment.refunds).toHaveLength(1)
337
338 jest.restoreAllMocks()
339 })
340
341 it("should not duplicate the order bookkeeping when a refund is replayed", async () => {
342 const payment = order.payment_collections[0].payments[0]
343
344 const refundReason = (
345 await api.post(
346 `/admin/refund-reasons`,
347 { label: "Test", code: "test" },
348 adminHeaders
349 )
350 ).data.refund_reason
351
352 await api.post(
353 `/admin/payments/${payment.id}/capture`,
354 undefined,
355 adminHeaders
356 )
357
358 const body = {
359 amount: 50,
360 refund_reason_id: refundReason.id,
361 idempotency_key: "rma_42_refund",
362 }
363
364 await api.post(`/admin/payments/${payment.id}/refund`, body, adminHeaders)
365
366 const afterFirst = (
367 await api.get(`/admin/orders/${order.id}`, adminHeaders)
368 ).data.order
369
370 await api.post(`/admin/payments/${payment.id}/refund`, body, adminHeaders)
371
372 const afterReplay = (
373 await api.get(`/admin/orders/${order.id}`, adminHeaders)
374 ).data.order
375
376 // A replay moves no funds, so it must not add a credit line or shift
377 // what the order says is still owed.
378 expect(afterReplay.credit_lines).toHaveLength(
379 afterFirst.credit_lines.length
380 )
381 expect(afterReplay.credit_line_total).toEqual(
382 afterFirst.credit_line_total
383 )
384 expect(afterReplay.summary.pending_difference).toEqual(
385 afterFirst.summary.pending_difference
386 )
387 })
388
389 it("should finish the order bookkeeping when a retry follows a half-written refund", async () => {
390 const orderModule = container.resolve(Modules.ORDER)
391 const payment = order.payment_collections[0].payments[0]
392
393 await api.post(
394 `/admin/payments/${payment.id}/capture`,
395 undefined,
396 adminHeaders
397 )
398
399 // The provider refunds, then the order bookkeeping blows up: the money
400 // is gone but the order doesn't know about it yet.
401 const addTransactionsSpy = jest
402 .spyOn(orderModule, "addOrderTransactions")
403 .mockRejectedValueOnce(new Error("order bookkeeping failed"))
404
405 const body = { amount: 50, idempotency_key: "rma_42_refund" }
406
407 const failure = await api
408 .post(`/admin/payments/${payment.id}/refund`, body, adminHeaders)
409 .catch((e) => e)
410
411 expect(failure.response.status).toEqual(500)
412 expect(addTransactionsSpy).toHaveBeenCalledTimes(1)
413
414 expect(
415 await orderModule.listOrderTransactions({
416 order_id: order.id,
417 reference: "refund",
418 })
419 ).toHaveLength(0)
420
421 // The retry must finish the job, not treat it as already done.
422 const retry = await api.post(
423 `/admin/payments/${payment.id}/refund`,
424 body,
425 adminHeaders
426 )
427
428 expect(retry.status).toEqual(200)
429
430 const transactions = await orderModule.listOrderTransactions({
431 order_id: order.id,
432 reference: "refund",
433 })
434
435 expect(transactions).toHaveLength(1)
436 expect(transactions[0].amount).toEqual(-50)
437 expect(retry.data.payment.refunds).toHaveLength(1)
438
439 jest.restoreAllMocks()
440 })
441
442 it("should reject a replayed idempotency key used for a different amount", async () => {
443 const payment = order.payment_collections[0].payments[0]
444
445 await api.post(
446 `/admin/payments/${payment.id}/capture`,
447 undefined,
448 adminHeaders
449 )
450
451 await api.post(
452 `/admin/payments/${payment.id}/refund`,
453 { amount: 50, idempotency_key: "rma_42_refund" },
454 adminHeaders
455 )
456
457 const error = await api
458 .post(
459 `/admin/payments/${payment.id}/refund`,
460 { amount: 25, idempotency_key: "rma_42_refund" },
461 adminHeaders
462 )
463 .catch((e) => e)
464
465 expect(error.response.status).toEqual(400)
466 })
467
468 it("should reject an empty idempotency key", async () => {
469 const payment = order.payment_collections[0].payments[0]
470
471 const error = await api
472 .post(
473 `/admin/payments/${payment.id}/refund`,
474 { amount: 50, idempotency_key: "" },
475 adminHeaders
476 )
477 .catch((e) => e)
478
479 expect(error.response.status).toEqual(400)
480 })
481
482 it("should reject a refund with an amount of 0", async () => {
483 const payment = order.payment_collections[0].payments[0]
484
485 await api.post(
486 `/admin/payments/${payment.id}/capture`,
487 undefined,
488 adminHeaders
489 )
490
491 const error = await api
492 .post(
493 `/admin/payments/${payment.id}/refund`,
494 { amount: 0 },
495 adminHeaders
496 )
497 .catch((e) => e)
498
499 expect(error.response.status).toEqual(400)
500 })
501
502 it("should reject a refund with a negative amount", async () => {
503 const payment = order.payment_collections[0].payments[0]
504
505 await api.post(
506 `/admin/payments/${payment.id}/capture`,
507 undefined,
508 adminHeaders
509 )
510
511 const error = await api
512 .post(
513 `/admin/payments/${payment.id}/refund`,
514 { amount: -50 },
515 adminHeaders
516 )
517 .catch((e) => e)
518
519 expect(error.response.status).toEqual(400)
520 })
521
522 it("should issue multiple refunds", async () => {
523 const payment = order.payment_collections[0].payments[0]
524
525 await api.post(
526 `/admin/payments/${payment.id}/capture`,
527 undefined,
528 adminHeaders
529 )
530
531 const refundReason = (
532 await api.post(
533 `/admin/refund-reasons`,
534 { label: "test", code: "test" },
535 adminHeaders
536 )
537 ).data.refund_reason
538
539 await createClaim({ order })
540
541 await api.post(
542 `/admin/payments/${payment.id}/refund`,
543 {
544 amount: 25,
545 refund_reason_id: refundReason.id,
546 note: "Do not like it",
547 },
548 adminHeaders
549 )
550
551 await api.post(
552 `/admin/payments/${payment.id}/refund`,
553 {
554 amount: 25,
555 refund_reason_id: refundReason.id,
556 note: "Do not like it",
557 },
558 adminHeaders
559 )
560
561 const refundedPayment = (
562 await api.get(`/admin/payments/${payment.id}`, adminHeaders)
563 ).data.payment
564
565 expect(refundedPayment).toEqual(
566 expect.objectContaining({
567 id: payment.id,
568 currency_code: "usd",
569 amount: 100,
570 captured_at: expect.any(String),
571 captures: [
572 expect.objectContaining({
573 amount: 100,
574 }),
575 ],
576 refunds: [
577 expect.objectContaining({
578 amount: 25,
579 note: "Do not like it",
580 }),
581 expect.objectContaining({
582 amount: 25,
583 note: "Do not like it",
584 }),
585 ],
586 })
587 )
588 })
589
590 it("should create credit lines if issuing a refund when outstanding amount if >= 0", async () => {
591 const payment = order.payment_collections[0].payments[0]
592
593 const refundReason = (
594 await api.post(
595 `/admin/refund-reasons`,
596 { label: "Test", code: "test" },
597 adminHeaders
598 )
599 ).data.refund_reason
600
601 await api.post(
602 `/admin/payments/${payment.id}/capture`,
603 undefined,
604 adminHeaders
605 )
606
607 await api.post(
608 `/admin/payments/${payment.id}/refund`,
609 {
610 amount: 50,
611 refund_reason_id: refundReason.id,
612 },
613 adminHeaders
614 )
615
616 const updatedOrder = (
617 await api.get(`/admin/orders/${order.id}`, adminHeaders)
618 ).data.order
619
620 expect(updatedOrder.credit_line_total).toEqual(50)
621 expect(updatedOrder.credit_lines).toEqual([
622 expect.objectContaining({
623 reference: "Test",
624 reference_id: "test",
625 }),
626 ])
627 })
628
629 it("should throw if the refund amount exceeds the payment amount", async () => {
630 const payment = order.payment_collections[0].payments[0]
631
632 const refundReason = (
633 await api.post(
634 `/admin/refund-reasons`,
635 { label: "Test", code: "test" },
636 adminHeaders
637 )
638 ).data.refund_reason
639
640 await api.post(
641 `/admin/payments/${payment.id}/capture`,
642 undefined,
643 adminHeaders
644 )
645
646 await api.post(
647 `/admin/payments/${payment.id}/refund`,
648 {
649 amount: 50,
650 refund_reason_id: refundReason.id,
651 },
652 adminHeaders
653 )
654
655 const updatedOrder = (
656 await api.get(`/admin/orders/${order.id}`, adminHeaders)
657 ).data.order
658
659 expect(updatedOrder.credit_line_total).toEqual(50)
660 expect(updatedOrder.credit_lines).toEqual([
661 expect.objectContaining({
662 reference: "Test",
663 reference_id: "test",
664 }),
665 ])
666
667 try {
668 await api.post(
669 `/admin/payments/${payment.id}/refund`,
670 {
671 amount: 5000,
672 refund_reason_id: refundReason.id,
673 },
674 adminHeaders
675 )
676 } catch (error) {
677 expect(error.response.status).toBe(400)
678 expect(error.response.data.message).toBe(
679 "You are not allowed to refund more than the captured amount"
680 )
681 }
682
683 const updatedUpdatedOrder = (
684 await api.get(`/admin/orders/${order.id}`, adminHeaders)
685 ).data.order
686
687 expect(updatedUpdatedOrder.credit_line_total).toEqual(50)
688 expect(updatedUpdatedOrder.credit_lines).toEqual([
689 expect.objectContaining({
690 reference: "Test",
691 reference_id: "test",
692 }),
693 ])
694 })
695
696 it("should allow refund slightly exceeding captured amount within currency epsilon", async () => {
697 const payment = order.payment_collections[0].payments[0]
698
699 const refundReason = (
700 await api.post(
701 `/admin/refund-reasons`,
702 { label: "test", code: "test" },
703 adminHeaders
704 )
705 ).data.refund_reason
706
707 // Capture with sub-cent precision amount (more decimals than USD supports)
708 await api.post(
709 `/admin/payments/${payment.id}/capture`,
710 { amount: 87.957975 },
711 adminHeaders
712 )
713
714 // 87.96 > 87.957975 but the difference (0.002025) is within USD epsilon (0.01)
715 const response = await api.post(
716 `/admin/payments/${payment.id}/refund`,
717 {
718 amount: 87.96,
719 refund_reason_id: refundReason.id,
720 },
721 adminHeaders
722 )
723
724 expect(response.status).toEqual(200)
725 expect(response.data.payment).toEqual(
726 expect.objectContaining({
727 id: payment.id,
728 refunds: [
729 expect.objectContaining({
730 amount: 87.96,
731 }),
732 ],
733 })
734 )
735 })
736
737 it("refundPaymentsWorkflow allows refund slightly exceeding captured amount within currency epsilon", async () => {
738 const payment = order.payment_collections[0].payments[0]
739
740 await api.post(
741 `/admin/payments/${payment.id}/capture`,
742 { amount: 87.957975 },
743 adminHeaders
744 )
745
746 const { result } = await refundPaymentsWorkflow(container).run({
747 input: [{ payment_id: payment.id, amount: 87.96 }],
748 })
749
750 expect(result).toEqual([
751 expect.objectContaining({
752 id: payment.id,
753 refunds: expect.arrayContaining([
754 expect.objectContaining({ amount: 87.96 }),
755 ]),
756 }),
757 ])
758 })
759
760 it("refundPaymentsWorkflow rejects refund exceeding captured amount beyond currency epsilon", async () => {
761 const payment = order.payment_collections[0].payments[0]
762
763 await api.post(
764 `/admin/payments/${payment.id}/capture`,
765 { amount: 87.957975 },
766 adminHeaders
767 )
768
769 // 87.98 - 87.957975 = 0.022025, which is beyond USD epsilon (0.01)
770 await expect(
771 refundPaymentsWorkflow(container).run({
772 input: [{ payment_id: payment.id, amount: 87.98 }],
773 })
774 ).rejects.toMatchObject({
775 message: expect.stringContaining(
776 "is trying to refund amount greater than the refundable amount"
777 ),
778 })
779 })
780 })
781 },
782 })