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
Derive price list prices from a percentage adjustment
Damian Legawiec826752fb1dc7
diff --git a/packages/admin-sdk/src/types/generated/PriceList.ts b/packages/admin-sdk/src/types/generated/PriceList.tsindex 86c5c11b11..2e97e83668 100644--- a/packages/admin-sdk/src/types/generated/PriceList.ts+++ b/packages/admin-sdk/src/types/generated/PriceList.ts@@ -1,4 +1,4 @@-// Typelizer digest 77f42bb7225d6f9a8560ce61bec813df+// Typelizer digest 1533c4ebdb05ae2164291b0ffb2da744//// DO NOT MODIFY: This file was automatically generated by Typelizer.import type {PriceRule} from '@/types'@@ -10,11 +10,14 @@ interface PriceList {status: string;position: number;match_policy: string;+ adjust_compare_at: boolean;starts_at: string | null;ends_at: string | null;deleted_at: string | null;created_at: string;updated_at: string;+ price_adjustment_percentage: string | null;+ automatic_pricing: boolean;currently_active: boolean;products_count: number;prices_count: number;diff --git a/packages/dashboard/src/components/spree/price-list-editors/price-list-form.tsx b/packages/dashboard/src/components/spree/price-list-editors/price-list-form.tsxindex d6434e56b1..da5b4d54d3 100644--- a/packages/dashboard/src/components/spree/price-list-editors/price-list-form.tsx+++ b/packages/dashboard/src/components/spree/price-list-editors/price-list-form.tsx@@ -64,6 +64,7 @@ import {SheetDescription,SheetHeader,SheetTitle,+ Switch,Textarea,} from '@spree/dashboard-ui'import {@@ -75,8 +76,11 @@ import {useRemovePriceListProducts,} from '../../../hooks/use-price-lists'import {+ ADJUSTMENT_DIRECTIONS,+ adjustmentFormValues,MATCH_POLICIES,PRICE_LIST_DEFAULTS,+ PRICING_MODES,type PriceListFormValues,type PriceRuleFormDraft,priceListFormSchema,@@ -153,6 +157,8 @@ export function PriceListForm({starts_at: priceList.starts_at,ends_at: priceList.ends_at,match_policy: (priceList.match_policy as 'all' | 'any') ?? 'all',+ ...adjustmentFormValues(priceList.price_adjustment_percentage),+ adjust_compare_at: priceList.adjust_compare_at ?? false,rules: initialRules.map(ruleDraftFromRule),staged_products: { adds: [], removes: [] },})@@ -259,6 +265,7 @@ export function PriceListForm({{form.formState.errors.root.message}</p>)}+ <PricingCard form={form} /><RulesCard form={form} rulesArray={rulesArray} />{mode === 'edit' && priceList && (<DeferredProductMembershipCard@@ -290,6 +297,141 @@ export function PriceListForm({)}+// =============================================================================+// Main column — Pricing+// =============================================================================++/**+ * How the list produces prices: only what it holds rows for, or derived from+ * base prices by a percentage. The percentage is stored signed, but edited+ * as magnitude + direction because that is how a merchant states it.+ */+function PricingCard({ form }: { form: UseFormReturn<PriceListFormValues> }) {+ const { t } = useTranslation()+ const { errors } = form.formState+ const mode = form.watch('pricing_mode')++ const modeItems = PRICING_MODES.map((value) => ({+ value,+ label: t(`admin.fields.price_list.pricing_mode.${value}`),+ }))+ const directionItems = ADJUSTMENT_DIRECTIONS.map((value) => ({+ value,+ label: t(`admin.fields.price_list.adjustment_direction.${value}`),+ }))++ return (+ <Card>+ <CardHeader>+ <CardTitle>{t('admin.pages.products.price_lists.pricing_section')}</CardTitle>+ <p className="text-sm text-muted-foreground">+ {t('admin.pages.products.price_lists.pricing_help')}+ </p>+ </CardHeader>+ <CardContent>+ <FieldGroup>+ <Field>+ <FieldLabel htmlFor="pricing_mode">+ {t('admin.fields.price_list.pricing_mode.label')}+ </FieldLabel>+ <Controller+ name="pricing_mode"+ control={form.control}+ render={({ field }) => (+ <Select+ items={modeItems as never}+ value={field.value}+ onValueChange={field.onChange}+ >+ <SelectTrigger id="pricing_mode">+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ {modeItems.map((option) => (+ <SelectItem key={option.value} value={option.value}>+ {option.label}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ )}+ />+ </Field>++ {mode === 'automatic' && (+ <>+ <div className="flex items-end gap-2">+ <Field className="w-32">+ <FieldLabel htmlFor="adjustment_magnitude">+ {t('admin.fields.price_list.adjustment_magnitude.label')}+ </FieldLabel>+ <Input+ id="adjustment_magnitude"+ inputMode="decimal"+ placeholder="15"+ aria-invalid={!!errors.adjustment_magnitude || undefined}+ {...form.register('adjustment_magnitude')}+ />+ </Field>+ <Field className="flex-1">+ <FieldLabel htmlFor="adjustment_direction" className="sr-only">+ {t('admin.fields.price_list.adjustment_direction.label')}+ </FieldLabel>+ <Controller+ name="adjustment_direction"+ control={form.control}+ render={({ field }) => (+ <Select+ items={directionItems as never}+ value={field.value}+ onValueChange={field.onChange}+ >+ <SelectTrigger id="adjustment_direction">+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ {directionItems.map((option) => (+ <SelectItem key={option.value} value={option.value}>+ {option.label}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ )}+ />+ </Field>+ </div>+ <FieldError errors={[errors.adjustment_magnitude]} />++ <Field orientation="horizontal">+ <Controller+ name="adjust_compare_at"+ control={form.control}+ render={({ field }) => (+ <Switch+ id="adjust_compare_at"+ checked={field.value}+ onCheckedChange={field.onChange}+ />+ )}+ />+ <div>+ <FieldLabel htmlFor="adjust_compare_at">+ {t('admin.fields.price_list.adjust_compare_at.label')}+ </FieldLabel>+ <p className="text-xs text-muted-foreground">+ {t('admin.fields.price_list.adjust_compare_at.help')}+ </p>+ </div>+ </Field>+ </>+ )}+ </FieldGroup>+ </CardContent>+ </Card>+ )+}+// =============================================================================// Sidebar cards// =============================================================================diff --git a/packages/dashboard/src/locales/ar.json b/packages/dashboard/src/locales/ar.jsonindex d1ee2b8315..5491d10fd5 100644--- a/packages/dashboard/src/locales/ar.json+++ b/packages/dashboard/src/locales/ar.json@@ -1431,6 +1431,18 @@"label": "الرمز البريدي"},"price_list": {+ "adjust_compare_at": {+ "help": "اشتقاق سعر المقارنة من سعر المقارنة الأساسي بالنسبة نفسها.",+ "label": "اضبط أسعار المقارنة أيضًا"+ },+ "adjustment_direction": {+ "decrease": "خفض",+ "increase": "زيادة",+ "label": "الاتجاه"+ },+ "adjustment_magnitude": {+ "label": "النسبة المئوية"+ },"description": {"label": "الوصف","placeholder": "وصف داخلي اختياري"@@ -1450,6 +1462,11 @@"label": "الاسم","placeholder": "مثلًا EU wholesale"},+ "pricing_mode": {+ "automatic": "نسبة مئوية من الأسعار الأساسية",+ "fixed": "الأسعار التي أُدخلها فقط",+ "label": "التسعير"+ },"starts_at": {"help": "متى تصبح هذه القائمة نشطة. اتركه فارغًا للبدء فور التفعيل.","label": "يبدأ",@@ -3061,6 +3078,8 @@},"edit_prices_cta": "تحرير الأسعار","no_changes": "لا توجد تغييرات للحفظ.",+ "pricing_help": "كيف تُنتج هذه القائمة الأسعار. الأسعار التي تُدخلها بنفسك لها الأولوية دائمًا.",+ "pricing_section": "التسعير","products": {"add_cta": "إضافة منتجات","column_product": "المنتج",@@ -3765,6 +3784,8 @@"updated": "تم تحديث قائمة الأسعار"},"validation": {+ "adjustment_required": "أدخل نسبة مئوية.",+ "adjustment_too_deep": "يجب أن تكون أقل من 100%.","ends_after_starts": "يجب أن يكون بعد تاريخ البدء."}},diff --git a/packages/dashboard/src/locales/de.json b/packages/dashboard/src/locales/de.jsonindex 36d210b1d2..ad9a3cee52 100644--- a/packages/dashboard/src/locales/de.json+++ b/packages/dashboard/src/locales/de.json@@ -1417,6 +1417,18 @@"label": "Postleitzahl"},"price_list": {+ "adjust_compare_at": {+ "help": "Den Vergleichspreis mit demselben Prozentsatz aus dem Grund-Vergleichspreis ableiten.",+ "label": "Auch Vergleichspreise anpassen"+ },+ "adjustment_direction": {+ "decrease": "Verringerung",+ "increase": "Erhöhung",+ "label": "Richtung"+ },+ "adjustment_magnitude": {+ "label": "Prozentsatz"+ },"description": {"label": "Beschreibung","placeholder": "Optionale interne Beschreibung"@@ -1436,6 +1448,11 @@"label": "Name","placeholder": "z. B. EU-Großhandel"},+ "pricing_mode": {+ "automatic": "Ein Prozentsatz auf die Grundpreise",+ "fixed": "Nur die Preise, die ich eingebe",+ "label": "Preisgestaltung"+ },"starts_at": {"help": "Wann diese Liste aktiv wird. Leer lassen, um bei Aktivierung sofort zu starten.","label": "Beginnt",@@ -3048,6 +3065,8 @@},"edit_prices_cta": "Preise bearbeiten","no_changes": "Keine Änderungen zum Speichern.",+ "pricing_help": "Wie diese Liste Preise erzeugt. Selbst eingegebene Preise haben immer Vorrang.",+ "pricing_section": "Preisgestaltung","products": {"add_cta": "Produkte hinzufügen","column_product": "Produkt",@@ -3747,6 +3766,8 @@"updated": "Preisliste aktualisiert"},"validation": {+ "adjustment_required": "Bitte einen Prozentsatz eingeben.",+ "adjustment_too_deep": "Muss kleiner als 100 % sein.","ends_after_starts": "Muss nach dem Startdatum liegen."}},diff --git a/packages/dashboard/src/locales/en.json b/packages/dashboard/src/locales/en.jsonindex ed9865cfa0..0e59d7d071 100644--- a/packages/dashboard/src/locales/en.json+++ b/packages/dashboard/src/locales/en.json@@ -1417,6 +1417,18 @@"label": "Postal code"},"price_list": {+ "adjust_compare_at": {+ "help": "Derive the compare-at price from the base compare-at by the same percentage.",+ "label": "Also adjust compare-at prices"+ },+ "adjustment_direction": {+ "decrease": "decrease",+ "increase": "increase",+ "label": "Direction"+ },+ "adjustment_magnitude": {+ "label": "Percentage"+ },"description": {"label": "Description","placeholder": "Optional internal description"@@ -1436,6 +1448,11 @@"label": "Name","placeholder": "e.g. EU wholesale"},+ "pricing_mode": {+ "automatic": "A percentage off base prices",+ "fixed": "Only the prices I enter",+ "label": "Pricing"+ },"starts_at": {"help": "When this list becomes active. Leave blank to start immediately on activation.","label": "Starts",@@ -3048,6 +3065,8 @@},"edit_prices_cta": "Edit prices","no_changes": "No changes to save.",+ "pricing_help": "How this list produces prices. Prices you enter yourself always win.",+ "pricing_section": "Pricing","products": {"add_cta": "Add products","column_product": "Product",@@ -3747,6 +3766,8 @@"updated": "Price list updated"},"validation": {+ "adjustment_required": "Enter a percentage.",+ "adjustment_too_deep": "Must be less than 100%.","ends_after_starts": "Must be after start date."}},diff --git a/packages/dashboard/src/locales/fr.json b/packages/dashboard/src/locales/fr.jsonindex c4dcb1184a..5e84a96e54 100644--- a/packages/dashboard/src/locales/fr.json+++ b/packages/dashboard/src/locales/fr.json@@ -1417,6 +1417,18 @@"label": "Code postal"},"price_list": {+ "adjust_compare_at": {+ "help": "Déduire le prix barré du prix barré de base avec le même pourcentage.",+ "label": "Ajuster aussi les prix barrés"+ },+ "adjustment_direction": {+ "decrease": "diminution",+ "increase": "augmentation",+ "label": "Sens"+ },+ "adjustment_magnitude": {+ "label": "Pourcentage"+ },"description": {"label": "Description","placeholder": "Description interne facultative"@@ -1436,6 +1448,11 @@"label": "Nom","placeholder": "ex. Vente en gros UE"},+ "pricing_mode": {+ "automatic": "Un pourcentage sur les prix de base",+ "fixed": "Uniquement les prix que je saisis",+ "label": "Tarification"+ },"starts_at": {"help": "Moment où cette liste devient active. Laissez vide pour démarrer immédiatement à l'activation.","label": "Début",@@ -3048,6 +3065,8 @@},"edit_prices_cta": "Modifier les prix","no_changes": "Aucune modification à enregistrer.",+ "pricing_help": "Comment cette liste produit ses prix. Les prix que vous saisissez priment toujours.",+ "pricing_section": "Tarification","products": {"add_cta": "Ajouter des produits","column_product": "Produit",@@ -3747,6 +3766,8 @@"updated": "Liste de prix mise à jour"},"validation": {+ "adjustment_required": "Saisissez un pourcentage.",+ "adjustment_too_deep": "Doit être inférieur à 100 %.","ends_after_starts": "Doit être postérieur à la date de début."}},diff --git a/packages/dashboard/src/locales/pl.json b/packages/dashboard/src/locales/pl.jsonindex 56283cb409..a1d25167f7 100644--- a/packages/dashboard/src/locales/pl.json+++ b/packages/dashboard/src/locales/pl.json@@ -1429,6 +1429,18 @@"label": "Kod pocztowy"},"price_list": {+ "adjust_compare_at": {+ "help": "Wylicz cenę porównawczą z bazowej ceny porównawczej tym samym procentem.",+ "label": "Dostosuj też ceny porównawcze"+ },+ "adjustment_direction": {+ "decrease": "obniżka",+ "increase": "podwyżka",+ "label": "Kierunek"+ },+ "adjustment_magnitude": {+ "label": "Procent"+ },"description": {"label": "Opis","placeholder": "Opcjonalny opis wewnętrzny"@@ -1448,6 +1460,11 @@"label": "Nazwa","placeholder": "np. Hurt UE"},+ "pricing_mode": {+ "automatic": "Procent od cen bazowych",+ "fixed": "Tylko ceny, które wpiszę",+ "label": "Ceny"+ },"starts_at": {"help": "Kiedy ta lista staje się aktywna. Pozostaw puste, aby rozpocząć natychmiast po aktywacji.","label": "Rozpoczyna się",@@ -3082,6 +3099,8 @@},"edit_prices_cta": "Edytuj ceny","no_changes": "Brak zmian do zapisania.",+ "pricing_help": "Jak ta lista tworzy ceny. Ceny wpisane ręcznie zawsze mają pierwszeństwo.",+ "pricing_section": "Ceny","products": {"add_cta": "Dodaj produkty","column_product": "Produkt",@@ -3795,6 +3814,8 @@"updated": "Zaktualizowano cennik"},"validation": {+ "adjustment_required": "Podaj wartość procentową.",+ "adjustment_too_deep": "Musi być mniejsza niż 100%.","ends_after_starts": "Musi być po dacie rozpoczęcia."}},diff --git a/packages/dashboard/src/locales/zh-CN.json b/packages/dashboard/src/locales/zh-CN.jsonindex 2941e96522..a7e92cbb1e 100644--- a/packages/dashboard/src/locales/zh-CN.json+++ b/packages/dashboard/src/locales/zh-CN.json@@ -1413,6 +1413,18 @@"label": "邮政编码"},"price_list": {+ "adjust_compare_at": {+ "help": "按相同百分比从基准对比价格推算对比价格。",+ "label": "同时调整对比价格"+ },+ "adjustment_direction": {+ "decrease": "下调",+ "increase": "上调",+ "label": "方向"+ },+ "adjustment_magnitude": {+ "label": "百分比"+ },"description": {"label": "描述","placeholder": "可选的内部描述"@@ -1432,6 +1444,11 @@"label": "名称","placeholder": "例如:欧盟批发"},+ "pricing_mode": {+ "automatic": "在基准价格上按百分比调整",+ "fixed": "仅使用我输入的价格",+ "label": "定价"+ },"starts_at": {"help": "此列表何时生效。留空则在激活时立即开始。","label": "开始时间",@@ -3041,6 +3058,8 @@},"edit_prices_cta": "编辑价格","no_changes": "没有需要保存的更改。",+ "pricing_help": "此价目表如何生成价格。您手动输入的价格始终优先。",+ "pricing_section": "定价","products": {"add_cta": "添加产品","column_product": "产品",@@ -3739,6 +3758,8 @@"updated": "价目表已更新"},"validation": {+ "adjustment_required": "请输入百分比。",+ "adjustment_too_deep": "必须小于 100%。","ends_after_starts": "必须晚于开始日期。"}},diff --git a/packages/dashboard/src/routes/_authenticated/$storeId/products/catalogs/$catalogId.tsx b/packages/dashboard/src/routes/_authenticated/$storeId/products/catalogs/$catalogId.tsxindex 3b2ad796a5..c65f672209 100644--- a/packages/dashboard/src/routes/_authenticated/$storeId/products/catalogs/$catalogId.tsx+++ b/packages/dashboard/src/routes/_authenticated/$storeId/products/catalogs/$catalogId.tsx@@ -249,7 +249,17 @@ function CatalogSettingsCard({render={({ field }) => (<ResourceCombobox<PriceList>queryKey="catalog-price-lists"- search={(q) => adminClient.priceLists.list({ name_cont: q, limit: 10 })}+ // Only lists that are actually available: unowned ones,+ // plus the one this catalog already holds. A list another+ // catalog owns is refused server-side, so offering it+ // would only produce a confusing error.+ search={(q) =>+ adminClient.priceLists.list({+ name_cont: q,+ catalog_id_null: true,+ limit: 10,+ })+ }hydrate={(ids) => adminClient.priceLists.list({ id_in: ids, limit: ids.length })}getOptionLabel={(list) => list.name}placeholder={t('admin.fields.catalog.price_list.placeholder')}diff --git a/packages/dashboard/src/schemas/price-list.ts b/packages/dashboard/src/schemas/price-list.tsindex da8fd42a03..eaa1226e84 100644--- a/packages/dashboard/src/schemas/price-list.ts+++ b/packages/dashboard/src/schemas/price-list.ts@@ -13,6 +13,22 @@ import type { ProductMembershipStagingValue } from '../components/spree/product-export const MATCH_POLICIES = ['all', 'any'] as constexport type MatchPolicy = (typeof MATCH_POLICIES)[number]+/**+ * How a list produces prices. `fixed` prices only what it holds explicit+ * rows for — every list that existed before automatic pricing. `automatic`+ * derives from base prices by a percentage, with explicit rows still+ * winning per variant.+ */+export const PRICING_MODES = ['fixed', 'automatic'] as const+export type PricingMode = (typeof PRICING_MODES)[number]++/**+ * Stored signed (negative = discount), but edited as magnitude + direction:+ * a merchant thinks "15% off", not "-15".+ */+export const ADJUSTMENT_DIRECTIONS = ['decrease', 'increase'] as const+export type AdjustmentDirection = (typeof ADJUSTMENT_DIRECTIONS)[number]+/*** Form-state row for a price rule. Carries the editor's display fields* (`label`, `description`, `preference_schema`) alongside the payload@@ -85,6 +101,14 @@ export const priceListFormSchema = zstarts_at: z.string().optional().nullable(),ends_at: z.string().optional().nullable(),match_policy: z.enum(MATCH_POLICIES).default('all'),+ /**+ * Split across three fields for editing, recombined into the single+ * signed `price_adjustment_percentage` by `priceListValuesToParams`.+ */+ pricing_mode: z.enum(PRICING_MODES).default('fixed'),+ adjustment_direction: z.enum(ADJUSTMENT_DIRECTIONS).default('decrease'),+ adjustment_magnitude: z.string().trim().optional(),+ adjust_compare_at: z.boolean().default(false),rules: z.array(priceRuleDraftSchema).default([]),/*** Staged product membership, applied on Save through the nested products@@ -105,6 +129,33 @@ export const priceListFormSchema = zerror: () => i18n.t('admin.products.price_lists.validation.ends_after_starts'),},)+ .refine(+ (v) => v.pricing_mode !== 'automatic' || parsePercentage(v.adjustment_magnitude) !== null,+ {+ path: ['adjustment_magnitude'],+ error: () => i18n.t('admin.products.price_lists.validation.adjustment_required'),+ },+ )+ .refine(+ (v) => {+ if (v.pricing_mode !== 'automatic' || v.adjustment_direction !== 'decrease') return true+ const magnitude = parsePercentage(v.adjustment_magnitude)+ // A 100% discount is free, and deeper is negative money. The server+ // enforces the same bound on the signed value.+ return magnitude === null || magnitude < 100+ },+ {+ path: ['adjustment_magnitude'],+ error: () => i18n.t('admin.products.price_lists.validation.adjustment_too_deep'),+ },+ )++/** A positive percentage, or null when absent or unparseable. */+function parsePercentage(value: string | undefined): number | null {+ if (!value?.trim()) return null+ const parsed = Number(value)+ return Number.isFinite(parsed) && parsed > 0 ? parsed : null+}export type PriceListFormValues = z.infer<typeof priceListFormSchema>@@ -114,6 +165,10 @@ export const PRICE_LIST_DEFAULTS: PriceListFormValues = {starts_at: null,ends_at: null,match_policy: 'all',+ pricing_mode: 'fixed',+ adjustment_direction: 'decrease',+ adjustment_magnitude: '',+ adjust_compare_at: false,rules: [],staged_products: { adds: [], removes: [] },}@@ -127,10 +182,49 @@ export function priceListValuesToParams(starts_at: v.starts_at || null,ends_at: v.ends_at || null,match_policy: v.match_policy,+ ...adjustmentParams(v),rules: v.rules.map(ruleDraftToPayload),}}+/**+ * Recombines the edited magnitude and direction into the signed percentage+ * the API stores. A fixed list sends an explicit null, which is what clears+ * an adjustment a list previously carried.+ */+function adjustmentParams(v: PriceListFormValues) {+ if (v.pricing_mode !== 'automatic') {+ return { price_adjustment_percentage: null, adjust_compare_at: false }+ }++ const magnitude = parsePercentage(v.adjustment_magnitude)+ if (magnitude === null) return { adjust_compare_at: v.adjust_compare_at }++ const signed = v.adjustment_direction === 'decrease' ? -magnitude : magnitude+ return {+ price_adjustment_percentage: String(signed),+ adjust_compare_at: v.adjust_compare_at,+ }+}++/** Splits the stored signed percentage back into the edited pair. */+export function adjustmentFormValues(percentage: string | null | undefined): {+ pricing_mode: PricingMode+ adjustment_direction: AdjustmentDirection+ adjustment_magnitude: string+} {+ const parsed = percentage == null || percentage === '' ? null : Number(percentage)+ if (parsed === null || !Number.isFinite(parsed)) {+ return { pricing_mode: 'fixed', adjustment_direction: 'decrease', adjustment_magnitude: '' }+ }++ return {+ pricing_mode: 'automatic',+ adjustment_direction: parsed < 0 ? 'decrease' : 'increase',+ adjustment_magnitude: String(Math.abs(parsed)),+ }+}+let nextLocalId = 0function newLocalId(): string {nextLocalId += 1diff --git a/spree/api/app/controllers/spree/api/v3/admin/price_lists_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/price_lists_controller.rbindex 7d6f8d2fd2..080f31ded3 100644--- a/spree/api/app/controllers/spree/api/v3/admin/price_lists_controller.rb+++ b/spree/api/app/controllers/spree/api/v3/admin/price_lists_controller.rb@@ -118,6 +118,7 @@ module Spreeparams.permit(:name, :description, :position,:starts_at, :ends_at, :match_policy,+ :price_adjustment_percentage, :adjust_compare_at,rules: [:id, :type, { preferences: {} }],prices: [:id, :variant_id, :currency, :amount, :compare_at_amount])diff --git a/spree/api/app/serializers/spree/api/v3/admin/price_list_serializer.rb b/spree/api/app/serializers/spree/api/v3/admin/price_list_serializer.rbindex 647990ca30..65829d1de7 100644--- a/spree/api/app/serializers/spree/api/v3/admin/price_list_serializer.rb+++ b/spree/api/app/serializers/spree/api/v3/admin/price_list_serializer.rb@@ -15,14 +15,26 @@ module Spreeends_at: 'string | null',deleted_at: 'string | null',match_policy: :string,+ price_adjustment_percentage: 'string | null',+ adjust_compare_at: :boolean,+ automatic_pricing: :boolean,currently_active: :boolean,products_count: :number,prices_count: :numberattributes :name, :description, :status, :position, :match_policy,+ :adjust_compare_at,starts_at: :iso8601, ends_at: :iso8601, deleted_at: :iso8601,created_at: :iso8601, updated_at: :iso8601+ # A decimal as a string, like every other money-shaped value on the+ # wire — a float would round the merchant's own figure.+ attribute :price_adjustment_percentage do |price_list|+ price_list.price_adjustment_percentage&.to_s+ end++ attribute :automatic_pricing, &:automatic_pricing?+attribute :currently_active, &:currently_active?# Cheap counts so the index can render "12 products / 36 prices"diff --git a/spree/api/spec/controllers/spree/api/v3/admin/price_lists_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/price_lists_controller_spec.rbindex df3d34835b..381c5b3f04 100644--- a/spree/api/spec/controllers/spree/api/v3/admin/price_lists_controller_spec.rb+++ b/spree/api/spec/controllers/spree/api/v3/admin/price_lists_controller_spec.rb@@ -9,6 +9,40 @@ RSpec.describe Spree::Api::V3::Admin::PriceListsController, type: :controller dobefore { request.headers.merge!(headers) }+ # A percentage adjustment is how a list prices without holding rows+ # (docs/plans/6.0-price-list-automatic-pricing.md).+ describe 'automatic pricing attributes' do+ it 'creates a list with a percentage adjustment' do+ post :create, params: { name: 'Wholesale minus 15', price_adjustment_percentage: '-15.0' }, as: :json++ expect(response).to have_http_status(:created)+ expect(json_response['price_adjustment_percentage']).to eq('-15.0')+ expect(json_response['automatic_pricing']).to be true+ expect(json_response['adjust_compare_at']).to be false+ end++ it 'sets and clears the adjustment on an existing list' do+ patch :update, params: { id: price_list.prefixed_id, price_adjustment_percentage: '10.5',+ adjust_compare_at: true }, as: :json++ expect(response).to have_http_status(:ok)+ expect(price_list.reload.price_adjustment_percentage).to eq(10.5)+ expect(price_list.adjust_compare_at).to be true++ patch :update, params: { id: price_list.prefixed_id, price_adjustment_percentage: nil }, as: :json++ expect(price_list.reload.price_adjustment_percentage).to be_nil+ expect(json_response['automatic_pricing']).to be false+ end++ it 'refuses a discount of 100% or deeper' do+ patch :update, params: { id: price_list.prefixed_id, price_adjustment_percentage: '-100' }, as: :json++ expect(response).to have_http_status(:unprocessable_content)+ expect(price_list.reload.price_adjustment_percentage).to be_nil+ end+ end+describe 'POST #create — one-shot creation' dolet(:customer_group) { create(:customer_group, store: store) }diff --git a/spree/core/app/models/spree/catalog.rb b/spree/core/app/models/spree/catalog.rbindex 316d4aa7e1..f28fed8d43 100644--- a/spree/core/app/models/spree/catalog.rb+++ b/spree/core/app/models/spree/catalog.rb@@ -36,6 +36,8 @@ module Spreevalidates :name, presence: truevalidate :price_list_in_same_store+ validate :price_list_must_be_resolvable+ validate :price_list_not_owned_elsewhere# The binding is applied inside the save, never on assignment: writing a# has_one on a persisted record updates the child immediately, so a@@ -47,8 +49,15 @@ module Spreeafter_save :apply_pending_price_list# Request-scoped catalog memoization must not keep a set that a write- # in the same request has already superseded.- after_commit -> { Spree::Current.applicable_catalogs = nil }+ # in the same request has already superseded. Destroying a catalog also+ # releases its list through `dependent: :nullify`, which is an+ # `update_all` and so never runs PriceList's own callback — without this+ # the released list stays missing from the request's matching set, and+ # anything priced later in that request misses it.+ after_commit -> {+ Spree::Current.applicable_catalogs = nil+ Spree::Current.price_lists = nil+ }scope :active, -> { where(active: true) }scope :by_position, -> { order(position: :asc) }@@ -143,15 +152,27 @@ module Spree# Attaches the given list as this catalog's owned list (raw id), or# detaches with nil — releasing the list back to standalone matching.- # A list already owned elsewhere is re-homed to this catalog.## Records the intent only; {#apply_pending_price_list} performs the write- # inside the save, so a record that fails validation changes nothing.+ # inside the save, so a record that fails validation changes nothing. An+ # unknown id is recorded as invalid rather than raised, so a bad payload+ # becomes a validation error rather than an exception out of+ # +assign_attributes+.## @param value [Integer, String, nil] raw price list PK# @return [void]def price_list_id=(value)- @pending_price_list = value.presence && Spree::PriceList.find(value)+ if value.blank?+ @pending_price_list = nil+ remove_instance_variable(:@pending_price_list_id) if defined?(@pending_price_list_id)+ return+ end++ # Scoped to this store's lists: an id from another tenant must not be+ # reachable here, whatever the caller. Missing resolves to nil and is+ # rejected by #price_list_must_be_resolvable.+ @pending_price_list_id = value+ @pending_price_list = (store || Spree::Current.store)&.price_lists&.find_by(id: value)end# Assigning the association directly goes through the same deferral, so@@ -235,6 +256,30 @@ module Spreeerrors.add(:price_list, :invalid)end+ # An id that resolved to nothing in this store is an error, not a silent+ # detach — otherwise a typo reads as "remove the pricing".+ def price_list_must_be_resolvable+ return unless defined?(@pending_price_list_id)+ return if @pending_price_list_id.blank? || @pending_price_list.present?++ errors.add(:price_list, :invalid)+ end++ # A list belongs to exactly one catalog, so claiming one another catalog+ # already owns would silently un-price that catalog. Moving a list is a+ # detach on the current owner followed by an attach here — two deliberate+ # acts, not a side effect of picking a familiar name.+ def price_list_not_owned_elsewhere+ return if price_list.nil? || !price_list.persisted?++ # Read the stored owner rather than the in-memory one: the caller may+ # hold a copy loaded before another catalog claimed it.+ owner_id = Spree::PriceList.where(id: price_list.id).pick(:catalog_id)+ return if owner_id.nil? || owner_id == id++ errors.add(:price_list, :owned_by_another_catalog)+ end+# Applies the deferred binding inside the save transaction: the newly# claimed list points here, and a list this catalog is giving up is# released. Written through the child, since the FK lives on the list.@@ -245,34 +290,69 @@ module Spreeremove_instance_variable(:@pending_price_list)# An unsaved list is persisted through its own lifecycle — it has no id- # to bind yet, and skipping that would silently drop it.+ # to bind yet, and skipping that would silently drop it. Any list this+ # catalog already owns is released first, or the one-live-list-per-+ # catalog rule rejects the replacement before it can take over.if pending && !pending.persisted?+ release_owned_price_listpending.catalog_id = idpending.save!finish_price_list_bindingreturnend- # Ownership moves under a row lock, so two concurrent saves cannot- # interleave the read of the current binding with the writes. Locking in- # id order avoids deadlock, and the binding is re-read once held.- association(:price_list).reset- lock_ids = [association(:price_list).load_target&.id, pending&.id].compact.uniq.sort- Spree::PriceList.where(id: lock_ids).order(:id).lock.load if lock_ids.any?-association(:price_list).resetprevious = association(:price_list).load_targetreturn if previous&.id == pending&.id- # Compare-and-swap on the release: a list another request has already- # re-homed must not be sent back to standalone matching, where a- # rule-less list prices the whole store.- Spree::PriceList.where(id: previous.id, catalog_id: id).update_all(catalog_id: nil) if previous- pending&.update_column(:catalog_id, id)+ release_owned_price_list(previous)++ if pending+ # Compare-and-swap on the claim: only an unowned list is taken. The+ # validation already refuses a list whose owner is visible, so this+ # only fires when a concurrent request claimed it in between — the+ # write raises and rolls the transaction back rather than silently+ # un-pricing the catalog that won.+ claimed = Spree::PriceList.where(id: pending.id, catalog_id: nil).update_all(catalog_id: id)++ if claimed.zero?+ raise ActiveRecord::RecordNotUnique,+ "price list #{pending.id} was claimed by another catalog"+ end++ # The conditional UPDATE bypasses the instance, so tell the caller's+ # copy what was written — otherwise it still reads catalog_id as nil+ # and a later `price_list.catalog = nil` looks like a no-op and+ # silently fails to detach.+ sync_written_catalog_id(pending, id)+ endfinish_price_list_bindingend+ # Compare-and-swap on the release: a list another request has already+ # re-homed must not be sent back to standalone matching, where a+ # rule-less list prices the whole store.+ def release_owned_price_list(previous = nil)+ previous ||= begin+ association(:price_list).reset+ association(:price_list).load_target+ end+ return if previous.nil?++ released = Spree::PriceList.where(id: previous.id, catalog_id: id).update_all(catalog_id: nil)+ sync_written_catalog_id(previous, nil) if released.positive?+ end++ # Reflects an `update_all` back onto the in-memory record, so the copy a+ # caller holds agrees with the row and stays clean rather than dirty.+ def sync_written_catalog_id(price_list, catalog_id)+ return if price_list.catalog_id == catalog_id++ price_list.catalog_id = catalog_id+ price_list.send(:clear_attribute_changes, [:catalog_id])+ end+def finish_price_list_bindingassociation(:price_list).reset# The writes above skip PriceList's own after_commit, so the request'sdiff --git a/spree/core/app/models/spree/price_list.rb b/spree/core/app/models/spree/price_list.rbindex d1ca661693..4013738dae 100644--- a/spree/core/app/models/spree/price_list.rb+++ b/spree/core/app/models/spree/price_list.rb@@ -44,10 +44,17 @@ module Spree# over a stored generated column on MySQL/MariaDB.validates :catalog_id, uniqueness: { scope: spree_base_uniqueness_scope,conditions: -> { where(deleted_at: nil) } }, allow_nil: true+ # Greater than -100: at exactly -100 every derived price is zero, and+ # below it the arithmetic goes negative. The upper end is deliberately+ # open — a markup has no natural ceiling.+ validates :price_adjustment_percentage,+ numericality: { greater_than: -100 }, allow_nil: truevalidate :starts_at_before_ends_atvalidate :catalog_in_same_store- self.whitelisted_ransackable_attributes = %w[status match_policy starts_at ends_at]+ # `catalog_id` is queryable so a picker can offer the lists that are+ # actually available — unowned, plus the one the catalog already holds.+ self.whitelisted_ransackable_attributes = %w[status match_policy starts_at ends_at catalog_id]scope :by_position, -> { order(position: :asc) }scope :for_store, ->(store) { where(store: store) }@@ -134,6 +141,22 @@ module Spreeendend+ # Whether this list derives prices from base prices rather than pricing+ # only what it holds explicit rows for.+ # @return [Boolean]+ def automatic_pricing?+ price_adjustment_percentage.present?+ end++ # What a base price is multiplied by to derive this list's price:+ # -15% gives 0.85, +10% gives 1.1.+ # @return [BigDecimal, nil]+ def adjustment_factor+ return if price_adjustment_percentage.nil?++ 1 + (price_adjustment_percentage / 100)+ end+# Returns true if the price list is active or scheduled# @return [Boolean]def active_or_scheduled?diff --git a/spree/core/app/models/spree/pricing_provider/internal.rb b/spree/core/app/models/spree/pricing_provider/internal.rbindex 7b2f4f6d34..184b88ed8e 100644--- a/spree/core/app/models/spree/pricing_provider/internal.rb+++ b/spree/core/app/models/spree/pricing_provider/internal.rb@@ -100,14 +100,26 @@ module Spreeendend- # Returns the price for a given price list+ # Returns the price for a given price list. An explicit row wins; a+ # list carrying a percentage adjustment otherwise derives one from the+ # base price.# @param price_list [Spree::PriceList]- # @return [Spree::Price]+ # @return [Spree::Price, nil]def find_price_for_list(price_list)+ explicit_price_for_list(price_list) ||+ (price_list.automatic_pricing? ? derived_price_for_list(price_list) : nil)+ end++ # An amount someone typed for this variant on this list.+ # @param price_list [Spree::PriceList]+ # @return [Spree::Price, nil]+ def explicit_price_for_list(price_list)currency = context.currency&.upcase# Zero is a valid override (free for this list); only nil placeholder- # rows (materialized by PriceList#add_products) are skipped.+ # rows (materialized by PriceList#add_products) are skipped, so a+ # placeholder on an adjustment list falls through to the derived+ # amount rather than blocking it.if prices.loaded?prices.detect do |p|p.currency == currency &&@@ -123,26 +135,71 @@ module Spreeendend+ # The base price times the list's factor, rounded to the currency's+ # minor unit. Built unsaved and never written: deriving on read is+ # what keeps an adjustment list from drifting when base prices move+ # (docs/plans/6.0-price-list-automatic-pricing.md).+ #+ # A variant with no base price in this currency yields nothing, so the+ # walk moves on to the next list exactly as it would for a list+ # holding no row.+ #+ # @param price_list [Spree::PriceList]+ # @return [Spree::Price, nil]+ def derived_price_for_list(price_list)+ base = base_price+ return if base.nil? || base.amount.nil?++ factor = price_list.adjustment_factor+ compare_at =+ if price_list.adjust_compare_at && base.compare_at_amount.present?+ round_for_currency(base.compare_at_amount * factor, base.currency)+ end++ Spree::Price.new(+ variant_id: context.variant.id,+ currency: base.currency,+ amount: round_for_currency(base.amount * factor, base.currency),+ compare_at_amount: compare_at,+ price_list_id: price_list.id+ )+ end++ # Rounds to the currency's own minor unit — two places for USD, none+ # for JPY — rather than assuming cents.+ # @return [BigDecimal]+ def round_for_currency(amount, currency)+ amount.round(::Money::Currency.find(currency)&.exponent || 2)+ end+# Returns the base price for the variant in the current currency# @return [Spree::Price]def find_base_price+ base_price || build_empty_price+ end++ # The variant's own price in this currency, or nil when it has none.+ # Memoized: an adjustment list asks for it, and the base fallback may+ # ask again for the same context.+ # @return [Spree::Price, nil]+ def base_price+ return @base_price if defined?(@base_price)+currency = context.currency&.upcase- price = if prices.loaded?- prices.detect do |p|- p.currency == currency &&- p.price_list_id.nil? &&- p.amount.present?- end- else- context.variant.prices- .with_currency(currency)- .where(price_list_id: nil)- .where.not(amount: nil)- .first- end-- price || build_empty_price+ @base_price = if prices.loaded?+ prices.detect do |p|+ p.currency == currency &&+ p.price_list_id.nil? &&+ p.amount.present?+ end+ else+ context.variant.prices+ .with_currency(currency)+ .where(price_list_id: nil)+ .where.not(amount: nil)+ .first+ endend# Returns the prices for the variantdiff --git a/spree/core/config/locales/en.yml b/spree/core/config/locales/en.ymlindex e5a7037eea..37cf5fa6d6 100644--- a/spree/core/config/locales/en.yml+++ b/spree/core/config/locales/en.yml@@ -255,6 +255,10 @@ en:values_should_be_percent: Tier values should all be percentages between 0% and 100%preferred_tiers:should_be_hash: should be a hash+ spree/catalog:+ attributes:+ price_list:+ owned_by_another_catalog: is already used by another catalog. Detach it there first.spree/category:attributes:parent:diff --git a/spree/core/db/migrate/20260830000002_add_price_adjustment_to_spree_price_lists.rb b/spree/core/db/migrate/20260830000002_add_price_adjustment_to_spree_price_lists.rbnew file mode 100644index 0000000000..c9b956e013--- /dev/null+++ b/spree/core/db/migrate/20260830000002_add_price_adjustment_to_spree_price_lists.rb@@ -0,0 +1,14 @@+class AddPriceAdjustmentToSpreePriceLists < ActiveRecord::Migration[8.1]+ def change+ # Signed: negative is a discount off the base price, positive a markup.+ # nil means the list prices only what it holds explicit rows for, which+ # is every list that exists today+ # (docs/plans/6.0-price-list-automatic-pricing.md).+ add_column :spree_price_lists, :price_adjustment_percentage, :decimal, precision: 6, scale: 3++ # Whether a derived price also derives its compare-at from the base+ # compare-at. Off by default: a derived compare-at is a claim about a+ # former price, so it is stated deliberately.+ add_column :spree_price_lists, :adjust_compare_at, :boolean, null: false, default: false+ end+enddiff --git a/spree/core/spec/models/spree/catalog_spec.rb b/spree/core/spec/models/spree/catalog_spec.rbindex 14f8674d3e..cd676270e0 100644--- a/spree/core/spec/models/spree/catalog_spec.rb+++ b/spree/core/spec/models/spree/catalog_spec.rb@@ -234,15 +234,58 @@ describe Spree::Catalog, type: :model doexpect(price_list.reload.catalog).to be_nilend- it 're-homes a list already owned by another catalog' do- create(:catalog, store: store, price_list: price_list)+ # Taking a list another catalog owns would silently un-price that+ # catalog, so moving one is detach-then-attach: two deliberate acts.+ it 'refuses a list another catalog already owns' do+ owner = create(:catalog, store: store, price_list: price_list)other = create(:catalog, store: store)- other.update!(price_list: price_list)+ expect(other.update(price_list: price_list)).to be false+ expect(other.errors[:price_list]).to be_present+ expect(price_list.reload.catalog).to eq(owner)+ end++ it 'accepts the list once its previous owner lets go' do+ owner = create(:catalog, store: store, price_list: price_list)+ other = create(:catalog, store: store)+ owner.update!(price_list: nil)++ expect(other.update(price_list: price_list)).to be trueexpect(price_list.reload.catalog).to eq(other)end+ # Validation re-reads the stored owner, so a list taken between the+ # caller loading it and saving is refused rather than stolen.+ it 'refuses a list claimed concurrently before this save ran' do+ other = create(:catalog, store: store)+ rival = create(:catalog, store: store)++ other.price_list = price_list+ Spree::PriceList.where(id: price_list.id).update_all(catalog_id: rival.id)++ expect(other.save).to be false+ expect(other.errors[:price_list]).to be_present+ expect(price_list.reload.catalog_id).to eq(rival.id)+ end++ # The claim itself is a conditional UPDATE, so even a list taken after+ # validation passed is never stolen — it raises instead.+ it 'raises rather than stealing a list claimed between validation and write' do+ other = create(:catalog, store: store)+ rival = create(:catalog, store: store)+ other.price_list = price_list++ allow(other).to receive(:price_list_not_owned_elsewhere) do+ Spree::PriceList.where(id: price_list.id).update_all(catalog_id: rival.id)+ end++ # The write rolls back with the transaction, so what matters is that+ # this catalog never ends up owning the list.+ expect { other.save }.to raise_error(ActiveRecord::RecordNotUnique)+ expect(price_list.reload.catalog_id).not_to eq(other.id)+ end+it 'releases the list back to standalone when the catalog is destroyed' docatalog = create(:catalog, store: store, price_list: price_list)@@ -251,6 +294,54 @@ describe Spree::Catalog, type: :model doexpect(price_list.reload.catalog_id).to be_nilend+ # `dependent: :nullify` releases the list with an update_all, which never+ # runs PriceList's own callback — so without the catalog clearing it, the+ # released list stays missing from this request's matching set.+ it 'makes a list released by destroy visible to the rest of the request' do+ price_list.update!(status: 'active')+ catalog = create(:catalog, store: store, price_list: price_list)+ Spree::Current.store = store+ expect(Spree::Current.price_lists.map(&:id)).not_to include(price_list.id)++ catalog.destroy!++ expect(Spree::Current.price_lists.map(&:id)).to include(price_list.id)+ end++ # The binding is written with update_all, which never touches the+ # instance the caller holds. Left unsynced, that copy still reads+ # catalog_id as nil and detaching from the list side looks like a no-op.+ it 'leaves the attached list agreeing with its row' do+ catalog = create(:catalog, store: store, price_list: price_list)++ expect(price_list.catalog_id).to eq(catalog.id)+ expect(price_list.changed).to be_empty++ price_list.update!(catalog: nil)++ expect(Spree::PriceList.where(id: price_list.id).pick(:catalog_id)).to be_nil+ end++ describe 'the price_list_id writer' do+ it 'records an unknown id as invalid rather than raising' do+ catalog = create(:catalog, store: store)++ expect { catalog.price_list_id = 999_999 }.not_to raise_error+ expect(catalog).not_to be_valid+ expect(catalog.errors[:price_list]).to be_present+ end++ it 'does not reach another store list' do+ catalog = create(:catalog, store: store)+ foreign = create(:price_list, store: create(:store))++ catalog.price_list_id = foreign.id++ expect(catalog).not_to be_valid+ expect(catalog.price_list).to be_nil+ end+ end+# The binding is a write on the LIST, so assigning it on a persisted# catalog would hit the database before validation. A rejected save that# had already detached would release a rule-less list to the whole store@@ -312,7 +403,10 @@ describe Spree::Catalog, type: :model doit 'does not release a list that another catalog has already claimed' docatalog = create(:catalog, store: store, price_list: price_list)other = create(:catalog, store: store)- other.update!(price_list: price_list)++ # Stand in for a concurrent request that legitimately took the list+ # over after this record loaded it.+ Spree::PriceList.where(id: price_list.id).update_all(catalog_id: other.id)# `catalog` still believes it owns the list; detaching must be a no-op.catalog.association(:price_list).resetdiff --git a/spree/core/spec/models/spree/price_list_spec.rb b/spree/core/spec/models/spree/price_list_spec.rbindex 099b8dae70..95cdba953e 100644--- a/spree/core/spec/models/spree/price_list_spec.rb+++ b/spree/core/spec/models/spree/price_list_spec.rb@@ -12,6 +12,30 @@ describe Spree::PriceList, type: :model doendend+ # A percentage adjustment makes the list derive prices from base prices+ # (docs/plans/6.0-price-list-automatic-pricing.md).+ describe 'automatic pricing' do+ it 'is off unless a percentage is set' do+ expect(build(:price_list)).not_to be_automatic_pricing+ expect(build(:price_list, price_adjustment_percentage: -15)).to be_automatic_pricing+ end++ it 'turns the percentage into the factor a base price is multiplied by' do+ expect(build(:price_list, price_adjustment_percentage: -15).adjustment_factor).to eq(0.85)+ expect(build(:price_list, price_adjustment_percentage: 10).adjustment_factor).to eq(1.1)+ expect(build(:price_list).adjustment_factor).to be_nil+ end++ # At -100 every derived price is zero; below it the arithmetic goes+ # negative. A markup has no ceiling.+ it 'refuses a discount of 100% or deeper' do+ expect(build(:price_list, price_adjustment_percentage: -100)).not_to be_valid+ expect(build(:price_list, price_adjustment_percentage: -100.001)).not_to be_valid+ expect(build(:price_list, price_adjustment_percentage: -99.999)).to be_valid+ expect(build(:price_list, price_adjustment_percentage: 500)).to be_valid+ end+ end+# The catalog binding: nil = standalone (rule-matched), set = owned by# exactly one catalog and reached only through it# (docs/plans/6.0-catalog-agreement-rework.md).diff --git a/spree/core/spec/models/spree/pricing_provider/internal_resolution_spec.rb b/spree/core/spec/models/spree/pricing_provider/internal_resolution_spec.rbindex 999cfd3e29..8d47ccfd1f 100644--- a/spree/core/spec/models/spree/pricing_provider/internal_resolution_spec.rb+++ b/spree/core/spec/models/spree/pricing_provider/internal_resolution_spec.rb@@ -175,6 +175,130 @@ describe Spree::PricingProvider::Internal::Resolution doendend+ # A list carrying a percentage derives a price from the base price for+ # every variant it holds no explicit amount for+ # (docs/plans/6.0-price-list-automatic-pricing.md).+ context 'with an automatic (percentage adjustment) price list' do+ let!(:price_list) do+ create(:price_list, :active, store: store, price_adjustment_percentage: -15)+ end++ before { variant.prices.base_prices.with_currency(currency).update_all(amount: 20.00) }++ it 'derives the price from the base price' do+ price = resolver.resolve++ expect(price.amount).to eq(17.00)+ expect(price.price_list_id).to eq(price_list.id)+ expect(price).not_to be_persisted+ end++ it 'applies a markup for a positive percentage' do+ price_list.update!(price_adjustment_percentage: 10)++ expect(resolver.resolve.amount).to eq(22.00)+ end++ it 'tracks the base price rather than freezing a copy of it' do+ variant.prices.base_prices.with_currency(currency).update_all(amount: 40.00)++ expect(resolver.resolve.amount).to eq(34.00)+ end++ it 'rounds to the currency minor unit' do+ variant.prices.base_prices.with_currency(currency).update_all(amount: 9.99)++ # 9.99 × 0.85 = 8.4915+ expect(resolver.resolve.amount).to eq(8.49)+ end++ it 'lets an explicit row override the adjustment' do+ create(:price, variant: variant, currency: currency, amount: 12.34, price_list: price_list)++ expect(resolver.resolve.amount).to eq(12.34)+ end++ # `add_products` materializes nil-amount rows; those mean "in the list,+ # not priced", so they must not block the derived amount.+ it 'derives through a nil-amount placeholder row' do+ create(:price, variant: variant, currency: currency, amount: nil, price_list: price_list)++ expect(resolver.resolve.amount).to eq(17.00)+ end++ it 'yields nothing when the variant has no base price in this currency' do+ variant.prices.delete_all++ price = resolver.resolve+ expect(price.amount).to be_nil+ expect(price).not_to be_persisted+ end++ # A fresh resolver per assertion, because one instance memoizes the+ # base price it read — which is the point of the object, and what a+ # request-scoped resolution relies on.+ it 'leaves the compare-at alone by default' do+ variant.prices.base_prices.with_currency(currency).update_all(compare_at_amount: 30.00)++ expect(described_class.new(context).resolve.compare_at_amount).to be_nil+ end++ it 'derives the compare-at when the list says to' do+ variant.prices.base_prices.with_currency(currency).update_all(compare_at_amount: 30.00)+ price_list.update!(adjust_compare_at: true)++ expect(described_class.new(context).resolve.compare_at_amount).to eq(25.50)+ end++ it 'works the same when the variant prices are already loaded' do+ variant.prices.load++ expect(resolver.resolve.amount).to eq(17.00)+ end++ # The adjustment is a property of the list, not of a currency: it+ # applies to whatever base price the buyer's currency has.+ it 'applies to every currency the variant is priced in' do+ create(:price, variant: variant, currency: 'EUR', amount: 50.00)+ eur_context = Spree::Pricing::Context.new(variant: variant, currency: 'EUR', store: store)++ expect(described_class.new(eur_context).resolve.amount).to eq(42.50)+ end++ # An adjustment list is an ordinary list otherwise — status, dates and+ # rules gate it exactly as before.+ it 'does not apply when the list is not in effect' do+ price_list.update!(status: 'inactive')++ expect(resolver.resolve.amount).to eq(20.00)+ end++ it 'obeys its own rules' do+ create(:volume_price_rule, price_list: price_list, min_quantity: 10)++ expect(resolver.resolve.amount).to eq(20.00)++ bulk_context = Spree::Pricing::Context.new(+ variant: variant, currency: currency, store: store, quantity: 10+ )+ expect(described_class.new(bulk_context).resolve.amount).to eq(17.00)+ end++ it 'is reached through a catalog when the list is catalog-owned' do+ company = create(:company, store: store)+ catalog = create(:catalog, store: store)+ create(:catalog_assignment, catalog: catalog, assignable: company)+ price_list.update!(catalog: catalog)++ member_context = Spree::Pricing::Context.new(+ variant: variant, currency: currency, store: store, company: company+ )+ expect(described_class.new(member_context).resolve.amount).to eq(17.00)+ # …and not by anyone outside its audience.+ expect(resolver.resolve.amount).to eq(20.00)+ end+ end+context 'with price list from different store' dolet(:other_store) { create(:store) }let!(:other_store_list) { create(:price_list, :active, store: other_store) }