Open MercatoDocsSearch docsAPI reference

Framework

Pricing and tax overrides

Suppose a local tax service must supply the tax for every line on a quote. Choose the tax calculation hook for that decision, then verify line amounts and the final document total together. Use the pricing resolver when the change concerns the base price instead.

The catalog and sales modules expose overridable services so you can plug in regional tax engines, bespoke price selection, or special document totals without forking core code.

Pipelines you can extend

Favor events or resolver hooks when you only need to alter inputs or selection. Swap the DI service when the whole pipeline must be replaced (e.g., delegating to an external engine).

Hooking into tax calculation events

export const metadata = { event: 'bootstrap', persistent: false }

export default async function register(_, ctx) {
  const eventBus = ctx.resolve('eventBus')

  // Route Brazilian orgs to a default class before the built-in math runs
  eventBus?.on('sales.tax.calculate.before', ({ input, setInput }) => {
    if (input.organizationId === 'org-brazil' && !input.taxRateId) {
      setInput({ taxRateId: 'default-brazil' })
    }
  })

  // Snap to whole cents after the default calculation
  eventBus?.on('sales.tax.calculate.after', ({ result, setResult }) => {
    if (!result) return
    const taxAmount = Math.ceil(result.taxAmount * 100) / 100
    setResult({ ...result, taxAmount })
  })
}

Adding a custom catalog pricing resolver

import { registerCatalogPricingResolver } from '@open-mercato/core/src/modules/catalog/lib/pricing'
import type { AppContainer } from '@open-mercato/shared/lib/di/container'

export function register(_: AppContainer) {
  registerCatalogPricingResolver((rows, ctx) => {
    // Prefer a member-only price when a loyalty id is present
    if (!ctx.customerGroupId) return undefined
    const memberPrice = rows.find(
      (row) => row.priceKind?.code === 'member' && row.customerGroupId === ctx.customerGroupId
    )
    if (memberPrice) return memberPrice
    return undefined // fall back to next resolver or selectBestPrice
  }, { priority: 10 })
}

Adjusting order/quote totals

import {
  registerSalesTotalsCalculator,
  type SalesTotalsCalculationHook,
} from '@open-mercato/core/src/modules/sales/lib/calculations'
import type { AppContainer } from '@open-mercato/shared/lib/di/container'

const addEnvironmentalFee: SalesTotalsCalculationHook = async ({ current, context }) => {
  if (context.countryCode !== 'SE') return current
  const fee = 2.5
  return {
    ...current,
    totals: {
      ...current.totals,
      surchargeTotalAmount: current.totals.surchargeTotalAmount + fee,
      grandTotalNetAmount: current.totals.grandTotalNetAmount + fee,
      grandTotalGrossAmount: current.totals.grandTotalGrossAmount + fee,
    },
  }
}

export function register(_: AppContainer) {
  registerSalesTotalsCalculator(addEnvironmentalFee, { prepend: true })
}

Override via events (no code changes to core)

When you only need to patch a few fields, listen to the calculation events and call setResult to override values per line or for the full document:

export const metadata = { event: 'bootstrap' }

export default async function register(_, ctx) {
  const eventBus = ctx.resolve('eventBus')

  // Apply a free-gift line: zero out price on a specific SKU
  eventBus?.on('sales.line.calculate.after', ({ line, result, setResult }) => {
    if (line.productId === 'gift-product-id') {
      setResult({
        ...result,
        netAmount: 0,
        grossAmount: 0,
        taxAmount: 0,
        discountAmount: result.netAmount, // capture the waived value
      })
    }
  })

  // Enforce a minimum order total at the document level
  eventBus?.on('sales.document.calculate.after', ({ result, setResult }) => {
    const minTotal = 25
    if (result.totals.grandTotalGrossAmount < minTotal) {
      const bump = minTotal - result.totals.grandTotalGrossAmount
      setResult({
        ...result,
        totals: {
          ...result.totals,
          surchargeTotalAmount: (result.totals.surchargeTotalAmount ?? 0) + bump,
          grandTotalGrossAmount: minTotal,
          grandTotalNetAmount: result.totals.grandTotalNetAmount + bump,
        },
      })
    }
  })
}

Swapping DI services entirely

When an external engine must own the calculation, replace the DI token in your module di.ts.

import { asFunction } from 'awilix'
import type { AppContainer } from '@open-mercato/shared/lib/di/container'
import type { TaxCalculationService, CalculateTaxInput, TaxCalculationResult } from '@open-mercato/core/src/modules/sales/services/taxCalculationService'

class ExternalTaxService implements TaxCalculationService {
  constructor(private readonly eventBus) {}

  async fetchExternalQuote(
    input: CalculateTaxInput
  ): Promise<{ net: number; gross: number; tax: number; rate: number | null }> {
    // Call your provider here (Avalara, TaxJar, etc.) and map the response
    return { net: input.amount, gross: input.amount, tax: 0, rate: null }
  }

  async calculateUnitAmounts(input: CalculateTaxInput): Promise<TaxCalculationResult> {
    const external = await this.fetchExternalQuote(input)
    const result: TaxCalculationResult = {
      netAmount: external.net,
      grossAmount: external.gross,
      taxAmount: external.tax,
      taxRate: external.rate,
    }

    await this.eventBus?.emitEvent('sales.tax.calculate.after', {
      input,
      result,
      setResult(next) {
        if (next) Object.assign(result, next)
      },
    })
    return result
  }
}

export function register(container: AppContainer) {
  container.register({
    taxCalculationService: asFunction(
      ({ eventBus }) => new ExternalTaxService(eventBus)
    ).scoped(),
  })
}

Debugging and validation tips

Previous: System status variables · Next: Progress Tracking