The complete open source platform to run your entire marketplace. Storefront, vendor panel, admin console, and integrations in one enterprise-grade platform you own.
TypeScript b2b-marketplacecomposable-commerceecommerceenterpriseheadless-commercemarketplacemedusamedusajsmulti-vendortypescript
fix(vendor): show authorized payment status on split orders (#1390)
Viktor Holike8e205dc127a
diff --git a/apps/docs/learn/order-groups.mdx b/apps/docs/learn/order-groups.mdxindex 93fc62f15..f5e45094c 100644--- a/apps/docs/learn/order-groups.mdx+++ b/apps/docs/learn/order-groups.mdx@@ -51,12 +51,17 @@ Order groups are created automatically during checkout by the `completeCartWithS5. **Link everything** — The workflow creates links between:- Each order and the order group- Each order and its seller- - Each order and the cart's payment collection- Each seller and the customer (if new relationship)6. **Finalize** — Inventory is reserved, payment is authorized, and the `order_group.created` event is emitted<Info>- Payment collections are linked at the **individual order level**, not on the order group. This is a deliberate design decision — each per-seller order gets its own link to the payment collection, which enables per-order capture and refund flows.+ A single payment collection is shared across all of a cart's split orders and stays on the **cart**, not on each order. Split orders are **not** linked directly to the payment collection (Medusa's `order ↔ payment_collection` link is one-to-one on the payment-collection side). Read the payment collection through the cart:++ ```text+ order → cart → payment_collection+ ```++ Order-group and vendor order reads normalize `cart.payment_collection` back onto `payment_collections` and recompute `payment_status` from it, so consumers keep the familiar shape. When requesting fields on vendor order routes, make sure the request does not replace route defaults that already include `cart.payment_collection.*` (a `fields=` list containing bare fields replaces defaults in Medusa; use `+`-prefixed fields to merge, or include the `cart.payment_collection.*` paths explicitly).</Info>## Eventsdiff --git a/integration-tests/http/order/vendor/order-payment-status.spec.ts b/integration-tests/http/order/vendor/order-payment-status.spec.tsnew file mode 100644index 000000000..fc81016cf--- /dev/null+++ b/integration-tests/http/order/vendor/order-payment-status.spec.ts@@ -0,0 +1,362 @@+import { medusaIntegrationTestRunner } from "@medusajs/test-utils"+import {+ IRegionModuleService,+ ISalesChannelModuleService,+ MedusaContainer,+} from "@medusajs/framework/types"+import { ContainerRegistrationKeys, Modules } from "@medusajs/framework/utils"+import { MercurModules, SellerStatus } from "@mercurjs/types"+import { createSellerUser } from "../../../helpers/create-seller-user"+import { createCustomerUser } from "../../../helpers/create-customer-user"+import { createVendorProduct } from "../../../helpers/create-product"+import {+ generatePublishableKey,+ generateStoreHeaders,+} from "../../../helpers/create-admin-user"++jest.setTimeout(120000)++/**+ * Issue #1387 — after the 2.3.0 cutover, split orders no longer carry an+ * `order ↔ payment_collection` link; the shared payment collection stays on+ * the cart (`order → cart → payment_collection`). Vendor order reads must+ * surface that collection under `payment_collections` and recompute+ * `payment_status`, otherwise the badge stays `not_paid` even though checkout+ * authorized the payment.+ */++const approveSeller = async (+ container: MedusaContainer,+ sellerId: string+) => {+ const sellerModule: any = container.resolve(MercurModules.SELLER)+ await sellerModule.updateSellers({+ id: sellerId,+ status: SellerStatus.OPEN,+ })+}++medusaIntegrationTestRunner({+ testSuite: ({ getContainer, api }) => {+ describe("Vendor - Order payment status (cart payment collection)", () => {+ let appContainer: MedusaContainer+ let sellerSeed: any+ let storeHeaders: any+ let region: any+ let salesChannel: any+ let prerequisiteCounter = 0++ const seedSellerOfferWithShipping = async (opts: {+ email: string+ name: string+ stocked: number+ offerPrice: number+ }) => {+ const result = await createSellerUser(appContainer, {+ email: opts.email,+ name: opts.name,+ })+ await approveSeller(appContainer, (result.seller as any).id)+ const headers = result.headers+ const tag = `_${opts.name}_${Date.now()}_${++prerequisiteCounter}`++ const stockLocation = (+ await api.post(+ `/vendor/stock-locations`,+ { name: `Warehouse${tag}` },+ headers+ )+ ).data.stock_location++ await api.post(+ `/vendor/stock-locations/${stockLocation.id}/fulfillment-sets`,+ { name: `FS${tag}`, type: "shipping" },+ headers+ )+ const fulfillmentSet = (+ await api.get(+ `/vendor/stock-locations/${stockLocation.id}?fields=*fulfillment_sets`,+ headers+ )+ ).data.stock_location.fulfillment_sets[0]+ const serviceZone = (+ await api.post(+ `/vendor/fulfillment-sets/${fulfillmentSet.id}/service-zones`,+ {+ name: `SZ${tag}`,+ geo_zones: [{ type: "country", country_code: "us" }],+ },+ headers+ )+ ).data.fulfillment_set.service_zones.find(+ (z: any) => z.name === `SZ${tag}`+ )+ const shippingProfile = (+ await api.post(+ `/vendor/shipping-profiles`,+ { name: `SP${tag}`, type: "default" },+ headers+ )+ ).data.shipping_profile++ await api.post(+ `/vendor/stock-locations/${stockLocation.id}/fulfillment-providers`,+ { add: ["manual_manual"] },+ headers+ )+ await api.post(+ `/vendor/stock-locations/${stockLocation.id}/sales-channels`,+ { add: [salesChannel.id] },+ headers+ )+ await api.post(+ `/vendor/shipping-options`,+ {+ name: `Ship${tag}`,+ service_zone_id: serviceZone.id,+ shipping_profile_id: shippingProfile.id,+ provider_id: "manual_manual",+ price_type: "flat",+ type: {+ label: "Standard",+ description: "Standard",+ code: "standard",+ },+ prices: [{ currency_code: "usd", amount: 500 }],+ rules: [+ {+ attribute: "enabled_in_store",+ value: "true",+ operator: "eq",+ },+ ],+ },+ headers+ )++ const product = await createVendorProduct(api, headers, {+ title: `Prod${tag}`,+ sku: `V${tag}`,+ })++ await api.post(+ `/vendor/sales-channels/${salesChannel.id}/products`,+ { add: [product.id] },+ headers+ )++ const offer = (+ await api.post(+ `/vendor/offers`,+ {+ sku: `OF${tag}`,+ variant_id: product.variants[0].id,+ shipping_profile_id: shippingProfile.id,+ inventory_items: [+ {+ title: `Inv${tag}`,+ required_quantity: 1,+ stock_levels: [+ {+ location_id: stockLocation.id,+ stocked_quantity: opts.stocked,+ },+ ],+ },+ ],+ prices: [+ {+ amount: opts.offerPrice,+ currency_code: "usd",+ },+ ],+ },+ headers+ )+ ).data.offer++ return { sellerId: result.seller.id, headers, offer }+ }++ const completeCartCheckout = async (offerId: string) => {+ const cart = (+ await api.post(+ `/store/carts`,+ {+ region_id: region.id,+ sales_channel_id: salesChannel.id,+ currency_code: "usd",+ },+ storeHeaders+ )+ ).data.cart++ await api.post(+ `/store/carts/${cart.id}/line-items`,+ { offer_id: offerId, quantity: 1 },+ storeHeaders+ )++ await api.post(+ `/store/carts/${cart.id}`,+ {+ email: "[email protected]",+ shipping_address: {+ first_name: "Buyer",+ last_name: "Test",+ address_1: "123 Main St",+ city: "New York",+ country_code: "us",+ postal_code: "10001",+ },+ billing_address: {+ first_name: "Buyer",+ last_name: "Test",+ address_1: "123 Main St",+ city: "New York",+ country_code: "us",+ postal_code: "10001",+ },+ },+ storeHeaders+ )++ const shippingOptionsResp = await api.get(+ `/store/shipping-options?cart_id=${cart.id}`,+ storeHeaders+ )+ const allOptions = Object.values(+ shippingOptionsResp.data.shipping_options as Record<+ string,+ any[]+ >+ ).flat()+ for (const opt of allOptions) {+ await api.post(+ `/store/carts/${cart.id}/shipping-methods`,+ { option_id: opt.id },+ storeHeaders+ )+ }++ const paymentCollection = (+ await api.post(+ `/store/payment-collections`,+ { cart_id: cart.id },+ storeHeaders+ )+ ).data.payment_collection+ await api.post(+ `/store/payment-collections/${paymentCollection.id}/payment-sessions`,+ { provider_id: "pp_system_default" },+ storeHeaders+ )++ const completeResp = await api.post(+ `/store/carts/${cart.id}/complete`,+ {},+ storeHeaders+ )+ const orderGroupId = completeResp.data.order_group.id+ const query = appContainer.resolve(+ ContainerRegistrationKeys.QUERY+ )+ const { data: orderGroup } = await query.graph({+ entity: "order_group",+ filters: { id: orderGroupId },+ fields: ["id", "orders.id"],+ })+ return (orderGroup[0] as any).orders[0]+ }++ beforeAll(async () => {+ appContainer = getContainer()+ })++ beforeEach(async () => {+ const customerResult = await createCustomerUser(appContainer, {+ email: "[email protected]",+ first_name: "Payment",+ last_name: "Buyer",+ })+ const apiKey = await generatePublishableKey(appContainer)+ const baseStoreHeaders = generateStoreHeaders({+ publishableKey: apiKey,+ })+ storeHeaders = {+ headers: {+ ...baseStoreHeaders.headers,+ ...customerResult.headers.headers,+ },+ }++ const salesChannelModule =+ appContainer.resolve<ISalesChannelModuleService>(+ Modules.SALES_CHANNEL+ )+ salesChannel = await salesChannelModule.createSalesChannels({+ name: "Payment Channel",+ })++ const regionModule = appContainer.resolve<IRegionModuleService>(+ Modules.REGION+ )+ region = await regionModule.createRegions({+ name: "Payment Region",+ currency_code: "usd",+ countries: ["us"],+ })++ const link = appContainer.resolve(ContainerRegistrationKeys.LINK)+ await link.create({+ [Modules.REGION]: { region_id: region.id },+ [Modules.PAYMENT]: {+ payment_provider_id: "pp_system_default",+ },+ })++ sellerSeed = await seedSellerOfferWithShipping({+ email: "[email protected]",+ name: "PaymentS1",+ stocked: 20,+ offerPrice: 2500,+ })+ })++ it("GET /vendor/orders/:id surfaces the cart payment collection and an authorized payment_status", async () => {+ const order = await completeCartCheckout(sellerSeed.offer.id)++ const { data } = await api.get(+ `/vendor/orders/${order.id}`,+ sellerSeed.headers+ )++ expect(data.order.payment_collections).toHaveLength(1)+ expect(data.order.payment_collections[0].amount).toBeGreaterThan(+ 0+ )+ expect(["authorized", "captured"]).toContain(+ data.order.payment_status+ )+ // The shared cart must not leak onto the response.+ expect(data.order.cart).toBeUndefined()+ })++ it("GET /vendor/orders list surfaces payment_collections and payment_status", async () => {+ const order = await completeCartCheckout(sellerSeed.offer.id)++ const { data } = await api.get(+ `/vendor/orders`,+ sellerSeed.headers+ )++ const listed = data.orders.find((o: any) => o.id === order.id)+ expect(listed).toBeDefined()+ expect(listed.payment_collections).toHaveLength(1)+ expect(["authorized", "captured"]).toContain(+ listed.payment_status+ )+ })+ })+ },+})diff --git a/packages/core/src/api/vendor/orders/[id]/route.ts b/packages/core/src/api/vendor/orders/[id]/route.tsindex 8787b3ba9..5ce387a71 100644--- a/packages/core/src/api/vendor/orders/[id]/route.ts+++ b/packages/core/src/api/vendor/orders/[id]/route.ts@@ -8,6 +8,7 @@ import { HttpTypes } from "@mercurjs/types"import {normalizeOrderPaymentCollections,validateSellerOrder,+ withCartPaymentCollectionFields,} from "../helpers"export const GET = async (@@ -21,7 +22,7 @@ export const GET = async (const workflow = getOrderDetailWorkflow(req.scope)const { result } = await workflow.run({input: {- fields: req.queryConfig.fields,+ fields: withCartPaymentCollectionFields(req.queryConfig.fields),order_id: req.params.id,},})diff --git a/packages/core/src/api/vendor/orders/helpers.ts b/packages/core/src/api/vendor/orders/helpers.tsindex b2b3ccb30..ef8a8c2c9 100644--- a/packages/core/src/api/vendor/orders/helpers.ts+++ b/packages/core/src/api/vendor/orders/helpers.ts@@ -1,17 +1,44 @@import { MedusaContainer } from "@medusajs/framework"+import type { OrderDetailDTO } from "@medusajs/framework/types"import {ContainerRegistrationKeys,MedusaError,} from "@medusajs/framework/utils"+import { deduplicate } from "@medusajs/framework/utils"++import { getLastPaymentStatus } from "../../../workflows/order-group/utils/aggregate-status"+type OrderWithCartPaymentCollection = {cart?: { payment_collection?: unknown } | nullpayment_collections?: unknown[]+ payment_status?: string+}++// The shared cart payment collection is reached through the cart, not linked+// to the order. These fields must always be loaded so the routes can normalize+// them back onto `payment_collections` and recompute `payment_status` — even+// when the client sends an absolute `fields=` list that would otherwise replace+// the route defaults.+const CART_PAYMENT_COLLECTION_FIELDS = [+ "cart.payment_collection.*",+ "cart.payment_collection.payments.*",+ "cart.payment_collection.payments.refunds.*",+ "cart.payment_collection.payments.refunds.refund_reason.*",+ "cart.payment_collection.payment_sessions.*",+]++export const withCartPaymentCollectionFields = (+ fields: string[]+): string[] => {+ return deduplicate([...fields, ...CART_PAYMENT_COLLECTION_FIELDS])}// The shared cart payment collection is fetched via `cart.payment_collection`// (it is not linked directly to an order). Expose it back on the order under-// `payment_collections` so consumers keep the familiar shape.+// `payment_collections` so consumers keep the familiar shape, and recompute+// `payment_status` from it — Medusa's aggregation reads the linked payment+// collections, which are always empty for split orders under the cart-path model.export const normalizeOrderPaymentCollections = <T extends OrderWithCartPaymentCollection>(@@ -21,6 +48,10 @@ export const normalizeOrderPaymentCollections = <order.payment_collections = paymentCollection ? [paymentCollection] : []delete order.cart+ order.payment_status = getLastPaymentStatus(+ order as unknown as OrderDetailDTO+ )+return order}diff --git a/packages/core/src/api/vendor/orders/route.ts b/packages/core/src/api/vendor/orders/route.tsindex ef84d0dd0..7a05cb41a 100644--- a/packages/core/src/api/vendor/orders/route.ts+++ b/packages/core/src/api/vendor/orders/route.ts@@ -6,7 +6,10 @@ import {import { OrderDTO } from "@medusajs/framework/types"import { HttpTypes } from "@mercurjs/types"-import { normalizeOrderPaymentCollections } from "./helpers"+import {+ normalizeOrderPaymentCollections,+ withCartPaymentCollectionFields,+} from "./helpers"export const GET = async (req: AuthenticatedMedusaRequest,@@ -23,7 +26,7 @@ export const GET = async (const workflow = getOrdersListWorkflow(req.scope)const { result } = await workflow.run({input: {- fields: req.queryConfig.fields,+ fields: withCartPaymentCollectionFields(req.queryConfig.fields),variables,},})