Skip to main content

Workflows

cancelOrderWorkflow

This documentation provides a reference to the cancelOrderWorkflow. It belongs to the @mercurjs/b2c-core package. This workflow cancels an order and handles all associated cleanup including inventory reservation deletion, payment refunds, and payout reversals. It validates that all fulfillments are canceled before proceeding and ensures data consistency across the marketplace. Source code

Examples

packages/modules/b2c-core/src/api/vendor/orders/[id]/cancel/route.ts
import { AuthenticatedMedusaRequest, MedusaResponse } from '@medusajs/framework'
import { getVendorOrdersListWorkflow } from '../../../../../workflows/order/workflows'
import { cancelOrderWorkflow } from '../../../../../workflows/order/workflows/cancel-order'

export const POST = async (
  req: AuthenticatedMedusaRequest,
  res: MedusaResponse
) => {
  const { id } = req.params

  await cancelOrderWorkflow(req.scope).run({
    input: {
      order_id: id,
      canceled_by: req.auth_context.actor_id
    }
  })

  const {
    result: [order]
  } = await getVendorOrdersListWorkflow(req.scope).run({
    input: {
      fields: req.queryConfig.fields,
      variables: {
        filters: {
          id
        }
      }
    }
  })

  res.json({ order })
}

Steps

  • useQueryGraphStep: Fetches the order with fulfillments, payment, and payout details.
  • cancelValidateOrder: Validates that the order can be canceled (not already canceled, all fulfillments canceled).
  • deleteReservationsByLineItemsStep: Removes inventory reservations for the order items.
  • cancelOrdersStep: Marks the order as canceled.
  • refundSplitOrderPaymentWorkflow: Refunds the payment to the customer.
  • createPayoutReversalStep: Creates a reversal for any payout that was already processed.
  • emitEventStep: Emits the order.canceled event.

Input

input
object
required
The order cancellation details.

Output

string
string
The ID of the canceled order.

getVendorOrdersListWorkflow

This documentation provides a reference to the getVendorOrdersListWorkflow. It belongs to the @mercurjs/b2c-core package. This workflow retrieves a list of orders with aggregated payment and fulfillment status. It enhances the standard order data by computing the fulfillment status based on the order’s fulfillments and their states. Source code

Examples

packages/modules/b2c-core/src/api/vendor/orders/route.ts
import { AuthenticatedMedusaRequest, MedusaResponse } from '@medusajs/framework'
import { ContainerRegistrationKeys } from '@medusajs/framework/utils'
import sellerOrderLink from '../../../links/seller-order'
import { fetchSellerByAuthActorId } from '../../../shared/infra/http/utils'
import { getVendorOrdersListWorkflow } from '../../../workflows/order/workflows'
import { VendorGetOrderParamsType } from './validators'

export const GET = async (
  req: AuthenticatedMedusaRequest<VendorGetOrderParamsType>,
  res: MedusaResponse
) => {
  const query = req.scope.resolve(ContainerRegistrationKeys.QUERY)

  const seller = await fetchSellerByAuthActorId(
    req.auth_context.actor_id,
    req.scope
  )

  const { data: orderRelations } = await query.graph({
    entity: sellerOrderLink.entryPoint,
    fields: ['order_id'],
    filters: {
      seller_id: seller.id,
      deleted_at: {
        $eq: null
      }
    }
  })

  const { result } = await getVendorOrdersListWorkflow(req.scope).run({
    input: {
      fields: req.queryConfig.fields,
      variables: {
        filters: {
          ...req.filterableFields,
          id: orderRelations.map((relation) => relation.order_id)
        },
        ...req.queryConfig.pagination
      }
    }
  })

  const { rows, metadata } = result as any

  res.json({
    orders: rows,
    count: metadata?.count,
    offset: metadata?.skip,
    limit: metadata?.take
  })
}

Steps

  • useRemoteQueryStep: Fetches the orders with specified fields including items, fulfillments, and split payment data.

Input

input
object
required
The order list query parameters.

Output

OrderDTO[]
OrderDTO[]
Array of orders with aggregated statuses.

processPayoutForOrderWorkflow

This documentation provides a reference to the processPayoutForOrderWorkflow. It belongs to the @mercurjs/b2c-core package. This workflow processes a payout for a completed order by calculating the amount after commissions, creating the payout via the payment provider, and linking it to the order. It handles both success and failure scenarios, emitting appropriate events. Source code

Examples

packages/modules/b2c-core/src/subscribers/payout-order.ts
import { SubscriberArgs, SubscriberConfig } from '@medusajs/framework'
import { PayoutWorkflowEvents } from '@mercurjs/framework'
import { processPayoutForOrderWorkflow } from '../workflows/order/workflows'

export default async function payoutOrderHandler({
  event,
  container
}: SubscriberArgs<{ order_id: string }>) {
  await processPayoutForOrderWorkflow(container).run({
    input: {
      order_id: event.data.order_id
    },
    context: {
      transactionId: event.data.order_id
    }
  })
}

export const config: SubscriberConfig = {
  event: PayoutWorkflowEvents.RECEIVED,
  context: {
    subscriberId: 'payout-order-handler'
  }
}

Steps

  • validateNoExistingPayoutForOrderStep: Ensures no payout has already been created for this order.
  • useQueryGraphStep: Fetches the order with seller, payment, and commission details.
  • validateSellerPayoutAccountStep: Validates that the seller has an active payout account.
  • calculatePayoutForOrderStep: Calculates the payout amount after deducting commissions and refunds.
  • createPayoutStep: Creates the payout via the payment provider.
  • createRemoteLinkStep: Links the payout to the order (on success).
  • emitEventStep: Emits either payout.succeeded or payout.failed event based on the outcome.

Input

input
object
required
The payout processing details.

Output

This workflow does not return a value.

Steps

calculatePayoutForOrderStep

Calculates the payout amount for an order by subtracting total commissions and refunds from the captured payment amount. Source code

Input

input
object
required

Output

BigNumber
BigNumber
The calculated payout amount (captured_amount - refunded_amount - total_commission).

calculateTotalCommissionStep

Calculates the total commission amount for an order by summing all commission lines associated with the order’s line items. Source code

Input

input
object
required

Output

object
object

cancelValidateOrder

Validates that an order can be canceled. It checks that the order is not already canceled and that all fulfillments have been canceled first. Source code

Input

input
object
required

Output

void
void
Throws an error if validation fails.

createPayoutStep

Creates a payout via the payment provider. This step handles errors gracefully and returns both the payout result and error status. Source code

Input

input
CreatePayoutDTO
required
The payout creation details.

Output

object
object

validateNoExistingPayoutForOrderStep

Validates that no payout has already been created for the given order. Throws an error if a payout already exists. Source code

Input

id
string
required
The order ID to check for existing payouts.

Output

void
void
Throws a DUPLICATE_ERROR if a payout already exists for the order.

validateSellerPayoutAccountStep

Validates that a seller has a payout account and that the account is active. Throws an error if the seller has no payout account or if the account is not active. Source code

Input

seller
SellerWithPayoutAccountDTO
required
The seller to validate, including payout account details.

Output

void
void
Throws an INVALID_DATA error if validation fails.