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: Re-importing an unchanged products export no longer lowers stock (#14825)
Łukasz Adamczyk644c605269c3
diff --git a/docs/plans/5.6-admin-spa-csv-import.md b/docs/plans/5.6-admin-spa-csv-import.mdindex 830292939d..31be004fdd 100644--- a/docs/plans/5.6-admin-spa-csv-import.md+++ b/docs/plans/5.6-admin-spa-csv-import.md@@ -420,6 +420,21 @@ to `Variant#default_stock_location`, which answers the *store's* — so anlocation. The processor passes the seller's default location instead, fallingback to the store's when they have none.+**Stock is per location, named in `stock_location`** (amended 2026-10-06, see+decisions.md). A row's `inventory_count` and `inventory_backorderable` are the+shelf count and setting at one location: the one `stock_location` names, or the+owner's default when it is blank. The export writes the default location on+the full row and adds a stock-only row per further location holding stock,+modelled on the price-only rows for extra currencies. Names are matched without+regard to case. An operator's file covers the marketplace's locations and, for+a seller's product, that seller's too; on import a name on a seller's product+resolves to the seller's own location first, so the seller's wins when both+owners use the name — the rule cartons follow. A seller's file and import+cover only their own locations: unlike cartons, a seller never falls back to+the marketplace's, since they may pack into a marketplace carton but must never+set the marketplace's shelf. An unknown name fails the row before anything on+it is written.+**The CSV's `status` column is ignored on a seller's import.** A sellerreaches `active` only through review, so an uploaded `status,active` wouldotherwise publish to the marketplace catalog with nobody having looked at it —diff --git a/docs/plans/6.0-stock-reservations.md b/docs/plans/6.0-stock-reservations.mdindex 4bb38c0abe..16232b95c9 100644--- a/docs/plans/6.0-stock-reservations.md+++ b/docs/plans/6.0-stock-reservations.md@@ -395,6 +395,7 @@ This is purely additive — no existing tables or models are modified (beyond Qu- **Don't modify `StockItem.count_on_hand` for reservations.** Reservations are a separate layer. `count_on_hand` only changes on order completion, stock adjustments, and shipment.- **Use `Quantifier#total_on_hand` for availability checks.** Don't query `count_on_hand` directly — the quantifier will handle the reservation subtraction.+- **A figure written back to the shelf reads the shelf.** Anything handed to `set_stock` or re-imported (the products CSV's `inventory_count`) reads the `count_on_hand` of the stock level it will be written back to; reading `total_on_hand` there takes every held unit off the shelf on each round trip (decisions.md, 2026-10-06).- **New checkout services should call `StockReservations::Extend`** after any successful step to keep reservations alive.## Open Questionsdiff --git a/docs/plans/6.0-typed-stock-movements.md b/docs/plans/6.0-typed-stock-movements.mdindex a7d36556e0..7394e4e903 100644--- a/docs/plans/6.0-typed-stock-movements.md+++ b/docs/plans/6.0-typed-stock-movements.md@@ -498,7 +498,7 @@ Two things that are **not** bridges and therefore have nothing to remove here: t- **Don't write `count_on_hand` outside a movement.** No new callers of `adjust_count_on_hand`, `set_count_on_hand`, `set_stock` or `update_all(count_on_hand:)`, and no new callers of `restock_backordered` — it is being deleted.- **Don't write a negative `count_on_hand`.** A level is held at or above zero whatever the variant's backorder or pre-order settings say, and only a forced dispatch is exempt. Code that expressed an oversell as a negative shelf expresses it as `allocated_count` above `count_on_hand` instead.- **Don't build business logic on `originator_type`.** It is gone in 6.1. Anything that needs to know why stock moved is waiting on `kind`.-- **Read availability through `Stock::Quantifier`, `StockLevel#available_count` or `#allocated_count`** — never raw `count_on_hand`. The shims already return correct answers today (`allocated_count` is 0), so code written against them keeps working unchanged when the column arrives. New raw `count_on_hand` reads are the main way this plan can regress.+- **Read availability through `Stock::Quantifier`, `StockLevel#available_count` or `#allocated_count`** — never raw `count_on_hand`. The shims already return correct answers today (`allocated_count` is 0), so code written against them keeps working unchanged when the column arrives. New raw `count_on_hand` reads are the main way this plan can regress. The one exception is a figure written back to the shelf — `set_stock`, or a file meant to be re-imported such as the products CSV — which reads the `count_on_hand` of the stock level it will be written back to, since subtracting allocations there removes them from the shelf (decisions.md, 2026-10-06).- **Don't assume stock leaves at placement.** Anything that reconciles on-hand against a warehouse, or reports "units removed", should key off fulfillment rather than order placement.- **The `:stock` permission resource already covers `StockMovement`** — a new stock endpoint needs no catalog entry, and must not ride `settings`.- **Don't add public surface named `stock_item`.** Phase 0 renames the class, the table, the endpoint, the SDK resource and the ID prefix, so a new endpoint, event name or SDK method carrying the old word ships already-deprecated. Internal references are fine until Phase 0 lands — that phase renames them wholesale.diff --git a/docs/plans/decisions.md b/docs/plans/decisions.mdindex 2373b3883c..fe95340bb5 100644--- a/docs/plans/decisions.md+++ b/docs/plans/decisions.md@@ -6104,3 +6104,46 @@ endpoint that names it, and naming it needs `write_customers`. The staff andseller reset requests are declared `webhook: false` and never reach anywebhook endpoint, whatever it subscribes to — the rule 5.x kept in thesubscriber's `NON_DELIVERABLE_EVENTS`, now read from the catalog.++## 2026-10-06 — The products CSV carries each location's shelf count++**Context:** The products export filled `inventory_count` from+`Variant#total_on_hand`, which since stock reservations and allocation means+what a customer can still buy: the shelf, minus units promised to placed+orders, minus units held by checkouts, summed over every active location. The+import writes the same column back through `Variant#set_stock`, which sets the+shelf at a single location. Exporting and re-importing an unchanged file+therefore took every promised and held unit off the shelf, once per round trip+(V-3697), and moved stock from every other location onto the default one. Both+stock plans told readers to go through the availability figure and never the+shelf, and neither listed the export as a reader.++**Decision:** `inventory_count` is the shelf count at one location, and+`inventory_backorderable` that location's setting. A new `stock_location`+column names the location; blank means the owner's default, so existing files+keep their meaning. The export writes the default location on the full row and+a stock-only row for each further location holding stock — the shape the+price-only rows for extra currencies already have. Locations are named, not+referenced by id, as the purchase-order import's `destination` is. An+operator's file covers the marketplace's locations and, for a seller's+product, that seller's; on import the seller's own location wins when both+owners use the name, as with cartons. That misroutes only a seller's product+stocked in a marketplace location named like one of the seller's own — rare+enough that failing every shared name was the worse trade, since it would+fail ordinary rows. A seller's file and import cover only their own locations:+a seller never sets the marketplace's shelf. Rejected: keeping the+sellable figure and having the import add held units back (holds change+between export and import); one column per location (headers change when a+location is renamed); exporting the default location alone (stock elsewhere+disappears from the file).++**Consequences:** A reader whose figure is written back to the shelf+(`set_stock`, a stock adjustment, a file meant to be re-imported) reads the+stock level's own `count_on_hand`; every availability reader still reads+`total_on_hand`. Renaming a location between export and import fails that+location's rows rather than writing elsewhere. A seller's export leaves out+their products' stock held in marketplace locations.++**Plans amended:** `5.6-admin-spa-csv-import.md` (stock is per location),+`6.0-stock-reservations.md` and `6.0-typed-stock-movements.md` (the "read+availability, never the shelf" constraints name the write-back exception).diff --git a/docs/user/manage-products/export-products.mdx b/docs/user/manage-products/export-products.mdxindex 0af58bb85e..c0611358d0 100644--- a/docs/user/manage-products/export-products.mdx+++ b/docs/user/manage-products/export-products.mdx@@ -27,3 +27,5 @@ This opens an export modal that gives you two options to choose from:Once you’ve made your selection, click **Export** in the modal, and a link to download the file will be sent to the email address associated with your user account.<Note>If your store sells in multiple currencies, the exported file will automatically include additional price-only rows for each currency. See [<u>Multi-Currency Import/Export</u>](https://spreecommerce.org/docs/user/manage-products/multi-currency-import-export) for details on how these rows work.</Note>++<Note>If a product is stocked at more than one location, the first row carries the stock at your default location and the file includes an extra stock-only row for each other location, named in the **stock_location** column. Importing the file sets the stock at each named location. Keep the location names as they are: a row naming a location that no longer exists, for example after a rename, is reported as failed and changes nothing.</Note>diff --git a/docs/user/manage-products/import-products.mdx b/docs/user/manage-products/import-products.mdxindex 2aa063c1b3..dcbbec4a74 100644--- a/docs/user/manage-products/import-products.mdx+++ b/docs/user/manage-products/import-products.mdx@@ -84,3 +84,5 @@ This is the safest and most efficient way to make large-scale updates to product<Note>If your store sells in multiple currencies, your exported file will include additional price-only rows for each currency. See [<u>Multi-Currency Import/Export</u>](https://spreecommerce.org/docs/user/manage-products/multi-currency-import-export) for details on how these rows work.</Note>+<Note>If a product is stocked at more than one location, the first row carries the stock at your default location and the file includes an extra stock-only row for each other location, named in the **stock_location** column. Importing the file sets the stock at each named location. Keep the location names as they are: a row naming a location that no longer exists, for example after a rename, is reported as failed and changes nothing.</Note>+diff --git a/docs/user/manage-products/product-import-file-template.mdx b/docs/user/manage-products/product-import-file-template.mdxindex 1562c48623..9ac56c78f2 100644--- a/docs/user/manage-products/product-import-file-template.mdx+++ b/docs/user/manage-products/product-import-file-template.mdx@@ -36,8 +36,9 @@ For an example of **how to structure multi-variant products**, please download t| available_on | When the product should be made available for purchase || discontinue_on | When the product should be discontinued and hidden from the storefront || track_inventory | Whether or not you track inventory levels for the product (TRUE/FALSE) |-| inventory_count | The stock quantity of the product/variant |-| inventory_backorderable | Whether the product can be ordered when out of stock |+| inventory_count | Units on the shelf at the row's stock location, including any held for checkouts or promised to unshipped orders |+| inventory_backorderable | Whether the product can be ordered when out of stock at the row's stock location |+| stock_location | The name of the stock location the two inventory fields apply to. Leave it blank for your default location || tax_category | The tax category the product should be assigned, e.g., Default, Non-taxable || shipping_category | The shipping category the product should be assigned, e.g., Default, Digital || image1_src | A link to the primary image product/variant image |diff --git a/spree/core/app/models/spree/exports/products.rb b/spree/core/app/models/spree/exports/products.rbindex b9b9020987..ab06efd4c9 100644--- a/spree/core/app/models/spree/exports/products.rb+++ b/spree/core/app/models/spree/exports/products.rb@@ -9,13 +9,22 @@ module Spreeenddef variant_includes- [:images, :prices, :stock_levels, :stock_locations, { option_values: [:option_type] }]+ [:images, :prices, { stock_levels: :stock_location, option_values: [:option_type] }]enddef multi_line_csv?trueend+ # The seller scopes which locations the inventory columns cover; their+ # default, worked out once per export, carries the full row's stock.+ def to_csv_options+ @to_csv_options ||= {+ seller: seller,+ default_stock_location: Spree::StockLocation.owned_by(store_id: store.id, seller_id: seller&.id).active.order_default.first || store.default_stock_location+ }+ end+# when doing full product export, we want to exclude archived productsdef scopeif search_params.nil?diff --git a/spree/core/app/models/spree/import_schemas/products.rb b/spree/core/app/models/spree/import_schemas/products.rbindex 768a559fce..ad3d4ea81c 100644--- a/spree/core/app/models/spree/import_schemas/products.rb+++ b/spree/core/app/models/spree/import_schemas/products.rb@@ -25,6 +25,7 @@ module Spree{ name: 'track_inventory', label: 'Track Inventory' },{ name: 'inventory_count', label: 'Inventory Count' },{ name: 'inventory_backorderable', label: 'Inventory Backorderable' },+ { name: 'stock_location', label: 'Stock Location' },{ name: 'tax_category', label: 'Tax Category' },{ name: 'product_type', label: 'Product Type' },{ name: 'hs_code', label: 'HS Code' },diff --git a/spree/core/app/models/spree/product.rb b/spree/core/app/models/spree/product.rbindex c9a5e8d015..a4e7c314f7 100644--- a/spree/core/app/models/spree/product.rb+++ b/spree/core/app/models/spree/product.rb@@ -815,7 +815,13 @@ module SpreeSpree::Products::AutoMatchCollectionsJob.set(wait: 30.seconds).perform_later(id)end- def to_csv(store = nil)+ # @param seller [Spree::Seller, nil] the seller exporting their own+ # products, whose rows cover only their own locations; nil for the+ # operator, whose rows cover the marketplace's and the product's seller's+ # @param default_stock_location [Spree::StockLocation, nil] the location+ # the full rows carry; further locations get stock-only rows. The+ # store's default when nil+ def to_csv(store = nil, seller: nil, default_stock_location: nil)store ||= self.storeproperties_for_csv = if respond_to?(:product_properties) && Spree::Config.respond_to?(:product_properties_enabled) && Spree::Config[:product_properties_enabled]Spree::Property.order(:position).flat_map do |property|@@ -838,11 +844,12 @@ module Spreeall_variants = variants.to_adefault_currency = store.default_currencyadditional_currencies = store.supported_currencies_list.map(&:iso_code) - [default_currency]+ default_stock_location ||= store.default_stock_location# Primary rows in the store's default currencyall_variants.each_with_index do |variant, index|csv_lines << Spree::CSV::ProductVariantPresenter.new(self, variant, index, properties_for_csv, categories_for_csv, store,- custom_field_values).call+ custom_field_values, default_stock_location: default_stock_location).callend# Price-only rows for each additional currency@@ -855,6 +862,25 @@ module Spreeendend+ # Stock-only rows for every other location the importer can name back. A+ # row the import cannot route to its variant is left out: with no SKU it+ # would land on the default variant.+ location_owner_ids = seller ? [seller.id] : [nil, seller_id].uniq+ all_variants.each do |variant|+ next unless variant.should_track_inventory?+ next if variant.sku.blank? && variant != default_variant++ variant.stock_levels.each do |stock_level|+ location = stock_level.stock_location+ next if location.nil? || location == default_stock_location+ next unless location.store_id == store.id && location_owner_ids.include?(location.seller_id)+ next if stock_level.count_on_hand.zero?++ csv_lines << Spree::CSV::ProductVariantPresenter.new(self, variant, 0, [], [], store,+ stock_level: stock_level).call+ end+ end+csv_linesenddiff --git a/spree/core/app/presenters/spree/csv/product_variant_presenter.rb b/spree/core/app/presenters/spree/csv/product_variant_presenter.rbindex f0f543689e..fdb839c739 100644--- a/spree/core/app/presenters/spree/csv/product_variant_presenter.rb+++ b/spree/core/app/presenters/spree/csv/product_variant_presenter.rb@@ -30,6 +30,7 @@ module Spree'track_inventory','inventory_count','inventory_backorderable',+ 'stock_location','tax_category','product_type','image1_src',@@ -46,7 +47,13 @@ module Spree'category3',].freeze- def initialize(product, variant, index = 0, properties = [], categories = [], store = nil, custom_fields = [], currency = nil)+ # @param default_stock_location [Spree::StockLocation, nil] where the full row's+ # inventory columns read from, blank when the variant has no stock+ # there; the store's default when nil+ # @param stock_level [Spree::StockLevel, nil] turns the row into a+ # stock-only row for that level's location+ def initialize(product, variant, index = 0, properties = [], categories = [], store = nil, custom_fields = [], currency = nil,+ default_stock_location: nil, stock_level: nil)@product = product@variant = variant@index = index@@ -56,9 +63,12 @@ module Spree@currency = currency || @store.default_currency@price_only = @currency != @store.default_currency@custom_fields = custom_fields+ @default_stock_location = default_stock_location+ @stock_level = stock_levelend- attr_accessor :product, :variant, :index, :properties, :categories, :store, :currency, :price_only, :custom_fields+ attr_accessor :product, :variant, :index, :properties, :categories, :store, :currency, :price_only, :custom_fields,+ :default_stock_location, :stock_level### Generates an array representing a CSV row of product variant data.@@ -73,8 +83,7 @@ module Spree# @return [Array] An array containing the combined product and variant CSV data.def callreturn price_only_row if price_only-- total_on_hand = variant.total_on_hand+ return stock_only_row if stock_levelcsv = [product.id,@@ -104,8 +113,12 @@ module Spreepublication_available_on&.strftime('%Y-%m-%d %H:%M:%S'),(variant.discontinue_on || publication_discontinue_on)&.strftime('%Y-%m-%d %H:%M:%S'),variant.track_inventory?,- total_on_hand == BigDecimal::INFINITY ? '∞' : total_on_hand,- variant.backorderable?,+ # The shelf count at the one location the import writes this row+ # back to, not what is left to sell: that would drop every unit held+ # by a cart or promised to an order on each round trip.+ variant.should_track_inventory? ? default_stock_level&.count_on_hand : '∞',+ default_stock_level&.backorderable,+ nil,variant.tax_category&.name,product.product_type&.name,spree_image_url(variant.images[0], image_url_options),@@ -168,6 +181,23 @@ module Spreecsvend+ def stock_only_row+ csv = Array.new(CSV_HEADERS.size)+ csv[CSV_HEADERS.index('sku')] = variant.sku+ csv[CSV_HEADERS.index('slug')] = product.slug+ csv[CSV_HEADERS.index('inventory_count')] = stock_level.count_on_hand+ csv[CSV_HEADERS.index('inventory_backorderable')] = stock_level.backorderable+ csv[CSV_HEADERS.index('stock_location')] = stock_level.stock_location.name+ csv+ end++ def default_stock_level+ return @default_stock_level if defined?(@default_stock_level)++ location = default_stock_location || store.default_stock_location+ @default_stock_level = variant.stock_levels.find { |level| level.stock_location_id == location.id }+ end+def image_url_options{ variant: :xlarge }enddiff --git a/spree/core/app/services/spree/imports/row_processors/product_variant.rb b/spree/core/app/services/spree/imports/row_processors/product_variant.rbindex a7a75571d3..093920209a 100644--- a/spree/core/app/services/spree/imports/row_processors/product_variant.rb+++ b/spree/core/app/services/spree/imports/row_processors/product_variant.rb@@ -9,10 +9,13 @@ module Spreesuper@store = row.store@seller = import.seller+ # Before the product is saved: rows are not wrapped in a transaction,+ # so an unknown location must fail the row with nothing written.+ @stock_location = import_stock_location if attributes['inventory_count'].present?@product = ensure_product_existsend- attr_reader :product, :store, :seller+ attr_reader :product, :store, :seller, :stock_locationdef process!variant = if attributes['sku'].present?@@ -63,7 +66,7 @@ module Spreevariant.set_stock(attributes['inventory_count'].to_i,attributes['inventory_backorderable']&.to_b,- import_stock_location+ stock_location)end@@ -253,23 +256,32 @@ module Spreeendend- # Where an imported row's stock lands.- #- # Nil for an operator's import, which leaves `set_stock` to pick the- # store's default. A seller's stock belongs in their own warehouse:- # `Variant#default_stock_location` answers the *store's*, so without- # this a seller's `inventory_count` would deposit their goods in the- # marketplace's location — the same mistake the seller products- # endpoint narrows `stock_levels` to prevent.- #- # A seller with no location of their own falls back to the store's- # rather than dropping the count on the floor.def import_stock_location- return nil if seller.blank?+ name = attributes['stock_location'].to_s.squish- cached_lookup(:seller_stock_location, seller.id) do- seller.stock_locations.active.order_default.first+ if name.blank?+ return cached_lookup(:default_stock_location) do+ Spree::StockLocation.owned_by(store_id: store.id, seller_id: seller&.id).active.order_default.first ||+ store.default_stock_location+ endend++ owner_ids = stock_location_owner_ids+ name_column = Spree::StockLocation.arel_table[:name]+ cached_lookup(:stock_location, owner_ids, name.downcase) do+ store.stock_locations.where(seller_id: owner_ids).+ order(Arel.sql('CASE WHEN seller_id IS NULL THEN 1 ELSE 0 END')).+ find_by(name_column.lower.eq(Arel::Nodes::NamedFunction.new('LOWER', [Arel::Nodes.build_quoted(name)])))+ end || raise(ArgumentError, Spree.t(:product_import_unknown_stock_location, name: name))+ end++ # A seller reaches only their own locations — never the marketplace's+ # shelf. An operator reaches the marketplace's and, for a seller's+ # product, that seller's, whose own wins on a shared name as with cartons.+ def stock_location_owner_ids+ return [seller.id] if seller.present?++ [nil, product_scope.where(slug: attributes['slug'].to_s.strip.downcase).pick(:seller_id)].uniqenddef prepare_option_value_variantsdiff --git a/spree/core/config/locales/en.yml b/spree/core/config/locales/en.ymlindex 66f013f1d0..763fd056c4 100644--- a/spree/core/config/locales/en.yml+++ b/spree/core/config/locales/en.yml@@ -1379,6 +1379,7 @@ en:process: Processprocessing: Processingproduct: Product+ product_import_unknown_stock_location: You have no stock location named %{name}.product_name: Product Nameproduct_properties: Product Propertiesproduct_translations: Product Translationsdiff --git a/spree/core/spec/models/spree/exports/products_spec.rb b/spree/core/spec/models/spree/exports/products_spec.rbindex 2749d800ce..86f507ef7b 100644--- a/spree/core/spec/models/spree/exports/products_spec.rb+++ b/spree/core/spec/models/spree/exports/products_spec.rb@@ -25,6 +25,27 @@ RSpec.describe Spree::Exports::Products, type: :model doendend+ describe '#generate' do+ let(:seller) { create(:seller, :approved, store: store) }+ let(:product) { create(:product, store: store, seller: seller) }+ let(:seller_location) { create(:stock_location, store: store, seller: seller, name: 'Seller Shed') }++ before do+ product.default_variant.update!(sku: 'SHED-MUG', track_inventory: true)+ product.default_variant.set_stock(12, false, store.default_stock_location)+ product.default_variant.set_stock(7, false, seller_location)+ end++ it "writes only a seller's own stock on the seller's export" do+ export = described_class.new(store: store, seller: seller)+ export.save!+ export.generate++ rows = CSV.parse(export.attachment.download, headers: true)+ expect(rows.map { |row| row.values_at('sku', 'inventory_count', 'stock_location') }).to eq [['SHED-MUG', '7', nil]]+ end+ end+describe '#csv_headers' docontext 'when no custom_fields' doit 'returns product variant headers without properties' do@@ -55,6 +76,7 @@ RSpec.describe Spree::Exports::Products, type: :model do'track_inventory','inventory_count','inventory_backorderable',+ 'stock_location','tax_category','product_type','image1_src',@@ -105,6 +127,7 @@ RSpec.describe Spree::Exports::Products, type: :model do'track_inventory','inventory_count','inventory_backorderable',+ 'stock_location','tax_category','product_type','image1_src',diff --git a/spree/core/spec/models/spree/product_spec.rb b/spree/core/spec/models/spree/product_spec.rbindex d33d4f7838..e1ce94d6dc 100644--- a/spree/core/spec/models/spree/product_spec.rb+++ b/spree/core/spec/models/spree/product_spec.rb@@ -1440,6 +1440,41 @@ describe Spree::Product, type: :model doexpect(eur_lines[0][Spree::CSV::ProductVariantPresenter::CSV_HEADERS.index('sku')]).to eq variant1.skuendend++ context 'when stock sits at several locations' do+ let(:headers) { Spree::CSV::ProductVariantPresenter::CSV_HEADERS }+ let(:variant) { product.default_variant }+ let(:seller) { create(:seller, store: store) }+ let(:warehouse) { create(:stock_location, store: store, name: 'Warehouse B') }+ let(:empty_location) { create(:stock_location, store: store, name: 'Empty') }+ let(:seller_location) { create(:stock_location, store: store, seller: seller, name: 'Seller Shed') }++ before do+ variant.update!(sku: 'MUG', track_inventory: true)+ variant.set_stock(12, false, store.default_stock_location)+ variant.set_stock(5, true, warehouse)+ variant.set_stock(0, false, empty_location)+ variant.set_stock(7, false, seller_location)+ end++ def stock_rows(lines)+ lines.map { |row| row.values_at(headers.index('inventory_count'), headers.index('stock_location')) }+ end++ it "covers the marketplace's locations, the default on the full row" do+ expect(stock_rows(product.reload.to_csv(store))).to eq [[12, nil], [5, 'Warehouse B']]+ end++ it "also covers the seller's own locations for a seller's product" do+ product.update!(seller: seller)++ expect(stock_rows(product.reload.to_csv(store))).to eq [[12, nil], [5, 'Warehouse B'], [7, 'Seller Shed']]+ end++ it "covers only a seller's own locations on the seller's export" do+ expect(stock_rows(product.reload.to_csv(store, seller: seller, default_stock_location: seller_location))).to eq [[7, nil]]+ end+ endenddescribe '#to_translation_csv' dodiff --git a/spree/core/spec/presenters/spree/csv/product_variant_presenter_spec.rb b/spree/core/spec/presenters/spree/csv/product_variant_presenter_spec.rbindex 12579349a7..4dd1cf25cb 100644--- a/spree/core/spec/presenters/spree/csv/product_variant_presenter_spec.rb+++ b/spree/core/spec/presenters/spree/csv/product_variant_presenter_spec.rb@@ -42,19 +42,88 @@ RSpec.describe Spree::CSV::ProductVariantPresenter do(variant.discontinue_on || default_publication.unpublished_at)&.strftime('%Y-%m-%d %H:%M:%S'))expect(subject[23]).to eq variant.track_inventory?- expect(subject[24]).to eq(variant.total_on_hand == BigDecimal::INFINITY ? '∞' : variant.total_on_hand)- expect(subject[25]).to eq variant.backorderable?- expect(subject[26]).to eq variant.tax_category&.name- expect(subject[27]).to eq product.product_type&.name- expect(subject[28]).to end_with(variant.images[0].filename.to_s)- expect(subject[29]).to end_with(variant.images[1].filename.to_s)- expect(subject[30]).to end_with(variant.images[2].filename.to_s)- expect(subject[31]).to eq nil+ default_level = variant.stock_levels.find_by(stock_location: store.default_stock_location)+ expect(subject[24]).to eq default_level&.count_on_hand+ expect(subject[25]).to eq default_level&.backorderable+ expect(subject[26]).to eq nil+ expect(subject[27]).to eq variant.tax_category&.name+ expect(subject[28]).to eq product.product_type&.name+ expect(subject[29]).to end_with(variant.images[0].filename.to_s)+ expect(subject[30]).to end_with(variant.images[1].filename.to_s)+ expect(subject[31]).to end_with(variant.images[2].filename.to_s)expect(subject[32]).to eq nilexpect(subject[33]).to eq nilexpect(subject[34]).to eq nilexpect(subject[35]).to eq nilexpect(subject[36]).to eq nil+ expect(subject[37]).to eq nil+ end++ context 'when units are promised to an order and held by a cart' do+ let(:stock_location) { create(:stock_location) }+ let(:presenter) { described_class.new(product, variant, 0, [], [], store, [], default_stock_location: stock_location) }+ let(:stock_level) { variant.stock_levels.find_by!(stock_location: stock_location) }+ let(:cart) { create(:cart, store: store) }++ before do+ stub_store_preferences(stock_reservations_enabled: true)+ variant.update!(track_inventory: true)+ variant.set_stock(12, false, stock_location)+ stock_level.update_columns(allocated_count: 3)+ create(+ :stock_reservation,+ stock_level: stock_level,+ line_item: create(:line_item, order: cart, variant: variant),+ cart: cart,+ quantity: 1+ )+ end++ it 'exports the shelf count as inventory_count' do+ expect(variant.total_on_hand).to eq 8+ expect(subject[described_class::CSV_HEADERS.index('inventory_count')]).to eq 12+ end+ end++ context 'with stock at several locations' do+ let(:default_location) { create(:stock_location, name: 'Main') }+ let(:other_location) { create(:stock_location, name: 'Warehouse B') }+ let(:presenter) { described_class.new(product, variant, 0, [], [], store, [], default_stock_location: default_location) }++ before do+ variant.update!(track_inventory: true)+ variant.set_stock(12, false, default_location)+ variant.set_stock(5, true, other_location)+ end++ it 'carries only the given location on the full row' do+ expect(subject[described_class::CSV_HEADERS.index('inventory_count')]).to eq 12+ expect(subject[described_class::CSV_HEADERS.index('inventory_backorderable')]).to be false+ expect(subject[described_class::CSV_HEADERS.index('stock_location')]).to be_nil+ end++ it 'leaves the inventory columns blank when the given location holds no stock' do+ row = described_class.new(product, variant, 0, [], [], store, [], default_stock_location: create(:stock_location)).call++ expect(row.values_at(described_class::CSV_HEADERS.index('inventory_count'),+ described_class::CSV_HEADERS.index('inventory_backorderable'))).to eq [nil, nil]+ end++ it 'writes a stock-only row naming any other location' do+ stock_level = variant.stock_levels.find_by!(stock_location: other_location)+ row = described_class.new(product, variant, 0, [], [], store, stock_level: stock_level).call++ expect(row.size).to eq described_class::CSV_HEADERS.size+ expect(row.compact).to contain_exactly(variant.sku, product.slug, 5, true, 'Warehouse B')+ end+ end++ context 'when the variant does not track inventory' do+ before { variant.update!(track_inventory: false) }++ it 'exports inventory_count as unlimited' do+ expect(subject[described_class::CSV_HEADERS.index('inventory_count')]).to eq '∞'+ endendcontext 'when the variant has option values' do@@ -70,12 +139,12 @@ RSpec.describe Spree::CSV::ProductVariantPresenter doit 'returns the options alongside the product-level fields' doexpect(subject[2]).to eq product.nameexpect(subject[1]).to eq variant.sku- expect(subject[31]).to eq 'Color'- expect(subject[32]).to eq 'Red'- expect(subject[33]).to eq 'Size'- expect(subject[34]).to eq 'Small'- expect(subject[35]).to eq nil+ expect(subject[32]).to eq 'Color'+ expect(subject[33]).to eq 'Red'+ expect(subject[34]).to eq 'Size'+ expect(subject[35]).to eq 'Small'expect(subject[36]).to eq nil+ expect(subject[37]).to eq nilendend@@ -92,12 +161,12 @@ RSpec.describe Spree::CSV::ProductVariantPresenter doexpect(subject[1]).to eq variant.skuexpect(subject[12]).to eq variant.amount_in(store.default_currency).to_fexpect(subject[23]).to eq false- expect(subject[31]).to eq 'Color'- expect(subject[32]).to eq 'Red'- expect(subject[33]).to eq 'Size'- expect(subject[34]).to eq 'Small'- expect(subject[35]).to eq nil+ expect(subject[32]).to eq 'Color'+ expect(subject[33]).to eq 'Red'+ expect(subject[34]).to eq 'Size'+ expect(subject[35]).to eq 'Small'expect(subject[36]).to eq nil+ expect(subject[37]).to eq nilendendend@@ -109,9 +178,9 @@ RSpec.describe Spree::CSV::ProductVariantPresenter doendit 'returns images with default host' do- expect(subject[28]).to start_with('http://test.host')expect(subject[29]).to start_with('http://test.host')expect(subject[30]).to start_with('http://test.host')+ expect(subject[31]).to start_with('http://test.host')endend@@ -121,9 +190,9 @@ RSpec.describe Spree::CSV::ProductVariantPresenter doendit 'returns images with the store url' do- expect(subject[28]).to start_with("http://#{store.url}")expect(subject[29]).to start_with("http://#{store.url}")expect(subject[30]).to start_with("http://#{store.url}")+ expect(subject[31]).to start_with("http://#{store.url}")endend@@ -227,7 +296,7 @@ RSpec.describe Spree::CSV::ProductVariantPresenter doit 'exports the product type name' doresult = presenter.call- expect(result[27]).to eq 'Digital'+ expect(result[28]).to eq 'Digital'endend@@ -236,7 +305,7 @@ RSpec.describe Spree::CSV::ProductVariantPresenter doit 'exports a blank column' doresult = presenter.call- expect(result[27]).to be_nil+ expect(result[28]).to be_nilendendenddiff --git a/spree/core/spec/services/spree/imports/row_processors/product_variant_seller_spec.rb b/spree/core/spec/services/spree/imports/row_processors/product_variant_seller_spec.rbindex 7f60240edb..57eb78d27d 100644--- a/spree/core/spec/services/spree/imports/row_processors/product_variant_seller_spec.rb+++ b/spree/core/spec/services/spree/imports/row_processors/product_variant_seller_spec.rb@@ -168,6 +168,29 @@ RSpec.describe Spree::Imports::RowProcessors::ProductVariant, 'for a seller-owneexpect(level).to be_presentexpect(level.count_on_hand).to eq(7)end++ context 'when the row names a location' do+ let(:marketplace_namesake) { create(:stock_location, store: store, name: 'Shared name') }+ # Created after its namesake, so an unscoped lookup would find the marketplace's first.+ let!(:seller_location) do+ marketplace_namesake+ create(:stock_location, seller: seller, store: store, name: 'Shared name', default: false)+ end++ let(:row_data) do+ csv_row_hash('slug' => 'denim-shirt', 'name' => 'Denim Shirt', 'price' => '1.00',+ 'inventory_count' => '7', 'stock_location' => seller_location.name)+ end++ before { import.mappings.find_by(schema_field: 'stock_location').update!(file_column: 'stock_location') }++ it "resolves it among the seller's own, never the marketplace's namesake" do+ variant = subject.process!++ expect(variant.stock_levels.find_by(stock_location: seller_location).count_on_hand).to eq(7)+ expect(variant.stock_levels.find_by(stock_location: marketplace_namesake)).to be_nil+ end+ endenddescribe 'updating' dodiff --git a/spree/core/spec/services/spree/imports/row_processors/product_variant_spec.rb b/spree/core/spec/services/spree/imports/row_processors/product_variant_spec.rbindex 0e6bb93f3f..013e395ff9 100644--- a/spree/core/spec/services/spree/imports/row_processors/product_variant_spec.rb+++ b/spree/core/spec/services/spree/imports/row_processors/product_variant_spec.rb@@ -540,6 +540,86 @@ RSpec.describe Spree::Imports::RowProcessors::ProductVariant, type: :service doendend+ context 'when importing stock-only rows for a named location' do+ let!(:product) { create(:product, slug: 'mug', name: 'Mug') }+ let!(:existing_variant) { product.default_variant.tap { |variant| variant.update!(sku: 'MUG', track_inventory: true) } }+ let!(:warehouse) { create(:stock_location, store: store, name: 'Warehouse B') }+ let(:location_name) { ' warehouse b ' }++ let(:row_data) do+ csv_row_hash(+ 'slug' => 'mug',+ 'sku' => 'MUG',+ 'inventory_count' => '5',+ 'inventory_backorderable' => 'true',+ 'stock_location' => location_name+ )+ end++ before do+ %w[inventory_count inventory_backorderable stock_location].each do |field|+ import.mappings.find_by(schema_field: field)&.update(file_column: field)+ end+ existing_variant.set_stock(12, false, store.default_stock_location)+ end++ def count_at(location)+ existing_variant.stock_levels.find_by(stock_location: location)&.count_on_hand+ end++ it 'sets the stock at that location only, matching the name as the location stores it' do+ subject.process!++ expect(count_at(warehouse)).to eq 5+ expect(existing_variant.stock_levels.find_by(stock_location: warehouse).backorderable).to be true+ expect(count_at(store.default_stock_location)).to eq 12+ end++ context 'when no location has that name' do+ let(:row_data) do+ csv_row_hash('slug' => 'mug', 'name' => 'Renamed Mug', 'sku' => 'MUG', 'price' => '99.00',+ 'inventory_count' => '5', 'stock_location' => 'Nowhere')+ end++ before { import.mappings.find_by(schema_field: 'name')&.update(file_column: 'name') }++ it 'fails the row before writing anything' do+ expect { subject.process! }.to raise_error(ArgumentError, 'You have no stock location named Nowhere.')+ expect(product.reload.name).to eq 'Mug'+ expect(existing_variant.reload.price_in(store.default_currency).amount.to_f).not_to eq 99.0+ end+ end++ # The split cartons use: an operator's file names the marketplace's+ # locations, a seller's names their own, so a shared name is never ambiguous.+ context "when the name is a seller's location" do+ let(:seller) { create(:seller, store: store) }+ let!(:warehouse) { create(:stock_location, store: store, seller: seller, name: 'Warehouse B') }++ it "does not reach it for a marketplace product" do+ expect { subject.process! }.to raise_error(ArgumentError, 'You have no stock location named warehouse b.')+ end++ context "and the product is that seller's" do+ # Created first, so only the ordering keeps it from winning the lookup.+ let!(:marketplace_namesake) { create(:stock_location, store: store, name: 'Warehouse B') }+ let!(:warehouse) do+ marketplace_namesake+ create(:stock_location, store: store, seller: seller, name: 'Warehouse B')+ end++ before { product.update!(seller: seller) }++ it "writes to the seller's own location, which wins over the marketplace's namesake as with cartons" do+ subject.process!++ expect(count_at(warehouse)).to eq 5+ expect(count_at(marketplace_namesake)).to be_nil+ end+ end+ end+ end+context 'when importing a variant row with a new option type/value' dolet!(:product) docreate(:product, slug: 'denim-shirt', name: 'Denim Shirt')