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.

Add the quantity-rule editors to the dashboard

Damian Legawiec2c9a76e79785
diff --git a/packages/admin-sdk/src/admin-client.ts b/packages/admin-sdk/src/admin-client.ts
index 20031e0766..40ac1b485a 100644
--- a/packages/admin-sdk/src/admin-client.ts
+++ b/packages/admin-sdk/src/admin-client.ts
@@ -101,7 +101,9 @@ import type {
ApiKeyCreateParams,
ApiKeyUpdateParams,
CatalogAssignParams,
+ CatalogOrderMinimumParams,
CatalogParams,
+ CatalogQuantityRuleParams,
CategoryCreateParams,
CategoryRepositionParams,
CategoryUpdateParams,
@@ -257,6 +259,8 @@ import type {
ApiKey,
Catalog,
CatalogAssignment,
+ CatalogOrderMinimum,
+ CatalogQuantityRule,
Category,
Channel,
Claim,
@@ -3414,6 +3418,85 @@ export class AdminClient {
...options,
body: params,
}),
+
+ /**
+ * Per-variant quantity terms. The catalog-wide default is a pair of
+ * fields on the catalog itself, so this is strictly the overrides.
+ */
+ quantityRules: {
+ list: (
+ catalogId: string,
+ params?: ListParams & Record<string, unknown>,
+ options?: RequestOptions,
+ ): Promise<PaginatedResponse<CatalogQuantityRule>> =>
+ this.request<PaginatedResponse<CatalogQuantityRule>>(
+ 'GET',
+ `/catalogs/${catalogId}/quantity_rules`,
+ { ...options, params: params ? transformListParams(params) : undefined },
+ ),
+
+ create: (
+ catalogId: string,
+ params: CatalogQuantityRuleParams,
+ options?: RequestOptions,
+ ): Promise<CatalogQuantityRule> =>
+ this.request<CatalogQuantityRule>('POST', `/catalogs/${catalogId}/quantity_rules`, {
+ ...options,
+ body: params,
+ }),
+
+ update: (
+ catalogId: string,
+ id: string,
+ params: CatalogQuantityRuleParams,
+ options?: RequestOptions,
+ ): Promise<CatalogQuantityRule> =>
+ this.request<CatalogQuantityRule>('PATCH', `/catalogs/${catalogId}/quantity_rules/${id}`, {
+ ...options,
+ body: params,
+ }),
+
+ delete: (catalogId: string, id: string, options?: RequestOptions): Promise<void> =>
+ this.request<void>('DELETE', `/catalogs/${catalogId}/quantity_rules/${id}`, options),
+ },
+
+ /** The order minimum in each currency this agreement states one for. */
+ orderMinimums: {
+ list: (
+ catalogId: string,
+ params?: ListParams & Record<string, unknown>,
+ options?: RequestOptions,
+ ): Promise<PaginatedResponse<CatalogOrderMinimum>> =>
+ this.request<PaginatedResponse<CatalogOrderMinimum>>(
+ 'GET',
+ `/catalogs/${catalogId}/order_minimums`,
+ { ...options, params: params ? transformListParams(params) : undefined },
+ ),
+
+ create: (
+ catalogId: string,
+ params: CatalogOrderMinimumParams,
+ options?: RequestOptions,
+ ): Promise<CatalogOrderMinimum> =>
+ this.request<CatalogOrderMinimum>('POST', `/catalogs/${catalogId}/order_minimums`, {
+ ...options,
+ body: params,
+ }),
+
+ update: (
+ catalogId: string,
+ id: string,
+ params: CatalogOrderMinimumParams,
+ options?: RequestOptions,
+ ): Promise<CatalogOrderMinimum> =>
+ this.request<CatalogOrderMinimum>('PATCH', `/catalogs/${catalogId}/order_minimums/${id}`, {
+ ...options,
+ body: params,
+ }),
+
+ delete: (catalogId: string, id: string, options?: RequestOptions): Promise<void> =>
+ this.request<void>('DELETE', `/catalogs/${catalogId}/order_minimums/${id}`, options),
+ },
}
readonly catalogAssignments = {
diff --git a/packages/admin-sdk/src/params.ts b/packages/admin-sdk/src/params.ts
index 0f330afcc4..2f084ecb20 100644
--- a/packages/admin-sdk/src/params.ts
+++ b/packages/admin-sdk/src/params.ts
@@ -2587,6 +2587,13 @@ export interface CompanyMembershipCreateParams {
export interface CatalogParams {
name?: string
+ /**
+ * The catalog-wide quantity terms — the middle of the three levels a
+ * buyer's rules resolve through (variant base -> this -> a per-variant
+ * override). Null on either leaves that field to the variant's own rule.
+ */
+ minimum_order_quantity?: number | null
+ order_multiple?: number | null
/** Internal note on what the agreement is — never shown to shoppers. */
description?: string | null
active?: boolean
@@ -2643,6 +2650,29 @@ export interface CatalogPriceListParams {
prices?: Array<PriceListPriceOverrideParams>
}
+/**
+ * A catalog's quantity terms for ONE variant — the narrowest of the three
+ * levels. Both fields are independently optional, but a row must state at
+ * least one: an override that overrides nothing is a half-filled form.
+ */
+export interface CatalogQuantityRuleParams {
+ /** Prefixed variant id (variant_...). Required on create. */
+ variant_id?: string
+ minimum_order_quantity?: number | null
+ order_multiple?: number | null
+}
+
+/**
+ * The least a whole order must come to under this agreement, in ONE
+ * currency. One row per currency — Spree holds no exchange rates, so a
+ * threshold is never stated once and converted.
+ */
+export interface CatalogOrderMinimumParams {
+ /** ISO 4217 code. Required on create; unique per catalog. */
+ currency?: string
+ amount?: string | number
+}
+
export interface CatalogAssignParams {
/**
* Who sees the catalog — buyer audiences only. A company assignment covers
diff --git a/packages/admin-sdk/src/types/index.ts b/packages/admin-sdk/src/types/index.ts
index 596e047f9f..f40a2c4e0e 100644
--- a/packages/admin-sdk/src/types/index.ts
+++ b/packages/admin-sdk/src/types/index.ts
@@ -22,6 +22,8 @@ export type { default as ApiKey } from './generated/ApiKey'
export type { default as AppliedPromotion } from './generated/AppliedPromotion'
export type { default as Catalog } from './generated/Catalog'
export type { default as CatalogAssignment } from './generated/CatalogAssignment'
+export type { default as CatalogOrderMinimum } from './generated/CatalogOrderMinimum'
+export type { default as CatalogQuantityRule } from './generated/CatalogQuantityRule'
export type { default as Category } from './generated/Category'
export type { default as Channel } from './generated/Channel'
export type { default as Claim } from './generated/Claim'
diff --git a/packages/dashboard-core/src/locales/ar.json b/packages/dashboard-core/src/locales/ar.json
index 8667d05f3d..e9d55d82f0 100644
--- a/packages/dashboard-core/src/locales/ar.json
+++ b/packages/dashboard-core/src/locales/ar.json
@@ -805,7 +805,35 @@
},
"width": {
"label": "العرض"
+ },
+ "minimum_order_quantity": {
+ "label": "الحد الأدنى لكمية الطلب",
+ "placeholder": "بلا حد أدنى",
+ "help": "أقل كمية يمكن للمشتري طلبها. اتركه فارغًا لعدم وجود حد أدنى."
+ },
+ "order_multiple": {
+ "label": "مضاعف الطلب",
+ "placeholder": "بلا مضاعف",
+ "help": "يجب أن تكون الطلبات من مضاعفات هذا الرقم. اتركه فارغًا للسماح بأي كمية."
+ },
+ "purchase_unit": {
+ "label": "وحدة الشراء",
+ "options": {
+ "unit": "وحدات",
+ "carton": "كراتين"
+ }
+ },
+ "units_per_carton": {
+ "label": "الوحدات في الكرتونة"
}
+ },
+ "minimum_order_quantity": {
+ "label": "الحد الأدنى لكمية الطلب",
+ "help": "أقل كمية يمكن للمشتري طلبها. اتركه فارغًا لعدم وجود حد أدنى."
+ },
+ "order_multiple": {
+ "label": "مضاعف الطلب",
+ "help": "يجب أن تكون الطلبات من مضاعفات هذا الرقم. اتركه فارغًا للسماح بأي كمية."
}
},
"image_upload": {
@@ -1427,7 +1455,9 @@
"customs": "الجمارك",
"customs_help": "يُستخدم في نماذج الجمارك عند شحن هذا المنتج عبر الحدود.",
"identity": "هوية",
- "tax_category_placeholder": "ترث من المنتج"
+ "tax_category_placeholder": "ترث من المنتج",
+ "ordering": "الطلب للشركات",
+ "ordering_help": "الكمية التي يجب على المشتري أخذها. لا يزال المخزون يُحسب بالوحدات."
},
"title": "المتغيرات",
"variant_label": "البديل"
@@ -1518,6 +1548,41 @@
},
"media_library": {
"download": "تنزيل"
+ },
+ "catalogs": {
+ "terms": {
+ "title": "الشروط التجارية",
+ "description": "الكمية التي يجب على المشترين ضمن هذه الاتفاقية طلبها.",
+ "no_rule_placeholder": "بلا قاعدة",
+ "minimums_title": "الحدود الدنيا للطلب",
+ "minimums_description": "أقل قيمة يجب أن يبلغها الطلب بالكامل، لكل عملة.",
+ "minimums_empty": "لا يوجد حد أدنى للطلب. يمكن للمشترين إتمام الشراء بأي إجمالي.",
+ "overrides_title": "قواعد لكل منتج",
+ "overrides_description": "قواعد الكمية لمنتجات محددة، تتجاوز الإعداد الافتراضي أعلاه.",
+ "overrides_empty": "لا توجد قواعد لكل منتج. تستخدم كل المنتجات الإعداد الافتراضي أعلاه.",
+ "product_column": "المنتج",
+ "add_minimum_title": "إضافة حد أدنى للطلب",
+ "minimum_amount_label": "المبلغ الأدنى",
+ "add_rule_title": "إضافة قاعدة منتج",
+ "variant_placeholder": "البحث عن المنتجات",
+ "variant_empty": "لم يتم العثور على منتجات",
+ "override_help": "اترك الحقل فارغًا للرجوع إلى الإعداد الافتراضي أعلاه.",
+ "remove_minimum_title": "إزالة الحد الأدنى للطلب؟",
+ "remove_minimum_description": "لن تحتاج الطلبات بعملة {{currency}} إلى بلوغ حد أدنى. يسري هذا فورًا.",
+ "remove_rule_title": "إزالة قاعدة المنتج؟",
+ "remove_rule_description": "سيعود {{name}} إلى الإعداد الافتراضي للكتالوج. يسري هذا فورًا.",
+ "validation": {
+ "positive_integer": "أدخل عددًا صحيحًا أكبر من صفر، أو اترك الحقل فارغًا.",
+ "currency_taken": "هذه العملة لديها حد أدنى بالفعل."
+ },
+ "messages": {
+ "rule_created": "تمت إضافة قاعدة المنتج",
+ "rule_updated": "تم تحديث قاعدة المنتج",
+ "rule_deleted": "تمت إزالة قاعدة المنتج",
+ "minimum_created": "تمت إضافة الحد الأدنى للطلب",
+ "minimum_deleted": "تمت إزالة الحد الأدنى للطلب"
+ }
+ }
}
}
}
diff --git a/packages/dashboard-core/src/locales/de.json b/packages/dashboard-core/src/locales/de.json
index d182c054fd..646bcc12c8 100644
--- a/packages/dashboard-core/src/locales/de.json
+++ b/packages/dashboard-core/src/locales/de.json
@@ -805,7 +805,35 @@
},
"width": {
"label": "Breite"
+ },
+ "minimum_order_quantity": {
+ "label": "Mindestbestellmenge",
+ "placeholder": "Kein Minimum",
+ "help": "Die geringste Menge, die ein Käufer bestellen darf. Leer lassen für kein Minimum."
+ },
+ "order_multiple": {
+ "label": "Bestellvielfaches",
+ "placeholder": "Kein Vielfaches",
+ "help": "Bestellungen müssen ein Vielfaches davon sein. Leer lassen für beliebige Mengen."
+ },
+ "purchase_unit": {
+ "label": "Verkaufseinheit",
+ "options": {
+ "unit": "Stück",
+ "carton": "Kartons"
+ }
+ },
+ "units_per_carton": {
+ "label": "Stück pro Karton"
}
+ },
+ "minimum_order_quantity": {
+ "label": "Mindestbestellmenge",
+ "help": "Die geringste Menge, die ein Käufer bestellen darf. Leer lassen für kein Minimum."
+ },
+ "order_multiple": {
+ "label": "Bestellvielfaches",
+ "help": "Bestellungen müssen ein Vielfaches davon sein. Leer lassen für beliebige Mengen."
}
},
"image_upload": {
@@ -1428,7 +1456,9 @@
"customs": "Zoll",
"customs_help": "Wird auf Zollformularen verwendet, wenn dieser Artikel eine Grenze überquert.",
"identity": "Identität",
- "tax_category_placeholder": "Vom Produkt übernehmen"
+ "tax_category_placeholder": "Vom Produkt übernehmen",
+ "ordering": "B2B-Bestellung",
+ "ordering_help": "Wie viel ein Käufer abnehmen muss. Der Bestand wird weiterhin in Stück gezählt."
},
"title": "Varianten",
"variant_label": "Variante"
@@ -1513,6 +1543,41 @@
},
"media_library": {
"download": "Herunterladen"
+ },
+ "catalogs": {
+ "terms": {
+ "title": "Handelsbedingungen",
+ "description": "Wie viel Käufer dieser Vereinbarung bestellen müssen.",
+ "no_rule_placeholder": "Keine Regel",
+ "minimums_title": "Mindestbestellwerte",
+ "minimums_description": "Der Mindestwert einer gesamten Bestellung, je Währung.",
+ "minimums_empty": "Kein Mindestbestellwert. Käufer können mit jeder Summe bestellen.",
+ "overrides_title": "Produktbezogene Regeln",
+ "overrides_description": "Mengenregeln für einzelne Produkte, die den Standard oben überschreiben.",
+ "overrides_empty": "Keine produktbezogenen Regeln. Alle Produkte nutzen den Standard oben.",
+ "product_column": "Produkt",
+ "add_minimum_title": "Mindestbestellwert hinzufügen",
+ "minimum_amount_label": "Mindestbetrag",
+ "add_rule_title": "Produktregel hinzufügen",
+ "variant_placeholder": "Produkte suchen",
+ "variant_empty": "Keine Produkte gefunden",
+ "override_help": "Feld leer lassen, um auf den Standard oben zurückzufallen.",
+ "remove_minimum_title": "Mindestbestellwert entfernen?",
+ "remove_minimum_description": "Bestellungen in {{currency}} benötigen keinen Mindestwert mehr. Dies wirkt sofort.",
+ "remove_rule_title": "Produktregel entfernen?",
+ "remove_rule_description": "{{name}} nutzt wieder den Katalogstandard. Dies wirkt sofort.",
+ "validation": {
+ "positive_integer": "Geben Sie eine ganze Zahl größer als null ein oder lassen Sie das Feld leer.",
+ "currency_taken": "Für diese Währung gibt es bereits einen Mindestwert."
+ },
+ "messages": {
+ "rule_created": "Produktregel hinzugefügt",
+ "rule_updated": "Produktregel aktualisiert",
+ "rule_deleted": "Produktregel entfernt",
+ "minimum_created": "Mindestbestellwert hinzugefügt",
+ "minimum_deleted": "Mindestbestellwert entfernt"
+ }
+ }
}
}
}
diff --git a/packages/dashboard-core/src/locales/en.json b/packages/dashboard-core/src/locales/en.json
index 2087635485..ee00449952 100644
--- a/packages/dashboard-core/src/locales/en.json
+++ b/packages/dashboard-core/src/locales/en.json
@@ -807,7 +807,35 @@
},
"width": {
"label": "Width"
+ },
+ "minimum_order_quantity": {
+ "label": "Minimum order quantity",
+ "placeholder": "No minimum",
+ "help": "The least a buyer may order. Leave blank for no minimum."
+ },
+ "order_multiple": {
+ "label": "Order multiple",
+ "placeholder": "No multiple",
+ "help": "Orders must be a multiple of this. Leave blank for any quantity."
+ },
+ "purchase_unit": {
+ "label": "Purchase unit",
+ "options": {
+ "unit": "Units",
+ "carton": "Cartons"
+ }
+ },
+ "units_per_carton": {
+ "label": "Units per carton"
}
+ },
+ "minimum_order_quantity": {
+ "label": "Minimum order quantity",
+ "help": "The least a buyer may order. Leave blank for no minimum."
+ },
+ "order_multiple": {
+ "label": "Order multiple",
+ "help": "Orders must be a multiple of this. Leave blank for any quantity."
}
},
"image_upload": {
@@ -1430,7 +1458,9 @@
"customs": "Customs",
"customs_help": "Used on customs forms when this item ships across a border.",
"identity": "Identity",
- "tax_category_placeholder": "Inherit from product"
+ "tax_category_placeholder": "Inherit from product",
+ "ordering": "B2B ordering",
+ "ordering_help": "How much a buyer must take. Stock is still counted in units."
},
"title": "Variants",
"variant_label": "Variant"
@@ -1515,6 +1545,41 @@
},
"media_library": {
"download": "Download"
+ },
+ "catalogs": {
+ "terms": {
+ "title": "Commercial terms",
+ "description": "How much buyers on this agreement must order.",
+ "no_rule_placeholder": "No rule",
+ "minimums_title": "Order minimums",
+ "minimums_description": "The least a whole order must come to, per currency.",
+ "minimums_empty": "No order minimum. Buyers may check out with any total.",
+ "overrides_title": "Per-product rules",
+ "overrides_description": "Quantity rules for specific products, overriding the default above.",
+ "overrides_empty": "No per-product rules. Every product uses the default above.",
+ "product_column": "Product",
+ "add_minimum_title": "Add order minimum",
+ "minimum_amount_label": "Minimum amount",
+ "add_rule_title": "Add product rule",
+ "variant_placeholder": "Search products",
+ "variant_empty": "No products found",
+ "override_help": "Leave a field blank to fall back to the default above.",
+ "remove_minimum_title": "Remove order minimum?",
+ "remove_minimum_description": "Orders in {{currency}} will no longer need to reach a minimum. This takes effect immediately.",
+ "remove_rule_title": "Remove product rule?",
+ "remove_rule_description": "{{name}} will fall back to the catalog default. This takes effect immediately.",
+ "validation": {
+ "positive_integer": "Enter a whole number greater than zero, or leave blank.",
+ "currency_taken": "This currency already has a minimum."
+ },
+ "messages": {
+ "rule_created": "Product rule added",
+ "rule_updated": "Product rule updated",
+ "rule_deleted": "Product rule removed",
+ "minimum_created": "Order minimum added",
+ "minimum_deleted": "Order minimum removed"
+ }
+ }
}
}
}
diff --git a/packages/dashboard-core/src/locales/fr.json b/packages/dashboard-core/src/locales/fr.json
index f1e3712ca5..be2b03b478 100644
--- a/packages/dashboard-core/src/locales/fr.json
+++ b/packages/dashboard-core/src/locales/fr.json
@@ -805,7 +805,35 @@
},
"width": {
"label": "Largeur"
+ },
+ "minimum_order_quantity": {
+ "label": "Quantité minimale de commande",
+ "placeholder": "Aucun minimum",
+ "help": "La plus petite quantité qu'un acheteur peut commander. Laisser vide pour aucun minimum."
+ },
+ "order_multiple": {
+ "label": "Multiple de commande",
+ "placeholder": "Aucun multiple",
+ "help": "Les commandes doivent être un multiple de cette valeur. Laisser vide pour toute quantité."
+ },
+ "purchase_unit": {
+ "label": "Unité de vente",
+ "options": {
+ "unit": "Unités",
+ "carton": "Cartons"
+ }
+ },
+ "units_per_carton": {
+ "label": "Unités par carton"
}
+ },
+ "minimum_order_quantity": {
+ "label": "Quantité minimale de commande",
+ "help": "La plus petite quantité qu'un acheteur peut commander. Laisser vide pour aucun minimum."
+ },
+ "order_multiple": {
+ "label": "Multiple de commande",
+ "help": "Les commandes doivent être un multiple de cette valeur. Laisser vide pour toute quantité."
}
},
"image_upload": {
@@ -1428,7 +1456,9 @@
"customs": "Douane",
"customs_help": "Utilisé sur les formulaires douaniers lorsque cet article franchit une frontière.",
"identity": "Identité",
- "tax_category_placeholder": "Hériter du produit"
+ "tax_category_placeholder": "Hériter du produit",
+ "ordering": "Commande B2B",
+ "ordering_help": "Combien un acheteur doit prendre. Le stock reste compté en unités."
},
"title": "Variantes",
"variant_label": "Variante"
@@ -1513,6 +1543,41 @@
},
"media_library": {
"download": "Télécharger"
+ },
+ "catalogs": {
+ "terms": {
+ "title": "Conditions commerciales",
+ "description": "Combien les acheteurs de cet accord doivent commander.",
+ "no_rule_placeholder": "Aucune règle",
+ "minimums_title": "Minimums de commande",
+ "minimums_description": "Le montant minimal d'une commande entière, par devise.",
+ "minimums_empty": "Aucun minimum de commande. Les acheteurs peuvent commander tout montant.",
+ "overrides_title": "Règles par produit",
+ "overrides_description": "Règles de quantité pour des produits précis, qui remplacent la valeur par défaut ci-dessus.",
+ "overrides_empty": "Aucune règle par produit. Tous les produits utilisent la valeur par défaut ci-dessus.",
+ "product_column": "Produit",
+ "add_minimum_title": "Ajouter un minimum de commande",
+ "minimum_amount_label": "Montant minimal",
+ "add_rule_title": "Ajouter une règle produit",
+ "variant_placeholder": "Rechercher des produits",
+ "variant_empty": "Aucun produit trouvé",
+ "override_help": "Laisser un champ vide pour revenir à la valeur par défaut ci-dessus.",
+ "remove_minimum_title": "Supprimer le minimum de commande ?",
+ "remove_minimum_description": "Les commandes en {{currency}} n'auront plus de minimum. Effet immédiat.",
+ "remove_rule_title": "Supprimer la règle produit ?",
+ "remove_rule_description": "{{name}} reviendra à la valeur par défaut du catalogue. Effet immédiat.",
+ "validation": {
+ "positive_integer": "Saisissez un nombre entier supérieur à zéro, ou laissez vide.",
+ "currency_taken": "Cette devise a déjà un minimum."
+ },
+ "messages": {
+ "rule_created": "Règle produit ajoutée",
+ "rule_updated": "Règle produit mise à jour",
+ "rule_deleted": "Règle produit supprimée",
+ "minimum_created": "Minimum de commande ajouté",
+ "minimum_deleted": "Minimum de commande supprimé"
+ }
+ }
}
}
}
diff --git a/packages/dashboard-core/src/locales/pl.json b/packages/dashboard-core/src/locales/pl.json
index 8e31dad082..0a2896c204 100644
--- a/packages/dashboard-core/src/locales/pl.json
+++ b/packages/dashboard-core/src/locales/pl.json
@@ -805,7 +805,35 @@
},
"width": {
"label": "Szerokość"
+ },
+ "minimum_order_quantity": {
+ "label": "Minimalna wielkość zamówienia",
+ "placeholder": "Brak minimum",
+ "help": "Najmniejsza ilość, jaką kupujący może zamówić. Pozostaw puste, aby nie było minimum."
+ },
+ "order_multiple": {
+ "label": "Wielokrotność zamówienia",
+ "placeholder": "Brak wielokrotności",
+ "help": "Zamówienia muszą być wielokrotnością tej liczby. Pozostaw puste, aby dopuścić dowolną ilość."
+ },
+ "purchase_unit": {
+ "label": "Jednostka sprzedaży",
+ "options": {
+ "unit": "Sztuki",
+ "carton": "Kartony"
+ }
+ },
+ "units_per_carton": {
+ "label": "Sztuk w kartonie"
}
+ },
+ "minimum_order_quantity": {
+ "label": "Minimalna wielkość zamówienia",
+ "help": "Najmniejsza ilość, jaką kupujący może zamówić. Pozostaw puste, aby nie było minimum."
+ },
+ "order_multiple": {
+ "label": "Wielokrotność zamówienia",
+ "help": "Zamówienia muszą być wielokrotnością tej liczby. Pozostaw puste, aby dopuścić dowolną ilość."
}
},
"image_upload": {
@@ -1448,7 +1476,9 @@
"customs": "Cło",
"customs_help": "Używane na formularzach celnych, gdy ten produkt przekracza granicę.",
"identity": "Tożsamość",
- "tax_category_placeholder": "Dziedzicz z produktu"
+ "tax_category_placeholder": "Dziedzicz z produktu",
+ "ordering": "Zamówienia B2B",
+ "ordering_help": "Ile kupujący musi wziąć. Stan magazynowy nadal liczony jest w sztukach."
},
"title": "Warianty",
"variant_label": "Wariant"
@@ -1539,6 +1569,41 @@
},
"media_library": {
"download": "Pobierz"
+ },
+ "catalogs": {
+ "terms": {
+ "title": "Warunki handlowe",
+ "description": "Ile muszą zamawiać kupujący objęci tą umową.",
+ "no_rule_placeholder": "Brak reguły",
+ "minimums_title": "Minimalne wartości zamówienia",
+ "minimums_description": "Najniższa wartość całego zamówienia, dla każdej waluty.",
+ "minimums_empty": "Brak minimalnej wartości zamówienia. Kupujący mogą złożyć zamówienie na dowolną kwotę.",
+ "overrides_title": "Reguły dla produktów",
+ "overrides_description": "Reguły ilości dla wybranych produktów, nadpisujące wartość domyślną powyżej.",
+ "overrides_empty": "Brak reguł dla produktów. Wszystkie produkty używają wartości domyślnej powyżej.",
+ "product_column": "Produkt",
+ "add_minimum_title": "Dodaj minimalną wartość zamówienia",
+ "minimum_amount_label": "Kwota minimalna",
+ "add_rule_title": "Dodaj regułę produktu",
+ "variant_placeholder": "Szukaj produktów",
+ "variant_empty": "Nie znaleziono produktów",
+ "override_help": "Pozostaw pole puste, aby użyć wartości domyślnej powyżej.",
+ "remove_minimum_title": "Usunąć minimalną wartość zamówienia?",
+ "remove_minimum_description": "Zamówienia w {{currency}} nie będą już musiały osiągać minimum. Zmiana działa natychmiast.",
+ "remove_rule_title": "Usunąć regułę produktu?",
+ "remove_rule_description": "{{name}} wróci do wartości domyślnej katalogu. Zmiana działa natychmiast.",
+ "validation": {
+ "positive_integer": "Podaj liczbę całkowitą większą od zera lub pozostaw pole puste.",
+ "currency_taken": "Ta waluta ma już ustawione minimum."
+ },
+ "messages": {
+ "rule_created": "Dodano regułę produktu",
+ "rule_updated": "Zaktualizowano regułę produktu",
+ "rule_deleted": "Usunięto regułę produktu",
+ "minimum_created": "Dodano minimalną wartość zamówienia",
+ "minimum_deleted": "Usunięto minimalną wartość zamówienia"
+ }
+ }
}
}
}
diff --git a/packages/dashboard-core/src/locales/zh-CN.json b/packages/dashboard-core/src/locales/zh-CN.json
index 19cda1a68d..975db5b2db 100644
--- a/packages/dashboard-core/src/locales/zh-CN.json
+++ b/packages/dashboard-core/src/locales/zh-CN.json
@@ -805,7 +805,35 @@
},
"width": {
"label": "宽度"
+ },
+ "minimum_order_quantity": {
+ "label": "最小起订量",
+ "placeholder": "无最小值",
+ "help": "买家可以订购的最小数量。留空表示没有最小值。"
+ },
+ "order_multiple": {
+ "label": "订购倍数",
+ "placeholder": "无倍数",
+ "help": "订单数量必须是该数值的倍数。留空表示不限数量。"
+ },
+ "purchase_unit": {
+ "label": "销售单位",
+ "options": {
+ "unit": "件",
+ "carton": "箱"
+ }
+ },
+ "units_per_carton": {
+ "label": "每箱件数"
}
+ },
+ "minimum_order_quantity": {
+ "label": "最小起订量",
+ "help": "买家可以订购的最小数量。留空表示没有最小值。"
+ },
+ "order_multiple": {
+ "label": "订购倍数",
+ "help": "订单数量必须是该数值的倍数。留空表示不限数量。"
}
},
"image_upload": {
@@ -1427,7 +1455,9 @@
"customs": "海关",
"customs_help": "当该商品跨境运输时用于海关申报单。",
"identity": "标识",
- "tax_category_placeholder": "继承自商品"
+ "tax_category_placeholder": "继承自商品",
+ "ordering": "B2B 订购",
+ "ordering_help": "买家必须订购的数量。库存仍以件计算。"
},
"title": "变体",
"variant_label": "变体"
@@ -1512,6 +1542,41 @@
},
"media_library": {
"download": "下载"
+ },
+ "catalogs": {
+ "terms": {
+ "title": "商务条款",
+ "description": "适用本协议的买家必须订购多少。",
+ "no_rule_placeholder": "无规则",
+ "minimums_title": "订单最低金额",
+ "minimums_description": "整笔订单必须达到的最低金额,按币种设置。",
+ "minimums_empty": "没有订单最低金额。买家可以任意金额结账。",
+ "overrides_title": "单品规则",
+ "overrides_description": "针对特定商品的数量规则,覆盖上面的默认值。",
+ "overrides_empty": "没有单品规则。所有商品都使用上面的默认值。",
+ "product_column": "商品",
+ "add_minimum_title": "添加订单最低金额",
+ "minimum_amount_label": "最低金额",
+ "add_rule_title": "添加商品规则",
+ "variant_placeholder": "搜索商品",
+ "variant_empty": "未找到商品",
+ "override_help": "留空该字段将回退到上面的默认值。",
+ "remove_minimum_title": "移除订单最低金额?",
+ "remove_minimum_description": "{{currency}} 订单将不再需要达到最低金额。此更改立即生效。",
+ "remove_rule_title": "移除商品规则?",
+ "remove_rule_description": "{{name}} 将回退到目录默认值。此更改立即生效。",
+ "validation": {
+ "positive_integer": "请输入大于零的整数,或留空。",
+ "currency_taken": "该币种已设置最低金额。"
+ },
+ "messages": {
+ "rule_created": "已添加商品规则",
+ "rule_updated": "已更新商品规则",
+ "rule_deleted": "已移除商品规则",
+ "minimum_created": "已添加订单最低金额",
+ "minimum_deleted": "已移除订单最低金额"
+ }
+ }
}
}
}
diff --git a/packages/dashboard-core/src/products/normalize-quantity.test.ts b/packages/dashboard-core/src/products/normalize-quantity.test.ts
new file mode 100644
index 0000000000..316399a311
--- /dev/null
+++ b/packages/dashboard-core/src/products/normalize-quantity.test.ts
@@ -0,0 +1,28 @@
+import { describe, expect, it } from 'vitest'
+import { normalizeQuantityRule } from './normalize-quantity'
+
+describe('normalizeQuantityRule', () => {
+ it('reads a whole number', () => {
+ expect(normalizeQuantityRule('48')).toBe(48)
+ expect(normalizeQuantityRule(24)).toBe(24)
+ })
+
+ // Blank means the rule is unset, which is not zero: an empty minimum lets
+ // a buyer take one.
+ it('treats a blank field as unset', () => {
+ expect(normalizeQuantityRule('')).toBeNull()
+ expect(normalizeQuantityRule(' ')).toBeNull()
+ expect(normalizeQuantityRule(null)).toBeNull()
+ expect(normalizeQuantityRule(undefined)).toBeNull()
+ })
+
+ it('rejects values a rule cannot mean', () => {
+ expect(normalizeQuantityRule('0')).toBeNull()
+ expect(normalizeQuantityRule('-5')).toBeNull()
+ expect(normalizeQuantityRule('abc')).toBeNull()
+ })
+
+ it('truncates a fractional entry to whole units', () => {
+ expect(normalizeQuantityRule('48.9')).toBe(48)
+ })
+})
diff --git a/packages/dashboard-core/src/products/normalize-quantity.ts b/packages/dashboard-core/src/products/normalize-quantity.ts
new file mode 100644
index 0000000000..0388f8317d
--- /dev/null
+++ b/packages/dashboard-core/src/products/normalize-quantity.ts
@@ -0,0 +1,25 @@
+// Purchasing-rule normalization for the variant editors, mirroring
+// `Spree::Variant`'s own validations so a merchant hears about a bad value
+// while typing rather than on save.
+
+/** What a buyer is quoted in. Stored quantities stay units at every level. */
+export const PURCHASE_UNITS = ['unit', 'carton'] as const
+
+export type PurchaseUnit = (typeof PURCHASE_UNITS)[number]
+
+/**
+ * Reads a quantity rule from a number input. Blank means the rule is unset,
+ * which is not the same as zero: an empty minimum lets a buyer take one, a
+ * minimum of zero is meaningless and the server refuses it.
+ *
+ * @returns a positive whole number, or null when the field says nothing.
+ */
+export function normalizeQuantityRule(value: unknown): number | null {
+ const trimmed = String(value ?? '').trim()
+ if (trimmed === '') return null
+
+ const parsed = Number(trimmed)
+ if (!Number.isFinite(parsed) || parsed < 1) return null
+
+ return Math.trunc(parsed)
+}
diff --git a/packages/dashboard-core/src/products/product-form-mapping.ts b/packages/dashboard-core/src/products/product-form-mapping.ts
index 6cc83f0313..55cae40971 100644
--- a/packages/dashboard-core/src/products/product-form-mapping.ts
+++ b/packages/dashboard-core/src/products/product-form-mapping.ts
@@ -31,6 +31,10 @@ export function variantToFormValues(variant: PanelVariant, position: number): Va
hs_code: variant.hs_code ?? null,
country_of_origin: variant.country_of_origin ?? null,
customs_description: variant.customs_description ?? null,
+ minimum_order_quantity: variant.minimum_order_quantity ?? null,
+ order_multiple: variant.order_multiple ?? null,
+ purchase_unit: variant.purchase_unit ?? null,
+ units_per_carton: variant.units_per_carton ?? null,
track_inventory: variant.track_inventory,
preorderable: variant.preorderable ?? false,
preorder_ships_at: variant.preorder_ships_at ?? null,
@@ -173,6 +177,10 @@ export function variantToWirePayload(v: VariantFormValues, index: number) {
hs_code: v.hs_code ?? null,
country_of_origin: v.country_of_origin ?? null,
customs_description: v.customs_description ?? null,
+ minimum_order_quantity: v.minimum_order_quantity ?? null,
+ order_multiple: v.order_multiple ?? null,
+ purchase_unit: v.purchase_unit ?? null,
+ units_per_carton: v.units_per_carton ?? null,
}
if (v.id) payload.id = v.id
if (v.track_inventory != null) payload.track_inventory = v.track_inventory
diff --git a/packages/dashboard-core/src/products/product-schema.ts b/packages/dashboard-core/src/products/product-schema.ts
index cef359702b..68047c8205 100644
--- a/packages/dashboard-core/src/products/product-schema.ts
+++ b/packages/dashboard-core/src/products/product-schema.ts
@@ -49,6 +49,10 @@ export const variantFormSchema = z.object({
hs_code: z.string().nullable().optional(),
country_of_origin: z.string().nullable().optional(),
customs_description: z.string().nullable().optional(),
+ minimum_order_quantity: z.number().int().positive().nullable().optional(),
+ order_multiple: z.number().int().positive().nullable().optional(),
+ purchase_unit: z.string().nullable().optional(),
+ units_per_carton: z.number().int().positive().nullable().optional(),
track_inventory: z.boolean().optional(),
preorderable: z.boolean().optional(),
preorder_ships_at: z.string().nullable().optional(),
@@ -271,6 +275,10 @@ export function isPlaceholderDefaultVariant(v: VariantFormValues): boolean {
!v.hs_code &&
!v.country_of_origin &&
!v.customs_description &&
+ v.minimum_order_quantity == null &&
+ v.order_multiple == null &&
+ v.purchase_unit == null &&
+ v.units_per_carton == null &&
v.preorderable !== true &&
v.preorder_ships_at == null &&
v.backorder_limit == null &&
diff --git a/packages/dashboard-core/src/products/product-types.ts b/packages/dashboard-core/src/products/product-types.ts
index 8098d01a4c..ebe7433e11 100644
--- a/packages/dashboard-core/src/products/product-types.ts
+++ b/packages/dashboard-core/src/products/product-types.ts
@@ -56,6 +56,10 @@ export interface PanelVariant {
hs_code?: string | null
country_of_origin?: string | null
customs_description?: string | null
+ minimum_order_quantity?: number | null
+ order_multiple?: number | null
+ purchase_unit?: string | null
+ units_per_carton?: number | null
track_inventory?: boolean
preorderable?: boolean
preorder_ships_at?: string | null
diff --git a/packages/dashboard-core/src/products/variant-edit-sheet.tsx b/packages/dashboard-core/src/products/variant-edit-sheet.tsx
index fd4046ae84..217e236e79 100644
--- a/packages/dashboard-core/src/products/variant-edit-sheet.tsx
+++ b/packages/dashboard-core/src/products/variant-edit-sheet.tsx
@@ -22,6 +22,7 @@ import { useEffect, useRef } from 'react'
import { Controller, type UseFormReturn } from 'react-hook-form'
import { useTranslation } from 'react-i18next'
import { normalizeCustomsDescription, normalizeHsCode } from './normalize-customs'
+import { normalizeQuantityRule, PURCHASE_UNITS } from './normalize-quantity'
import {
useFormOptionTypes as useOptionTypes,
useFormTaxCategories as useTaxCategories,
@@ -327,6 +328,102 @@ export function VariantEditSheet({ form, variantIndex, open, onOpenChange }: Pro
</Field>
</Section>
+ <Section title={t('admin.products.variants.sheet.ordering')}>
+ <p className="text-sm text-muted-foreground">
+ {t('admin.products.variants.sheet.ordering_help')}
+ </p>
+ <div className="grid grid-cols-2 gap-3">
+ <Field>
+ <FieldLabel htmlFor={`variant-${variantIndex}-moq`}>
+ {t('admin.fields.variant.minimum_order_quantity.label')}
+ </FieldLabel>
+ <Input
+ id={`variant-${variantIndex}-moq`}
+ type="number"
+ min="1"
+ step="1"
+ placeholder={t('admin.fields.variant.minimum_order_quantity.placeholder')}
+ {...form.register(`variants.${variantIndex}.minimum_order_quantity`, {
+ setValueAs: normalizeQuantityRule,
+ })}
+ />
+ <FieldError
+ errors={[form.formState.errors.variants?.[variantIndex]?.minimum_order_quantity]}
+ />
+ </Field>
+ <Field>
+ <FieldLabel htmlFor={`variant-${variantIndex}-order-multiple`}>
+ {t('admin.fields.variant.order_multiple.label')}
+ </FieldLabel>
+ <Input
+ id={`variant-${variantIndex}-order-multiple`}
+ type="number"
+ min="1"
+ step="1"
+ placeholder={t('admin.fields.variant.order_multiple.placeholder')}
+ {...form.register(`variants.${variantIndex}.order_multiple`, {
+ setValueAs: normalizeQuantityRule,
+ })}
+ />
+ <FieldError
+ errors={[form.formState.errors.variants?.[variantIndex]?.order_multiple]}
+ />
+ </Field>
+ <Field>
+ <FieldLabel htmlFor={`variant-${variantIndex}-purchase-unit`}>
+ {t('admin.fields.variant.purchase_unit.label')}
+ </FieldLabel>
+ <Controller
+ name={`variants.${variantIndex}.purchase_unit`}
+ control={form.control}
+ render={({ field }) => (
+ <Select
+ value={field.value ?? ''}
+ onValueChange={(v) => field.onChange(v || null)}
+ >
+ <SelectTrigger
+ id={`variant-${variantIndex}-purchase-unit`}
+ className="w-full"
+ >
+ <SelectValue>
+ {(v) =>
+ v
+ ? t(`admin.fields.variant.purchase_unit.options.${v as string}`)
+ : t('admin.fields.variant.purchase_unit.options.unit')
+ }
+ </SelectValue>
+ </SelectTrigger>
+ <SelectContent>
+ {PURCHASE_UNITS.map((unit) => (
+ <SelectItem key={unit} value={unit}>
+ {t(`admin.fields.variant.purchase_unit.options.${unit}`)}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ )}
+ />
+ </Field>
+ <Field>
+ <FieldLabel htmlFor={`variant-${variantIndex}-units-per-carton`}>
+ {t('admin.fields.variant.units_per_carton.label')}
+ </FieldLabel>
+ <Input
+ id={`variant-${variantIndex}-units-per-carton`}
+ type="number"
+ min="1"
+ step="1"
+ {...form.register(`variants.${variantIndex}.units_per_carton`, {
+ setValueAs: normalizeQuantityRule,
+ })}
+ />
+ <FieldError
+ errors={[form.formState.errors.variants?.[variantIndex]?.units_per_carton]}
+ />
+ </Field>
+ </div>
+ </Section>
+
<Section title={t('admin.products.variants.sheet.availability')}>
<Field>
<div className="flex items-start justify-between gap-4">
diff --git a/packages/dashboard-core/src/products/variants-section.tsx b/packages/dashboard-core/src/products/variants-section.tsx
index bb4200da3c..25d7cc8063 100644
--- a/packages/dashboard-core/src/products/variants-section.tsx
+++ b/packages/dashboard-core/src/products/variants-section.tsx
@@ -226,6 +226,16 @@ export function VariantsSection({ form, seedFromType = false }: Props) {
dimensions_unit: carry?.dimensions_unit ?? null,
track_inventory: carry?.track_inventory ?? true,
tax_category_id: carry?.tax_category_id ?? null,
+ // Carried like the rest: removing the last option type must not
+ // silently wipe the customs classification or the purchasing rules a
+ // merchant entered on the row this collapses into.
+ hs_code: carry?.hs_code ?? null,
+ country_of_origin: carry?.country_of_origin ?? null,
+ customs_description: carry?.customs_description ?? null,
+ minimum_order_quantity: carry?.minimum_order_quantity ?? null,
+ order_multiple: carry?.order_multiple ?? null,
+ purchase_unit: carry?.purchase_unit ?? null,
+ units_per_carton: carry?.units_per_carton ?? null,
prices: carry?.prices ?? [],
stock_levels: carry?.stock_levels ?? [],
}
diff --git a/packages/dashboard/src/components/spree/catalog-terms-card.tsx b/packages/dashboard/src/components/spree/catalog-terms-card.tsx
new file mode 100644
index 0000000000..96f5152ad7
--- /dev/null
+++ b/packages/dashboard/src/components/spree/catalog-terms-card.tsx
@@ -0,0 +1,499 @@
+import type { CatalogOrderMinimum, CatalogQuantityRule, Variant } from '@spree/admin-sdk'
+import { adminClient, CurrencySelect, ResourceCombobox, useStore } from '@spree/dashboard-core'
+import {
+ Button,
+ Card,
+ CardContent,
+ CardDescription,
+ CardHeader,
+ CardTitle,
+ Dialog,
+ DialogBody,
+ DialogContent,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+ Field,
+ FieldDescription,
+ FieldError,
+ FieldGroup,
+ FieldLabel,
+ Input,
+ Pagination,
+ Table,
+ TableBody,
+ TableCell,
+ TableHead,
+ TableHeader,
+ TableRow,
+ useConfirm,
+} from '@spree/dashboard-ui'
+import { PlusIcon, XIcon } from 'lucide-react'
+import { useState } from 'react'
+import type { UseFormReturn } from 'react-hook-form'
+import { useTranslation } from 'react-i18next'
+import {
+ useCatalogQuantityRules,
+ useCreateCatalogOrderMinimum,
+ useCreateCatalogQuantityRule,
+ useDeleteCatalogOrderMinimum,
+ useDeleteCatalogQuantityRule,
+} from '../../hooks/use-catalogs'
+import type { CatalogFormValues } from '../../schemas/catalog'
+
+/**
+ * What this agreement lets a buyer order, and what it requires the whole
+ * order to reach. Three grains in one card because they answer one merchant
+ * question — "how much must they buy?" — at different scopes: the catalog's
+ * own default, the per-SKU exceptions, and the order-level threshold.
+ *
+ * The catalog-wide pair rides the page form and saves with everything else;
+ * the rows below write immediately, since each is its own record
+ * (docs/plans/6.0-b2b-quantity-rules.md).
+ */
+export function CatalogTermsCard({
+ catalogId,
+ form,
+ orderMinimums,
+ canEdit,
+}: {
+ catalogId: string
+ form: UseFormReturn<CatalogFormValues>
+ orderMinimums: CatalogOrderMinimum[]
+ canEdit: boolean
+}) {
+ const { t } = useTranslation()
+
+ return (
+ <Card>
+ <CardHeader>
+ <CardTitle>{t('admin.catalogs.terms.title')}</CardTitle>
+ <CardDescription>{t('admin.catalogs.terms.description')}</CardDescription>
+ </CardHeader>
+ <CardContent className="space-y-8">
+ <CatalogDefaultFields form={form} canEdit={canEdit} />
+ <OrderMinimumsSection
+ catalogId={catalogId}
+ orderMinimums={orderMinimums}
+ canEdit={canEdit}
+ />
+ <QuantityRulesSection catalogId={catalogId} canEdit={canEdit} />
+ </CardContent>
+ </Card>
+ )
+}
+
+/** The catalog-wide default — part of the page form, saved with it. */
+function CatalogDefaultFields({
+ form,
+ canEdit,
+}: {
+ form: UseFormReturn<CatalogFormValues>
+ canEdit: boolean
+}) {
+ const { t } = useTranslation()
+ const errors = form.formState.errors
+
+ return (
+ <FieldGroup className="sm:grid sm:grid-cols-2 sm:gap-4">
+ <Field>
+ <FieldLabel htmlFor="catalog-moq">
+ {t('admin.fields.minimum_order_quantity.label')}
+ </FieldLabel>
+ <Input
+ id="catalog-moq"
+ type="number"
+ min={1}
+ step={1}
+ disabled={!canEdit}
+ aria-invalid={!!errors.minimum_order_quantity}
+ placeholder={t('admin.catalogs.terms.no_rule_placeholder')}
+ {...form.register('minimum_order_quantity')}
+ />
+ <FieldDescription>{t('admin.fields.minimum_order_quantity.help')}</FieldDescription>
+ {errors.minimum_order_quantity && (
+ <FieldError>{errors.minimum_order_quantity.message}</FieldError>
+ )}
+ </Field>
+
+ <Field>
+ <FieldLabel htmlFor="catalog-multiple">{t('admin.fields.order_multiple.label')}</FieldLabel>
+ <Input
+ id="catalog-multiple"
+ type="number"
+ min={1}
+ step={1}
+ disabled={!canEdit}
+ aria-invalid={!!errors.order_multiple}
+ placeholder={t('admin.catalogs.terms.no_rule_placeholder')}
+ {...form.register('order_multiple')}
+ />
+ <FieldDescription>{t('admin.fields.order_multiple.help')}</FieldDescription>
+ {errors.order_multiple && <FieldError>{errors.order_multiple.message}</FieldError>}
+ </Field>
+ </FieldGroup>
+ )
+}
+
+/** One row per currency — never one amount with a currency beside it. */
+function OrderMinimumsSection({
+ catalogId,
+ orderMinimums,
+ canEdit,
+}: {
+ catalogId: string
+ orderMinimums: CatalogOrderMinimum[]
+ canEdit: boolean
+}) {
+ const { t } = useTranslation()
+ const confirm = useConfirm()
+ const [dialogOpen, setDialogOpen] = useState(false)
+ const deleteMutation = useDeleteCatalogOrderMinimum(catalogId)
+
+ async function handleDelete(minimum: CatalogOrderMinimum) {
+ const confirmed = await confirm({
+ title: t('admin.catalogs.terms.remove_minimum_title'),
+ message: t('admin.catalogs.terms.remove_minimum_description', {
+ currency: minimum.currency,
+ }),
+ confirmLabel: t('admin.actions.remove'),
+ variant: 'destructive',
+ })
+ if (confirmed) await deleteMutation.mutateAsync(minimum.id).catch(() => undefined)
+ }
+
+ return (
+ <section className="space-y-3">
+ <header className="flex items-center justify-between">
+ <div>
+ <h3 className="text-sm font-medium">{t('admin.catalogs.terms.minimums_title')}</h3>
+ <p className="text-muted-foreground text-sm">
+ {t('admin.catalogs.terms.minimums_description')}
+ </p>
+ </div>
+ {canEdit && (
+ <Button type="button" variant="outline" size="sm" onClick={() => setDialogOpen(true)}>
+ <PlusIcon />
+ {t('admin.actions.add')}
+ </Button>
+ )}
+ </header>
+
+ {orderMinimums.length === 0 ? (
+ <p className="text-muted-foreground text-sm">{t('admin.catalogs.terms.minimums_empty')}</p>
+ ) : (
+ <Table>
+ <TableBody>
+ {orderMinimums.map((minimum) => (
+ <TableRow key={minimum.id}>
+ <TableCell className="font-medium">{minimum.currency}</TableCell>
+ <TableCell>{minimum.display_amount}</TableCell>
+ <TableCell className="w-10 text-right">
+ {canEdit && (
+ <Button
+ type="button"
+ variant="ghost"
+ size="icon"
+ aria-label={t('admin.actions.remove')}
+ onClick={() => handleDelete(minimum)}
+ >
+ <XIcon />
+ </Button>
+ )}
+ </TableCell>
+ </TableRow>
+ ))}
+ </TableBody>
+ </Table>
+ )}
+
+ <AddOrderMinimumDialog
+ catalogId={catalogId}
+ open={dialogOpen}
+ onOpenChange={setDialogOpen}
+ usedCurrencies={orderMinimums.map((minimum) => minimum.currency)}
+ />
+ </section>
+ )
+}
+
+function AddOrderMinimumDialog({
+ catalogId,
+ open,
+ onOpenChange,
+ usedCurrencies,
+}: {
+ catalogId: string
+ open: boolean
+ onOpenChange: (open: boolean) => void
+ usedCurrencies: string[]
+}) {
+ const { t } = useTranslation()
+ const { store } = useStore()
+ const createMutation = useCreateCatalogOrderMinimum(catalogId)
+ const [currency, setCurrency] = useState(store?.default_currency ?? 'USD')
+ const [amount, setAmount] = useState('')
+
+ const duplicate = usedCurrencies.includes(currency)
+
+ async function handleSubmit() {
+ if (!amount.trim() || duplicate) return
+
+ await createMutation
+ .mutateAsync({ currency, amount })
+ .then(() => {
+ setAmount('')
+ onOpenChange(false)
+ })
+ .catch(() => undefined)
+ }
+
+ return (
+ <Dialog open={open} onOpenChange={onOpenChange}>
+ <DialogContent>
+ <DialogHeader>
+ <DialogTitle>{t('admin.catalogs.terms.add_minimum_title')}</DialogTitle>
+ </DialogHeader>
+ <DialogBody>
+ <FieldGroup>
+ <Field>
+ <FieldLabel>{t('admin.fields.currency.label')}</FieldLabel>
+ <CurrencySelect value={currency} onChange={setCurrency} />
+ {duplicate && (
+ <FieldError>{t('admin.catalogs.terms.validation.currency_taken')}</FieldError>
+ )}
+ </Field>
+ <Field>
+ <FieldLabel htmlFor="minimum-amount">
+ {t('admin.catalogs.terms.minimum_amount_label')}
+ </FieldLabel>
+ <Input
+ id="minimum-amount"
+ inputMode="decimal"
+ value={amount}
+ onChange={(event) => setAmount(event.target.value)}
+ />
+ </Field>
+ </FieldGroup>
+ </DialogBody>
+ <DialogFooter>
+ <Button type="button" variant="outline" onClick={() => onOpenChange(false)}>
+ {t('admin.actions.cancel')}
+ </Button>
+ <Button
+ type="button"
+ disabled={createMutation.isPending || !amount.trim() || duplicate}
+ onClick={handleSubmit}
+ >
+ {t('admin.actions.add')}
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ )
+}
+
+/** The per-variant overrides, paged — an agreement may name thousands. */
+function QuantityRulesSection({ catalogId, canEdit }: { catalogId: string; canEdit: boolean }) {
+ const { t } = useTranslation()
+ const confirm = useConfirm()
+ const [page, setPage] = useState(1)
+ const [dialogOpen, setDialogOpen] = useState(false)
+ const { data } = useCatalogQuantityRules(catalogId, page)
+ const deleteMutation = useDeleteCatalogQuantityRule(catalogId)
+
+ const rules = data?.data ?? []
+
+ async function handleDelete(rule: CatalogQuantityRule) {
+ const confirmed = await confirm({
+ title: t('admin.catalogs.terms.remove_rule_title'),
+ message: t('admin.catalogs.terms.remove_rule_description', {
+ name: rule.product_name ?? rule.variant_sku ?? '',
+ }),
+ confirmLabel: t('admin.actions.remove'),
+ variant: 'destructive',
+ })
+ if (confirmed) await deleteMutation.mutateAsync(rule.id).catch(() => undefined)
+ }
+
+ return (
+ <section className="space-y-3">
+ <header className="flex items-center justify-between">
+ <div>
+ <h3 className="text-sm font-medium">{t('admin.catalogs.terms.overrides_title')}</h3>
+ <p className="text-muted-foreground text-sm">
+ {t('admin.catalogs.terms.overrides_description')}
+ </p>
+ </div>
+ {canEdit && (
+ <Button type="button" variant="outline" size="sm" onClick={() => setDialogOpen(true)}>
+ <PlusIcon />
+ {t('admin.actions.add')}
+ </Button>
+ )}
+ </header>
+
+ {rules.length === 0 ? (
+ <p className="text-muted-foreground text-sm">{t('admin.catalogs.terms.overrides_empty')}</p>
+ ) : (
+ <>
+ <Table>
+ <TableHeader>
+ <TableRow>
+ <TableHead>{t('admin.catalogs.terms.product_column')}</TableHead>
+ <TableHead>{t('admin.fields.minimum_order_quantity.label')}</TableHead>
+ <TableHead>{t('admin.fields.order_multiple.label')}</TableHead>
+ <TableHead className="w-10" />
+ </TableRow>
+ </TableHeader>
+ <TableBody>
+ {rules.map((rule) => (
+ <TableRow key={rule.id}>
+ <TableCell>
+ <span className="font-medium">{rule.product_name}</span>
+ {rule.options_text && (
+ <span className="text-muted-foreground"> · {rule.options_text}</span>
+ )}
+ {rule.variant_sku && (
+ <span className="text-muted-foreground block text-xs">
+ {rule.variant_sku}
+ </span>
+ )}
+ </TableCell>
+ <TableCell>{rule.minimum_order_quantity ?? '—'}</TableCell>
+ <TableCell>{rule.order_multiple ?? '—'}</TableCell>
+ <TableCell className="text-right">
+ {canEdit && (
+ <Button
+ type="button"
+ variant="ghost"
+ size="icon"
+ aria-label={t('admin.actions.remove')}
+ onClick={() => handleDelete(rule)}
+ >
+ <XIcon />
+ </Button>
+ )}
+ </TableCell>
+ </TableRow>
+ ))}
+ </TableBody>
+ </Table>
+ {data?.meta && <Pagination meta={data.meta} onPageChange={setPage} />}
+ </>
+ )}
+
+ <AddQuantityRuleDialog catalogId={catalogId} open={dialogOpen} onOpenChange={setDialogOpen} />
+ </section>
+ )
+}
+
+function AddQuantityRuleDialog({
+ catalogId,
+ open,
+ onOpenChange,
+}: {
+ catalogId: string
+ open: boolean
+ onOpenChange: (open: boolean) => void
+}) {
+ const { t } = useTranslation()
+ const createMutation = useCreateCatalogQuantityRule(catalogId)
+ const [variantId, setVariantId] = useState('')
+ const [minimum, setMinimum] = useState('')
+ const [multiple, setMultiple] = useState('')
+
+ // A row must state at least one field: an override that overrides nothing
+ // is a half-filled form, and the server refuses it anyway.
+ const statesSomething = !!minimum.trim() || !!multiple.trim()
+
+ async function handleSubmit() {
+ if (!variantId || !statesSomething) return
+
+ await createMutation
+ .mutateAsync({
+ variant_id: variantId,
+ minimum_order_quantity: minimum.trim() ? Number(minimum) : null,
+ order_multiple: multiple.trim() ? Number(multiple) : null,
+ })
+ .then(() => {
+ setVariantId('')
+ setMinimum('')
+ setMultiple('')
+ onOpenChange(false)
+ })
+ .catch(() => undefined)
+ }
+
+ return (
+ <Dialog open={open} onOpenChange={onOpenChange}>
+ <DialogContent>
+ <DialogHeader>
+ <DialogTitle>{t('admin.catalogs.terms.add_rule_title')}</DialogTitle>
+ </DialogHeader>
+ <DialogBody>
+ <FieldGroup>
+ <Field>
+ <FieldLabel>{t('admin.catalogs.terms.product_column')}</FieldLabel>
+ <ResourceCombobox<Variant>
+ queryKey="catalog-term-variants"
+ search={(query) =>
+ adminClient.variants.list({ product_name_or_sku_cont: query, limit: 10 })
+ }
+ hydrate={(ids) => adminClient.variants.list({ id_in: ids, limit: ids.length })}
+ getOptionLabel={(variant) =>
+ [variant.product_name, variant.options_text, variant.sku]
+ .filter(Boolean)
+ .join(' · ')
+ }
+ placeholder={t('admin.catalogs.terms.variant_placeholder')}
+ emptyText={t('admin.catalogs.terms.variant_empty')}
+ value={variantId || undefined}
+ onChange={(id) => setVariantId(id ?? '')}
+ />
+ </Field>
+ <Field>
+ <FieldLabel htmlFor="rule-minimum">
+ {t('admin.fields.minimum_order_quantity.label')}
+ </FieldLabel>
+ <Input
+ id="rule-minimum"
+ type="number"
+ min={1}
+ step={1}
+ value={minimum}
+ onChange={(event) => setMinimum(event.target.value)}
+ />
+ </Field>
+ <Field>
+ <FieldLabel htmlFor="rule-multiple">
+ {t('admin.fields.order_multiple.label')}
+ </FieldLabel>
+ <Input
+ id="rule-multiple"
+ type="number"
+ min={1}
+ step={1}
+ value={multiple}
+ onChange={(event) => setMultiple(event.target.value)}
+ />
+ <FieldDescription>{t('admin.catalogs.terms.override_help')}</FieldDescription>
+ </Field>
+ </FieldGroup>
+ </DialogBody>
+ <DialogFooter>
+ <Button type="button" variant="outline" onClick={() => onOpenChange(false)}>
+ {t('admin.actions.cancel')}
+ </Button>
+ <Button
+ type="button"
+ disabled={createMutation.isPending || !variantId || !statesSomething}
+ onClick={handleSubmit}
+ >
+ {t('admin.actions.add')}
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ )
+}
diff --git a/packages/dashboard/src/hooks/use-catalogs.ts b/packages/dashboard/src/hooks/use-catalogs.ts
index fcab170d73..b9fdcf9435 100644
--- a/packages/dashboard/src/hooks/use-catalogs.ts
+++ b/packages/dashboard/src/hooks/use-catalogs.ts
@@ -2,7 +2,11 @@ import type {
Catalog,
CatalogAssignment,
CatalogAssignParams,
+ CatalogOrderMinimum,
+ CatalogOrderMinimumParams,
CatalogParams,
+ CatalogQuantityRule,
+ CatalogQuantityRuleParams,
} from '@spree/admin-sdk'
import {
adminClient,
@@ -18,7 +22,7 @@ export function useCatalog(id: string | undefined) {
queryKey: useResourceKey('catalogs', id ?? 'noop'),
queryFn: () =>
adminClient.catalogs.get(id as string, {
- expand: ['assignments', 'price_list', 'price_list.price_rules'],
+ expand: ['assignments', 'price_list', 'price_list.price_rules', 'order_minimums'],
}),
enabled: !!id,
})
@@ -138,3 +142,81 @@ export function useUnassignCatalog(catalogId: string) {
errorMessage: i18n.t('admin.errors.failed_to_update'),
})
}
+
+// ---------------------------------------------------------------------------
+// Commercial terms — what the buyer may order, and what the order must reach
+// ---------------------------------------------------------------------------
+
+/**
+ * The per-variant quantity overrides. Paginated rather than capped: an
+ * agreement can name terms for thousands of SKUs, and a silent limit would
+ * hide the rest while still calling itself the list.
+ */
+export function useCatalogQuantityRules(catalogId: string | undefined, page = 1) {
+ return useQuery({
+ queryKey: useResourceKey('catalogs', catalogId ?? 'noop', 'quantity_rules', `${page}`),
+ queryFn: () =>
+ adminClient.catalogs.quantityRules.list(catalogId as string, { page, limit: 25 }),
+ enabled: !!catalogId,
+ placeholderData: (previous) => previous,
+ })
+}
+
+export function useCreateCatalogQuantityRule(catalogId: string) {
+ return useResourceMutation<CatalogQuantityRule, Error, CatalogQuantityRuleParams>({
+ mutationFn: (params) => adminClient.catalogs.quantityRules.create(catalogId, params),
+ invalidate: [
+ ['catalogs', catalogId],
+ ['catalogs', catalogId, 'quantity_rules'],
+ ],
+ successMessage: i18n.t('admin.catalogs.terms.messages.rule_created'),
+ errorMessage: i18n.t('admin.errors.failed_to_create'),
+ })
+}
+
+export function useUpdateCatalogQuantityRule(catalogId: string) {
+ return useResourceMutation<
+ CatalogQuantityRule,
+ Error,
+ { id: string; params: CatalogQuantityRuleParams }
+ >({
+ mutationFn: ({ id, params }) =>
+ adminClient.catalogs.quantityRules.update(catalogId, id, params),
+ invalidate: [
+ ['catalogs', catalogId],
+ ['catalogs', catalogId, 'quantity_rules'],
+ ],
+ successMessage: i18n.t('admin.catalogs.terms.messages.rule_updated'),
+ errorMessage: i18n.t('admin.errors.failed_to_update'),
+ })
+}
+
+export function useDeleteCatalogQuantityRule(catalogId: string) {
+ return useResourceMutation<void, Error, string>({
+ mutationFn: (id) => adminClient.catalogs.quantityRules.delete(catalogId, id),
+ invalidate: [
+ ['catalogs', catalogId],
+ ['catalogs', catalogId, 'quantity_rules'],
+ ],
+ successMessage: i18n.t('admin.catalogs.terms.messages.rule_deleted'),
+ errorMessage: i18n.t('admin.errors.failed_to_delete'),
+ })
+}
+
+export function useCreateCatalogOrderMinimum(catalogId: string) {
+ return useResourceMutation<CatalogOrderMinimum, Error, CatalogOrderMinimumParams>({
+ mutationFn: (params) => adminClient.catalogs.orderMinimums.create(catalogId, params),
+ invalidate: [['catalogs'], ['catalogs', catalogId]],
+ successMessage: i18n.t('admin.catalogs.terms.messages.minimum_created'),
+ errorMessage: i18n.t('admin.errors.failed_to_create'),
+ })
+}
+
+export function useDeleteCatalogOrderMinimum(catalogId: string) {
+ return useResourceMutation<void, Error, string>({
+ mutationFn: (id) => adminClient.catalogs.orderMinimums.delete(catalogId, id),
+ invalidate: [['catalogs'], ['catalogs', catalogId]],
+ successMessage: i18n.t('admin.catalogs.terms.messages.minimum_deleted'),
+ errorMessage: i18n.t('admin.errors.failed_to_delete'),
+ })
+}
diff --git a/packages/dashboard/src/locales/ar.json b/packages/dashboard/src/locales/ar.json
index 7f2df500a4..85f69e38cf 100644
--- a/packages/dashboard/src/locales/ar.json
+++ b/packages/dashboard/src/locales/ar.json
@@ -156,7 +156,40 @@
"title": "المنتجات"
},
"products_column": "المنتجات",
- "search_placeholder": "البحث في الكتالوجات"
+ "search_placeholder": "البحث في الكتالوجات",
+ "terms": {
+ "title": "الشروط التجارية",
+ "description": "الكمية التي يجب على المشترين ضمن هذه الاتفاقية طلبها.",
+ "no_rule_placeholder": "بلا قاعدة",
+ "minimums_title": "الحدود الدنيا للطلب",
+ "minimums_description": "أقل قيمة يجب أن يبلغها الطلب بالكامل، لكل عملة.",
+ "minimums_empty": "لا يوجد حد أدنى للطلب. يمكن للمشترين إتمام الشراء بأي إجمالي.",
+ "overrides_title": "قواعد لكل منتج",
+ "overrides_description": "قواعد الكمية لمنتجات محددة، تتجاوز الإعداد الافتراضي أعلاه.",
+ "overrides_empty": "لا توجد قواعد لكل منتج. تستخدم كل المنتجات الإعداد الافتراضي أعلاه.",
+ "product_column": "المنتج",
+ "add_minimum_title": "إضافة حد أدنى للطلب",
+ "minimum_amount_label": "المبلغ الأدنى",
+ "add_rule_title": "إضافة قاعدة منتج",
+ "variant_placeholder": "البحث عن المنتجات",
+ "variant_empty": "لم يتم العثور على منتجات",
+ "override_help": "اترك الحقل فارغًا للرجوع إلى الإعداد الافتراضي أعلاه.",
+ "remove_minimum_title": "إزالة الحد الأدنى للطلب؟",
+ "remove_minimum_description": "لن تحتاج الطلبات بعملة {{currency}} إلى بلوغ حد أدنى. يسري هذا فورًا.",
+ "remove_rule_title": "إزالة قاعدة المنتج؟",
+ "remove_rule_description": "سيعود {{name}} إلى الإعداد الافتراضي للكتالوج. يسري هذا فورًا.",
+ "validation": {
+ "positive_integer": "أدخل عددًا صحيحًا أكبر من صفر، أو اترك الحقل فارغًا.",
+ "currency_taken": "هذه العملة لديها حد أدنى بالفعل."
+ },
+ "messages": {
+ "rule_created": "تمت إضافة قاعدة المنتج",
+ "rule_updated": "تم تحديث قاعدة المنتج",
+ "rule_deleted": "تمت إزالة قاعدة المنتج",
+ "minimum_created": "تمت إضافة الحد الأدنى للطلب",
+ "minimum_deleted": "تمت إزالة الحد الأدنى للطلب"
+ }
+ }
},
"categories": {
"add_cta": "فئة جديدة",
@@ -2130,6 +2163,26 @@
},
"width": {
"label": "العرض"
+ },
+ "minimum_order_quantity": {
+ "label": "الحد الأدنى لكمية الطلب",
+ "placeholder": "بلا حد أدنى",
+ "help": "أقل كمية يمكن للمشتري طلبها. اتركه فارغًا لعدم وجود حد أدنى."
+ },
+ "order_multiple": {
+ "label": "مضاعف الطلب",
+ "placeholder": "بلا مضاعف",
+ "help": "يجب أن تكون الطلبات من مضاعفات هذا الرقم. اتركه فارغًا للسماح بأي كمية."
+ },
+ "purchase_unit": {
+ "label": "وحدة الشراء",
+ "options": {
+ "unit": "وحدات",
+ "carton": "كراتين"
+ }
+ },
+ "units_per_carton": {
+ "label": "الوحدات في الكرتونة"
}
},
"webhook_endpoint": {
@@ -2150,6 +2203,14 @@
"label": "Destination URL",
"placeholder": "https://example.com/webhooks"
}
+ },
+ "minimum_order_quantity": {
+ "label": "الحد الأدنى لكمية الطلب",
+ "help": "أقل كمية يمكن للمشتري طلبها. اتركه فارغًا لعدم وجود حد أدنى."
+ },
+ "order_multiple": {
+ "label": "مضاعف الطلب",
+ "help": "يجب أن تكون الطلبات من مضاعفات هذا الرقم. اتركه فارغًا للسماح بأي كمية."
}
},
"gift_cards": {
@@ -3923,7 +3984,9 @@
"customs": "الجمارك",
"customs_help": "يُستخدم في نماذج الجمارك عند شحن هذا المنتج عبر الحدود.",
"identity": "هوية",
- "tax_category_placeholder": "ترث من المنتج"
+ "tax_category_placeholder": "ترث من المنتج",
+ "ordering": "الطلب للشركات",
+ "ordering_help": "الكمية التي يجب على المشتري أخذها. لا يزال المخزون يُحسب بالوحدات."
},
"title": "المتغيرات",
"variant_label": "البديل"
diff --git a/packages/dashboard/src/locales/de.json b/packages/dashboard/src/locales/de.json
index c016e3c9d2..f9874d98d9 100644
--- a/packages/dashboard/src/locales/de.json
+++ b/packages/dashboard/src/locales/de.json
@@ -156,7 +156,40 @@
"title": "Produkte"
},
"products_column": "Produkte",
- "search_placeholder": "Kataloge suchen"
+ "search_placeholder": "Kataloge suchen",
+ "terms": {
+ "title": "Handelsbedingungen",
+ "description": "Wie viel Käufer dieser Vereinbarung bestellen müssen.",
+ "no_rule_placeholder": "Keine Regel",
+ "minimums_title": "Mindestbestellwerte",
+ "minimums_description": "Der Mindestwert einer gesamten Bestellung, je Währung.",
+ "minimums_empty": "Kein Mindestbestellwert. Käufer können mit jeder Summe bestellen.",
+ "overrides_title": "Produktbezogene Regeln",
+ "overrides_description": "Mengenregeln für einzelne Produkte, die den Standard oben überschreiben.",
+ "overrides_empty": "Keine produktbezogenen Regeln. Alle Produkte nutzen den Standard oben.",
+ "product_column": "Produkt",
+ "add_minimum_title": "Mindestbestellwert hinzufügen",
+ "minimum_amount_label": "Mindestbetrag",
+ "add_rule_title": "Produktregel hinzufügen",
+ "variant_placeholder": "Produkte suchen",
+ "variant_empty": "Keine Produkte gefunden",
+ "override_help": "Feld leer lassen, um auf den Standard oben zurückzufallen.",
+ "remove_minimum_title": "Mindestbestellwert entfernen?",
+ "remove_minimum_description": "Bestellungen in {{currency}} benötigen keinen Mindestwert mehr. Dies wirkt sofort.",
+ "remove_rule_title": "Produktregel entfernen?",
+ "remove_rule_description": "{{name}} nutzt wieder den Katalogstandard. Dies wirkt sofort.",
+ "validation": {
+ "positive_integer": "Geben Sie eine ganze Zahl größer als null ein oder lassen Sie das Feld leer.",
+ "currency_taken": "Für diese Währung gibt es bereits einen Mindestwert."
+ },
+ "messages": {
+ "rule_created": "Produktregel hinzugefügt",
+ "rule_updated": "Produktregel aktualisiert",
+ "rule_deleted": "Produktregel entfernt",
+ "minimum_created": "Mindestbestellwert hinzugefügt",
+ "minimum_deleted": "Mindestbestellwert entfernt"
+ }
+ }
},
"categories": {
"add_cta": "Neue Kategorie",
@@ -2116,6 +2149,26 @@
},
"width": {
"label": "Breite"
+ },
+ "minimum_order_quantity": {
+ "label": "Mindestbestellmenge",
+ "placeholder": "Kein Minimum",
+ "help": "Die geringste Menge, die ein Käufer bestellen darf. Leer lassen für kein Minimum."
+ },
+ "order_multiple": {
+ "label": "Bestellvielfaches",
+ "placeholder": "Kein Vielfaches",
+ "help": "Bestellungen müssen ein Vielfaches davon sein. Leer lassen für beliebige Mengen."
+ },
+ "purchase_unit": {
+ "label": "Verkaufseinheit",
+ "options": {
+ "unit": "Stück",
+ "carton": "Kartons"
+ }
+ },
+ "units_per_carton": {
+ "label": "Stück pro Karton"
}
},
"webhook_endpoint": {
@@ -2136,6 +2189,14 @@
"label": "Ziel-URL",
"placeholder": "https://example.com/webhooks"
}
+ },
+ "minimum_order_quantity": {
+ "label": "Mindestbestellmenge",
+ "help": "Die geringste Menge, die ein Käufer bestellen darf. Leer lassen für kein Minimum."
+ },
+ "order_multiple": {
+ "label": "Bestellvielfaches",
+ "help": "Bestellungen müssen ein Vielfaches davon sein. Leer lassen für beliebige Mengen."
}
},
"gift_cards": {
@@ -3905,7 +3966,9 @@
"customs": "Zoll",
"customs_help": "Wird auf Zollformularen verwendet, wenn dieser Artikel eine Grenze überquert.",
"identity": "Identität",
- "tax_category_placeholder": "Vom Produkt übernehmen"
+ "tax_category_placeholder": "Vom Produkt übernehmen",
+ "ordering": "B2B-Bestellung",
+ "ordering_help": "Wie viel ein Käufer abnehmen muss. Der Bestand wird weiterhin in Stück gezählt."
},
"title": "Varianten",
"variant_label": "Variante"
diff --git a/packages/dashboard/src/locales/en.json b/packages/dashboard/src/locales/en.json
index c24a6aa5ac..6d933ccb18 100644
--- a/packages/dashboard/src/locales/en.json
+++ b/packages/dashboard/src/locales/en.json
@@ -156,7 +156,40 @@
"title": "Products"
},
"products_column": "Products",
- "search_placeholder": "Search catalogs"
+ "search_placeholder": "Search catalogs",
+ "terms": {
+ "title": "Commercial terms",
+ "description": "How much buyers on this agreement must order.",
+ "no_rule_placeholder": "No rule",
+ "minimums_title": "Order minimums",
+ "minimums_description": "The least a whole order must come to, per currency.",
+ "minimums_empty": "No order minimum. Buyers may check out with any total.",
+ "overrides_title": "Per-product rules",
+ "overrides_description": "Quantity rules for specific products, overriding the default above.",
+ "overrides_empty": "No per-product rules. Every product uses the default above.",
+ "product_column": "Product",
+ "add_minimum_title": "Add order minimum",
+ "minimum_amount_label": "Minimum amount",
+ "add_rule_title": "Add product rule",
+ "variant_placeholder": "Search products",
+ "variant_empty": "No products found",
+ "override_help": "Leave a field blank to fall back to the default above.",
+ "remove_minimum_title": "Remove order minimum?",
+ "remove_minimum_description": "Orders in {{currency}} will no longer need to reach a minimum. This takes effect immediately.",
+ "remove_rule_title": "Remove product rule?",
+ "remove_rule_description": "{{name}} will fall back to the catalog default. This takes effect immediately.",
+ "validation": {
+ "positive_integer": "Enter a whole number greater than zero, or leave blank.",
+ "currency_taken": "This currency already has a minimum."
+ },
+ "messages": {
+ "rule_created": "Product rule added",
+ "rule_updated": "Product rule updated",
+ "rule_deleted": "Product rule removed",
+ "minimum_created": "Order minimum added",
+ "minimum_deleted": "Order minimum removed"
+ }
+ }
},
"categories": {
"add_cta": "New category",
@@ -2116,6 +2149,26 @@
},
"width": {
"label": "Width"
+ },
+ "minimum_order_quantity": {
+ "label": "Minimum order quantity",
+ "placeholder": "No minimum",
+ "help": "The least a buyer may order. Leave blank for no minimum."
+ },
+ "order_multiple": {
+ "label": "Order multiple",
+ "placeholder": "No multiple",
+ "help": "Orders must be a multiple of this. Leave blank for any quantity."
+ },
+ "purchase_unit": {
+ "label": "Purchase unit",
+ "options": {
+ "unit": "Units",
+ "carton": "Cartons"
+ }
+ },
+ "units_per_carton": {
+ "label": "Units per carton"
}
},
"webhook_endpoint": {
@@ -2136,6 +2189,14 @@
"label": "Destination URL",
"placeholder": "https://example.com/webhooks"
}
+ },
+ "minimum_order_quantity": {
+ "label": "Minimum order quantity",
+ "help": "The least a buyer may order. Leave blank for no minimum."
+ },
+ "order_multiple": {
+ "label": "Order multiple",
+ "help": "Orders must be a multiple of this. Leave blank for any quantity."
}
},
"gift_cards": {
@@ -3905,7 +3966,9 @@
"customs": "Customs",
"customs_help": "Used on customs forms when this item ships across a border.",
"identity": "Identity",
- "tax_category_placeholder": "Inherit from product"
+ "tax_category_placeholder": "Inherit from product",
+ "ordering": "B2B ordering",
+ "ordering_help": "How much a buyer must take. Stock is still counted in units."
},
"title": "Variants",
"variant_label": "Variant"
diff --git a/packages/dashboard/src/locales/fr.json b/packages/dashboard/src/locales/fr.json
index b3742b4dfc..37133ebb49 100644
--- a/packages/dashboard/src/locales/fr.json
+++ b/packages/dashboard/src/locales/fr.json
@@ -156,7 +156,40 @@
"title": "Produits"
},
"products_column": "Produits",
- "search_placeholder": "Rechercher des catalogues"
+ "search_placeholder": "Rechercher des catalogues",
+ "terms": {
+ "title": "Conditions commerciales",
+ "description": "Combien les acheteurs de cet accord doivent commander.",
+ "no_rule_placeholder": "Aucune règle",
+ "minimums_title": "Minimums de commande",
+ "minimums_description": "Le montant minimal d'une commande entière, par devise.",
+ "minimums_empty": "Aucun minimum de commande. Les acheteurs peuvent commander tout montant.",
+ "overrides_title": "Règles par produit",
+ "overrides_description": "Règles de quantité pour des produits précis, qui remplacent la valeur par défaut ci-dessus.",
+ "overrides_empty": "Aucune règle par produit. Tous les produits utilisent la valeur par défaut ci-dessus.",
+ "product_column": "Produit",
+ "add_minimum_title": "Ajouter un minimum de commande",
+ "minimum_amount_label": "Montant minimal",
+ "add_rule_title": "Ajouter une règle produit",
+ "variant_placeholder": "Rechercher des produits",
+ "variant_empty": "Aucun produit trouvé",
+ "override_help": "Laisser un champ vide pour revenir à la valeur par défaut ci-dessus.",
+ "remove_minimum_title": "Supprimer le minimum de commande ?",
+ "remove_minimum_description": "Les commandes en {{currency}} n'auront plus de minimum. Effet immédiat.",
+ "remove_rule_title": "Supprimer la règle produit ?",
+ "remove_rule_description": "{{name}} reviendra à la valeur par défaut du catalogue. Effet immédiat.",
+ "validation": {
+ "positive_integer": "Saisissez un nombre entier supérieur à zéro, ou laissez vide.",
+ "currency_taken": "Cette devise a déjà un minimum."
+ },
+ "messages": {
+ "rule_created": "Règle produit ajoutée",
+ "rule_updated": "Règle produit mise à jour",
+ "rule_deleted": "Règle produit supprimée",
+ "minimum_created": "Minimum de commande ajouté",
+ "minimum_deleted": "Minimum de commande supprimé"
+ }
+ }
},
"categories": {
"add_cta": "Nouvelle catégorie",
@@ -2116,6 +2149,26 @@
},
"width": {
"label": "Largeur"
+ },
+ "minimum_order_quantity": {
+ "label": "Quantité minimale de commande",
+ "placeholder": "Aucun minimum",
+ "help": "La plus petite quantité qu'un acheteur peut commander. Laisser vide pour aucun minimum."
+ },
+ "order_multiple": {
+ "label": "Multiple de commande",
+ "placeholder": "Aucun multiple",
+ "help": "Les commandes doivent être un multiple de cette valeur. Laisser vide pour toute quantité."
+ },
+ "purchase_unit": {
+ "label": "Unité de vente",
+ "options": {
+ "unit": "Unités",
+ "carton": "Cartons"
+ }
+ },
+ "units_per_carton": {
+ "label": "Unités par carton"
}
},
"webhook_endpoint": {
@@ -2136,6 +2189,14 @@
"label": "URL de destination",
"placeholder": "https://example.com/webhooks"
}
+ },
+ "minimum_order_quantity": {
+ "label": "Quantité minimale de commande",
+ "help": "La plus petite quantité qu'un acheteur peut commander. Laisser vide pour aucun minimum."
+ },
+ "order_multiple": {
+ "label": "Multiple de commande",
+ "help": "Les commandes doivent être un multiple de cette valeur. Laisser vide pour toute quantité."
}
},
"gift_cards": {
@@ -3905,7 +3966,9 @@
"customs": "Douane",
"customs_help": "Utilisé sur les formulaires douaniers lorsque cet article franchit une frontière.",
"identity": "Identité",
- "tax_category_placeholder": "Hériter du produit"
+ "tax_category_placeholder": "Hériter du produit",
+ "ordering": "Commande B2B",
+ "ordering_help": "Combien un acheteur doit prendre. Le stock reste compté en unités."
},
"title": "Variantes",
"variant_label": "Variante"
diff --git a/packages/dashboard/src/locales/pl.json b/packages/dashboard/src/locales/pl.json
index f6910c7883..c03ae018ea 100644
--- a/packages/dashboard/src/locales/pl.json
+++ b/packages/dashboard/src/locales/pl.json
@@ -158,7 +158,40 @@
"title": "Produkty"
},
"products_column": "Produkty",
- "search_placeholder": "Szukaj katalogów"
+ "search_placeholder": "Szukaj katalogów",
+ "terms": {
+ "title": "Warunki handlowe",
+ "description": "Ile muszą zamawiać kupujący objęci tą umową.",
+ "no_rule_placeholder": "Brak reguły",
+ "minimums_title": "Minimalne wartości zamówienia",
+ "minimums_description": "Najniższa wartość całego zamówienia, dla każdej waluty.",
+ "minimums_empty": "Brak minimalnej wartości zamówienia. Kupujący mogą złożyć zamówienie na dowolną kwotę.",
+ "overrides_title": "Reguły dla produktów",
+ "overrides_description": "Reguły ilości dla wybranych produktów, nadpisujące wartość domyślną powyżej.",
+ "overrides_empty": "Brak reguł dla produktów. Wszystkie produkty używają wartości domyślnej powyżej.",
+ "product_column": "Produkt",
+ "add_minimum_title": "Dodaj minimalną wartość zamówienia",
+ "minimum_amount_label": "Kwota minimalna",
+ "add_rule_title": "Dodaj regułę produktu",
+ "variant_placeholder": "Szukaj produktów",
+ "variant_empty": "Nie znaleziono produktów",
+ "override_help": "Pozostaw pole puste, aby użyć wartości domyślnej powyżej.",
+ "remove_minimum_title": "Usunąć minimalną wartość zamówienia?",
+ "remove_minimum_description": "Zamówienia w {{currency}} nie będą już musiały osiągać minimum. Zmiana działa natychmiast.",
+ "remove_rule_title": "Usunąć regułę produktu?",
+ "remove_rule_description": "{{name}} wróci do wartości domyślnej katalogu. Zmiana działa natychmiast.",
+ "validation": {
+ "positive_integer": "Podaj liczbę całkowitą większą od zera lub pozostaw pole puste.",
+ "currency_taken": "Ta waluta ma już ustawione minimum."
+ },
+ "messages": {
+ "rule_created": "Dodano regułę produktu",
+ "rule_updated": "Zaktualizowano regułę produktu",
+ "rule_deleted": "Usunięto regułę produktu",
+ "minimum_created": "Dodano minimalną wartość zamówienia",
+ "minimum_deleted": "Usunięto minimalną wartość zamówienia"
+ }
+ }
},
"categories": {
"add_cta": "Nowa kategoria",
@@ -2128,6 +2161,26 @@
},
"width": {
"label": "Szerokość"
+ },
+ "minimum_order_quantity": {
+ "label": "Minimalna wielkość zamówienia",
+ "placeholder": "Brak minimum",
+ "help": "Najmniejsza ilość, jaką kupujący może zamówić. Pozostaw puste, aby nie było minimum."
+ },
+ "order_multiple": {
+ "label": "Wielokrotność zamówienia",
+ "placeholder": "Brak wielokrotności",
+ "help": "Zamówienia muszą być wielokrotnością tej liczby. Pozostaw puste, aby dopuścić dowolną ilość."
+ },
+ "purchase_unit": {
+ "label": "Jednostka sprzedaży",
+ "options": {
+ "unit": "Sztuki",
+ "carton": "Kartony"
+ }
+ },
+ "units_per_carton": {
+ "label": "Sztuk w kartonie"
}
},
"webhook_endpoint": {
@@ -2148,6 +2201,14 @@
"label": "Docelowy adres URL",
"placeholder": "https://example.com/webhooks"
}
+ },
+ "minimum_order_quantity": {
+ "label": "Minimalna wielkość zamówienia",
+ "help": "Najmniejsza ilość, jaką kupujący może zamówić. Pozostaw puste, aby nie było minimum."
+ },
+ "order_multiple": {
+ "label": "Wielokrotność zamówienia",
+ "help": "Zamówienia muszą być wielokrotnością tej liczby. Pozostaw puste, aby dopuścić dowolną ilość."
}
},
"gift_cards": {
@@ -3957,7 +4018,9 @@
"customs": "Cło",
"customs_help": "Używane na formularzach celnych, gdy ten produkt przekracza granicę.",
"identity": "Tożsamość",
- "tax_category_placeholder": "Dziedzicz z produktu"
+ "tax_category_placeholder": "Dziedzicz z produktu",
+ "ordering": "Zamówienia B2B",
+ "ordering_help": "Ile kupujący musi wziąć. Stan magazynowy nadal liczony jest w sztukach."
},
"title": "Warianty",
"variant_label": "Wariant"
diff --git a/packages/dashboard/src/locales/zh-CN.json b/packages/dashboard/src/locales/zh-CN.json
index 0e7255bfc1..79737d2e6b 100644
--- a/packages/dashboard/src/locales/zh-CN.json
+++ b/packages/dashboard/src/locales/zh-CN.json
@@ -156,7 +156,40 @@
"title": "产品"
},
"products_column": "产品",
- "search_placeholder": "搜索目录"
+ "search_placeholder": "搜索目录",
+ "terms": {
+ "title": "商务条款",
+ "description": "适用本协议的买家必须订购多少。",
+ "no_rule_placeholder": "无规则",
+ "minimums_title": "订单最低金额",
+ "minimums_description": "整笔订单必须达到的最低金额,按币种设置。",
+ "minimums_empty": "没有订单最低金额。买家可以任意金额结账。",
+ "overrides_title": "单品规则",
+ "overrides_description": "针对特定商品的数量规则,覆盖上面的默认值。",
+ "overrides_empty": "没有单品规则。所有商品都使用上面的默认值。",
+ "product_column": "商品",
+ "add_minimum_title": "添加订单最低金额",
+ "minimum_amount_label": "最低金额",
+ "add_rule_title": "添加商品规则",
+ "variant_placeholder": "搜索商品",
+ "variant_empty": "未找到商品",
+ "override_help": "留空该字段将回退到上面的默认值。",
+ "remove_minimum_title": "移除订单最低金额?",
+ "remove_minimum_description": "{{currency}} 订单将不再需要达到最低金额。此更改立即生效。",
+ "remove_rule_title": "移除商品规则?",
+ "remove_rule_description": "{{name}} 将回退到目录默认值。此更改立即生效。",
+ "validation": {
+ "positive_integer": "请输入大于零的整数,或留空。",
+ "currency_taken": "该币种已设置最低金额。"
+ },
+ "messages": {
+ "rule_created": "已添加商品规则",
+ "rule_updated": "已更新商品规则",
+ "rule_deleted": "已移除商品规则",
+ "minimum_created": "已添加订单最低金额",
+ "minimum_deleted": "已移除订单最低金额"
+ }
+ }
},
"categories": {
"add_cta": "新建分类",
@@ -2112,6 +2145,26 @@
},
"width": {
"label": "宽度"
+ },
+ "minimum_order_quantity": {
+ "label": "最小起订量",
+ "placeholder": "无最小值",
+ "help": "买家可以订购的最小数量。留空表示没有最小值。"
+ },
+ "order_multiple": {
+ "label": "订购倍数",
+ "placeholder": "无倍数",
+ "help": "订单数量必须是该数值的倍数。留空表示不限数量。"
+ },
+ "purchase_unit": {
+ "label": "销售单位",
+ "options": {
+ "unit": "件",
+ "carton": "箱"
+ }
+ },
+ "units_per_carton": {
+ "label": "每箱件数"
}
},
"webhook_endpoint": {
@@ -2132,6 +2185,14 @@
"label": "目标 URL",
"placeholder": "https://example.com/webhooks"
}
+ },
+ "minimum_order_quantity": {
+ "label": "最小起订量",
+ "help": "买家可以订购的最小数量。留空表示没有最小值。"
+ },
+ "order_multiple": {
+ "label": "订购倍数",
+ "help": "订单数量必须是该数值的倍数。留空表示不限数量。"
}
},
"gift_cards": {
@@ -3897,7 +3958,9 @@
"customs": "海关",
"customs_help": "当该商品跨境运输时用于海关申报单。",
"identity": "标识",
- "tax_category_placeholder": "继承自商品"
+ "tax_category_placeholder": "继承自商品",
+ "ordering": "B2B 订购",
+ "ordering_help": "买家必须订购的数量。库存仍以件计算。"
},
"title": "变体",
"variant_label": "变体"
diff --git a/packages/dashboard/src/routes/_authenticated/$storeId/products/catalogs/$catalogId.tsx b/packages/dashboard/src/routes/_authenticated/$storeId/products/catalogs/$catalogId.tsx
index 986ffb6da2..fd5821fd2c 100644
--- a/packages/dashboard/src/routes/_authenticated/$storeId/products/catalogs/$catalogId.tsx
+++ b/packages/dashboard/src/routes/_authenticated/$storeId/products/catalogs/$catalogId.tsx
@@ -46,6 +46,7 @@ import { useEffect, useState } from 'react'
import { Controller, type UseFormReturn, useForm } from 'react-hook-form'
import { useTranslation } from 'react-i18next'
import { CatalogPricingFields } from '../../../../../components/spree/catalog-pricing-fields'
+import { CatalogTermsCard } from '../../../../../components/spree/catalog-terms-card'
import { DeferredProductMembershipCard } from '../../../../../components/spree/deferred-product-membership-card'
import {
ProductMembershipStagingProvider,
@@ -130,6 +131,8 @@ function CatalogBody({ catalog }: { catalog: Catalog }) {
name: catalog.name,
description: catalog.description ?? '',
active: catalog.active,
+ minimum_order_quantity: catalog.minimum_order_quantity?.toString() ?? '',
+ order_multiple: catalog.order_multiple?.toString() ?? '',
...catalogPricingValues(catalog.price_list),
staged_products: { adds: [], removes: [] },
})
@@ -215,6 +218,12 @@ function CatalogBody({ catalog }: { catalog: Catalog }) {
<>
<CatalogSettingsCard form={form} canEdit={canEdit} />
<CatalogPricingCard catalog={catalog} form={form} canEdit={canEdit} />
+ <CatalogTermsCard
+ catalogId={catalog.id}
+ form={form}
+ orderMinimums={catalog.order_minimums ?? []}
+ canEdit={canEdit}
+ />
<CatalogAssignmentsCard catalog={catalog} canEdit={canEdit} />
</>
}
diff --git a/packages/dashboard/src/routes/_authenticated/$storeId/products/new.tsx b/packages/dashboard/src/routes/_authenticated/$storeId/products/new.tsx
index e341375e82..4c943d518d 100644
--- a/packages/dashboard/src/routes/_authenticated/$storeId/products/new.tsx
+++ b/packages/dashboard/src/routes/_authenticated/$storeId/products/new.tsx
@@ -128,6 +128,10 @@ function NewProductPage() {
v.hs_code != null ||
v.country_of_origin != null ||
v.customs_description != null ||
+ v.minimum_order_quantity != null ||
+ v.order_multiple != null ||
+ v.purchase_unit != null ||
+ v.units_per_carton != null ||
v.track_inventory === false ||
v.preorderable === true ||
v.preorder_ships_at != null ||
diff --git a/packages/dashboard/src/schemas/catalog.ts b/packages/dashboard/src/schemas/catalog.ts
index 54974d20d7..f485ae4a3d 100644
--- a/packages/dashboard/src/schemas/catalog.ts
+++ b/packages/dashboard/src/schemas/catalog.ts
@@ -51,6 +51,24 @@ export const catalogFormSchema = z
* (docs/plans/6.0-price-list-automatic-pricing.md).
*/
minimum_quantity: z.string().trim().optional(),
+ /**
+ * The catalog-wide quantity terms — the middle of the three levels a
+ * buyer's rules resolve through. Blank means this agreement is silent,
+ * which passes the question down rather than answering it.
+ *
+ * Distinct from `minimum_quantity` above: that one decides when a
+ * discount starts, these decide what a buyer may order at all.
+ */
+ minimum_order_quantity: z.string().trim().optional(),
+ order_multiple: z.string().trim().optional(),
+ })
+ .refine((v) => isBlankOrPositiveInteger(v.minimum_order_quantity), {
+ path: ['minimum_order_quantity'],
+ error: () => i18n.t('admin.catalogs.terms.validation.positive_integer'),
+ })
+ .refine((v) => isBlankOrPositiveInteger(v.order_multiple), {
+ path: ['order_multiple'],
+ error: () => i18n.t('admin.catalogs.terms.validation.positive_integer'),
})
// Only while the field is on screen. The value survives a switch away from
// automatic pricing, and judging it then would block Save over a field the
@@ -97,9 +115,23 @@ export const CATALOG_DEFAULTS: CatalogFormValues = {
adjustment_magnitude: '',
adjust_compare_at: false,
minimum_quantity: '',
+ minimum_order_quantity: '',
+ order_multiple: '',
staged_products: { adds: [], removes: [] },
}
+/** Blank is a valid answer — it means the agreement states nothing. */
+function isBlankOrPositiveInteger(value: string | undefined): boolean {
+ if (!value?.trim()) return true
+ return /^\d+$/.test(value.trim()) && Number(value) > 0
+}
+
+/** Parses a terms field, where blank means "say nothing" rather than zero. */
+export function parseTermQuantity(value: string | undefined): number | null {
+ const trimmed = value?.trim()
+ return trimmed ? Number(trimmed) : null
+}
+
/**
* Maps form values to the Admin API payload. The catalog and the list it
* prices through are written in one request, so `price_list` rides inline:
@@ -116,6 +148,8 @@ export function catalogValuesToParams(
name: values.name,
description: blankToNull(values.description),
active: values.active,
+ minimum_order_quantity: parseTermQuantity(values.minimum_order_quantity),
+ order_multiple: parseTermQuantity(values.order_multiple),
price_list: priceListPayload(values, previousMode),
}
}