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: commissions (#667)

Viktor Holikc66ea7c13d68
diff --git a/integration-tests/http/cart/store/cart-commission.spec.ts b/integration-tests/http/cart/store/cart-commission.spec.ts
new file mode 100644
index 000000000..6add215d0
--- /dev/null
+++ b/integration-tests/http/cart/store/cart-commission.spec.ts
@@ -0,0 +1,1270 @@
+import { medusaIntegrationTestRunner } from "@medusajs/test-utils"
+import {
+ IRegionModuleService,
+ ISalesChannelModuleService,
+ MedusaContainer,
+} from "@medusajs/framework/types"
+import { ContainerRegistrationKeys, Modules } from "@medusajs/framework/utils"
+import {
+ CommissionRateType,
+ CommissionRateTarget,
+} from "@mercurjs/types"
+import { COMMISSION_MODULE } from "@mercurjs/core/modules/commission"
+import { createSellerUser } from "../../../helpers/create-seller-user"
+import { generatePublishableKey, generateStoreHeaders } from "../../../helpers/create-admin-user"
+
+jest.setTimeout(120000)
+
+medusaIntegrationTestRunner({
+ testSuite: ({ getContainer, api }) => {
+ describe("Store - Cart Commission Lines", () => {
+ let appContainer: MedusaContainer
+ let commissionService: any
+ let query: any
+ let seller: any
+ let sellerHeaders: any
+ let storeHeaders: any
+ let region: any
+ let salesChannel: any
+ let product: any
+ let shippingOption: any
+
+ beforeAll(async () => {
+ appContainer = getContainer()
+ commissionService = appContainer.resolve(COMMISSION_MODULE)
+ query = appContainer.resolve(ContainerRegistrationKeys.QUERY)
+ })
+
+ beforeEach(async () => {
+ // Create seller
+ const sellerResult = await createSellerUser(appContainer, {
+ email: "[email protected]",
+ name: "Commission Test Seller",
+ })
+ seller = sellerResult.seller
+ sellerHeaders = sellerResult.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: "Commission Test Store",
+ })
+
+ // Create region
+ const regionModule = appContainer.resolve<IRegionModuleService>(Modules.REGION)
+ region = await regionModule.createRegions({
+ name: "Commission 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: "Commission Test Product",
+ description: "A test product for commission",
+ options: [{ title: "Size", values: ["S", "M"] }],
+ variants: [
+ {
+ title: "Small",
+ sku: "COMM-TEST-S",
+ options: { Size: "S" },
+ prices: [{ currency_code: "usd", amount: 10000 }], // $100
+ manage_inventory: false,
+ },
+ {
+ title: "Medium",
+ sku: "COMM-TEST-M",
+ options: { Size: "M" },
+ prices: [{ currency_code: "usd", amount: 5000 }], // $50
+ manage_inventory: false,
+ },
+ ],
+ sales_channels: [{ id: salesChannel.id }],
+ },
+ sellerHeaders
+ )
+ product = productResponse.data.product
+
+ // Create shipping prerequisites and option
+ const shippingPrerequisites = await createShippingPrerequisites(sellerHeaders)
+ const shippingOptionResponse = await api.post(
+ `/vendor/shipping-options`,
+ {
+ name: "Commission Test 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: 2000 }], // $20
+ 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 = `_comm_${Date.now()}_${++prerequisiteCounter}`
+
+ const locationResponse = await api.post(
+ `/vendor/stock-locations`,
+ { name: `Commission Warehouse${uniqueSuffix}` },
+ headers
+ )
+ const stockLocation = locationResponse.data.stock_location
+
+ await api.post(
+ `/vendor/stock-locations/${stockLocation.id}/fulfillment-sets`,
+ {
+ name: `Commission 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]
+
+ const serviceZoneResponse = await api.post(
+ `/vendor/fulfillment-sets/${fulfillmentSet.id}/service-zones`,
+ {
+ name: `Commission Service Zone${uniqueSuffix}`,
+ geo_zones: [{ type: "country", country_code: "us" }],
+ },
+ headers
+ )
+ const serviceZone = serviceZoneResponse.data.fulfillment_set.service_zones.find(
+ (z: any) => z.name === `Commission Service Zone${uniqueSuffix}`
+ )
+
+ const shippingProfileResponse = await api.post(
+ `/vendor/shipping-profiles`,
+ {
+ name: `Commission Shipping Profile${uniqueSuffix}`,
+ type: "default",
+ },
+ headers
+ )
+ const shippingProfile = shippingProfileResponse.data.shipping_profile
+
+ await api.post(
+ `/vendor/stock-locations/${stockLocation.id}/fulfillment-providers`,
+ { add: ["manual_manual"] },
+ headers
+ )
+
+ await api.post(
+ `/vendor/stock-locations/${stockLocation.id}/sales-channels`,
+ { add: [salesChannel.id] },
+ headers
+ )
+
+ return {
+ stockLocation,
+ fulfillmentSet,
+ serviceZone,
+ shippingProfile,
+ }
+ }
+
+ const createCart = async () => {
+ const response = await api.post(
+ `/store/carts`,
+ {
+ region_id: region.id,
+ sales_channel_id: salesChannel.id,
+ currency_code: "usd",
+ },
+ storeHeaders
+ )
+ return response.data.cart
+ }
+
+ const addItemToCart = async (cartId: string, variantId: string, quantity: number) => {
+ const response = await api.post(
+ `/store/carts/${cartId}/line-items`,
+ { variant_id: variantId, quantity },
+ storeHeaders
+ )
+ return response.data.cart
+ }
+
+ const updateCartWithAddress = async (cartId: string) => {
+ const response = await api.post(
+ `/store/carts/${cartId}`,
+ {
+ 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
+ )
+ return response.data.cart
+ }
+
+ const addShippingMethodToCart = async (cartId: string, optionId: string) => {
+ const response = await api.post(
+ `/store/carts/${cartId}/shipping-methods`,
+ { option_id: optionId },
+ storeHeaders
+ )
+ return response.data.cart
+ }
+
+ describe("1. Basic Item Commission", () => {
+ it("1.1 should apply percentage-based item commission and calculate correct amount", async () => {
+ // Create 10% commission rate
+ await commissionService.createCommissionRates({
+ name: "Standard Item Commission",
+ code: "ITEM_10_PCT",
+ type: CommissionRateType.PERCENTAGE,
+ target: CommissionRateTarget.ITEM,
+ value: 10,
+ is_enabled: true,
+ priority: 0,
+ })
+
+ const cart = await createCart()
+ const updatedCart = await addItemToCart(cart.id, product.variants[0].id, 1)
+
+ // Get commission lines using the service
+ // Item subtotal is $100 (10000 cents), 10% = $10 (1000 cents)
+ const commissionLines = await commissionService.getCommissionLines({
+ currency_code: "usd",
+ items: updatedCart.items.map((item: any) => ({
+ id: item.id,
+ subtotal: 10000, // $100 in cents
+ product: { id: product.id },
+ })),
+ })
+
+ expect(commissionLines).toHaveLength(1)
+ expect(commissionLines[0].code).toEqual("ITEM_10_PCT")
+ expect(commissionLines[0].rate).toEqual(10)
+ expect(commissionLines[0].amount).toEqual(1000) // 10% of $100 = $10 (1000 cents)
+ })
+
+ it("1.2 should apply fixed-rate item commission and return fixed amount", async () => {
+ // Create $5 fixed commission rate
+ await commissionService.createCommissionRates({
+ name: "Fixed Item Commission",
+ code: "ITEM_5_FIXED",
+ type: CommissionRateType.FIXED,
+ target: CommissionRateTarget.ITEM,
+ value: 500, // $5 in cents
+ is_enabled: true,
+ priority: 0,
+ })
+
+ const cart = await createCart()
+ const updatedCart = await addItemToCart(cart.id, product.variants[0].id, 1)
+
+ const commissionLines = await commissionService.getCommissionLines({
+ currency_code: "usd",
+ items: updatedCart.items.map((item: any) => ({
+ id: item.id,
+ subtotal: 10000, // $100 in cents (doesn't affect fixed rate)
+ product: { id: product.id },
+ })),
+ })
+
+ expect(commissionLines).toHaveLength(1)
+ expect(commissionLines[0].code).toEqual("ITEM_5_FIXED")
+ expect(commissionLines[0].rate).toEqual(500)
+ expect(commissionLines[0].amount).toEqual(500) // Fixed $5 (500 cents)
+ })
+ })
+
+ describe("2. Shipping Commission", () => {
+ it("2.1 should apply percentage-based shipping commission and calculate correct amount", async () => {
+ // Create 15% shipping commission rate
+ await commissionService.createCommissionRates({
+ name: "Standard Shipping Commission",
+ code: "SHIP_15_PCT",
+ type: CommissionRateType.PERCENTAGE,
+ target: CommissionRateTarget.SHIPPING,
+ value: 15,
+ is_enabled: true,
+ priority: 0,
+ })
+
+ const cart = await createCart()
+ await addItemToCart(cart.id, product.variants[0].id, 1)
+ await updateCartWithAddress(cart.id)
+ const cartWithShipping = await addShippingMethodToCart(cart.id, shippingOption.id)
+
+ // Shipping is $20 (2000 cents), 15% = $3 (300 cents)
+ const commissionLines = await commissionService.getCommissionLines({
+ currency_code: "usd",
+ items: [],
+ shipping_methods: cartWithShipping.shipping_methods.map((sm: any) => ({
+ id: sm.id,
+ subtotal: 2000, // $20 in cents
+ shipping_option: { shipping_option_type_id: sm.shipping_option?.type?.id },
+ })),
+ })
+
+ expect(commissionLines).toHaveLength(1)
+ expect(commissionLines[0].code).toEqual("SHIP_15_PCT")
+ expect(commissionLines[0].rate).toEqual(15)
+ expect(commissionLines[0].amount).toEqual(300) // 15% of $20 = $3 (300 cents)
+ })
+
+ it("2.2 should apply fixed-rate shipping commission and return fixed amount", async () => {
+ // Create $2 fixed shipping commission
+ await commissionService.createCommissionRates({
+ name: "Fixed Shipping Commission",
+ code: "SHIP_2_FIXED",
+ type: CommissionRateType.FIXED,
+ target: CommissionRateTarget.SHIPPING,
+ value: 200, // $2 in cents
+ is_enabled: true,
+ priority: 0,
+ })
+
+ const cart = await createCart()
+ await addItemToCart(cart.id, product.variants[0].id, 1)
+ await updateCartWithAddress(cart.id)
+ const cartWithShipping = await addShippingMethodToCart(cart.id, shippingOption.id)
+
+ const commissionLines = await commissionService.getCommissionLines({
+ currency_code: "usd",
+ items: [],
+ shipping_methods: cartWithShipping.shipping_methods.map((sm: any) => ({
+ id: sm.id,
+ subtotal: 2000, // $20 in cents
+ shipping_option: { shipping_option_type_id: sm.shipping_option?.type?.id },
+ })),
+ })
+
+ expect(commissionLines).toHaveLength(1)
+ expect(commissionLines[0].code).toEqual("SHIP_2_FIXED")
+ expect(commissionLines[0].rate).toEqual(200)
+ expect(commissionLines[0].amount).toEqual(200) // Fixed $2 (200 cents)
+ })
+ })
+
+ describe("3. Rule-Based Overrides", () => {
+ it("3.1 should apply product-specific override", async () => {
+ // Create default rate 10%
+ await commissionService.createCommissionRates({
+ name: "Default Rate",
+ code: "DEFAULT_10",
+ type: CommissionRateType.PERCENTAGE,
+ target: CommissionRateTarget.ITEM,
+ value: 10,
+ is_enabled: true,
+ priority: 0,
+ })
+
+ // Create product-specific override 5%
+ await commissionService.createCommissionRates({
+ name: "Product Override",
+ code: "PROD_OVERRIDE_5",
+ type: CommissionRateType.PERCENTAGE,
+ target: CommissionRateTarget.ITEM,
+ value: 5,
+ is_enabled: true,
+ priority: 10,
+ rules: [{ reference: "product", reference_id: product.id }],
+ })
+
+ const cart = await createCart()
+ const updatedCart = await addItemToCart(cart.id, product.variants[0].id, 1)
+
+ const commissionLines = await commissionService.getCommissionLines({
+ currency_code: "usd",
+ items: updatedCart.items.map((item: any) => ({
+ id: item.id,
+ subtotal: item.subtotal,
+ product: { id: product.id },
+ })),
+ })
+
+ expect(commissionLines).toHaveLength(1)
+ expect(commissionLines[0].code).toEqual("PROD_OVERRIDE_5")
+ expect(commissionLines[0].rate).toEqual(5)
+ })
+
+ it("3.5 should apply seller-specific override", async () => {
+ // Create default rate 10%
+ await commissionService.createCommissionRates({
+ name: "Default Rate",
+ code: "DEFAULT_10_SELLER",
+ type: CommissionRateType.PERCENTAGE,
+ target: CommissionRateTarget.ITEM,
+ value: 10,
+ is_enabled: true,
+ priority: 0,
+ })
+
+ // Create seller-specific override 6%
+ await commissionService.createCommissionRates({
+ name: "VIP Seller Override",
+ code: "SELLER_VIP_6",
+ type: CommissionRateType.PERCENTAGE,
+ target: CommissionRateTarget.ITEM,
+ value: 6,
+ is_enabled: true,
+ priority: 10,
+ rules: [{ reference: "seller", reference_id: seller.id }],
+ })
+
+ const cart = await createCart()
+ const updatedCart = await addItemToCart(cart.id, product.variants[0].id, 1)
+
+ const commissionLines = await commissionService.getCommissionLines({
+ currency_code: "usd",
+ items: updatedCart.items.map((item: any) => ({
+ id: item.id,
+ subtotal: item.subtotal,
+ product: { id: product.id, seller: { id: seller.id } },
+ })),
+ })
+
+ expect(commissionLines).toHaveLength(1)
+ expect(commissionLines[0].code).toEqual("SELLER_VIP_6")
+ expect(commissionLines[0].rate).toEqual(6)
+ })
+ })
+
+ describe("4. Priority Ordering", () => {
+ it("4.1 should apply higher priority rate", async () => {
+ // Rate A: 10%, priority = 0 (default)
+ await commissionService.createCommissionRates({
+ name: "Default Rate",
+ code: "PRIORITY_DEFAULT",
+ type: CommissionRateType.PERCENTAGE,
+ target: CommissionRateTarget.ITEM,
+ value: 10,
+ is_enabled: true,
+ priority: 0,
+ })
+
+ // Rate B: 5%, priority = 10, rule: seller
+ await commissionService.createCommissionRates({
+ name: "High Priority Seller Rate",
+ code: "PRIORITY_HIGH_SELLER",
+ type: CommissionRateType.PERCENTAGE,
+ target: CommissionRateTarget.ITEM,
+ value: 5,
+ is_enabled: true,
+ priority: 10,
+ rules: [{ reference: "seller", reference_id: seller.id }],
+ })
+
+ // Rate C: 8%, priority = 5, rule: product
+ await commissionService.createCommissionRates({
+ name: "Medium Priority Product Rate",
+ code: "PRIORITY_MED_PRODUCT",
+ type: CommissionRateType.PERCENTAGE,
+ target: CommissionRateTarget.ITEM,
+ value: 8,
+ is_enabled: true,
+ priority: 5,
+ rules: [{ reference: "product", reference_id: product.id }],
+ })
+
+ const cart = await createCart()
+ const updatedCart = await addItemToCart(cart.id, product.variants[0].id, 1)
+
+ // Item matches both seller and product rules, highest priority (10) wins
+ const commissionLines = await commissionService.getCommissionLines({
+ currency_code: "usd",
+ items: updatedCart.items.map((item: any) => ({
+ id: item.id,
+ subtotal: item.subtotal,
+ product: { id: product.id, seller: { id: seller.id } },
+ })),
+ })
+
+ expect(commissionLines).toHaveLength(1)
+ expect(commissionLines[0].code).toEqual("PRIORITY_HIGH_SELLER")
+ expect(commissionLines[0].rate).toEqual(5)
+ })
+ })
+
+ describe("5. Minimum Commission", () => {
+ it("5.1 should apply minimum when calculated is below", async () => {
+ // 2% commission with $1 minimum
+ await commissionService.createCommissionRates({
+ name: "Low Rate With Minimum",
+ code: "MIN_COMM_1",
+ type: CommissionRateType.PERCENTAGE,
+ target: CommissionRateTarget.ITEM,
+ value: 2,
+ min_amount: 100, // $1 minimum (100 cents)
+ is_enabled: true,
+ priority: 0,
+ })
+
+ const cart = await createCart()
+ const updatedCart = await addItemToCart(cart.id, product.variants[1].id, 1)
+
+ // $10 subtotal -> 2% = $0.20 (20 cents), but min is $1 (100 cents)
+ const commissionLines = await commissionService.getCommissionLines({
+ currency_code: "usd",
+ items: updatedCart.items.map((item: any) => ({
+ id: item.id,
+ subtotal: 1000, // $10 in cents
+ product: { id: product.id },
+ })),
+ })
+
+ expect(commissionLines).toHaveLength(1)
+ expect(commissionLines[0].code).toEqual("MIN_COMM_1")
+ expect(commissionLines[0].rate).toEqual(2)
+ expect(commissionLines[0].amount).toEqual(100) // Min $1 applied (100 cents)
+ })
+
+ it("5.2 should not apply minimum when calculated is above", async () => {
+ // 10% commission with $1 minimum
+ await commissionService.createCommissionRates({
+ name: "Rate Above Minimum",
+ code: "ABOVE_MIN",
+ type: CommissionRateType.PERCENTAGE,
+ target: CommissionRateTarget.ITEM,
+ value: 10,
+ min_amount: 100, // $1 minimum (100 cents)
+ is_enabled: true,
+ priority: 0,
+ })
+
+ const cart = await createCart()
+ const updatedCart = await addItemToCart(cart.id, product.variants[0].id, 1)
+
+ // $100 subtotal -> 10% = $10 (1000 cents), above $1 minimum
+ const commissionLines = await commissionService.getCommissionLines({
+ currency_code: "usd",
+ items: updatedCart.items.map((item: any) => ({
+ id: item.id,
+ subtotal: 10000, // $100 in cents
+ product: { id: product.id },
+ })),
+ })
+
+ expect(commissionLines).toHaveLength(1)
+ expect(commissionLines[0].code).toEqual("ABOVE_MIN")
+ expect(commissionLines[0].rate).toEqual(10)
+ expect(commissionLines[0].amount).toEqual(1000) // 10% of $100 = $10 (1000 cents)
+ })
+
+ it("5.3 should apply minimum on fixed rate when below", async () => {
+ // $0.50 fixed commission with $1 minimum
+ await commissionService.createCommissionRates({
+ name: "Low Fixed With Minimum",
+ code: "FIXED_MIN",
+ type: CommissionRateType.FIXED,
+ target: CommissionRateTarget.ITEM,
+ value: 50, // $0.50 (50 cents)
+ min_amount: 100, // $1 minimum (100 cents)
+ is_enabled: true,
+ priority: 0,
+ })
+
+ const cart = await createCart()
+ const updatedCart = await addItemToCart(cart.id, product.variants[0].id, 1)
+
+ const commissionLines = await commissionService.getCommissionLines({
+ currency_code: "usd",
+ items: updatedCart.items.map((item: any) => ({
+ id: item.id,
+ subtotal: 10000, // $100 in cents
+ product: { id: product.id },
+ })),
+ })
+
+ expect(commissionLines).toHaveLength(1)
+ expect(commissionLines[0].code).toEqual("FIXED_MIN")
+ expect(commissionLines[0].rate).toEqual(50)
+ expect(commissionLines[0].amount).toEqual(100) // Min $1 applied (100 cents)
+ })
+ })
+
+ describe("6. Include Tax", () => {
+ it("6.1 should include tax in calculation when enabled", async () => {
+ // 10% commission with include_tax = true
+ await commissionService.createCommissionRates({
+ name: "Rate With Tax",
+ code: "INCLUDE_TAX",
+ type: CommissionRateType.PERCENTAGE,
+ target: CommissionRateTarget.ITEM,
+ value: 10,
+ include_tax: true,
+ is_enabled: true,
+ priority: 0,
+ })
+
+ const cart = await createCart()
+ const updatedCart = await addItemToCart(cart.id, product.variants[0].id, 1)
+
+ // Commission calculated on $100 + $10 tax = $110 -> 10% = $11 (1100 cents)
+ const commissionLines = await commissionService.getCommissionLines({
+ currency_code: "usd",
+ items: updatedCart.items.map((item: any) => ({
+ id: item.id,
+ subtotal: 10000, // $100 in cents
+ tax_total: 1000, // $10 tax in cents
+ product: { id: product.id },
+ })),
+ })
+
+ expect(commissionLines).toHaveLength(1)
+ expect(commissionLines[0].code).toEqual("INCLUDE_TAX")
+ expect(commissionLines[0].rate).toEqual(10)
+ expect(commissionLines[0].amount).toEqual(1100) // 10% of ($100 + $10 tax) = $11 (1100 cents)
+ })
+
+ it("6.2 should not include tax when disabled", async () => {
+ // 10% commission with include_tax = false
+ await commissionService.createCommissionRates({
+ name: "Rate Without Tax",
+ code: "EXCLUDE_TAX",
+ type: CommissionRateType.PERCENTAGE,
+ target: CommissionRateTarget.ITEM,
+ value: 10,
+ include_tax: false,
+ is_enabled: true,
+ priority: 0,
+ })
+
+ const cart = await createCart()
+ const updatedCart = await addItemToCart(cart.id, product.variants[0].id, 1)
+
+ // Commission calculated on $100 only -> 10% = $10 (1000 cents)
+ const commissionLines = await commissionService.getCommissionLines({
+ currency_code: "usd",
+ items: updatedCart.items.map((item: any) => ({
+ id: item.id,
+ subtotal: 10000, // $100 in cents
+ tax_total: 1000, // $10 tax in cents (ignored)
+ product: { id: product.id },
+ })),
+ })
+
+ expect(commissionLines).toHaveLength(1)
+ expect(commissionLines[0].code).toEqual("EXCLUDE_TAX")
+ expect(commissionLines[0].rate).toEqual(10)
+ expect(commissionLines[0].amount).toEqual(1000) // 10% of $100 = $10 (1000 cents), tax ignored
+ })
+
+ it("6.3 should include tax on shipping commission", async () => {
+ // 10% shipping commission with include_tax = true
+ await commissionService.createCommissionRates({
+ name: "Shipping With Tax",
+ code: "SHIP_INCLUDE_TAX",
+ type: CommissionRateType.PERCENTAGE,
+ target: CommissionRateTarget.SHIPPING,
+ value: 10,
+ include_tax: true,
+ is_enabled: true,
+ priority: 0,
+ })
+
+ const cart = await createCart()
+ await addItemToCart(cart.id, product.variants[0].id, 1)
+ await updateCartWithAddress(cart.id)
+ const cartWithShipping = await addShippingMethodToCart(cart.id, shippingOption.id)
+
+ // Commission calculated on $20 + $2 tax = $22 -> 10% = $2.20 (220 cents)
+ const commissionLines = await commissionService.getCommissionLines({
+ currency_code: "usd",
+ items: [],
+ shipping_methods: cartWithShipping.shipping_methods.map((sm: any) => ({
+ id: sm.id,
+ subtotal: 2000, // $20 in cents
+ tax_total: 200, // $2 tax in cents
+ shipping_option: { shipping_option_type_id: sm.shipping_option?.type?.id },
+ })),
+ })
+
+ expect(commissionLines).toHaveLength(1)
+ expect(commissionLines[0].code).toEqual("SHIP_INCLUDE_TAX")
+ expect(commissionLines[0].rate).toEqual(10)
+ expect(commissionLines[0].amount).toEqual(220) // 10% of ($20 + $2 tax) = $2.20 (220 cents)
+ })
+ })
+
+ describe("7. Currency Code Matching", () => {
+ it("7.1 should apply currency-specific rate when matches", async () => {
+ // USD rate 10%
+ await commissionService.createCommissionRates({
+ name: "USD Rate",
+ code: "USD_RATE",
+ type: CommissionRateType.PERCENTAGE,
+ target: CommissionRateTarget.ITEM,
+ value: 10,
+ currency_code: "usd",
+ is_enabled: true,
+ priority: 10,
+ })
+
+ // EUR rate 12%
+ await commissionService.createCommissionRates({
+ name: "EUR Rate",
+ code: "EUR_RATE",
+ type: CommissionRateType.PERCENTAGE,
+ target: CommissionRateTarget.ITEM,
+ value: 12,
+ currency_code: "eur",
+ is_enabled: true,
+ priority: 10,
+ })
+
+ const cart = await createCart()
+ const updatedCart = await addItemToCart(cart.id, product.variants[0].id, 1)
+
+ const commissionLines = await commissionService.getCommissionLines({
+ currency_code: "usd",
+ items: updatedCart.items.map((item: any) => ({
+ id: item.id,
+ subtotal: item.subtotal,
+ product: { id: product.id },
+ })),
+ })
+
+ expect(commissionLines).toHaveLength(1)
+ expect(commissionLines[0].code).toEqual("USD_RATE")
+ })
+
+ it("7.2 should fall back to rate without currency when specific doesn't match", async () => {
+ // EUR rate 10%
+ await commissionService.createCommissionRates({
+ name: "EUR Only Rate",
+ code: "EUR_ONLY",
+ type: CommissionRateType.PERCENTAGE,
+ target: CommissionRateTarget.ITEM,
+ value: 10,
+ currency_code: "eur",
+ is_enabled: true,
+ priority: 10,
+ })
+
+ // Any currency rate 8%
+ await commissionService.createCommissionRates({
+ name: "Any Currency Rate",
+ code: "ANY_CURRENCY",
+ type: CommissionRateType.PERCENTAGE,
+ target: CommissionRateTarget.ITEM,
+ value: 8,
+ currency_code: null,
+ is_enabled: true,
+ priority: 0,
+ })
+
+ const cart = await createCart()
+ const updatedCart = await addItemToCart(cart.id, product.variants[0].id, 1)
+
+ // Cart is USD, EUR rate won't match, should use ANY_CURRENCY
+ const commissionLines = await commissionService.getCommissionLines({
+ currency_code: "usd",
+ items: updatedCart.items.map((item: any) => ({
+ id: item.id,
+ subtotal: item.subtotal,
+ product: { id: product.id },
+ })),
+ })
+
+ expect(commissionLines).toHaveLength(1)
+ expect(commissionLines[0].code).toEqual("ANY_CURRENCY")
+ })
+
+ it("7.3 should not create commission line when no currency matches", async () => {
+ // EUR only rate
+ await commissionService.createCommissionRates({
+ name: "EUR Only",
+ code: "EUR_ONLY_STRICT",
+ type: CommissionRateType.PERCENTAGE,
+ target: CommissionRateTarget.ITEM,
+ value: 10,
+ currency_code: "eur",
+ is_enabled: true,
+ priority: 0,
+ })
+
+ const cart = await createCart()
+ const updatedCart = await addItemToCart(cart.id, product.variants[0].id, 1)
+
+ // Cart is USD, no matching rate
+ const commissionLines = await commissionService.getCommissionLines({
+ currency_code: "usd",
+ items: updatedCart.items.map((item: any) => ({
+ id: item.id,
+ subtotal: item.subtotal,
+ product: { id: product.id },
+ })),
+ })
+
+ expect(commissionLines).toHaveLength(0)
+ })
+ })
+
+ describe("8. Default Rate (No Rules)", () => {
+ it("8.1 should apply default rate when no specific rules match", async () => {
+ // Specific product rule (won't match)
+ await commissionService.createCommissionRates({
+ name: "Specific Product Rate",
+ code: "SPECIFIC_PROD",
+ type: CommissionRateType.PERCENTAGE,
+ target: CommissionRateTarget.ITEM,
+ value: 5,
+ is_enabled: true,
+ priority: 10,
+ rules: [{ reference: "product", reference_id: "prod_nonexistent" }],
+ })
+
+ // Default rate (no rules)
+ await commissionService.createCommissionRates({
+ name: "Default Rate",
+ code: "DEFAULT_RATE",
+ type: CommissionRateType.PERCENTAGE,
+ target: CommissionRateTarget.ITEM,
+ value: 10,
+ is_enabled: true,
+ priority: 0,
+ })
+
+ const cart = await createCart()
+ const updatedCart = await addItemToCart(cart.id, product.variants[0].id, 1)
+
+ const commissionLines = await commissionService.getCommissionLines({
+ currency_code: "usd",
+ items: updatedCart.items.map((item: any) => ({
+ id: item.id,
+ subtotal: item.subtotal,
+ product: { id: product.id },
+ })),
+ })
+
+ expect(commissionLines).toHaveLength(1)
+ expect(commissionLines[0].code).toEqual("DEFAULT_RATE")
+ })
+
+ it("8.2 should apply specific rule over default", async () => {
+ // Specific seller rule
+ await commissionService.createCommissionRates({
+ name: "Seller Rate",
+ code: "SELLER_SPECIFIC",
+ type: CommissionRateType.PERCENTAGE,
+ target: CommissionRateTarget.ITEM,
+ value: 5,
+ is_enabled: true,
+ priority: 10,
+ rules: [{ reference: "seller", reference_id: seller.id }],
+ })
+
+ // Default rate (no rules)
+ await commissionService.createCommissionRates({
+ name: "Default Rate",
+ code: "DEFAULT_FALLBACK",
+ type: CommissionRateType.PERCENTAGE,
+ target: CommissionRateTarget.ITEM,
+ value: 10,
+ is_enabled: true,
+ priority: 0,
+ })
+
+ const cart = await createCart()
+ const updatedCart = await addItemToCart(cart.id, product.variants[0].id, 1)
+
+ const commissionLines = await commissionService.getCommissionLines({
+ currency_code: "usd",
+ items: updatedCart.items.map((item: any) => ({
+ id: item.id,
+ subtotal: item.subtotal,
+ product: { id: product.id, seller: { id: seller.id } },
+ })),
+ })
+
+ expect(commissionLines).toHaveLength(1)
+ expect(commissionLines[0].code).toEqual("SELLER_SPECIFIC")
+ })
+ })
+
+ describe("9. Edge Cases", () => {
+ it("9.1 should return no commission lines when no matching rates", async () => {
+ // Only shipping rate, no item rate
+ await commissionService.createCommissionRates({
+ name: "Shipping Only",
+ code: "SHIPPING_ONLY",
+ type: CommissionRateType.PERCENTAGE,
+ target: CommissionRateTarget.SHIPPING,
+ value: 15,
+ is_enabled: true,
+ priority: 0,
+ })
+
+ const cart = await createCart()
+ const updatedCart = await addItemToCart(cart.id, product.variants[0].id, 1)
+
+ const commissionLines = await commissionService.getCommissionLines({
+ currency_code: "usd",
+ items: updatedCart.items.map((item: any) => ({
+ id: item.id,
+ subtotal: item.subtotal,
+ product: { id: product.id },
+ })),
+ shipping_methods: [],
+ })
+
+ expect(commissionLines).toHaveLength(0)
+ })
+
+ it("9.2 should return empty array for empty cart", async () => {
+ await commissionService.createCommissionRates({
+ name: "Default",
+ code: "EMPTY_CART_DEFAULT",
+ type: CommissionRateType.PERCENTAGE,
+ target: CommissionRateTarget.ITEM,
+ value: 10,
+ is_enabled: true,
+ priority: 0,
+ })
+
+ const commissionLines = await commissionService.getCommissionLines({
+ currency_code: "usd",
+ items: [],
+ shipping_methods: [],
+ })
+
+ expect(commissionLines).toHaveLength(0)
+ })
+
+ it("9.4 should handle multiple items with different rates and calculate correct amounts", async () => {
+ // Create second seller
+ const seller2Result = await createSellerUser(appContainer, {
+ email: "[email protected]",
+ name: "Commission Test Seller 2",
+ })
+ const seller2 = seller2Result.seller
+
+ // Seller 1 rate 5%
+ await commissionService.createCommissionRates({
+ name: "Seller 1 Rate",
+ code: "SELLER1_5",
+ type: CommissionRateType.PERCENTAGE,
+ target: CommissionRateTarget.ITEM,
+ value: 5,
+ is_enabled: true,
+ priority: 10,
+ rules: [{ reference: "seller", reference_id: seller.id }],
+ })
+
+ // Seller 2 rate 8%
+ await commissionService.createCommissionRates({
+ name: "Seller 2 Rate",
+ code: "SELLER2_8",
+ type: CommissionRateType.PERCENTAGE,
+ target: CommissionRateTarget.ITEM,
+ value: 8,
+ is_enabled: true,
+ priority: 10,
+ rules: [{ reference: "seller", reference_id: seller2.id }],
+ })
+
+ // Default rate 10%
+ await commissionService.createCommissionRates({
+ name: "Default Rate",
+ code: "DEFAULT_10_MULTI",
+ type: CommissionRateType.PERCENTAGE,
+ target: CommissionRateTarget.ITEM,
+ value: 10,
+ is_enabled: true,
+ priority: 0,
+ })
+
+ // Each item has $100 subtotal
+ const commissionLines = await commissionService.getCommissionLines({
+ currency_code: "usd",
+ items: [
+ { id: "item_1", subtotal: 10000, product: { id: "prod_1", seller: { id: seller.id } } }, // 5% of $100 = $5
+ { id: "item_2", subtotal: 10000, product: { id: "prod_2", seller: { id: seller2.id } } }, // 8% of $100 = $8
+ { id: "item_3", subtotal: 10000, product: { id: "prod_3" } }, // 10% of $100 = $10 (default)
+ ],
+ })
+
+ expect(commissionLines).toHaveLength(3)
+
+ const seller1Line = commissionLines.find(l => l.item_id === "item_1")
+ const seller2Line = commissionLines.find(l => l.item_id === "item_2")
+ const defaultLine = commissionLines.find(l => l.item_id === "item_3")
+
+ expect(seller1Line?.code).toEqual("SELLER1_5")
+ expect(seller1Line?.amount).toEqual(500) // 5% of $100 = $5 (500 cents)
+
+ expect(seller2Line?.code).toEqual("SELLER2_8")
+ expect(seller2Line?.amount).toEqual(800) // 8% of $100 = $8 (800 cents)
+
+ expect(defaultLine?.code).toEqual("DEFAULT_10_MULTI")
+ expect(defaultLine?.amount).toEqual(1000) // 10% of $100 = $10 (1000 cents)
+ })
+
+ it("9.5 should ignore disabled rates", async () => {
+ // Disabled rate
+ await commissionService.createCommissionRates({
+ name: "Disabled Rate",
+ code: "DISABLED_RATE",
+ type: CommissionRateType.PERCENTAGE,
+ target: CommissionRateTarget.ITEM,
+ value: 10,
+ is_enabled: false,
+ priority: 10,
+ })
+
+ // Enabled rate
+ await commissionService.createCommissionRates({
+ name: "Enabled Rate",
+ code: "ENABLED_RATE",
+ type: CommissionRateType.PERCENTAGE,
+ target: CommissionRateTarget.ITEM,
+ value: 15,
+ is_enabled: true,
+ priority: 0,
+ })
+
+ const cart = await createCart()
+ const updatedCart = await addItemToCart(cart.id, product.variants[0].id, 1)
+
+ const commissionLines = await commissionService.getCommissionLines({
+ currency_code: "usd",
+ items: updatedCart.items.map((item: any) => ({
+ id: item.id,
+ subtotal: item.subtotal,
+ product: { id: product.id },
+ })),
+ })
+
+ expect(commissionLines).toHaveLength(1)
+ expect(commissionLines[0].code).toEqual("ENABLED_RATE")
+ })
+ })
+
+ describe("10. Combined Scenarios", () => {
+ it("10.1 should handle full cart with items and shipping and calculate correct amounts", async () => {
+ // Item commission 10%
+ await commissionService.createCommissionRates({
+ name: "Item Commission",
+ code: "COMBINED_ITEM",
+ type: CommissionRateType.PERCENTAGE,
+ target: CommissionRateTarget.ITEM,
+ value: 10,
+ is_enabled: true,
+ priority: 0,
+ })
+
+ // Shipping commission 15%
+ await commissionService.createCommissionRates({
+ name: "Shipping Commission",
+ code: "COMBINED_SHIPPING",
+ type: CommissionRateType.PERCENTAGE,
+ target: CommissionRateTarget.SHIPPING,
+ value: 15,
+ is_enabled: true,
+ priority: 0,
+ })
+
+ const cart = await createCart()
+ await addItemToCart(cart.id, product.variants[0].id, 1) // $100
+ await addItemToCart(cart.id, product.variants[1].id, 1) // $50
+ await updateCartWithAddress(cart.id)
+ const cartWithShipping = await addShippingMethodToCart(cart.id, shippingOption.id)
+
+ // Item 1: $100 -> 10% = $10
+ // Item 2: $50 -> 10% = $5
+ // Shipping: $20 -> 15% = $3
+ const commissionLines = await commissionService.getCommissionLines({
+ currency_code: "usd",
+ items: [
+ { id: "item_100", subtotal: 10000, product: { id: product.id } }, // $100
+ { id: "item_50", subtotal: 5000, product: { id: product.id } }, // $50
+ ],
+ shipping_methods: cartWithShipping.shipping_methods.map((sm: any) => ({
+ id: sm.id,
+ subtotal: 2000, // $20
+ })),
+ })
+
+ // 2 item commission lines + 1 shipping commission line
+ expect(commissionLines).toHaveLength(3)
+
+ const item100Line = commissionLines.find(l => l.item_id === "item_100")
+ const item50Line = commissionLines.find(l => l.item_id === "item_50")
+ const shippingLine = commissionLines.find(l => l.code === "COMBINED_SHIPPING")
+
+ expect(item100Line?.code).toEqual("COMBINED_ITEM")
+ expect(item100Line?.amount).toEqual(1000) // 10% of $100 = $10 (1000 cents)
+
+ expect(item50Line?.code).toEqual("COMBINED_ITEM")
+ expect(item50Line?.amount).toEqual(500) // 10% of $50 = $5 (500 cents)
+
+ expect(shippingLine?.code).toEqual("COMBINED_SHIPPING")
+ expect(shippingLine?.amount).toEqual(300) // 15% of $20 = $3 (300 cents)
+ })
+
+ it("10.2 should create commission lines linked to order line items after checkout", async () => {
+ // Create 10% item commission rate
+ await commissionService.createCommissionRates({
+ name: "Order Item Commission",
+ code: "ORDER_ITEM_10",
+ type: CommissionRateType.PERCENTAGE,
+ target: CommissionRateTarget.ITEM,
+ value: 10,
+ is_enabled: true,
+ priority: 0,
+ })
+
+ // Create cart and complete checkout flow
+ // Find the $100 variant (Small) by SKU to ensure correct variant
+ const variant100 = product.variants.find((v: any) => v.sku === "COMM-TEST-S")
+ const cart = await createCart()
+ await addItemToCart(cart.id, variant100.id, 1) // $100
+ await updateCartWithAddress(cart.id)
+ await addShippingMethodToCart(cart.id, shippingOption.id)
+
+ // Create payment collection
+ const paymentCollectionResponse = await api.post(
+ `/store/payment-collections`,
+ { cart_id: cart.id },
+ storeHeaders
+ )
+ const paymentCollection = paymentCollectionResponse.data.payment_collection
+
+ // Initialize payment session
+ await api.post(
+ `/store/payment-collections/${paymentCollection.id}/payment-sessions`,
+ { provider_id: "pp_system_default" },
+ storeHeaders
+ )
+
+ // Complete cart
+ const completeResponse = await api.post(
+ `/store/carts/${cart.id}/complete`,
+ {},
+ storeHeaders
+ )
+
+ expect(completeResponse.data.type).toEqual("order_group")
+ const orderGroupId = completeResponse.data.order_group.id
+
+ // Fetch order with commission lines linked through line items using query
+ const { data: [orderGroup] } = await query.graph({
+ entity: "order_group",
+ fields: ["id", "orders.*", "orders.items.*", "orders.items.commission_lines.*"],
+ filters: { id: orderGroupId },
+ })
+ const order = orderGroup.orders[0]
+
+ expect(order).toBeDefined()
+ expect(order.items).toBeDefined()
+ expect(order.items.length).toBeGreaterThan(0)
+
+ // Verify commission lines are linked to line items
+ const itemWithCommission = order.items[0]
+ expect(itemWithCommission.commission_lines).toBeDefined()
+ expect(itemWithCommission.commission_lines.length).toBeGreaterThan(0)
+
+ // Verify commission line details
+ const commissionLine = itemWithCommission.commission_lines[0]
+ expect(commissionLine.code).toEqual("ORDER_ITEM_10")
+ expect(commissionLine.rate).toEqual(10)
+ expect(commissionLine.amount).toEqual(1000) // 10% of $100 = $10 (1000 cents)
+ })
+
+ it("10.3 should apply correct rate in complex override hierarchy and calculate amount", async () => {
+ // Product type rate 7%
+ await commissionService.createCommissionRates({
+ name: "Product Type Rate",
+ code: "TYPE_7",
+ type: CommissionRateType.PERCENTAGE,
+ target: CommissionRateTarget.ITEM,
+ value: 7,
+ is_enabled: true,
+ priority: 5,
+ rules: [{ reference: "product_type", reference_id: "ptyp_electronics" }],
+ })
+
+ // Category rate 8%
+ await commissionService.createCommissionRates({
+ name: "Category Rate",
+ code: "CATEGORY_8",
+ type: CommissionRateType.PERCENTAGE,
+ target: CommissionRateTarget.ITEM,
+ value: 8,
+ is_enabled: true,
+ priority: 7,
+ rules: [{ reference: "product_category", reference_id: "pcat_premium" }],
+ })
+
+ // Seller VIP rate 6% (highest priority)
+ await commissionService.createCommissionRates({
+ name: "VIP Seller Rate",
+ code: "SELLER_VIP_6_COMPLEX",
+ type: CommissionRateType.PERCENTAGE,
+ target: CommissionRateTarget.ITEM,
+ value: 6,
+ is_enabled: true,
+ priority: 10,
+ rules: [{ reference: "seller", reference_id: seller.id }],
+ })
+
+ // Item has all three: seller_vip, category_premium, type_electronics
+ // Seller rate should win (priority 10)
+ // $100 subtotal -> 6% = $6 (600 cents)
+ const commissionLines = await commissionService.getCommissionLines({
+ currency_code: "usd",
+ items: [{
+ id: "item_complex",
+ subtotal: 10000, // $100 in cents
+ product: {
+ id: product.id,
+ type_id: "ptyp_electronics",
+ categories: [{ id: "pcat_premium" }],
+ seller: { id: seller.id },
+ },
+ }],
+ })
+
+ expect(commissionLines).toHaveLength(1)
+ expect(commissionLines[0].code).toEqual("SELLER_VIP_6_COMPLEX")
+ expect(commissionLines[0].rate).toEqual(6)
+ expect(commissionLines[0].amount).toEqual(600) // 6% of $100 = $6 (600 cents)
+ })
+ })
+ })
+ },
+})
diff --git a/packages/core/src/links/line-item-commission-line-link.ts b/packages/core/src/links/line-item-commission-line-link.ts
new file mode 100644
index 000000000..c8a0c49c3
--- /dev/null
+++ b/packages/core/src/links/line-item-commission-line-link.ts
@@ -0,0 +1,20 @@
+import { defineLink } from "@medusajs/framework/utils"
+import OrderModule from "@medusajs/medusa/order"
+import CommissionModule from "../modules/commission"
+
+export default defineLink(
+ {
+ linkable: OrderModule.linkable.orderLineItem,
+ field: "id",
+ isList: true,
+ },
+ {
+ ...CommissionModule.linkable.commissionLine.id,
+ alias: "commission_lines",
+ primaryKey: "item_id",
+ isList: true,
+ },
+ {
+ readOnly: true,
+ }
+)
diff --git a/packages/core/src/modules/commission/index.ts b/packages/core/src/modules/commission/index.ts
new file mode 100644
index 000000000..090f7c413
--- /dev/null
+++ b/packages/core/src/modules/commission/index.ts
@@ -0,0 +1,9 @@
+import { Module } from "@medusajs/framework/utils"
+
+import CommissionModuleService from "./service"
+
+export const COMMISSION_MODULE = "commission"
+
+export default Module(COMMISSION_MODULE, {
+ service: CommissionModuleService,
+})
diff --git a/packages/core/src/modules/commission/migrations/.snapshot-medusa-commission.json b/packages/core/src/modules/commission/migrations/.snapshot-medusa-commission.json
new file mode 100644
index 000000000..ba59630a8
--- /dev/null
+++ b/packages/core/src/modules/commission/migrations/.snapshot-medusa-commission.json
@@ -0,0 +1,463 @@
+{
+ "namespaces": [
+ "public"
+ ],
+ "name": "public",
+ "tables": [
+ {
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "unsigned": false,
+ "autoincrement": false,
+ "primary": false,
+ "nullable": false,
+ "mappedType": "text"
+ },
+ "item_id": {
+ "name": "item_id",
+ "type": "text",
+ "unsigned": false,
+ "autoincrement": false,
+ "primary": false,
+ "nullable": false,
+ "mappedType": "text"
+ },
+ "commission_rate_id": {
+ "name": "commission_rate_id",
+ "type": "text",
+ "unsigned": false,
+ "autoincrement": false,
+ "primary": false,
+ "nullable": true,
+ "mappedType": "text"
+ },
+ "code": {
+ "name": "code",
+ "type": "text",
+ "unsigned": false,
+ "autoincrement": false,
+ "primary": false,
+ "nullable": false,
+ "mappedType": "text"
+ },
+ "rate": {
+ "name": "rate",
+ "type": "real",
+ "unsigned": false,
+ "autoincrement": false,
+ "primary": false,
+ "nullable": false,
+ "mappedType": "float"
+ },
+ "amount": {
+ "name": "amount",
+ "type": "numeric",
+ "unsigned": false,
+ "autoincrement": false,
+ "primary": false,
+ "nullable": false,
+ "mappedType": "decimal"
+ },
+ "description": {
+ "name": "description",
+ "type": "text",
+ "unsigned": false,
+ "autoincrement": false,
+ "primary": false,
+ "nullable": true,
+ "mappedType": "text"
+ },
+ "raw_amount": {
+ "name": "raw_amount",
+ "type": "jsonb",
+ "unsigned": false,
+ "autoincrement": false,
+ "primary": false,
+ "nullable": false,
+ "mappedType": "json"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamptz",
+ "unsigned": false,
+ "autoincrement": false,
+ "primary": false,
+ "nullable": false,
+ "length": 6,
+ "default": "now()",
+ "mappedType": "datetime"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamptz",
+ "unsigned": false,
+ "autoincrement": false,
+ "primary": false,
+ "nullable": false,
+ "length": 6,
+ "default": "now()",
+ "mappedType": "datetime"
+ },
+ "deleted_at": {
+ "name": "deleted_at",
+ "type": "timestamptz",
+ "unsigned": false,
+ "autoincrement": false,
+ "primary": false,
+ "nullable": true,
+ "length": 6,
+ "mappedType": "datetime"
+ }
+ },
+ "name": "commission_line",
+ "schema": "public",
+ "indexes": [
+ {
+ "keyName": "IDX_commission_line_deleted_at",
+ "columnNames": [],
+ "composite": false,
+ "constraint": false,
+ "primary": false,
+ "unique": false,
+ "expression": "CREATE INDEX IF NOT EXISTS \"IDX_commission_line_deleted_at\" ON \"commission_line\" (\"deleted_at\") WHERE deleted_at IS NULL"
+ },
+ {
+ "keyName": "commission_line_pkey",
+ "columnNames": [
+ "id"
+ ],
+ "composite": false,
+ "constraint": true,
+ "primary": true,
+ "unique": true
+ }
+ ],
+ "checks": [],
+ "foreignKeys": {},
+ "nativeEnums": {}
+ },
+ {
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "unsigned": false,
+ "autoincrement": false,
+ "primary": false,
+ "nullable": false,
+ "mappedType": "text"
+ },
+ "is_enabled": {
+ "name": "is_enabled",
+ "type": "boolean",
+ "unsigned": false,
+ "autoincrement": false,
+ "primary": false,
+ "nullable": false,
+ "default": "true",
+ "mappedType": "boolean"
+ },
+ "priority": {
+ "name": "priority",
+ "type": "integer",
+ "unsigned": false,
+ "autoincrement": false,
+ "primary": false,
+ "nullable": false,
+ "default": "0",
+ "mappedType": "integer"
+ },
+ "currency_code": {
+ "name": "currency_code",
+ "type": "text",
+ "unsigned": false,
+ "autoincrement": false,
+ "primary": false,
+ "nullable": true,
+ "mappedType": "text"
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "unsigned": false,
+ "autoincrement": false,
+ "primary": false,
+ "nullable": false,
+ "mappedType": "text"
+ },
+ "code": {
+ "name": "code",
+ "type": "text",
+ "unsigned": false,
+ "autoincrement": false,
+ "primary": false,
+ "nullable": false,
+ "mappedType": "text"
+ },
+ "type": {
+ "name": "type",
+ "type": "text",
+ "unsigned": false,
+ "autoincrement": false,
+ "primary": false,
+ "nullable": false,
+ "enumItems": [
+ "fixed",
+ "percentage"
+ ],
+ "mappedType": "enum"
+ },
+ "target": {
+ "name": "target",
+ "type": "text",
+ "unsigned": false,
+ "autoincrement": false,
+ "primary": false,
+ "nullable": false,
+ "default": "'item'",
+ "enumItems": [
+ "item",
+ "shipping"
+ ],
+ "mappedType": "enum"
+ },
+ "value": {
+ "name": "value",
+ "type": "numeric",
+ "unsigned": false,
+ "autoincrement": false,
+ "primary": false,
+ "nullable": false,
+ "mappedType": "decimal"
+ },
+ "min_amount": {
+ "name": "min_amount",
+ "type": "numeric",
+ "unsigned": false,
+ "autoincrement": false,
+ "primary": false,
+ "nullable": true,
+ "mappedType": "decimal"
+ },
+ "include_tax": {
+ "name": "include_tax",
+ "type": "boolean",
+ "unsigned": false,
+ "autoincrement": false,
+ "primary": false,
+ "nullable": false,
+ "default": "false",
+ "mappedType": "boolean"
+ },
+ "raw_value": {
+ "name": "raw_value",
+ "type": "jsonb",
+ "unsigned": false,
+ "autoincrement": false,
+ "primary": false,
+ "nullable": false,
+ "mappedType": "json"
+ },
+ "raw_min_amount": {
+ "name": "raw_min_amount",
+ "type": "jsonb",
+ "unsigned": false,
+ "autoincrement": false,
+ "primary": false,
+ "nullable": true,
+ "mappedType": "json"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamptz",
+ "unsigned": false,
+ "autoincrement": false,
+ "primary": false,
+ "nullable": false,
+ "length": 6,
+ "default": "now()",
+ "mappedType": "datetime"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamptz",
+ "unsigned": false,
+ "autoincrement": false,
+ "primary": false,
+ "nullable": false,
+ "length": 6,
+ "default": "now()",
+ "mappedType": "datetime"
+ },
+ "deleted_at": {
+ "name": "deleted_at",
+ "type": "timestamptz",
+ "unsigned": false,
+ "autoincrement": false,
+ "primary": false,
+ "nullable": true,
+ "length": 6,
+ "mappedType": "datetime"
+ }
+ },
+ "name": "commission_rate",
+ "schema": "public",
+ "indexes": [
+ {
+ "keyName": "IDX_commission_rate_code_unique",
+ "columnNames": [],
+ "composite": false,
+ "constraint": false,
+ "primary": false,
+ "unique": false,
+ "expression": "CREATE UNIQUE INDEX IF NOT EXISTS \"IDX_commission_rate_code_unique\" ON \"commission_rate\" (\"code\") WHERE deleted_at IS NULL"
+ },
+ {
+ "keyName": "IDX_commission_rate_deleted_at",
+ "columnNames": [],
+ "composite": false,
+ "constraint": false,
+ "primary": false,
+ "unique": false,
+ "expression": "CREATE INDEX IF NOT EXISTS \"IDX_commission_rate_deleted_at\" ON \"commission_rate\" (\"deleted_at\") WHERE deleted_at IS NULL"
+ },
+ {
+ "keyName": "commission_rate_pkey",
+ "columnNames": [
+ "id"
+ ],
+ "composite": false,
+ "constraint": true,
+ "primary": true,
+ "unique": true
+ }
+ ],
+ "checks": [],
+ "foreignKeys": {},
+ "nativeEnums": {}
+ },
+ {
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "unsigned": false,
+ "autoincrement": false,
+ "primary": false,
+ "nullable": false,
+ "mappedType": "text"
+ },
+ "reference": {
+ "name": "reference",
+ "type": "text",
+ "unsigned": false,
+ "autoincrement": false,
+ "primary": false,
+ "nullable": false,
+ "mappedType": "text"
+ },
+ "reference_id": {
+ "name": "reference_id",
+ "type": "text",
+ "unsigned": false,
+ "autoincrement": false,
+ "primary": false,
+ "nullable": false,
+ "mappedType": "text"
+ },
+ "commission_rate_id": {
+ "name": "commission_rate_id",
+ "type": "text",
+ "unsigned": false,
+ "autoincrement": false,
+ "primary": false,
+ "nullable": false,
+ "mappedType": "text"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamptz",
+ "unsigned": false,
+ "autoincrement": false,
+ "primary": false,
+ "nullable": false,
+ "length": 6,
+ "default": "now()",
+ "mappedType": "datetime"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamptz",
+ "unsigned": false,
+ "autoincrement": false,
+ "primary": false,
+ "nullable": false,
+ "length": 6,
+ "default": "now()",
+ "mappedType": "datetime"
+ },
+ "deleted_at": {
+ "name": "deleted_at",
+ "type": "timestamptz",
+ "unsigned": false,
+ "autoincrement": false,
+ "primary": false,
+ "nullable": true,
+ "length": 6,
+ "mappedType": "datetime"
+ }
+ },
+ "name": "commission_rule",
+ "schema": "public",
+ "indexes": [
+ {
+ "keyName": "IDX_commission_rule_commission_rate_id",
+ "columnNames": [],
+ "composite": false,
+ "constraint": false,
+ "primary": false,
+ "unique": false,
+ "expression": "CREATE INDEX IF NOT EXISTS \"IDX_commission_rule_commission_rate_id\" ON \"commission_rule\" (\"commission_rate_id\") WHERE deleted_at IS NULL"
+ },
+ {
+ "keyName": "IDX_commission_rule_deleted_at",
+ "columnNames": [],
+ "composite": false,
+ "constraint": false,
+ "primary": false,
+ "unique": false,
+ "expression": "CREATE INDEX IF NOT EXISTS \"IDX_commission_rule_deleted_at\" ON \"commission_rule\" (\"deleted_at\") WHERE deleted_at IS NULL"
+ },
+ {
+ "keyName": "commission_rule_pkey",
+ "columnNames": [
+ "id"
+ ],
+ "composite": false,
+ "constraint": true,
+ "primary": true,
+ "unique": true
+ }
+ ],
+ "checks": [],
+ "foreignKeys": {
+ "commission_rule_commission_rate_id_foreign": {
+ "constraintName": "commission_rule_commission_rate_id_foreign",
+ "columnNames": [
+ "commission_rate_id"
+ ],
+ "localTableName": "public.commission_rule",
+ "referencedColumnNames": [
+ "id"
+ ],
+ "referencedTableName": "public.commission_rate",
+ "updateRule": "cascade"
+ }
+ },
+ "nativeEnums": {}
+ }
+ ],
+ "nativeEnums": {}
+}
diff --git a/packages/core/src/modules/commission/migrations/Migration20260128163533.ts b/packages/core/src/modules/commission/migrations/Migration20260128163533.ts
new file mode 100644
index 000000000..62ea55b14
--- /dev/null
+++ b/packages/core/src/modules/commission/migrations/Migration20260128163533.ts
@@ -0,0 +1,31 @@
+import { Migration } from "@medusajs/framework/mikro-orm/migrations";
+
+export class Migration20260128163533 extends Migration {
+
+ override async up(): Promise<void> {
+ this.addSql(`alter table if exists "commission_rate" drop constraint if exists "commission_rate_code_unique";`);
+ this.addSql(`create table if not exists "commission_line" ("id" text not null, "item_id" text not null, "commission_rate_id" text null, "code" text not null, "rate" real not null, "amount" numeric not null, "description" text null, "raw_amount" jsonb not null, "created_at" timestamptz not null default now(), "updated_at" timestamptz not null default now(), "deleted_at" timestamptz null, constraint "commission_line_pkey" primary key ("id"));`);
+ this.addSql(`CREATE INDEX IF NOT EXISTS "IDX_commission_line_deleted_at" ON "commission_line" ("deleted_at") WHERE deleted_at IS NULL;`);
+
+ this.addSql(`create table if not exists "commission_rate" ("id" text not null, "is_enabled" boolean not null default true, "priority" integer not null default 0, "currency_code" text null, "name" text not null, "code" text not null, "type" text check ("type" in ('fixed', 'percentage')) not null, "target" text check ("target" in ('item', 'shipping')) not null default 'item', "value" numeric not null, "min_amount" numeric null, "include_tax" boolean not null default false, "raw_value" jsonb not null, "raw_min_amount" jsonb null, "created_at" timestamptz not null default now(), "updated_at" timestamptz not null default now(), "deleted_at" timestamptz null, constraint "commission_rate_pkey" primary key ("id"));`);
+ this.addSql(`CREATE UNIQUE INDEX IF NOT EXISTS "IDX_commission_rate_code_unique" ON "commission_rate" ("code") WHERE deleted_at IS NULL;`);
+ this.addSql(`CREATE INDEX IF NOT EXISTS "IDX_commission_rate_deleted_at" ON "commission_rate" ("deleted_at") WHERE deleted_at IS NULL;`);
+
+ this.addSql(`create table if not exists "commission_rule" ("id" text not null, "reference" text not null, "reference_id" text not null, "commission_rate_id" text not null, "created_at" timestamptz not null default now(), "updated_at" timestamptz not null default now(), "deleted_at" timestamptz null, constraint "commission_rule_pkey" primary key ("id"));`);
+ this.addSql(`CREATE INDEX IF NOT EXISTS "IDX_commission_rule_commission_rate_id" ON "commission_rule" ("commission_rate_id") WHERE deleted_at IS NULL;`);
+ this.addSql(`CREATE INDEX IF NOT EXISTS "IDX_commission_rule_deleted_at" ON "commission_rule" ("deleted_at") WHERE deleted_at IS NULL;`);
+
+ this.addSql(`alter table if exists "commission_rule" add constraint "commission_rule_commission_rate_id_foreign" foreign key ("commission_rate_id") references "commission_rate" ("id") on update cascade;`);
+ }
+
+ override async down(): Promise<void> {
+ this.addSql(`alter table if exists "commission_rule" drop constraint if exists "commission_rule_commission_rate_id_foreign";`);
+
+ this.addSql(`drop table if exists "commission_line" cascade;`);
+
+ this.addSql(`drop table if exists "commission_rate" cascade;`);
+
+ this.addSql(`drop table if exists "commission_rule" cascade;`);
+ }
+
+}
diff --git a/packages/core/src/modules/commission/models/commission-line.ts b/packages/core/src/modules/commission/models/commission-line.ts
new file mode 100644
index 000000000..fbe8e6615
--- /dev/null
+++ b/packages/core/src/modules/commission/models/commission-line.ts
@@ -0,0 +1,13 @@
+import { model } from "@medusajs/framework/utils"
+
+const CommissionLine = model.define("commission_line", {
+ id: model.id({ prefix: "comline" }).primaryKey(),
+ item_id: model.text(),
+ commission_rate_id: model.text().nullable(),
+ code: model.text(),
+ rate: model.float(),
+ amount: model.bigNumber(),
+ description: model.text().nullable(),
+})
+
+export default CommissionLine
diff --git a/packages/core/src/modules/commission/models/commission-rate.ts b/packages/core/src/modules/commission/models/commission-rate.ts
new file mode 100644
index 000000000..97cd1c8c7
--- /dev/null
+++ b/packages/core/src/modules/commission/models/commission-rate.ts
@@ -0,0 +1,23 @@
+import { model } from "@medusajs/framework/utils"
+import { CommissionRateType, CommissionRateTarget } from "@mercurjs/types"
+
+import CommissionRule from "./commission-rule"
+
+const CommissionRate = model.define("commission_rate", {
+ id: model.id({ prefix: "comrate" }).primaryKey(),
+ is_enabled: model.boolean().default(true),
+ priority: model.number().default(0),
+ currency_code: model.text().nullable(),
+ name: model.text(),
+ code: model.text().unique(),
+ type: model.enum(CommissionRateType),
+ target: model.enum(CommissionRateTarget).default(CommissionRateTarget.ITEM),
+ value: model.bigNumber(),
+ min_amount: model.bigNumber().nullable(),
+ include_tax: model.boolean().default(false),
+ rules: model.hasMany(() => CommissionRule, {
+ mappedBy: "commission_rate",
+ }),
+})
+
+export default CommissionRate
diff --git a/packages/core/src/modules/commission/models/commission-rule.ts b/packages/core/src/modules/commission/models/commission-rule.ts
new file mode 100644
index 000000000..e1cbf9433
--- /dev/null
+++ b/packages/core/src/modules/commission/models/commission-rule.ts
@@ -0,0 +1,14 @@
+import { model } from "@medusajs/framework/utils"
+
+import CommissionRate from "./commission-rate"
+
+const CommissionRule = model.define("commission_rule", {
+ id: model.id({ prefix: "comrule" }).primaryKey(),
+ reference: model.text(),
+ reference_id: model.text(),
+ commission_rate: model.belongsTo(() => CommissionRate, {
+ mappedBy: "rules",
+ }),
+})
+
+export default CommissionRule
diff --git a/packages/core/src/modules/commission/models/index.ts b/packages/core/src/modules/commission/models/index.ts
new file mode 100644
index 000000000..3d0e4c4e3
--- /dev/null
+++ b/packages/core/src/modules/commission/models/index.ts
@@ -0,0 +1,3 @@
+export { default as CommissionRate } from "./commission-rate"
+export { default as CommissionRule } from "./commission-rule"
+export { default as CommissionLine } from "./commission-line"
diff --git a/packages/core/src/modules/commission/service.ts b/packages/core/src/modules/commission/service.ts
new file mode 100644
index 000000000..7824c3a1f
--- /dev/null
+++ b/packages/core/src/modules/commission/service.ts
@@ -0,0 +1,222 @@
+import { Context, DAL, InferEntityType, ModulesSdkTypes } from "@medusajs/framework/types"
+import {
+ EmitEvents,
+ InjectManager,
+ MathBN,
+ MedusaContext,
+ MedusaService,
+} from "@medusajs/framework/utils"
+
+import {
+ CommissionCalculationContext,
+ CommissionLineDTO,
+ CommissionRateType,
+ CommissionRateTarget,
+ CommissionRateDTO,
+ CreateCommissionLineDTO,
+ UpdateCommissionLineDTO,
+} from "@mercurjs/types"
+
+import { CommissionRate, CommissionRule, CommissionLine } from "./models"
+
+class CommissionModuleService extends MedusaService({
+ CommissionRate,
+ CommissionRule,
+ CommissionLine,
+}) {
+ protected commissionLineService_: ModulesSdkTypes.IMedusaInternalService<
+ InferEntityType<typeof CommissionLine>
+ >
+ protected baseRepository_: DAL.RepositoryService
+
+ constructor({ commissionLineService, baseRepository }) {
+ super(...arguments)
+ this.commissionLineService_ = commissionLineService
+ this.baseRepository_ = baseRepository
+ }
+
+ @InjectManager()
+ async getCommissionLines(
+ context: CommissionCalculationContext,
+ @MedusaContext() sharedContext: Context = {}
+ ): Promise<CreateCommissionLineDTO[]> {
+ const commissionLines: CreateCommissionLineDTO[] = []
+ const { items = [], shipping_methods = [], currency_code } = context
+
+ // Get all enabled commission rates with their rules, ordered by priority DESC
+ const commissionRates = await this.listCommissionRates(
+ { is_enabled: true },
+ { relations: ["rules"], order: { priority: "DESC" } },
+ sharedContext
+ )
+
+ // Separate rates by target
+ const itemRates = commissionRates.filter(
+ (rate) => rate.target === CommissionRateTarget.ITEM
+ )
+ const shippingRates = commissionRates.filter(
+ (rate) => rate.target === CommissionRateTarget.SHIPPING
+ )
+
+ // Process each item
+ for (const item of items) {
+ const product = item.product
+ let matchedRate: CommissionRateDTO | null = null
+
+ // Find matching rate based on rules (priority order)
+ for (const rate of itemRates) {
+ // Check currency code match if specified
+ if (rate.currency_code && rate.currency_code !== currency_code) {
+ continue
+ }
+
+ // If no rules, this is a default rate
+ if (!rate.rules || rate.rules.length === 0) {
+ matchedRate = rate
+ break
+ }
+
+ // Check if any rule matches
+ const ruleMatches = rate.rules.some((rule) => {
+ if (!product) return false
+
+ switch (rule.reference) {
+ case "product":
+ return product.id === rule.reference_id
+ case "product_type":
+ return product.type_id === rule.reference_id
+ case "product_collection":
+ return product.collection_id === rule.reference_id
+ case "product_category":
+ return product.categories?.some((cat) => cat.id === rule.reference_id) ?? false
+ case "seller":
+ return product.seller?.id === rule.reference_id
+ default:
+ return false
+ }
+ })
+
+ if (ruleMatches) {
+ matchedRate = rate
+ break
+ }
+ }
+
+ if (!matchedRate) {
+ continue
+ }
+
+ // Calculate base amount (include tax if specified)
+ let baseAmount = item.subtotal
+ if (matchedRate.include_tax && item.tax_total) {
+ baseAmount = MathBN.add(item.subtotal, item.tax_total)
+ }
+
+ // Calculate commission amount using MathBN
+ let amount
+ if (matchedRate.type === CommissionRateType.PERCENTAGE) {
+ amount = MathBN.div(MathBN.mult(baseAmount, matchedRate.value), 100)
+ } else {
+ amount = matchedRate.value
+ }
+
+ // Apply minimum commission if set
+ if (matchedRate.min_amount !== null && MathBN.lt(amount, matchedRate.min_amount)) {
+ amount = matchedRate.min_amount
+ }
+
+ commissionLines.push({
+ item_id: item.id,
+ code: matchedRate.code,
+ rate: matchedRate.value,
+ amount: MathBN.convert(amount).toNumber(),
+ commission_rate_id: matchedRate.id,
+ })
+ }
+
+ // Process shipping methods
+ for (const shippingMethod of shipping_methods) {
+ let matchedRate: CommissionRateDTO | null = null
+
+ for (const rate of shippingRates) {
+ // Check currency code match if specified
+ if (rate.currency_code && rate.currency_code !== currency_code) {
+ continue
+ }
+
+ // If no rules, this is a default rate
+ if (!rate.rules || rate.rules.length === 0) {
+ matchedRate = rate
+ break
+ }
+
+ // Check if any rule matches shipping option
+ const ruleMatches = rate.rules.some((rule) => {
+ if (!shippingMethod.shipping_option) return false
+
+ switch (rule.reference) {
+ case "shipping_option_type":
+ return shippingMethod.shipping_option.shipping_option_type_id === rule.reference_id
+ default:
+ return false
+ }
+ })
+
+ if (ruleMatches) {
+ matchedRate = rate
+ break
+ }
+ }
+
+ if (!matchedRate) {
+ continue
+ }
+
+ // Calculate base amount (include tax if specified)
+ let baseAmount = shippingMethod.subtotal
+ if (matchedRate.include_tax && shippingMethod.tax_total) {
+ baseAmount = MathBN.add(shippingMethod.subtotal, shippingMethod.tax_total)
+ }
+
+ // Calculate commission amount using MathBN
+ let amount
+ if (matchedRate.type === CommissionRateType.PERCENTAGE) {
+ amount = MathBN.div(MathBN.mult(baseAmount, matchedRate.value), 100)
+ } else {
+ amount = matchedRate.value
+ }
+
+ // Apply minimum commission if set
+ if (matchedRate.min_amount !== null && MathBN.lt(amount, matchedRate.min_amount)) {
+ amount = matchedRate.min_amount
+ }
+
+ commissionLines.push({
+ item_id: shippingMethod.id,
+ code: matchedRate.code,
+ rate: matchedRate.value,
+ commission_rate_id: matchedRate.id,
+ description: `Shipping Commission`,
+ amount: MathBN.convert(amount).toNumber(),
+ })
+ }
+
+ return commissionLines
+ }
+
+ @InjectManager()
+ @EmitEvents()
+ async upsertCommissionLines(
+ commissionLines: (CreateCommissionLineDTO | UpdateCommissionLineDTO)[],
+ @MedusaContext() sharedContext: Context = {}
+ ): Promise<CommissionLineDTO[]> {
+ const result = await this.commissionLineService_.upsert(
+ commissionLines,
+ sharedContext
+ )
+
+ return await this.baseRepository_.serialize<CommissionLineDTO[]>(result)
+ }
+}
+
+export default CommissionModuleService
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
index 9bdb31293..4289f18a1 100644
--- a/packages/core/src/workflows/cart/utils/prepare-line-item-data.ts
+++ b/packages/core/src/workflows/cart/utils/prepare-line-item-data.ts
@@ -9,6 +9,7 @@ import {
ProductVariantDTO,
} from "@medusajs/framework/types"
import {
+ generateEntityId,
isDefined,
isPresent,
MathBN,
@@ -138,6 +139,7 @@ export function prepareLineItemData(data: PrepareLineItemDataInput) {
: hasShippingProfile || someInventoryRequiresShipping
let lineItem: any = {
+ id: generateEntityId(undefined, 'ordli'),
quantity: item?.quantity,
title: item?.title ?? variant?.product?.title,
subtitle: item?.subtitle ?? variant?.title,
diff --git a/packages/core/src/workflows/cart/workflows/complete-cart-with-split-orders.ts b/packages/core/src/workflows/cart/workflows/complete-cart-with-split-orders.ts
index 7c6c053c6..b0f2ad83d 100644
--- a/packages/core/src/workflows/cart/workflows/complete-cart-with-split-orders.ts
+++ b/packages/core/src/workflows/cart/workflows/complete-cart-with-split-orders.ts
@@ -54,6 +54,7 @@ import {
prepareConfirmInventoryInput,
} from "../utils"
import { registerUsageStep } from "../../promotion"
+import { refreshOrderCommissionLinesWorkflow } from "../../commission/workflows/refresh-order-commission-lines"
type CompleteCartWithSplitOrdersWorkflowInput = {
cart_id: string
@@ -77,6 +78,8 @@ export const completeCartWithSplitOrdersWorkflow = createWorkflow(
ttl: TWO_MINUTES,
})
+
+
const [orderGroup, cartData] = parallelize(
useQueryGraphStep({
entity: "order_group",
@@ -498,7 +501,17 @@ export const completeCartWithSplitOrdersWorkflow = createWorkflow(
}
)
- addOrderTransactionStep(orderTransactions)
+ const orderIds = transform({ createdOrders }, ({ createdOrders }) => {
+ return createdOrders.map((order) => order.id)
+ })
+
+ parallelize(
+ addOrderTransactionStep(orderTransactions),
+ refreshOrderCommissionLinesWorkflow.runAsStep({
+ input: {
+ order_ids: orderIds
+ }
+ }))
createHook("orderGroupCreated", {
order_group_id: createdOrderGroup.id,
diff --git a/packages/core/src/workflows/commission/index.ts b/packages/core/src/workflows/commission/index.ts
new file mode 100644
index 000000000..68de82c9f
--- /dev/null
+++ b/packages/core/src/workflows/commission/index.ts
@@ -0,0 +1,2 @@
+export * from "./steps"
+export * from "./workflows"
diff --git a/packages/core/src/workflows/commission/steps/get-commission-lines.ts b/packages/core/src/workflows/commission/steps/get-commission-lines.ts
new file mode 100644
index 000000000..90207f5d1
--- /dev/null
+++ b/packages/core/src/workflows/commission/steps/get-commission-lines.ts
@@ -0,0 +1,31 @@
+import { StepResponse, createStep } from "@medusajs/framework/workflows-sdk"
+import {
+ CommissionCalculationContext,
+ CreateCommissionLineDTO,
+} from "@mercurjs/types"
+
+import { COMMISSION_MODULE } from "../../../modules/commission"
+import CommissionModuleService from "../../../modules/commission/service"
+import { promiseAll } from "@medusajs/framework/utils"
+
+export const getCommissionLinesStepId = "get-commission-lines"
+
+export const getCommissionLinesStep = createStep(
+ getCommissionLinesStepId,
+ async (
+ input: CommissionCalculationContext[],
+ { container }
+ ): Promise<StepResponse<CreateCommissionLineDTO[]>> => {
+ const service =
+ container.resolve(COMMISSION_MODULE) as CommissionModuleService
+
+
+ const commissionLines = await promiseAll(
+ input.map(async (context) => {
+ return await service.getCommissionLines(context)
+ })
+ )
+
+ return new StepResponse(commissionLines.flat())
+ }
+)
diff --git a/packages/core/src/workflows/commission/steps/index.ts b/packages/core/src/workflows/commission/steps/index.ts
new file mode 100644
index 000000000..280639841
--- /dev/null
+++ b/packages/core/src/workflows/commission/steps/index.ts
@@ -0,0 +1,2 @@
+export * from "./get-commission-lines"
+export * from "./upsert-commission-lines"
diff --git a/packages/core/src/workflows/commission/steps/upsert-commission-lines.ts b/packages/core/src/workflows/commission/steps/upsert-commission-lines.ts
new file mode 100644
index 000000000..74a34c299
--- /dev/null
+++ b/packages/core/src/workflows/commission/steps/upsert-commission-lines.ts
@@ -0,0 +1,32 @@
+import { StepResponse, createStep } from "@medusajs/framework/workflows-sdk"
+import {
+ CommissionLineDTO,
+ CreateCommissionLineDTO,
+ UpdateCommissionLineDTO,
+} from "@mercurjs/types"
+
+import { COMMISSION_MODULE } from "../../../modules/commission"
+import CommissionModuleService from "../../../modules/commission/service"
+
+type UpsertCommissionLinesStepInput = {
+ commission_lines: (CreateCommissionLineDTO | UpdateCommissionLineDTO)[]
+}
+
+export const upsertCommissionLinesStepId = "upsert-commission-lines"
+
+export const upsertCommissionLinesStep = createStep(
+ upsertCommissionLinesStepId,
+ async (
+ input: UpsertCommissionLinesStepInput,
+ { container }
+ ): Promise<StepResponse<CommissionLineDTO[]>> => {
+ const service =
+ container.resolve<CommissionModuleService>(COMMISSION_MODULE)
+
+ const commissionLines = await service.upsertCommissionLines(
+ input.commission_lines
+ )
+
+ return new StepResponse(commissionLines)
+ }
+)
diff --git a/packages/core/src/workflows/commission/workflows/index.ts b/packages/core/src/workflows/commission/workflows/index.ts
new file mode 100644
index 000000000..1ef9312c7
--- /dev/null
+++ b/packages/core/src/workflows/commission/workflows/index.ts
@@ -0,0 +1 @@
+export * from "./refresh-order-commission-lines"
diff --git a/packages/core/src/workflows/commission/workflows/refresh-order-commission-lines.ts b/packages/core/src/workflows/commission/workflows/refresh-order-commission-lines.ts
new file mode 100644
index 000000000..9ac9e2a91
--- /dev/null
+++ b/packages/core/src/workflows/commission/workflows/refresh-order-commission-lines.ts
@@ -0,0 +1,99 @@
+import {
+ WorkflowData,
+ WorkflowResponse,
+ createWorkflow,
+ transform,
+} from "@medusajs/framework/workflows-sdk"
+import { useQueryGraphStep } from "@medusajs/medusa/core-flows"
+import { CommissionLineDTO } from "@mercurjs/types"
+
+import { getCommissionLinesStep, upsertCommissionLinesStep } from "../steps"
+
+const orderFields = [
+ "id",
+ "status",
+ "version",
+ "currency_code",
+ "email",
+ "canceled_at",
+ "sales_channel_id",
+ "region_id",
+ "customer_id",
+ "customer.*",
+ "customer.groups.*",
+ "promotions.*",
+ "subtotal",
+ "items.*",
+ "items.subtotal",
+ "items.product.id",
+ "items.product.collection_id",
+ "items.product.categories.id",
+ "items.product.tags.id",
+ "items.product.type_id",
+ "items.product.seller.id",
+ "items.adjustments.*",
+ "shipping_methods.*",
+ "shipping_methods.total",
+ "shipping_methods.subtotal",
+ "shipping_methods.tax_total",
+ "shipping_methods.adjustments.*",
+ "shipping_methods.shipping_option_id",
+ "shipping_address.*",
+]
+
+export type RefreshOrderCommissionLinesWorkflowInput = {
+ order_ids: string[]
+}
+
+export const refreshOrderCommissionLinesWorkflowId = "refresh-order-commission-lines"
+
+
+export const refreshOrderCommissionLinesWorkflow = createWorkflow(
+ refreshOrderCommissionLinesWorkflowId,
+ function (
+ input: WorkflowData<RefreshOrderCommissionLinesWorkflowInput>
+ ): WorkflowResponse<CommissionLineDTO[]> {
+ const { data: orders } = useQueryGraphStep({
+ entity: "order",
+ fields: orderFields,
+ filters: { id: input.order_ids },
+ options: {
+ throwIfKeyNotFound: true,
+ },
+ }).config({ name: "fetch-orders" })
+
+ const commissionContexts = transform({ orders }, ({ orders }) => {
+ return orders.map((order: any) => ({
+ currency_code: order.currency_code,
+ items: (order.items ?? []).map((item: any) => ({
+ id: item.id,
+ subtotal: item.subtotal,
+ tax_total: item.tax_total,
+ product: item.product
+ ? {
+ id: item.product.id,
+ collection_id: item.product.collection_id,
+ categories: item.product.categories,
+ tags: item.product.tags,
+ type_id: item.product.type_id,
+ seller: item.product.seller,
+ }
+ : undefined,
+ })),
+ shipping_methods: (order.shipping_methods ?? []).map((method: any) => ({
+ id: method.id,
+ subtotal: method.subtotal,
+ tax_total: method.tax_total,
+ })),
+ }))
+ })
+
+ const commissionLines = getCommissionLinesStep(commissionContexts)
+
+ const upsertedCommissionLines = upsertCommissionLinesStep({
+ commission_lines: commissionLines,
+ })
+
+ return new WorkflowResponse(upsertedCommissionLines)
+ }
+)
diff --git a/packages/core/src/workflows/index.ts b/packages/core/src/workflows/index.ts
index 655a55a42..d1226fba6 100644
--- a/packages/core/src/workflows/index.ts
+++ b/packages/core/src/workflows/index.ts
@@ -1,4 +1,5 @@
export * from "./campaign"
+export * from "./commission"
export * from "./inventory-item"
export * from "./order-group"
export * from "./price-list"
diff --git a/packages/types/src/commission/common.ts b/packages/types/src/commission/common.ts
new file mode 100644
index 000000000..47c21640e
--- /dev/null
+++ b/packages/types/src/commission/common.ts
@@ -0,0 +1,138 @@
+import { BigNumberInput } from "@medusajs/framework/types"
+
+export enum CommissionRateType {
+ FIXED = "fixed",
+ PERCENTAGE = "percentage",
+}
+
+export enum CommissionRateTarget {
+ ITEM = "item",
+ SHIPPING = "shipping",
+}
+
+export type CommissionRuleDTO = {
+ id: string
+ reference: string
+ reference_id: string
+ commission_rate_id: string
+ created_at: Date
+ updated_at: Date
+ deleted_at: Date | null
+}
+
+export type CommissionLineDTO = {
+ id: string
+ item_id: string
+ commission_rate_id: string | null
+ code: string
+ rate: number
+ amount: number
+ description: string | null
+ created_at: Date
+ updated_at: Date
+ deleted_at: Date | null
+}
+
+export type CommissionRateDTO = {
+ id: string
+ name: string
+ code: string
+ type: CommissionRateType
+ target: CommissionRateTarget
+ value: number
+ currency_code: string | null
+ min_amount: number | null
+ include_tax: boolean
+ is_enabled: boolean
+ priority: number
+ rules?: CommissionRuleDTO[]
+ created_at: Date
+ updated_at: Date
+ deleted_at: Date | null
+}
+
+export interface CommissionCalculationItemLine {
+ /**
+ * The ID of the item line.
+ */
+ id: string
+
+ /**
+ * The subtotal of the line item (base amount for commission calculation).
+ */
+ subtotal: BigNumberInput
+
+ /**
+ * The tax total of the line item (used when include_tax is true).
+ */
+ tax_total?: BigNumberInput
+
+ /**
+ * The product of the line item.
+ */
+ product?: {
+ id: string
+ collection_id?: string
+ tags?: { id: string }[]
+ categories?: { id: string }[]
+ type_id?: string
+ seller?: { id: string }
+ }
+}
+
+export interface CommissionCalculationShippingLine {
+ /**
+ * The ID of the shipping line.
+ */
+ id: string
+
+ /**
+ * The subtotal of the shipping method.
+ */
+ subtotal: BigNumberInput
+
+ /**
+ * The tax total of the shipping method (used when include_tax is true).
+ */
+ tax_total?: BigNumberInput
+
+ /**
+ * The shipping option type associated with the shipping method.
+ */
+ shipping_option?: {
+ /**
+ * The ID of the shipping option type associated with the shipping method.
+ */
+ shipping_option_type_id?: string
+ }
+}
+
+export interface CommissionCalculationContext {
+ /**
+ * The cart's currency
+ */
+ currency_code: string
+
+ /**
+ * The cart's line items.
+ */
+ items?: CommissionCalculationItemLine[]
+
+ /**
+ * The cart's shipping methods.
+ */
+ shipping_methods?: CommissionCalculationShippingLine[]
+}
+
+export interface CreateCommissionLineDTO {
+ item_id: string
+ commission_rate_id: string
+ code: string
+ rate: number
+ amount: number
+ description?: string | null
+}
+
+export interface UpdateCommissionLineDTO extends Partial<CreateCommissionLineDTO> {
+ id: string
+}
\ No newline at end of file
diff --git a/packages/types/src/commission/index.ts b/packages/types/src/commission/index.ts
new file mode 100644
index 000000000..488a94fdf
--- /dev/null
+++ b/packages/types/src/commission/index.ts
@@ -0,0 +1 @@
+export * from "./common"
diff --git a/packages/types/src/index.ts b/packages/types/src/index.ts
index 0f7c51a9e..c0d19d30e 100644
--- a/packages/types/src/index.ts
+++ b/packages/types/src/index.ts
@@ -4,5 +4,8 @@ export * from "./seller"
// Order Group types
export * from "./order-group"
+// Commission types
+export * from "./commission"
+
// HTTP types
export * as HttpTypes from "./http"