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
Make the agreement page and the cap tell the truth
Damian Legawieccb7c1b51ffc9
diff --git a/packages/dashboard-ui/src/spree/bulk-price-table.tsx b/packages/dashboard-ui/src/spree/bulk-price-table.tsxindex 9207874a60..26bc216bd3 100644--- a/packages/dashboard-ui/src/spree/bulk-price-table.tsx+++ b/packages/dashboard-ui/src/spree/bulk-price-table.tsx@@ -61,8 +61,11 @@ export interface BulkPriceTableLabels {compareAtAriaTemplate?: string/** Column header over the quantity-break buttons. Omit to hide the column. */tiers?: string- /** Label on a row's tier button. `{count}` is replaced with the break count. */- tiersWithCount?: string+ /**+ * Labels a row's tier button. Called with the break count so the caller's+ * own translator picks the plural form — a pre-substituted template cannot.+ */+ tiersWithCount?: (count: number) => string/** Label on a row's tier button when the row carries no breaks yet. */tiersEmpty?: string}@@ -202,8 +205,7 @@ export function BulkPriceTable({onClick={() => onOpenTiers(r.id)}>{count > 0- ? (labels.tiersWithCount?.replace('{count}', String(count)) ??- String(count))+ ? (labels.tiersWithCount?.(count) ?? String(count)): (labels.tiersEmpty ?? '+')}</Button></div>diff --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 ed3728a300..0f016c87f0 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@@ -11,10 +11,12 @@ import { useCallback, useDeferredValue, useEffect, useMemo, useState } from 'reaimport { useTranslation } from 'react-i18next'import { useCurrencyLocale } from '../../../hooks/use-currency-locale'import { useBulkUpsertPrices } from '../../../hooks/use-prices'-import { MAXIMUM_QUANTITY_TIERS } from '../../../schemas/price-list'import { VariantTierDialog } from './variant-tier-dialog'const PAGE_SIZE = 50+// The API caps a page at 100 rows, so the break sweep asks for exactly that+// and pages until it has them all.+const BREAK_PAGE_SIZE = 100interface PriceListRowFromServer {id: string@@ -180,33 +182,51 @@ export function BulkPriceEditor({[data],)- // The rungs above the bottom one, for this page's variants only — one query- // rather than one per row, and none at all when this editor has no list to- // hold a ladder (docs/plans/6.0-volume-pricing.md).- const { data: breakData } = useQuery({+ // The rungs above the bottom one, for this page's variants only — a few+ // queries rather than one per row, and none at all when this editor has no+ // list to hold a ladder (docs/plans/6.0-volume-pricing.md).+ //+ // Paged rather than asked for in one call: a page of fifty fully-laddered+ // variants is five hundred rows and the API caps a page at a hundred, so a+ // single request would silently truncate and under-report the badges.+ const { data: breakRows } = useQuery({queryKey: useResourceKey('prices', {breaks: priceListId ?? null,currency,variants: pageVariantIds.join(','),}),- queryFn: () =>- adminClient.prices.list({- variant_id_in: pageVariantIds,- price_list_id_eq: priceListId,- currency_eq: currency,- min_quantity_gt: 1,- limit: pageVariantIds.length * MAXIMUM_QUANTITY_TIERS,- } as never),+ queryFn: async () => {+ const collected: PriceListRowFromServer[] = []+ let breakPage = 1+ let lastPage = 1++ do {+ const response = await adminClient.prices.list({+ variant_id_in: pageVariantIds,+ price_list_id_eq: priceListId,+ currency_eq: currency,+ min_quantity_gt: 1,+ page: breakPage,+ limit: BREAK_PAGE_SIZE,+ } as never)++ collected.push(...(response.data as unknown as PriceListRowFromServer[]))+ lastPage = response.meta?.pages ?? 1+ breakPage += 1+ } while (breakPage <= lastPage)++ return collected+ },enabled: !!priceListId && pageVariantIds.length > 0,})const breakCounts = useMemo(() => {const counts = new Map<string, number>()- for (const row of (breakData?.data ?? []) as unknown as PriceListRowFromServer[]) {+ for (const row of breakRows ?? []) {counts.set(row.variant_id, (counts.get(row.variant_id) ?? 0) + 1)}return counts- }, [breakData])+ }, [breakRows])const baselineRows = useMemo<BaselineRow[]>(() => {if (!data) return []@@ -427,9 +447,8 @@ export function BulkPriceEditor({tiers: priceListId? t('admin.pages.products.price_lists.edit_prices.columns.tiers'): undefined,- tiersWithCount: t('admin.pages.products.price_lists.tiers.count_badge', {- count: '{count}' as never,- }),+ tiersWithCount: (count: number) =>+ t('admin.pages.products.price_lists.tiers.count_badge', { count }),tiersEmpty: t('admin.pages.products.price_lists.tiers.add_short'),}}/>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 7b6d5ba82c..946a42591e 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@@ -131,15 +131,21 @@ export function VariantTierDialog({amount: toCanonical(rung.value),}))- // A rung the merchant deleted is a stored row this draft no longer names.- const keptIds = new Set(draft.map((rung) => rung.priceId).filter(Boolean))+ // 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).+ const keptQuantities = new Set(upserts.map((rung) => rung.min_quantity))const removedIds = stored- .filter((rung) => rung.min_quantity > 1 && !keptIds.has(rung.id))+ .filter((rung) => rung.min_quantity > 1 && !keptQuantities.has(rung.min_quantity)).map((rung) => rung.id)try {- if (removedIds.length > 0) await adminClient.prices.bulkDestroy({ ids: removedIds })+ // 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 queryClient.invalidateQueries({ queryKey: ['prices'] })toastManager.add({diff --git a/packages/dashboard/src/schemas/catalog.ts b/packages/dashboard/src/schemas/catalog.tsindex c98f192b6d..ff764bfdb3 100644--- a/packages/dashboard/src/schemas/catalog.ts+++ b/packages/dashboard/src/schemas/catalog.ts@@ -160,7 +160,9 @@ export const catalogFormSchema = z},).refine(- (v) => v.pricing_mode !== 'automatic' || v.adjustment_tiers.every(tierPercentageIsUsable),+ (v) =>+ v.pricing_mode !== 'automatic' ||+ v.adjustment_tiers.every((tier) => tierPercentageIsUsable(tier, v.adjustment_direction)),{path: ['adjustment_tiers'],error: () => i18n.t('admin.products.price_lists.validation.tier_percentage_invalid'),@@ -282,11 +284,16 @@ function priceListPayload(values: CatalogFormValues, previousMode?: CatalogPriciif (values.pricing_mode === 'fixed') {// A fixed list holds explicit rows; clearing any adjustment is what- // makes it fixed. The quantity threshold goes with the percentage — left- // behind it would gate the hand-entered prices, and the card stops- // showing it, so nothing would explain the gap. `rules: []` clears only- // the contextual ones; the server keeps the rest.- return { price_adjustment_percentage: null, adjust_compare_at: false, rules: [] }+ // makes it fixed. The quantity threshold and the percentage's bands go+ // with it — a band left behind still derives a discount (a list with+ // bands prices automatically even with no percentage of its own), while+ // the card shows no percentage at all to explain it.+ return {+ price_adjustment_percentage: null,+ adjust_compare_at: false,+ rules: [],+ price_adjustment_tiers: [],+ }}const magnitude = parsePercentage(values.adjustment_magnitude)@@ -352,9 +359,16 @@ function adjustmentTiersAreWellFormed(tiers: AdjustmentTierValue[]): boolean {return new Set(quantities).size === quantities.length}-function tierPercentageIsUsable(tier: AdjustmentTierValue): boolean {+// A discount past 100% would price below zero; a markup has no ceiling short+// of what the column holds. The same bound the list's own figure carries.+function tierPercentageIsUsable(+ tier: AdjustmentTierValue,+ direction: (typeof ADJUSTMENT_DIRECTIONS)[number],+): boolean {const magnitude = parsePercentage(tier.percentage)- return magnitude !== null && magnitude < 100+ if (magnitude === null) return false++ return direction === 'increase' || magnitude < 100}function volumeRulePayload(minimumQuantity: string | undefined) {@@ -400,19 +414,33 @@ export function catalogPricingValues(}}+ const bands = priceList.price_adjustment_tiers ?? []const { pricing_mode, adjustment_direction, adjustment_magnitude } = adjustmentFormValues(priceList.price_adjustment_percentage,)+ // A list may discount only from a quantity up, with no percentage of its+ // own — the backend prices that automatically, so reading it as a fixed+ // list would hide the bands behind a card that cannot show them, and the+ // next Save would clear terms the merchant never saw+ // (docs/plans/6.0-volume-pricing.md).+ const bandsOnly = pricing_mode !== 'automatic' && bands.length > 0+return {- pricing_mode,- adjustment_direction,+ pricing_mode: bandsOnly ? 'automatic' : pricing_mode,+ // With no percentage of its own the direction comes from the bands, so+ // the magnitudes below read as the discounts they are.+ adjustment_direction: bandsOnly+ ? Number(bands[0]?.percentage) > 0+ ? 'increase'+ : 'decrease'+ : adjustment_direction,adjustment_magnitude,adjust_compare_at: priceList.adjust_compare_at ?? false,minimum_quantity: minimumQuantityOf(priceList.price_rules),// Shown as magnitudes, like the list's own figure: the direction select// above them carries the sign for the whole ladder.- adjustment_tiers: (priceList.price_adjustment_tiers ?? []).map((tier) => ({+ adjustment_tiers: bands.map((tier) => ({min_quantity: String(tier.min_quantity),percentage: String(Math.abs(Number(tier.percentage))),})),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 e3f78a0ba6..4f85d16dc5 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@@ -52,17 +52,19 @@ module Spree)end- over_cap = rows_over_break_cap(rows)- if over_cap.any?+ 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).+ unless result.success?return render_error(code: 'too_many_breaks',message: "A variant can carry at most #{Spree::Price::MAXIMUM_BREAKS_PER_VARIANT} quantity breaks on one price list.",status: :unprocessable_content,- details: { rows: over_cap }+ details: { ladders: result.error.value[:over_cap] })end- result = Spree::Prices::BulkUpsert.call(rows: rows)render json: result.valueend@@ -120,44 +122,6 @@ module Spreeprivate- # Which incoming rows would push a ladder past the cap. This path- # writes in SQL, so the model validation never runs — the check has- # to happen where the rows can still be named back to the caller.- #- # Counted against what is already stored, minus the rungs this batch- # is itself rewriting, so re-sending a full ladder is never refused- # for being the size it already is.- #- # @param rows [Array<Hash>]- # @return [Array<Hash>] `[{ index: }, ...]` for the offending rows- def rows_over_break_cap(rows)- ladders = Hash.new { |hash, key| hash[key] = Set.new }-- rows.each_with_index do |row, index|- next if row[:price_list_id].blank?- next if row[:amount].blank?-- ladders[[row[:variant_id].to_s, row[:currency], row[:price_list_id].to_s]] << index- end- return [] if ladders.empty?-- ladders.filter_map do |(variant_id, currency, price_list_id), indexes|- incoming = rows.values_at(*indexes).map { |row| quantity_of(row) }.uniq- stored = Spree::Price.where(- variant_id: variant_id, currency: currency, price_list_id: price_list_id- ).where.not(amount: nil).pluck(:min_quantity)-- next if (stored | incoming).size <= Spree::Price::MAXIMUM_BREAKS_PER_VARIANT-- indexes.map { |index| { index: index } }- end.flatten- end-- def quantity_of(row)- quantity = row[:min_quantity].to_i- quantity.positive? ? quantity : 1- end-def store_variantscurrent_store.variants.accessible_by(current_ability, :update)enddiff --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 ae2294dc82..1fdf9edb4a 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@@ -356,10 +356,10 @@ RSpec.describe Spree::Api::V3::Admin::PricesController, type: :controller doexpect(rows.pluck(:min_quantity, :amount)).to eq([[1, 10.0], [24, 8.5]])end- # This path writes in SQL, so the model validation never runs — the cap- # has to be enforced where the offending rows can still be named.+ # This path writes in SQL, so the model validation never runs — the cap is+ # enforced in the service every write path reaches.it 'refuses a batch that would push the ladder past the cap' do- rungs = (1..Spree::Price::MAXIMUM_BREAKS_PER_VARIANT + 1).map do |rung|+ rungs = (2..(Spree::Price::MAXIMUM_BREAKS_PER_VARIANT + 2)).map do |rung|{variant_id: variant.prefixed_id, currency: 'USD',price_list_id: price_list.prefixed_id, min_quantity: rung, amount: '9.00'@@ -370,13 +370,13 @@ RSpec.describe Spree::Api::V3::Admin::PricesController, type: :controller doexpect(response).to have_http_status(:unprocessable_content)expect(json_response['error']['code']).to eq('too_many_breaks')- expect(Spree::Price.where(variant: variant, currency: 'USD', price_list: price_list)).to be_empty+ expect(Spree::Price.where(variant: variant, currency: 'USD', price_list: price_list).breaks).to be_emptyend# 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- full = (1..Spree::Price::MAXIMUM_BREAKS_PER_VARIANT).map do |rung|+ full = (2..(Spree::Price::MAXIMUM_BREAKS_PER_VARIANT + 1)).map do |rung|{variant_id: variant.prefixed_id, currency: 'USD',price_list_id: price_list.prefixed_id, min_quantity: rung, amount: '9.00'diff --git a/spree/core/app/models/spree/price.rb b/spree/core/app/models/spree/price.rbindex 479fe6c42c..fa8d6959c3 100644--- a/spree/core/app/models/spree/price.rb+++ b/spree/core/app/models/spree/price.rb@@ -252,13 +252,18 @@ module Spreeerrors.add(:min_quantity, :requires_price_list)end- # Counted over the siblings this row would join, so the message names the- # ladder that is full rather than the row that arrived last.+ # Counted the way the constant is named: breaks *above* the bottom rung,+ # so a variant priced at one figure plus ten breaks is exactly at the+ # limit. Placeholder rows carry no amount and charge nothing, so they do+ # not fill the ladder — the bulk path counts the same rows, and a cap two+ # writers disagree about is one that refuses what it just allowed.def breaks_within_cap+ return unless quantity_break?return if price_list_id.blank? || variant_id.blank? || currency.blank?return unless will_save_change_to_attribute?(:min_quantity) || new_record?- siblings = self.class.where(variant_id: variant_id, currency: currency, price_list_id: price_list_id)+ siblings = self.class.where(variant_id: variant_id, currency: currency, price_list_id: price_list_id).+ breaks.where.not(amount: nil)siblings = siblings.where.not(id: id) if persisted?return if siblings.count < MAXIMUM_BREAKS_PER_VARIANTdiff --git a/spree/core/app/models/spree/price_adjustment_tier.rb b/spree/core/app/models/spree/price_adjustment_tier.rbindex e019998105..cc1d9db334 100644--- a/spree/core/app/models/spree/price_adjustment_tier.rb+++ b/spree/core/app/models/spree/price_adjustment_tier.rb@@ -24,15 +24,24 @@ module Spree# The same bounds the list's own column carries: at -100 every derived# price is zero, below it the arithmetic goes negative, and above 1000 the# decimal(6,3) column cannot hold the value.+ # Zero is refused rather than accepted and then ignored: "0% from ten"+ # reads as "no further discount at this tier", but a factor of exactly 1+ # makes the list decline to price the line at all, so it would fall+ # through to the next list or base — the opposite of what it says+ # (docs/plans/6.0-volume-pricing.md). Removing the band is how a merchant+ # says the ladder stops here.validates :percentage, presence: true,- numericality: { greater_than: -100, less_than: 1000 }+ numericality: { greater_than: -100, less_than: 1000, other_than: 0 }validate :tiers_within_capscope :by_quantity, -> { order(min_quantity: :asc) }# Bands a line of this size qualifies for, deepest first.scope :for_quantity, ->(quantity) { where(min_quantity: ..quantity.to_i).order(min_quantity: :desc) }- self.whitelisted_ransackable_attributes = %w[min_quantity percentage price_list_id]+ # No ransack allowlist: a band is reached only through the list that owns+ # it, exactly like a PriceRule, and there is no endpoint that filters+ # bands. An entry here would be a filter any caller could run against a+ # model that carries no store of its own.privatediff --git a/spree/core/app/services/spree/catalogs/resolve_prices.rb b/spree/core/app/services/spree/catalogs/resolve_prices.rbindex 674aa6ac02..70073abc22 100644--- a/spree/core/app/services/spree/catalogs/resolve_prices.rb+++ b/spree/core/app/services/spree/catalogs/resolve_prices.rb@@ -65,23 +65,28 @@ module Spreeif price_listlist_rows = rows.select { |row| row.price_list_id == price_list.id }- # The bottom rung, because this reading makes no purchase — the- # deeper rungs are reported as a count so the view can say "and- # three more from a case up" without pretending to know the size of- # an order nobody has placed.- explicit = list_rows.min_by { |row| row.min_quantity.to_i }- return build(explicit, 'explicit', break_count: list_rows.count { |row| row.min_quantity.to_i > 1 }) if explicit+ break_count = list_rows.count { |row| row.min_quantity.to_i > 1 }+ # The bottom rung only — this reading makes no purchase, so a deeper+ # rung read as the single-unit price would name an amount the+ # resolver does not charge at that quantity. A ladder starting above+ # one unit therefore reads as base here, which is what a buyer of+ # one actually pays.+ explicit = list_rows.detect { |row| row.min_quantity.to_i == 1 }+ return build(explicit, 'explicit', break_count: break_count) if explicit# Derived by the list itself, so the amount a merchant reads here is- # the one the pricing resolver charges — one formula, not two.- derived = price_list.automatic_pricing? ? price_list.derived_price_from(base, 1) : nil+ # the one the pricing resolver charges — one formula, not two. A+ # variant with a ladder is priced by the ladder alone, so the list's+ # percentage is not reported for it either.+ derived = price_list.automatic_pricing? && break_count.zero? ? price_list.derived_price_from(base, 1) : nilreturn build(derived, 'automatic', break_count: band_count) if derived- # A list whose percentage only starts at a quantity charges the base- # price for a single unit, and says so — with the bands counted, so- # the reading is "base now, and less from a case up" rather than a- # bare base price that hides the agreement.- return build(base, 'base', break_count: band_count) if base && band_count.positive?+ # A list that prices this variant only from a quantity up charges+ # the base price for a single unit, and says so — with the tiers+ # counted, so the reading is "base now, less from a case up" rather+ # than a bare base price that hides the agreement.+ tiers_above = break_count.positive? ? break_count : band_count+ return build(base, 'base', break_count: tiers_above) if base && tiers_above.positive?endbase && build(base, 'base')diff --git a/spree/core/app/services/spree/prices/bulk_upsert.rb b/spree/core/app/services/spree/prices/bulk_upsert.rbindex 781a15bd48..f419e7bbc0 100644--- a/spree/core/app/services/spree/prices/bulk_upsert.rb+++ b/spree/core/app/services/spree/prices/bulk_upsert.rb@@ -33,10 +33,12 @@ module Spree# `amount` is treated as "clear this price", and a blank# `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`. The break cap is enforced by the caller that can- # report which rows crossed it — see the admin prices controller —- # since this path writes in SQL and runs no model validations.+ # `{ 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).def call(rows:)rows = Array(rows).map { |r| r.with_indifferent_access }keyed = rows.select { |r| r[:variant_id].present? && r[:currency].present? }@@ -52,6 +54,9 @@ module Spreereturn success(price_count: 0) if affected_keys.empty?+ over_cap = ladders_over_cap(upsert_rows)+ return failure(nil, over_cap: over_cap) if over_cap.any?+base_rows, override_rows = payload.partition { |r| r[:price_list_id].nil? }Spree::Price.transaction do@@ -121,6 +126,37 @@ module Spreequantity.positive? ? quantity : 1end+ # Which ladders this batch would take past the cap, counted the way the+ # 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+ # @return [Array<Hash>] `[{ variant_id:, currency:, price_list_id: }, ...]`+ def ladders_over_cap(rows)+ touched = rows.each_with_object(Hash.new { |hash, key| hash[key] = Set.new }) do |row, ladders|+ next if row[:price_list_id].blank?+ next if quantity_of(row) == 1++ ladders[[row[:variant_id].to_s, row[:currency], row[:price_list_id].to_s]] << quantity_of(row)+ end+ return [] if touched.empty?++ touched.filter_map do |(variant_id, currency, price_list_id), incoming|+ stored = Spree::Price.+ where(variant_id: variant_id, currency: currency, price_list_id: price_list_id).+ breaks.+ pluck(:min_quantity)++ next if (stored.to_set | incoming).size <= Spree::Price::MAXIMUM_BREAKS_PER_VARIANT++ { variant_id: variant_id, currency: currency, price_list_id: price_list_id }+ end+ 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)diff --git a/spree/core/spec/models/spree/price_adjustment_tier_spec.rb b/spree/core/spec/models/spree/price_adjustment_tier_spec.rbindex 0113ef82c9..4a5d76fe32 100644--- a/spree/core/spec/models/spree/price_adjustment_tier_spec.rb+++ b/spree/core/spec/models/spree/price_adjustment_tier_spec.rb@@ -39,6 +39,13 @@ describe Spree::PriceAdjustmentTier, type: :model doexpect(band.call(999.999)).to be_validend+ # A factor of exactly 1 makes the list decline to price the line, so a+ # band reading "no further discount here" would fall through to the next+ # list instead. Removing the band is how a ladder stops.+ it 'refuses a band of zero rather than accepting one that does nothing' do+ expect(build(:price_adjustment_tier, price_list: price_list, min_quantity: 10, percentage: 0)).not_to be_valid+ end+it 'refuses a ladder past the cap' do(2..(described_class::MAXIMUM_TIERS_PER_LIST + 1)).each do |quantity|create(:price_adjustment_tier, price_list: price_list, min_quantity: quantity)diff --git a/spree/core/spec/models/spree/price_spec.rb b/spree/core/spec/models/spree/price_spec.rbindex 7240f8d763..d0c4961b6a 100644--- a/spree/core/spec/models/spree/price_spec.rb+++ b/spree/core/spec/models/spree/price_spec.rb@@ -230,8 +230,11 @@ describe Spree::Price, type: :model doexpect(subject).to be_validend+ # The cap counts breaks, not rows: a variant priced at one figure plus+ # ten breaks is exactly at the limit.it 'refuses a ladder past the cap' do- (1..Spree::Price::MAXIMUM_BREAKS_PER_VARIANT).each do |rung|+ create(:price, variant: variant, currency: 'USD', amount: 10, price_list: price_list, min_quantity: 1)+ (2..(Spree::Price::MAXIMUM_BREAKS_PER_VARIANT + 1)).each do |rung|create(:price, variant: variant, currency: 'USD', amount: 10, price_list: price_list, min_quantity: rung)end@@ -241,10 +244,20 @@ describe Spree::Price, type: :model doexpect(eleventh.errors.messages[:min_quantity].first).to include('at most 10')end+ # A placeholder charges nothing, so it does not fill the ladder — the+ # bulk path counts the same rows.+ it 'does not count placeholder rows against the cap' do+ (2..(Spree::Price::MAXIMUM_BREAKS_PER_VARIANT + 1)).each do |rung|+ create(:price, variant: variant, currency: 'USD', amount: nil, price_list: price_list, min_quantity: rung)+ end++ expect(build(:price, variant: variant, currency: 'USD', amount: 9, price_list: price_list, min_quantity: 99)).to be_valid+ end+# The cap counts a variant's rungs on one list in one currency, so a# second currency is a ladder of its own.it 'counts the cap per currency' do- (1..Spree::Price::MAXIMUM_BREAKS_PER_VARIANT).each do |rung|+ (2..(Spree::Price::MAXIMUM_BREAKS_PER_VARIANT + 1)).each do |rung|create(:price, variant: variant, currency: 'USD', amount: 10, price_list: price_list, min_quantity: rung)enddiff --git a/spree/core/spec/services/spree/catalogs/resolve_prices_spec.rb b/spree/core/spec/services/spree/catalogs/resolve_prices_spec.rbindex 29b386f575..f586477541 100644--- a/spree/core/spec/services/spree/catalogs/resolve_prices_spec.rb+++ b/spree/core/spec/services/spree/catalogs/resolve_prices_spec.rb@@ -151,6 +151,78 @@ RSpec.describe Spree::Catalogs::ResolvePrices doexpect(resolve(catalog.reload).amount).to eq(charged_to_buyer)end++ # Quantity ladders (docs/plans/6.0-volume-pricing.md). This reading makes+ # no purchase, so it must answer for one unit — and agree with what a+ # buyer of one is actually charged.+ context 'with a quantity ladder' do+ let(:list) { create(:price_list, :active, store: store, catalog: catalog) }++ it 'reads the bottom rung and counts the ones above it' do+ create(:price, variant: variant, price_list: list, amount: 60, currency: 'USD', min_quantity: 1)+ create(:price, variant: variant, price_list: list, amount: 50, currency: 'USD', min_quantity: 24)++ price = resolve(catalog.reload)++ expect(price.amount).to eq(60)+ expect(price.amount).to eq(charged_to_buyer)+ expect(price.source).to eq('explicit')+ expect(price.break_count).to eq(1)+ expect(price).to be_tiered+ end++ # A ladder starting above one unit prices nothing for a buyer of one, so+ # reading its first rung as the agreement's price would name an amount+ # nobody is charged.+ it 'reads base when the ladder starts above one unit' do+ create(:price, variant: variant, price_list: list, amount: 50, currency: 'USD', min_quantity: 24)++ price = resolve(catalog.reload)++ expect(price.amount).to eq(charged_to_buyer)+ expect(price.source).to eq('base')+ expect(price.break_count).to eq(1)+ end++ # A laddered variant is priced by its ladder alone, so the list's+ # percentage must not be reported for it either.+ it 'does not report the percentage for a laddered variant' do+ list.update!(price_adjustment_percentage: -15)+ create(:price, variant: variant, price_list: list, amount: 50, currency: 'USD', min_quantity: 24)++ price = resolve(catalog.reload)++ expect(price.amount).to eq(charged_to_buyer)+ expect(price.source).to eq('base')+ end+ end++ context 'with quantity bands on the percentage' do+ it 'reads the quantity-1 percentage and counts the bands above it' 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)++ price = resolve(catalog.reload)++ expect(price.amount).to eq(90)+ expect(price.amount).to eq(charged_to_buyer)+ expect(price.source).to eq('automatic')+ expect(price.break_count).to eq(1)+ 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' do+ list = create(:price_list, :active, store: store, catalog: catalog)+ create(:price_adjustment_tier, price_list: list, min_quantity: 50, percentage: -20)++ price = resolve(catalog.reload)++ expect(price.amount).to eq(charged_to_buyer)+ expect(price.source).to eq('base')+ expect(price.break_count).to eq(1)+ end+ endenddescribe '#preload' dodiff --git a/spree/core/spec/services/spree/prices/bulk_upsert_spec.rb b/spree/core/spec/services/spree/prices/bulk_upsert_spec.rbindex 8069e2c2bc..c16c7bcc65 100644--- a/spree/core/spec/services/spree/prices/bulk_upsert_spec.rb+++ b/spree/core/spec/services/spree/prices/bulk_upsert_spec.rb@@ -157,4 +157,47 @@ RSpec.describe Spree::Prices::BulkUpsert doexpect(surviving.first.amount).to eq(BigDecimal('12.34'))endend++ # The cap lives here because every write path reaches this service and none+ # of them run model validations (docs/plans/6.0-volume-pricing.md).+ describe 'the quantity-break cap' do+ let(:price_list) { create(:price_list, store: @default_store) }+ let(:variant) { create(:variant) }++ def rung(quantity, amount = '9.00')+ { variant_id: variant.id, currency: 'USD', price_list_id: price_list.id,+ min_quantity: quantity, amount: amount }+ end++ it 'refuses a batch that would take a variant past the cap' do+ result = described_class.call(rows: (2..(Spree::Price::MAXIMUM_BREAKS_PER_VARIANT + 2)).map { |q| rung(q) })++ expect(result).to be_failure+ expect(result.error.value[:over_cap].first).to include(variant_id: variant.id.to_s)+ expect(Spree::Price.where(price_list: price_list).breaks).to be_empty+ end++ it 'accepts a ladder exactly at the cap, bottom rung included' do+ rows = [rung(1, '10.00')] + (2..(Spree::Price::MAXIMUM_BREAKS_PER_VARIANT + 1)).map { |q| rung(q) }++ expect(described_class.call(rows: rows)).to be_success+ expect(Spree::Price.where(price_list: price_list, variant: variant).count).+ to eq(Spree::Price::MAXIMUM_BREAKS_PER_VARIANT + 1)+ end++ it 'lets a full ladder be rewritten in place' do+ rows = (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+ 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)++ expect(described_class.call(rows: [rung(1, '10.00')])).to be_success+ end+ endend