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
feat: add tests for seller-specific promotions in cart functionality
vholikaf8bff6e815b
diff --git a/integration-tests/http/cart/store/cart.spec.ts b/integration-tests/http/cart/store/cart.spec.tsindex 29ba9f6cc..9cf1eee33 100644--- a/integration-tests/http/cart/store/cart.spec.ts+++ b/integration-tests/http/cart/store/cart.spec.ts@@ -608,6 +608,319 @@ medusaIntegrationTestRunner({})})+ describe("Promotions/Discounts", () => {+ it("should apply seller promotion only to that seller's items", async () => {+ // Create promotion for seller (10% off order)+ const promotionResponse = await api.post(+ `/vendor/promotions`,+ {+ code: "SELLER10",+ type: "standard",+ status: "active",+ application_method: {+ type: "percentage",+ target_type: "order",+ value: 10,+ },+ },+ sellerHeaders+ )+ expect(promotionResponse.status).toEqual(200)++ // Create cart with item+ const cartResponse = await api.post(+ `/store/carts`,+ {+ region_id: region.id,+ sales_channel_id: salesChannel.id,+ currency_code: "usd",+ },+ storeHeaders+ )+ let cart = cartResponse.data.cart++ // Add item to cart (item price: $20.00)+ const addItemResponse = await api.post(+ `/store/carts/${cart.id}/line-items`,+ {+ variant_id: product.variants[0].id,+ quantity: 1,+ },+ storeHeaders+ )+ cart = addItemResponse.data.cart++ // Apply promotion+ const promoResponse = await api.post(+ `/store/carts/${cart.id}/promotions`,+ {+ promo_codes: ["SELLER10"],+ },+ storeHeaders+ )++ expect(promoResponse.status).toEqual(200)+ cart = promoResponse.data.cart++ // Verify discount was applied+ expect(cart.items[0].adjustments).toBeDefined()+ expect(cart.items[0].adjustments.length).toBeGreaterThan(0)+ expect(cart.items[0].adjustments[0].code).toEqual("SELLER10")+ expect(cart.items[0].adjustments[0].amount).toBeGreaterThan(0)+ })++ it("should only apply seller promotion to that seller's items when cart has multiple sellers", async () => {+ // Create second seller with product+ const seller2Result = await createSellerUser(appContainer, {+ email: "[email protected]",+ name: "Promo Seller 2",+ })+ const seller2Headers = seller2Result.headers++ // Create product for seller 2+ const product2Response = await api.post(+ `/vendor/products`,+ {+ status: "published",+ title: "Seller 2 Product",+ options: [{ title: "Size", values: ["M"] }],+ variants: [+ {+ title: "Medium",+ sku: "S2-M",+ options: { Size: "M" },+ prices: [{ currency_code: "usd", amount: 3000 }],+ manage_inventory: false,+ },+ ],+ sales_channels: [{ id: salesChannel.id }],+ },+ seller2Headers+ )+ const product2 = product2Response.data.product++ // Create promotion for seller 1 only (20% off order)+ await api.post(+ `/vendor/promotions`,+ {+ code: "SELLER1ONLY",+ type: "standard",+ status: "active",+ application_method: {+ type: "percentage",+ target_type: "order",+ value: 20,+ },+ },+ sellerHeaders+ )++ // Create cart+ const cartResponse = await api.post(+ `/store/carts`,+ {+ region_id: region.id,+ sales_channel_id: salesChannel.id,+ currency_code: "usd",+ },+ storeHeaders+ )+ let cart = cartResponse.data.cart++ // Add item from seller 1 ($20.00)+ await api.post(+ `/store/carts/${cart.id}/line-items`,+ {+ variant_id: product.variants[0].id,+ quantity: 1,+ },+ storeHeaders+ )++ // Add item from seller 2 ($30.00)+ await api.post(+ `/store/carts/${cart.id}/line-items`,+ {+ variant_id: product2.variants[0].id,+ quantity: 1,+ },+ storeHeaders+ )++ // Apply seller 1's promotion+ const promoResponse = await api.post(+ `/store/carts/${cart.id}/promotions`,+ {+ promo_codes: ["SELLER1ONLY"],+ },+ storeHeaders+ )++ expect(promoResponse.status).toEqual(200)+ cart = promoResponse.data.cart++ // Find seller 1's item and seller 2's item+ const seller1Item = cart.items.find((item: any) => item.variant_id === product.variants[0].id)+ const seller2Item = cart.items.find((item: any) => item.variant_id === product2.variants[0].id)++ // Seller 1's item should have the discount+ const seller1Adjustment = seller1Item.adjustments?.find(+ (adj: any) => adj.code === "SELLER1ONLY"+ )+ expect(seller1Adjustment).toBeDefined()+ expect(seller1Adjustment.amount).toBeGreaterThan(0)++ // Seller 2's item should NOT have any discount adjustments from seller 1's promotion+ const seller2Adjustments = seller2Item.adjustments?.filter(+ (adj: any) => adj.code === "SELLER1ONLY"+ ) || []+ expect(seller2Adjustments.length).toEqual(0)+ })++ it("should apply different seller promotions to their respective items", async () => {+ // Create second seller with product+ const seller2Result = await createSellerUser(appContainer, {+ email: "[email protected]",+ name: "Multi Promo Seller 2",+ })+ const seller2Headers = seller2Result.headers++ // Create product for seller 2+ const product2Response = await api.post(+ `/vendor/products`,+ {+ status: "published",+ title: "Seller 2 Multi Product",+ options: [{ title: "Size", values: ["L"] }],+ variants: [+ {+ title: "Large",+ sku: "S2-L-MULTI",+ options: { Size: "L" },+ prices: [{ currency_code: "usd", amount: 5000 }],+ manage_inventory: false,+ },+ ],+ sales_channels: [{ id: salesChannel.id }],+ },+ seller2Headers+ )+ const product2 = product2Response.data.product++ // Create promotion for seller 1 (10% off)+ await api.post(+ `/vendor/promotions`,+ {+ code: "SELLER1TEN",+ type: "standard",+ status: "active",+ application_method: {+ type: "percentage",+ target_type: "order",+ value: 10,+ },+ },+ sellerHeaders+ )++ // Create promotion for seller 2 (15% off)+ await api.post(+ `/vendor/promotions`,+ {+ code: "SELLER2FIFTEEN",+ type: "standard",+ status: "active",+ application_method: {+ type: "percentage",+ target_type: "order",+ value: 15,+ },+ },+ seller2Headers+ )++ // Create cart+ const cartResponse = await api.post(+ `/store/carts`,+ {+ region_id: region.id,+ sales_channel_id: salesChannel.id,+ currency_code: "usd",+ },+ storeHeaders+ )+ let cart = cartResponse.data.cart++ // Add item from seller 1 ($20.00)+ await api.post(+ `/store/carts/${cart.id}/line-items`,+ {+ variant_id: product.variants[0].id,+ quantity: 1,+ },+ storeHeaders+ )++ // Add item from seller 2 ($50.00)+ await api.post(+ `/store/carts/${cart.id}/line-items`,+ {+ variant_id: product2.variants[0].id,+ quantity: 1,+ },+ storeHeaders+ )++ // Apply both promotions+ await api.post(+ `/store/carts/${cart.id}/promotions`,+ {+ promo_codes: ["SELLER1TEN"],+ },+ storeHeaders+ )++ const promoResponse = await api.post(+ `/store/carts/${cart.id}/promotions`,+ {+ promo_codes: ["SELLER2FIFTEEN"],+ },+ storeHeaders+ )++ expect(promoResponse.status).toEqual(200)+ cart = promoResponse.data.cart++ // Find items+ const seller1Item = cart.items.find((item: any) => item.variant_id === product.variants[0].id)+ const seller2Item = cart.items.find((item: any) => item.variant_id === product2.variants[0].id)++ // Seller 1's item should have SELLER1TEN discount+ const seller1Adjustment = seller1Item.adjustments?.find(+ (adj: any) => adj.code === "SELLER1TEN"+ )+ expect(seller1Adjustment).toBeDefined()+ expect(seller1Adjustment.amount).toBeGreaterThan(0)++ // Seller 2's item should have SELLER2FIFTEEN discount+ const seller2Adjustment = seller2Item.adjustments?.find(+ (adj: any) => adj.code === "SELLER2FIFTEEN"+ )+ expect(seller2Adjustment).toBeDefined()+ expect(seller2Adjustment.amount).toBeGreaterThan(0)++ // Verify cross-seller promotions are not applied+ const seller1WrongAdjustment = seller1Item.adjustments?.find(+ (adj: any) => adj.code === "SELLER2FIFTEEN"+ )+ const seller2WrongAdjustment = seller2Item.adjustments?.find(+ (adj: any) => adj.code === "SELLER1TEN"+ )+ expect(seller1WrongAdjustment).toBeUndefined()+ expect(seller2WrongAdjustment).toBeUndefined()+ })+ })+describe("Shipping Options", () => {it("should return shipping options grouped by seller", async () => {// Create cart with itemdiff --git a/packages/core/src/api/store/carts/[id]/promotions/route.ts b/packages/core/src/api/store/carts/[id]/promotions/route.tsnew file mode 100644index 000000000..1ecfeace1--- /dev/null+++ b/packages/core/src/api/store/carts/[id]/promotions/route.ts@@ -0,0 +1,33 @@+import { MedusaRequest, MedusaResponse } from "@medusajs/framework/http"+import { HttpTypes } from "@medusajs/framework/types"+import { PromotionActions } from "@medusajs/framework/utils"+import { refetchCart } from "@medusajs/medusa/api/store/carts/helpers"++import { updateCartSellerPromotionsWorkflow } from "../../../../../workflows/cart/update-cart-seller-promotions"++export const POST = async (+ req: MedusaRequest<HttpTypes.StoreCartAddPromotion, HttpTypes.SelectParams>,+ res: MedusaResponse<HttpTypes.StoreCartResponse>+) => {+ const payload = req.validatedBody++ await updateCartSellerPromotionsWorkflow(req.scope).run({+ input: {+ promo_codes: payload.promo_codes,+ cart_id: req.params.id,+ action:+ payload.promo_codes.length > 0+ ? PromotionActions.ADD+ : PromotionActions.REPLACE,+ force_refresh_payment_collection: true,+ },+ })++ const cart = await refetchCart(+ req.params.id,+ req.scope,+ req.queryConfig.fields+ )++ res.status(200).json({ cart })+}diff --git a/packages/core/src/workflows/cart/steps/prepare-adjustments-from-promotion-actions.ts b/packages/core/src/workflows/cart/steps/prepare-adjustments-from-promotion-actions.tsnew file mode 100644index 000000000..d1dccc296--- /dev/null+++ b/packages/core/src/workflows/cart/steps/prepare-adjustments-from-promotion-actions.ts@@ -0,0 +1,165 @@+import {+ AddItemAdjustmentAction,+ AddShippingMethodAdjustment,+ ComputeActions,+ PromotionDTO,+ RemoveItemAdjustmentAction,+ RemoveShippingMethodAdjustment,+} from "@medusajs/framework/types"+import {+ ComputedActions,+ ContainerRegistrationKeys,+ promiseAll,+} from "@medusajs/framework/utils"+import { StepResponse, createStep } from "@medusajs/framework/workflows-sdk"+import { PrepareAdjustmentsFromPromotionActionsStepOutput } from "@medusajs/medusa/core-flows"+++export interface PrepareSellerAdjustmentsFromPromotionActionsStepInput {+ actions: ComputeActions[]+}++export const prepareSellerAdjustmentsFromPromotionActionsStep = createStep(+ "prepare-seller-adjustments-from-promotion-actions",+ async (+ data: PrepareSellerAdjustmentsFromPromotionActionsStepInput,+ { container }+ ) => {+ const query = container.resolve(ContainerRegistrationKeys.QUERY)++ const { actions = [] } = data++ if (!actions.length) {+ return new StepResponse({+ lineItemAdjustmentsToCreate: [],+ lineItemAdjustmentIdsToRemove: [],+ shippingMethodAdjustmentsToCreate: [],+ shippingMethodAdjustmentIdsToRemove: [],+ computedPromotionCodes: [],+ } as PrepareAdjustmentsFromPromotionActionsStepOutput)+ }++ const [{ data: promotions }, { data: lineItems }, { data: shippingMethods }] = await promiseAll([query.graph(+ {+ entity: "promotion",+ fields: ["id", "code", 'seller.id'],+ filters: { code: actions.map((a) => a.code) },+ },+ { cache: { enable: true } },+ ), query.graph(+ {+ entity: "line_item",+ fields: ['id', 'variant.id', 'variant.product.id', 'variant.product.seller.id'],+ filters: { id: actions.filter((a) => a.action === ComputedActions.ADD_ITEM_ADJUSTMENT).map((a) => (a as AddItemAdjustmentAction).item_id) },+ },+ { cache: { enable: true } },+ ), query.graph(+ {+ entity: "shipping_method",+ fields: ['id', 'shipping_option_id'],+ filters: { id: actions.filter((a) => a.action === ComputedActions.ADD_SHIPPING_METHOD_ADJUSTMENT).map((a) => (a as AddShippingMethodAdjustment).shipping_method_id) },+ },+ { cache: { enable: true } },+ )])+ const { data: shippingOptions } = await query.graph(+ {+ entity: "shipping_option",+ fields: ['id', 'seller.id'],+ filters: { id: shippingMethods.map((sm) => sm.shipping_option_id) },+ },+ { cache: { enable: true } },+ )++ const promotionsMap = new Map<string, PromotionDTO & { seller?: { id: string } }>(+ promotions.map((promotion) => [promotion.code!, promotion])+ )+ const shippingMethodsMap = new Map<string, { id: string, shipping_option_id: string, }>(+ shippingMethods.map((shippingMethod) => [shippingMethod.id!, shippingMethod])+ )+ const shippingOptionsMap = new Map<string, { id: string, seller?: { id: string } }>(+ shippingOptions.map((shippingOption) => [shippingOption.id!, shippingOption])+ )+ const lineItemsMap = new Map<string, { id: string, variant: { id: string, product: { id: string, seller?: { id: string } } } }>(+ lineItems.map((lineItem) => [lineItem.id!, lineItem])+ )++ const lineItemAdjustmentsToCreate: PrepareAdjustmentsFromPromotionActionsStepOutput["lineItemAdjustmentsToCreate"] =+ []+ const lineItemAdjustmentIdsToRemove: string[] = []+ const shippingMethodAdjustmentsToCreate: PrepareAdjustmentsFromPromotionActionsStepOutput["shippingMethodAdjustmentsToCreate"] =+ []+ const shippingMethodAdjustmentIdsToRemove: string[] = []++ for (const action of actions) {+ switch (action.action) {+ case ComputedActions.ADD_ITEM_ADJUSTMENT:+ const itemAction = action as AddItemAdjustmentAction+ const promotion = promotionsMap.get(itemAction.code)+ const lineItem = lineItemsMap.get(itemAction.item_id)++ if (promotion && lineItem) {+ const promotionSellerId = promotion.seller?.id+ const itemSellerId = lineItem.variant?.product?.seller?.id++ // If promotion has no seller, add adjustment for all items+ // If promotion has a seller, only add if it matches the item's seller+ if (!promotionSellerId || promotionSellerId === itemSellerId) {+ lineItemAdjustmentsToCreate.push({+ code: action.code,+ amount: itemAction.amount as number,+ is_tax_inclusive: itemAction.is_tax_inclusive,+ item_id: itemAction.item_id,+ promotion_id: promotion.id,+ } as PrepareAdjustmentsFromPromotionActionsStepOutput["lineItemAdjustmentsToCreate"][number])+ }+ }+ break+ case ComputedActions.REMOVE_ITEM_ADJUSTMENT:+ lineItemAdjustmentIdsToRemove.push(+ (action as RemoveItemAdjustmentAction).adjustment_id+ )+ break+ case ComputedActions.ADD_SHIPPING_METHOD_ADJUSTMENT:+ const shippingAction = action as AddShippingMethodAdjustment+ const shippingMethod = shippingMethodsMap.get(shippingAction.shipping_method_id)+ const shippingOption = shippingOptionsMap.get(shippingMethod?.shipping_option_id!)+ const shippingPromotion = promotionsMap.get(action.code)++ if (shippingMethod && shippingPromotion) {+ const promotionSellerId = shippingPromotion.seller?.id+ const shippingMethodSellerId = shippingOption?.seller?.id++ // If promotion has no seller, add adjustment for all shipping methods+ // If promotion has a seller, only add if it matches the shipping method's seller+ if (!promotionSellerId || promotionSellerId === shippingMethodSellerId) {+ shippingMethodAdjustmentsToCreate.push({+ code: action.code,+ amount: shippingAction.amount as number,+ shipping_method_id: shippingAction.shipping_method_id,+ promotion_id: shippingPromotion.id,+ })+ }+ }+ break+ case ComputedActions.REMOVE_SHIPPING_METHOD_ADJUSTMENT:+ shippingMethodAdjustmentIdsToRemove.push(+ (action as RemoveShippingMethodAdjustment).adjustment_id+ )+ break+ }+ }++ const computedPromotionCodes = [+ ...lineItemAdjustmentsToCreate,+ ...shippingMethodAdjustmentsToCreate,+ ].map((adjustment) => adjustment.code)++ return new StepResponse({+ lineItemAdjustmentsToCreate,+ lineItemAdjustmentIdsToRemove,+ shippingMethodAdjustmentsToCreate,+ shippingMethodAdjustmentIdsToRemove,+ computedPromotionCodes,+ } as PrepareAdjustmentsFromPromotionActionsStepOutput)+ }+)\ No newline at end of filediff --git a/packages/core/src/workflows/cart/update-cart-seller-promotions.ts b/packages/core/src/workflows/cart/update-cart-seller-promotions.tsnew file mode 100644index 000000000..395dc7c0f--- /dev/null+++ b/packages/core/src/workflows/cart/update-cart-seller-promotions.ts@@ -0,0 +1,111 @@+import { PromotionActions } from "@medusajs/framework/utils"+import {+ createHook,+ createWorkflow,+ parallelize,+ transform,+ when,+ WorkflowResponse,+} from "@medusajs/framework/workflows-sdk"+import { acquireLockStep, createLineItemAdjustmentsStep, createShippingMethodAdjustmentsStep, getActionsToComputeFromPromotionsStep, getPromotionCodesToApply, prepareAdjustmentsFromPromotionActionsStep, refreshPaymentCollectionForCartWorkflow, releaseLockStep, removeLineItemAdjustmentsStep, removeShippingMethodAdjustmentsStep, updateCartPromotionsStep, UpdateCartPromotionsWorkflowInput, useQueryGraphStep, validateCartStep } from "@medusajs/medusa/core-flows"+import { cartFieldsForRefreshSteps } from "./utils"+import { prepareSellerAdjustmentsFromPromotionActionsStep } from "./steps/prepare-adjustments-from-promotion-actions"+++export const updateCartSellerPromotionsWorkflow = createWorkflow(+ {+ name: 'update-cart-seller-promotions',+ idempotent: false,+ },+ (input: UpdateCartPromotionsWorkflowInput) => {+ const fetchCart = when("should-fetch-cart", { input }, ({ input }) => {+ return !input.cart+ }).then(() => {+ const { data: cart } = useQueryGraphStep({+ entity: "cart",+ fields: cartFieldsForRefreshSteps,+ filters: { id: input.cart_id },+ options: { isList: false },+ }).config({ name: "fetch-cart" })++ return cart+ })++ const cart = transform({ fetchCart, input }, ({ fetchCart, input }) => {+ return input.cart ?? fetchCart+ })++ validateCartStep({ cart })++ acquireLockStep({+ key: cart.id,+ timeout: 2,+ ttl: 10,+ })++ const validate = createHook("validate", {+ input,+ cart,+ })++ const promo_codes = transform({ input }, (data) => {+ return (data.input.promo_codes || []) as string[]+ })++ const action = transform({ input }, (data) => {+ return data.input.action || PromotionActions.ADD+ })++ const promotionCodesToApply = getPromotionCodesToApply({+ cart: cart,+ promo_codes,+ action: action as PromotionActions,+ })++ const actions = getActionsToComputeFromPromotionsStep({+ computeActionContext: cart,+ promotionCodesToApply,+ })++ const {+ lineItemAdjustmentsToCreate,+ lineItemAdjustmentIdsToRemove,+ shippingMethodAdjustmentsToCreate,+ shippingMethodAdjustmentIdsToRemove,+ computedPromotionCodes,+ } = prepareSellerAdjustmentsFromPromotionActionsStep({ actions })++ parallelize(+ removeLineItemAdjustmentsStep({ lineItemAdjustmentIdsToRemove }),+ removeShippingMethodAdjustmentsStep({+ shippingMethodAdjustmentIdsToRemove,+ }),+ createLineItemAdjustmentsStep({ lineItemAdjustmentsToCreate }),+ createShippingMethodAdjustmentsStep({+ shippingMethodAdjustmentsToCreate,+ }),+ updateCartPromotionsStep({+ id: cart.id,+ promo_codes: computedPromotionCodes,+ action: PromotionActions.REPLACE,+ })+ )++ when(+ { input },+ ({ input }) => input.force_refresh_payment_collection === true+ ).then(() => {+ refreshPaymentCollectionForCartWorkflow.runAsStep({+ input: { cart },+ })+ })++ releaseLockStep({+ key: cart.id,+ })++ return new WorkflowResponse(void 0, {+ hooks: [validate],+ })+ }+)\ No newline at end of filediff --git a/packages/core/src/workflows/cart/utils/fields.ts b/packages/core/src/workflows/cart/utils/fields.tsindex 02c0a7ed1..dfbcca5bd 100644--- a/packages/core/src/workflows/cart/utils/fields.ts+++ b/packages/core/src/workflows/cart/utils/fields.ts@@ -1,3 +1,52 @@+// Always ensure that cartFieldsForPricingContext is present in cartFieldsForRefreshSteps+// Always ensure that cartFieldsForCalculateShippingOptionsPrices is present in cartFieldsForRefreshSteps+export const cartFieldsForRefreshSteps = [+ "id",+ "email",+ "currency_code",+ "quantity",+ "subtotal",+ "item_total",+ "locale",+ "total",+ "item_subtotal",+ "shipping_subtotal",+ "region_id",+ "metadata",+ "completed_at",+ "sales_channel_id",+ "region.*",+ "items.*",+ "items.product.id",+ "items.product.is_giftcard",+ "items.product.collection_id",+ "items.product.categories.id",+ "items.product.tags.id",+ "items.product.type_id",+ "items.variant.id",+ "items.variant.product.id",+ "items.variant.weight",+ "items.variant.length",+ "items.variant.height",+ "items.variant.width",+ "items.variant.material",+ "items.adjustments.*",+ "items.tax_lines.*",+ "shipping_address.*",+ "shipping_methods.*",+ "shipping_methods.adjustments.*",+ "shipping_methods.tax_lines.*",+ "shipping_methods.shipping_option.shipping_option_type_id",+ "customer.*",+ "customer.groups.*",+ "promotions.id",+ "promotions.code",+ "payment_collection.id",+ "payment_collection.raw_amount",+ "payment_collection.amount",+ "payment_collection.currency_code",+ "payment_collection.payment_sessions.id",+]export const completeCartFields = ["metadata",