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.
Ruby b2b-commercee-commerceecommerceecommerce-apiecommerce-frameworkecommerce-platformheadlessheadless-commerceheadless-ecommercemarketplacemulti-tenantmulti-vendormulti-vendor-ecommerceopen-sourcespree-commerce
Refuse commission percentages over 100% and warn on flat fees (V-3594) (#14568)
Damian Legawiec1384333ed02a
diff --git a/packages/dashboard/src/locales/ar.json b/packages/dashboard/src/locales/ar.jsonindex c723b11de7..d742112c87 100644--- a/packages/dashboard/src/locales/ar.json+++ b/packages/dashboard/src/locales/ar.json@@ -471,13 +471,17 @@},"edit_description": "حدّث الرسوم وحدودها والمبيعات التي تنطبق عليها.","empty": "لا توجد نسب عمولة بعد",+ "flat_fee_exceeds_sale_warning": "تُحتسب هذه الرسوم بالكامل عن كل وحدة تُباع. على منتج رخيص قد تتجاوز ما حققه البائع من البيع. حدّد حدًا أقصى أدناه للحد من المبلغ الذي يمكن احتسابه على سطر بيع واحد.","messages": {"created": "تم إنشاء نسبة العمولة","deleted": "تم حذف نسبة العمولة","updated": "تم تحديث نسبة العمولة"},"order_hint": "تُضاف النسب الجديدة إلى أعلى القائمة، وتفوز أول نسبة مطابقة — اسحب لإعادة الترتيب.",- "search_placeholder": "البحث بالاسم…"+ "search_placeholder": "البحث بالاسم…",+ "validation": {+ "percentage_exceeds_one_hundred": "لا يمكن أن تتجاوز نسبة العمولة 100%."+ }},"companies": {"add_cta": "إضافة شركة",@@ -1142,6 +1146,10 @@"enabled": {"help": "تُتجاهل النسب المعطّلة عند الاحتساب."},+ "flat_fee_cap": {+ "help": "حد أقصى اختياري لكل سطر بيع. اتركه فارغًا لاحتساب الرسوم الثابتة كاملة.",+ "label": "الحد الأقصى لكل سطر بيع (اختياري)"+ },"include_shipping": {"help": "احتساب العمولة أيضًا على إيرادات التوصيل لدى البائع.","label": "احتساب على التوصيل"diff --git a/packages/dashboard/src/locales/de.json b/packages/dashboard/src/locales/de.jsonindex 65f285a1ae..274b1682b8 100644--- a/packages/dashboard/src/locales/de.json+++ b/packages/dashboard/src/locales/de.json@@ -467,13 +467,17 @@},"edit_description": "Gebühr, Grenzen und betroffene Verkäufe aktualisieren.","empty": "Noch keine Provisionssätze",+ "flat_fee_exceeds_sale_warning": "Diese Gebühr wird pro verkaufter Einheit voll berechnet. Bei günstigen Artikeln kann sie höher sein als der Erlös des Verkäufers. Setzen Sie unten ein Maximum, um die Gebühr pro Verkaufszeile zu begrenzen.","messages": {"created": "Provisionssatz erstellt","deleted": "Provisionssatz gelöscht","updated": "Provisionssatz aktualisiert"},"order_hint": "Neue Sätze stehen oben in der Liste, und der erste passende gilt — zum Umsortieren ziehen.",- "search_placeholder": "Nach Namen suchen…"+ "search_placeholder": "Nach Namen suchen…",+ "validation": {+ "percentage_exceeds_one_hundred": "Der Provisionsprozentsatz darf 100 % nicht überschreiten."+ }},"companies": {"add_cta": "Unternehmen hinzufügen",@@ -1124,6 +1128,10 @@"enabled": {"help": "Deaktivierte Sätze werden bei der Berechnung übersprungen."},+ "flat_fee_cap": {+ "help": "Optionale Obergrenze pro Verkaufszeile. Leer lassen, um die volle Pauschale zu berechnen.",+ "label": "Maximum pro Verkaufszeile (optional)"+ },"include_shipping": {"help": "Provision auch auf die Versanderlöse des Verkäufers berechnen.","label": "Auf Versand berechnen"diff --git a/packages/dashboard/src/locales/en.json b/packages/dashboard/src/locales/en.jsonindex 9c20fe18c0..3ecf78e361 100644--- a/packages/dashboard/src/locales/en.json+++ b/packages/dashboard/src/locales/en.json@@ -467,13 +467,17 @@},"edit_description": "Update the charge, its limits, and which sales it applies to.","empty": "No commission rates yet",+ "flat_fee_exceeds_sale_warning": "This fee is charged in full for every unit sold. On a cheap item it can cost the seller more than they earned from the sale. Set a maximum below to cap what one sale line can be charged.","messages": {"created": "Commission rate created","deleted": "Commission rate deleted","updated": "Commission rate updated"},"order_hint": "New rates go to the top of the list, and the first one that matches a sale wins — drag to reorder.",- "search_placeholder": "Search by name…"+ "search_placeholder": "Search by name…",+ "validation": {+ "percentage_exceeds_one_hundred": "Commission percentage cannot exceed 100%."+ }},"companies": {"add_cta": "Add company",@@ -1124,6 +1128,10 @@"enabled": {"help": "Disabled rates are skipped when charging a sale."},+ "flat_fee_cap": {+ "help": "Optional ceiling on what one sale line can be charged. Leave empty to charge the full flat fee.",+ "label": "Maximum per sale line (optional)"+ },"include_shipping": {"help": "Also charge commission on the seller's delivery revenue.","label": "Charge on delivery"diff --git a/packages/dashboard/src/locales/fr.json b/packages/dashboard/src/locales/fr.jsonindex d9dbc75184..083a895d81 100644--- a/packages/dashboard/src/locales/fr.json+++ b/packages/dashboard/src/locales/fr.json@@ -467,13 +467,17 @@},"edit_description": "Modifiez les frais, leurs limites et les ventes concernées.","empty": "Aucun taux de commission",+ "flat_fee_exceeds_sale_warning": "Ce montant est facturé intégralement pour chaque unité vendue. Sur un article bon marché, il peut dépasser ce que le vendeur a gagné. Définissez un plafond ci-dessous pour limiter le montant par ligne de vente.","messages": {"created": "Taux de commission créé","deleted": "Taux de commission supprimé","updated": "Taux de commission mis à jour"},"order_hint": "Les nouveaux taux se placent en haut de la liste, et le premier qui correspond l'emporte — glissez pour réordonner.",- "search_placeholder": "Rechercher par nom…"+ "search_placeholder": "Rechercher par nom…",+ "validation": {+ "percentage_exceeds_one_hundred": "Le pourcentage de commission ne peut pas dépasser 100 %."+ }},"companies": {"add_cta": "Ajouter une entreprise",@@ -1124,6 +1128,10 @@"enabled": {"help": "Les taux désactivés sont ignorés lors de la facturation."},+ "flat_fee_cap": {+ "help": "Plafond optionnel par ligne de vente. Laissez vide pour facturer le montant forfaitaire complet.",+ "label": "Maximum par ligne de vente (facultatif)"+ },"include_shipping": {"help": "Facturer aussi la commission sur les revenus de livraison du vendeur.","label": "Facturer sur la livraison"diff --git a/packages/dashboard/src/locales/pl.json b/packages/dashboard/src/locales/pl.jsonindex 85645a7c53..de295f1077 100644--- a/packages/dashboard/src/locales/pl.json+++ b/packages/dashboard/src/locales/pl.json@@ -471,13 +471,17 @@},"edit_description": "Zaktualizuj opłatę, jej limity i objęte nią sprzedaże.","empty": "Brak stawek prowizji",+ "flat_fee_exceeds_sale_warning": "Ta opłata jest naliczana w pełni za każdą sprzedaną sztukę. Przy tanich produktach może przewyższyć to, co sprzedawca zarobił. Ustaw maksimum poniżej, aby ograniczyć opłatę za jedną pozycję sprzedaży.","messages": {"created": "Utworzono stawkę prowizji","deleted": "Usunięto stawkę prowizji","updated": "Zaktualizowano stawkę prowizji"},"order_hint": "Nowe stawki trafiają na górę listy, a wygrywa pierwsza pasująca — przeciągnij, aby zmienić kolejność.",- "search_placeholder": "Szukaj po nazwie…"+ "search_placeholder": "Szukaj po nazwie…",+ "validation": {+ "percentage_exceeds_one_hundred": "Procent prowizji nie może przekraczać 100%."+ }},"companies": {"add_cta": "Dodaj firmę",@@ -1138,6 +1142,10 @@"enabled": {"help": "Wyłączone stawki są pomijane przy naliczaniu."},+ "flat_fee_cap": {+ "help": "Opcjonalny limit na jedną pozycję sprzedaży. Zostaw puste, aby naliczać pełną kwotę stałą.",+ "label": "Maksimum na pozycję sprzedaży (opcjonalnie)"+ },"include_shipping": {"help": "Nalicz prowizję również od przychodów sprzedawcy z dostawy.","label": "Nalicz od dostawy"diff --git a/packages/dashboard/src/locales/zh-CN.json b/packages/dashboard/src/locales/zh-CN.jsonindex de09b7211a..8c66425411 100644--- a/packages/dashboard/src/locales/zh-CN.json+++ b/packages/dashboard/src/locales/zh-CN.json@@ -466,13 +466,17 @@},"edit_description": "更新费用、上下限以及适用的销售范围。","empty": "暂无佣金费率",+ "flat_fee_exceeds_sale_warning": "此费用按每件售出商品全额收取。对于低价商品,佣金可能超过卖家从该笔销售中获得的收入。请在下方设置最高限额,以限制单笔销售行的收费上限。","messages": {"created": "佣金费率已创建","deleted": "佣金费率已删除","updated": "佣金费率已更新"},"order_hint": "新费率会添加到列表顶部,首个匹配的费率生效——拖动可调整顺序。",- "search_placeholder": "按名称搜索…"+ "search_placeholder": "按名称搜索…",+ "validation": {+ "percentage_exceeds_one_hundred": "佣金百分比不能超过 100%。"+ }},"companies": {"add_cta": "添加公司",@@ -1119,6 +1123,10 @@"enabled": {"help": "停用的费率在计费时会被跳过。"},+ "flat_fee_cap": {+ "help": "可选的单笔销售行收费上限。留空则收取完整的固定费用。",+ "label": "每笔销售行最高限额(可选)"+ },"include_shipping": {"help": "同时对卖家的配送收入收取佣金。","label": "对配送收费"diff --git a/packages/dashboard/src/routes/_authenticated/$storeId/settings/commission-rates.tsx b/packages/dashboard/src/routes/_authenticated/$storeId/settings/commission-rates.tsxindex 0074df28d1..18d2b4c1d3 100644--- a/packages/dashboard/src/routes/_authenticated/$storeId/settings/commission-rates.tsx+++ b/packages/dashboard/src/routes/_authenticated/$storeId/settings/commission-rates.tsx@@ -17,6 +17,8 @@ import {useStore,} from '@spree/dashboard-core'import {+ Alert,+ AlertDescription,Button,DropdownMenu,DropdownMenuContent,@@ -47,7 +49,7 @@ import {useConfirm,useRowClickBridge,} from '@spree/dashboard-ui'-import { PlusIcon, Trash2Icon } from '@spree/dashboard-ui/icons'+import { PlusIcon, Trash2Icon, TriangleAlertIcon } from '@spree/dashboard-ui/icons'import { useQueryClient } from '@tanstack/react-query'import { createFileRoute, useNavigate } from '@tanstack/react-router'import { useEffect } from 'react'@@ -399,6 +401,7 @@ function CommissionRateFormFields({ form }: { form: UseFormReturn<CommissionRatetype="number"step="0.01"min="0"+ max="100"aria-invalid={!!errors.value || undefined}{...form.register('value')}/>@@ -412,7 +415,10 @@ function CommissionRateFormFields({ form }: { form: UseFormReturn<CommissionRate<FieldError errors={[errors.value]} /></Field>) : (- <FlatFeeAmountsField form={form} />+ <>+ <FlatFeeAmountsField form={form} />+ <FlatFeeCapField form={form} />+ </>)}<CommissionRulesField form={form} />@@ -514,6 +520,10 @@ function ToggleField({function FlatFeeAmountsField({ form }: { form: UseFormReturn<CommissionRateFormValues> }) {const { t } = useTranslation()const { currencies } = useStore()+ const amounts = form.watch('amounts')+ const hasAmount = Object.values(amounts ?? {}).some(+ (amount) => String(amount ?? '').trim() !== '',+ )return (<Field>@@ -521,6 +531,14 @@ function FlatFeeAmountsField({ form }: { form: UseFormReturn<CommissionRateFormV<span className="text-xs text-muted-foreground">{t('admin.fields.commission_rate.amounts.help')}</span>+ {hasAmount && (+ <Alert variant="warning" className="mt-2">+ <TriangleAlertIcon />+ <AlertDescription>+ {t('admin.commission_rates.flat_fee_exceeds_sale_warning')}+ </AlertDescription>+ </Alert>+ )}<div className="flex flex-col gap-2 pt-1">{currencies.map((currency) => (<div key={currency} className="flex items-center gap-2">@@ -548,6 +566,65 @@ function FlatFeeAmountsField({ form }: { form: UseFormReturn<CommissionRateFormV)}+/**+ * Optional cap on a flat fee per sale line. The engine already clamps the+ * computed fee to this ceiling — surfacing it here is what makes a minimum+ * fee larger than a cheap item's price a deliberate choice rather than a+ * silent overcharge.+ */+function FlatFeeCapField({ form }: { form: UseFormReturn<CommissionRateFormValues> }) {+ const { t } = useTranslation()+ const { currencies } = useStore()+ const amounts = form.watch('amounts')+ const cappedCurrencies = currencies.filter(+ (currency) => String(amounts?.[currency] ?? '').trim() !== '',+ )++ if (cappedCurrencies.length === 0) {+ return null+ }++ return (+ <Field>+ <FieldLabel>{t('admin.fields.commission_rate.flat_fee_cap.label')}</FieldLabel>+ <span className="text-xs text-muted-foreground">+ {t('admin.fields.commission_rate.flat_fee_cap.help')}+ </span>+ <div className="flex flex-col gap-2 pt-1">+ {cappedCurrencies.map((currency) => (+ <div key={currency} className="flex items-center gap-2">+ <span className="w-12 shrink-0 text-sm text-muted-foreground">{currency}</span>+ <Controller+ control={form.control}+ name="bounds"+ render={({ field }) => {+ const bound = field.value?.[currency] ?? { min_amount: '', max_amount: '' }++ return (+ <Input+ type="number"+ step="0.01"+ min="0"+ aria-label={`${currency} ${t('admin.fields.commission_rate.max_amount.label')}`}+ placeholder={t('admin.fields.commission_rate.max_amount.label')}+ value={bound.max_amount}+ onChange={(event) =>+ field.onChange({+ ...field.value,+ [currency]: { ...bound, max_amount: event.target.value },+ })+ }+ />+ )+ }}+ />+ </div>+ ))}+ </div>+ </Field>+ )+}+/*** Optional bounds on a percentage: never charge less than this, never more* than that. Amounts, so they carry a currency of their own — which is whatdiff --git a/packages/dashboard/src/schemas/commission-rate.ts b/packages/dashboard/src/schemas/commission-rate.tsindex ed8f31bcab..793a6c0ab0 100644--- a/packages/dashboard/src/schemas/commission-rate.ts+++ b/packages/dashboard/src/schemas/commission-rate.ts@@ -3,13 +3,13 @@ import type {CommissionRateCreateParams,CommissionRateUpdateParams,} from '@spree/admin-sdk'-import { blankToNull } from '@spree/dashboard-core'+import { blankToNull, i18n } from '@spree/dashboard-core'import { requiredMessage } from '@spree/dashboard-ui'import { z } from 'zod/v4'export const COMMISSION_RATE_KINDS = ['percentage', 'fixed'] as const-export const commissionRateFormSchema = z.object({+const commissionRateFieldsSchema = z.object({name: z.string().min(1, { error: requiredMessage('name') }),code: z.string().optional(),enabled: z.boolean(),@@ -43,6 +43,16 @@ export const commissionRateFormSchema = z.object({),})+export const commissionRateFormSchema = commissionRateFieldsSchema.superRefine((values, ctx) => {+ if (values.kind === 'percentage' && values.value > 100) {+ 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 = {@@ -128,12 +138,19 @@ export function commissionRateValuesToParams(max_amount: decimalOrNull(bound.max_amount),},])- .filter(([, bound]) => {- const { min_amount, max_amount } = bound as {- min_amount: number | null- max_amount: number | null+ .filter((entry) => {+ const [currencyCode, bound] = entry as [+ string,+ { min_amount: number | null; max_amount: number | 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 min_amount !== null || max_amount !== null+ return true}),),commission_tax_rate: taxPercentage === null ? null : taxPercentage / 100,diff --git a/spree/api/spec/controllers/spree/api/v3/admin/commission_rates_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/commission_rates_controller_spec.rbindex 5b7e6d2c67..0fe8a0cf79 100644--- a/spree/api/spec/controllers/spree/api/v3/admin/commission_rates_controller_spec.rb+++ b/spree/api/spec/controllers/spree/api/v3/admin/commission_rates_controller_spec.rb@@ -76,6 +76,13 @@ RSpec.describe Spree::Api::V3::Admin::CommissionRatesController, type: :controllexpect(response).to have_http_status(:unprocessable_entity)end+ it 'refuses a percentage above one hundred' do+ post :create, params: { name: 'Too high', kind: 'percentage', value: 150 }, as: :json++ expect(response).to have_http_status(:unprocessable_entity)+ expect(json_response['error']['code']).to eq('validation_error')+ end+it 'writes a floor and a cap per currency' dopost :create, params: {name: 'Bounded', kind: 'percentage', value: 10,diff --git a/spree/core/app/models/spree/commission_rate.rb b/spree/core/app/models/spree/commission_rate.rbindex 613a097307..0c39386770 100644--- a/spree/core/app/models/spree/commission_rate.rb+++ b/spree/core/app/models/spree/commission_rate.rb@@ -68,6 +68,10 @@ module Spreevalidates :name, presence: truevalidates :kind, presence: true, inclusion: { in: KINDS }validates :value, numericality: { greater_than_or_equal_to: 0 }+ # Commission is a share of the seller's revenue, not a surcharge on top of+ # it — a figure above 100 reads as a typo (150 for 15) and bills the seller+ # more than the sale was worth.+ validates :value, numericality: { less_than_or_equal_to: 100 }, if: :percentage?# Stored lowercase so the database enforces the same uniqueness the# validation promises. A functional index over LOWER(code) would be the# alternative, but that is a MySQL-only construct MariaDB rejects — and@@ -190,7 +194,6 @@ module Spree# @return [void]def amounts=(values)@pending_amounts = (values || {}).to_h.transform_keys { |key| key.to_s.upcase }- apply_pending_amounts if persisted?end# Replaces the floors and caps wholesale, on the same rows the flat fee@@ -201,7 +204,6 @@ module Spree# @return [void]def bounds=(values)@pending_bounds = (values || {}).to_h.transform_keys { |key| key.to_s.upcase }- apply_pending_bounds if persisted?end# Whether this rate charges every sale, having named nothing to narrow it.@@ -292,11 +294,12 @@ module Spreewanted = @pending_amounts.compact_blank@pending_amounts = nil- # A row carrying bounds outlives the amount it was written with: the two- # are written by different fields, and dropping a currency from the flat- # fee must not silently uncap a percentage.+ # A percentage's bounds outlive clearing +amounts+ — the two are different+ # fields and dropping a currency from amounts must not silently uncap it.+ # A flat fee's cap lives on the same row as its amount; clearing the amount+ # retires the whole currency.commission_rate_values.- reject { |value| wanted.key?(value.currency) || value.bounded? }.+ reject { |value| wanted.key?(value.currency) || (!fixed? && value.bounded?) }.each(&:destroy)wanted.each do |currency, amount|@@ -322,6 +325,15 @@ module Spreewanted.each do |currency, bound|bound = (bound || {}).symbolize_keys++ # A flat fee applies only where it states an amount. Writing bounds alone+ # would create a zero-amount row that still matches and blocks fallthrough.+ # +amounts=+ may run after +bounds=+ on update, so pending amounts count.+ if fixed? && effective_amount_for(currency) <= 0+ commission_rate_values.find { |value| value.currency == currency }&.destroy+ next+ end+row_for_currency(currency).update!(min_amount: bound[:min_amount].presence, max_amount: bound[:max_amount].presence)@@ -334,6 +346,14 @@ module Spreecommission_rate_values.build(currency: currency)end+ def effective_amount_for(currency)+ if @pending_amounts&.key?(currency)+ @pending_amounts[currency].to_d+ else+ amount_for(currency).to_d+ end+ end+def flat_fee_does_not_charge_deliveryreturn unless fixed? && include_shipping?diff --git a/spree/core/spec/models/spree/commission_rate_spec.rb b/spree/core/spec/models/spree/commission_rate_spec.rbindex bd301d5b2a..891809904a 100644--- a/spree/core/spec/models/spree/commission_rate_spec.rb+++ b/spree/core/spec/models/spree/commission_rate_spec.rb@@ -18,6 +18,11 @@ RSpec.describe Spree::CommissionRate, type: :model doexpect(build(:commission_rate, commission_tax_rate: 0.21)).to be_validend+ it 'refuses a percentage above one hundred' do+ expect(build(:commission_rate, kind: 'percentage', value: 150)).not_to be_valid+ expect(build(:commission_rate, kind: 'percentage', value: 100)).to be_valid+ end+it 'rejects a cap below the floor' dorate = create(:commission_rate, store: store)value = rate.commission_rate_values.build(currency: 'USD', min_amount: 10, max_amount: 5)@@ -132,6 +137,38 @@ RSpec.describe Spree::CommissionRate, type: :model doexpect(rate.reload.bounds.keys).to eq(['USD'])end++ it 'ignores a flat-fee cap for a currency with no stated amount' do+ rate = create(:commission_rate, :fixed, store: store, amounts: { 'USD' => 5 })++ rate.update!(bounds: { 'EUR' => { max_amount: 20 } })++ expect(rate.bounds.keys).to eq([])+ expect(rate.applies_to_currency?('EUR')).to be false+ end++ it 'retires a flat fee and its cap when the amount is cleared' do+ rate = create(:commission_rate, :fixed, store: store,+ amounts: { 'USD' => 5, 'GBP' => 4 },+ bounds: { 'USD' => { max_amount: 20 } })++ rate.update!(amounts: { 'GBP' => 4 })++ expect(rate.amount_for('USD')).to be_nil+ expect(rate.max_amount_for('USD')).to be_nil+ expect(rate.amount_for('GBP')).to eq(4)+ end++ it 'applies a flat-fee cap when bounds are assigned before amounts' do+ rate = create(:commission_rate, :fixed, store: store, amounts: { 'USD' => 5 })++ rate.bounds = { 'EUR' => { max_amount: 20 } }+ rate.amounts = { 'EUR' => 10, 'USD' => 5 }+ rate.save!++ expect(rate.amount_for('EUR')).to eq(10)+ expect(rate.max_amount_for('EUR')).to eq(20)+ endenddescribe 'flat fee amounts' do