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.

Refuse a mistyped quantity instead of guessing what it meant

Damian Legawiec5ba290a61e55
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.rb
index 0534d668fb..21520bfe9e 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
@@ -53,11 +53,20 @@ module Spree
end
result = Spree::Prices::BulkUpsert.call(rows: rows)
- # The cap lives in the service, since every write path reaches it
- # and none of them run model validations
- # (docs/plans/6.0-volume-pricing.md). Guarded on the failure
- # actually carrying `over_cap`, so a failure mode the service grows
- # later is not reported under this one's name.
+ # The quantity check and the cap both live in the service, since
+ # every write path reaches it and none of them run model
+ # 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.
+ if (invalid = result.error&.value.try(:[], :invalid_quantities))
+ return render_error(
+ code: 'invalid_min_quantity',
+ message: 'Each quantity break must start at a whole number of units.',
+ status: :unprocessable_content,
+ details: { rows: invalid }
+ )
+ end
+
if (over_cap = result.error&.value.try(:[], :over_cap))
return render_error(
code: 'too_many_breaks',
diff --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.rb
index 1fdf9edb4a..ed68509b28 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
@@ -373,6 +373,22 @@ RSpec.describe Spree::Api::V3::Admin::PricesController, type: :controller do
expect(Spree::Price.where(variant: variant, currency: 'USD', price_list: price_list).breaks).to be_empty
end
+ # Coercing a typo with `to_i` would make it quantity 1 and overwrite the
+ # contracted price the variant is actually sold at.
+ it 'refuses a quantity that is not a whole number' do
+ upsert([{ variant_id: variant.prefixed_id, currency: 'USD',
+ price_list_id: price_list.prefixed_id, amount: '10.00' }])
+
+ upsert([{ variant_id: variant.prefixed_id, currency: 'USD',
+ price_list_id: price_list.prefixed_id, min_quantity: 'not-a-number', amount: '1.11' }])
+
+ expect(response).to have_http_status(:unprocessable_content)
+ expect(json_response['error']['code']).to eq('invalid_min_quantity')
+ expect(json_response['error']['details']['rows']).to eq([{ 'index' => 0 }])
+ expect(Spree::Price.find_by(variant: variant, currency: 'USD', price_list: price_list, min_quantity: 1).amount).
+ to eq(10)
+ end
+
# Re-sending a full ladder must not be refused for being the size it
# already is.
it 'accepts a batch that rewrites a full ladder in place' do
diff --git a/spree/core/app/models/spree/price_list.rb b/spree/core/app/models/spree/price_list.rb
index ca06ee83cd..28faef3118 100644
--- a/spree/core/app/models/spree/price_list.rb
+++ b/spree/core/app/models/spree/price_list.rb
@@ -56,13 +56,17 @@ module Spree
return super if rows.first.is_a?(Spree.base_class)
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 }
+ by_quantity = price_adjustment_tiers.index_by(&:min_quantity)
- kept = wanted.filter_map do |row|
- quantity = row[:min_quantity].to_i
- next if quantity.zero?
+ kept = wanted.map do |row|
+ # Assigned raw rather than coerced with `to_i`: a value that is not a
+ # number would become 0 and read as a band to drop, so a single typo
+ # would silently delete the whole ladder and report success. Left as
+ # it arrived, the tier's own numericality validation refuses the save
+ # and names the row (docs/plans/6.0-volume-pricing.md).
+ quantity = Spree::PriceAdjustmentTier.type_for_attribute(:min_quantity).cast(row[:min_quantity])
- tier = by_quantity[quantity] || price_adjustment_tiers.build(min_quantity: quantity)
+ tier = by_quantity[quantity] || price_adjustment_tiers.build(min_quantity: row[:min_quantity])
tier.percentage = row[:percentage]
tier
end
diff --git a/spree/core/app/services/spree/prices/bulk_upsert.rb b/spree/core/app/services/spree/prices/bulk_upsert.rb
index 49acf5a52b..2d38dbdb43 100644
--- a/spree/core/app/services/spree/prices/bulk_upsert.rb
+++ b/spree/core/app/services/spree/prices/bulk_upsert.rb
@@ -34,18 +34,24 @@ module Spree
# `min_quantity` means the ladder's bottom rung.
# @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 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 the cap
- # is enforced here rather than in each of the three controllers that
- # reach it (docs/plans/6.0-volume-pricing.md).
+ # 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).
def call(rows:)
rows = Array(rows).map { |r| r.with_indifferent_access }
keyed = rows.select { |r| r[:variant_id].present? && r[:currency].present? }
- # PG rejects an upsert with two rows hitting the same unique-key
- # triple in one statement ("ON CONFLICT DO UPDATE command cannot
- # affect row a second time"). Last-write-wins: keep the last
- # occurrence of each triple.
+ # Checked before anything is deduped: `row_key` coerces the quantity,
+ # so two malformed rows would collapse into one and the batch would be
+ # judged on a shape the caller never sent.
+ malformed = rows_with_unusable_quantity(keyed)
+ return failure(nil, invalid_quantities: malformed) if malformed.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? }
@@ -121,9 +127,33 @@ module Spree
[row[:variant_id], row[:currency], row[:price_list_id], quantity_of(row)]
end
+ # Absent means the ladder's bottom rung. Anything present must be a
+ # positive whole number — see #rows_with_unusable_quantity, which
+ # refuses the batch before this coerces anything.
def quantity_of(row)
- quantity = row[:min_quantity].to_i
- quantity.positive? ? quantity : 1
+ return 1 if row[:min_quantity].blank?
+
+ row[:min_quantity].to_i
+ end
+
+ # Rows whose `min_quantity` is present but not a positive whole number.
+ #
+ # Coercing these with `to_i` would turn a typo into quantity 1 and
+ # overwrite the contracted price the variant is actually sold at — the
+ # row a customer is charged (docs/plans/6.0-volume-pricing.md). This
+ # path writes in SQL and runs no model validations, so the check has to
+ # happen here.
+ #
+ # @param rows [Array<Hash>]
+ # @return [Array<Hash>] `[{ index: }, ...]` for the offending rows
+ def rows_with_unusable_quantity(rows)
+ rows.each_with_index.filter_map do |row, index|
+ raw = row[:min_quantity]
+ next if raw.blank?
+
+ quantity = Integer(raw, exception: false)
+ { index: index } if quantity.nil? || quantity < 1
+ end
end
# Which ladders this batch would take past the cap, counted the way the
diff --git a/spree/core/spec/models/spree/price_list_spec.rb b/spree/core/spec/models/spree/price_list_spec.rb
index bdaf94ce9d..1dfdb589c2 100644
--- a/spree/core/spec/models/spree/price_list_spec.rb
+++ b/spree/core/spec/models/spree/price_list_spec.rb
@@ -147,6 +147,16 @@ describe Spree::PriceList, type: :model do
expect(price_list.reload.price_adjustment_tiers).to be_empty
end
+ # Coercing with `to_i` would turn a typo into 0 and read it as a band to
+ # drop, so one bad row would silently delete the whole ladder.
+ it 'refuses a malformed quantity rather than clearing the ladder' do
+ expect(price_list.reload.price_adjustment_tiers.map(&:min_quantity)).to eq([10, 50])
+
+ expect(price_list.update(price_adjustment_tiers: [{ min_quantity: 'invalid', percentage: '-10' }])).to be(false)
+ expect(price_list.errors.full_messages.join).to match(/quantity/i)
+ expect(price_list.reload.price_adjustment_tiers.map(&:min_quantity)).to eq([10, 50])
+ end
+
# Rails assigns model instances on an association swap; the writer has to
# fall through to the ordinary setter rather than treat them as rows.
it 'falls through to the standard writer for model instances' do
diff --git a/spree/core/spec/services/spree/prices/bulk_upsert_spec.rb b/spree/core/spec/services/spree/prices/bulk_upsert_spec.rb
index 01b9269cda..8655d22d5c 100644
--- a/spree/core/spec/services/spree/prices/bulk_upsert_spec.rb
+++ b/spree/core/spec/services/spree/prices/bulk_upsert_spec.rb
@@ -217,6 +217,39 @@ RSpec.describe Spree::Prices::BulkUpsert do
expect(described_class.call(rows: [rung(500)])).to be_success
end
+ # Coercing a typo with `to_i` would make it quantity 1 and overwrite the
+ # contracted price the variant is actually sold at.
+ it 'refuses a batch whose quantity is not a whole number' do
+ described_class.call(rows: [rung(1, '10.00')])
+
+ result = described_class.call(rows: [rung('not-a-number', '1.11')])
+
+ expect(result).to be_failure
+ expect(result.error.value[:invalid_quantities]).to eq([{ index: 0 }])
+ expect(Spree::Price.find_by(variant: variant, currency: 'USD', price_list: price_list, min_quantity: 1).amount).
+ to eq(10)
+ end
+
+ it 'refuses a quantity below one' do
+ expect(described_class.call(rows: [rung(0)])).to be_failure
+ expect(described_class.call(rows: [rung(-5)])).to be_failure
+ end
+
+ # Two malformed rows must both be reported, not collapsed into one by the
+ # dedup that keys on the coerced quantity.
+ it 'names every offending row' do
+ result = described_class.call(rows: [rung('x'), rung('y')])
+
+ expect(result.error.value[:invalid_quantities]).to eq([{ index: 0 }, { index: 1 }])
+ end
+
+ # An absent quantity is the ladder's bottom rung, which is every row
+ # written before breaks existed.
+ it 'still accepts a row that names no quantity' do
+ expect(described_class.call(rows: [{ variant_id: variant.id, currency: 'USD',
+ price_list_id: price_list.id, amount: '10.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