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
Fix: refuse quantity breaks that charge more for a bigger order (#14665)
Łukasz Adamczykc93e7bee13c7
diff --git a/docs/plans/6.0-volume-pricing.md b/docs/plans/6.0-volume-pricing.mdindex d8005e2a59..845d5c0fc3 100644--- a/docs/plans/6.0-volume-pricing.md+++ b/docs/plans/6.0-volume-pricing.md@@ -120,6 +120,47 @@ promotion territory and are deliberately deferred.would cross the cap, so no writer can get past it. A dashboard-only capwould leave the API unbounded and let the resolver's per-line row scangrow without limit.+- **A ladder may never charge more for a bigger order** (2026-09-16):+ every rung is refused if it costs more than the quantity below it buys —+ inside the ladder that is the rung beneath, and for a ladder with no+ quantity-1 row of its own it is the variant's base price, which is what+ the buyer actually pays up to the threshold. A *bottom* rung above base+ stays legal: an agreement is free to be dearer than the shop, and only a+ break promises a better price for a bigger order. Without this a break+ entered above the shop price multiplied the bill at the threshold, in+ separate columns where nothing looked wrong (V-3644). Four consequences+ worth stating, because each was a hole the first cut left open:+ - **Enforced on both paths**, like the break cap. `Prices::BulkUpsert`+ judges the whole ladder, since only the batch sees it whole; a model+ validation covers the single-row writers, which would otherwise create+ exactly the state the bulk path refuses.+ - **A base price is part of the ladder's shape.** Lowering the shop price+ under a break raises the bill at the threshold as surely as mispricing+ the break, so a batch carrying only base rows is checked too, and the+ floor is the base price *as the batch leaves it*.+ - **Every save is judged on the state it would leave, not on what it+ changed.** An earlier cut exempted a breach that predated the batch, so a+ ladder found rising stayed editable. That exemption was dropped: no write+ path can produce a rising ladder, so one found rising came from outside+ them — raw SQL, or data predating the rule — and comparing against it let+ a *new* breach above the old one through unreported. Repairing the+ offending rung is always allowed, which is the way out.+ - **The floor is the base price, not the price the buyer would really+ pay.** A different list may undercut base below the threshold and leave+ the buyer paying more at it; the write path cannot know which list wins+ for which buyer. Narrower than the silence it replaces, and the reason+ the resolver is not the place for this check.+- **The import is applied a row at a time, so a ladder passes through+ states it would refuse** (2026-09-16): lowering every rung of a stored+ ladder fails on the first row unless the file lists the higher quantities+ first, because the intermediate ladder really does rise. The refusal+ names the rung and the floor and says so. Batching a variant's rungs into+ one write is the structural fix, and belongs with the row-processor+ contract rather than here.+- **Two rows addressing one rung are refused, not merged** (2026-09-16):+ `upsert_all` cannot carry a key twice, and keeping the last occurrence+ answered success while discarding a price the merchant had typed. The+ batch now fails and names the repeated quantity.- **A ladder needs no quantity-1 row** (2026-09-07): a list may price avariant only from 24 up, and quantities below that fall through to thenext list or the base price exactly as they do for a variant the listdiff --git a/docs/user/pricing/price-lists.mdx b/docs/user/pricing/price-lists.mdxindex 020e3abea1..b7bfe4caec 100644--- a/docs/user/pricing/price-lists.mdx+++ b/docs/user/pricing/price-lists.mdx@@ -88,11 +88,15 @@ A price list can charge less per unit from a given quantity up. In the price ediWhen a customer's order line reaches a break, the line is priced at that break's unit price. A variant with breaks is priced by its breaks alone: a catalog's percentage adjustment does not apply on top of them.+A break must not cost more than the quantity below it buys, and saving is refused if it does — otherwise a customer would pay more for ordering more. The price a break is measured against is the one directly beneath it: the break below, or the variant's regular price on this list. You may leave that regular price empty, which means the list does not change the price until the first break is reached; the break is then measured against the shop price the customer pays up to that point.++A price list may be dearer than the shop overall — only the breaks within it have to go down.+### Importing and Exporting PricesNext to **Edit Prices** you'll find **Export** and **Import**, which move a price list's prices as a CSV file, one row per variant, currency and quantity break.-**Export** downloads every priced row of the list. **Import** merges a file into the list: each row in the file is written or updated, a row with a blank price removes that row from the list (the regular price or a break alike; a variant with no rows left is no longer on the list), and prices the file does not mention are left as they are. Rows the import cannot place are listed in the import report and do not stop the rest: an unknown SKU, a SKU shared by more than one variant, a currency the store does not sell in, a price that is not a plain number like `16.50`, a quantity that is not a whole number, or an eleventh break on one variant. Rows are applied one at a time, so to replace a variant's full set of ten breaks with new quantities, import the blank-price rows that clear the old breaks first, then the new ones.+**Export** downloads every priced row of the list. **Import** merges a file into the list: each row in the file is written or updated, a row with a blank price removes that row from the list (the regular price or a break alike; a variant with no rows left is no longer on the list), and prices the file does not mention are left as they are. Rows the import cannot place are listed in the import report and do not stop the rest: an unknown SKU, a SKU shared by more than one variant, a currency the store does not sell in, a price that is not a plain number like `16.50`, a quantity that is not a whole number, an eleventh break on one variant, or a price that would make a bigger order cost more per unit. Rows are applied one at a time, so to replace a variant's full set of ten breaks with new quantities, import the blank-price rows that clear the old breaks first, then the new ones. For the same reason, when lowering every price on a variant's ladder at once, list the higher quantities first — a file that lowers the regular price before the breaks above it is momentarily a ladder that charges more for a bigger order, and that row is refused.| Field | Description || -------------------- | ----------------------------------------------------------------------------------------- |diff --git a/packages/dashboard-ui/src/spree/bulk-price-table.tsx b/packages/dashboard-ui/src/spree/bulk-price-table.tsxindex 34d145becc..a56ddb4bec 100644--- a/packages/dashboard-ui/src/spree/bulk-price-table.tsx+++ b/packages/dashboard-ui/src/spree/bulk-price-table.tsx@@ -92,6 +92,10 @@ export interface BulkPriceTableProps {onTierAdd?: (rowId: string) => void/** Removes a tier row. */onTierRemove?: (rowId: string) => void+ /** Why the last save was refused. Rendered above the grid rather than+ * toasted: this table lives in a dialog, and the toast viewport sits+ * below the overlay layer so nothing raised from in here is visible. */+ error?: string | null// Optional state for the toolbar + pagination footer. Omitting all of these// hides the toolbar/pagination entirely (use for in-memory single-page lists).@@ -125,6 +129,7 @@ export function BulkPriceTable({totalPages,onPageChange,isLoading,+ error,}: BulkPriceTableProps) {const columns = useMemo<ColumnDef<BulkPriceRow>[]>(() => [@@ -306,6 +311,14 @@ export function BulkPriceTable({// grid between them should run to the container's edges, the way a// table in a card does.<div className="flex h-full flex-col gap-3">+ {error && (+ <div+ role="alert"+ className="mx-3 shrink-0 rounded-md border border-destructive/50 bg-destructive/10 px-3 py-2 text-destructive text-sm"+ >+ {error}+ </div>+ )}{showToolbar && (// Always-mounted toolbar. Conditionally rendering the search input// would unmount it whenever a deferred query refetches into thediff --git a/packages/dashboard/src/components/spree/bulk-price-editor/bulk-price-editor.tsx b/packages/dashboard/src/components/spree/bulk-price-editor/bulk-price-editor.tsxindex 8ce39c3b91..45385a2ae4 100644--- a/packages/dashboard/src/components/spree/bulk-price-editor/bulk-price-editor.tsx+++ b/packages/dashboard/src/components/spree/bulk-price-editor/bulk-price-editor.tsx@@ -346,6 +346,10 @@ export function BulkPriceEditor({return out}, [data, breaksByVariant, draftRungs])+ // A toast cannot be seen from in here: the viewport sits below the overlay+ // layer on purpose, so it never covers a sheet's footer buttons. Refusals+ // render in the grid's own header instead.+ const [saveError, setSaveError] = useState<string | null>(null)const [edits, setEdits] = useState<Map<string, CellEdit>>(() => new Map())// Keys already written to the server, kept in `edits` until the refetch// carries their values — see the release effect below.@@ -361,6 +365,7 @@ export function BulkPriceEditor({setEdits(new Map())setSavedPending(new Set())setDraftRungs([])+ setSaveError(null)}, [priceListId, currency, filterKey])// Releases a saved edit once the refetched row agrees with it, so the cell@@ -461,6 +466,7 @@ export function BulkPriceEditor({const handleChange = useCallback((rowId: string, field: 'amount' | 'compareAt', next: string | null) => {+ setSaveError(null)// Typing a price into the trailing blank row is what creates the rung.const promoted = promoteBlankRow(rowId)const targetId = promoted ?? rowId@@ -524,6 +530,7 @@ export function BulkPriceEditor({const changeTierQuantity = useCallback((rowId: string, value: string) => {+ setSaveError(null)const promoted = promoteBlankRow(rowId)const targetId = promoted ?? rowId@@ -559,6 +566,7 @@ export function BulkPriceEditor({const removeTier = useCallback((rowId: string) => {+ setSaveError(null)// A draft rung has nothing stored to remove; a saved one is cleared by// sending a blank amount, which the bulk endpoint reads as "delete this".if (rowId.startsWith('draft:')) {@@ -614,12 +622,11 @@ export function BulkPriceEditor({return edit != null && !edit.removing && Boolean(edit.minQuantity) && !edit.amount})if (incomplete) {- toastManager.add({- type: 'error',- title: t('admin.pages.products.price_lists.edit_prices.tier_needs_price', {+ setSaveError(+ t('admin.pages.products.price_lists.edit_prices.tier_needs_price', {quantity: edits.get(incomplete)?.minQuantity ?? '',}),- })+ )return false}// Ship the unique-key triple `(variant_id, currency, price_list_id)`@@ -663,6 +670,7 @@ export function BulkPriceEditor({},]})+ setSaveError(null)try {const res = await bulkUpsertAsync({ prices: payload })toastManager.add({@@ -680,16 +688,17 @@ export function BulkPriceEditor({setSavedPending((prev) => new Set([...prev, ...savedKeys]))return true} catch (err) {- const message =+ setSaveError(err instanceof Error? err.message- : t('admin.pages.products.price_lists.edit_prices.save_failed')- toastManager.add({ type: 'error', title: message })+ : t('admin.pages.products.price_lists.edit_prices.save_failed'),+ )return false}}, [edits, savedPending, currency, priceListId, bulkUpsertAsync, marketLocale, t])const discard = useCallback(() => {+ setSaveError(null)setEdits(new Map())setSavedPending(new Set())setDraftRungs([])@@ -771,6 +780,7 @@ export function BulkPriceEditor({tierRemove: t('admin.pages.products.price_lists.tiers.remove_short'),tierQuantity: t('admin.pages.products.price_lists.tiers.quantity'),}}+ error={saveError}/>)}diff --git a/spree/api/app/controllers/spree/api/v3/admin/prices_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/prices_controller.rbindex df1dd80c88..2737fb4002 100644--- a/spree/api/app/controllers/spree/api/v3/admin/prices_controller.rb+++ b/spree/api/app/controllers/spree/api/v3/admin/prices_controller.rb@@ -58,6 +58,10 @@ module Spree# validations (docs/plans/6.0-volume-pricing.md). Each branch is# guarded on the key its own failure carries, so a failure mode the# service grows later is not reported under one of these names.+ #+ # `I18n.t` rather than `Spree.t` for these: the models raise them+ # under `activerecord.errors`, and `Spree.t` would scope the lookup+ # to `spree.` and miss the key.if (invalid = result.error&.value.try(:[], :invalid_quantities))return render_error(code: 'invalid_min_quantity',@@ -70,16 +74,34 @@ module Spreeif (negative = result.error&.value.try(:[], :invalid_amounts))return render_error(code: 'invalid_amount',- message: Spree.t('activerecord.errors.models.spree/price_list.attributes.base.negative_price').upcase_first,+ message: I18n.t('activerecord.errors.models.spree/price_list.attributes.base.negative_price').upcase_first,status: :unprocessable_content,details: { rows: negative })end+ if (misplaced = result.error&.value.try(:[], :quantities_on_base_prices))+ return render_error(+ code: 'quantity_on_base_price',+ message: I18n.t('activerecord.errors.models.spree/price_list.attributes.base.quantity_on_base_price').upcase_first,+ status: :unprocessable_content,+ details: { rows: misplaced }+ )+ end++ if (duplicates = result.error&.value.try(:[], :duplicate_quantities))+ return render_error(+ code: 'duplicate_min_quantity',+ message: I18n.t('activerecord.errors.models.spree/price_list.attributes.base.duplicate_quantity').upcase_first,+ status: :unprocessable_content,+ details: { rows: duplicates }+ )+ end+if (over_cap = result.error&.value.try(:[], :over_cap))return render_error(code: 'too_many_breaks',- message: Spree.t(+ message: I18n.t('activerecord.errors.models.spree/price.attributes.min_quantity.too_many_breaks',count: Spree::Price::MAXIMUM_BREAKS_PER_VARIANT).upcase_first,@@ -88,6 +110,15 @@ module Spree)end+ if (rising = result.error&.value.try(:[], :rising_ladders))+ return render_error(+ code: 'price_rises_with_quantity',+ message: I18n.t('activerecord.errors.models.spree/price_list.attributes.base.price_rises_with_quantity').upcase_first,+ status: :unprocessable_content,+ details: { ladders: rising }+ )+ end+render json: result.valueenddiff --git a/spree/api/spec/controllers/spree/api/v3/admin/prices_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/prices_controller_spec.rbindex 9b2f318bc9..6bc25a52d6 100644--- a/spree/api/spec/controllers/spree/api/v3/admin/prices_controller_spec.rb+++ b/spree/api/spec/controllers/spree/api/v3/admin/prices_controller_spec.rb@@ -415,6 +415,38 @@ RSpec.describe Spree::Api::V3::Admin::PricesController, type: :controller doexpect(response).to have_http_status(:ok)expect(Spree::Price.where(variant: variant, currency: 'USD', price_list: price_list).pluck(:amount).uniq).to eq([8.0])end++ # A break the list does not undercut charges more for a bigger order. With+ # no rung of its own the floor is the shop price, which is what the buyer+ # pays right up to the threshold.+ it 'refuses a break that costs more than the shop price' do+ upsert([{ variant_id: variant.prefixed_id, currency: 'USD',+ price_list_id: price_list.prefixed_id, min_quantity: 100, amount: '440.00' }])++ expect(response).to have_http_status(:unprocessable_content)+ expect(json_response['error']['code']).to eq('price_rises_with_quantity')+ expect(Spree::Price.where(variant: variant, currency: 'USD', price_list: price_list)).to be_empty+ end++ it 'accepts a break that undercuts the shop price without a rung of its own' do+ upsert([{ variant_id: variant.prefixed_id, currency: 'USD',+ price_list_id: price_list.prefixed_id, min_quantity: 100, amount: '9.00' }])++ expect(response).to have_http_status(:ok)+ end++ # Keeping the later row would answer 200 while discarding a price the+ # merchant typed.+ it 'refuses two rows addressing the same quantity' do+ upsert([+ { variant_id: variant.prefixed_id, currency: 'USD', price_list_id: price_list.prefixed_id, min_quantity: 100, amount: '9.00' },+ { variant_id: variant.prefixed_id, currency: 'USD', price_list_id: price_list.prefixed_id, min_quantity: 100, amount: '8.00' }+ ])++ expect(response).to have_http_status(:unprocessable_content)+ expect(json_response['error']['code']).to eq('duplicate_min_quantity')+ expect(Spree::Price.where(variant: variant, currency: 'USD', price_list: price_list)).to be_empty+ endenddescribe 'POST #create' dodiff --git a/spree/core/app/models/spree/price.rb b/spree/core/app/models/spree/price.rbindex a0fb070ebd..0b04778be7 100644--- a/spree/core/app/models/spree/price.rb+++ b/spree/core/app/models/spree/price.rb@@ -56,6 +56,7 @@ module Spreenumericality: { only_integer: true, greater_than: 0 }validate :break_requires_price_listvalidate :breaks_within_cap+ validate :ladder_does_not_risescope :with_currency, ->(currency) { where(currency: currency) }scope :non_zero, -> { where.not(amount: [nil, 0]) }@@ -229,6 +230,31 @@ module Spreevariant&.product&.storeend+ # The first rung of `[[quantity, amount], ...]` costing more than the+ # quantity below it buys — the rung beneath, or `floor` for a ladder+ # starting above one unit. Returned as `[quantity, amount, floor]`.+ #+ # @param ladder [Array<Array>] rungs by quantity+ # @param floor [BigDecimal, nil]+ # @return [Array, nil]+ def self.rising_rung(ladder, floor)+ bottom_quantity, bottom_amount = ladder.first+ return if bottom_quantity.nil?++ # The bottom rung answers to the floor, and is checked first so the rung+ # named is the first breach reading upward — a merchant who fixes what+ # they are told to fix should not meet a second error beneath it.+ if bottom_quantity != 1 && floor.present? && bottom_amount > floor+ return [bottom_quantity, bottom_amount, floor]+ end++ ladder.each_cons(2) do |(_, below), (quantity, amount)|+ return [quantity, amount, below] if amount > below+ end++ nil+ end+# Whether this row is a quantity break rather than the list's ordinary# price for the variant.# @return [Boolean]@@ -268,6 +294,54 @@ module Spreeerrors.add(:min_quantity, :too_many_breaks, count: MAXIMUM_BREAKS_PER_VARIANT)end+ # A break promises a better price for a bigger order, so no rung may cost+ # more than the quantity below it buys. Judged over the ladder this save+ # would leave behind rather than this row alone: lowering one rung strands+ # every rung above it, and a base price is the floor each ladder falls+ # through to. The bulk path judges the same way; this covers the+ # single-row writers, as the break cap is covered on both+ # (docs/plans/6.0-volume-pricing.md).+ def ladder_does_not_rise+ return if amount.nil? || variant_id.blank? || currency.blank?+ return unless new_record? || will_save_change_to_attribute?(:amount) || will_save_change_to_attribute?(:min_quantity)++ breach = affected_ladders.lazy.filter_map { |list_id, floor| self.class.rising_rung(resulting_ladder(list_id), floor) }.first+ return if breach.nil?++ errors.add(:amount, :leaves_a_rising_ladder,+ quantity: breach[0],+ amount: Spree::Money.new(breach[1], currency: currency),+ floor: Spree::Money.new(breach[2], currency: currency))+ end++ # The ladders this row can disturb, each with the floor it falls through+ # to: its own list for a break, and every ladder the variant carries for a+ # base price, since that is the floor they all read.+ #+ # @return [Array<Array>] `[[price_list_id, floor], ...]`+ def affected_ladders+ if price_list_id.present?+ base = self.class.base_prices.where(variant_id: variant_id, currency: currency).+ where.not(amount: nil).pick(:amount)+ return [[price_list_id, base]]+ end++ self.class.where(variant_id: variant_id, currency: currency).+ where.not(price_list_id: nil).where.not(amount: nil).+ distinct.pluck(:price_list_id).map { |list_id| [list_id, amount] }+ end++ # One list's rungs as this save would leave them, by quantity.+ #+ # @return [Array<Array>] `[[quantity, amount], ...]`+ def resulting_ladder(list_id)+ rows = self.class.where(variant_id: variant_id, currency: currency, price_list_id: list_id).where.not(amount: nil)+ rows = rows.where.not(id: id) if persisted?+ rungs = rows.pluck(:min_quantity, :amount).to_h+ rungs[min_quantity] = amount if price_list_id == list_id+ rungs.sort_by(&:first)+ end+def should_record_price_history?price_list_id.nil? &&amount.present? &&diff --git a/spree/core/app/services/spree/imports/row_processors/price_list_price.rb b/spree/core/app/services/spree/imports/row_processors/price_list_price.rbindex 9aaa2ddd57..b404a7895a 100644--- a/spree/core/app/services/spree/imports/row_processors/price_list_price.rb+++ b/spree/core/app/services/spree/imports/row_processors/price_list_price.rb@@ -154,6 +154,12 @@ module SpreeSpree.t(:price_list_import_too_many_breaks, count: Spree::Price::MAXIMUM_BREAKS_PER_VARIANT)elsif value[:invalid_quantities].present?Spree.t(:price_list_import_invalid_quantity, value: attributes['min_quantity'])+ elsif (rising = value[:rising_ladders].presence)+ # Named rung and floor, like the sibling branches: a file is written+ # one rung per row, so the merchant needs to know which one and what+ # it had to beat.+ Spree.t(:price_list_import_price_rises_with_quantity,+ quantity: rising.first[:min_quantity], floor: rising.first[:floor])elseresult.error.to_s.presence || Spree.t(:price_list_import_failed)enddiff --git a/spree/core/app/services/spree/prices/bulk_upsert.rb b/spree/core/app/services/spree/prices/bulk_upsert.rbindex e12332de01..cd3dde29ba 100644--- a/spree/core/app/services/spree/prices/bulk_upsert.rb+++ b/spree/core/app/services/spree/prices/bulk_upsert.rb@@ -35,11 +35,13 @@ module Spree# @return [Spree::ServiceModule::Result] success carries# `{ price_count: N }` — the number of rows passed to `upsert_all`.# Fails with the offending rows when a batch carries an unusable- # `min_quantity`, or would take a variant past- # {Spree::Price::MAXIMUM_BREAKS_PER_VARIANT} breaks on one list. This- # path writes in SQL and runs no model validations, so both checks- # live here rather than in each of the three controllers that reach- # it (docs/plans/6.0-volume-pricing.md).+ # `min_quantity`, puts a quantity on a base price, names one rung twice,+ # would take a variant past+ # {Spree::Price::MAXIMUM_BREAKS_PER_VARIANT} breaks on one list, or+ # would leave a ladder charging more for a bigger order. This path+ # writes in SQL and runs no model validations, so the checks live here+ # rather than in each of the three writers that reach it+ # (docs/plans/6.0-volume-pricing.md).def call(rows:)rows = Array(rows).map { |r| r.with_indifferent_access }# Amounts are parsed once, here; everything below reads numbers.@@ -54,20 +56,35 @@ module Spreenegative = rows_with_negative_amount(keyed)return failure(nil, invalid_amounts: negative) if negative.any?- # PG rejects an upsert with two rows hitting the same unique key in one- # statement ("ON CONFLICT DO UPDATE command cannot affect row a second- # time"). Last-write-wins: keep the last occurrence of each key.- deduped = keyed.reverse.uniq { |r| row_key(r) }.reverse- upsert_rows, clear_rows = deduped.partition { |r| r[:amount].present? }+ # A base price is one row per (variant, currency) whatever quantity it+ # names, so a quantity here would upsert onto a key it does not+ # describe. The model refuses it in `break_requires_price_list`, which+ # this SQL path never runs.+ misplaced = base_rows_with_quantity(keyed)+ return failure(nil, quantities_on_base_prices: misplaced) if misplaced.any?++ duplicates = rows_with_duplicate_quantity(keyed)+ return failure(nil, duplicate_quantities: duplicates) if duplicates.any?++ upsert_rows, clear_rows = keyed.partition { |r| r[:amount].present? }+ # A clear at a quantity the batch also prices is a rung moving onto+ # it, so the amount wins.+ claimed = upsert_rows.map { |r| row_key(r) }.to_set+ clear_rows = clear_rows.reject { |r| claimed.include?(row_key(r)) }payload = build_payload(upsert_rows)- affected_keys = deduped.map { |r| row_key(r) }+ affected_keys = (upsert_rows + clear_rows).map { |r| row_key(r) }return success(price_count: 0) if affected_keys.empty?- over_cap = ladders_over_cap(upsert_rows, clear_rows)+ stored = stored_rungs(upsert_rows + clear_rows)++ over_cap = ladders_over_cap(upsert_rows, clear_rows, stored)return failure(nil, over_cap: over_cap) if over_cap.any?+ rising = rising_ladders(upsert_rows, clear_rows, stored)+ return failure(nil, rising_ladders: rising) if rising.any?+base_rows, override_rows = payload.partition { |r| r[:price_list_id].nil? }Spree::Price.transaction do@@ -129,7 +146,7 @@ module Spree# quantity address the bottom rung, which is every row written before# breaks existed (docs/plans/6.0-volume-pricing.md).def row_key(row)- [row[:variant_id], row[:currency], row[:price_list_id], quantity_of(row)]+ [row[:variant_id].to_s, row[:currency], row[:price_list_id].presence&.to_s, quantity_of(row)]end# Absent means the ladder's bottom rung. Anything present must be a@@ -182,55 +199,177 @@ module Spree# constant is named: breaks *above* the bottom rung, so a variant priced# at one figure plus ten breaks is exactly at the limit.#- # Only ladders the batch actually adds a break to are checked, so an- # ordinary spreadsheet save — one quantity-1 row per variant — costs no- # extra queries at all.- ## @param rows [Array<Hash>] the rows carrying an amount# @param cleared_rows [Array<Hash>] the rows whose blank amount removes a rung+ # @param stored [Hash] `{ ladder_key => { quantity => amount } }` as stored# @return [Array<Hash>] `[{ variant_id:, currency:, price_list_id: }, ...]`- def ladders_over_cap(rows, cleared_rows = [])- touched = rows.- reject { |row| row[:price_list_id].blank? || quantity_of(row) == 1 }.- group_by { |row| [row[:variant_id].to_s, row[:currency], row[:price_list_id].to_s] }.- transform_values { |group| group.map { |row| quantity_of(row) }.to_set }+ def ladders_over_cap(rows, cleared_rows, stored)+ touched = breaks_by_ladder(rows)return [] if touched.empty?- cleared = cleared_rows.- reject { |row| row[:price_list_id].blank? || quantity_of(row) == 1 }.- group_by { |row| [row[:variant_id].to_s, row[:currency], row[:price_list_id].to_s] }.- transform_values { |group| group.map { |row| quantity_of(row) }.to_set }-- # One query for every ladder in the batch rather than one each: an- # import writing a ladder across two hundred variants would otherwise- # issue two hundred round trips inside the request. Cross-pairs the- # `IN` clauses pull in are dropped by the lookup below, the same way- # #sweep handles them.- # Placeholder rows charge nothing, so they do not fill a ladder — the- # model's own guard counts the same way, and a cap two writers- # disagree about is one that refuses what it just allowed.- stored = Spree::Price.- where(variant_id: touched.keys.map { |key| key[0] },- currency: touched.keys.map { |key| key[1] },- price_list_id: touched.keys.map { |key| key[2] }).- breaks.- where.not(amount: nil).- pluck(:variant_id, :currency, :price_list_id, :min_quantity).- group_by { |variant_id, currency, price_list_id, _| [variant_id.to_s, currency, price_list_id.to_s] }+ cleared = breaks_by_ladder(cleared_rows)touched.filter_map do |key, incoming|# Stored rungs this batch does not name are the ones that survive it;# counting the rest as well would refuse a merchant who deleted two# rungs and added two others, whose ladder ends the size it began.- # The deletions ride in `clear_rows` and the sweep applies them, so- # what is left after this batch is (survivors + incoming).- survivors = stored.fetch(key, []).map(&:last).to_set - cleared.fetch(key, Set.new)+ survivors = stored.fetch(key, {}).keys.reject { |quantity| quantity == 1 }.to_set - cleared.fetch(key, Set.new)next if (survivors | incoming).size <= Spree::Price::MAXIMUM_BREAKS_PER_VARIANT{ variant_id: key[0], currency: key[1], price_list_id: key[2] }endend+ # The break quantities each ladder in these rows carries.+ def breaks_by_ladder(rows)+ rows.+ reject { |row| row[:price_list_id].blank? || quantity_of(row) == 1 }.+ group_by { |row| ladder_key(row) }.+ transform_values { |group| group.map { |row| quantity_of(row) }.to_set }+ end++ # Base-price rows naming a quantity. A base price is one row per+ # (variant, currency), so the quantity describes nothing and the row+ # would upsert onto a key it does not match.+ #+ # @return [Array<Hash>] `[{ index: }, ...]`+ def base_rows_with_quantity(rows)+ rows.each_with_index.filter_map do |row, index|+ { index: index } if row[:price_list_id].blank? && quantity_of(row) != 1+ end+ end++ # Rows repeating a rung the batch has already priced. Only amounts+ # collide: a clear at the same key is a rung moving onto it, which #call+ # resolves in favour of the amount.+ #+ # @param rows [Array<Hash>]+ # @return [Array<Hash>] `[{ index:, min_quantity: }, ...]`+ def rows_with_duplicate_quantity(rows)+ seen = Set.new++ rows.each_with_index.filter_map do |row, index|+ next if row[:amount].blank?++ { index: index, min_quantity: quantity_of(row) } unless seen.add?(row_key(row))+ end+ end++ # Ladders this batch would leave charging more for a bigger order. A rung+ # must not cost more than the rung beneath it, or than the base price for+ # a ladder starting above one unit; a bottom rung above base is a dearer+ # agreement, which is allowed. Judged on the state the batch leaves, not+ # on what it changed: no write path can produce a rising ladder, so one+ # found rising came from outside them and must be repaired rather than+ # built on. Base is the floor even where another list would undercut it+ # below the threshold — the write path cannot know which list wins for+ # which buyer (docs/plans/6.0-volume-pricing.md).+ #+ # @param rows [Array<Hash>] the rows carrying an amount+ # @param cleared_rows [Array<Hash>] the rows whose blank amount removes a rung+ # @param stored [Hash] `{ ladder_key => { quantity => amount } }` as stored+ # @return [Array<Hash>] the offending rung and the price it must not exceed+ def rising_ladders(rows, cleared_rows, stored)+ keys = ladder_keys_to_check(rows + cleared_rows, stored)+ return [] if keys.empty?++ incoming = rungs_by_ladder(rows)+ cleared = breaks_and_bottom_by_ladder(cleared_rows)+ floors = base_floors(rows, cleared_rows, keys)++ keys.filter_map do |key|+ dropped = cleared.fetch(key, Set.new)+ now = stored.fetch(key, {}).reject { |quantity, _| dropped.include?(quantity) }.+ merge(incoming.fetch(key, {}))++ breach = Spree::Price.rising_rung(now.sort_by(&:first), floors[key.first(2)])+ next if breach.nil?++ { variant_id: key[0], currency: key[1], price_list_id: key[2],+ min_quantity: breach[0], amount: breach[1], floor: breach[2] }+ end+ end++ # The ladders whose shape or floor this batch could change: those it+ # writes rows on, plus every stored ladder of a variant whose base price+ # it moves — lowering the shop price under a break raises the bill at the+ # threshold just as surely as mispricing the break.+ def ladder_keys_to_check(rows, stored)+ own = rows.reject { |row| row[:price_list_id].blank? }.map { |row| ladder_key(row) }+ rebased = rows.select { |row| row[:price_list_id].blank? }.+ map { |row| [row[:variant_id].to_s, row[:currency]] }.to_set+ return own.uniq if rebased.empty?++ (own + stored.keys.select { |key| rebased.include?(key.first(2)) }).uniq+ end++ # `{ ladder_key => { quantity => amount } }` for these rows.+ def rungs_by_ladder(rows)+ rows.+ reject { |row| row[:price_list_id].blank? }.+ group_by { |row| ladder_key(row) }.+ transform_values { |group| group.to_h { |row| [quantity_of(row), row[:amount]] } }+ end++ # Every quantity these rows remove, bottom rung included — unlike the cap+ # check, which only counts breaks.+ def breaks_and_bottom_by_ladder(rows)+ rows.+ reject { |row| row[:price_list_id].blank? }.+ group_by { |row| ladder_key(row) }.+ transform_values { |group| group.map { |row| quantity_of(row) }.to_set }+ end++ # The stored rungs of every ladder this batch touches, and of every+ # ladder whose base price it moves. Placeholder rows charge nothing, so a+ # ladder whose quantity-1 row is a placeholder starts at its first real+ # break. Cross-pairs the `IN` clauses pull in are dropped by the lookup,+ # as in #sweep.+ #+ # @param rows [Array<Hash>]+ # @return [Hash] `{ ladder_key => { quantity => amount } }`+ def stored_rungs(rows)+ variant_ids = rows.map { |row| row[:variant_id] }.uniq+ currencies = rows.map { |row| row[:currency] }.uniq+ return {} if variant_ids.empty?++ Spree::Price.+ where(variant_id: variant_ids, currency: currencies).+ where.not(price_list_id: nil).+ where.not(amount: nil).+ pluck(:variant_id, :currency, :price_list_id, :min_quantity, :amount).+ group_by { |variant_id, currency, price_list_id, _, _| [variant_id.to_s, currency, price_list_id.to_s] }.+ transform_values { |rungs| rungs.to_h { |rung| [rung[3], rung[4]] } }+ end++ # The base price each ladder falls through to, as this batch would leave+ # it, so a save that moves both the shop price and a break is judged on+ # the pair it sent.+ #+ # @return [Hash] `{ [variant_id, currency] => amount }`+ def base_floors(rows, cleared_rows, keys)+ pairs = keys.map { |key| key.first(2) }.uniq+ return {} if pairs.empty?++ stored = Spree::Price.+ where(variant_id: pairs.map(&:first), currency: pairs.map(&:last), price_list_id: nil).+ where.not(amount: nil).+ pluck(:variant_id, :currency, :amount).+ to_h { |variant_id, currency, amount| [[variant_id.to_s, currency], amount] }++ written = rows.select { |row| row[:price_list_id].blank? }.+ to_h { |row| [[row[:variant_id].to_s, row[:currency]], row[:amount]] }+ removed = cleared_rows.select { |row| row[:price_list_id].blank? }.+ map { |row| [row[:variant_id].to_s, row[:currency]] }++ stored.merge(written).except(*removed)+ end++ # A ladder is one variant's rungs, in one currency, on one list.+ def ladder_key(row)+ [row[:variant_id].to_s, row[:currency], row[:price_list_id].to_s]+ end+# Parses locale-aware decimal input ("1.234,56" in DE, "1,234.56"# in en-US). Numeric values pass through; blank values become nil.def parse_amount(value)@@ -254,7 +393,7 @@ module Spree.pluck(:id, :variant_id, :currency, :price_list_id, :min_quantity, :amount)doomed_ids = candidates.filter_map do |id, variant_id, currency, price_list_id, min_quantity, amount|- key = [variant_id, currency, price_list_id, min_quantity]+ key = [variant_id.to_s, currency, price_list_id&.to_s, min_quantity]next unless affected_set.include?(key)next id if amount.nil?next id if cleared_keys.include?(key)diff --git a/spree/core/app/workflows/spree/price_lists/update.rb b/spree/core/app/workflows/spree/price_lists/update.rbindex 96c15cd630..d26547f753 100644--- a/spree/core/app/workflows/spree/price_lists/update.rb+++ b/spree/core/app/workflows/spree/price_lists/update.rb@@ -65,6 +65,12 @@ module Spreeprice_list.errors.add(:base, :negative_price)elsif refusal[:invalid_quantities].present?price_list.errors.add(:base, :invalid_quantity)+ elsif refusal[:quantities_on_base_prices].present?+ price_list.errors.add(:base, :quantity_on_base_price)+ elsif refusal[:duplicate_quantities].present?+ price_list.errors.add(:base, :duplicate_quantity)+ elsif refusal[:rising_ladders].present?+ price_list.errors.add(:base, :price_rises_with_quantity)elseprice_list.errors.add(:base, :too_many_breaks, count: Spree::Price::MAXIMUM_BREAKS_PER_VARIANT)enddiff --git a/spree/core/config/locales/en.yml b/spree/core/config/locales/en.ymlindex 5abee4f3b9..63c5499415 100644--- a/spree/core/config/locales/en.yml+++ b/spree/core/config/locales/en.yml@@ -375,6 +375,8 @@ en:greater_than_max_amount: is greater than the allowed maximum amount of %{max_amount}spree/price:attributes:+ amount:+ leaves_a_rising_ladder: would leave the price from %{quantity} units at %{amount}, above the %{floor} a buyer pays below that quantitymin_quantity:requires_price_list: quantity breaks can only be set on a price listtoo_many_breaks: a variant can carry at most %{count} quantity breaks on one price list@@ -385,9 +387,12 @@ en:spree/price_list:attributes:base:+ duplicate_quantity: each quantity break must have its own quantityinvalid_quantity: each quantity break must start at a whole number of unitsnegative_price: a price cannot be below zeronothing_to_apply_to: has no rules, no catalog and no products, so it would apply to nothing. Add one before activating.+ price_rises_with_quantity: a quantity break cannot cost more than the price a buyer pays below it+ quantity_on_base_price: a shop price applies at every quantity, so it cannot start at one. Remove the quantity, or pick a price list to put the break on.ends_at:must_be_after_starts_at: must be after starts atprice_adjustment_percentage:@@ -1537,6 +1542,7 @@ en:price_list_import_invalid_amount: "%{column} must be a number like 16.50, got %{value}."price_list_import_invalid_quantity: min_quantity must be a whole number of units, got %{value}.price_list_import_no_price_list: This import is not attached to a price list.+ price_list_import_price_rises_with_quantity: The price from %{quantity} units must not be above %{floor}, what a buyer pays below that quantity. A file is applied a row at a time, so list the higher quantities first when lowering a whole ladder.price_list_import_sku_required: SKU is required.price_list_import_too_many_breaks: A variant can carry at most %{count} quantity breaks on one price list.price_list_import_unknown_sku: No product in this store has the SKU %{sku}.diff --git a/spree/core/spec/models/spree/price_spec.rb b/spree/core/spec/models/spree/price_spec.rbindex d0c4961b6a..4e171edbe9 100644--- a/spree/core/spec/models/spree/price_spec.rb+++ b/spree/core/spec/models/spree/price_spec.rb@@ -588,4 +588,68 @@ describe Spree::Price, type: :model doexpect(base.final_for_destination?).to be(false)endend++ # The single-row writers reach the same rule the bulk path enforces over a+ # whole batch — the admin price endpoints write through the model+ # (docs/plans/6.0-volume-pricing.md).+ describe 'a ladder that charges more for a bigger order' do+ let(:price_list) { create(:price_list, store: @default_store) }+ let(:variant) { create(:variant, price: 10.00) }++ def rung(quantity, amount)+ Spree::Price.create!(variant: variant, currency: 'USD', price_list: price_list,+ min_quantity: quantity, amount: amount)+ end++ it 'refuses a break above the rung below it' do+ rung(10, 9.00)+ price = Spree::Price.new(variant: variant, currency: 'USD', price_list: price_list,+ min_quantity: 20, amount: 9.50)++ expect(price).not_to be_valid+ expect(price.errors[:amount].first).to include('20')+ end++ it 'refuses a break above the base price when the list prices nothing below' do+ price = Spree::Price.new(variant: variant, currency: 'USD', price_list: price_list,+ min_quantity: 100, amount: 12.00)++ expect(price).not_to be_valid+ end++ # Lowering a rung strands every rung above it, which the row being saved+ # cannot see by looking downward alone.+ it 'refuses lowering a rung below one that sits above it' do+ low = rung(10, 9.00)+ rung(20, 8.00)+ low.amount = 7.00++ expect(low).not_to be_valid+ expect(low.errors[:amount].first).to include('20')+ end++ # A base price is the floor every one of the variant's ladders reads.+ it 'refuses dropping the base price below a break' do+ rung(100, 9.00)+ base = variant.prices.find_by(price_list_id: nil, currency: 'USD')+ base.amount = 2.00++ expect(base).not_to be_valid+ end++ it 'accepts a descending ladder and a flat one' do+ rung(10, 9.00)++ expect(Spree::Price.new(variant: variant, currency: 'USD', price_list: price_list,+ min_quantity: 20, amount: 8.00)).to be_valid+ expect(Spree::Price.new(variant: variant, currency: 'USD', price_list: price_list,+ min_quantity: 20, amount: 9.00)).to be_valid+ end++ # An agreement may be dearer than the shop; only breaks promise less.+ it 'accepts a bottom rung above the base price' do+ expect(Spree::Price.new(variant: variant, currency: 'USD', price_list: price_list,+ min_quantity: 1, amount: 25.00)).to be_valid+ end+ endenddiff --git a/spree/core/spec/services/spree/prices/bulk_upsert_spec.rb b/spree/core/spec/services/spree/prices/bulk_upsert_spec.rbindex 8655d22d5c..cf58f11934 100644--- a/spree/core/spec/services/spree/prices/bulk_upsert_spec.rb+++ b/spree/core/spec/services/spree/prices/bulk_upsert_spec.rb@@ -164,7 +164,9 @@ RSpec.describe Spree::Prices::BulkUpsert dolet(:price_list) { create(:price_list, store: @default_store) }let(:variant) { create(:variant) }- def rung(quantity, amount = '9.00')+ # Below the $5.00 bottom rung these specs inherit from `override`: a cap+ # spec must build a ladder that is otherwise legal.+ def rung(quantity, amount = '4.00'){ variant_id: variant.id, currency: 'USD', price_list_id: price_list.id,min_quantity: quantity, amount: amount }end@@ -189,7 +191,7 @@ RSpec.describe Spree::Prices::BulkUpsert dorows = (2..(Spree::Price::MAXIMUM_BREAKS_PER_VARIANT + 1)).map { |q| rung(q) }described_class.call(rows: rows)- expect(described_class.call(rows: rows.map { |row| row.merge(amount: '8.00') })).to be_success+ expect(described_class.call(rows: rows.map { |row| row.merge(amount: '3.00') })).to be_successend# A merchant who drops two rungs and adds two others ends with the ladder@@ -249,13 +251,227 @@ RSpec.describe Spree::Prices::BulkUpsert doexpect(described_class.call(rows: [{ variant_id: variant.id, currency: 'USD',price_list_id: price_list.id, amount: '10.00' }])).to be_successend+ end++ # A quantity break that costs more than the quantity below it buys is the+ # opposite of what it says, and the resolver charges it without comparing+ # (docs/plans/6.0-volume-pricing.md).+ describe 'a ladder that charges more for a bigger order' do+ let(:price_list) { create(:price_list, store: @default_store) }+ let(:variant) { create(:variant, price: 39.99) }+ # These build their own ladders; the outer override would seed a bottom+ # rung none of them asked for.+ let!(:override) { nil }++ def rung(quantity, amount)+ { variant_id: variant.id, currency: 'USD', price_list_id: price_list.id,+ min_quantity: quantity, amount: amount }+ end++ it 'refuses a break priced above the rung below it' do+ result = described_class.call(rows: [rung(1, '30.00'), rung(100, '20.00'), rung(200, '25.00')])++ expect(result).to be_failure+ expect(result.error.value[:rising_ladders].first).to include(min_quantity: 200, floor: BigDecimal('20.00'))+ expect(Spree::Price.where(price_list: price_list, variant: variant)).to be_empty+ end++ # The reported bug: with no rung of its own the ladder's floor is the shop+ # price, which is what the buyer pays right up to the threshold.+ it 'refuses a break priced above the base price when the list has no bottom rung' do+ result = described_class.call(rows: [rung(100, '440.00')])++ expect(result).to be_failure+ expect(result.error.value[:rising_ladders].first).to include(min_quantity: 100, floor: BigDecimal('39.99'))+ end++ it 'accepts a break below the base price when the list has no bottom rung' do+ expect(described_class.call(rows: [rung(100, '35.00')])).to be_success+ end++ it 'accepts a descending ladder' do+ expect(described_class.call(rows: [rung(1, '30.00'), rung(100, '20.00'), rung(200, '15.00')])).to be_success+ end++ it 'accepts a ladder that holds one price at every quantity' do+ expect(described_class.call(rows: [rung(1, '30.00'), rung(100, '30.00')])).to be_success+ end- # An ordinary spreadsheet save carries no breaks at all, and must not pay- # for the check.- it 'runs no cap query for a batch of bottom rungs' do- expect(Spree::Price).not_to receive(:breaks)+ # A merchant fixes the rung they are told to fix, so the one named is the+ # first breach reading upward — not a later pair that happens to be found+ # while walking the ladder.+ it 'names the bottom rung when it and a later pair both breach' do+ result = described_class.call(rows: [rung(25, '45.00'), rung(50, '50.00')])- expect(described_class.call(rows: [rung(1, '10.00')])).to be_success+ expect(result).to be_failure+ expect(result.error.value[:rising_ladders].first).to include(min_quantity: 25, floor: BigDecimal('39.99'))+ end++ # Lowering the shop price under a break raises the bill at the threshold+ # just as surely as mispricing the break, and the batch names no rung.+ it 'refuses a base price dropped below a stored break' do+ described_class.call(rows: [rung(100, '35.00')])++ result = described_class.call(rows: [{ variant_id: variant.id, currency: 'USD', amount: '10.00' }])++ expect(result).to be_failure+ expect(result.error.value[:rising_ladders].first).to include(min_quantity: 100)+ expect(variant.prices.find_by(price_list_id: nil, currency: 'USD').amount).to eq(BigDecimal('39.99'))+ end++ # Removing the bottom rung drops the ladder onto the shop price, and the+ # batch carries nothing but the removal.+ it 'refuses a cleared bottom rung that leaves a break above the base price' do+ # Legal as it stands: the bottom rung may sit above the $39.99 base, and+ # the break undercuts it. Removing the bottom rung drops the break onto+ # the base, which it does not undercut.+ described_class.call(rows: [rung(1, '50.00'), rung(100, '45.00')])++ expect(described_class.call(rows: [rung(1, nil)])).to be_failure+ expect(Spree::Price.find_by(variant: variant, price_list: price_list, min_quantity: 1)&.amount).to eq(50)+ end++ # No write path can leave a ladder rising, so one found rising was planted+ # from outside them — raw SQL, or data predating the rule. It is repaired+ # rather than built on: every save is judged on the state it would leave.+ it 'refuses to build on a ladder that is already rising' do+ Spree::Price.insert_all!([{ variant_id: variant.id, currency: 'USD', price_list_id: price_list.id,+ min_quantity: 1, amount: 30, created_at: Time.current, updated_at: Time.current },+ { variant_id: variant.id, currency: 'USD', price_list_id: price_list.id,+ min_quantity: 200, amount: 45, created_at: Time.current, updated_at: Time.current }])++ # Editing elsewhere, and adding a rung above the breach, both leave it standing.+ expect(described_class.call(rows: [rung(1, '28.00')])).to be_failure+ expect(described_class.call(rows: [rung(300, '50.00')])).to be_failure++ # Repairing the offending rung is what the merchant can always do.+ expect(described_class.call(rows: [rung(200, '20.00')])).to be_success+ end++ # An agreement is free to be dearer than the shop; only a break promises a+ # better price for a bigger order.+ it 'accepts a bottom rung above the base price' do+ expect(described_class.call(rows: [rung(1, '99.00')])).to be_success+ expect(described_class.call(rows: [rung(1, '99.00'), rung(100, '50.00')])).to be_success+ end++ it 'reads the rungs already stored, not only the batch' do+ described_class.call(rows: [rung(1, '30.00'), rung(100, '20.00')])++ expect(described_class.call(rows: [rung(200, '25.00')])).to be_failure+ expect(described_class.call(rows: [rung(200, '15.00')])).to be_success+ end++ # Removing the bottom rung drops the ladder onto the shop price, so the+ # break it leaves behind is measured against that instead.+ it 'measures against the base price when the batch clears the bottom rung' do+ described_class.call(rows: [rung(1, '30.00'), rung(100, '20.00')])++ expect(described_class.call(rows: [rung(1, nil), rung(100, '45.00')])).to be_failure+ expect(described_class.call(rows: [rung(1, nil), rung(100, '20.00')])).to be_success+ end++ # A merchant lowering the shop price and adding a break in one save is+ # judged on the pair they sent, not on the price being replaced.+ it 'compares against a base price the same batch writes' do+ rows = [{ variant_id: variant.id, currency: 'USD', amount: '10.00' }, rung(100, '20.00')]++ expect(described_class.call(rows: rows)).to be_failure+ end++ it 'leaves a ladder on another list alone' do+ other = create(:price_list, store: @default_store)+ rows = [rung(1, '30.00'), rung(100, '20.00'),+ { variant_id: variant.id, currency: 'USD', price_list_id: other.id,+ min_quantity: 100, amount: '45.00' }]++ result = described_class.call(rows: rows)++ expect(result).to be_failure+ expect(result.error.value[:rising_ladders].map { |l| l[:price_list_id] }).to eq([other.id.to_s])+ end+ end++ # Two prices at one quantity is a merchant meaning one of them; keeping the+ # later one silently discards the other (docs/plans/6.0-volume-pricing.md).+ describe 'two rows addressing one rung' do+ let(:price_list) { create(:price_list, store: @default_store) }+ let(:variant) { create(:variant, price: 39.99) }+ # These build their own ladders; the outer override would seed a bottom+ # rung none of them asked for.+ let!(:override) { nil }++ def rung(quantity, amount)+ { variant_id: variant.id, currency: 'USD', price_list_id: price_list.id,+ min_quantity: quantity, amount: amount }+ end++ it 'refuses the batch and names the repeated quantity' do+ result = described_class.call(rows: [rung(1, '30.00'), rung(100, '10.00'), rung(100, '25.00')])++ expect(result).to be_failure+ expect(result.error.value[:duplicate_quantities]).to eq([{ index: 2, min_quantity: 100 }])+ expect(Spree::Price.where(price_list: price_list, variant: variant)).to be_empty+ end++ # An absent quantity is the bottom rung, so it collides with an explicit 1.+ it 'counts an absent quantity as the bottom rung' do+ rows = [{ variant_id: variant.id, currency: 'USD', price_list_id: price_list.id, amount: '30.00' },+ rung(1, '25.00')]++ expect(described_class.call(rows: rows)).to be_failure+ end++ # The editor sends a moved rung plus a clear for the row it left behind, so+ # a chain of moves lands both on one quantity. That is one rung, not two.+ it 'takes the amount when a rung moves onto a quantity the batch clears' do+ described_class.call(rows: [rung(10, '30.00'), rung(50, '20.00')])++ result = described_class.call(rows: [rung(50, '30.00'), rung(10, nil), rung(100, '20.00'), rung(50, nil)])++ expect(result).to be_success+ expect(Spree::Price.where(price_list: price_list, variant: variant).where.not(amount: nil).+ order(:min_quantity).pluck(:min_quantity, :amount)).to eq([[50, 30.0], [100, 20.0]])+ end++ # Base prices upsert on `(variant_id, currency)` alone, so a quantity here+ # addresses a key it does not describe — and PG rejects the statement.+ # Reported under its own key: "must be a whole number" says nothing to+ # someone who sent 2.+ it 'refuses a base-price row that names a quantity' do+ rows = [{ variant_id: variant.id, currency: 'USD', min_quantity: 1, amount: '10.00' },+ { variant_id: variant.id, currency: 'USD', min_quantity: 2, amount: '9.00' }]++ result = described_class.call(rows: rows)++ expect(result).to be_failure+ expect(result.error.value[:quantities_on_base_prices]).to eq([{ index: 1 }])+ end++ # The documented CSV contract: a blank quantity and an explicit 1 both mean+ # the variant's regular price.+ it 'accepts a base-price row whose quantity is 1' do+ expect(described_class.call(rows: [{ variant_id: variant.id, currency: 'USD', min_quantity: 1, amount: '10.00' }])).+ to be_success+ end++ # One writer decodes ids to Integer and another leaves them as String; left+ # raw, the same rung reads as two keys and PG rejects the statement.+ it 'counts ids of different Ruby types as one rung' do+ rows = [rung(100, '30.00'),+ { variant_id: variant.id.to_s, currency: 'USD', price_list_id: price_list.id.to_s,+ min_quantity: 100, amount: '20.00' }]++ expect(described_class.call(rows: rows)).to be_failure+ end++ it 'lets one quantity appear once on each of two lists' do+ other = create(:price_list, store: @default_store)+ rows = [rung(100, '30.00'),+ { variant_id: variant.id, currency: 'USD', price_list_id: other.id,+ min_quantity: 100, amount: '25.00' }]++ expect(described_class.call(rows: rows)).to be_successendendend