Workflows
calculateCommissionWorkflow
This documentation provides a reference to the calculateCommissionWorkflow. It belongs to the @mercurjs/commission package.
This workflow calculates and creates commission lines for an order. It determines the applicable commission rule for each line item based on seller, product category, and product type, then calculates the commission amount according to the rule’s rate configuration (percentage or flat).
Source code
Examples
packages/modules/commission/src/subscribers/commission-order-set-placed.ts
import { SubscriberArgs , SubscriberConfig } from "@medusajs/framework" ;
import { ContainerRegistrationKeys } from "@medusajs/framework/utils" ;
import { OrderSetWorkflowEvents , SELLER_ORDER_LINK } from "@mercurjs/framework" ;
import { calculateCommissionWorkflow } from "../workflows/commission/workflows" ;
export default async function commissionOrderSetPlacedHandler ({
event ,
container ,
} : SubscriberArgs <{ id : string }>) {
const query = container . resolve ( ContainerRegistrationKeys . QUERY );
const {
data : [ set ],
} = await query . graph ({
entity: "order_set" ,
fields: [ "orders.id" ],
filters: {
id: event . data . id ,
},
});
const ordersCreated = set . orders . map (( o ) => o . id );
for ( const order_id of ordersCreated ) {
const {
data : [ seller ],
} = await query . graph ({
entity: SELLER_ORDER_LINK ,
fields: [ "seller_id" ],
filters: {
order_id: order_id ,
},
});
if ( ! seller ) {
return ;
}
await calculateCommissionWorkflow . run ({
input: {
order_id: order_id ,
seller_id: seller . seller_id ,
},
container ,
});
}
}
export const config : SubscriberConfig = {
event: OrderSetWorkflowEvents . PLACED ,
context: {
subscriberId: "commission-order-set-placed-handler" ,
},
};
Steps
The commission calculation details. The ID of the order to calculate commission for.
The ID of the seller whose commission to calculate.
Output
Array of created commission lines. The ID of the commission line.
The ID of the order line item.
The ID of the applied commission rule.
The calculated commission amount.
The date the commission line was created.
The date the commission line was last updated.
createCommissionRuleWorkflow
This documentation provides a reference to the createCommissionRuleWorkflow. It belongs to the @mercurjs/commission package.
This workflow creates a commission rule with its associated rate. It validates that no duplicate rule exists for the same reference and reference_id combination, creates price sets for flat rates or min/max limits, and exposes a hook for custom extensions.
Source code
Examples
packages/modules/commission/src/api/admin/commission/rules/route.ts
import { MedusaRequest , MedusaResponse } from '@medusajs/framework'
import { ContainerRegistrationKeys } from '@medusajs/framework/utils'
import {
createCommissionRuleWorkflow ,
} from '../../../../workflows/commission/workflows'
import {
AdminCreateCommissionRuleType ,
validateCommissionRate ,
validateCommissionRule
} from '../validators'
export async function POST (
req : MedusaRequest < AdminCreateCommissionRuleType >,
res : MedusaResponse
) : Promise < void > {
validateCommissionRate ( req . validatedBody . rate )
validateCommissionRule ( req . validatedBody )
const query = req . scope . resolve ( ContainerRegistrationKeys . QUERY )
const { result } = await createCommissionRuleWorkflow . run ({
input: req . validatedBody ,
container: req . scope ,
throwOnError: true
})
const {
data : [ commission_rule ]
} = await query . graph ({
entity: 'commission_rule' ,
fields: req . queryConfig . fields ,
filters: {
id: result . id
}
})
res . status ( 201 ). json ({
commission_rule
})
}
Steps
Hooks
commissionRuleCreated : Hook that fires after a commission rule is created, providing the commission_rule_id.
input
CreateCommissionRuleDTO
required
The commission rule creation details. The name of the commission rule.
The reference type. Available types:
site - Default commission for all products
product_type - Applied to products of specified type
product_category - Applied to products from specified category
seller - Applied to products sold by specified seller
seller+product_category - Applied to products from specified category and seller
seller+product_type - Applied to products of specified type and seller
The ID(s) of the reference entity. For combined types, use format “seller_id+entity_id”.
Whether the rule is active.
rate
CreateCommissionRateDTO
required
The commission rate configuration. The type of commission: “percentage” or “flat”.
Whether to include tax in the commission calculation.
The percentage rate (required if type is “percentage”).
Price set for flat commission (required if type is “flat”). Minimum commission price set.
Maximum commission price set.
Output
The created commission rule. The ID of the commission rule.
The associated commission rate.
The date the rule was created.
The date the rule was last updated.
deleteCommissionRuleWorkflow
This documentation provides a reference to the deleteCommissionRuleWorkflow. It belongs to the @mercurjs/commission package.
This workflow soft deletes a commission rule. It exposes a hook for custom extensions after the rule is deleted.
Source code
Examples
packages/modules/commission/src/api/admin/commission/rules/[id]/route.ts
import { MedusaRequest , MedusaResponse } from '@medusajs/framework'
import {
deleteCommissionRuleWorkflow ,
} from '../../../../../workflows/commission/workflows'
export async function DELETE (
req : MedusaRequest ,
res : MedusaResponse
) : Promise < void > {
const { result } = await deleteCommissionRuleWorkflow . run ({
input: req . params . id ,
container: req . scope
})
res . json ({
id: result ,
object: 'commission_rule' ,
deleted: true
})
}
Steps
Hooks
commissionRuleDeleted : Hook that fires after a commission rule is deleted, providing the commission_rule_id.
The ID of the commission rule to delete.
Output
The ID of the deleted commission rule.
listCommissionLinesWorkflow
This documentation provides a reference to the listCommissionLinesWorkflow. It belongs to the @mercurjs/commission package.
This workflow retrieves commission lines with optional filtering by date range and seller, and optional expansion to include related order and rule details.
Source code
Examples
packages/modules/commission/src/api/admin/commission/commission-lines/route.ts
import { MedusaRequest , MedusaResponse } from '@medusajs/framework'
import { listCommissionLinesWorkflow } from '../../../../workflows/commission/workflows'
import { AdminGetCommissionLinesParamsType } from '../validators'
export async function GET (
req : MedusaRequest < AdminGetCommissionLinesParamsType >,
res : MedusaResponse
) : Promise < void > {
const {
result : { lines : commission_lines , count }
} = await listCommissionLinesWorkflow ( req . scope ). run ({
input: {
expand: true ,
pagination: {
skip: req . queryConfig . pagination . skip ,
take: req . queryConfig . pagination . take || 20
},
filters: req . filterableFields
}
})
res . json ({
commission_lines ,
count ,
offset: req . queryConfig . pagination . skip ,
limit: req . queryConfig . pagination . take
})
}
Steps
The commission lines query parameters. Whether to expand commission lines with related order and rule details.
Pagination configuration. The number of items to skip.
The number of items to return.
Filters to apply. Filter commission lines created after this date.
Filter commission lines created before this date.
Filter commission lines by seller ID.
Output
Array of commission lines (expanded with order and rule details if expand is true).
The total count of commission lines.
listCommissionRulesWorkflow
This documentation provides a reference to the listCommissionRulesWorkflow. It belongs to the @mercurjs/commission package.
This workflow retrieves commission rules with expanded reference values and formatted rate information. It transforms rules to include human-readable reference values (e.g., seller names, category names) and formatted fee values.
Source code
Examples
API Route
Get Single Rule
packages/modules/commission/src/api/admin/commission/rules/route.ts
import { MedusaRequest , MedusaResponse } from '@medusajs/framework'
import {
listCommissionRulesWorkflow
} from '../../../../workflows/commission/workflows'
export async function GET (
req : MedusaRequest ,
res : MedusaResponse
) : Promise < void > {
const { result } = await listCommissionRulesWorkflow . run ({
container: req . scope ,
input: { pagination: req . queryConfig . pagination }
})
res . json ({
commission_rules: result . commission_rules ,
count: result . count ,
offset: req . queryConfig . pagination . skip ,
limit: req . queryConfig . pagination . take
})
}
packages/modules/commission/src/api/admin/commission/rules/[id]/route.ts
import { MedusaRequest , MedusaResponse } from '@medusajs/framework'
import { listCommissionRulesWorkflow } from '../../../../../workflows/commission/workflows'
export async function GET (
req : MedusaRequest ,
res : MedusaResponse
) : Promise < void > {
const {
result : {
commission_rules : [ commission_rule ]
}
} = await listCommissionRulesWorkflow . run ({
container: req . scope ,
input: {
ids: [ req . params . id ]
}
})
res . json ({
commission_rule
})
}
Steps
The commission rules query parameters. Pagination configuration. The number of items to skip.
The number of items to return.
Filter by specific rule IDs. If provided, only these rules are returned.
Output
commission_rules
AdminCommissionAggregate[]
Array of commission rules with expanded reference values and formatted rates. Human-readable reference value (e.g., seller name, category name).
Whether the rule is active.
The rate type (percentage or flat).
Whether tax is included in calculation.
The percentage rate (if applicable).
Formatted fee value (e.g., “15%” or “10USD/20EUR”).
Flat rate prices (if applicable).
Minimum commission prices.
Maximum commission prices.
The total count of commission rules.
listOrderCommissionLinesWorkflow
This documentation provides a reference to the listOrderCommissionLinesWorkflow. It belongs to the @mercurjs/commission package.
This workflow retrieves all commission lines for a specific order and calculates the total commission amount.
Source code
Examples
packages/modules/commission/src/api/vendor/orders/[id]/commission/route.ts
import { AuthenticatedMedusaRequest } from "@medusajs/framework" ;
import { MedusaResponse } from "@medusajs/framework" ;
import { listOrderCommissionLinesWorkflow } from "../../../../../workflows" ;
export const GET = async (
req : AuthenticatedMedusaRequest ,
res : MedusaResponse
) => {
const { id } = req . params ;
const { result : commission } = await listOrderCommissionLinesWorkflow (
req . scope
). run ({
input: {
order_id: id ,
},
});
res . json ({ commission });
};
Steps
The ID of the order to retrieve commission lines for.
Output
The total commission for the order. The total commission amount.
Array of commission lines for the order.
updateCommissionRuleWorkflow
This documentation provides a reference to the updateCommissionRuleWorkflow. It belongs to the @mercurjs/commission package.
This workflow updates an existing commission rule.
Source code
Examples
packages/modules/commission/src/api/admin/commission/rules/[id]/route.ts
import { MedusaRequest , MedusaResponse } from '@medusajs/framework'
import { ContainerRegistrationKeys } from '@medusajs/framework/utils'
import {
updateCommissionRuleWorkflow
} from '../../../../../workflows/commission/workflows'
import { AdminUpdateCommissionRuleType } from '../../validators'
export async function POST (
req : MedusaRequest < AdminUpdateCommissionRuleType >,
res : MedusaResponse
) : Promise < void > {
const query = req . scope . resolve ( ContainerRegistrationKeys . QUERY )
await updateCommissionRuleWorkflow . run ({
input: { ... req . validatedBody , id: req . params . id },
container: req . scope
})
const {
data : [ commission_rule ]
} = await query . graph ({
entity: 'commission_rule' ,
fields: req . queryConfig . fields ,
filters: {
id: req . params . id
}
})
res . status ( 200 ). json ({
commission_rule
})
}
Steps
input
UpdateCommissionRuleDTO
required
The commission rule update details. The ID of the commission rule to update.
Whether the rule should be active.
Updates to the commission rate.
Output
The updated commission rule.
upsertDefaultCommissionRuleWorkflow
This documentation provides a reference to the upsertDefaultCommissionRuleWorkflow. It belongs to the @mercurjs/commission package.
This workflow creates or updates the default site-wide commission rule. If a default rule already exists, it deletes the old one before creating the new one.
Source code
Examples
packages/modules/commission/src/api/admin/commission/default/route.ts
import { MedusaRequest , MedusaResponse } from '@medusajs/framework'
import { ContainerRegistrationKeys } from '@medusajs/framework/utils'
import {
listCommissionRulesWorkflow ,
upsertDefaultCommissionRuleWorkflow
} from '../../../../workflows/commission/workflows'
import {
AdminUpsertDefaultCommissionRuleType ,
validateCommissionRate
} from '../validators'
export async function POST (
req : MedusaRequest < AdminUpsertDefaultCommissionRuleType >,
res : MedusaResponse
) : Promise < void > {
validateCommissionRate ( req . validatedBody . rate )
const query = req . scope . resolve ( ContainerRegistrationKeys . QUERY )
await upsertDefaultCommissionRuleWorkflow . run ({
container: req . scope ,
input: req . validatedBody
})
const {
data : [ default_rule ]
} = await query . graph ({
entity: 'commission_rule' ,
fields: [ 'id' ],
filters: {
reference: 'site'
}
})
const {
result : {
commission_rules : [ commission_rule ]
}
} = await listCommissionRulesWorkflow . run ({
container: req . scope ,
input: {
ids: [ default_rule . id ]
}
})
res . json ({
commission_rule
})
}
Steps
input
CreateCommissionRuleDTO
required
The default commission rule details (reference will be set to “site”).
Output
The created default commission rule.
Steps
calculateCommissionLinesStep
Calculates commission amounts for each line item in an order. For each item, it:
Fetches the product’s category
Selects the applicable commission rule based on priority (seller+type > seller+category > seller > type > category > site)
Calculates the commission value based on the rule’s rate type (percentage or flat)
Applies min/max limits if configured
Source code
Output
CreateCommissionLineDTO[]
CreateCommissionLineDTO[]
Array of commission line data to be created.
checkForDuplicateStep
Validates that no commission rule already exists for the given reference and reference_id combination. Throws an error if a duplicate is found.
Source code
input
CreateCommissionRuleDTO
required
The commission rule to validate.
Output
Returns true if no duplicate exists.
createCommissionLinesStep
Creates commission line records in the database.
Source code
input
CreateCommissionLineDTO[]
required
Array of commission lines to create.
Output
The created commission lines.
createCommissionRuleStep
Creates a commission rule with its rate and associated price sets. If an error occurs after creation, the step’s compensation function automatically deletes the created rule.
For flat rates, it creates price sets for the base commission and optional min/max limits. For percentage rates, it creates price sets only for min/max limits if provided.
Source code
input
CreateCommissionRuleDTO
required
The commission rule creation details.
Output
The created commission rule.
deleteCommissionRuleStep
Soft deletes a commission rule. The step includes a compensation function that restores the rule if a subsequent step fails.
Source code
The ID of the commission rule to delete.
Output
The ID of the deleted commission rule.
findCommissionReferencesStep
Fetches the names of referenced entities (sellers, product types, product categories) for display purposes. It extracts IDs from the rules (including combined references) and queries the database for the corresponding entity names.
Source code
Array of commission rules to find references for.
Output
sellers
Array<{id: string, value: string}>
Array of seller IDs and names.
productTypes
Array<{id: string, value: string}>
Array of product type IDs and values.
productCategories
Array<{id: string, value: string}>
Array of product category IDs and names.
findCommissionRulesStep
Retrieves commission rules with their rates and price set details. It excludes the site-wide default rule unless specific IDs are provided. Returns rules formatted with aggregated price set information.
Source code
Pagination configuration.
Specific rule IDs to retrieve.
Output
Array of commission rules with expanded rate and price set details.
The total count of rules.
listCommissionLinesStep
Retrieves commission lines with optional filtering and expansion. When expand is true, it includes related order and rule details. Supports filtering by date range and seller.
Source code
The commission lines query parameters.
Output
Array of commission lines (expanded if requested).
The total count of commission lines.
listOrderCommissionLinesStep
Retrieves all commission lines for a specific order and calculates the total commission amount by summing all line values.
Source code
Output
Array of commission lines.
updateCommissionRuleStep
Updates a commission rule. This step includes a compensation function that restores the previous rule state if a subsequent step in the workflow fails.
Source code
input
UpdateCommissionRuleDTO
required
The commission rule update details.
Output
The updated commission rule.