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.

Reserve the percentage adjustment for catalog-owned price lists

Damian Legawiec7f6deae072c0
diff --git a/CLAUDE.md b/CLAUDE.md
index e2c0b6d951..d4edac0751 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -16,7 +16,7 @@ Active plans (6.0 target, work pending):
- `6.0-catalog-agreement-rework.md` — Implementation of the one-question-per-entity catalog consequences (design finalized 2026-08-30; extracted from the `6.0-b2b-companies-and-catalogs.md` amendment block so its Implemented status stops hiding unbuilt work; **sequence Wave 1 — everything catalog-shaped builds on it**; **phases 1–3 implemented 2026-08-30** — schema inversion, resolver leak fix, rule supersession; phase 4 — inline `price_list` payload, agreement editor, products-with-prices view, wizard, detach warning — pending, Wave 2): the binding inversion (`spree_price_lists.catalog_id` replaces `spree_catalogs.price_list_id`; catalogs migration rewritten in place — unreleased edge; generic rule matching skips owned lists by FK in `PriceList.for_context`, closing the deactivated-catalog leak in `bound_price_list_ids`, which is deleted along with its `Spree::Current` memoization; the catalog↔list binding is applied in an `after_save`, never on assignment — a rejected save must not silently release a list store-wide); `PriceRules::CustomerGroupRule`/`UserRule` **grandfathered like `ChannelRule`** (revised 2026-08-30: kept working indefinitely, `superseded?` hides them from the rule picker — NO deprecation warning, NO removal date, NO data task; migrating who-gets-which-price automatically is a silent-price-change risk merchants gain nothing from). **Constraints now:** no new reads of `spree_catalogs.price_list_id` or `bound_price_list_ids`; no new features on the grandfathered price rules (audience targeting is catalog assignment, channel pricing is the default catalog); catalog-page features (terms, pricing card) mount on the agreement editor, never parallel surfaces.
- `6.0-b2b-wholesale-shipping.md` — Wholesale/freight shipping (design finalized 2026-08-30, nothing built): **`Spree::PackageType`** — store-scoped packaging vocabulary (`box|envelope|carton|pallet|container`, one default per store Channel-style) absorbing the four `default_package_*` store preferences (one-release bridges; deliberately NOT `Spree::Package` — `Stock::Package` is the in-memory packer); variant packing chain `carton_package_type_id` + `units_per_carton` + `carton_weight` + `cartons_per_pallet` (geometry on the shared carton row, packing facts on the variant; Unit → Carton → Pallet → CBM/weight); unit-aware `Spree::FreightSummary` (units/cartons/pallets/CBM/gross weight, `complete?` flag) built on the currently-unused `Stock::Package#volume` chain via a new `Spree::Measurement` conversion helper; shipment tiers = `DeliveryMethodRules::VolumeRule` (CBM min/max) + `CompanyRule` (`company_presence`) — **no new delivery profile kind** (the same product ships parcel retail and carton wholesale, and a product has one profile); **unpriced rates are first-class** (`unpriced` on Estimate + `spree_delivery_rates`, estimator skips markup, UIs render "quoted after review" — never a $0 rate that displays as Free) returned by `DeliveryRateProvider::Freight`, whose rate `metadata` snapshots the summary + deposit terms (frozen at completion — duties doctrine, never re-derived); **deposits are collected, not displayed**: deposit terms → `Cart#amount_due_at_checkout`, `Carts::Complete` validates payments against the deposit (base = order total at placement), order completes `partially_paid` with the existing `outstanding_balance` (2026-08-30 amendment: the method-level `deposit_percentage` is a *default source* feeding the order's `payment_terms` snapshot — see `6.0-6.1-b2b-payment-terms.md`); the forwarder's quote lands later as `Fee(kind: 'freight')` through `/admin/orders/:id/fees`. **Constraints now:** all volume/CBM math goes through the unit-aware helper (raw dimension-column multiplication is forbidden — the `WeightRule` raw-number shortcut does not extend to volume); no new readers of the `default_package_*` preferences; never model quote-later as a zero-cost priced rate; carton geometry never becomes variant columns; nothing may assume a completed order is paid in full (check `payment_status`/`outstanding_balance`); post-placement freight charges are Fees, never delivery-rate edits.
- `6.0-b2b-quantity-rules.md` — B2B MOQ + order multiples + purchase unit (design finalized 2026-08-30 under the one-question-per-entity doctrine — decisions.md): variant base columns `minimum_order_quantity`/`order_multiple`/`purchase_unit` (`unit|carton`, display-only vocabulary — stored quantities stay units) binding every cart, enforced as named steps in `Carts::AddItem`/`UpsertItems` on the RESULTING line quantity and re-checked at `Carts::Complete` (staff/admin unrestricted; server refuses invalid quantities naming the nearest valid neighbors — **never silently rounds**); storefront steppers step by the multiple / count cartons ("2 CTNS — 48 units"). **Commercial terms are Catalog data:** the catalog-wide default = `minimum_order_quantity` + `order_multiple` **columns on `spree_catalogs`** (same pair at three levels: variant base → catalog default → override), contextual per-SKU tiers = `spree_catalog_quantity_rules` (catalog_id, variant_id both null: false, one plain unique index — strictly overrides), and the cart-level minimum = `spree_catalog_order_minimums` (per-currency rows, never one amount + a currency column) — **deliberately typed tables per grain, never one generic catalog_rules table or an STI rule family** (hot-path indexed lookups + DB uniqueness; rules are matching predicates, terms are values — typed-adjustments doctrine), all resolved **per-field nearest-agreement-wins** through `Catalog.for_context` (override row → catalog columns → variant base; a channel minimum is just its default catalog's terms; a terms-only catalog with empty assortment is legitimate); serializers expose the buyer's *resolved* rules + the minimum/shortfall. The earlier same-day `ChannelRule` STI family is superseded — access gating (`storefront_access`/`guest_checkout`) stays as Channel preferences because gating binds before identity exists. **Constraints now:** nothing below the cart layer may read quantity rules (stock/allocation/fulfillment stay unit-pure); new item mutations keep routing through `AddItem`/`UpsertItems`; commercial terms are catalog rows/columns resolved per-field — no purchase-term settings on Channel, no term columns on variants beyond the base rules; never move gating onto catalogs.
-- `6.0-price-list-automatic-pricing.md` — Automatic price adjustments (design finalized 2026-08-30): `spree_price_lists.price_adjustment_percentage` (signed decimal, nil = fixed list; `adjust_compare_at` boolean) — the resolver derives base × factor **on read** for variants without an explicit row (explicit amounts override per variant × currency; nil-amount placeholder rows fall through), currency-rounded, currency-agnostic (applies to every base currency), **never materialized** (no refresh jobs, no drift; resolution cache keys must include the base price's version). Combined with `VolumeRule` this gives automatic % volume discounts with zero rows to maintain. Dashboard Pricing card (magnitude + increase/decrease + compare-at switch) on the standalone list page AND embedded on the catalog page for a catalog-owned list. **Constraints now:** no job/rake/import may write price rows computed from an adjustment; price exports/feeds/reports must resolve through the pricing provider once adjustment lists exist; "how numbers are made" lives on PriceList, never Catalog.
+- `6.0-price-list-automatic-pricing.md` — Automatic price adjustments (design finalized 2026-08-30): `spree_price_lists.price_adjustment_percentage` (signed decimal, nil = fixed list; `adjust_compare_at` boolean) — the resolver derives base × factor **on read** for variants without an explicit row (explicit amounts override per variant × currency; nil-amount placeholder rows fall through), currency-rounded, currency-agnostic (applies to every base currency), **never materialized** (no refresh jobs, no drift; resolution cache keys must include the base price's version). Combined with `VolumeRule` this gives automatic % volume discounts with zero rows to maintain. **Catalog-owned lists only** (revised 2026-08-31): a percentage has no product scope of its own — the owning catalog's assortment is what scopes it — so `price_adjustment_percentage` is refused on a standalone list by validation, and the Pricing card lives on the catalog page, never the standalone price-list page. A standalone list with no rules, no catalog and no products is refused activation. Product-scoped store-wide percentage discounts are a Promotion's job. **Constraints now:** no job/rake/import may write price rows computed from an adjustment; price exports/feeds/reports must resolve through the pricing provider once adjustment lists exist; "how numbers are made" lives on PriceList, never Catalog.
- `6.0-b2b-customer-po-numbers.md` — Buyer PO reference on orders (design finalized 2026-08-30): `po_number` string on cart + order (industry-exact name; copied at completion; staff may correct post-placement as a plain write — it is not money) + optional **`po_document`** private-storage attachment (direct upload, spoofing-protected, blob re-attached to the order at completion — no competitor has order-native PO upload) + **`po_number_required` boolean on `Spree::Company`** (per-company is the market's control granularity; deliberately NOT a catalog term — buyer process ≠ agreement; not governance, so the OSS-companies constraint holds) enforced as a `Carts::Complete` validation (`code: 'po_number_required'`, staff-created orders skip); `po_number` ransackable + the dashboard order search matches number OR PO; surfaced on admin order page, customer order history, confirmation email, and every future order-facing document. The Enterprise quote plan's `customer_reference`/attachment were replaced by these order fields (amended 2026-08-30). **Constraints now:** never model the buyer PO as a payment method or couple it to tender choice; `po_number` (buyer reference) and `Spree::PurchaseOrder` (merchant procurement, inventory-operations) never mix — no shared endpoints/serializers/vocabulary; new order-facing documents/emails render `po_number` when present; post-placement PO edits never route through the order-change substrate.
- `6.0-draft-order-negotiation-mechanics.md` — Manual line pricing on draft orders + cart→draft copy (design finalized 2026-08-30; **implemented in full 2026-08-30**, including `Orders::CreateFromCart` and the payment-terms plan's payment-number fixes riding along; OSS half of the quotes tier split — the quote product is Enterprise `b2b-quotes.md`). **6.0:** admin item endpoints accept `price` on incomplete orders, stamping **`price_source: 'manual'`** — the provenance column's first readers land as guards (`Carts::PriceItems` skips manual rows, `LineItem#should_update_price?` false for them) so quantity edits stop silently re-pricing negotiated lines; `'manual'` is a reserved key no pricing provider may register; `price: null` = explicit revert; `price_source` exposed admin-only, never on store serializers; plus fixes — `Orders::Create` stamps `created_by`, and the `payment_pending` docstring corrected (completion yields `payment_status: 'none'`, not `'balance_due'`; a distinct unpaid value is the wholesale-deposit rollup work's call). **6.0, late (retargeted 2026-08-30 so Enterprise quotes need nothing beyond 6.0 GA):** `Spree::Orders::CreateFromCart` copies a customer cart into a fresh draft order leaving the cart untouched (not the completion copier — no money re-pointing, no `cart_id` claim). **Constraints now:** nothing reprices a `manual` line except the explicit revert and new repricing call sites must honor the guard; no post-placement price overrides (fees/discounts until the order-change substrate's `update_item_price` kind); quote lifecycle/statuses/expiry/customer surfaces never grow here (Enterprise plan).
- `6.0-b2b-company-self-registration.md` — B2B front door, OSS mechanisms only (design finalized 2026-08-30; **retargeted 6.1 → 6.0 the same day**: the Enterprise onboarding product must ship on 6.0 GA and these small additive mechanisms are its only missing input): `POST /store/companies` (authenticated customer — including an existing retail customer — founds a root company + membership in one call; companies **born active**; registration answers → `metadata['registration']`; `company.registered` event, core sends no mail), fourth storefront access posture **`approval_required`** (prices + checkout need a standing over an active company; `prices_hidden` guest-only semantics untouched), **`pricing_access`** reason code beside every nulled price (`login_required` | `company_required` | policy-supplied), and **`Spree::Companies::ActivationPolicy`** (dependency-registered, default: every company active) consulted by `Catalog.for_company`, BOTH `sole_standing_company`s, cart `company_id` writes and the posture. The approval FLOW (pending lifecycle, requirements checklist mirroring seller onboarding, queue, request-more-info) is **Enterprise** (`spree-enterprise-v2/docs/plans/b2b-company-onboarding.md`) via the policy — no competitor ships approval OSS. **Constraints now:** new company-resolving code (visibility/pricing/checkout) consults the policy and the two `sole_standing_company`s stay mirrored; self-service standing never approval-gated; no status columns on `spree_companies`; no interim approval primitives beside it (customer-group membership prices, never approves); prices-hidden surfaces always carry the `pricing_access` code.
diff --git a/docs/plans/6.0-price-list-automatic-pricing.md b/docs/plans/6.0-price-list-automatic-pricing.md
index e3cf79e14f..947f408250 100644
--- a/docs/plans/6.0-price-list-automatic-pricing.md
+++ b/docs/plans/6.0-price-list-automatic-pricing.md
@@ -51,6 +51,20 @@ maintain and no drift when base prices move.
decimal column (negative = decrease, positive = increase); the dashboard
renders magnitude + an increase/decrease select. No separate direction
column to fall out of sync.
+- **Catalog-owned lists only** (2026-08-31, review — supersedes the
+ standalone half of the dashboard bullet below). A percentage has no
+ product scope of its own: it adjusts every variant the list is asked
+ about. On an owned list the catalog's assortment draws that line, since
+ the audience is only ever priced on what it can see. On a standalone list
+ nothing does — a rule-less −15% list put the whole store on sale, and
+ adding products to it (offered and counted by the UI) changed nothing.
+ So `price_adjustment_percentage` is refused on a standalone list by
+ validation, `Catalogs::SetPriceList` creates owned lists with their
+ `catalog_id` already set, and the standalone editor no longer offers the
+ percentage. A product-scoped store-wide percentage discount is a
+ Promotion's job (product rules + percent action already exist). Rejected:
+ letting the list's own products scope it with "none = everything" — that
+ is the catalog-rework leak reintroduced as a default. See decisions.md.
## Design Details
@@ -104,13 +118,14 @@ base row changes, not when the list does).
- Admin price list endpoints accept the two new attributes; serializers
expose them (admin only — the storefront just sees prices).
- Dashboard: a Pricing card — magnitude input + increase/decrease select +
- "also adjust compare-at" switch — on the standalone price list page, and
- the same card embedded on the **catalog page** for a catalog-owned list
- (the binding is `spree_price_lists.catalog_id` per
+ "also adjust compare-at" switch — on the **catalog page only** (the
+ binding is `spree_price_lists.catalog_id` per
`6.0-catalog-agreement-rework.md`; the catalog page is the agreement
- editor that plan establishes). The products table shows computed prices grayed as
- "automatic" with the explicit-row override editable per variant (clearing
- the override returns the variant to automatic).
+ editor that plan establishes). The standalone price-list page does not
+ offer it — see the catalog-owned-only decision above. The products table
+ shows computed prices grayed as "automatic" with the explicit-row override
+ editable per variant (clearing the override returns the variant to
+ automatic).
- CSV export of an adjustment list exports resolved amounts flagged
`automatic`, so a re-import doesn't accidentally freeze computed values
into explicit rows.
diff --git a/docs/plans/decisions.md b/docs/plans/decisions.md
index 5ec879ebd9..0cba49e6d4 100644
--- a/docs/plans/decisions.md
+++ b/docs/plans/decisions.md
@@ -4498,3 +4498,43 @@ keeps provider-free). It is a comparison figure, not a promise: the revert
re-prices through the resolver and may land elsewhere. It required
eager-loading variant prices in the orders controller's own `scope`, which
bypasses `scope_includes` — 15 price queries per order page became 1.
+
+## 2026-08-31 — Percentage adjustment is a catalog-owned feature; a standalone list must have something to apply to
+
+Revises the same-day automatic-pricing decision, which put the ±% Pricing
+card on the standalone price-list page as well as the catalog page.
+
+**The finding.** A percentage list has no product scope of its own: it
+adjusts every variant it is asked about. On a catalog-owned list the
+catalog's assortment draws that line, because the audience only ever sees
+(and so is only ever priced on) what the assortment allows. On a standalone
+list nothing draws it. A rule-less standalone −15% list put the entire store
+on sale for every shopper — and adding products to that list, which the UI
+offered and counted, changed nothing at all. A control that looks like it
+scopes and does not is worse than a missing one.
+
+**Decision.** `price_adjustment_percentage` may only be set on a list a
+catalog owns (a `PriceList` validation; `Catalogs::SetPriceList` creates
+owned lists with their `catalog_id` already set). The standalone price-list
+editor no longer offers the percentage at all. **Open consequence for the plan's headline case** — automatic volume
+pricing, a `VolumeRule` plus a percentage: an owned list's own rules are not
+consulted by the resolver (`catalog_price_lists` selects on status and dates
+only, per the catalogs doc), so that combination has no working home until
+owned lists honour their *context* rules. Deciding that is the next call;
+recorded here rather than silently changing resolver semantics. A product-scoped store-wide percentage discount ("−15% on these 40
+SKUs for everyone") is a Promotion's job: promotions already have product
+rules and a percent action, and it is a campaign, not an agreement.
+
+**Also.** A standalone list with no rules, no catalog and no products is
+refused activation (`PriceLists::Activate`). Such a list applies to
+everyone and prices nothing; a draft may sit that way while it is built,
+but making it live is refused so that emptiness reads as the mistake it is.
+
+Rejected: letting the list's own products scope an automatic list, with
+"no products" meaning "everything". That reintroduces the exact leak the
+catalog rework closed — remove the last product and the whole store goes on
+sale — as a default rather than an accident.
+
+Plans amended: `6.0-price-list-automatic-pricing.md` (Key Decisions, API +
+dashboard), `6.0-catalog-agreement-rework.md` (unchanged in substance — the
+catalog page was always the card's home).
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.tsx
index da5b4d54d3..d6434e56b1 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,7 +64,6 @@ import {
SheetDescription,
SheetHeader,
SheetTitle,
- Switch,
Textarea,
} from '@spree/dashboard-ui'
import {
@@ -76,11 +75,8 @@ import {
useRemovePriceListProducts,
} from '../../../hooks/use-price-lists'
import {
- ADJUSTMENT_DIRECTIONS,
- adjustmentFormValues,
MATCH_POLICIES,
PRICE_LIST_DEFAULTS,
- PRICING_MODES,
type PriceListFormValues,
type PriceRuleFormDraft,
priceListFormSchema,
@@ -157,8 +153,6 @@ 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: [] },
})
@@ -265,7 +259,6 @@ export function PriceListForm({
{form.formState.errors.root.message}
</p>
)}
- <PricingCard form={form} />
<RulesCard form={form} rulesArray={rulesArray} />
{mode === 'edit' && priceList && (
<DeferredProductMembershipCard
@@ -297,141 +290,6 @@ 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.json
index 47dcf58ecb..bbaad82ded 100644
--- a/packages/dashboard/src/locales/ar.json
+++ b/packages/dashboard/src/locales/ar.json
@@ -1479,11 +1479,6 @@
"label": "الاسم",
"placeholder": "مثلًا EU wholesale"
},
- "pricing_mode": {
- "automatic": "نسبة مئوية من الأسعار الأساسية",
- "fixed": "الأسعار التي أُدخلها فقط",
- "label": "التسعير"
- },
"starts_at": {
"help": "متى تصبح هذه القائمة نشطة. اتركه فارغًا للبدء فور التفعيل.",
"label": "يبدأ",
@@ -3095,8 +3090,6 @@
},
"edit_prices_cta": "تحرير الأسعار",
"no_changes": "لا توجد تغييرات للحفظ.",
- "pricing_help": "كيف تُنتج هذه القائمة الأسعار. الأسعار التي تُدخلها بنفسك لها الأولوية دائمًا.",
- "pricing_section": "التسعير",
"products": {
"add_cta": "إضافة منتجات",
"column_product": "المنتج",
diff --git a/packages/dashboard/src/locales/de.json b/packages/dashboard/src/locales/de.json
index d77d0bb229..a96ec692d5 100644
--- a/packages/dashboard/src/locales/de.json
+++ b/packages/dashboard/src/locales/de.json
@@ -1465,11 +1465,6 @@
"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",
@@ -3082,8 +3077,6 @@
},
"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",
diff --git a/packages/dashboard/src/locales/en.json b/packages/dashboard/src/locales/en.json
index 3acc16573d..ae7ff837a7 100644
--- a/packages/dashboard/src/locales/en.json
+++ b/packages/dashboard/src/locales/en.json
@@ -1465,11 +1465,6 @@
"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",
@@ -3082,8 +3077,6 @@
},
"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",
diff --git a/packages/dashboard/src/locales/fr.json b/packages/dashboard/src/locales/fr.json
index c1cfe3e971..7e2911f858 100644
--- a/packages/dashboard/src/locales/fr.json
+++ b/packages/dashboard/src/locales/fr.json
@@ -1465,11 +1465,6 @@
"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",
@@ -3082,8 +3077,6 @@
},
"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",
diff --git a/packages/dashboard/src/locales/pl.json b/packages/dashboard/src/locales/pl.json
index c7fb0f90da..f444e2f71e 100644
--- a/packages/dashboard/src/locales/pl.json
+++ b/packages/dashboard/src/locales/pl.json
@@ -1477,11 +1477,6 @@
"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ę",
@@ -3116,8 +3111,6 @@
},
"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",
diff --git a/packages/dashboard/src/locales/zh-CN.json b/packages/dashboard/src/locales/zh-CN.json
index 3b83e48d5e..a48926c01d 100644
--- a/packages/dashboard/src/locales/zh-CN.json
+++ b/packages/dashboard/src/locales/zh-CN.json
@@ -1461,11 +1461,6 @@
"label": "名称",
"placeholder": "例如:欧盟批发"
},
- "pricing_mode": {
- "automatic": "在基准价格上按百分比调整",
- "fixed": "仅使用我输入的价格",
- "label": "定价"
- },
"starts_at": {
"help": "此列表何时生效。留空则在激活时立即开始。",
"label": "开始时间",
@@ -3075,8 +3070,6 @@
},
"edit_prices_cta": "编辑价格",
"no_changes": "没有需要保存的更改。",
- "pricing_help": "此价目表如何生成价格。您手动输入的价格始终优先。",
- "pricing_section": "定价",
"products": {
"add_cta": "添加产品",
"column_product": "产品",
diff --git a/packages/dashboard/src/schemas/price-list.ts b/packages/dashboard/src/schemas/price-list.ts
index 6854aa248c..2808e944ae 100644
--- a/packages/dashboard/src/schemas/price-list.ts
+++ b/packages/dashboard/src/schemas/price-list.ts
@@ -101,14 +101,6 @@ export const priceListFormSchema = z
starts_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
@@ -129,28 +121,13 @@ export const priceListFormSchema = z
error: () => 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. */
+/**
+ * A positive percentage, or null when absent or unparseable. Lives here
+ * with the other percentage helpers, though only the catalog form uses them
+ * now: a percentage adjustment is valid only on a list a catalog owns, so
+ * the standalone editor no longer offers it.
+ */
export function parsePercentage(value: string | undefined): number | null {
if (!value?.trim()) return null
const parsed = Number(value)
@@ -165,10 +142,6 @@ 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: [] },
}
@@ -182,31 +155,10 @@ 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
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.rb
index 381c5b3f04..68eab67758 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,37 +9,30 @@ RSpec.describe Spree::Api::V3::Admin::PriceListsController, type: :controller do
before { request.headers.merge!(headers) }
- # A percentage adjustment is how a list prices without holding rows
- # (docs/plans/6.0-price-list-automatic-pricing.md).
+ # A percentage adjustment lives only on a list a catalog owns — the
+ # assortment is what scopes it to products. Standalone, it would put the
+ # whole store on sale (docs/plans/6.0-price-list-automatic-pricing.md).
describe 'automatic pricing attributes' do
- it 'creates a list with a percentage adjustment' do
+ it 'refuses a percentage on a standalone list' 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
+ expect(response).to have_http_status(:unprocessable_content)
+ expect(store.price_lists.find_by(name: 'Wholesale minus 15')).to be_nil
- patch :update, params: { id: price_list.prefixed_id, price_adjustment_percentage: nil }, as: :json
+ patch :update, params: { id: price_list.prefixed_id, price_adjustment_percentage: '10.5' }, as: :json
+ expect(response).to have_http_status(:unprocessable_content)
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
+ it 'still exposes the fields, read-only in effect, on an owned list' do
+ catalog = create(:catalog, store: store)
+ owned = create(:price_list, store: store, catalog: catalog, price_adjustment_percentage: -15)
- expect(response).to have_http_status(:unprocessable_content)
- expect(price_list.reload.price_adjustment_percentage).to be_nil
+ get :show, params: { id: owned.prefixed_id }, as: :json
+
+ expect(json_response['price_adjustment_percentage']).to eq('-15.0')
+ expect(json_response['automatic_pricing']).to be true
end
end
diff --git a/spree/api/spec/integration/spree/api/v3/admin/price_lists_spec.rb b/spree/api/spec/integration/spree/api/v3/admin/price_lists_spec.rb
index 5bd464f7f3..d428cede41 100644
--- a/spree/api/spec/integration/spree/api/v3/admin/price_lists_spec.rb
+++ b/spree/api/spec/integration/spree/api/v3/admin/price_lists_spec.rb
@@ -406,6 +406,9 @@ RSpec.describe 'Admin Price Lists API', type: :request, swagger_doc: 'api-refere
response '200', 'price list activated' do
let(:'x-spree-api-key') { secret_api_key.plaintext_token }
let(:id) { price_list.prefixed_id }
+ # Activation refuses a list with nothing to apply to; a rule is the
+ # cheapest way to give the shared fixture something.
+ before { create(:volume_price_rule, price_list: price_list, min_quantity: 2) }
schema '$ref' => '#/components/schemas/PriceList'
diff --git a/spree/core/app/models/spree/price_list.rb b/spree/core/app/models/spree/price_list.rb
index 4013738dae..04419f78b1 100644
--- a/spree/core/app/models/spree/price_list.rb
+++ b/spree/core/app/models/spree/price_list.rb
@@ -51,6 +51,7 @@ module Spree
numericality: { greater_than: -100 }, allow_nil: true
validate :starts_at_before_ends_at
validate :catalog_in_same_store
+ validate :percentage_requires_catalog
# `catalog_id` is queryable so a picker can offer the lists that are
# actually available — unowned, plus the one the catalog already holds.
@@ -310,6 +311,17 @@ module Spree
errors.add(:catalog, :invalid)
end
+ # A percentage has no product scope of its own — it adjusts every variant
+ # the list is asked about. Owned by a catalog, the assortment draws that
+ # line; standalone, nothing does, and a rule-less list would put the
+ # whole store on sale while its product list changed nothing. So the
+ # feature exists only inside an agreement.
+ def percentage_requires_catalog
+ return if price_adjustment_percentage.nil? || catalog_id.present?
+
+ errors.add(:price_adjustment_percentage, :requires_catalog)
+ end
+
def starts_at_before_ends_at
return if starts_at.blank? || ends_at.blank?
diff --git a/spree/core/app/workflows/spree/catalogs/set_price_list.rb b/spree/core/app/workflows/spree/catalogs/set_price_list.rb
index 9e7c208982..6529f2c9d9 100644
--- a/spree/core/app/workflows/spree/catalogs/set_price_list.rb
+++ b/spree/core/app/workflows/spree/catalogs/set_price_list.rb
@@ -48,9 +48,12 @@ module Spree
failure(catalog, result.error.value) unless result.success?
end
+ # Born owned: the catalog id goes in with the create, since a percentage
+ # is only valid on a list that has a catalog to scope it.
def create_owned
result = Spree.price_list_create_workflow.call(
- store: catalog.store, attributes: list_attributes(for_create: true)
+ store: catalog.store,
+ attributes: list_attributes(for_create: true).merge(catalog_id: catalog.id)
)
return failure(catalog, result.error.value) unless result.success?
diff --git a/spree/core/app/workflows/spree/price_lists/activate.rb b/spree/core/app/workflows/spree/price_lists/activate.rb
index f697e7e45b..790172ef6d 100644
--- a/spree/core/app/workflows/spree/price_lists/activate.rb
+++ b/spree/core/app/workflows/spree/price_lists/activate.rb
@@ -11,6 +11,7 @@ module Spree
def perform(price_list:)
super
+ step :require_something_to_apply_to
run_hooks :validate
ApplicationRecord.transaction do
@@ -23,6 +24,19 @@ module Spree
private
+ # A list with no rules, no catalog and no products applies to everyone
+ # and prices nothing. A draft may sit in that state while it is built;
+ # making it live is refused so that emptiness reads as the mistake it
+ # is rather than silently going nowhere.
+ def require_something_to_apply_to
+ return if price_list.catalog_id.present?
+ return if price_list.price_rules.any?
+ return if price_list.prices.exists?
+
+ price_list.errors.add(:base, :nothing_to_apply_to)
+ failure(price_list)
+ end
+
def scheduled?
price_list.starts_at.present? && price_list.starts_at.future?
end
diff --git a/spree/core/config/locales/en.yml b/spree/core/config/locales/en.yml
index 37cf5fa6d6..4ffc670644 100644
--- a/spree/core/config/locales/en.yml
+++ b/spree/core/config/locales/en.yml
@@ -344,8 +344,12 @@ en:
greater_than_max_amount: is greater than the allowed maximum amount of %{max_amount}
spree/price_list:
attributes:
+ base:
+ nothing_to_apply_to: has no rules, no catalog and no products, so it would apply to nothing. Add one before activating.
ends_at:
must_be_after_starts_at: must be after starts at
+ price_adjustment_percentage:
+ requires_catalog: can only be set on a price list a catalog owns
spree/product:
attributes:
base:
diff --git a/spree/core/spec/models/spree/price_list_spec.rb b/spree/core/spec/models/spree/price_list_spec.rb
index 95cdba953e..246dfe65ac 100644
--- a/spree/core/spec/models/spree/price_list_spec.rb
+++ b/spree/core/spec/models/spree/price_list_spec.rb
@@ -29,10 +29,23 @@ describe Spree::PriceList, type: :model do
# 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
+ catalog = create(:catalog, store: @default_store)
+ owned = ->(pct) { build(:price_list, store: @default_store, catalog: catalog, price_adjustment_percentage: pct) }
+
+ expect(owned.call(-100)).not_to be_valid
+ expect(owned.call(-100.001)).not_to be_valid
+ expect(owned.call(-99.999)).to be_valid
+ expect(owned.call(500)).to be_valid
+ end
+
+ # A percentage has no product scope of its own; the owning catalog's
+ # assortment is what gives it one. Standalone, it would put the whole
+ # store on sale while the list's own products changed nothing.
+ it 'is only valid on a list a catalog owns' do
+ expect(build(:price_list, price_adjustment_percentage: -15)).not_to be_valid
+
+ catalog = create(:catalog, store: @default_store)
+ expect(build(:price_list, store: @default_store, catalog: catalog, price_adjustment_percentage: -15)).to be_valid
end
end
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.rb
index 8d47ccfd1f..7900c6d11e 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
@@ -176,11 +176,22 @@ describe Spree::PricingProvider::Internal::Resolution do
end
# A list carrying a percentage derives a price from the base price for
- # every variant it holds no explicit amount for
+ # every variant it holds no explicit amount for. Such a list is always
+ # catalog-owned — the assortment is what scopes the percentage to
+ # products — so the buyer here is a member of the catalog's audience
# (docs/plans/6.0-price-list-automatic-pricing.md).
context 'with an automatic (percentage adjustment) price list' do
+ let(:company) { create(:company, store: store) }
+ let(:catalog) do
+ create(:catalog, store: store).tap do |owner|
+ create(:catalog_assignment, catalog: owner, assignable: company)
+ end
+ end
let!(:price_list) do
- create(:price_list, :active, store: store, price_adjustment_percentage: -15)
+ create(:price_list, :active, store: store, catalog: catalog, price_adjustment_percentage: -15)
+ end
+ let(:context) do
+ Spree::Pricing::Context.new(variant: variant, currency: currency, store: store, company: company)
end
before { variant.prices.base_prices.with_currency(currency).update_all(amount: 20.00) }
@@ -260,42 +271,25 @@ describe Spree::PricingProvider::Internal::Resolution do
# 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)
+ eur_context = Spree::Pricing::Context.new(
+ variant: variant, currency: 'EUR', store: store, company: company
+ )
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.
+ # An adjustment list is an ordinary owned list otherwise — its status
+ # and dates 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)
+ it 'is not reached by a buyer outside the catalog audience' do
+ outsider = Spree::Pricing::Context.new(variant: variant, currency: currency, store: store)
- 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)
+ expect(described_class.new(outsider).resolve.amount).to eq(20.00)
end
end
diff --git a/spree/core/spec/workflows/spree/price_lists/status_transitions_spec.rb b/spree/core/spec/workflows/spree/price_lists/status_transitions_spec.rb
index 092b99dba5..b0df678c20 100644
--- a/spree/core/spec/workflows/spree/price_lists/status_transitions_spec.rb
+++ b/spree/core/spec/workflows/spree/price_lists/status_transitions_spec.rb
@@ -2,19 +2,51 @@ require 'spec_helper'
RSpec.describe 'Spree::PriceLists status workflows' do
describe Spree::PriceLists::Activate do
+ # A list needs something to apply to before it goes live; a rule is the
+ # cheapest way to give one that.
+ def priced_list(**attrs)
+ create(:price_list, **attrs).tap { |list| create(:volume_price_rule, price_list: list, min_quantity: 2) }
+ end
+
it 'activates a list that is already due' do
- price_list = create(:price_list)
+ price_list = priced_list
expect { described_class.call(price_list: price_list) }.to change { price_list.reload.status }.from('draft').to('active')
end
it 'schedules a list whose start date has not arrived' do
- price_list = create(:price_list, starts_at: 1.week.from_now)
+ price_list = priced_list(starts_at: 1.week.from_now)
described_class.call(price_list: price_list)
expect(price_list.reload.status).to eq('scheduled')
end
+
+ # No rules, no catalog, no products: it would apply to everyone and price
+ # nothing. Fine as a draft being built up; refused as a live list.
+ it 'refuses a list with nothing to apply to' do
+ price_list = create(:price_list)
+
+ result = described_class.call(price_list: price_list)
+
+ expect(result).not_to be_success
+ expect(price_list.reload.status).to eq('draft')
+ expect(price_list.errors[:base]).to be_present
+ end
+
+ it 'accepts a list that has products even without rules' do
+ price_list = create(:price_list)
+ create(:price, variant: create(:variant), currency: 'USD', amount: 9, price_list: price_list)
+
+ expect(described_class.call(price_list: price_list)).to be_success
+ end
+
+ it 'accepts a catalog-owned list with nothing else' do
+ catalog = create(:catalog, store: @default_store)
+ price_list = create(:price_list, store: @default_store, catalog: catalog)
+
+ expect(described_class.call(price_list: price_list)).to be_success
+ end
end
describe Spree::PriceLists::Deactivate do