Skip to content

The complete open source platform to run your entire marketplace. Storefront, vendor panel, admin console, and integrations in one enterprise-grade platform you own.

Feat/split cart (#658)

Viktor Holike37d43849cfd
diff --git a/integration-tests/helpers/create-customer-user.ts b/integration-tests/helpers/create-customer-user.ts
new file mode 100644
index 000000000..7270afa6e
--- /dev/null
+++ b/integration-tests/helpers/create-customer-user.ts
@@ -0,0 +1,77 @@
+import {
+ IAuthModuleService,
+ ICustomerModuleService,
+ MedusaContainer,
+} from "@medusajs/framework/types"
+import {
+ ContainerRegistrationKeys,
+ Modules,
+} from "@medusajs/framework/utils"
+import jwt from "jsonwebtoken"
+import Scrypt from "scrypt-kdf"
+
+export const customerHeaders = {
+ headers: { "x-medusa-access-token": "test_token" },
+}
+
+export const createCustomerUser = async (
+ container: MedusaContainer,
+ options?: { email?: string; first_name?: string; last_name?: string }
+) => {
+ const email = options?.email ?? "[email protected]"
+ const first_name = options?.first_name ?? "Test"
+ const last_name = options?.last_name ?? "Customer"
+
+ const authModule: IAuthModuleService = container.resolve(Modules.AUTH)
+ const customerModule: ICustomerModuleService = container.resolve(Modules.CUSTOMER)
+
+ const customer = await customerModule.createCustomers({
+ first_name,
+ last_name,
+ email,
+ })
+
+ const hashConfig = { logN: 15, r: 8, p: 1 }
+ const passwordHash = await Scrypt.kdf("somepassword", hashConfig)
+
+ const authIdentity = await authModule.createAuthIdentities({
+ provider_identities: [
+ {
+ provider: "emailpass",
+ entity_id: email,
+ provider_metadata: {
+ password: passwordHash.toString("base64"),
+ },
+ },
+ ],
+ app_metadata: {
+ customer_id: customer.id,
+ },
+ })
+
+ const config = container.resolve(ContainerRegistrationKeys.CONFIG_MODULE)
+ const { projectConfig } = config
+ const { jwtSecret, jwtOptions } = projectConfig.http
+ const token = jwt.sign(
+ {
+ actor_id: customer.id,
+ actor_type: "customer",
+ auth_identity_id: authIdentity.id,
+ },
+ jwtSecret,
+ {
+ expiresIn: "1d",
+ ...jwtOptions,
+ }
+ )
+
+ customerHeaders.headers["authorization"] = `Bearer ${token}`
+
+ const headers = {
+ headers: {
+ authorization: `Bearer ${token}`,
+ },
+ }
+
+ return { customer, authIdentity, headers }
+}
diff --git a/integration-tests/http/cart/store/cart.spec.ts b/integration-tests/http/cart/store/cart.spec.ts
new file mode 100644
index 000000000..951dd9933
--- /dev/null
+++ b/integration-tests/http/cart/store/cart.spec.ts
@@ -0,0 +1,612 @@
+import { medusaIntegrationTestRunner } from "@medusajs/test-utils"
+import {
+ IApiKeyModuleService,
+ IRegionModuleService,
+ ISalesChannelModuleService,
+ MedusaContainer,
+} from "@medusajs/framework/types"
+import { ApiKeyType, ContainerRegistrationKeys, Modules } from "@medusajs/framework/utils"
+import { createSellerUser } from "../../../helpers/create-seller-user"
+import { createCustomerUser } from "../../../helpers/create-customer-user"
+import { generatePublishableKey, generateStoreHeaders } from "../../../helpers/create-admin-user"
+
+jest.setTimeout(120000)
+
+medusaIntegrationTestRunner({
+ testSuite: ({ getContainer, api }) => {
+ describe("Store - Cart", () => {
+ let appContainer: MedusaContainer
+ let seller: any
+ let sellerHeaders: any
+ let customer: any
+ let customerHeaders: any
+ let storeHeaders: any
+ let region: any
+ let salesChannel: any
+ let product: any
+ let shippingOption: any
+
+ beforeAll(async () => {
+ appContainer = getContainer()
+ })
+
+ beforeEach(async () => {
+ // Create seller
+ const sellerResult = await createSellerUser(appContainer, {
+ email: "[email protected]",
+ name: "Test Seller",
+ })
+ seller = sellerResult.seller
+ sellerHeaders = sellerResult.headers
+
+ // Create customer
+ const customerResult = await createCustomerUser(appContainer, {
+ email: "[email protected]",
+ first_name: "Test",
+ last_name: "Customer",
+ })
+ customer = customerResult.customer
+ customerHeaders = customerResult.headers
+
+ const apiKey = await generatePublishableKey(appContainer)
+ storeHeaders = generateStoreHeaders({ publishableKey: apiKey })
+
+ // Create sales channel
+ const salesChannelModule = appContainer.resolve<ISalesChannelModuleService>(Modules.SALES_CHANNEL)
+ salesChannel = await salesChannelModule.createSalesChannels({
+ name: "Test Store",
+ })
+
+ // Create region
+ const regionModule = appContainer.resolve<IRegionModuleService>(Modules.REGION)
+ region = await regionModule.createRegions({
+ name: "Test Region",
+ currency_code: "usd",
+ countries: ["us"],
+ })
+
+ // Link payment provider to region
+ const link = appContainer.resolve(ContainerRegistrationKeys.LINK)
+ await link.create({
+ [Modules.REGION]: { region_id: region.id },
+ [Modules.PAYMENT]: { payment_provider_id: "pp_system_default" },
+ })
+
+ // Create product with variant
+ const productResponse = await api.post(
+ `/vendor/products`,
+ {
+ status: 'published',
+ title: "Test Product",
+ description: "A test product for cart",
+ options: [{ title: "Size", values: ["S", "M", "L"] }],
+ variants: [
+ {
+ title: "Small",
+ sku: "TEST-S",
+ options: { Size: "S" },
+ prices: [{ currency_code: "usd", amount: 2000 }],
+ manage_inventory: false,
+ },
+ {
+ title: "Medium",
+ sku: "TEST-M",
+ options: { Size: "M" },
+ prices: [{ currency_code: "usd", amount: 2500 }],
+ manage_inventory: false,
+ },
+ ],
+ sales_channels: [{ id: salesChannel.id }],
+ },
+ sellerHeaders
+ )
+ product = productResponse.data.product
+
+ // Create shipping prerequisites
+ const shippingPrerequisites = await createShippingPrerequisites(sellerHeaders)
+
+ // Create shipping option
+ const shippingOptionResponse = await api.post(
+ `/vendor/shipping-options`,
+ {
+ name: "Standard Shipping",
+ service_zone_id: shippingPrerequisites.serviceZone.id,
+ shipping_profile_id: shippingPrerequisites.shippingProfile.id,
+ provider_id: "manual_manual",
+ price_type: "flat",
+ type: {
+ label: "Standard",
+ description: "Standard shipping",
+ code: "standard",
+ },
+ prices: [{ currency_code: "usd", amount: 500 }],
+ rules: [
+ {
+ attribute: "enabled_in_store",
+ value: "true",
+ operator: "eq",
+ },
+ ],
+ },
+ sellerHeaders
+ )
+ shippingOption = shippingOptionResponse.data.shipping_option
+ })
+
+ let prerequisiteCounter = 0
+
+ const createShippingPrerequisites = async (headers: any) => {
+ const uniqueSuffix = `_${Date.now()}_${++prerequisiteCounter}`
+
+ // Create stock location
+ const locationResponse = await api.post(
+ `/vendor/stock-locations`,
+ { name: `Test Warehouse${uniqueSuffix}` },
+ headers
+ )
+ const stockLocation = locationResponse.data.stock_location
+
+ // Create fulfillment set
+ await api.post(
+ `/vendor/stock-locations/${stockLocation.id}/fulfillment-sets`,
+ {
+ name: `Test Fulfillment Set${uniqueSuffix}`,
+ type: "shipping",
+ },
+ headers
+ )
+
+ const updatedLocation = await api.get(
+ `/vendor/stock-locations/${stockLocation.id}?fields=*fulfillment_sets`,
+ headers
+ )
+ const fulfillmentSet = updatedLocation.data.stock_location.fulfillment_sets[0]
+
+ // Create service zone
+ const serviceZoneResponse = await api.post(
+ `/vendor/fulfillment-sets/${fulfillmentSet.id}/service-zones`,
+ {
+ name: `Test Service Zone${uniqueSuffix}`,
+ geo_zones: [{ type: "country", country_code: "us" }],
+ },
+ headers
+ )
+ const serviceZone = serviceZoneResponse.data.fulfillment_set.service_zones.find(
+ (z: any) => z.name === `Test Service Zone${uniqueSuffix}`
+ )
+
+ // Create shipping profile
+ const shippingProfileResponse = await api.post(
+ `/vendor/shipping-profiles`,
+ {
+ name: `Test Shipping Profile${uniqueSuffix}`,
+ type: "default",
+ },
+ headers
+ )
+ const shippingProfile = shippingProfileResponse.data.shipping_profile
+
+ // Add fulfillment provider
+ await api.post(
+ `/vendor/stock-locations/${stockLocation.id}/fulfillment-providers`,
+ { add: ["manual_manual"] },
+ headers
+ )
+
+ // Link stock location to sales channel
+ await api.post(
+ `/vendor/stock-locations/${stockLocation.id}/sales-channels`,
+ { add: [salesChannel.id] },
+ headers
+ )
+
+ return {
+ stockLocation,
+ fulfillmentSet,
+ serviceZone,
+ shippingProfile,
+ }
+ }
+
+ describe("Cart Flow", () => {
+ it("should create a cart", async () => {
+ const response = await api.post(
+ `/store/carts`,
+ {
+ region_id: region.id,
+ sales_channel_id: salesChannel.id,
+ currency_code: "usd",
+ },
+ storeHeaders
+ )
+
+ expect(response.status).toEqual(200)
+ expect(response.data.cart).toBeDefined()
+ expect(response.data.cart.id).toBeDefined()
+ expect(response.data.cart.region_id).toEqual(region.id)
+ })
+
+ it("should add items to cart", async () => {
+ // Create cart
+ const cartResponse = await api.post(
+ `/store/carts`,
+ {
+ region_id: region.id,
+ sales_channel_id: salesChannel.id,
+ currency_code: "usd",
+ },
+ storeHeaders
+ )
+ const cart = cartResponse.data.cart
+
+ // Add item to cart
+ const addItemResponse = await api.post(
+ `/store/carts/${cart.id}/line-items`,
+ {
+ variant_id: product.variants[0].id,
+ quantity: 2,
+ },
+ storeHeaders
+ )
+
+ expect(addItemResponse.status).toEqual(200)
+ expect(addItemResponse.data.cart.items).toHaveLength(1)
+ expect(addItemResponse.data.cart.items[0].quantity).toEqual(2)
+ expect(addItemResponse.data.cart.items[0].variant_id).toEqual(product.variants[0].id)
+ })
+
+ it("should update cart with shipping address", async () => {
+ // Create cart with item
+ const cartResponse = await api.post(
+ `/store/carts`,
+ {
+ region_id: region.id,
+ sales_channel_id: salesChannel.id,
+ currency_code: "usd",
+ },
+ storeHeaders
+ )
+ const cart = cartResponse.data.cart
+
+ await api.post(
+ `/store/carts/${cart.id}/line-items`,
+ {
+ variant_id: product.variants[0].id,
+ quantity: 1,
+ },
+ storeHeaders
+ )
+
+ // Update cart with shipping address
+ const updateResponse = await api.post(
+ `/store/carts/${cart.id}`,
+ {
+ email: "[email protected]",
+ shipping_address: {
+ first_name: "John",
+ last_name: "Doe",
+ address_1: "123 Main St",
+ city: "New York",
+ country_code: "us",
+ postal_code: "10001",
+ },
+ billing_address: {
+ first_name: "John",
+ last_name: "Doe",
+ address_1: "123 Main St",
+ city: "New York",
+ country_code: "us",
+ postal_code: "10001",
+ },
+ },
+ storeHeaders
+ )
+
+ expect(updateResponse.status).toEqual(200)
+ expect(updateResponse.data.cart.shipping_address).toBeDefined()
+ expect(updateResponse.data.cart.shipping_address.city).toEqual("New York")
+ })
+
+ it("should add shipping method to cart", async () => {
+ // Create cart with item
+ const cartResponse = await api.post(
+ `/store/carts`,
+ {
+ region_id: region.id,
+ sales_channel_id: salesChannel.id,
+ currency_code: "usd",
+ },
+ storeHeaders
+ )
+ const cart = cartResponse.data.cart
+
+ await api.post(
+ `/store/carts/${cart.id}/line-items`,
+ {
+ variant_id: product.variants[0].id,
+ quantity: 1,
+ },
+ storeHeaders
+ )
+
+ // Update cart with shipping address
+ await api.post(
+ `/store/carts/${cart.id}`,
+ {
+ email: "[email protected]",
+ shipping_address: {
+ first_name: "John",
+ last_name: "Doe",
+ address_1: "123 Main St",
+ city: "New York",
+ country_code: "us",
+ postal_code: "10001",
+ },
+ },
+ storeHeaders
+ )
+
+ // Get shipping options for cart (grouped by seller)
+ const shippingOptionsResponse = await api.get(
+ `/store/shipping-options?cart_id=${cart.id}`,
+ storeHeaders
+ )
+
+ expect(shippingOptionsResponse.status).toEqual(200)
+
+ // Flatten shipping options from seller map
+ const allShippingOptions = Object.values(
+ shippingOptionsResponse.data.shipping_options as Record<string, any[]>
+ ).flat()
+
+ if (allShippingOptions.length > 0) {
+ // Add shipping method
+ const addShippingResponse = await api.post(
+ `/store/carts/${cart.id}/shipping-methods`,
+ {
+ option_id: allShippingOptions[0].id,
+ },
+ storeHeaders
+ )
+
+ expect(addShippingResponse.status).toEqual(200)
+ expect(addShippingResponse.data.cart.shipping_methods).toBeDefined()
+ }
+ })
+
+ it("should complete full cart checkout flow and return order_group", async () => {
+ // 1. 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
+ expect(cart.id).toBeDefined()
+
+ // 2. Add items to cart
+ const addItemResponse = await api.post(
+ `/store/carts/${cart.id}/line-items`,
+ {
+ variant_id: product.variants[0].id,
+ quantity: 2,
+ },
+ storeHeaders
+ )
+ cart = addItemResponse.data.cart
+ expect(cart.items).toHaveLength(1)
+
+ // 3. Update cart with customer info and addresses
+ const updateResponse = await api.post(
+ `/store/carts/${cart.id}`,
+ {
+ email: "[email protected]",
+ shipping_address: {
+ first_name: "Jane",
+ last_name: "Doe",
+ address_1: "456 Oak Ave",
+ city: "Los Angeles",
+ country_code: "us",
+ postal_code: "90001",
+ phone: "555-1234",
+ },
+ billing_address: {
+ first_name: "Jane",
+ last_name: "Doe",
+ address_1: "456 Oak Ave",
+ city: "Los Angeles",
+ country_code: "us",
+ postal_code: "90001",
+ },
+ },
+ storeHeaders
+ )
+ cart = updateResponse.data.cart
+ expect(cart.email).toEqual("[email protected]")
+ expect(cart.shipping_address).toBeDefined()
+
+ // 4. Get available shipping options (grouped by seller)
+ const shippingOptionsResponse = await api.get(
+ `/store/shipping-options?cart_id=${cart.id}`,
+ storeHeaders
+ )
+
+ // Flatten shipping options from seller map
+ const allShippingOptions = Object.values(
+ shippingOptionsResponse.data.shipping_options as Record<string, any[]>
+ ).flat()
+
+ // 5. Add shipping method if available
+ if (allShippingOptions.length > 0) {
+ const addShippingResponse = await api.post(
+ `/store/carts/${cart.id}/shipping-methods`,
+ {
+ option_id: allShippingOptions[0].id,
+ },
+ storeHeaders
+ )
+ cart = addShippingResponse.data.cart
+ expect(cart.shipping_methods?.length).toBeGreaterThan(0)
+ }
+
+ // 6. Create payment collection for the cart
+ const paymentCollectionResponse = await api.post(
+ `/store/payment-collections`,
+ { cart_id: cart.id },
+ storeHeaders
+ )
+
+ const paymentCollection = paymentCollectionResponse.data.payment_collection
+ // 7. Initialize payment session
+ await api.post(
+ `/store/payment-collections/${paymentCollection.id}/payment-sessions`,
+ {
+ provider_id: "pp_system_default",
+ },
+ storeHeaders
+ )
+
+ // 8. Complete the cart using complete endpoint
+ const completeResponse = await api.post(
+ `/store/carts/${cart.id}/complete`,
+ {},
+ storeHeaders
+ )
+
+ expect(completeResponse.status).toEqual(200)
+ expect(completeResponse.data.type).toEqual("order_group")
+ expect(completeResponse.data.order_group).toBeDefined()
+ expect(completeResponse.data.order_group.id).toBeDefined()
+ })
+
+ it("should add multiple items from different variants", async () => {
+ // Create cart
+ const cartResponse = await api.post(
+ `/store/carts`,
+ {
+ region_id: region.id,
+ sales_channel_id: salesChannel.id,
+ currency_code: "usd",
+ },
+ storeHeaders
+ )
+ const cart = cartResponse.data.cart
+
+ // Add first variant
+ await api.post(
+ `/store/carts/${cart.id}/line-items`,
+ {
+ variant_id: product.variants[0].id,
+ quantity: 1,
+ },
+ storeHeaders
+ )
+
+ // Add second variant
+ const addSecondResponse = await api.post(
+ `/store/carts/${cart.id}/line-items`,
+ {
+ variant_id: product.variants[1].id,
+ quantity: 2,
+ },
+ storeHeaders
+ )
+
+ expect(addSecondResponse.data.cart.items).toHaveLength(2)
+ })
+
+ it("should update line item quantity", async () => {
+ // Create cart with item
+ const cartResponse = await api.post(
+ `/store/carts`,
+ {
+ region_id: region.id,
+ sales_channel_id: salesChannel.id,
+ currency_code: "usd",
+ },
+ storeHeaders
+ )
+ const cart = cartResponse.data.cart
+
+ const addItemResponse = await api.post(
+ `/store/carts/${cart.id}/line-items`,
+ {
+ variant_id: product.variants[0].id,
+ quantity: 1,
+ },
+ storeHeaders
+ )
+ const lineItemId = addItemResponse.data.cart.items[0].id
+
+ // Update quantity
+ const updateResponse = await api.post(
+ `/store/carts/${cart.id}/line-items/${lineItemId}`,
+ {
+ quantity: 5,
+ },
+ storeHeaders
+ )
+
+ expect(updateResponse.data.cart.items[0].quantity).toEqual(5)
+ })
+
+ it("should remove line item from cart", async () => {
+ // Create cart with item
+ const cartResponse = await api.post(
+ `/store/carts`,
+ {
+ region_id: region.id,
+ sales_channel_id: salesChannel.id,
+ currency_code: "usd",
+ },
+ storeHeaders
+ )
+ const cart = cartResponse.data.cart
+
+ const addItemResponse = await api.post(
+ `/store/carts/${cart.id}/line-items`,
+ {
+ variant_id: product.variants[0].id,
+ quantity: 1,
+ },
+ storeHeaders
+ )
+ const lineItemId = addItemResponse.data.cart.items[0].id
+
+ // Remove item
+ const deleteResponse = await api.delete(
+ `/store/carts/${cart.id}/line-items/${lineItemId}`,
+ storeHeaders
+ )
+
+ expect(deleteResponse.data.parent.items).toHaveLength(0)
+ })
+
+ it("should create cart with customer authentication", async () => {
+ // Create cart with customer headers (authenticated)
+ const response = await api.post(
+ `/store/carts`,
+ {
+ region_id: region.id,
+ sales_channel_id: salesChannel.id,
+ currency_code: "usd",
+ },
+ {
+ headers: {
+ ...storeHeaders.headers,
+ ...customerHeaders.headers,
+ },
+ }
+ )
+
+ expect(response.status).toEqual(200)
+ expect(response.data.cart).toBeDefined()
+ })
+ })
+ })
+ },
+})
diff --git a/packages/core/src/api/store/carts/[id]/complete/query-config.ts b/packages/core/src/api/store/carts/[id]/complete/query-config.ts
new file mode 100644
index 000000000..ff73d4776
--- /dev/null
+++ b/packages/core/src/api/store/carts/[id]/complete/query-config.ts
@@ -0,0 +1,14 @@
+export const defaultStoreRetrieveOrderGroupFields = [
+ "id",
+ "customer_id",
+ "cart_id",
+ "seller_count",
+ "total",
+ "created_at",
+ "updated_at",
+]
+
+export const storeCompleteCartQueryConfig = {
+ defaults: defaultStoreRetrieveOrderGroupFields,
+ isList: false,
+}
diff --git a/packages/core/src/api/store/carts/[id]/complete/route.ts b/packages/core/src/api/store/carts/[id]/complete/route.ts
new file mode 100644
index 000000000..1d51c901f
--- /dev/null
+++ b/packages/core/src/api/store/carts/[id]/complete/route.ts
@@ -0,0 +1,66 @@
+import { MedusaRequest, MedusaResponse } from "@medusajs/framework/http"
+import { ContainerRegistrationKeys, MedusaError } from "@medusajs/framework/utils"
+import { HttpTypes } from "@mercurjs/types"
+
+import { completeCartWithSplitOrdersWorkflow } from "../../../../../workflows/cart"
+import { defaultStoreCartFields, refetchCart } from "../../helpers"
+import { defaultStoreRetrieveOrderGroupFields } from "./query-config"
+import { StoreCompleteCartParamsType } from "./validators"
+
+export const POST = async (
+ req: MedusaRequest<{}, StoreCompleteCartParamsType>,
+ res: MedusaResponse<HttpTypes.StoreCompleteCartResponse>
+) => {
+ const cart_id = req.params.id
+
+ const { errors, result } = await completeCartWithSplitOrdersWorkflow(req.scope).run({
+ input: { cart_id },
+ throwOnError: false,
+ })
+
+ const query = req.scope.resolve(ContainerRegistrationKeys.QUERY)
+
+ // When an error occurs on the workflow, it's potentially to do with cart validations, payments
+ // or inventory checks. Return the cart here along with errors for the consumer to take more action
+ // and fix them
+ if (errors?.[0]) {
+ const error = errors[0].error
+ const statusOKErrors: string[] = [
+ MedusaError.Types.PAYMENT_AUTHORIZATION_ERROR,
+ MedusaError.Types.PAYMENT_REQUIRES_MORE_ERROR,
+ ]
+
+ const cart = await refetchCart(
+ cart_id,
+ req.scope,
+ defaultStoreCartFields
+ )
+
+ if (!statusOKErrors.includes(error?.type)) {
+ throw error
+ }
+
+ res.status(200).json({
+ type: "cart",
+ cart,
+ error: {
+ message: error.message,
+ name: error.name,
+ type: error.type,
+ },
+ })
+ return
+ }
+
+ // Fetch the order group with orders
+ const { data: orderGroups } = await query.graph({
+ entity: "order_group",
+ fields: req.queryConfig.fields,
+ filters: { id: result.order_group_id },
+ })
+
+ res.status(200).json({
+ type: "order_group",
+ order_group: orderGroups[0],
+ })
+}
diff --git a/packages/core/src/api/store/carts/[id]/complete/validators.ts b/packages/core/src/api/store/carts/[id]/complete/validators.ts
new file mode 100644
index 000000000..54fb1236f
--- /dev/null
+++ b/packages/core/src/api/store/carts/[id]/complete/validators.ts
@@ -0,0 +1,5 @@
+import { z } from "zod"
+import { createSelectParams } from "@medusajs/medusa/api/utils/validators"
+
+export type StoreCompleteCartParamsType = z.infer<typeof StoreCompleteCartParams>
+export const StoreCompleteCartParams = createSelectParams()
diff --git a/packages/core/src/api/store/carts/helpers.ts b/packages/core/src/api/store/carts/helpers.ts
new file mode 100644
index 000000000..4b727f59f
--- /dev/null
+++ b/packages/core/src/api/store/carts/helpers.ts
@@ -0,0 +1,149 @@
+import { MedusaRequest } from "@medusajs/framework/http"
+import { ContainerRegistrationKeys } from "@medusajs/framework/utils"
+
+export const defaultStoreCartFields = [
+ "id",
+ "currency_code",
+ "email",
+ "locale",
+ "region_id",
+ "created_at",
+ "updated_at",
+ "completed_at",
+ "total",
+ "subtotal",
+ "tax_total",
+ "discount_total",
+ "discount_subtotal",
+ "discount_tax_total",
+ "original_total",
+ "original_tax_total",
+ "item_total",
+ "item_subtotal",
+ "item_tax_total",
+ "item_discount_total",
+ "original_item_total",
+ "original_item_subtotal",
+ "original_item_tax_total",
+ "shipping_total",
+ "shipping_subtotal",
+ "shipping_tax_total",
+ "shipping_discount_total",
+ "original_shipping_tax_total",
+ "original_shipping_subtotal",
+ "original_shipping_total",
+ "credit_line_subtotal",
+ "credit_line_tax_total",
+ "credit_line_total",
+ "metadata",
+ "sales_channel_id",
+ "promotions.id",
+ "promotions.code",
+ "promotions.is_automatic",
+ "promotions.is_tax_inclusive",
+ "promotions.application_method.value",
+ "promotions.application_method.type",
+ "promotions.application_method.currency_code",
+ "items.id",
+ "items.thumbnail",
+ "items.product",
+ "items.product.id",
+ "items.variant",
+ "items.variant_id",
+ "items.product_id",
+ "items.product.categories.id",
+ "items.product.tags.id",
+ "items.product.collection_id",
+ "items.product.type_id",
+ "items.product_type_id",
+ "items.product_title",
+ "items.product_description",
+ "items.product_subtitle",
+ "items.product_type",
+ "items.product_collection",
+ "items.product_handle",
+ "items.variant_sku",
+ "items.variant_barcode",
+ "items.variant_title",
+ "items.requires_shipping",
+ "items.metadata",
+ "items.created_at",
+ "items.updated_at",
+ "items.title",
+ "items.quantity",
+ "items.unit_price",
+ "items.compare_at_unit_price",
+ "items.is_tax_inclusive",
+ "items.tax_lines.id",
+ "items.tax_lines.description",
+ "items.tax_lines.code",
+ "items.tax_lines.rate",
+ "items.tax_lines.provider_id",
+ "items.adjustments.id",
+ "items.adjustments.code",
+ "items.adjustments.promotion_id",
+ "items.adjustments.amount",
+ "items.adjustments.is_tax_inclusive",
+ "customer.id",
+ "customer.email",
+ "customer.groups.id",
+ "shipping_methods.tax_lines.id",
+ "shipping_methods.tax_lines.description",
+ "shipping_methods.tax_lines.code",
+ "shipping_methods.tax_lines.rate",
+ "shipping_methods.tax_lines.provider_id",
+ "shipping_methods.amount",
+ "shipping_methods.is_tax_inclusive",
+ "shipping_methods.adjustments.id",
+ "shipping_methods.adjustments.code",
+ "shipping_methods.adjustments.amount",
+ "shipping_methods.shipping_option_id",
+ "shipping_address_id",
+ "shipping_address.id",
+ "shipping_address.first_name",
+ "shipping_address.last_name",
+ "shipping_address.company",
+ "shipping_address.address_1",
+ "shipping_address.address_2",
+ "shipping_address.city",
+ "shipping_address.postal_code",
+ "shipping_address.country_code",
+ "shipping_address.region_code",
+ "shipping_address.province",
+ "shipping_address.phone",
+ "billing_address_id",
+ "billing_address.id",
+ "billing_address.first_name",
+ "billing_address.last_name",
+ "billing_address.company",
+ "billing_address.address_1",
+ "billing_address.address_2",
+ "billing_address.city",
+ "billing_address.postal_code",
+ "billing_address.country_code",
+ "billing_address.region_code",
+ "billing_address.province",
+ "billing_address.phone",
+ "region.id",
+ "region.name",
+ "region.currency_code",
+ "region.automatic_taxes",
+ "region.countries",
+ "payment_collection",
+ "payment_collection.payment_sessions",
+ "credit_lines",
+]
+
+export const refetchCart = async (
+ cartId: string,
+ scope: MedusaRequest["scope"],
+ fields: string[]
+) => {
+ const query = scope.resolve(ContainerRegistrationKeys.QUERY)
+ const { data } = await query.graph({
+ entity: "cart",
+ fields,
+ filters: { id: cartId },
+ })
+ return data[0]
+}
diff --git a/packages/core/src/api/store/carts/middlewares.ts b/packages/core/src/api/store/carts/middlewares.ts
new file mode 100644
index 000000000..4ffd34619
--- /dev/null
+++ b/packages/core/src/api/store/carts/middlewares.ts
@@ -0,0 +1,18 @@
+import { validateAndTransformQuery } from "@medusajs/framework/http"
+import { MiddlewareRoute } from "@medusajs/medusa"
+
+import { storeCompleteCartQueryConfig } from "./[id]/complete/query-config"
+import { StoreCompleteCartParams } from "./[id]/complete/validators"
+
+export const storeCartsMiddlewares: MiddlewareRoute[] = [
+ {
+ method: ["POST"],
+ matcher: "/store/carts/:id/complete",
+ middlewares: [
+ validateAndTransformQuery(
+ StoreCompleteCartParams,
+ storeCompleteCartQueryConfig
+ ),
+ ],
+ },
+]
diff --git a/packages/core/src/api/store/middlewares.ts b/packages/core/src/api/store/middlewares.ts
index 79573a212..978488759 100644
--- a/packages/core/src/api/store/middlewares.ts
+++ b/packages/core/src/api/store/middlewares.ts
@@ -1,7 +1,9 @@
import { MiddlewareRoute } from "@medusajs/medusa"
+import { storeCartsMiddlewares } from "./carts/middlewares"
import { storeOrderGroupsMiddlewares } from "./order-groups/middlewares"
export const storeMiddlewares: MiddlewareRoute[] = [
+ ...storeCartsMiddlewares,
...storeOrderGroupsMiddlewares,
]
diff --git a/packages/core/src/api/store/shipping-options/route.ts b/packages/core/src/api/store/shipping-options/route.ts
new file mode 100644
index 000000000..3bbc0c8fa
--- /dev/null
+++ b/packages/core/src/api/store/shipping-options/route.ts
@@ -0,0 +1,22 @@
+import { MedusaRequest, MedusaResponse } from "@medusajs/framework/http"
+import { HttpTypes } from "@medusajs/framework/types"
+import { HttpTypes as MercurHttpTypes } from "@mercurjs/types"
+
+import { listSellerShippingOptionsForCartWorkflow } from "../../../workflows"
+
+export const GET = async (
+ req: MedusaRequest<{}, HttpTypes.StoreGetShippingOptionList>,
+ res: MedusaResponse<MercurHttpTypes.StoreSellerShippingOptionsResponse>
+) => {
+ const { cart_id, is_return } = req.filterableFields
+
+ const { result: shipping_options } = await listSellerShippingOptionsForCartWorkflow(req.scope).run({
+ input: {
+ cart_id,
+ is_return: !!is_return,
+ fields: req.queryConfig.fields,
+ },
+ })
+
+ res.json({ shipping_options })
+}
diff --git a/packages/core/src/api/vendor/campaigns/helpers.ts b/packages/core/src/api/vendor/campaigns/helpers.ts
index 84d89a1ca..765deb20a 100644
--- a/packages/core/src/api/vendor/campaigns/helpers.ts
+++ b/packages/core/src/api/vendor/campaigns/helpers.ts
@@ -32,7 +32,7 @@ export const validateSellerCampaign = async (
const {
data: [sellerCampaign],
} = await query.graph({
- entity: "seller_campaign",
+ entity: "campaign_seller",
filters: {
seller_id: sellerId,
campaign_id: campaignId,
diff --git a/packages/core/src/api/vendor/campaigns/middlewares.ts b/packages/core/src/api/vendor/campaigns/middlewares.ts
index f9bcafb9f..8fcb01cba 100644
--- a/packages/core/src/api/vendor/campaigns/middlewares.ts
+++ b/packages/core/src/api/vendor/campaigns/middlewares.ts
@@ -27,7 +27,7 @@ const applySellerCampaignLinkFilter = (
req.filterableFields.seller_id = req.auth_context.actor_id
return maybeApplyLinkFilter({
- entryPoint: "seller_campaign",
+ entryPoint: "campaign_seller",
resourceId: "campaign_id",
filterableField: "seller_id",
})(req, res, next)
diff --git a/packages/core/src/api/vendor/fulfillment-sets/helpers.ts b/packages/core/src/api/vendor/fulfillment-sets/helpers.ts
index d805c443b..72df6d67d 100644
--- a/packages/core/src/api/vendor/fulfillment-sets/helpers.ts
+++ b/packages/core/src/api/vendor/fulfillment-sets/helpers.ts
@@ -31,7 +31,7 @@ export const validateSellerFulfillmentSet = async (
const {
data: [sellerStockLocation],
} = await query.graph({
- entity: "seller_stock_location",
+ entity: "stock_location_seller",
filters: {
stock_location_id: locationFulfillmentSet.stock_location_id,
seller_id: sellerId,
diff --git a/packages/core/src/api/vendor/inventory-items/helpers.ts b/packages/core/src/api/vendor/inventory-items/helpers.ts
index 108124982..9df58db86 100644
--- a/packages/core/src/api/vendor/inventory-items/helpers.ts
+++ b/packages/core/src/api/vendor/inventory-items/helpers.ts
@@ -32,7 +32,7 @@ export const validateSellerInventoryItem = async (
const {
data: [sellerInventoryItem],
} = await query.graph({
- entity: "seller_inventory_item",
+ entity: "inventory_item_seller",
filters: {
seller_id: sellerId,
inventory_item_id: inventoryItemId,
@@ -60,28 +60,10 @@ export const validateVariantBySku = async (
} = await query.graph({
entity: "product_variant",
filters: { sku },
- fields: ["id", "product_id"],
+ fields: ["id", "product.id", 'product.seller.id'],
})
- if (!variant) {
- throw new MedusaError(
- MedusaError.Types.NOT_FOUND,
- `Variant with sku: ${sku} was not found`
- )
- }
-
- const {
- data: [sellerProduct],
- } = await query.graph({
- entity: "seller_product",
- filters: {
- seller_id: sellerId,
- product_id: variant.product_id,
- },
- fields: ["seller_id"],
- })
-
- if (!sellerProduct) {
+ if (!variant || variant.product.seller.id !== sellerId) {
throw new MedusaError(
MedusaError.Types.NOT_FOUND,
`Variant with sku: ${sku} was not found`
diff --git a/packages/core/src/api/vendor/inventory-items/middlewares.ts b/packages/core/src/api/vendor/inventory-items/middlewares.ts
index 701676858..431f2e008 100644
--- a/packages/core/src/api/vendor/inventory-items/middlewares.ts
+++ b/packages/core/src/api/vendor/inventory-items/middlewares.ts
@@ -31,7 +31,7 @@ const applySellerInventoryItemLinkFilter = (
req.filterableFields.seller_id = req.auth_context.actor_id
return maybeApplyLinkFilter({
- entryPoint: "seller_inventory_item",
+ entryPoint: "inventory_item_seller",
resourceId: "inventory_item_id",
filterableField: "seller_id",
})(req, res, next)
diff --git a/packages/core/src/api/vendor/orders/helpers.ts b/packages/core/src/api/vendor/orders/helpers.ts
index b710e0b95..d37b98e74 100644
--- a/packages/core/src/api/vendor/orders/helpers.ts
+++ b/packages/core/src/api/vendor/orders/helpers.ts
@@ -14,7 +14,7 @@ export const validateSellerOrder = async (
const orderIds = Array.isArray(orderIdOrIds) ? orderIdOrIds : [orderIdOrIds]
const { data: sellerOrders } = await query.graph({
- entity: "seller_order",
+ entity: "order_seller",
filters: {
seller_id: sellerId,
order_id: orderIds,
diff --git a/packages/core/src/api/vendor/orders/middlewares.ts b/packages/core/src/api/vendor/orders/middlewares.ts
index e20e335bc..3d3655678 100644
--- a/packages/core/src/api/vendor/orders/middlewares.ts
+++ b/packages/core/src/api/vendor/orders/middlewares.ts
@@ -30,7 +30,7 @@ const applySellerLinkFilter = (
req.filterableFields.seller_id = req.auth_context.actor_id
return maybeApplyLinkFilter({
- entryPoint: "seller_order",
+ entryPoint: "order_seller",
resourceId: "order_id",
filterableField: "seller_id",
})(req, res, next)
diff --git a/packages/core/src/api/vendor/price-lists/helpers.ts b/packages/core/src/api/vendor/price-lists/helpers.ts
index 4d0e5824b..07f4e9163 100644
--- a/packages/core/src/api/vendor/price-lists/helpers.ts
+++ b/packages/core/src/api/vendor/price-lists/helpers.ts
@@ -16,7 +16,7 @@ export const validateSellerPriceList = async (
const {
data: [sellerPriceList],
} = await query.graph({
- entity: "seller_price_list",
+ entity: "price_list_seller",
filters: {
seller_id: sellerId,
price_list_id: priceListId,
diff --git a/packages/core/src/api/vendor/price-lists/middlewares.ts b/packages/core/src/api/vendor/price-lists/middlewares.ts
index d458bd9b5..333a2088a 100644
--- a/packages/core/src/api/vendor/price-lists/middlewares.ts
+++ b/packages/core/src/api/vendor/price-lists/middlewares.ts
@@ -27,7 +27,7 @@ const applySellerPriceListLinkFilter = (
req.filterableFields.seller_id = req.auth_context.actor_id
return maybeApplyLinkFilter({
- entryPoint: "seller_price_list",
+ entryPoint: "price_list_seller",
resourceId: "price_list_id",
filterableField: "seller_id",
})(req, res, next)
diff --git a/packages/core/src/api/vendor/product-categories/helpers.ts b/packages/core/src/api/vendor/product-categories/helpers.ts
index cd09d130f..1d31761a3 100644
--- a/packages/core/src/api/vendor/product-categories/helpers.ts
+++ b/packages/core/src/api/vendor/product-categories/helpers.ts
@@ -16,7 +16,7 @@ export const validateSellerProducts = async (
const query = scope.resolve(ContainerRegistrationKeys.QUERY)
const { data: sellerProducts } = await query.graph({
- entity: "seller_product",
+ entity: "product_seller",
filters: {
seller_id: sellerId,
},
diff --git a/packages/core/src/api/vendor/products/helpers.ts b/packages/core/src/api/vendor/products/helpers.ts
index 28ef805e0..e122b4f4b 100644
--- a/packages/core/src/api/vendor/products/helpers.ts
+++ b/packages/core/src/api/vendor/products/helpers.ts
@@ -14,7 +14,7 @@ export const validateSellerProduct = async (
const {
data: [sellerProduct],
} = await query.graph({
- entity: "seller_product",
+ entity: "product_seller",
filters: {
seller_id: sellerId,
product_id: productId,
diff --git a/packages/core/src/api/vendor/products/middlewares.ts b/packages/core/src/api/vendor/products/middlewares.ts
index 5aaea9e29..9e10039f0 100644
--- a/packages/core/src/api/vendor/products/middlewares.ts
+++ b/packages/core/src/api/vendor/products/middlewares.ts
@@ -34,7 +34,7 @@ const applySellerProductLinkFilter = (
req.filterableFields.seller_id = req.auth_context.actor_id
return maybeApplyLinkFilter({
- entryPoint: "seller_product",
+ entryPoint: "product_seller",
resourceId: "product_id",
filterableField: "seller_id",
})(req, res, next)
diff --git a/packages/core/src/api/vendor/promotions/helpers.ts b/packages/core/src/api/vendor/promotions/helpers.ts
index 1f2967d3f..6b2901644 100644
--- a/packages/core/src/api/vendor/promotions/helpers.ts
+++ b/packages/core/src/api/vendor/promotions/helpers.ts
@@ -47,7 +47,7 @@ export const validateSellerPromotions = async (
const query = scope.resolve(ContainerRegistrationKeys.QUERY)
const { data: sellerPromotions } = await query.graph({
- entity: "seller_promotion",
+ entity: "promotion_seller",
filters: {
seller_id: sellerId,
promotion_id: promotionIds,
diff --git a/packages/core/src/api/vendor/promotions/middlewares.ts b/packages/core/src/api/vendor/promotions/middlewares.ts
index 77156c535..23fbd2529 100644
--- a/packages/core/src/api/vendor/promotions/middlewares.ts
+++ b/packages/core/src/api/vendor/promotions/middlewares.ts
@@ -32,7 +32,7 @@ const applySellerPromotionLinkFilter = (
req.filterableFields.seller_id = req.auth_context.actor_id
return maybeApplyLinkFilter({
- entryPoint: "seller_promotion",
+ entryPoint: "promotion_seller",
resourceId: "promotion_id",
filterableField: "seller_id",
})(req, res, next)
diff --git a/packages/core/src/api/vendor/returns/middlewares.ts b/packages/core/src/api/vendor/returns/middlewares.ts
index 23584a1f3..e2b5e62dd 100644
--- a/packages/core/src/api/vendor/returns/middlewares.ts
+++ b/packages/core/src/api/vendor/returns/middlewares.ts
@@ -45,7 +45,7 @@ const applySellerOrderLinkFilter = async (
req.filterableFields.seller_id = req.auth_context.actor_id
return maybeApplyLinkFilter({
- entryPoint: "seller_order",
+ entryPoint: "order_seller",
resourceId: "order_id",
filterableField: "seller_id",
filterByField: "order_id",
diff --git a/packages/core/src/api/vendor/shipping-options/helpers.ts b/packages/core/src/api/vendor/shipping-options/helpers.ts
index 8db68cf64..da3b440be 100644
--- a/packages/core/src/api/vendor/shipping-options/helpers.ts
+++ b/packages/core/src/api/vendor/shipping-options/helpers.ts
@@ -19,7 +19,7 @@ export const validateSellerShippingOption = async (
const {
data: [sellerShippingOption],
} = await query.graph({
- entity: "seller_shipping_option",
+ entity: "shipping_option_seller",
filters: {
seller_id: sellerId,
shipping_option_id: shippingOptionId,
diff --git a/packages/core/src/api/vendor/shipping-options/middlewares.ts b/packages/core/src/api/vendor/shipping-options/middlewares.ts
index 2c1916707..64ff168ad 100644
--- a/packages/core/src/api/vendor/shipping-options/middlewares.ts
+++ b/packages/core/src/api/vendor/shipping-options/middlewares.ts
@@ -33,7 +33,7 @@ const applySellerShippingOptionLinkFilter = (
req.filterableFields.seller_id = req.auth_context.actor_id
return maybeApplyLinkFilter({
- entryPoint: "seller_shipping_option",
+ entryPoint: "shipping_option_seller",
resourceId: "shipping_option_id",
filterableField: "seller_id",
})(req, res, next)
diff --git a/packages/core/src/api/vendor/shipping-profiles/helpers.ts b/packages/core/src/api/vendor/shipping-profiles/helpers.ts
index 4e1262a0c..33a754a78 100644
--- a/packages/core/src/api/vendor/shipping-profiles/helpers.ts
+++ b/packages/core/src/api/vendor/shipping-profiles/helpers.ts
@@ -32,7 +32,7 @@ export const validateSellerShippingProfile = async (
const {
data: [sellerShippingProfile],
} = await query.graph({
- entity: "seller_shipping_profile",
+ entity: "shipping_profile_seller",
filters: {
seller_id: sellerId,
shipping_profile_id: shippingProfileId,
diff --git a/packages/core/src/api/vendor/shipping-profiles/middlewares.ts b/packages/core/src/api/vendor/shipping-profiles/middlewares.ts
index 3c98e9c90..88bc5e670 100644
--- a/packages/core/src/api/vendor/shipping-profiles/middlewares.ts
+++ b/packages/core/src/api/vendor/shipping-profiles/middlewares.ts
@@ -26,7 +26,7 @@ const applySellerShippingProfileLinkFilter = (
req.filterableFields.seller_id = req.auth_context.actor_id
return maybeApplyLinkFilter({
- entryPoint: "seller_shipping_profile",
+ entryPoint: "shipping_profile_seller",
resourceId: "shipping_profile_id",
filterableField: "seller_id",
})(req, res, next)
diff --git a/packages/core/src/api/vendor/stock-locations/helpers.ts b/packages/core/src/api/vendor/stock-locations/helpers.ts
index 76019ab00..db85b54e7 100644
--- a/packages/core/src/api/vendor/stock-locations/helpers.ts
+++ b/packages/core/src/api/vendor/stock-locations/helpers.ts
@@ -14,7 +14,7 @@ export const validateSellerStockLocation = async (
const {
data: [sellerStockLocation],
} = await query.graph({
- entity: "seller_stock_location",
+ entity: "stock_location_seller",
filters: {
seller_id: sellerId,
stock_location_id: stockLocationId,
diff --git a/packages/core/src/api/vendor/stock-locations/middlewares.ts b/packages/core/src/api/vendor/stock-locations/middlewares.ts
index d2bfe5188..705826ba6 100644
--- a/packages/core/src/api/vendor/stock-locations/middlewares.ts
+++ b/packages/core/src/api/vendor/stock-locations/middlewares.ts
@@ -28,7 +28,7 @@ const applySellerStockLocationLinkFilter = (
req.filterableFields.seller_id = req.auth_context.actor_id
return maybeApplyLinkFilter({
- entryPoint: "seller_stock_location",
+ entryPoint: "stock_location_seller",
resourceId: "stock_location_id",
filterableField: "seller_id",
})(req, res, next)
diff --git a/packages/core/src/links/seller-campaign-link.ts b/packages/core/src/links/campaign-seller-link.ts
similarity index 57%
rename from packages/core/src/links/seller-campaign-link.ts
rename to packages/core/src/links/campaign-seller-link.ts
index 2f44ec34b..09f027e79 100644
--- a/packages/core/src/links/seller-campaign-link.ts
+++ b/packages/core/src/links/campaign-seller-link.ts
@@ -2,4 +2,4 @@ import { defineLink } from "@medusajs/framework/utils"
import PromotionModule from "@medusajs/medusa/promotion"
import SellerModule from "../modules/seller"
-export default defineLink(SellerModule.linkable.seller, { linkable: PromotionModule.linkable.campaign, isList: true })
+export default defineLink({ linkable: PromotionModule.linkable.campaign, isList: true }, SellerModule.linkable.seller)
diff --git a/packages/core/src/links/seller-inventory-item-link.ts b/packages/core/src/links/inventory-item-seller-link.ts
similarity index 56%
rename from packages/core/src/links/seller-inventory-item-link.ts
rename to packages/core/src/links/inventory-item-seller-link.ts
index 13146a4f3..6bfa5588e 100644
--- a/packages/core/src/links/seller-inventory-item-link.ts
+++ b/packages/core/src/links/inventory-item-seller-link.ts
@@ -2,4 +2,4 @@ import { defineLink } from "@medusajs/framework/utils"
import InventoryModule from "@medusajs/medusa/inventory"
import SellerModule from "../modules/seller"
-export default defineLink(SellerModule.linkable.seller, { linkable: InventoryModule.linkable.inventoryItem, isList: true })
+export default defineLink({ linkable: InventoryModule.linkable.inventoryItem, isList: true }, SellerModule.linkable.seller)
diff --git a/packages/core/src/links/order-group-cart-link.ts b/packages/core/src/links/order-group-cart-link.ts
new file mode 100644
index 000000000..608e69fec
--- /dev/null
+++ b/packages/core/src/links/order-group-cart-link.ts
@@ -0,0 +1,14 @@
+import { defineLink } from "@medusajs/framework/utils"
+import CartModule from "@medusajs/medusa/cart"
+import SellerModule from "../modules/seller"
+
+export default defineLink(
+ {
+ linkable: SellerModule.linkable.orderGroup,
+ field: "cart_id",
+ },
+ CartModule.linkable.cart,
+ {
+ readOnly: true,
+ }
+)
diff --git a/packages/core/src/links/order-group-order-link.ts b/packages/core/src/links/order-group-order-link.ts
new file mode 100644
index 000000000..2af56befa
--- /dev/null
+++ b/packages/core/src/links/order-group-order-link.ts
@@ -0,0 +1,9 @@
+import { defineLink } from "@medusajs/framework/utils"
+import OrderModule from "@medusajs/medusa/order"
+import SellerModule from "../modules/seller"
+
+export default defineLink(SellerModule.linkable.orderGroup, { linkable: OrderModule.linkable.order, isList: true }, {
+ database: {
+ table: 'order_group_order',
+ }
+})
diff --git a/packages/core/src/links/seller-order-link.ts b/packages/core/src/links/order-seller-link.ts
similarity index 57%
rename from packages/core/src/links/seller-order-link.ts
rename to packages/core/src/links/order-seller-link.ts
index d13ff50d2..61a650c71 100644
--- a/packages/core/src/links/seller-order-link.ts
+++ b/packages/core/src/links/order-seller-link.ts
@@ -2,4 +2,4 @@ import { defineLink } from "@medusajs/framework/utils"
import OrderModule from "@medusajs/medusa/order"
import SellerModule from "../modules/seller"
-export default defineLink(SellerModule.linkable.seller, { linkable: OrderModule.linkable.order, isList: true })
+export default defineLink({ linkable: OrderModule.linkable.order, isList: true }, SellerModule.linkable.seller)
diff --git a/packages/core/src/links/seller-price-list-link.ts b/packages/core/src/links/price-list-seller-link.ts
similarity index 65%
rename from packages/core/src/links/seller-price-list-link.ts
rename to packages/core/src/links/price-list-seller-link.ts
index a95f68383..f0a1ec602 100644
--- a/packages/core/src/links/seller-price-list-link.ts
+++ b/packages/core/src/links/price-list-seller-link.ts
@@ -3,6 +3,6 @@ import PricingModule from "@medusajs/medusa/pricing"
import SellerModule from "../modules/seller"
export default defineLink(
- SellerModule.linkable.seller,
- { linkable: PricingModule.linkable.priceList, isList: true }
+ { linkable: PricingModule.linkable.priceList, isList: true },
+ SellerModule.linkable.seller
)
diff --git a/packages/core/src/links/seller-product-link.ts b/packages/core/src/links/product-seller-link.ts
similarity index 57%
rename from packages/core/src/links/seller-product-link.ts
rename to packages/core/src/links/product-seller-link.ts
index e57594f2d..b2e0d3b60 100644
--- a/packages/core/src/links/seller-product-link.ts
+++ b/packages/core/src/links/product-seller-link.ts
@@ -2,4 +2,4 @@ import { defineLink } from "@medusajs/framework/utils"
import ProductModule from "@medusajs/medusa/product"
import SellerModule from "../modules/seller"
-export default defineLink(SellerModule.linkable.seller, { linkable: ProductModule.linkable.product, isList: true })
+export default defineLink({ linkable: ProductModule.linkable.product, isList: true }, SellerModule.linkable.seller)
diff --git a/packages/core/src/links/seller-promotion-link.ts b/packages/core/src/links/promotion-seller-link.ts
similarity index 56%
rename from packages/core/src/links/seller-promotion-link.ts
rename to packages/core/src/links/promotion-seller-link.ts
index dc5b1d56a..c7ecbf2f5 100644
--- a/packages/core/src/links/seller-promotion-link.ts
+++ b/packages/core/src/links/promotion-seller-link.ts
@@ -2,4 +2,4 @@ import { defineLink } from "@medusajs/framework/utils"
import PromotionModule from "@medusajs/medusa/promotion"
import SellerModule from "../modules/seller"
-export default defineLink(SellerModule.linkable.seller, { linkable: PromotionModule.linkable.promotion, isList: true })
+export default defineLink({ linkable: PromotionModule.linkable.promotion, isList: true }, SellerModule.linkable.seller)
diff --git a/packages/core/src/links/seller-payment-link.ts b/packages/core/src/links/seller-payment-link.ts
deleted file mode 100644
index a29f27cde..000000000
--- a/packages/core/src/links/seller-payment-link.ts
+++ /dev/null
@@ -1,5 +0,0 @@
-import { defineLink } from "@medusajs/framework/utils"
-import PaymentModule from "@medusajs/medusa/payment"
-import SellerModule from "../modules/seller"
-
-export default defineLink(SellerModule.linkable.seller, { linkable: PaymentModule.linkable.payment, isList: true })
diff --git a/packages/core/src/links/seller-shipping-option-link.ts b/packages/core/src/links/shipping-option-seller-link.ts
similarity index 56%
rename from packages/core/src/links/seller-shipping-option-link.ts
rename to packages/core/src/links/shipping-option-seller-link.ts
index 9aa8c5b46..735e95687 100644
--- a/packages/core/src/links/seller-shipping-option-link.ts
+++ b/packages/core/src/links/shipping-option-seller-link.ts
@@ -2,4 +2,4 @@ import { defineLink } from "@medusajs/framework/utils"
import FulfillmentModule from "@medusajs/medusa/fulfillment"
import SellerModule from "../modules/seller"
-export default defineLink(SellerModule.linkable.seller, { linkable: FulfillmentModule.linkable.shippingOption, isList: true })
+export default defineLink({ linkable: FulfillmentModule.linkable.shippingOption, isList: true }, SellerModule.linkable.seller)
diff --git a/packages/core/src/links/seller-shipping-profile-link.ts b/packages/core/src/links/shipping-profile-seller-link.ts
similarity index 55%
rename from packages/core/src/links/seller-shipping-profile-link.ts
rename to packages/core/src/links/shipping-profile-seller-link.ts
index 6a314a943..a0aaf1cea 100644
--- a/packages/core/src/links/seller-shipping-profile-link.ts
+++ b/packages/core/src/links/shipping-profile-seller-link.ts
@@ -2,4 +2,4 @@ import { defineLink } from "@medusajs/framework/utils"
import FulfillmentModule from "@medusajs/medusa/fulfillment"
import SellerModule from "../modules/seller"
-export default defineLink(SellerModule.linkable.seller, { linkable: FulfillmentModule.linkable.shippingProfile, isList: true })
+export default defineLink({ linkable: FulfillmentModule.linkable.shippingProfile, isList: true }, SellerModule.linkable.seller)
diff --git a/packages/core/src/links/seller-stock-location-link.ts b/packages/core/src/links/stock-location-seller-link.ts
similarity index 56%
rename from packages/core/src/links/seller-stock-location-link.ts
rename to packages/core/src/links/stock-location-seller-link.ts
index 129e6da2e..c241ca420 100644
--- a/packages/core/src/links/seller-stock-location-link.ts
+++ b/packages/core/src/links/stock-location-seller-link.ts
@@ -2,4 +2,4 @@ import { defineLink } from "@medusajs/framework/utils"
import StockLocationModule from "@medusajs/medusa/stock-location"
import SellerModule from "../modules/seller"
-export default defineLink(SellerModule.linkable.seller, { linkable: StockLocationModule.linkable.stockLocation, isList: true })
+export default defineLink({ linkable: StockLocationModule.linkable.stockLocation, isList: true }, SellerModule.linkable.seller)
diff --git a/packages/core/src/modules/seller/migrations/.snapshot-medusa-seller.json b/packages/core/src/modules/seller/migrations/.snapshot-medusa-seller.json
index 66876b951..cb506d1e5 100644
--- a/packages/core/src/modules/seller/migrations/.snapshot-medusa-seller.json
+++ b/packages/core/src/modules/seller/migrations/.snapshot-medusa-seller.json
@@ -21,6 +21,15 @@
"unsigned": false,
"autoincrement": false,
"primary": false,
+ "nullable": true,
+ "mappedType": "text"
+ },
+ "cart_id": {
+ "name": "cart_id",
+ "type": "text",
+ "unsigned": false,
+ "autoincrement": false,
+ "primary": false,
"nullable": false,
"mappedType": "text"
},
diff --git a/packages/core/src/modules/seller/migrations/Migration20260126130937.ts b/packages/core/src/modules/seller/migrations/Migration20260126130937.ts
new file mode 100644
index 000000000..249c7fc85
--- /dev/null
+++ b/packages/core/src/modules/seller/migrations/Migration20260126130937.ts
@@ -0,0 +1,18 @@
+import { Migration } from "@medusajs/framework/mikro-orm/migrations";
+
+export class Migration20260126130937 extends Migration {
+
+ override async up(): Promise<void> {
+ this.addSql(`alter table if exists "order_group" add column if not exists "cart_id" text not null;`);
+ this.addSql(`alter table if exists "order_group" alter column "customer_id" type text using ("customer_id"::text);`);
+ this.addSql(`alter table if exists "order_group" alter column "customer_id" drop not null;`);
+ }
+
+ override async down(): Promise<void> {
+ this.addSql(`alter table if exists "order_group" drop column if exists "cart_id";`);
+
+ this.addSql(`alter table if exists "order_group" alter column "customer_id" type text using ("customer_id"::text);`);
+ this.addSql(`alter table if exists "order_group" alter column "customer_id" set not null;`);
+ }
+
+}
diff --git a/packages/core/src/modules/seller/models/order-group.ts b/packages/core/src/modules/seller/models/order-group.ts
index 69925860b..c932089b5 100644
--- a/packages/core/src/modules/seller/models/order-group.ts
+++ b/packages/core/src/modules/seller/models/order-group.ts
@@ -3,8 +3,9 @@ import { model } from "@medusajs/framework/utils"
const OrderGroup = model.define("order_group", {
id: model.id({ prefix: 'og' }).primaryKey(),
seller_count: model.number().computed(),
- customer_id: model.text(),
+ customer_id: model.text().nullable(),
total: model.bigNumber().computed(),
+ cart_id: model.text(),
})
export default OrderGroup
diff --git a/packages/core/src/modules/seller/models/seller.ts b/packages/core/src/modules/seller/models/seller.ts
index 4bac2fe1b..ac57093f2 100644
--- a/packages/core/src/modules/seller/models/seller.ts
+++ b/packages/core/src/modules/seller/models/seller.ts
@@ -1,5 +1,5 @@
import { model } from "@medusajs/framework/utils"
-import { SellerStatus } from "../types"
+import { SellerStatus } from "@mercurjs/types"
const Seller = model.define("seller", {
id: model.id({ prefix: "slr" }).primaryKey(),
diff --git a/packages/core/src/modules/seller/repositories/order-group.ts b/packages/core/src/modules/seller/repositories/order-group.ts
index a6c17eb87..d1884cdb9 100644
--- a/packages/core/src/modules/seller/repositories/order-group.ts
+++ b/packages/core/src/modules/seller/repositories/order-group.ts
@@ -1,6 +1,7 @@
import { SqlEntityManager } from "@medusajs/framework/mikro-orm/postgresql"
import { Context, FindOptions } from "@medusajs/framework/types"
-import { isObject, MikroOrmBase } from "@medusajs/framework/utils"
+import { DALUtils, isObject, MikroOrmBase } from "@medusajs/framework/utils"
+import { OrderGroup } from "../models"
const OPERATOR_MAP = {
$eq: "=",
@@ -15,7 +16,9 @@ const OPERATOR_MAP = {
$ilike: "ILIKE",
}
-export class OrderGroupRepository extends MikroOrmBase {
+export class OrderGroupRepository extends DALUtils.mikroOrmBaseRepositoryFactory(
+ OrderGroup
+) {
constructor() {
// @ts-ignore
// eslint-disable-next-line prefer-rest-params
@@ -159,7 +162,7 @@ export class OrderGroupRepository extends MikroOrmBase {
FROM order_group og
LEFT JOIN order_group_order ogo ON ogo.order_group_id = og.id
LEFT JOIN "order" o ON o.id = ogo.order_id
- LEFT JOIN seller_seller_order_order oso ON oso.order_id = o.id
+ LEFT JOIN order_order_seller_seller oso ON oso.order_id = o.id
WHERE ${whereClause}
`
@@ -167,12 +170,12 @@ export class OrderGroupRepository extends MikroOrmBase {
SELECT
og.*,
COUNT(DISTINCT oso.seller_id) as seller_count,
- COALESCE(SUM(os.total), 0) as total
+ COALESCE(SUM((os.totals->>'current_order_total')::numeric), 0) as total
FROM order_group og
LEFT JOIN order_group_order ogo ON ogo.order_group_id = og.id
LEFT JOIN "order" o ON o.id = ogo.order_id
LEFT JOIN order_summary os ON os.order_id = o.id AND os.version = o.version
- LEFT JOIN seller_seller_order_order oso ON oso.order_id = o.id
+ LEFT JOIN order_order_seller_seller oso ON oso.order_id = o.id
WHERE ${whereClause}
GROUP BY og.id
ORDER BY ${orderByClauses.join(", ")}
@@ -195,7 +198,11 @@ export class OrderGroupRepository extends MikroOrmBase {
knex.raw(countQuery, params),
])
- const rows = result.rows || []
+ const rows = result.rows.map(row => ({
+ ...row,
+ total: row.total ? Number(row.total) : 0,
+ seller_count: row.seller_count ? Number(row.seller_count) : 0,
+ })) ?? []
const count = parseInt(countResult.rows?.[0]?.count || "0", 10)
return [rows, count]
diff --git a/packages/core/src/modules/seller/service.ts b/packages/core/src/modules/seller/service.ts
index 8086c8fd1..7579821bc 100644
--- a/packages/core/src/modules/seller/service.ts
+++ b/packages/core/src/modules/seller/service.ts
@@ -6,6 +6,7 @@ import {
MedusaError,
MedusaService,
toHandle,
+ InjectTransactionManager
} from "@medusajs/framework/utils"
import { OrderGroup, Seller } from "./models"
import { OrderGroupRepository } from "./repositories"
@@ -27,6 +28,7 @@ class SellerModuleService extends MedusaService({
this.orderGroupRepository_ = orderGroupRepository
}
+ @InjectTransactionManager()
// @ts-ignore
async createSellers(data: any | any[], sharedContext?: Context) {
const sellersData = Array.isArray(data) ? data : [data]
@@ -50,6 +52,7 @@ class SellerModuleService extends MedusaService({
return super.createSellers(data, sharedContext)
}
+ @InjectTransactionManager()
// @ts-ignore
async updateSellers(data: any | any[], sharedContext?: Context) {
const sellersData = Array.isArray(data) ? data : [data]
diff --git a/packages/core/src/modules/seller/types/common.ts b/packages/core/src/modules/seller/types/common.ts
deleted file mode 100644
index aa1c9c668..000000000
--- a/packages/core/src/modules/seller/types/common.ts
+++ /dev/null
@@ -1,10 +0,0 @@
-import { InferTypeOf } from "@medusajs/framework/types"
-import { Seller } from "../models"
-
-export enum SellerStatus {
- PENDING = "pending",
- ACTIVE = "active",
- SUSPENDED = "suspended",
-}
-
-export type SellerDTO = InferTypeOf<typeof Seller>
diff --git a/packages/core/src/modules/seller/types/index.ts b/packages/core/src/modules/seller/types/index.ts
deleted file mode 100644
index a717a5435..000000000
--- a/packages/core/src/modules/seller/types/index.ts
+++ /dev/null
@@ -1,2 +0,0 @@
-export * from "./common"
-export * from "./mutation"
diff --git a/packages/core/src/modules/seller/types/mutation.ts b/packages/core/src/modules/seller/types/mutation.ts
deleted file mode 100644
index 915d4f6bf..000000000
--- a/packages/core/src/modules/seller/types/mutation.ts
+++ /dev/null
@@ -1,34 +0,0 @@
-import { SellerStatus } from "./common"
-
-export type CreateSellerDTO = {
- name: string
- handle: string
- email: string
- phone?: string | null
- logo?: string | null
- cover_image?: string | null
- address_1?: string | null
- address_2?: string | null
- city?: string | null
- country_code?: string | null
- province?: string | null
- postal_code?: string | null
- status?: SellerStatus
-}
-
-export type UpdateSellerDTO = {
- id: string
- name?: string
- handle?: string
- email?: string
- phone?: string | null
- logo?: string | null
- cover_image?: string | null
- address_1?: string | null
- address_2?: string | null
- city?: string | null
- country_code?: string | null
- province?: string | null
- postal_code?: string | null
- status?: SellerStatus
-}
diff --git a/packages/core/src/workflows/campaign/steps/link-seller-campaign.ts b/packages/core/src/workflows/campaign/steps/link-seller-campaign.ts
index 69bb0a5f8..898598a76 100644
--- a/packages/core/src/workflows/campaign/steps/link-seller-campaign.ts
+++ b/packages/core/src/workflows/campaign/steps/link-seller-campaign.ts
@@ -14,12 +14,12 @@ export const linkSellerCampaignStep = createStep(
const remoteLink = container.resolve(ContainerRegistrationKeys.REMOTE_LINK)
const links = input.campaign_ids.map((campaignId) => ({
- [SELLER_MODULE]: {
- seller_id: input.seller_id,
- },
[Modules.PROMOTION]: {
campaign_id: campaignId,
},
+ [SELLER_MODULE]: {
+ seller_id: input.seller_id,
+ },
}))
await remoteLink.create(links)
@@ -35,12 +35,12 @@ export const linkSellerCampaignStep = createStep(
const remoteLink = container.resolve(ContainerRegistrationKeys.REMOTE_LINK)
const links = data.campaign_ids.map((campaignId) => ({
- [SELLER_MODULE]: {
- seller_id: data.seller_id,
- },
[Modules.PROMOTION]: {
campaign_id: campaignId,
},
+ [SELLER_MODULE]: {
+ seller_id: data.seller_id,
+ },
}))
await remoteLink.dismiss(links)
diff --git a/packages/core/src/workflows/cart/complete-cart-with-split-orders-workflow.ts b/packages/core/src/workflows/cart/complete-cart-with-split-orders-workflow.ts
new file mode 100644
index 000000000..511c5d24a
--- /dev/null
+++ b/packages/core/src/workflows/cart/complete-cart-with-split-orders-workflow.ts
@@ -0,0 +1,524 @@
+import {
+ CartWorkflowDTO,
+ CreateOrderDTO,
+ LinkDefinition,
+ PromotionDTO,
+ ShippingOptionDTO,
+ UsageComputedActions,
+} from "@medusajs/framework/types"
+import {
+ generateEntityId,
+ isDefined,
+ MathBN,
+ Modules,
+ OrderStatus,
+ OrderWorkflowEvents,
+} from "@medusajs/framework/utils"
+import {
+ createHook,
+ createWorkflow,
+ parallelize,
+ transform,
+ when,
+ WorkflowResponse,
+} from "@medusajs/framework/workflows-sdk"
+import {
+ acquireLockStep,
+ addOrderTransactionStep,
+ authorizePaymentSessionStep,
+ createOrdersStep,
+ createRemoteLinkStep,
+ emitEventStep,
+ releaseLockStep,
+ reserveInventoryStep,
+ updateCartsStep,
+ useQueryGraphStep,
+ validateCartPaymentsStep,
+ validateShippingStep,
+} from "@medusajs/medusa/core-flows"
+import { CreateOrderGroupDTO, SellerDTO } from "@mercurjs/types"
+
+import { SELLER_MODULE } from "../../modules/seller"
+import { createOrderGroupStep } from "../order-group"
+import { OrderGroupWorkflowEvents } from "../events"
+import {
+ validateSellerCartItemsStep,
+ validateSellerCartShippingStep,
+} from "./steps"
+import {
+ completeCartFields,
+ prepareAdjustmentsData,
+ PrepareLineItemDataInput,
+ prepareLineItemData,
+ prepareTaxLinesData,
+ prepareConfirmInventoryInput,
+} from "./utils"
+import { registerUsageStep } from "../promotion"
+
+type CompleteCartWithSplitOrdersWorkflowInput = {
+ cart_id: string
+}
+
+export const THREE_DAYS = 3 * 24 * 60 * 60 * 1000
+export const THIRTY_SECONDS = 30 * 1000
+export const TWO_MINUTES = 2 * 60 * 1000
+
+export const completeCartWithSplitOrdersWorkflow = createWorkflow(
+ {
+ name: "complete-cart-with-split-orders",
+ store: true,
+ idempotent: false,
+ retentionTime: THREE_DAYS,
+ },
+ (input: CompleteCartWithSplitOrdersWorkflowInput) => {
+ acquireLockStep({
+ key: input.cart_id,
+ timeout: THIRTY_SECONDS,
+ ttl: TWO_MINUTES,
+ })
+
+ const [orderGroup, cartData] = parallelize(
+ useQueryGraphStep({
+ entity: "order_group",
+ fields: ["cart_id"],
+ filters: { cart_id: input.cart_id },
+ options: {
+ isList: false,
+ },
+ }),
+ useQueryGraphStep({
+ entity: "cart",
+ fields: completeCartFields,
+ filters: { id: input.cart_id },
+ options: {
+ isList: false,
+ },
+ }).config({
+ name: "cart-query",
+ })
+ )
+
+ const orderGroupId = transform({ orderGroup }, ({ orderGroup }) => {
+ return orderGroup?.data?.id
+ })
+
+
+ const paymentSessions = validateCartPaymentsStep({ cart: cartData.data })
+
+ const validate = createHook("validate", {
+ input,
+ cart: cartData.data,
+ })
+
+ // If order ID does not exist, we are completing the cart for the first time
+ const createdOrderGroup = when("create-order-group", { orderGroupId }, ({ orderGroupId }) => {
+ return !orderGroupId
+ }).then(() => {
+ const cartOptionIds = transform({ cart: cartData.data }, ({ cart }) => {
+ return cart.shipping_methods?.map((sm) => sm.shipping_option_id)
+ })
+ const shippingOptionsData = useQueryGraphStep({
+ entity: "shipping_option",
+ fields: ['id', "shipping_profile_id", 'seller.id'],
+ filters: { id: cartOptionIds },
+ options: {
+ cache: {
+ enable: true,
+ },
+ },
+ }).config({
+ name: "shipping-options-query",
+ })
+ validateSellerCartItemsStep({
+ cart: cartData.data,
+ })
+ validateSellerCartShippingStep({
+ cart: cartData.data,
+ shippingOptions: shippingOptionsData.data as ShippingOptionDTO & { seller: SellerDTO }[],
+ })
+ validateShippingStep({
+ cart: cartData.data,
+ shippingOptions: shippingOptionsData.data,
+ })
+ const { variants, sales_channel_id } = transform(
+ { cart: cartData.data },
+ (data) => {
+ const variantsMap: Record<string, any> = {}
+ const allItems = data.cart?.items?.map((item) => {
+ variantsMap[item.variant_id] = item.variant
+ return {
+ id: item.id,
+ variant_id: item.variant_id,
+ quantity: item.quantity,
+ }
+ })
+
+ return {
+ variants: Object.values(variantsMap),
+ items: allItems,
+ sales_channel_id: data.cart.sales_channel_id,
+ }
+ }
+ )
+
+ const { ordersToCreate, sellerOrdersMap } = transform({ cart: cartData.data, shippingOptionsData: shippingOptionsData.data }, ({ cart, shippingOptionsData }) => {
+ const cartSellerIds = new Set<string>(cart.items?.map((item) => item.variant.product.seller.id))
+ const sellerShippingOptionsMap = new Map()
+ shippingOptionsData.forEach((so) => {
+ const previous = sellerShippingOptionsMap.get(so.id) ?? []
+ sellerShippingOptionsMap.set(so.id, [...previous, so])
+ })
+
+ const sellerOrdersMap: Record<string, string> = {}
+ const ordersToCreate: (CreateOrderDTO & { id: string })[] = []
+
+ Array.from(cartSellerIds).map((sellerId) => {
+ const sellerCartItems = (cart.items ?? []).filter((item) => item.variant.product.seller.id === sellerId)
+ const sellerShippingOptions = sellerShippingOptionsMap.get(sellerId) ?? []
+ const sellerCartShippingMethods = (cart.shipping_methods ?? []).filter((sm) => sellerShippingOptions.some((so) => so.id === sm.shipping_option_id))
+
+ const allItems = sellerCartItems.map((item) => {
+ const input: PrepareLineItemDataInput = {
+ item,
+ variant: item.variant,
+ cartId: cart.id,
+ unitPrice: item.unit_price,
+ isTaxInclusive: item.is_tax_inclusive,
+ taxLines: item.tax_lines ?? [],
+ adjustments: item.adjustments ?? [],
+ }
+ return prepareLineItemData(input)
+ })
+
+ const shippingMethods = sellerCartShippingMethods.map((sm) => {
+ return {
+ name: sm.name,
+ description: sm.description,
+ amount: sm.raw_amount ?? sm.amount,
+ is_tax_inclusive: sm.is_tax_inclusive,
+ shipping_option_id: sm.shipping_option_id,
+ data: sm.data,
+ metadata: sm.metadata,
+ tax_lines: prepareTaxLinesData(sm.tax_lines ?? []),
+ adjustments: prepareAdjustmentsData(sm.adjustments ?? []),
+ }
+ })
+
+ // todo: add credit lines support for child orders
+ // const creditLines = (cart.credit_lines ?? []).map(
+ // (creditLine: CartCreditLineDTO) => {
+ // return {
+ // amount: creditLine.amount,
+ // raw_amount: creditLine.raw_amount,
+ // reference: creditLine.reference,
+ // reference_id: creditLine.reference_id,
+ // metadata: creditLine.metadata,
+ // }
+ // }
+ // )
+
+ const itemAdjustments = allItems
+ .map((item) => item.adjustments ?? [])
+ .flat(1)
+ const shippingAdjustments = shippingMethods
+ .map((sm) => sm.adjustments ?? [])
+ .flat(1)
+
+ const promoCodes = [...itemAdjustments, ...shippingAdjustments]
+ .map((adjustment) => adjustment.code)
+ .filter(Boolean)
+
+ const shippingAddress = cart.shipping_address
+ ? { ...cart.shipping_address }
+ : null
+ const billingAddress = cart.billing_address
+ ? { ...cart.billing_address }
+ : null
+
+ if (shippingAddress) {
+ delete shippingAddress.id
+ }
+
+ if (billingAddress) {
+ delete billingAddress.id
+ }
+
+ const orderId = generateEntityId('order')
+ ordersToCreate.push({
+ id: orderId,
+ region_id: cart.region?.id,
+ customer_id: cart.customer?.id,
+ sales_channel_id: cart.sales_channel_id,
+ status: OrderStatus.PENDING,
+ email: cart.email,
+ currency_code: cart.currency_code,
+ locale: cart.locale,
+ shipping_address: shippingAddress,
+ billing_address: billingAddress,
+ no_notification: false,
+ items: allItems,
+ shipping_methods: shippingMethods,
+ metadata: cart.metadata,
+ promo_codes: promoCodes,
+ // todo: add credit lines support for child orders
+ credit_lines: [],
+ })
+
+ sellerOrdersMap[sellerId] = orderId
+ })
+
+ return {
+ sellerOrdersMap,
+ ordersToCreate,
+ }
+ })
+
+ const orderGroupData = transform(
+ { cart: cartData.data },
+ ({ cart }) => {
+ return {
+ customer_id: cart.customer_id,
+ cart_id: cart.id,
+ } satisfies CreateOrderGroupDTO
+ }
+ )
+
+
+ const sellerCustomerQueryFilters = transform(
+ { cart: cartData.data, sellerOrdersMap },
+ ({ cart, sellerOrdersMap }) => {
+ if (!cart.customer_id) {
+ return { seller_id: [], customer_id: "" }
+ }
+ return {
+ seller_id: Object.keys(sellerOrdersMap),
+ customer_id: cart.customer_id,
+ }
+ }
+ )
+
+ const existingSellerCustomerLinks = useQueryGraphStep({
+ entity: "seller_customer",
+ fields: ["seller_id", "customer_id"],
+ filters: sellerCustomerQueryFilters,
+ }).config({
+ name: "existing-seller-customer-links-query",
+ })
+
+ const [createdOrderGroup, createdOrders] = parallelize(
+ createOrderGroupStep(orderGroupData),
+ createOrdersStep(ordersToCreate)
+ )
+
+ const reservationItemsData = transform(
+ { createdOrders },
+ ({ createdOrders }) =>
+ createdOrders.flatMap((order) => order.items!).map((i) => ({
+ variant_id: i.variant_id,
+ quantity: i.quantity,
+ id: i.id,
+ }))
+ )
+
+ const formatedInventoryItems = transform(
+ {
+ input: {
+ sales_channel_id,
+ variants,
+ items: reservationItemsData,
+ },
+ },
+ prepareConfirmInventoryInput
+ )
+
+ const updateCompletedAt = transform(
+ { cart: cartData.data },
+ ({ cart }) => {
+ return {
+ id: cart.id,
+ completed_at: new Date(),
+ }
+ }
+ )
+
+ const promotionUsage = transform(
+ { cart: cartData.data },
+ ({ cart }: { cart: CartWorkflowDTO }) => {
+ const promotionUsage: UsageComputedActions[] = []
+
+ const itemAdjustments = (cart.items ?? [])
+ .map((item) => item.adjustments ?? [])
+ .flat(1)
+
+ const shippingAdjustments = (cart.shipping_methods ?? [])
+ .map((item) => item.adjustments ?? [])
+ .flat(1)
+
+ for (const adjustment of itemAdjustments) {
+ promotionUsage.push({
+ amount: adjustment.amount,
+ code: adjustment.code!,
+ })
+ }
+
+ for (const adjustment of shippingAdjustments) {
+ promotionUsage.push({
+ amount: adjustment.amount,
+ code: adjustment.code!,
+ })
+ }
+
+ return {
+ computedActions: promotionUsage,
+ registrationContext: {
+ customer_id: cart.customer?.id || null,
+ customer_email: cart.email || null,
+ },
+ }
+ }
+ )
+
+ const linksToCreate = transform(
+ { cart: cartData.data, createdOrders, createdOrderGroup, sellerOrdersMap, existingSellerCustomerLinks },
+ ({ cart, createdOrders, createdOrderGroup, sellerOrdersMap, existingSellerCustomerLinks }) => {
+ const links: LinkDefinition[] = createdOrders.map((order) => ({
+ [Modules.ORDER]: { order_id: order.id },
+ [Modules.CART]: { cart_id: cart.id },
+ }))
+
+ if (cart.promotions?.length) {
+ cart.promotions.forEach((promotion: PromotionDTO & { seller: SellerDTO }) => {
+ links.push({
+ [Modules.ORDER]: { order_id: sellerOrdersMap[promotion.seller.id] },
+ [Modules.PROMOTION]: { promotion_id: promotion.id },
+ })
+ })
+ }
+
+ if (isDefined(cart.payment_collection?.id)) {
+ createdOrders.forEach((order) => {
+ links.push({
+ [Modules.ORDER]: { order_id: order.id },
+ [Modules.PAYMENT]: {
+ payment_collection_id: cart.payment_collection.id,
+ },
+ })
+ })
+ }
+
+ links.push(...Object.entries(sellerOrdersMap).map(([sellerId, orderId]) => ({
+ [Modules.ORDER]: { order_id: orderId },
+ [SELLER_MODULE]: { seller_id: sellerId },
+ })))
+
+ // Link order group to orders
+ links.push(...createdOrders.map((order) => ({
+ [SELLER_MODULE]: { order_group_id: createdOrderGroup.id },
+ [Modules.ORDER]: { order_id: order.id },
+ })))
+
+ if (cart.customer_id) {
+ // Create seller-customer links for new relationships
+ const existingSellerIds = new Set(
+ (existingSellerCustomerLinks?.data ?? []).map((link) => link.seller_id)
+ )
+
+ Object.keys(sellerOrdersMap).forEach((sellerId) => {
+ if (!existingSellerIds.has(sellerId)) {
+ links.push({
+ [SELLER_MODULE]: { seller_id: sellerId },
+ [Modules.CUSTOMER]: { customer_id: cart.customer_id },
+ })
+ }
+ })
+ }
+
+ return links
+ }
+ )
+
+
+ const orderEventData = transform({ createdOrders }, ({ createdOrders }) => {
+ return createdOrders.map((order) => ({ id: order.id }))
+ })
+
+ createRemoteLinkStep(linksToCreate)
+
+ parallelize(
+ updateCartsStep([updateCompletedAt]),
+ reserveInventoryStep(formatedInventoryItems),
+ registerUsageStep(promotionUsage),
+ emitEventStep({
+ eventName: OrderWorkflowEvents.PLACED,
+ data: orderEventData
+ }).config({
+ name: "order-placed-event",
+ }),
+ emitEventStep({
+ eventName: OrderGroupWorkflowEvents.CREATED,
+ data: { id: createdOrderGroup.id },
+ }).config({
+ name: "order-group-created-event",
+ })
+ )
+
+ createHook("beforePaymentAuthorization", {
+ input,
+ })
+
+ // Authorize payment session
+ const payment = authorizePaymentSessionStep({
+ id: paymentSessions![0].id,
+ })
+
+ const orderTransactions = transform(
+ { payment, createdOrders },
+ ({ payment, createdOrders }) => {
+ if (!payment?.captures?.length) {
+ return []
+ }
+
+ const transactions = createdOrders.flatMap((order) => {
+ const proportion = MathBN.div(order.total, payment.amount)
+
+ return (payment.captures ?? []).map((capture) => {
+ const captureAmount = capture.raw_amount ?? capture.amount
+ const proportionalAmount = MathBN.mult(captureAmount, proportion)
+
+ return {
+ order_id: order.id,
+ amount: proportionalAmount,
+ currency_code: payment.currency_code,
+ reference: "capture",
+ reference_id: capture.id,
+ }
+ })
+ })
+
+ return transactions
+ }
+ )
+
+ addOrderTransactionStep(orderTransactions)
+
+ createHook("orderGroupCreated", {
+ order_group_id: createdOrderGroup.id,
+ cart_id: cartData.data.id,
+ })
+
+ return createdOrderGroup
+ })
+
+ releaseLockStep({
+ key: input.cart_id,
+ })
+
+ const result = transform({ createdOrderGroup, orderGroupId }, ({ createdOrderGroup, orderGroupId }) => {
+ return { order_group_id: createdOrderGroup?.id ?? orderGroupId }
+ })
+
+ return new WorkflowResponse(result, {
+ hooks: [validate],
+ })
+ }
+)
diff --git a/packages/core/src/workflows/cart/index.ts b/packages/core/src/workflows/cart/index.ts
new file mode 100644
index 000000000..dd9ad0c66
--- /dev/null
+++ b/packages/core/src/workflows/cart/index.ts
@@ -0,0 +1,3 @@
+export * from "./steps"
+export * from "./complete-cart-with-split-orders-workflow"
+export * from "./list-seller-shipping-options-for-cart"
\ No newline at end of file
diff --git a/packages/core/src/workflows/cart/list-seller-shipping-options-for-cart.ts b/packages/core/src/workflows/cart/list-seller-shipping-options-for-cart.ts
new file mode 100644
index 000000000..d57f12dc2
--- /dev/null
+++ b/packages/core/src/workflows/cart/list-seller-shipping-options-for-cart.ts
@@ -0,0 +1,310 @@
+import {
+ createHook,
+ createWorkflow,
+ transform,
+ WorkflowResponse,
+} from "@medusajs/framework/workflows-sdk"
+import { AdditionalData, ShippingOptionDTO } from "@medusajs/framework/types"
+import {
+ getTranslatedShippingOptionsStep,
+ useQueryGraphStep,
+ useRemoteQueryStep,
+ validatePresenceOfStep,
+} from "@medusajs/medusa/core-flows"
+import { deduplicate, filterObjectByKeys, isDefined } from "@medusajs/framework/utils"
+import { cartFieldsForPricingContext, pricingContextResult, shippingOptionsContextResult } from "./utils"
+import { SellerDTO } from "@mercurjs/types"
+
+export type ListSellerShippingOptionsForCartWorkflowInput = {
+ cart_id: string
+ is_return?: boolean
+ enabled_in_store?: boolean
+ fields?: string[]
+} & AdditionalData
+
+
+export const listSellerShippingOptionsForCartWorkflow = createWorkflow(
+ "list-seller-shipping-options-for-cart",
+ (input: ListSellerShippingOptionsForCartWorkflowInput) => {
+ const cartQuery = useQueryGraphStep({
+ entity: "cart",
+ filters: { id: input.cart_id },
+ fields: [
+ ...cartFieldsForPricingContext,
+ "items.*",
+ "items.variant.id",
+ "items.variant.product.id",
+ "items.variant.product.seller.id",
+ "items.variant.manage_inventory",
+ "items.variant.inventory_items.inventory_item_id",
+ "items.variant.inventory_items.inventory.requires_shipping",
+ "items.variant.inventory_items.inventory.location_levels.*",
+ ],
+ options: { throwIfKeyNotFound: true },
+ }).config({ name: "get-cart" })
+
+ const cart = transform({ cartQuery }, ({ cartQuery }) => cartQuery.data[0])
+ const cartSellers = transform({ cart }, ({ cart }) => cart.items.map((item) => item.variant.product.seller.id))
+
+ validatePresenceOfStep({
+ entity: cart,
+ fields: ["sales_channel_id", "region_id", "currency_code"],
+ })
+
+ const sellerStockLocationsQuery = useQueryGraphStep({
+ entity: "stock_location_seller",
+ filters: { seller_id: cartSellers },
+ fields: [
+ "stock_location.id",
+ "stock_location.name",
+ "stock_location.address.*",
+ "stock_location.fulfillment_sets.id",
+ ],
+ options: {
+ cache: {
+ enable: true,
+ },
+ },
+ }).config({ name: "seller-stock-locations-query" })
+
+ const stockLocationIds = transform(
+ { sellerStockLocationsQuery },
+ ({ sellerStockLocationsQuery }) => {
+ return sellerStockLocationsQuery.data.map((sl) => sl.stock_location.id)
+ }
+ )
+
+ const salesChannelStockLocationsQuery = useQueryGraphStep({
+ entity: "sales_channel_location",
+ filters: {
+ sales_channel_id: cart.sales_channel_id,
+ stock_location_id: stockLocationIds,
+ },
+ fields: [
+ "stock_location_id",
+ ],
+ options: {
+ cache: {
+ enable: true,
+ },
+ },
+ }).config({ name: "sales-channel-stock-locations-query" })
+
+ const validStockLocations = transform(
+ { salesChannelStockLocationsQuery, sellerStockLocationsQuery },
+ ({ salesChannelStockLocationsQuery, sellerStockLocationsQuery }) => {
+ const validIds = new Set<string>(salesChannelStockLocationsQuery.data.map((sl) => sl.stock_location_id))
+
+ return sellerStockLocationsQuery.data.filter((sl) => validIds.has(sl.stock_location.id))
+ }
+ )
+
+ const { fulfillmentSetIds } = transform(
+ { validStockLocations },
+ ({ validStockLocations }) => {
+ const fulfillmentSetIds = new Set<string>()
+
+ validStockLocations.forEach((stockLocation) => {
+ stockLocation.stock_location.fulfillment_sets?.forEach((fulfillmentSet) => {
+ fulfillmentSetIds.add(fulfillmentSet.id)
+ })
+ })
+
+ return {
+ fulfillmentSetIds: Array.from(fulfillmentSetIds),
+ }
+ }
+ )
+
+ const setPricingContext = createHook(
+ "setPricingContext",
+ {
+ cart: cart,
+ fulfillmentSetIds,
+ additional_data: input.additional_data,
+ },
+ {
+ resultValidator: pricingContextResult,
+ }
+ )
+ const setPricingContextResult = setPricingContext.getResult()
+
+ const setShippingOptionsContext = createHook(
+ "setShippingOptionsContext",
+ {
+ cart: cart,
+ fulfillmentSetIds,
+ additional_data: input.additional_data,
+ },
+ {
+ resultValidator: shippingOptionsContextResult,
+ }
+ )
+ const setShippingOptionsContextResult = setShippingOptionsContext.getResult()
+
+ const queryVariables = transform(
+ {
+ input,
+ fulfillmentSetIds,
+ cart,
+ setPricingContextResult,
+ setShippingOptionsContextResult,
+ },
+ ({
+ input,
+ fulfillmentSetIds,
+ cart,
+ setPricingContextResult,
+ setShippingOptionsContextResult,
+ }) => {
+ return {
+ context: {
+ ...(setShippingOptionsContextResult
+ ? setShippingOptionsContextResult
+ : {}),
+ is_return: input.is_return ? "true" : "false",
+ enabled_in_store: !isDefined(input.enabled_in_store)
+ ? "true"
+ : input.enabled_in_store
+ ? "true"
+ : "false",
+ },
+
+ filters: {
+ fulfillment_set_id: fulfillmentSetIds,
+ address: {
+ country_code: cart.shipping_address?.country_code,
+ province_code: cart.shipping_address?.province,
+ city: cart.shipping_address?.city,
+ postal_expression: cart.shipping_address?.postal_code,
+ },
+ },
+
+ calculated_price: {
+ context: {
+ ...filterObjectByKeys(cart, cartFieldsForPricingContext),
+ ...(setPricingContextResult ? setPricingContextResult : {}),
+ currency_code: cart.currency_code,
+ region_id: cart.region_id,
+ region: cart.region,
+ customer_id: cart.customer_id,
+ customer: cart.customer,
+ },
+ },
+ }
+ }
+ )
+
+ const fields = transform(input, ({ fields = [] }) => {
+ return deduplicate([
+ ...fields,
+ "id",
+ "name",
+ "price_type",
+ "service_zone_id",
+ "shipping_profile_id",
+ "provider_id",
+ "data",
+ "service_zone.fulfillment_set_id",
+ "service_zone.fulfillment_set.type",
+ "service_zone.fulfillment_set.location.id",
+ "service_zone.fulfillment_set.location.address.*",
+
+ "type.id",
+ "type.label",
+ "type.description",
+ "type.code",
+
+ "provider.id",
+ "provider.is_enabled",
+
+ "rules.attribute",
+ "rules.value",
+ "rules.operator",
+
+ "calculated_price.*",
+ "prices.*",
+ "prices.price_rules.*",
+ 'seller.id',
+ ])
+ })
+
+ const shippingOptions = useRemoteQueryStep({
+ entry_point: "shipping_options",
+ fields,
+ variables: queryVariables,
+ }).config({ name: "shipping-options-query" })
+
+ const shippingOptionsWithPrice = transform(
+ { shippingOptions, cart },
+ ({ shippingOptions, cart }) =>
+ shippingOptions.map((shippingOption) => {
+ const price = shippingOption.calculated_price
+
+ const locationId =
+ shippingOption.service_zone.fulfillment_set.location.id
+
+ const itemsAtLocationWithoutAvailableQuantity = cart.items.filter(
+ (item) => {
+ if (!item.variant?.manage_inventory) {
+ return false
+ }
+
+ return item.variant.inventory_items.some((inventoryItem) => {
+ if (!inventoryItem.inventory.requires_shipping) {
+ return false
+ }
+
+ const level = inventoryItem.inventory.location_levels.find(
+ (locationLevel) => {
+ return locationLevel.location_id === locationId
+ }
+ )
+
+ return !level ? true : level.available_quantity < item.quantity
+ })
+ }
+ )
+
+ return {
+ ...shippingOption,
+ amount: price?.calculated_amount,
+ is_tax_inclusive: !!price?.is_calculated_price_tax_inclusive,
+ insufficient_inventory:
+ itemsAtLocationWithoutAvailableQuantity.length > 0,
+ }
+ })
+ )
+
+ const translatedShippingOptions = getTranslatedShippingOptionsStep({
+ shippingOptions: shippingOptionsWithPrice,
+ locale: cart.locale,
+ })
+
+ // Group shipping options by seller
+ const sellerShippingOptionsMap = transform(
+ { translatedShippingOptions },
+ ({ translatedShippingOptions }) => {
+ const result: Record<string, ShippingOptionDTO[]> = {}
+
+ translatedShippingOptions.forEach((option_) => {
+ const option = option_ as ShippingOptionDTO & { seller: SellerDTO }
+ const sellerId = option.seller?.id
+ if (!sellerId) return
+
+ if (!result[sellerId]) {
+ result[sellerId] = []
+ }
+
+ result[sellerId].push(option)
+ })
+
+ return result
+ }
+ )
+
+ return new WorkflowResponse(sellerShippingOptionsMap, {
+ hooks: [setPricingContext, setShippingOptionsContext] as const,
+ })
+ }
+)
diff --git a/packages/core/src/workflows/cart/steps/index.ts b/packages/core/src/workflows/cart/steps/index.ts
new file mode 100644
index 000000000..74b14437f
--- /dev/null
+++ b/packages/core/src/workflows/cart/steps/index.ts
@@ -0,0 +1,2 @@
+export * from "./validate-seller-cart-items"
+export * from "./validate-seller-cart-shipping"
diff --git a/packages/core/src/workflows/cart/steps/validate-seller-cart-items.ts b/packages/core/src/workflows/cart/steps/validate-seller-cart-items.ts
new file mode 100644
index 000000000..450e57d64
--- /dev/null
+++ b/packages/core/src/workflows/cart/steps/validate-seller-cart-items.ts
@@ -0,0 +1,45 @@
+import {
+ CartLineItemDTO,
+ CartWorkflowDTO,
+ ProductDTO,
+ ProductVariantDTO,
+} from "@medusajs/framework/types"
+import { ContainerRegistrationKeys, MedusaError } from "@medusajs/framework/utils"
+import { createStep, StepResponse } from "@medusajs/framework/workflows-sdk"
+import { SellerDTO } from "@mercurjs/types"
+
+type ValidateSellerCartItemsStepInput = {
+ cart: Omit<CartWorkflowDTO, "items"> & {
+ items: (CartLineItemDTO & {
+ variant: ProductVariantDTO & {
+ product: ProductDTO & {
+ seller: SellerDTO
+ }
+ }
+ })[]
+ }
+}
+
+export const validateSellerCartItemsStep = createStep(
+ "validate-seller-cart-items",
+ (input: ValidateSellerCartItemsStepInput, { container }) => {
+ const logger = container.resolve(ContainerRegistrationKeys.LOGGER)
+
+ const itemsWithMissingSellers = input.cart.items.filter((item) => {
+ return !item.variant.product.seller?.id
+ })
+
+ if (itemsWithMissingSellers.length > 0) {
+ logger.warn(
+ `The cart items required to be assigned to a seller but some of them are missing: ${itemsWithMissingSellers.map((item) => item.variant.product_id).join(", ")}`
+ )
+
+ throw new MedusaError(
+ MedusaError.Types.INVALID_DATA,
+ `The cart items required to be assigned to a seller but some of them are missing`
+ )
+ }
+
+ return new StepResponse(void 0)
+ }
+)
diff --git a/packages/core/src/workflows/cart/steps/validate-seller-cart-shipping.ts b/packages/core/src/workflows/cart/steps/validate-seller-cart-shipping.ts
new file mode 100644
index 000000000..c03470fd3
--- /dev/null
+++ b/packages/core/src/workflows/cart/steps/validate-seller-cart-shipping.ts
@@ -0,0 +1,49 @@
+import {
+ CartLineItemDTO,
+ CartWorkflowDTO,
+ ProductDTO,
+ ProductVariantDTO,
+ ShippingOptionDTO,
+} from "@medusajs/framework/types"
+import { MedusaError } from "@medusajs/framework/utils"
+import { createStep, StepResponse } from "@medusajs/framework/workflows-sdk"
+import { SellerDTO } from "@mercurjs/types"
+
+type ValidateSellerCartShippingStepInput = {
+ cart: Omit<CartWorkflowDTO, "items"> & {
+ items: (CartLineItemDTO & {
+ variant: ProductVariantDTO & {
+ product: ProductDTO & {
+ seller: SellerDTO
+ }
+ }
+ })[]
+ }
+ shippingOptions: ShippingOptionDTO & {
+ seller: SellerDTO
+ }[]
+}
+
+export const validateSellerCartShippingStep = createStep(
+ "validate-seller-shipping",
+ (input: ValidateSellerCartShippingStepInput) => {
+ const { cart, shippingOptions } = input
+ const sellersWithShippingOptions = new Set<string>(
+ shippingOptions.map((so) => so.seller.id)
+ )
+
+ const itemsWithMissingShippingOptions = cart.items.filter((item) => {
+ const sellerId = item.variant.product.seller.id
+ return item.requires_shipping && !sellersWithShippingOptions.has(sellerId)
+ })
+
+ if (itemsWithMissingShippingOptions.length > 0) {
+ throw new MedusaError(
+ MedusaError.Types.INVALID_DATA,
+ "No shipping method selected but the cart contains seller items that require shipping."
+ )
+ }
+
+ return new StepResponse(void 0)
+ }
+)
diff --git a/packages/core/src/workflows/cart/utils/fields.ts b/packages/core/src/workflows/cart/utils/fields.ts
new file mode 100644
index 000000000..ab3c18d77
--- /dev/null
+++ b/packages/core/src/workflows/cart/utils/fields.ts
@@ -0,0 +1,102 @@
+
+export const completeCartFields = [
+ "metadata",
+ "id",
+ "currency_code",
+ "email",
+ "locale",
+ "created_at",
+ "updated_at",
+ "completed_at",
+ "total",
+ "subtotal",
+ "tax_total",
+ "discount_total",
+ "discount_tax_total",
+ "original_total",
+ "original_tax_total",
+ "item_total",
+ "item_subtotal",
+ "item_tax_total",
+ "sales_channel_id",
+ "original_item_total",
+ "original_item_subtotal",
+ "original_item_tax_total",
+ "shipping_total",
+ "shipping_subtotal",
+ "shipping_tax_total",
+ "original_shipping_tax_total",
+ "original_shipping_subtotal",
+ "original_shipping_total",
+ "raw_total",
+ "raw_subtotal",
+ "raw_tax_total",
+ "raw_discount_total",
+ "raw_discount_tax_total",
+ "raw_original_total",
+ "raw_original_tax_total",
+ "raw_item_total",
+ "raw_item_subtotal",
+ "raw_item_tax_total",
+ "raw_sales_channel_id",
+ "raw_original_item_total",
+ "raw_original_item_subtotal",
+ "raw_original_item_tax_total",
+ "raw_shipping_total",
+ "raw_shipping_subtotal",
+ "raw_shipping_tax_total",
+ "raw_original_shipping_tax_total",
+ "raw_original_shipping_subtotal",
+ "raw_original_shipping_total",
+ "items.*",
+ "items.tax_lines.*",
+ "items.adjustments.*",
+ "customer.*",
+ "shipping_methods.*",
+ "shipping_methods.tax_lines.*",
+ "shipping_methods.adjustments.*",
+ "shipping_address.*",
+ "billing_address.*",
+ "region.*",
+ "credit_lines.*",
+ "payment_collection.*",
+ "payment_collection.payment_sessions.*",
+ "promotions.id",
+ 'promotions.seller.id',
+ "items.variant.id",
+ "items.variant.product.id",
+ "items.variant.product.seller.id",
+ "items.variant.product.is_giftcard",
+ "items.variant.product.shipping_profile.id",
+ "items.variant.manage_inventory",
+ "items.variant.allow_backorder",
+ "items.variant.inventory_items.inventory_item_id",
+ "items.variant.inventory_items.required_quantity",
+ "items.variant.inventory_items.inventory.requires_shipping",
+ "items.variant.inventory_items.inventory.location_levels.stocked_quantity",
+ "items.variant.inventory_items.inventory.location_levels.reserved_quantity",
+ "items.variant.inventory_items.inventory.location_levels.raw_stocked_quantity",
+ "items.variant.inventory_items.inventory.location_levels.raw_reserved_quantity",
+ "items.variant.inventory_items.inventory.location_levels.location_id",
+ "items.variant.inventory_items.inventory.location_levels.stock_locations.id",
+ "items.variant.inventory_items.inventory.location_levels.stock_locations.name",
+ "items.variant.inventory_items.inventory.location_levels.stock_locations.sales_channels.id",
+ "items.variant.inventory_items.inventory.location_levels.stock_locations.sales_channels.name",
+]
+
+export const cartFieldsForPricingContext = [
+ "id",
+ "sales_channel_id",
+ "currency_code",
+ "region_id",
+ "shipping_address.city",
+ "shipping_address.country_code",
+ "shipping_address.province",
+ "shipping_address.postal_code",
+ "item_total",
+ "total",
+ "locale",
+ "customer.id",
+ "email",
+ "customer.groups.id",
+]
diff --git a/packages/core/src/workflows/cart/utils/index.ts b/packages/core/src/workflows/cart/utils/index.ts
new file mode 100644
index 000000000..14f994131
--- /dev/null
+++ b/packages/core/src/workflows/cart/utils/index.ts
@@ -0,0 +1,4 @@
+export * from './fields'
+export * from './prepare-line-item-data'
+export * from './prepare-confirm-inventory-input'
+export * from './schemas'
\ No newline at end of file
diff --git a/packages/core/src/workflows/cart/utils/prepare-confirm-inventory-input.ts b/packages/core/src/workflows/cart/utils/prepare-confirm-inventory-input.ts
new file mode 100644
index 000000000..d632cb333
--- /dev/null
+++ b/packages/core/src/workflows/cart/utils/prepare-confirm-inventory-input.ts
@@ -0,0 +1,276 @@
+import {
+ BigNumberInput,
+ ConfirmVariantInventoryWorkflowInputDTO,
+} from "@medusajs/framework/types"
+import {
+ BigNumber,
+ MathBN,
+ MedusaError,
+ deepFlatMap,
+} from "@medusajs/framework/utils"
+
+export const requiredOrderFieldsForInventoryConfirmation = [
+ "id",
+ "version",
+ "canceled_at",
+ "sales_channel_id",
+ "items.*",
+ "items.variant.manage_inventory",
+ "items.variant.allow_backorder",
+ "items.variant.inventory_items.inventory_item_id",
+ "items.variant.inventory_items.required_quantity",
+ "items.variant.inventory_items.inventory.location_levels.stocked_quantity",
+ "items.variant.inventory_items.inventory.location_levels.reserved_quantity",
+ "items.variant.inventory_items.inventory.location_levels.raw_stocked_quantity",
+ "items.variant.inventory_items.inventory.location_levels.raw_reserved_quantity",
+ "items.variant.inventory_items.inventory.location_levels.location_id",
+ "items.variant.inventory_items.inventory.location_levels.stock_locations.id",
+ "items.variant.inventory_items.inventory.location_levels.stock_locations.name",
+ "items.variant.inventory_items.inventory.location_levels.stock_locations.sales_channels.id",
+ "items.variant.inventory_items.inventory.location_levels.stock_locations.sales_channels.name",
+]
+
+export const requiredVariantFieldsForInventoryConfirmation = [
+ "manage_inventory",
+ "allow_backorder",
+ "inventory_items.inventory_item_id",
+ "inventory_items.required_quantity",
+ "inventory_items.inventory.location_levels.stocked_quantity",
+ "inventory_items.inventory.location_levels.reserved_quantity",
+ "inventory_items.inventory.location_levels.raw_stocked_quantity",
+ "inventory_items.inventory.location_levels.raw_reserved_quantity",
+ "inventory_items.inventory.location_levels.location_id",
+ "inventory_items.inventory.location_levels.stock_locations.id",
+ "inventory_items.inventory.location_levels.stock_locations.name",
+ "inventory_items.inventory.location_levels.stock_locations.sales_channels.id",
+ "inventory_items.inventory.location_levels.stock_locations.sales_channels.name",
+]
+
+interface ConfirmInventoryPreparationInput {
+ product_variant_inventory_items: {
+ variant_id: string
+ inventory_item_id: string
+ required_quantity: number
+ }[]
+ items: {
+ id?: string
+ variant_id?: string | null
+ quantity: BigNumberInput
+ }[]
+ variants: {
+ id: string
+ manage_inventory?: boolean
+ allow_backorder?: boolean
+ }[]
+ location_ids: string[]
+ stockAvailability: Map<string, Map<string, BigNumberInput>>
+}
+
+interface ConfirmInventoryItem {
+ id?: string
+ inventory_item_id: string
+ required_quantity: number
+ allow_backorder: boolean
+ quantity: BigNumberInput
+ location_ids: string[]
+}
+
+/**
+ * This function prepares the input for the confirm inventory workflow.
+ * In essesnce, it maps a list of cart items to a list of inventory items,
+ * serving as a bridge between the cart and inventory domains.
+ *
+ * @throws {MedusaError} INVALID_DATA if any cart item is for a variant that has no inventory items.
+ * @throws {MedusaError} INVALID_DATA if any cart item is for a variant with no stock locations in the input.sales_channel_id. An exception is made for variants with allow_backorder set to true.
+ *
+ * @returns {ConfirmInventoryPreparationInput}
+ * A list of inventory items to confirm. Only inventory items for variants with managed inventory are included.
+ */
+export const prepareConfirmInventoryInput = (data: {
+ input: ConfirmVariantInventoryWorkflowInputDTO
+}) => {
+ const productVariantInventoryItems = new Map<string, any>()
+ const stockLocationIds = new Set<string>()
+ const allVariants = new Map<string, any>()
+ const mapLocationAvailability = new Map<string, Map<string, BigNumberInput>>()
+ const variantsWithLocationForChannel = new Set<string>()
+ let hasManagedInventory = false
+
+ const salesChannelId = data.input.sales_channel_id
+
+ for (const updateItem of data.input.itemsToUpdate ?? []) {
+ const updateItem_ = "data" in updateItem ? updateItem.data : updateItem
+
+ const item = data.input.items.find(
+ (item) => item.variant_id === updateItem_.variant_id
+ )
+ if (item && updateItem_.quantity) {
+ item.quantity = updateItem_.quantity!
+ }
+ }
+
+ deepFlatMap(
+ data.input,
+ "variants.inventory_items.inventory.location_levels.stock_locations.sales_channels",
+ ({
+ variants,
+ inventory_items,
+ location_levels,
+ stock_locations,
+ sales_channels,
+ }) => {
+ if (!variants) {
+ return
+ }
+
+ if (salesChannelId && sales_channels?.id === salesChannelId) {
+ variantsWithLocationForChannel.add(variants.id)
+ }
+
+ if (location_levels && inventory_items) {
+ const availability = MathBN.sub(
+ location_levels.raw_stocked_quantity ??
+ location_levels.stocked_quantity ??
+ 0,
+ location_levels.raw_reserved_quantity ??
+ location_levels.reserved_quantity ??
+ 0
+ )
+
+ if (!mapLocationAvailability.has(location_levels.location_id)) {
+ mapLocationAvailability.set(location_levels.location_id, new Map())
+ }
+
+ const locationMap = mapLocationAvailability.get(
+ location_levels.location_id
+ )!
+ locationMap.set(
+ inventory_items.inventory_item_id,
+ new BigNumber(availability)
+ )
+ }
+
+ if (stock_locations && sales_channels?.id === salesChannelId) {
+ stockLocationIds.add(stock_locations.id)
+ }
+
+ if (inventory_items) {
+ const inventoryItemId = inventory_items.inventory_item_id
+ const mapKey = `${inventoryItemId}-${inventory_items.variant_id}`
+
+ if (!productVariantInventoryItems.has(mapKey)) {
+ productVariantInventoryItems.set(mapKey, {
+ variant_id: inventory_items.variant_id,
+ inventory_item_id: inventoryItemId,
+ required_quantity: inventory_items.required_quantity,
+ })
+ }
+ }
+
+ if (!allVariants.has(variants.id)) {
+ if (!hasManagedInventory && variants.manage_inventory) {
+ hasManagedInventory = true
+ }
+
+ allVariants.set(variants.id, {
+ id: variants.id,
+ manage_inventory: variants.manage_inventory,
+ allow_backorder: variants.allow_backorder,
+ })
+ }
+ }
+ )
+
+ if (!hasManagedInventory) {
+ return { items: [] }
+ }
+
+ if (salesChannelId) {
+ for (const variant of allVariants.values()) {
+ if (
+ variant.manage_inventory &&
+ !variantsWithLocationForChannel.has(variant.id) &&
+ !variant.allow_backorder
+ ) {
+ throw new MedusaError(
+ MedusaError.Types.INVALID_DATA,
+ `Sales channel ${salesChannelId} is not associated with any stock location for variant ${variant.id}.`
+ )
+ }
+ }
+ }
+
+ const items = formatInventoryInput({
+ product_variant_inventory_items: Array.from(
+ productVariantInventoryItems.values()
+ ),
+ location_ids: Array.from(stockLocationIds),
+ stockAvailability: mapLocationAvailability,
+ items: data.input.items,
+ variants: Array.from(allVariants.values()),
+ })
+
+ return { items }
+}
+
+const formatInventoryInput = ({
+ product_variant_inventory_items,
+ location_ids,
+ items,
+ stockAvailability,
+ variants,
+}: ConfirmInventoryPreparationInput) => {
+ if (!product_variant_inventory_items.length) {
+ return []
+ }
+
+ const variantsMap = new Map<
+ string,
+ ConfirmInventoryPreparationInput["variants"][0]
+ >(variants.map((v) => [v.id, v]))
+
+ const itemsToConfirm: ConfirmInventoryItem[] = []
+
+ items.forEach((item) => {
+ const variant = variantsMap.get(item.variant_id!)
+
+ if (!variant?.manage_inventory) {
+ return
+ }
+
+ const variantInventoryItems = product_variant_inventory_items.filter(
+ (i) => i.variant_id === item.variant_id
+ )
+
+ if (!variantInventoryItems.length) {
+ throw new MedusaError(
+ MedusaError.Types.INVALID_DATA,
+ `Variant ${item.variant_id} does not have any inventory items associated with it.`
+ )
+ }
+
+ variantInventoryItems.forEach((variantInventoryItem) => {
+ const locationsWithAvailability = location_ids.filter((locId) =>
+ MathBN.gte(
+ stockAvailability
+ .get(locId)
+ ?.get(variantInventoryItem.inventory_item_id) ?? 0,
+ MathBN.mult(variantInventoryItem.required_quantity, item.quantity)
+ )
+ )
+
+ itemsToConfirm.push({
+ id: item.id,
+ inventory_item_id: variantInventoryItem.inventory_item_id,
+ required_quantity: variantInventoryItem.required_quantity,
+ allow_backorder: !!variant.allow_backorder,
+ quantity: item.quantity,
+ location_ids: locationsWithAvailability.length
+ ? locationsWithAvailability
+ : location_ids,
+ })
+ })
+ })
+
+ return itemsToConfirm
+}
\ No newline at end of file
diff --git a/packages/core/src/workflows/cart/utils/prepare-line-item-data.ts b/packages/core/src/workflows/cart/utils/prepare-line-item-data.ts
new file mode 100644
index 000000000..9bdb31293
--- /dev/null
+++ b/packages/core/src/workflows/cart/utils/prepare-line-item-data.ts
@@ -0,0 +1,214 @@
+import {
+ BigNumberInput,
+ CreateOrderAdjustmentDTO,
+ CreateOrderLineItemTaxLineDTO,
+ InventoryItemDTO,
+ LineItemAdjustmentDTO,
+ LineItemTaxLineDTO,
+ ProductDTO,
+ ProductVariantDTO,
+} from "@medusajs/framework/types"
+import {
+ isDefined,
+ isPresent,
+ MathBN,
+ MedusaError,
+ PriceListType,
+} from "@medusajs/framework/utils"
+
+interface PrepareItemLineItemInput {
+ title?: string
+ subtitle?: string
+ thumbnail?: string
+ quantity: BigNumberInput
+
+ product_id?: string
+ product_title?: string
+ product_description?: string
+ product_subtitle?: string
+ product_type?: string
+ product_type_id?: string
+ product_collection?: string
+ product_handle?: string
+
+ variant_id?: string
+ variant_sku?: string
+ variant_barcode?: string
+ variant_title?: string
+ variant_option_values?: Record<string, unknown>
+
+ requires_shipping?: boolean
+
+ is_discountable?: boolean
+ is_tax_inclusive?: boolean
+
+ raw_compare_at_unit_price?: BigNumberInput
+ compare_at_unit_price?: BigNumberInput
+ unit_price?: BigNumberInput
+
+ tax_lines?: LineItemTaxLineDTO[]
+ adjustments?: LineItemAdjustmentDTO[]
+ cart_id?: string
+ metadata?: Record<string, unknown> | null
+}
+
+type AddItemProductDTO = ProductDTO & {
+ shipping_profile: { id: string }
+}
+
+export interface PrepareVariantLineItemInput extends ProductVariantDTO {
+ thumbnail: string
+ inventory_items: { inventory: InventoryItemDTO }[]
+ calculated_price: {
+ calculated_price: {
+ price_list_type: string
+ }
+ is_calculated_price_tax_inclusive: boolean
+ original_amount: BigNumberInput
+ calculated_amount: BigNumberInput
+ }
+}
+
+export interface PrepareLineItemDataInput {
+ item?: PrepareItemLineItemInput
+ isCustomPrice?: boolean
+ variant?: PrepareVariantLineItemInput
+ taxLines?: CreateOrderLineItemTaxLineDTO[]
+ adjustments?: CreateOrderAdjustmentDTO[]
+ cartId?: string
+ unitPrice?: BigNumberInput
+ isTaxInclusive: boolean
+}
+
+export function prepareLineItemData(data: PrepareLineItemDataInput) {
+ const {
+ item,
+ variant,
+ cartId,
+ taxLines,
+ adjustments,
+ isCustomPrice,
+ unitPrice,
+ isTaxInclusive,
+ } = data
+
+ if (variant && !variant.product) {
+ throw new MedusaError(
+ MedusaError.Types.INVALID_DATA,
+ "Variant does not have a product"
+ )
+ }
+
+ if (item && MathBN.lte(item.quantity, 0)) {
+ throw new MedusaError(
+ MedusaError.Types.INVALID_DATA,
+ "Item quantity must be greater than 0"
+ )
+ }
+
+ let compareAtUnitPrice = item?.compare_at_unit_price
+
+ const isSalePrice =
+ variant?.calculated_price?.calculated_price?.price_list_type ===
+ PriceListType.SALE
+
+ if (
+ !isPresent(compareAtUnitPrice) &&
+ isSalePrice &&
+ !MathBN.eq(
+ variant.calculated_price?.original_amount,
+ variant.calculated_price?.calculated_amount
+ )
+ ) {
+ compareAtUnitPrice = variant.calculated_price.original_amount
+ }
+
+ const hasShippingProfile = isDefined(
+ (variant?.product as AddItemProductDTO)?.shipping_profile?.id
+ )
+
+ const someInventoryRequiresShipping = !!variant?.inventory_items?.some(
+ (inventoryItem) => !!inventoryItem.inventory.requires_shipping
+ )
+
+ // Note: If any of the items require shipping or product has a shipping profile set,
+ // we enable fulfillment unless explicitly set to not require shipping by the item in the request
+ const requiresShipping = isDefined(item?.requires_shipping)
+ ? item.requires_shipping
+ : hasShippingProfile || someInventoryRequiresShipping
+
+ let lineItem: any = {
+ quantity: item?.quantity,
+ title: item?.title ?? variant?.product?.title,
+ subtitle: item?.subtitle ?? variant?.title,
+ thumbnail:
+ item?.thumbnail ?? variant?.thumbnail ?? variant?.product?.thumbnail,
+
+ product_id: variant?.product?.id ?? item?.product_id,
+ product_title: item?.product_title ?? variant?.product?.title,
+ product_description:
+ item?.product_description ?? variant?.product?.description,
+ product_subtitle: item?.product_subtitle ?? variant?.product?.subtitle,
+ product_type: item?.product_type ?? variant?.product?.type?.value ?? null,
+ product_type_id:
+ item?.product_type_id ?? variant?.product?.type?.id ?? null,
+ product_collection:
+ item?.product_collection ?? variant?.product?.collection?.title ?? null,
+ product_handle: item?.product_handle ?? variant?.product?.handle,
+
+ variant_id: variant?.id,
+ variant_sku: item?.variant_sku ?? variant?.sku,
+ variant_barcode: item?.variant_barcode ?? variant?.barcode,
+ variant_title: item?.variant_title ?? variant?.title,
+ variant_option_values: item?.variant_option_values,
+
+ is_discountable: item?.is_discountable ?? variant?.product?.discountable,
+ is_giftcard: variant?.product?.is_giftcard ?? false,
+ requires_shipping: requiresShipping,
+
+ unit_price: unitPrice,
+ compare_at_unit_price: compareAtUnitPrice,
+ is_tax_inclusive: !!isTaxInclusive,
+
+ metadata: item?.metadata ?? {},
+ }
+
+ if (isCustomPrice) {
+ lineItem.is_custom_price = !!isCustomPrice
+ }
+
+ if (taxLines) {
+ lineItem.tax_lines = prepareTaxLinesData(taxLines)
+ }
+
+ if (adjustments) {
+ lineItem.adjustments = prepareAdjustmentsData(adjustments)
+ }
+
+ if (cartId) {
+ lineItem.cart_id = cartId
+ }
+
+ return lineItem
+}
+
+export function prepareTaxLinesData(data: CreateOrderLineItemTaxLineDTO[]) {
+ return data.map((d) => ({
+ description: d.description,
+ tax_rate_id: d.tax_rate_id,
+ code: d.code,
+ rate: d.rate,
+ provider_id: d.provider_id,
+ }))
+}
+
+export function prepareAdjustmentsData(data: CreateOrderAdjustmentDTO[]) {
+ return data.map((d) => ({
+ code: d.code,
+ amount: d.amount,
+ description: d.description,
+ promotion_id: d.promotion_id,
+ provider_id: d.provider_id,
+ is_tax_inclusive: d.is_tax_inclusive,
+ }))
+}
\ No newline at end of file
diff --git a/packages/core/src/workflows/cart/utils/schemas.ts b/packages/core/src/workflows/cart/utils/schemas.ts
new file mode 100644
index 000000000..ed200f141
--- /dev/null
+++ b/packages/core/src/workflows/cart/utils/schemas.ts
@@ -0,0 +1,3 @@
+import { z } from "@medusajs/framework/zod"
+export const pricingContextResult = z.record(z.string(), z.any()).optional()
+export const shippingOptionsContextResult = z.record(z.string(), z.any()).optional()
\ No newline at end of file
diff --git a/packages/core/src/workflows/events.ts b/packages/core/src/workflows/events.ts
new file mode 100644
index 000000000..8fd4cfdd6
--- /dev/null
+++ b/packages/core/src/workflows/events.ts
@@ -0,0 +1,17 @@
+/**
+ * @category Order
+ * @customNamespace Order
+ */
+export const OrderGroupWorkflowEvents = {
+ /**
+ * Emitted when an order group is created.
+ *
+ * @eventPayload
+ * ```ts
+ * {
+ * id, // The ID of the order group
+ * }
+ * ```
+ */
+ CREATED: "order_group.created",
+}
\ No newline at end of file
diff --git a/packages/core/src/workflows/hooks/product-created.ts b/packages/core/src/workflows/hooks/product-created.ts
index ec63051df..b7be99e07 100644
--- a/packages/core/src/workflows/hooks/product-created.ts
+++ b/packages/core/src/workflows/hooks/product-created.ts
@@ -24,12 +24,12 @@ createProductsWorkflow.hooks.productsCreated(
for (const product of products) {
links.push({
- [SELLER_MODULE]: {
- seller_id: additional_data.seller_id,
- },
[Modules.PRODUCT]: {
product_id: product.id,
},
+ [SELLER_MODULE]: {
+ seller_id: additional_data.seller_id,
+ },
})
for (const variant of product.variants || []) {
@@ -49,12 +49,12 @@ createProductsWorkflow.hooks.productsCreated(
for (const variant of variants) {
for (const inventoryItem of variant.inventory_items || []) {
inventoryLinks.push({
- [SELLER_MODULE]: {
- seller_id: additional_data.seller_id,
- },
[Modules.INVENTORY]: {
inventory_item_id: inventoryItem.inventory_item_id,
},
+ [SELLER_MODULE]: {
+ seller_id: additional_data.seller_id,
+ },
})
}
}
diff --git a/packages/core/src/workflows/index.ts b/packages/core/src/workflows/index.ts
index 4c6eaebbd..655a55a42 100644
--- a/packages/core/src/workflows/index.ts
+++ b/packages/core/src/workflows/index.ts
@@ -1,8 +1,11 @@
export * from "./campaign"
export * from "./inventory-item"
+export * from "./order-group"
export * from "./price-list"
export * from "./promotion"
export * from "./seller"
export * from "./shipping-option"
export * from "./shipping-profile"
export * from "./stock-location"
+export * from './cart'
+export * from './events'
\ No newline at end of file
diff --git a/packages/core/src/workflows/inventory-item/steps/link-seller-inventory-item.ts b/packages/core/src/workflows/inventory-item/steps/link-seller-inventory-item.ts
index c143a6d67..f47d7e983 100644
--- a/packages/core/src/workflows/inventory-item/steps/link-seller-inventory-item.ts
+++ b/packages/core/src/workflows/inventory-item/steps/link-seller-inventory-item.ts
@@ -14,12 +14,12 @@ export const linkSellerInventoryItemStep = createStep(
const remoteLink = container.resolve(ContainerRegistrationKeys.REMOTE_LINK)
const links = input.inventory_item_ids.map((inventoryItemId) => ({
- [SELLER_MODULE]: {
- seller_id: input.seller_id,
- },
[Modules.INVENTORY]: {
inventory_item_id: inventoryItemId,
},
+ [SELLER_MODULE]: {
+ seller_id: input.seller_id,
+ },
}))
await remoteLink.create(links)
@@ -35,12 +35,12 @@ export const linkSellerInventoryItemStep = createStep(
const remoteLink = container.resolve(ContainerRegistrationKeys.REMOTE_LINK)
const links = data.inventory_item_ids.map((inventoryItemId) => ({
- [SELLER_MODULE]: {
- seller_id: data.seller_id,
- },
[Modules.INVENTORY]: {
inventory_item_id: inventoryItemId,
},
+ [SELLER_MODULE]: {
+ seller_id: data.seller_id,
+ },
}))
await remoteLink.dismiss(links)
diff --git a/packages/core/src/workflows/order-group/index.ts b/packages/core/src/workflows/order-group/index.ts
new file mode 100644
index 000000000..c1f49c23f
--- /dev/null
+++ b/packages/core/src/workflows/order-group/index.ts
@@ -0,0 +1 @@
+export * from "./steps"
diff --git a/packages/core/src/workflows/order-group/steps/create-order-group.ts b/packages/core/src/workflows/order-group/steps/create-order-group.ts
new file mode 100644
index 000000000..eb909ef38
--- /dev/null
+++ b/packages/core/src/workflows/order-group/steps/create-order-group.ts
@@ -0,0 +1,27 @@
+import { StepResponse, createStep } from "@medusajs/framework/workflows-sdk"
+import { CreateOrderGroupDTO, OrderGroupDTO } from "@mercurjs/types"
+
+import { SELLER_MODULE } from "../../../modules/seller"
+import SellerModuleService from "../../../modules/seller/service"
+
+type CreateOrderGroupStepInput = CreateOrderGroupDTO
+
+export const createOrderGroupStep = createStep(
+ "create-order-group",
+ async (input: CreateOrderGroupStepInput, { container }) => {
+ const service = container.resolve<SellerModuleService>(SELLER_MODULE)
+
+ const orderGroup: OrderGroupDTO = await service.createOrderGroups(input)
+
+ return new StepResponse(orderGroup, orderGroup.id)
+ },
+ async (id: string, { container }) => {
+ if (!id) {
+ return
+ }
+
+ const service = container.resolve<SellerModuleService>(SELLER_MODULE)
+
+ await service.deleteOrderGroups([id])
+ }
+)
diff --git a/packages/core/src/workflows/order-group/steps/index.ts b/packages/core/src/workflows/order-group/steps/index.ts
new file mode 100644
index 000000000..59eec27ab
--- /dev/null
+++ b/packages/core/src/workflows/order-group/steps/index.ts
@@ -0,0 +1 @@
+export * from "./create-order-group"
diff --git a/packages/core/src/workflows/price-list/steps/link-seller-price-list.ts b/packages/core/src/workflows/price-list/steps/link-seller-price-list.ts
index 1703f5ff7..94a3cf8fe 100644
--- a/packages/core/src/workflows/price-list/steps/link-seller-price-list.ts
+++ b/packages/core/src/workflows/price-list/steps/link-seller-price-list.ts
@@ -13,12 +13,12 @@ export const linkSellerPriceListStep = createStep(
const remoteLink = container.resolve(ContainerRegistrationKeys.REMOTE_LINK)
const links = input.price_list_ids.map((priceListId) => ({
- [SELLER_MODULE]: {
- seller_id: input.seller_id,
- },
[Modules.PRICING]: {
price_list_id: priceListId,
},
+ [SELLER_MODULE]: {
+ seller_id: input.seller_id,
+ },
}))
await remoteLink.create(links)
@@ -34,12 +34,12 @@ export const linkSellerPriceListStep = createStep(
const remoteLink = container.resolve(ContainerRegistrationKeys.REMOTE_LINK)
const links = data.price_list_ids.map((priceListId) => ({
- [SELLER_MODULE]: {
- seller_id: data.seller_id,
- },
[Modules.PRICING]: {
price_list_id: priceListId,
},
+ [SELLER_MODULE]: {
+ seller_id: data.seller_id,
+ },
}))
await remoteLink.dismiss(links)
diff --git a/packages/core/src/workflows/promotion/steps/index.ts b/packages/core/src/workflows/promotion/steps/index.ts
index e0dd4f12e..411655356 100644
--- a/packages/core/src/workflows/promotion/steps/index.ts
+++ b/packages/core/src/workflows/promotion/steps/index.ts
@@ -1 +1,2 @@
export * from "./link-seller-promotion"
+export * from "./register-usage"
diff --git a/packages/core/src/workflows/promotion/steps/link-seller-promotion.ts b/packages/core/src/workflows/promotion/steps/link-seller-promotion.ts
index 9dc30eddc..d61527d4a 100644
--- a/packages/core/src/workflows/promotion/steps/link-seller-promotion.ts
+++ b/packages/core/src/workflows/promotion/steps/link-seller-promotion.ts
@@ -14,12 +14,12 @@ export const linkSellerPromotionStep = createStep(
const remoteLink = container.resolve(ContainerRegistrationKeys.REMOTE_LINK)
const links = input.promotion_ids.map((promotionId) => ({
- [SELLER_MODULE]: {
- seller_id: input.seller_id,
- },
[Modules.PROMOTION]: {
promotion_id: promotionId,
},
+ [SELLER_MODULE]: {
+ seller_id: input.seller_id,
+ },
}))
await remoteLink.create(links)
@@ -35,12 +35,12 @@ export const linkSellerPromotionStep = createStep(
const remoteLink = container.resolve(ContainerRegistrationKeys.REMOTE_LINK)
const links = data.promotion_ids.map((promotionId) => ({
- [SELLER_MODULE]: {
- seller_id: data.seller_id,
- },
[Modules.PROMOTION]: {
promotion_id: promotionId,
},
+ [SELLER_MODULE]: {
+ seller_id: data.seller_id,
+ },
}))
await remoteLink.dismiss(links)
diff --git a/packages/core/src/workflows/promotion/steps/register-usage.ts b/packages/core/src/workflows/promotion/steps/register-usage.ts
new file mode 100644
index 000000000..c3203aae4
--- /dev/null
+++ b/packages/core/src/workflows/promotion/steps/register-usage.ts
@@ -0,0 +1,54 @@
+import {
+ CampaignBudgetUsageContext,
+ IPromotionModuleService,
+ UsageComputedActions,
+} from "@medusajs/framework/types"
+import { Modules } from "@medusajs/framework/utils"
+import { StepResponse, createStep } from "@medusajs/framework/workflows-sdk"
+
+export const registerUsageStepId = "register-usage"
+
+type RegisterUsageStepInput = {
+ computedActions: UsageComputedActions[]
+ registrationContext: CampaignBudgetUsageContext
+}
+
+/**
+ * This step registers usage for a promotion.
+ */
+export const registerUsageStep = createStep(
+ registerUsageStepId,
+ async (data: RegisterUsageStepInput, { container }) => {
+ if (!data.computedActions.length) {
+ return new StepResponse(null, {
+ computedActions: [],
+ registrationContext: data.registrationContext,
+ })
+ }
+
+ const promotionModule = container.resolve<IPromotionModuleService>(
+ Modules.PROMOTION
+ )
+
+ await promotionModule.registerUsage(
+ data.computedActions,
+ data.registrationContext
+ )
+
+ return new StepResponse(null, data)
+ },
+ async (revertData, { container }) => {
+ if (!revertData?.computedActions.length) {
+ return
+ }
+
+ const promotionModule = container.resolve<IPromotionModuleService>(
+ Modules.PROMOTION
+ )
+
+ await promotionModule.revertUsage(
+ revertData.computedActions,
+ revertData.registrationContext
+ )
+ }
+)
diff --git a/packages/core/src/workflows/seller/steps/create-seller.ts b/packages/core/src/workflows/seller/steps/create-seller.ts
index e84e1727f..96ebf990f 100644
--- a/packages/core/src/workflows/seller/steps/create-seller.ts
+++ b/packages/core/src/workflows/seller/steps/create-seller.ts
@@ -1,6 +1,6 @@
import { StepResponse, createStep } from "@medusajs/framework/workflows-sdk"
+import { CreateSellerDTO, SellerDTO } from "@mercurjs/types"
-import { CreateSellerDTO, SellerDTO } from "../../../modules/seller/types"
import { SELLER_MODULE } from "../../../modules/seller"
import SellerModuleService from "../../../modules/seller/service"
diff --git a/packages/core/src/workflows/seller/steps/update-seller.ts b/packages/core/src/workflows/seller/steps/update-seller.ts
index 4edf068ad..c880885a2 100644
--- a/packages/core/src/workflows/seller/steps/update-seller.ts
+++ b/packages/core/src/workflows/seller/steps/update-seller.ts
@@ -1,6 +1,6 @@
import { StepResponse, createStep } from "@medusajs/framework/workflows-sdk"
+import { SellerDTO, UpdateSellerDTO } from "@mercurjs/types"
-import { SellerDTO, UpdateSellerDTO } from "../../../modules/seller/types"
import { SELLER_MODULE } from "../../../modules/seller"
import SellerModuleService from "../../../modules/seller/service"
diff --git a/packages/core/src/workflows/seller/workflows/create-seller.ts b/packages/core/src/workflows/seller/workflows/create-seller.ts
index 28fe96b78..faffdf865 100644
--- a/packages/core/src/workflows/seller/workflows/create-seller.ts
+++ b/packages/core/src/workflows/seller/workflows/create-seller.ts
@@ -3,8 +3,8 @@ import {
createWorkflow,
} from "@medusajs/framework/workflows-sdk"
import { setAuthAppMetadataStep } from "@medusajs/medusa/core-flows"
+import { CreateSellerDTO } from "@mercurjs/types"
-import { CreateSellerDTO } from "../../../modules/seller/types"
import { createSellerStep } from "../steps"
type CreateSellerWorkflowInput = {
diff --git a/packages/core/src/workflows/seller/workflows/update-seller.ts b/packages/core/src/workflows/seller/workflows/update-seller.ts
index 74216ecf0..927acd4e4 100644
--- a/packages/core/src/workflows/seller/workflows/update-seller.ts
+++ b/packages/core/src/workflows/seller/workflows/update-seller.ts
@@ -2,8 +2,8 @@ import {
WorkflowResponse,
createWorkflow,
} from "@medusajs/framework/workflows-sdk"
+import { UpdateSellerDTO } from "@mercurjs/types"
-import { UpdateSellerDTO } from "../../../modules/seller/types"
import { updateSellerStep } from "../steps"
export const updateSellerWorkflow = createWorkflow(
diff --git a/packages/core/src/workflows/shipping-option/steps/link-seller-shipping-option.ts b/packages/core/src/workflows/shipping-option/steps/link-seller-shipping-option.ts
index 6ea3ffe3a..6157acaa8 100644
--- a/packages/core/src/workflows/shipping-option/steps/link-seller-shipping-option.ts
+++ b/packages/core/src/workflows/shipping-option/steps/link-seller-shipping-option.ts
@@ -14,12 +14,12 @@ export const linkSellerShippingOptionStep = createStep(
const remoteLink = container.resolve(ContainerRegistrationKeys.REMOTE_LINK)
const links = input.shipping_option_ids.map((shippingOptionId) => ({
- [SELLER_MODULE]: {
- seller_id: input.seller_id,
- },
[Modules.FULFILLMENT]: {
shipping_option_id: shippingOptionId,
},
+ [SELLER_MODULE]: {
+ seller_id: input.seller_id,
+ },
}))
await remoteLink.create(links)
@@ -35,12 +35,12 @@ export const linkSellerShippingOptionStep = createStep(
const remoteLink = container.resolve(ContainerRegistrationKeys.REMOTE_LINK)
const links = data.shipping_option_ids.map((shippingOptionId) => ({
- [SELLER_MODULE]: {
- seller_id: data.seller_id,
- },
[Modules.FULFILLMENT]: {
shipping_option_id: shippingOptionId,
},
+ [SELLER_MODULE]: {
+ seller_id: data.seller_id,
+ },
}))
await remoteLink.dismiss(links)
diff --git a/packages/core/src/workflows/shipping-profile/steps/link-seller-shipping-profile.ts b/packages/core/src/workflows/shipping-profile/steps/link-seller-shipping-profile.ts
index 3d7e67bb0..37ad2d5fc 100644
--- a/packages/core/src/workflows/shipping-profile/steps/link-seller-shipping-profile.ts
+++ b/packages/core/src/workflows/shipping-profile/steps/link-seller-shipping-profile.ts
@@ -14,12 +14,12 @@ export const linkSellerShippingProfileStep = createStep(
const remoteLink = container.resolve(ContainerRegistrationKeys.REMOTE_LINK)
const links = input.shipping_profile_ids.map((shippingProfileId) => ({
- [SELLER_MODULE]: {
- seller_id: input.seller_id,
- },
[Modules.FULFILLMENT]: {
shipping_profile_id: shippingProfileId,
},
+ [SELLER_MODULE]: {
+ seller_id: input.seller_id,
+ },
}))
await remoteLink.create(links)
@@ -35,12 +35,12 @@ export const linkSellerShippingProfileStep = createStep(
const remoteLink = container.resolve(ContainerRegistrationKeys.REMOTE_LINK)
const links = data.shipping_profile_ids.map((shippingProfileId) => ({
- [SELLER_MODULE]: {
- seller_id: data.seller_id,
- },
[Modules.FULFILLMENT]: {
shipping_profile_id: shippingProfileId,
},
+ [SELLER_MODULE]: {
+ seller_id: data.seller_id,
+ },
}))
await remoteLink.dismiss(links)
diff --git a/packages/core/src/workflows/stock-location/steps/link-seller-stock-location.ts b/packages/core/src/workflows/stock-location/steps/link-seller-stock-location.ts
index c387bbb94..6e1016003 100644
--- a/packages/core/src/workflows/stock-location/steps/link-seller-stock-location.ts
+++ b/packages/core/src/workflows/stock-location/steps/link-seller-stock-location.ts
@@ -14,12 +14,12 @@ export const linkSellerStockLocationStep = createStep(
const remoteLink = container.resolve(ContainerRegistrationKeys.REMOTE_LINK)
const links = input.stock_location_ids.map((stockLocationId) => ({
- [SELLER_MODULE]: {
- seller_id: input.seller_id,
- },
[Modules.STOCK_LOCATION]: {
stock_location_id: stockLocationId,
},
+ [SELLER_MODULE]: {
+ seller_id: input.seller_id,
+ },
}))
await remoteLink.create(links)
@@ -35,12 +35,12 @@ export const linkSellerStockLocationStep = createStep(
const remoteLink = container.resolve(ContainerRegistrationKeys.REMOTE_LINK)
const links = data.stock_location_ids.map((stockLocationId) => ({
- [SELLER_MODULE]: {
- seller_id: data.seller_id,
- },
[Modules.STOCK_LOCATION]: {
stock_location_id: stockLocationId,
},
+ [SELLER_MODULE]: {
+ seller_id: data.seller_id,
+ },
}))
await remoteLink.dismiss(links)
diff --git a/packages/types/src/http/order-group.ts b/packages/types/src/http/order-group.ts
index f2e2b4217..26879ca94 100644
--- a/packages/types/src/http/order-group.ts
+++ b/packages/types/src/http/order-group.ts
@@ -46,3 +46,18 @@ export type StoreOrderGroupListResponse = PaginatedResponse<{
*/
order_groups: OrderGroupDTO[]
}>
+
+export type StoreCompleteCartResponse =
+ | {
+ type: "order_group"
+ order_group: OrderGroupDTO
+ }
+ | {
+ type: "cart"
+ cart: any
+ error: {
+ message: string
+ name: string
+ type: string
+ }
+ }
diff --git a/packages/types/src/http/shipping-option.ts b/packages/types/src/http/shipping-option.ts
index 6c17c496c..93f39ceb0 100644
--- a/packages/types/src/http/shipping-option.ts
+++ b/packages/types/src/http/shipping-option.ts
@@ -39,3 +39,10 @@ export interface VendorUpdateShippingOptionRulesResponse {
deleted: boolean
}
}
+
+export interface StoreSellerShippingOptionsResponse {
+ /**
+ * The shipping options grouped by seller ID.
+ */
+ shipping_options: Record<string, ShippingOptionDTO[]>
+}
diff --git a/packages/types/src/order-group/common.ts b/packages/types/src/order-group/common.ts
index 2a0504faf..ddaf861d9 100644
--- a/packages/types/src/order-group/common.ts
+++ b/packages/types/src/order-group/common.ts
@@ -1,6 +1,7 @@
export type OrderGroupDTO = {
id: string
- customer_id: string
+ customer_id: string | null
+ cart_id: string
seller_count: number
total: number
created_at: Date
diff --git a/packages/types/src/order-group/mutation.ts b/packages/types/src/order-group/mutation.ts
index bea0b6290..279f018f3 100644
--- a/packages/types/src/order-group/mutation.ts
+++ b/packages/types/src/order-group/mutation.ts
@@ -1,8 +1,10 @@
export type CreateOrderGroupDTO = {
- customer_id: string
+ customer_id?: string | null
+ cart_id: string
}
export type UpdateOrderGroupDTO = {
id: string
customer_id?: string
+ cart_id?: string
}