Skip to main content

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

Input

input
object
required
The commission calculation details.

Output

CommissionLineDTO[]
CommissionLineDTO[]
Array of created commission lines.

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

input
CreateCommissionRuleDTO
required
The commission rule creation details.

Output

CommissionRuleDTO
CommissionRuleDTO
The created commission rule.

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.

Input

id
string
required
The ID of the commission rule to delete.

Output

string
string
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

Input

input
object
required
The commission lines query parameters.

Output

object
object

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

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
  })
}

Steps

Input

input
object
required
The commission rules query parameters.

Output

object
object

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

Input

input
object
required

Output

object
object

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

input
UpdateCommissionRuleDTO
required
The commission rule update details.

Output

CommissionRuleDTO
CommissionRuleDTO
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

input
CreateCommissionRuleDTO
required
The default commission rule details (reference will be set to “site”).

Output

CommissionRuleDTO
CommissionRuleDTO
The created default commission rule.

Steps

calculateCommissionLinesStep

Calculates commission amounts for each line item in an order. For each item, it:
  1. Fetches the product’s category
  2. Selects the applicable commission rule based on priority (seller+type > seller+category > seller > type > category > site)
  3. Calculates the commission value based on the rule’s rate type (percentage or flat)
  4. Applies min/max limits if configured
Source code

Input

input
object
required

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

input
CreateCommissionRuleDTO
required
The commission rule to validate.

Output

boolean
boolean
Returns true if no duplicate exists.

createCommissionLinesStep

Creates commission line records in the database. Source code

Input

input
CreateCommissionLineDTO[]
required
Array of commission lines to create.

Output

CommissionLineDTO[]
CommissionLineDTO[]
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

input
CreateCommissionRuleDTO
required
The commission rule creation details.

Output

CommissionRuleDTO
CommissionRuleDTO
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

Input

id
string
required
The ID of the commission rule to delete.

Output

string
string
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

Input

input
object[]
required
Array of commission rules to find references for.

Output

object
object

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

Input

input
object
required

Output

object
object

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

Input

input
object
required
The commission lines query parameters.

Output

object
object

listOrderCommissionLinesStep

Retrieves all commission lines for a specific order and calculates the total commission amount by summing all line values. Source code

Input

input
object
required

Output

object
object

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

input
UpdateCommissionRuleDTO
required
The commission rule update details.

Output

CommissionRuleDTO
CommissionRuleDTO
The updated commission rule.