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
Stop a refused ladder from reporting success
Damian Legawiecb79578059d1f
diff --git a/packages/dashboard/src/components/spree/bulk-price-editor/variant-tier-dialog.tsx b/packages/dashboard/src/components/spree/bulk-price-editor/variant-tier-dialog.tsxindex dd1012fbe9..2f2642f665 100644--- a/packages/dashboard/src/components/spree/bulk-price-editor/variant-tier-dialog.tsx+++ b/packages/dashboard/src/components/spree/bulk-price-editor/variant-tier-dialog.tsx@@ -117,8 +117,10 @@ export function VariantTierDialog({const quantity = Number(rung.minQuantity)return !Number.isInteger(quantity) || quantity < 2 || toCanonical(rung.value) === null})+ // Compared as numbers: "10" and "010" address the same rung, and letting+ // both through means the batch silently keeps one and drops the other.const duplicateQuantity =- new Set(draft.map((rung) => rung.minQuantity.trim())).size !== draft.length+ new Set(draft.map((rung) => Number(rung.minQuantity))).size !== draft.lengthasync function handleSave() {const upserts: PriceBulkUpsertRow[] = draft@@ -132,20 +134,28 @@ export function VariantTierDialog({}))// A rung is identified by its quantity, not by the row it came from:- // moving a break from 24 to 30 writes a new row, so keying the removals- // on the row id would leave the 24 behind and charge it to orders of- // 24-29 (docs/plans/6.0-volume-pricing.md).+ // moving a break from 24 to 30 writes a new row, so keying the removals on+ // the row id would leave the 24 behind and charge it to orders of 24-29+ // (docs/plans/6.0-volume-pricing.md).const keptQuantities = new Set(upserts.map((rung) => rung.min_quantity))- const removedIds = stored++ // Removals ride in the same batch as a blank amount, which is what the+ // bulk endpoint reads as "clear this price". One request rather than two:+ // the server then sees the whole ladder at once, so it neither refuses a+ // rewrite for rungs it is about to drop nor leaves the ladder half erased+ // when a write is refused.+ const removals: PriceBulkUpsertRow[] = stored.filter((rung) => rung.min_quantity > 1 && !keptQuantities.has(rung.min_quantity))- .map((rung) => rung.id)+ .map((rung) => ({+ variant_id: variantId,+ currency,+ price_list_id: priceListId,+ min_quantity: rung.min_quantity,+ amount: null,+ }))try {- // Written before the deletions, so a refused write (the cap, a- // validation) leaves the stored ladder as it was rather than half- // erased with nothing put in its place.- if (upserts.length > 0) await bulkUpsertAsync({ prices: upserts })- if (removedIds.length > 0) await adminClient.prices.bulkDestroy({ ids: removedIds })+ await bulkUpsertAsync({ prices: [...upserts, ...removals] })await queryClient.invalidateQueries({ queryKey: ['prices'] })toastManager.add({diff --git a/packages/dashboard/src/schemas/catalog.ts b/packages/dashboard/src/schemas/catalog.tsindex 76ac59c1e2..26e7584712 100644--- a/packages/dashboard/src/schemas/catalog.ts+++ b/packages/dashboard/src/schemas/catalog.ts@@ -131,8 +131,15 @@ export const catalogFormSchema = zerror: () => i18n.t('admin.products.price_lists.validation.minimum_quantity_invalid'),},)+ // A list may discount only from a quantity up, with no percentage at one+ // unit — the backend prices that automatically, so requiring a magnitude+ // would make such an agreement unsaveable from the form that shows it+ // (docs/plans/6.0-volume-pricing.md)..refine(- (v) => v.pricing_mode !== 'automatic' || parsePercentage(v.adjustment_magnitude) !== null,+ (v) =>+ v.pricing_mode !== 'automatic' ||+ v.adjustment_tiers.length > 0 ||+ parsePercentage(v.adjustment_magnitude) !== null,{path: ['adjustment_magnitude'],error: () => i18n.t('admin.products.price_lists.validation.adjustment_required'),@@ -299,7 +306,13 @@ function priceListPayload(values: CatalogFormValues, previousMode?: CatalogPriciconst magnitude = parsePercentage(values.adjustment_magnitude)const base =magnitude === null- ? { adjust_compare_at: values.adjust_compare_at }+ ? {+ // Explicit null rather than an omission when bands carry the list:+ // omitting it would leave a stale quantity-1 percentage in place+ // under a ladder that no longer names one.+ ...(values.adjustment_tiers.length > 0 ? { price_adjustment_percentage: null } : {}),+ adjust_compare_at: values.adjust_compare_at,+ }: {price_adjustment_percentage: String(values.adjustment_direction === 'decrease' ? -magnitude : magnitude,diff --git a/spree/core/app/models/spree/price_list.rb b/spree/core/app/models/spree/price_list.rbindex e21796c449..ca06ee83cd 100644--- a/spree/core/app/models/spree/price_list.rb+++ b/spree/core/app/models/spree/price_list.rb@@ -50,10 +50,12 @@ module Spree# @param rows [Array<Hash>] `[{ min_quantity:, percentage: }, ...]`# @return [void]def price_adjustment_tiers=(rows)- first = Array(rows).first- return super if first.nil? || first.is_a?(Spree.base_class)+ rows = Array(rows)+ # Records rather than a payload: Rails assigns those on an association+ # swap, and the ordinary setter is what it expects.+ return super if rows.first.is_a?(Spree.base_class)- wanted = Array(rows).map { |row| row.respond_to?(:to_h) ? row.to_h.with_indifferent_access : row }+ wanted = rows.map { |row| row.respond_to?(:to_h) ? row.to_h.with_indifferent_access : row }by_quantity = price_adjustment_tiers.index_by { |tier| tier.min_quantity.to_i }kept = wanted.filter_map do |row|diff --git a/spree/core/app/services/spree/prices/bulk_upsert.rb b/spree/core/app/services/spree/prices/bulk_upsert.rbindex 502abfec30..49acf5a52b 100644--- a/spree/core/app/services/spree/prices/bulk_upsert.rb+++ b/spree/core/app/services/spree/prices/bulk_upsert.rb@@ -54,7 +54,7 @@ module Spreereturn success(price_count: 0) if affected_keys.empty?- over_cap = ladders_over_cap(upsert_rows)+ over_cap = ladders_over_cap(upsert_rows, clear_rows)return failure(nil, over_cap: over_cap) if over_cap.any?base_rows, override_rows = payload.partition { |r| r[:price_list_id].nil? }@@ -135,30 +135,45 @@ module Spree# 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# @return [Array<Hash>] `[{ variant_id:, currency:, price_list_id: }, ...]`- def ladders_over_cap(rows)+ 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 }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] }touched.filter_map do |key, incoming|- rungs = stored.fetch(key, []).map(&:last).to_set | incoming- next if rungs.size <= Spree::Price::MAXIMUM_BREAKS_PER_VARIANT+ # 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)+ next if (survivors | incoming).size <= Spree::Price::MAXIMUM_BREAKS_PER_VARIANT{ variant_id: key[0], currency: key[1], price_list_id: key[2] }enddiff --git a/spree/core/app/workflows/spree/price_lists/update.rb b/spree/core/app/workflows/spree/price_lists/update.rbindex b284ad0c4a..47115022ae 100644--- a/spree/core/app/workflows/spree/price_lists/update.rb+++ b/spree/core/app/workflows/spree/price_lists/update.rb@@ -54,7 +54,15 @@ module Spreerows = price_rowsreturn if rows.empty?- Spree::Prices::BulkUpsert.call(rows: rows)+ # The service refuses a batch that would take a ladder past the break+ # cap. Ignoring that would answer 200 while writing nothing+ # (docs/plans/6.0-volume-pricing.md).+ result = Spree::Prices::BulkUpsert.call(rows: rows)+ unless result.success?+ price_list.errors.add(:base, :too_many_breaks, count: Spree::Price::MAXIMUM_BREAKS_PER_VARIANT)+ return failure(price_list)+ end+touch_variants(rows.map { |row| row[:variant_id] }.uniq)enddiff --git a/spree/core/spec/services/spree/catalogs/resolve_prices_spec.rb b/spree/core/spec/services/spree/catalogs/resolve_prices_spec.rbindex f586477541..1cbc2fc465 100644--- a/spree/core/spec/services/spree/catalogs/resolve_prices_spec.rb+++ b/spree/core/spec/services/spree/catalogs/resolve_prices_spec.rb@@ -211,6 +211,28 @@ RSpec.describe Spree::Catalogs::ResolvePrices doexpect(price.break_count).to eq(1)end+ # An explicit row is the deepest rung at every quantity, so the bands+ # never apply to that variant — and the page says so rather than+ # promising tiers the buyer will not get.+ it 'counts no tiers for a variant an explicit row shadows' do+ list = create(:price_list, :active, store: store, catalog: catalog,+ price_adjustment_percentage: -10)+ create(:price_adjustment_tier, price_list: list, min_quantity: 50, percentage: -20)+ create(:price, variant: variant, price_list: list, amount: 12, currency: 'USD')++ price = resolve(catalog.reload)++ expect(price.amount).to eq(12)+ expect(price.source).to eq('explicit')+ expect(price.break_count).to eq(0)+ expect(price).not_to be_tiered++ deep = Spree::Pricing::Context.new(+ variant: variant, currency: 'USD', store: store, company: company, quantity: 50+ )+ expect(Spree::PricingProvider::Internal.new.price_for(deep).amount).to eq(12)+ end+# A list that only discounts from a quantity up charges base for one.it 'reads base for a bands-only list, with the bands counted' dolist = create(:price_list, :active, store: store, catalog: catalog)diff --git a/spree/core/spec/services/spree/prices/bulk_upsert_spec.rb b/spree/core/spec/services/spree/prices/bulk_upsert_spec.rbindex c16c7bcc65..01b9269cda 100644--- a/spree/core/spec/services/spree/prices/bulk_upsert_spec.rb+++ b/spree/core/spec/services/spree/prices/bulk_upsert_spec.rb@@ -192,6 +192,31 @@ RSpec.describe Spree::Prices::BulkUpsert doexpect(described_class.call(rows: rows.map { |row| row.merge(amount: '8.00') })).to be_successend+ # A merchant who drops two rungs and adds two others ends with the ladder+ # the size it began, so the batch carrying both must not be refused for+ # the rungs it is about to remove.+ it 'lets a full ladder swap rungs in one batch' do+ full = (2..(Spree::Price::MAXIMUM_BREAKS_PER_VARIANT + 1)).map { |q| rung(q) }+ described_class.call(rows: full)++ swap = [rung(2, nil), rung(3, nil), rung(500), rung(600)]++ expect(described_class.call(rows: swap)).to be_success+ expect(Spree::Price.where(price_list: price_list, variant: variant).breaks.count).+ to eq(Spree::Price::MAXIMUM_BREAKS_PER_VARIANT)+ end++ # Placeholders charge nothing, so they do not fill a ladder — the model's+ # own guard counts the same way.+ it 'does not count placeholder rungs against the cap' do+ (2..(Spree::Price::MAXIMUM_BREAKS_PER_VARIANT + 1)).each do |quantity|+ create(:price, variant: variant, currency: 'USD', price_list: price_list,+ min_quantity: quantity, amount: nil)+ end++ expect(described_class.call(rows: [rung(500)])).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' dodiff --git a/spree/core/spec/workflows/spree/price_lists/write_spec.rb b/spree/core/spec/workflows/spree/price_lists/write_spec.rbindex 39d2b63530..1b95c3f2c6 100644--- a/spree/core/spec/workflows/spree/price_lists/write_spec.rb+++ b/spree/core/spec/workflows/spree/price_lists/write_spec.rb@@ -64,6 +64,37 @@ RSpec.describe 'Spree::PriceLists write workflows' doexpect(price_list.prices.where.not(amount: nil)).to be_emptyend+ # The bulk writer refuses a batch that would take a ladder past the break+ # cap, and a workflow that ignored that would answer success while+ # writing nothing (docs/plans/6.0-volume-pricing.md).+ it 'fails rather than reporting success when the ladder is over the cap' do+ price_list.add_products([product.id])+ rungs = (2..(Spree::Price::MAXIMUM_BREAKS_PER_VARIANT + 2)).map do |quantity|+ { variant_id: variant.id, currency: 'USD', min_quantity: quantity, amount: 5 }+ end++ result = described_class.call(price_list: price_list, attributes: { prices: rungs })++ expect(result).to be_failure+ expect(price_list.prices.breaks).to be_empty+ end++ it 'writes a ladder the payload names' do+ price_list.add_products([product.id])++ result = described_class.call(+ price_list: price_list,+ attributes: { prices: [+ { variant_id: variant.id, currency: 'USD', amount: 10 },+ { variant_id: variant.id, currency: 'USD', min_quantity: 24, amount: 8 }+ ] }+ )++ expect(result).to be_success+ expect(price_list.prices.where(variant_id: variant.id, currency: 'USD').order(:min_quantity).+ pluck(:min_quantity, :amount)).to eq([[1, 10], [24, 8]])+ end+it 'leaves prices alone when the payload carries none' doprice_list.add_products([product.id])described_class.call(