medusajs / medusa

The world's most flexible commerce platform.
https://medusajs.com
MIT License
25.8k stars 2.58k forks source link

(Re)setting payment sessions on cart fails after removing payment provider from region. #5374

Open chemicalkosek opened 1 year ago

chemicalkosek commented 1 year ago

Bug report

Describe the bug

When multiple payment sessions are set on a cart and then you delete one provider from cart's region, then trying to set the payment sessions again is failing.

System information

Medusa version (including plugins): 1.17.1 Node.js version: 18.18 Database: Postgres

Steps to reproduce the behavior

  1. Have more than one payment provider in region (stripe, stripe-przelewy24).
  2. Create a cart /store/carts/
  3. Add an item to cart (total > 0)
  4. Create payment sessions on cart /store/carts/{cartId}/payment-sessions
  5. Remove one payment provider from region (stripe-przelewy24)
  6. Run setting the payment sessions again: /store/carts/{cartId}/payment-sessions
  7. See it fails with this error
    {
    "code": "invalid_request_error",
    "type": "duplicate_error",
    "message": "Payment_session with cart_id, provider_id cart_01HCPZE801K341SB1E0FW13THB, stripe already exists."
    }

Expected behavior

According to the setPaymentSessions function: https://github.com/medusajs/medusa/blob/418ff2a33aae60586cbc5289886ca82e18855fd9/packages/medusa/src/services/cart.ts#L1893

/*
   * Creates, updates and sets payment sessions associated with the cart. The
   * first time the method is called payment sessions will be created for each
   * provider. Additional calls will ensure that payment sessions have correct
   * amounts, currencies, etc. as well as make sure to filter payment sessions
   * that are not available for the cart's region.
   */

running it should delete any payment sessions from cart that don't have a matching payment provider in region settings.

So in the steps above where we run setting the payment sessions second time it should:

  1. Delete any payment sessions that don't belong to current region
  2. Refresh payment sessions.
  3. We now have 1 payment provider so it should also automatically set the payment session as selected.

Additional context

We are moving from multiple stripe providers (stripe, stripe-przelewy24, stripe-blik) into just using the stripe provider with Stripe PaymentElement which has all the payment methods baked in (and additionally Google Pay) To not break current carts we are setting the payment sessions again if the cart.payment_sessions.length is more then needed. Unfortunately it fails here during testing.

bqst commented 10 months ago

+1