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(commission): add a provider seam to the commission module (#1509)

Viktor Holikf715d0bb7eb9
diff --git a/integration-tests/http/commission-rates/admin/commission-context-hook.spec.ts b/integration-tests/http/commission-rates/admin/commission-context-hook.spec.ts
new file mode 100644
index 000000000..8d604178d
--- /dev/null
+++ b/integration-tests/http/commission-rates/admin/commission-context-hook.spec.ts
@@ -0,0 +1,94 @@
+import { medusaIntegrationTestRunner } from "@medusajs/test-utils"
+import { MedusaContainer } from "@medusajs/framework/types"
+import { Modules } from "@medusajs/framework/utils"
+import { StepResponse } from "@medusajs/framework/workflows-sdk"
+import { CommissionCalculationContext, MercurModules } from "@mercurjs/types"
+import { refreshOrderCommissionLinesWorkflow } from "@mercurjs/core/workflows"
+
+jest.setTimeout(60000)
+
+medusaIntegrationTestRunner({
+ testSuite: ({ getContainer }) => {
+ describe("refreshOrderCommissionLinesWorkflow - setCommissionContext hook", () => {
+ let appContainer: MedusaContainer
+ let commissionService: any
+ let orderService: any
+ let productService: any
+
+ beforeAll(async () => {
+ appContainer = getContainer()
+ commissionService = appContainer.resolve(MercurModules.COMMISSION)
+ orderService = appContainer.resolve(Modules.ORDER)
+ productService = appContainer.resolve(Modules.PRODUCT)
+
+ refreshOrderCommissionLinesWorkflow.hooks.setCommissionContext(
+ ({ contexts }) =>
+ new StepResponse(
+ contexts.map((context) => ({
+ ...context,
+ additional_context: { marker: `hooked:${context.order_id}` },
+ }))
+ )
+ )
+ })
+
+ it("forwards additional_context, order_id and item totals to the provider", async () => {
+ const [product] = await productService.createProducts([
+ {
+ title: "Hooked product",
+ variants: [{ title: "Default", prices: [] }],
+ },
+ ])
+
+ const order = await orderService.createOrders({
+ currency_code: "usd",
+ email: "[email protected]",
+ items: [
+ {
+ title: "Hooked item",
+ quantity: 2,
+ unit_price: 100,
+ product_id: product.id,
+ variant_id: product.variants[0].id,
+ },
+ ],
+ shipping_methods: [{ name: "Standard", amount: 50 }],
+ })
+
+ const spy = jest.spyOn(commissionService, "getCommissionLines")
+
+ await refreshOrderCommissionLinesWorkflow(appContainer).run({
+ input: { order_ids: [order.id] },
+ })
+
+ expect(spy).toHaveBeenCalledTimes(1)
+ const [context] = spy.mock.calls[0] as [CommissionCalculationContext]
+
+ expect(context.order_id).toEqual(order.id)
+ expect(context.additional_context).toEqual({
+ marker: `hooked:${order.id}`,
+ })
+ expect(context.items).toHaveLength(1)
+ expect(context.items![0]).toEqual(
+ expect.objectContaining({
+ id: order.items![0].id,
+ subtotal: 200,
+ total: 200,
+ product: expect.objectContaining({
+ id: product.id,
+ attribute_value_ids: [],
+ }),
+ })
+ )
+
+ const lines = await commissionService.listCommissionLines({
+ item_id: order.items![0].id,
+ })
+ expect(lines).toHaveLength(1)
+ expect(lines[0].provider_id).toEqual("system")
+
+ spy.mockRestore()
+ })
+ })
+ },
+})
diff --git a/integration-tests/http/commission-rates/admin/commission-providers.spec.ts b/integration-tests/http/commission-rates/admin/commission-providers.spec.ts
new file mode 100644
index 000000000..a2c6ef657
--- /dev/null
+++ b/integration-tests/http/commission-rates/admin/commission-providers.spec.ts
@@ -0,0 +1,147 @@
+import path from "path"
+import { moduleIntegrationTestRunner } from "@medusajs/test-utils"
+import {
+ CommissionCalculationContext,
+ CreateCommissionLineDTO,
+ ICommissionProvider,
+ MercurModules,
+} from "@mercurjs/types"
+
+jest.setTimeout(60000)
+
+const resolve = path.resolve(
+ __dirname,
+ "../../../../packages/core/.medusa/server/src/modules/commission"
+)
+
+class FixedCommissionProvider implements ICommissionProvider {
+ static identifier = "fixed"
+
+ async getCommissionLines(
+ context: CommissionCalculationContext
+ ): Promise<CreateCommissionLineDTO[]> {
+ return (context.items ?? []).map((item) => ({
+ item_id: item.id,
+ shipping_method_id: null,
+ code: "FIXED",
+ rate: 7,
+ amount: 7,
+ data: { marker: context.additional_context?.marker ?? null },
+ }))
+ }
+}
+
+class OtherCommissionProvider implements ICommissionProvider {
+ static identifier = "other"
+
+ async getCommissionLines(): Promise<CreateCommissionLineDTO[]> {
+ return []
+ }
+}
+
+const context: CommissionCalculationContext = {
+ currency_code: "usd",
+ items: [{ id: "item_1", subtotal: 100 }],
+ shipping_methods: [],
+}
+
+moduleIntegrationTestRunner({
+ moduleName: MercurModules.COMMISSION,
+ dbName: "medusa-commission-providers-default",
+ resolve,
+ moduleOptions: {
+ providers: [
+ {
+ resolve: { services: [FixedCommissionProvider] },
+ id: "fixed",
+ is_default: true,
+ },
+ {
+ resolve: { services: [OtherCommissionProvider] },
+ id: "other",
+ },
+ ],
+ },
+ testSuite: ({ service }) => {
+ describe("Commission providers - is_default provider", () => {
+ it("delegates getCommissionLines to the default provider", async () => {
+ const lines = await service.getCommissionLines(context)
+
+ expect(lines).toEqual([
+ expect.objectContaining({
+ item_id: "item_1",
+ code: "FIXED",
+ amount: 7,
+ provider_id: "fixed",
+ data: { marker: null },
+ }),
+ ])
+ })
+
+ it("persists provider_id and data without a commission rate", async () => {
+ const lines = await service.getCommissionLines(context)
+ const [persisted] = await service.upsertCommissionLines(lines)
+
+ expect(persisted).toEqual(
+ expect.objectContaining({
+ item_id: "item_1",
+ commission_rate_id: null,
+ provider_id: "fixed",
+ data: { marker: null },
+ })
+ )
+ })
+ })
+ },
+})
+
+moduleIntegrationTestRunner({
+ moduleName: MercurModules.COMMISSION,
+ dbName: "medusa-commission-providers-system",
+ resolve,
+ moduleOptions: {
+ providers: [
+ {
+ resolve: { services: [FixedCommissionProvider] },
+ id: "fixed",
+ },
+ {
+ resolve: { services: [OtherCommissionProvider] },
+ id: "other",
+ },
+ ],
+ },
+ testSuite: ({ service }) => {
+ describe("Commission providers - no default flag", () => {
+ it("keeps the system provider as default", async () => {
+ const lines = await service.getCommissionLines(context)
+
+ expect(lines).toEqual([
+ expect.objectContaining({
+ item_id: "item_1",
+ provider_id: "system",
+ }),
+ ])
+ expect(lines[0].commission_rate_id).toBeTruthy()
+ })
+ })
+ },
+})
+
+moduleIntegrationTestRunner({
+ moduleName: MercurModules.COMMISSION,
+ dbName: "medusa-commission-providers-missing",
+ resolve,
+ moduleOptions: {
+ default_provider: "missing",
+ },
+ testSuite: ({ service }) => {
+ describe("Commission providers - unregistered default_provider", () => {
+ it("fails at first calculation", async () => {
+ await expect(service.getCommissionLines(context)).rejects.toThrow(
+ "Unable to retrieve the commission provider with id: missing"
+ )
+ })
+ })
+ },
+})
diff --git a/packages/core/src/modules/commission/index.ts b/packages/core/src/modules/commission/index.ts
index 9bbff3557..5e778417c 100644
--- a/packages/core/src/modules/commission/index.ts
+++ b/packages/core/src/modules/commission/index.ts
@@ -2,9 +2,10 @@ import { Module } from "@medusajs/framework/utils"
import { MercurModules } from "@mercurjs/types"
import CommissionModuleService from "./service"
+import loadProviders from "./loaders/providers"
import seedDefaultCommissionRateLoader from "./loaders/seed-default-commission-rate"
export default Module(MercurModules.COMMISSION, {
service: CommissionModuleService,
- loaders: [seedDefaultCommissionRateLoader],
+ loaders: [loadProviders, seedDefaultCommissionRateLoader],
})
diff --git a/packages/core/src/modules/commission/loaders/providers.ts b/packages/core/src/modules/commission/loaders/providers.ts
new file mode 100644
index 000000000..2463affc7
--- /dev/null
+++ b/packages/core/src/modules/commission/loaders/providers.ts
@@ -0,0 +1,66 @@
+import { asFunction, asValue, Lifetime } from "@medusajs/framework/awilix"
+import { moduleProviderLoader } from "@medusajs/framework/modules-sdk"
+import { LoaderOptions } from "@medusajs/framework/types"
+import { MedusaError } from "@medusajs/framework/utils"
+import { CommissionModuleOptions } from "@mercurjs/types"
+
+import { SystemCommissionProvider } from "../providers"
+import {
+ CommissionDefaultProvider,
+ CommissionProviderRegistrationPrefix,
+} from "../services/provider-service"
+
+const registrationFn = async (klass, container, pluginOptions) => {
+ if (!klass?.identifier) {
+ throw new MedusaError(
+ MedusaError.Types.INVALID_ARGUMENT,
+ "Trying to register a commission provider without a provider identifier."
+ )
+ }
+
+ const key = `${CommissionProviderRegistrationPrefix}${pluginOptions.id ?? klass.identifier}`
+
+ container.register({
+ [key]: asFunction(
+ (cradle) => new klass(cradle, pluginOptions.options ?? {}),
+ {
+ lifetime: klass.LIFE_TIME || Lifetime.SINGLETON,
+ }
+ ),
+ })
+}
+
+export default async ({
+ container,
+ options,
+}: LoaderOptions<CommissionModuleOptions>): Promise<void> => {
+ await registrationFn(SystemCommissionProvider, container, {
+ id: SystemCommissionProvider.identifier,
+ })
+ container.register(
+ CommissionDefaultProvider,
+ asValue(SystemCommissionProvider.identifier)
+ )
+
+ const providers = options?.providers ?? []
+
+ await moduleProviderLoader({
+ container,
+ providers,
+ registerServiceFn: registrationFn,
+ })
+
+ const isSingleProvider = providers.length === 1
+ for (const provider of providers) {
+ if (provider.is_default || isSingleProvider) {
+ container.register(CommissionDefaultProvider, asValue(provider.id))
+ }
+ }
+
+ if (options?.default_provider) {
+ container.register(
+ CommissionDefaultProvider,
+ asValue(options.default_provider)
+ )
+ }
+}
diff --git a/packages/core/src/modules/commission/migrations/.snapshot-medusa-commission.json b/packages/core/src/modules/commission/migrations/.snapshot-medusa-commission.json
index 9519b2bc5..7d4c769e6 100644
--- a/packages/core/src/modules/commission/migrations/.snapshot-medusa-commission.json
+++ b/packages/core/src/modules/commission/migrations/.snapshot-medusa-commission.json
@@ -42,6 +42,16 @@
"nullable": true,
"mappedType": "text"
},
+ "provider_id": {
+ "name": "provider_id",
+ "type": "text",
+ "unsigned": false,
+ "autoincrement": false,
+ "primary": false,
+ "nullable": false,
+ "default": "'system'",
+ "mappedType": "text"
+ },
"code": {
"name": "code",
"type": "text",
@@ -78,6 +88,15 @@
"nullable": true,
"mappedType": "text"
},
+ "data": {
+ "name": "data",
+ "type": "jsonb",
+ "unsigned": false,
+ "autoincrement": false,
+ "primary": false,
+ "nullable": true,
+ "mappedType": "json"
+ },
"raw_amount": {
"name": "raw_amount",
"type": "jsonb",
diff --git a/packages/core/src/modules/commission/migrations/Migration20260910000000.ts b/packages/core/src/modules/commission/migrations/Migration20260910000000.ts
new file mode 100644
index 000000000..c836b2a10
--- /dev/null
+++ b/packages/core/src/modules/commission/migrations/Migration20260910000000.ts
@@ -0,0 +1,15 @@
+import { Migration } from "@medusajs/framework/mikro-orm/migrations";
+
+export class Migration20260910000000 extends Migration {
+
+ override async up(): Promise<void> {
+ this.addSql(`alter table if exists "commission_line" add column if not exists "provider_id" text not null default 'system';`);
+ this.addSql(`alter table if exists "commission_line" add column if not exists "data" jsonb null;`);
+ }
+
+ override async down(): Promise<void> {
+ this.addSql(`alter table if exists "commission_line" drop column if exists "data";`);
+ this.addSql(`alter table if exists "commission_line" drop column if exists "provider_id";`);
+ }
+
+}
diff --git a/packages/core/src/modules/commission/models/commission-line.ts b/packages/core/src/modules/commission/models/commission-line.ts
index ead420506..467518e05 100644
--- a/packages/core/src/modules/commission/models/commission-line.ts
+++ b/packages/core/src/modules/commission/models/commission-line.ts
@@ -5,10 +5,12 @@ const CommissionLine = model.define("commission_line", {
item_id: model.text().nullable(),
shipping_method_id: model.text().nullable(),
commission_rate_id: model.text().nullable(),
+ provider_id: model.text().default("system"),
code: model.text(),
rate: model.float(),
amount: model.bigNumber(),
description: model.text().nullable(),
+ data: model.json().nullable(),
})
export default CommissionLine
diff --git a/packages/core/src/modules/commission/providers/index.ts b/packages/core/src/modules/commission/providers/index.ts
new file mode 100644
index 000000000..490c4c906
--- /dev/null
+++ b/packages/core/src/modules/commission/providers/index.ts
@@ -0,0 +1 @@
+export { SystemCommissionProvider } from "./system"
diff --git a/packages/core/src/modules/commission/providers/system.ts b/packages/core/src/modules/commission/providers/system.ts
new file mode 100644
index 000000000..5324dd3de
--- /dev/null
+++ b/packages/core/src/modules/commission/providers/system.ts
@@ -0,0 +1,239 @@
+import {
+ InferEntityType,
+ ModulesSdkTypes,
+} from "@medusajs/framework/types"
+import { MathBN } from "@medusajs/framework/utils"
+import {
+ CommissionCalculationContext,
+ CommissionCalculationItemLine,
+ CommissionCalculationShippingLine,
+ CommissionRateType,
+ CreateCommissionLineDTO,
+ ICommissionProvider,
+} from "@mercurjs/types"
+
+import { CommissionRate, CommissionRule } from "../models"
+
+type CommissionRateEntity = InferEntityType<typeof CommissionRate>
+type CommissionRuleEntity = InferEntityType<typeof CommissionRule>
+
+type InjectedDependencies = {
+ commissionRateService: ModulesSdkTypes.IMedusaInternalService<CommissionRateEntity>
+}
+
+/**
+ * The built-in provider: resolves commission lines from the module's own
+ * rates and rules. Registered unconditionally and used when no other
+ * provider is configured as default.
+ */
+export class SystemCommissionProvider implements ICommissionProvider {
+ static identifier = "system"
+
+ protected readonly commissionRateService_: InjectedDependencies["commissionRateService"]
+
+ constructor({ commissionRateService }: InjectedDependencies) {
+ this.commissionRateService_ = commissionRateService
+ }
+
+ /**
+ * Does a single rule match a product?
+ */
+ private ruleMatchesProduct(
+ rule: CommissionRuleEntity,
+ product?: CommissionCalculationItemLine["product"]
+ ): boolean {
+ 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
+ }
+ }
+
+ /**
+ * A rate matches an item when **every** present dimension group (rules
+ * grouped by `reference`) has at least one matching rule
+ * (AND-across-dimension, OR-within-dimension). A rule-less rate is the
+ * default and matches everything.
+ */
+ private rateMatchesItem(
+ rate: CommissionRateEntity,
+ item: CommissionCalculationItemLine
+ ): boolean {
+ const rules = (rate.rules ?? []) as CommissionRuleEntity[]
+ if (rules.length === 0) {
+ return true
+ }
+
+ const groups = new Map<string, CommissionRuleEntity[]>()
+ for (const rule of rules) {
+ const bucket = groups.get(rule.reference) ?? []
+ bucket.push(rule)
+ groups.set(rule.reference, bucket)
+ }
+
+ for (const groupRules of groups.values()) {
+ if (!groupRules.some((rule) => this.ruleMatchesProduct(rule, item.product))) {
+ return false
+ }
+ }
+
+ return true
+ }
+
+ /**
+ * Specificity = number of distinct dimension groups a rate scopes on.
+ * More dimensions → higher specificity → wins the tie-break.
+ */
+ private rateSpecificity(rate: CommissionRateEntity): number {
+ return new Set((rate.rules ?? []).map((rule) => rule.reference)).size
+ }
+
+ /**
+ * Resolve the commission amount + line `rate` for a base amount.
+ * Percentage uses the scalar `value`; Fixed reads the per-currency
+ * `values` (falling back to the legacy single `value`).
+ */
+ private computeCommission(
+ rate: CommissionRateEntity,
+ baseAmount: CommissionCalculationItemLine["subtotal"],
+ currencyCode: string
+ ): { rate: number; amount: number } {
+ if (rate.type === CommissionRateType.PERCENTAGE) {
+ const amount = MathBN.div(MathBN.mult(baseAmount, rate.value), 100)
+ return {
+ rate: MathBN.convert(rate.value).toNumber(),
+ amount: MathBN.convert(amount).toNumber(),
+ }
+ }
+
+ const perCurrency = (rate.values ?? []).find(
+ (value) => value.currency_code === currencyCode
+ )
+ const fixed = perCurrency ? perCurrency.amount : rate.value
+
+ return {
+ rate: MathBN.convert(fixed).toNumber(),
+ amount: MathBN.convert(fixed).toNumber(),
+ }
+ }
+
+ async getCommissionLines(
+ context: CommissionCalculationContext
+ ): Promise<CreateCommissionLineDTO[]> {
+ const commissionLines: CreateCommissionLineDTO[] = []
+ const { items = [], shipping_methods = [], currency_code } = context
+
+ // Load all enabled rates with their rules + per-currency values,
+ // oldest first (created_at ASC) so it is the deterministic tie-break.
+ const commissionRates = (await this.commissionRateService_.list(
+ { is_enabled: true },
+ { relations: ["rules", "values"], order: { created_at: "ASC" } }
+ )) as CommissionRateEntity[]
+
+ // Legacy single-currency rates only apply to their currency; rates
+ // without a currency_code apply to any currency.
+ const applicableRates = commissionRates.filter(
+ (rate) => !rate.currency_code || rate.currency_code === currency_code
+ )
+
+ // The Global Commission: the is_default rate (fallback: any rule-less rate).
+ const defaultRate =
+ applicableRates.find((rate) => rate.is_default) ??
+ applicableRates.find((rate) => (rate.rules ?? []).length === 0)
+
+ // Item lines — match per item, most-specific rate wins.
+ for (const item of items) {
+ const candidates = applicableRates.filter((rate) =>
+ this.rateMatchesItem(rate, item)
+ )
+
+ if (!candidates.length) {
+ continue
+ }
+
+ candidates.sort((a, b) => {
+ const specificityDiff = this.rateSpecificity(b) - this.rateSpecificity(a)
+ if (specificityDiff !== 0) {
+ return specificityDiff
+ }
+ return (
+ new Date(a.created_at).getTime() - new Date(b.created_at).getTime()
+ )
+ })
+
+ const matchedRate = candidates[0]
+
+ let baseAmount = item.subtotal
+ if (matchedRate.include_tax && item.tax_total) {
+ baseAmount = MathBN.add(item.subtotal, item.tax_total)
+ }
+
+ const { rate, amount } = this.computeCommission(
+ matchedRate,
+ baseAmount,
+ currency_code
+ )
+
+ commissionLines.push({
+ item_id: item.id,
+ shipping_method_id: null,
+ code: matchedRate.code,
+ rate,
+ amount,
+ commission_rate_id: matchedRate.id,
+ provider_id: SystemCommissionProvider.identifier,
+ })
+ }
+
+ // Shipping lines — one per shipping method, governed by the global
+ // rate, only when its include_shipping is on (resolved independently
+ // of the items the method ships).
+ if (defaultRate?.include_shipping) {
+ for (const shippingMethod of shipping_methods as CommissionCalculationShippingLine[]) {
+ let baseAmount = shippingMethod.subtotal
+ if (defaultRate.include_tax && shippingMethod.tax_total) {
+ baseAmount = MathBN.add(
+ shippingMethod.subtotal,
+ shippingMethod.tax_total
+ )
+ }
+
+ const { rate, amount } = this.computeCommission(
+ defaultRate,
+ baseAmount,
+ currency_code
+ )
+
+ commissionLines.push({
+ item_id: null,
+ shipping_method_id: shippingMethod.id,
+ code: defaultRate.code,
+ rate,
+ amount,
+ commission_rate_id: defaultRate.id,
+ provider_id: SystemCommissionProvider.identifier,
+ description: "Shipping Commission",
+ })
+ }
+ }
+
+ return commissionLines
+ }
+
+}
diff --git a/packages/core/src/modules/commission/service.ts b/packages/core/src/modules/commission/service.ts
index f409106d0..771584e33 100644
--- a/packages/core/src/modules/commission/service.ts
+++ b/packages/core/src/modules/commission/service.ts
@@ -8,7 +8,6 @@ import {
import {
EmitEvents,
InjectManager,
- MathBN,
MedusaContext,
MedusaService,
} from "@medusajs/framework/utils"
@@ -16,10 +15,7 @@ import { raw } from "@medusajs/framework/mikro-orm/postgresql"
import {
CommissionCalculationContext,
- CommissionCalculationItemLine,
- CommissionCalculationShippingLine,
CommissionLineDTO,
- CommissionRateType,
CreateCommissionLineDTO,
} from "@mercurjs/types"
@@ -29,9 +25,18 @@ import {
CommissionRateValue,
CommissionLine,
} from "./models"
+import CommissionProviderService, {
+ CommissionDefaultProvider,
+} from "./services/provider-service"
-type CommissionRateEntity = InferEntityType<typeof CommissionRate>
-type CommissionRuleEntity = InferEntityType<typeof CommissionRule>
+type InjectedDependencies = {
+ commissionLineService: ModulesSdkTypes.IMedusaInternalService<
+ InferEntityType<typeof CommissionLine>
+ >
+ commissionProviderService: CommissionProviderService
+ baseRepository: DAL.RepositoryService
+ [CommissionDefaultProvider]: string
+}
/** Build a unique, URL-safe code from a rate name. */
const generateCommissionCode = (name: string): string => {
@@ -54,213 +59,29 @@ class CommissionModuleService extends MedusaService({
InferEntityType<typeof CommissionLine>
>
protected baseRepository_: DAL.RepositoryService
+ protected commissionProviderService_: CommissionProviderService
+ protected defaultProviderId_: string
- constructor({ commissionLineService, baseRepository }) {
+ constructor(container: InjectedDependencies) {
super(...arguments)
- this.commissionLineService_ = commissionLineService
- this.baseRepository_ = baseRepository
- }
-
- /**
- * Does a single rule match a product?
- */
- private ruleMatchesProduct(
- rule: CommissionRuleEntity,
- product?: CommissionCalculationItemLine["product"]
- ): boolean {
- 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
- }
- }
-
- /**
- * A rate matches an item when **every** present dimension group (rules
- * grouped by `reference`) has at least one matching rule
- * (AND-across-dimension, OR-within-dimension). A rule-less rate is the
- * default and matches everything.
- */
- private rateMatchesItem(
- rate: CommissionRateEntity,
- item: CommissionCalculationItemLine
- ): boolean {
- const rules = (rate.rules ?? []) as CommissionRuleEntity[]
- if (rules.length === 0) {
- return true
- }
-
- const groups = new Map<string, CommissionRuleEntity[]>()
- for (const rule of rules) {
- const bucket = groups.get(rule.reference) ?? []
- bucket.push(rule)
- groups.set(rule.reference, bucket)
- }
-
- for (const groupRules of groups.values()) {
- if (!groupRules.some((rule) => this.ruleMatchesProduct(rule, item.product))) {
- return false
- }
- }
-
- return true
- }
-
- /**
- * Specificity = number of distinct dimension groups a rate scopes on.
- * More dimensions → higher specificity → wins the tie-break.
- */
- private rateSpecificity(rate: CommissionRateEntity): number {
- return new Set((rate.rules ?? []).map((rule) => rule.reference)).size
- }
-
- /**
- * Resolve the commission amount + line `rate` for a base amount.
- * Percentage uses the scalar `value`; Fixed reads the per-currency
- * `values` (falling back to the legacy single `value`).
- */
- private computeCommission(
- rate: CommissionRateEntity,
- baseAmount: CommissionCalculationItemLine["subtotal"],
- currencyCode: string
- ): { rate: number; amount: number } {
- if (rate.type === CommissionRateType.PERCENTAGE) {
- const amount = MathBN.div(MathBN.mult(baseAmount, rate.value), 100)
- return {
- rate: MathBN.convert(rate.value).toNumber(),
- amount: MathBN.convert(amount).toNumber(),
- }
- }
-
- const perCurrency = (rate.values ?? []).find(
- (value) => value.currency_code === currencyCode
- )
- const fixed = perCurrency ? perCurrency.amount : rate.value
-
- return {
- rate: MathBN.convert(fixed).toNumber(),
- amount: MathBN.convert(fixed).toNumber(),
- }
+ this.commissionLineService_ = container.commissionLineService
+ this.baseRepository_ = container.baseRepository
+ this.commissionProviderService_ = container.commissionProviderService
+ this.defaultProviderId_ = container[CommissionDefaultProvider]
}
- @InjectManager()
async getCommissionLines(
- context: CommissionCalculationContext,
- @MedusaContext() sharedContext: Context = {}
+ context: CommissionCalculationContext
): Promise<CreateCommissionLineDTO[]> {
- const commissionLines: CreateCommissionLineDTO[] = []
- const { items = [], shipping_methods = [], currency_code } = context
-
- // Load all enabled rates with their rules + per-currency values,
- // oldest first (created_at ASC) so it is the deterministic tie-break.
- const commissionRates = (await this.listCommissionRates(
- { is_enabled: true },
- { relations: ["rules", "values"], order: { created_at: "ASC" } },
- sharedContext
- )) as CommissionRateEntity[]
-
- // Legacy single-currency rates only apply to their currency; rates
- // without a currency_code apply to any currency.
- const applicableRates = commissionRates.filter(
- (rate) => !rate.currency_code || rate.currency_code === currency_code
+ const provider = this.commissionProviderService_.retrieveProvider(
+ this.defaultProviderId_
)
+ const lines = await provider.getCommissionLines(context)
- // The Global Commission: the is_default rate (fallback: any rule-less rate).
- const defaultRate =
- applicableRates.find((rate) => rate.is_default) ??
- applicableRates.find((rate) => (rate.rules ?? []).length === 0)
-
- // Item lines — match per item, most-specific rate wins.
- for (const item of items) {
- const candidates = applicableRates.filter((rate) =>
- this.rateMatchesItem(rate, item)
- )
-
- if (!candidates.length) {
- continue
- }
-
- candidates.sort((a, b) => {
- const specificityDiff = this.rateSpecificity(b) - this.rateSpecificity(a)
- if (specificityDiff !== 0) {
- return specificityDiff
- }
- return (
- new Date(a.created_at).getTime() - new Date(b.created_at).getTime()
- )
- })
-
- const matchedRate = candidates[0]
-
- let baseAmount = item.subtotal
- if (matchedRate.include_tax && item.tax_total) {
- baseAmount = MathBN.add(item.subtotal, item.tax_total)
- }
-
- const { rate, amount } = this.computeCommission(
- matchedRate,
- baseAmount,
- currency_code
- )
-
- commissionLines.push({
- item_id: item.id,
- shipping_method_id: null,
- code: matchedRate.code,
- rate,
- amount,
- commission_rate_id: matchedRate.id,
- })
- }
-
- // Shipping lines — one per shipping method, governed by the global
- // rate, only when its include_shipping is on (resolved independently
- // of the items the method ships).
- if (defaultRate?.include_shipping) {
- for (const shippingMethod of shipping_methods as CommissionCalculationShippingLine[]) {
- let baseAmount = shippingMethod.subtotal
- if (defaultRate.include_tax && shippingMethod.tax_total) {
- baseAmount = MathBN.add(
- shippingMethod.subtotal,
- shippingMethod.tax_total
- )
- }
-
- const { rate, amount } = this.computeCommission(
- defaultRate,
- baseAmount,
- currency_code
- )
-
- commissionLines.push({
- item_id: null,
- shipping_method_id: shippingMethod.id,
- code: defaultRate.code,
- rate,
- amount,
- commission_rate_id: defaultRate.id,
- description: "Shipping Commission",
- })
- }
- }
-
- return commissionLines
+ return lines.map((line) => ({
+ ...line,
+ provider_id: line.provider_id ?? this.defaultProviderId_,
+ }))
}
/**
diff --git a/packages/core/src/modules/commission/services/index.ts b/packages/core/src/modules/commission/services/index.ts
new file mode 100644
index 000000000..20140f26f
--- /dev/null
+++ b/packages/core/src/modules/commission/services/index.ts
@@ -0,0 +1,2 @@
+export { default as CommissionProviderService } from "./provider-service"
+export * from "./provider-service"
diff --git a/packages/core/src/modules/commission/services/provider-service.ts b/packages/core/src/modules/commission/services/provider-service.ts
new file mode 100644
index 000000000..668ac43c9
--- /dev/null
+++ b/packages/core/src/modules/commission/services/provider-service.ts
@@ -0,0 +1,30 @@
+import { MedusaError } from "@medusajs/framework/utils"
+import { ICommissionProvider } from "@mercurjs/types"
+
+export const CommissionProviderRegistrationPrefix = "cp_"
+export const CommissionDefaultProvider = "commission_default_provider"
+
+type InjectedDependencies = {
+ [key: `${typeof CommissionProviderRegistrationPrefix}${string}`]: ICommissionProvider
+}
+
+export default class CommissionProviderService {
+ protected readonly container_: InjectedDependencies
+
+ constructor(container: InjectedDependencies) {
+ this.container_ = container
+ }
+
+ retrieveProvider(providerId: string): ICommissionProvider {
+ try {
+ return this.container_[
+ `${CommissionProviderRegistrationPrefix}${providerId}`
+ ]
+ } catch {
+ throw new MedusaError(
+ MedusaError.Types.NOT_FOUND,
+ `Unable to retrieve the commission provider with id: ${providerId}. Please make sure that the provider is registered in the container and it is configured correctly in your project configuration file.`
+ )
+ }
+ }
+}
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
index e4d4b2d6d..b0ea76ebf 100644
--- a/packages/core/src/workflows/commission/workflows/refresh-order-commission-lines.ts
+++ b/packages/core/src/workflows/commission/workflows/refresh-order-commission-lines.ts
@@ -1,11 +1,17 @@
import {
WorkflowData,
WorkflowResponse,
+ createHook,
createWorkflow,
transform,
+ type Hook,
+ type ReturnWorkflow,
} from "@medusajs/framework/workflows-sdk"
import { useQueryGraphStep } from "@medusajs/medusa/core-flows"
-import { CommissionLineDTO } from "@mercurjs/types"
+import {
+ CommissionCalculationContext,
+ CommissionLineDTO,
+} from "@mercurjs/types"
import { getCommissionLinesStep, upsertCommissionLinesStep } from "../steps"
@@ -26,11 +32,13 @@ const orderFields = [
"items.*",
"items.subtotal",
"items.tax_total",
+ "items.total",
"items.product.id",
"items.product.collection_id",
"items.product.categories.id",
"items.product.tags.id",
"items.product.type_id",
+ "items.product.attribute_values.id",
"items.offer.seller_id",
"items.adjustments.*",
"shipping_methods.*",
@@ -48,12 +56,28 @@ export type RefreshOrderCommissionLinesWorkflowInput = {
export const refreshOrderCommissionLinesWorkflowId = "refresh-order-commission-lines"
+/**
+ * `setCommissionContext` receives the contexts built from the orders. A
+ * handler returns `new StepResponse(contexts)` with `additional_context`
+ * filled in, or nothing to leave the contexts as they are.
+ */
+export type RefreshOrderCommissionLinesWorkflowHooks = [
+ Hook<
+ "setCommissionContext",
+ { contexts: CommissionCalculationContext[] },
+ CommissionCalculationContext[] | void
+ >,
+]
-export const refreshOrderCommissionLinesWorkflow = createWorkflow(
+export const refreshOrderCommissionLinesWorkflow: ReturnWorkflow<
+ RefreshOrderCommissionLinesWorkflowInput,
+ CommissionLineDTO[],
+ RefreshOrderCommissionLinesWorkflowHooks
+> = createWorkflow(
refreshOrderCommissionLinesWorkflowId,
function (
input: WorkflowData<RefreshOrderCommissionLinesWorkflowInput>
- ): WorkflowResponse<CommissionLineDTO[]> {
+ ) {
const { data: orders } = useQueryGraphStep({
entity: "order",
fields: orderFields,
@@ -64,12 +88,15 @@ export const refreshOrderCommissionLinesWorkflow = createWorkflow(
}).config({ name: "fetch-orders" })
const commissionContexts = transform({ orders }, ({ orders }) => {
- return orders.map((order: any) => ({
+ return orders.map((order: any): CommissionCalculationContext => ({
currency_code: order.currency_code,
+ order_id: order.id,
+ seller_id: order.items?.[0]?.offer?.seller_id,
items: (order.items ?? []).map((item: any) => ({
id: item.id,
subtotal: item.subtotal,
tax_total: item.tax_total,
+ total: item.total,
product: item.product
? {
id: item.product.id,
@@ -80,6 +107,8 @@ export const refreshOrderCommissionLinesWorkflow = createWorkflow(
seller: item.offer?.seller_id
? { id: item.offer.seller_id }
: undefined,
+ attribute_value_ids: (item.product.attribute_values ?? [])
+ .map((value: { id: string }) => value.id),
}
: undefined,
})),
@@ -91,12 +120,25 @@ export const refreshOrderCommissionLinesWorkflow = createWorkflow(
}))
})
- const commissionLines = getCommissionLinesStep(commissionContexts)
+ const setCommissionContext = createHook("setCommissionContext", {
+ contexts: commissionContexts,
+ })
+
+ const contexts = transform(
+ { commissionContexts, hookResult: setCommissionContext.getResult() },
+ ({ commissionContexts, hookResult }): CommissionCalculationContext[] =>
+ (hookResult as CommissionCalculationContext[] | undefined) ??
+ commissionContexts
+ )
+
+ const commissionLines = getCommissionLinesStep(contexts)
const upsertedCommissionLines = upsertCommissionLinesStep({
commission_lines: commissionLines,
})
- return new WorkflowResponse(upsertedCommissionLines)
+ return new WorkflowResponse(upsertedCommissionLines, {
+ hooks: [setCommissionContext],
+ })
}
)
diff --git a/packages/types/src/commission/common.ts b/packages/types/src/commission/common.ts
index 80be6868f..f176b6c7f 100644
--- a/packages/types/src/commission/common.ts
+++ b/packages/types/src/commission/common.ts
@@ -30,10 +30,12 @@ export type CommissionLineDTO = {
item_id: string | null
shipping_method_id: string | null
commission_rate_id: string | null
+ provider_id: string
code: string
rate: number
amount: number
description: string | null
+ data: Record<string, unknown> | null
created_at: Date
updated_at: Date
deleted_at: Date | null
@@ -73,6 +75,11 @@ export interface CommissionCalculationItemLine {
*/
tax_total?: BigNumberInput
+ /**
+ * Line total after discounts — the ceiling a provider must not exceed.
+ */
+ total?: BigNumberInput
+
/**
* The product of the line item.
*/
@@ -83,6 +90,7 @@ export interface CommissionCalculationItemLine {
categories?: { id: string }[]
type_id?: string
seller?: { id: string }
+ attribute_value_ids?: string[]
}
}
@@ -109,6 +117,16 @@ export interface CommissionCalculationContext {
*/
currency_code: string
+ /**
+ * The order the lines are computed for, when known.
+ */
+ order_id?: string
+
+ /**
+ * The seller the order belongs to, when known.
+ */
+ seller_id?: string
+
/**
* The cart's line items.
*/
@@ -118,16 +136,25 @@ export interface CommissionCalculationContext {
* The cart's shipping methods.
*/
shipping_methods?: CommissionCalculationShippingLine[]
+
+ /**
+ * Data for the active provider that the framework fields do not carry,
+ * populated by the `setCommissionContext` hook of
+ * `refreshOrderCommissionLinesWorkflow`.
+ */
+ additional_context?: Record<string, unknown>
}
export interface CreateCommissionLineDTO {
item_id?: string | null
shipping_method_id?: string | null
- commission_rate_id: string
+ commission_rate_id?: string | null
+ provider_id?: string
code: string
rate: number
amount: number
description?: string | null
+ data?: Record<string, unknown> | null
}
export interface UpdateCommissionLineDTO extends Partial<CreateCommissionLineDTO> {
diff --git a/packages/types/src/commission/index.ts b/packages/types/src/commission/index.ts
index 5d3c3b82a..72c7b7bfa 100644
--- a/packages/types/src/commission/index.ts
+++ b/packages/types/src/commission/index.ts
@@ -1,2 +1,3 @@
export * from "./common"
export * from "./mutations"
+export * from "./provider"
diff --git a/packages/types/src/commission/provider.ts b/packages/types/src/commission/provider.ts
new file mode 100644
index 000000000..072a8df97
--- /dev/null
+++ b/packages/types/src/commission/provider.ts
@@ -0,0 +1,52 @@
+import type { ModuleProviderExports } from "@medusajs/types"
+
+import type {
+ CommissionCalculationContext,
+ CreateCommissionLineDTO,
+} from "./common"
+
+export interface ICommissionProvider {
+ /**
+ * Compute the commission lines for an order-shaped context. Returned lines
+ * without a `provider_id` are stamped with the provider's registration id.
+ */
+ getCommissionLines(
+ context: CommissionCalculationContext
+ ): Promise<CreateCommissionLineDTO[]>
+}
+
+export interface CommissionModuleOptions {
+ /**
+ * Providers to be registered next to the built-in `system` provider.
+ */
+ providers?: {
+ /**
+ * The module provider to be registered
+ */
+ resolve: string | ModuleProviderExports
+ /**
+ * The id of the provider
+ */
+ id: string
+ /**
+ * Key value pair of the configuration to be passed to the provider constructor
+ */
+ options?: Record<string, unknown>
+ /**
+ * Use this provider for every calculation. A single configured provider
+ * is the default implicitly.
+ */
+ is_default?: boolean
+ }[]
+
+ /**
+ * Provider id used when a calculation names none. Defaults to the built-in `system`.
+ */
+ default_provider?: string
+}
+
+declare module "@medusajs/types" {
+ interface ModuleOptions {
+ "@mercurjs/core/modules/commission": CommissionModuleOptions
+ }
+}