Skip to content

armgit / spree

Public Imported from GitHub
0

Open Source Platform for DTC, B2B Commerce, Marketplaces & Omnichannel. REST APIs, TypeScript SDKs, and production-ready Next.js storefront. Self-host it. Own your data. No vendor lock-in. Zero platform fees.

6.6 KB
Raw Blame
import type {
  CommissionRate,
  CommissionRateCreateParams,
  CommissionRateUpdateParams,
} from '@spree/admin-sdk'
import { COMMISSION_KINDS, compareMoney, isDecimalString } from '@spree/core'
import { blankToNull, fractionToPercent, i18n, percentToFraction } from '@spree/dashboard-core'
import { requiredMessage } from '@spree/dashboard-ui'
import { z } from 'zod/v4'

const commissionRateFieldsSchema = z.object({
  name: z.string().min(1, { error: requiredMessage('name') }),
  code: z.string().optional(),
  enabled: z.boolean(),
  kind: z.enum(COMMISSION_KINDS),
  // A canonical decimal string from a number input, sent as typed.
  value: z
    .string()
    .trim()
    .refine((value) => isDecimalString(value) && !value.startsWith('-')),
  // What a flat fee charges, keyed by currency. Held as strings because they
  // come from number inputs and an empty one means "not charged here".
  amounts: z.record(z.string(), z.string()).default({}),
  // The floor and cap a percentage charges within, keyed by currency. Each
  // holds only in its own currency, so a rate may bound some and leave the
  // rest unbounded rather than have a figure converted on its behalf.
  bounds: z
    .record(z.string(), z.object({ min_amount: z.string(), max_amount: z.string() }))
    .default({}),
  tax_inclusive: z.boolean(),
  include_shipping: z.boolean(),
  // Held as a percentage in the form because that is how merchants think about
  // VAT; converted to the fraction the API stores on the way out.
  commission_tax_rate: z.string().optional(),
  // Shallow on purpose: react-hook-form's `Path<T>` walks every nested key, so
  // an SDK entity here would drag its whole object graph into the form type.
  // Pickers resolve their own labels, so ids are all the form carries.
  rules: z.array(
    z.object({
      id: z.string().optional(),
      type: z.string(),
      preferences: z.record(z.string(), z.unknown()).default({}),
      // Reference lists ride beside preferences, not inside them — the API
      // exposes prefixed ids at the top level while preferences hold raw ids.
      product_ids: z.array(z.string()).default([]),
      seller_ids: z.array(z.string()).default([]),
      category_ids: z.array(z.string()).default([]),
    }),
  ),
})

export const commissionRateFormSchema = commissionRateFieldsSchema.superRefine((values, ctx) => {
  if (
    values.kind === 'percentage' &&
    isDecimalString(values.value) &&
    compareMoney(values.value, '100') > 0
  ) {
    ctx.addIssue({
      code: 'custom',
      path: ['value'],
      message: i18n.t('admin.commission_rates.validation.percentage_exceeds_one_hundred'),
    })
  }
})

export type CommissionRateFormValues = z.infer<typeof commissionRateFormSchema>

export const COMMISSION_RATE_DEFAULTS: CommissionRateFormValues = {
  name: '',
  code: '',
  enabled: true,
  kind: 'percentage',
  value: '10',
  amounts: {},
  bounds: {},
  tax_inclusive: false,
  include_shipping: false,
  commission_tax_rate: '',
  rules: [],
}

export function commissionRateToFormValues(rate: CommissionRate): CommissionRateFormValues {
  return {
    name: rate.name,
    code: rate.code ?? '',
    enabled: rate.enabled,
    kind: (rate.kind as CommissionRateFormValues['kind']) ?? 'percentage',
    value: rate.value ?? '0',
    amounts: Object.fromEntries(
      Object.entries(rate.amounts ?? {}).map(([code, amount]) => [code, String(amount ?? '')]),
    ),
    bounds: Object.fromEntries(
      Object.entries(rate.bounds ?? {}).map(([code, bound]) => [
        code,
        {
          min_amount: bound?.min_amount == null ? '' : String(bound.min_amount),
          max_amount: bound?.max_amount == null ? '' : String(bound.max_amount),
        },
      ]),
    ),
    tax_inclusive: rate.tax_inclusive,
    include_shipping: rate.include_shipping,
    commission_tax_rate: fractionToPercent(rate.commission_tax_rate),
    rules: (rate.rules ?? []).map((rule) => {
      const preferences = { ...(rule.preferences ?? {}) } as Record<string, unknown>
      // Top-level id lists are the picker source of truth; raw ids in
      // preferences would show as numbers after save.
      delete preferences.seller_ids
      delete preferences.category_ids

      return {
        id: rule.id,
        type: rule.type,
        preferences,
        product_ids: rule.product_ids ?? [],
        seller_ids: rule.seller_ids ?? [],
        category_ids: rule.category_ids ?? [],
      }
    }),
  }
}

function decimalOrNull(value: string | undefined): string | null {
  return value?.trim() || null
}

export function commissionRateValuesToParams(
  v: CommissionRateFormValues,
): CommissionRateCreateParams & CommissionRateUpdateParams {
  return {
    name: v.name,
    code: blankToNull(v.code),
    enabled: v.enabled,
    kind: v.kind,
    value: v.value,
    amounts:
      v.kind === 'fixed'
        ? Object.fromEntries(
            Object.entries(v.amounts).filter(([, amount]) => String(amount ?? '').trim() !== ''),
          )
        : {},
    tax_inclusive: v.tax_inclusive,
    // Only a percentage can charge delivery; a flat fee already charges for
    // the sale a parcel belongs to.
    include_shipping: v.kind === 'percentage' ? v.include_shipping : false,
    // A currency the merchant left blank carries no bound, so it is left out
    // entirely rather than sent as a pair of nulls.
    bounds: Object.fromEntries(
      Object.entries(v.bounds)
        .map(([code, bound]) => [
          code,
          {
            min_amount: decimalOrNull(bound.min_amount),
            max_amount: decimalOrNull(bound.max_amount),
          },
        ])
        .filter((entry) => {
          const [currencyCode, bound] = entry as [
            string,
            { min_amount: string | null; max_amount: string | null },
          ]
          const { min_amount, max_amount } = bound
          const hasBound = min_amount !== null || max_amount !== null
          if (!hasBound) return false
          // A flat fee cap without a stated amount would match at zero on the server.
          if (v.kind === 'fixed') {
            return String(v.amounts[currencyCode] ?? '').trim() !== ''
          }
          return true
        }),
    ),
    commission_tax_rate: percentToFraction(v.commission_tax_rate) || null,
    rules: v.rules.map((rule) => {
      const preferences = { ...rule.preferences }

      if (rule.type === 'seller_rule') {
        preferences.seller_ids = rule.seller_ids
      } else if (rule.type === 'category_rule') {
        preferences.category_ids = rule.category_ids
      }

      return {
        id: rule.id,
        type: rule.type,
        preferences,
        ...(rule.product_ids.length > 0 ? { product_ids: rule.product_ids } : {}),
      }
    }),
  }
}