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
Offer only the SKUs a warehouse can actually send
Łukasz Adamczyk8d02331e937f
diff --git a/packages/dashboard/e2e/stock-transfers.spec.ts b/packages/dashboard/e2e/stock-transfers.spec.tsindex 4ecd0ff3dc..4c5f2bb590 100644--- a/packages/dashboard/e2e/stock-transfers.spec.ts+++ b/packages/dashboard/e2e/stock-transfers.spec.ts@@ -36,6 +36,11 @@ test.describe('stock transfers', () => {await expect(page.locator('#destination')).toBeVisible()// Empty until a SKU is added — a draft may open with nothing on it.await expect(page.getByRole('button', { name: /create draft/i })).toBeVisible()++ // Nothing can be added until the source is known: the list can only offer+ // what that warehouse is able to send.+ await expect(page.getByPlaceholder(/search products/i)).toBeDisabled()+ await expect(page.getByText(/choose the warehouse it leaves from first/i)).toBeVisible()})test('sends a draft, then receives less than was sent', async ({ page }) => {diff --git a/packages/dashboard/src/components/spree/variant-line-editor.tsx b/packages/dashboard/src/components/spree/variant-line-editor.tsxindex 29b2e9d469..42b7ab69cf 100644--- a/packages/dashboard/src/components/spree/variant-line-editor.tsx+++ b/packages/dashboard/src/components/spree/variant-line-editor.tsx@@ -3,6 +3,7 @@ import { adminClient, formatPrice, ResourceCombobox } from '@spree/dashboard-corimport {Button,Field,+ FieldDescription,FieldLabel,Input,InputGroup,@@ -19,6 +20,7 @@ import {import { TrashIcon } from '@spree/dashboard-ui/icons'import { useRef } from 'react'import { useTranslation } from 'react-i18next'+import { VariantLink } from './variant-link'/** One SKU the merchant is putting on a transfer or a purchase order. */export interface VariantLine {@@ -40,6 +42,8 @@ export function VariantLineEditor({currency,quantityLabel,withCost = false,+ stockLocationId,+ requireStockLocation = false,}: {lines: VariantLine[]onChange: (lines: VariantLine[]) => void@@ -47,8 +51,20 @@ export function VariantLineEditor({currency?: stringquantityLabel: stringwithCost?: boolean+ /**+ * Offer only SKUs this warehouse could actually send. Transfers pass their+ * source; a purchase order passes nothing, because buying stock in is how a+ * merchant gets what they do not have.+ */+ stockLocationId?: string | null+ /** Refuse to open the picker until a warehouse is chosen. */+ requireStockLocation?: boolean}) {const { t } = useTranslation()+ // Nothing sensible to search until the source is known, and offering the+ // whole catalogue invites a line the warehouse cannot send — which is only+ // refused later, per line, when the transfer is marked in transit.+ const locked = !!requireStockLocation && !stockLocationId// `onChange` hands back only the option id, so keep the records the search// returned to resolve it. A ref, not state: it is a lookup table.const variantById = useRef(new Map<string, Variant>())@@ -83,14 +99,21 @@ export function VariantLineEditor({come from the primitive. Selecting adds the row and clears thefield, so no value is held. */}<ResourceCombobox<Variant>- queryKey="inventory-line-variant-picker"+ // Keyed by warehouse: the same query means different things at two+ // sources, and a cached result would offer the wrong shelf's SKUs.+ queryKey={`inventory-line-variant-picker:${stockLocationId ?? 'any'}`}value=""+ disabled={locked}onChange={(id) => {const variant = id ? variantById.current.get(id) : undefinedif (variant) addVariant(variant)}}search={async (query) => {- const res = await adminClient.variants.list({ search: query, limit: 8 })+ const res = await adminClient.variants.list({+ search: query,+ limit: 8,+ ...(stockLocationId ? { available_at_stock_location: stockLocationId } : {}),+ })for (const variant of res.data) variantById.current.set(variant.id, variant)return res}}@@ -109,6 +132,9 @@ export function VariantLineEditor({)}placeholder={t('admin.inventory_lines.search_placeholder')}/>+ {locked && (+ <FieldDescription>{t('admin.inventory_lines.pick_source_first')}</FieldDescription>+ )}</Field>{lines.length > 0 && (@@ -117,7 +143,6 @@ export function VariantLineEditor({<TableHeader><TableRow><TableHead>{t('admin.inventory_lines.columns.variant')}</TableHead>- <TableHead>{t('admin.inventory_lines.columns.sku')}</TableHead><TableHead className="text-right">{quantityLabel}</TableHead>{withCost && (<TableHead className="text-right">@@ -130,10 +155,16 @@ export function VariantLineEditor({<TableBody>{lines.map(({ variant, quantity, unitCost }) => (<TableRow key={variant.id}>- <TableCell className="font-medium">- {variant.product_name ?? variant.sku ?? variant.id}+ <TableCell>+ {/* No product link: this form has unsaved work in it, and+ the row reads the same as the ones on the saved+ document. */}+ <VariantLink+ name={variant.product_name ?? variant.sku ?? variant.id}+ sku={variant.sku}+ thumbnailUrl={variant.thumbnail_url}+ /></TableCell>- <TableCell className="text-muted-foreground">{variant.sku}</TableCell><TableCell className="text-right"><Inputtype="number"diff --git a/packages/dashboard/src/locales/ar.json b/packages/dashboard/src/locales/ar.jsonindex 87ea09e69a..f4f3a22e22 100644--- a/packages/dashboard/src/locales/ar.json+++ b/packages/dashboard/src/locales/ar.json@@ -5448,6 +5448,7 @@"inventory_lines": {"add_label": "إضافة منتج","search_placeholder": "ابحث عن المنتجات بالاسم أو رمز SKU…",+ "pick_source_first": "اختر المستودع المُرسِل أولاً — تعرض القائمة ما يمكن لهذا المستودع إرساله فقط.","columns": {"variant": "المنتج","sku": "رمز SKU",diff --git a/packages/dashboard/src/locales/de.json b/packages/dashboard/src/locales/de.jsonindex 08a9c5f2ff..180533fd04 100644--- a/packages/dashboard/src/locales/de.json+++ b/packages/dashboard/src/locales/de.json@@ -5419,6 +5419,7 @@"inventory_lines": {"add_label": "Produkt hinzufügen","search_placeholder": "Produkte nach Name oder SKU suchen…",+ "pick_source_first": "Wählen Sie zuerst das Lager, aus dem versandt wird — die Liste zeigt nur, was dieses Lager senden kann.","columns": {"variant": "Produkt","sku": "SKU",diff --git a/packages/dashboard/src/locales/en.json b/packages/dashboard/src/locales/en.jsonindex 4ad66c3616..353a9c37b6 100644--- a/packages/dashboard/src/locales/en.json+++ b/packages/dashboard/src/locales/en.json@@ -5419,6 +5419,7 @@"inventory_lines": {"add_label": "Add a product","search_placeholder": "Search products by name or SKU…",+ "pick_source_first": "Choose the warehouse it leaves from first — the list only offers what that warehouse can send.","columns": {"variant": "Product","sku": "SKU",diff --git a/packages/dashboard/src/locales/fr.json b/packages/dashboard/src/locales/fr.jsonindex 18018e3899..160be4c0cb 100644--- a/packages/dashboard/src/locales/fr.json+++ b/packages/dashboard/src/locales/fr.json@@ -5419,6 +5419,7 @@"inventory_lines": {"add_label": "Ajouter un produit","search_placeholder": "Rechercher un produit par nom ou UGS…",+ "pick_source_first": "Choisissez d'abord l'entrepôt de départ — la liste ne propose que ce qu'il peut envoyer.","columns": {"variant": "Produit","sku": "UGS",diff --git a/packages/dashboard/src/locales/pl.json b/packages/dashboard/src/locales/pl.jsonindex 3dcc08a9cb..cb271b1726 100644--- a/packages/dashboard/src/locales/pl.json+++ b/packages/dashboard/src/locales/pl.json@@ -5481,6 +5481,7 @@"inventory_lines": {"add_label": "Dodaj produkt","search_placeholder": "Szukaj produktów po nazwie lub SKU…",+ "pick_source_first": "Najpierw wybierz magazyn źródłowy — lista pokazuje tylko to, co ten magazyn może wysłać.","columns": {"variant": "Produkt","sku": "SKU",diff --git a/packages/dashboard/src/locales/zh-CN.json b/packages/dashboard/src/locales/zh-CN.jsonindex 5e03b0bff8..fe1d016d20 100644--- a/packages/dashboard/src/locales/zh-CN.json+++ b/packages/dashboard/src/locales/zh-CN.json@@ -5408,6 +5408,7 @@"inventory_lines": {"add_label": "添加商品","search_placeholder": "按名称或 SKU 搜索商品…",+ "pick_source_first": "请先选择发出仓库 — 列表只显示该仓库可以发出的商品。","columns": {"variant": "商品","sku": "SKU",diff --git a/packages/dashboard/src/routes/_authenticated/$storeId/products/transfers/new.tsx b/packages/dashboard/src/routes/_authenticated/$storeId/products/transfers/new.tsxindex 0560cee822..80fb719dbf 100644--- a/packages/dashboard/src/routes/_authenticated/$storeId/products/transfers/new.tsx+++ b/packages/dashboard/src/routes/_authenticated/$storeId/products/transfers/new.tsx@@ -159,10 +159,15 @@ function NewStockTransferPage() {<CardContent>{/* A draft may open empty and gain lines as the merchant packs, sothere is nothing to enforce here. */}+ {/* The picker offers only what the source can send, and stays shut+ until one is chosen: a line the source has none of is refused+ later, per line, when the transfer is marked in transit. */}<VariantLineEditorlines={lines}onChange={setLines}quantityLabel={t('admin.stock_transfers.columns.quantity_shipped')}+ stockLocationId={sourceId || null}+ requireStockLocation/></CardContent></Card>diff --git a/spree/core/app/models/spree/variant.rb b/spree/core/app/models/spree/variant.rbindex bf5bc9486a..1a183e160d 100644--- a/spree/core/app/models/spree/variant.rb+++ b/spree/core/app/models/spree/variant.rb@@ -167,6 +167,27 @@ module Spreescope :backorderable, -> { left_joins(:stock_levels).where(Spree::StockLevel.table_name => { backorderable: true }) }scope :in_stock_or_backorderable, -> { in_stock.or(backorderable) }+ # Variants one warehouse could actually send: it holds a level for them+ # with something available on it. Written for the transfer form's picker,+ # which would otherwise offer SKUs the source has none of — and+ # `MarkInTransit` refuses those per line, once the van is supposedly+ # loaded and the merchant has moved on.+ #+ # Untracked variants are excluded on purpose, unlike `in_stock`: a+ # transfer moves counted units, and the ship guard would refuse them too.+ #+ # Takes a prefixed or a raw id — a ransackable scope decodes its own+ # argument, since the controller only decodes keys carrying a predicate+ # suffix.+ scope :available_at_stock_location, ->(stock_location) {+ levels = Spree::StockLevel.table_name+ location_id = Spree::PrefixedId.decode_prefixed_id(stock_location) || stock_location++ joins(:stock_levels).+ where(levels => { stock_location_id: location_id }).+ where("#{levels}.count_on_hand - #{levels}.allocated_count > ?", 0)+ }+scope :eligible, -> { all }# Variants whose *resolved* seller is the given one: their own column when@@ -287,7 +308,8 @@ module Spreedeleted_at product_id hs_code country_of_originminimum_order_quantity order_multiple purchase_unit units_per_cartoncarton_package_type_id carton_weight cartons_per_pallet]- self.whitelisted_ransackable_scopes = %i(product_name_or_sku_cont search_by_product_name_or_sku search)+ self.whitelisted_ransackable_scopes = %i(product_name_or_sku_cont search_by_product_name_or_sku search+ available_at_stock_location)def self.product_name_or_sku_cont(query)sanitized_query = ActiveRecord::Base.sanitize_sql_like(query.to_s.downcase.strip)diff --git a/spree/core/spec/models/spree/variant_spec.rb b/spree/core/spec/models/spree/variant_spec.rbindex 0a2170b062..c3f20c12c1 100644--- a/spree/core/spec/models/spree/variant_spec.rb+++ b/spree/core/spec/models/spree/variant_spec.rb@@ -249,6 +249,41 @@ describe Spree::Variant, type: :model doenddescribe 'scope' do+ describe '.available_at_stock_location' do+ let(:store) { Spree::Store.default }+ let(:source) { create(:stock_location, store: store, propagate_all_variants: false) }+ let(:elsewhere) { create(:stock_location, store: store, propagate_all_variants: false) }+ let(:stocked) { create(:variant) }+ let(:empty) { create(:variant) }+ let(:stocked_elsewhere) { create(:variant) }++ before do+ source.restock(stocked, 4)+ source.stock_level_or_create(empty)+ elsewhere.restock(stocked_elsewhere, 9)+ end++ it 'is the variants that warehouse could send, and no others' do+ available = Spree::Variant.available_at_stock_location(source.prefixed_id)++ expect(available).to include(stocked)+ expect(available).not_to include(empty, stocked_elsewhere)+ end++ # Ransack hands a scope whatever the client sent, and the controller only+ # decodes keys carrying a predicate suffix — so this one decodes its own.+ it 'takes a raw id as readily as a prefixed one' do+ expect(Spree::Variant.available_at_stock_location(source.id)).to include(stocked)+ end++ it 'drops a variant once its stock is promised to an order' do+ level = source.stock_level(stocked.id)+ level.update!(allocated_count: level.count_on_hand)++ expect(Spree::Variant.available_at_stock_location(source.prefixed_id)).not_to include(stocked)+ end+ end+describe '.eligible' doit 'returns every variant' doproduct_1 = create(:product)