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
Add pre-orders: sell a variant before it's in stock (#14249)
Damian Legawiec3d93898f8116
diff --git a/docs/plans/5.6-preorders.md b/docs/plans/5.6-preorders.mdnew file mode 100644index 0000000000..5e164d5e48--- /dev/null+++ b/docs/plans/5.6-preorders.md@@ -0,0 +1,140 @@+# Pre-orders++**Status:** Implemented — PR #14249 (pending merge)+**Target:** Spree 5.6+**Depends on:** none (composes with stock + publishing, but couples to neither)+**Author:** Damian (with Claude)+**Last updated:** 2026-07-01++## Summary++Let a merchant sell a variant **before it's in stock**, with a clear "ships by" promise to the customer. Pre-order is modeled the way an operator thinks about it: an **out-of-stock selling behavior** (alongside backorder), **not** a publishing/launch concept.++A variant gets a `preorderable` boolean, a `preorder_ships_at` datetime, and a `backorder_limit` integer. When flagged, the variant is labeled a pre-order (and the storefront shows a "Pre-order — ships by `<date>`" badge). **The cap is `backorder_limit`** — a universal oversell ceiling: empty means unlimited, a value bounds how many units may be sold beyond available stock. Because it caps *any* oversell, it also limits plain backorders (previously unbounded). Pre-order itself adds only the label and the ship-by promise — the tally reuses the existing backorder mechanic (`count_on_hand` runs negative down to `-backorder_limit`), no new allocation model.++It also composes with **channel publishing**: a product *scheduled to publish later* (future `published_at`) that has a pre-order variant is surfaced (and buyable) on the Store API **before** its publish date — the "coming soon, open for pre-order" case. The publish date is the launch (when it becomes a normal live product); the variant's `preorder_ships_at` is when it actually ships.++## Operator mental model (the design driver)++A merchant answers the customer's question — *"Can I buy it, and when will I get it?"* — with two independent switches:++1. **Visibility** (publishing): is it in my catalog? Draft / Active / Scheduled. Unchanged, and unrelated to pre-order.+2. **Out-of-stock behavior** (inventory): *Don't sell* / *Backorder* / **Pre-order (+ ships-by date)** — each with an optional **limit** (`backorder_limit`) on how far you'll oversell.++Pre-order is just **backorder with a delivery promise**. It works for every "buy now, ships later" case the merchant lumps together — new launch, restock of a live product, made-to-order — because none of them depend on a future publish date. (An earlier draft gated pre-order on a future `published_at`; that excluded the common live-restock case and conflated "hide until launch" with "take pre-orders." Decoupling fixes both.) Since pre-order *is* backorder-with-a-promise, the two share one oversell cap: `backorder_limit`.++## Key Decisions (do not deviate without discussion)++- **`preorderable` + `preorder_ships_at` + `backorder_limit` live on `Spree::Variant`** — variant is the SKU/buy boundary, matching Saleor/Medusa/Shopify. `backorder_limit` sits on the variant (not the per-location `StockItem`) matching Vendure's variant-level `outOfStockThreshold`; it also anticipates 6.0 moving `backorderable` itself onto `Spree::Variant`, so the two end up colocated.+- **`preorder?` is publishing-independent.** It reads only the variant flag + ship date, never `published_at`/`available_on`. So pre-order works on live products (restocks) exactly as on scheduled ones.+- **The cap is `backorder_limit`, and it's universal.** One integer bounds overselling for *both* backorder and pre-order: **empty = unlimited**, a value caps how many units may be sold beyond available stock (`count_on_hand` runs negative down to `-backorder_limit`, combined with any on-hand stock). This replaces the old "cap is stock / backorder is unbounded" model.+- **Pre-order (or backorder) is a purchasability source.** `purchasable?` is now `in_stock? || oversellable_now?`, where `oversellable_now?` is true when the variant is backorderable or a pre-order and still within its (possibly unlimited) `backorder_limit`. Enabling pre-order with an empty limit makes the variant buyable (unlimited), just like enabling backorder — you set a number only to cap it.+- **The tally reuses the backorder mechanic — no new allocation model.** Oversold units are backordered inventory units; `count_on_hand` running negative is the running count, and `process_backorders` fills them on restock. `Quantifier#can_supply?` enforces the `-backorder_limit` floor; `StockItem` lifts its non-negative guard, `StockLocation#fill_status` backorders the shortfall, and `StockReservations::Reserve` skips reservation for backorderable *or* pre-order variants — pre-order rides every backorder seam.+- **Pre-order composes with publishing in one direction.** A *scheduled* (future-published) product with a pre-order variant is pulled forward: visible on the Store API and buyable (the cart's publish gate is lifted for a pre-order variant). It does not re-couple the concept — only `Quantifier#can_supply?`, the storefront `available` scope, and the search index/filter consult `preorder?` to admit the coming-soon case.+- **The ship date is variant-level and channel-agnostic** — it reflects when *stock arrives*, a supply fact, not a per-channel marketing date.+- **Pre-order is a label + a promise.** `preorder?` is presentation: flagged, and either open-ended or before `preorder_ships_at`. Once the date passes, the variant is a normal product again.++## Design Details++### Data model++```ruby+add_column :spree_variants, :preorderable, :boolean # no default; nil ⇒ false+add_column :spree_variants, :preorder_ships_at, :datetime # the "ships by" promise; nil ⇒ open-ended+add_column :spree_variants, :backorder_limit, :integer # oversell cap; nil ⇒ unlimited+```++### Predicates++```ruby+# Spree::Variant — flagged, and not past its ships-by date+def preorder?+ !discontinued? && preorderable? && product.active? && !product.deleted? &&+ (preorder_ships_at.nil? || preorder_ships_at > Time.current)+end++def purchasable?+ in_stock? || oversellable_now?+end+# Can the variant be bought by overselling (backorder OR pre-order)?+# Unlimited when backorder_limit is nil; otherwise only while allowance remains.+def oversellable_now?+ return false unless backorderable? || preorder?+ backorder_limit.nil? || can_supply?(1)+end++# Spree::Product+def preorder?+ default_variant.preorder? || variants.any?(&:preorder?)+end+def preorder_ships_at # latest ships-by across pre-order variants, for one product-level promise+ [master, *variants].select(&:preorder?).filter_map(&:preorder_ships_at).max+end+```++### The oversell cap (`backorder_limit`)++`Quantifier#can_supply?` is the one place the ceiling is enforced:++```ruby+def can_supply?(required = 1)+ return false unless variant.available? || variant.preorder?+ return true unless variant.should_track_inventory?++ oversellable = backorderable? || variant.preorder?+ limit = variant.backorder_limit+ return true if oversellable && limit.nil? # empty ⇒ unlimited++ supplyable = if oversellable+ [available_stock - reserved_quantity + limit, 0].max # one clamp: signed on-hand + limit+ else+ total_on_hand # on-hand only (clamped ≥ 0)+ end+ supplyable >= required+end+```++The capped-oversell capacity is a single clamp — `[signed_on_hand + limit, 0].max` — so units already oversold (negative `count_on_hand`) eat into the limit. `StockItem#verify_count_on_hand?` lifts its non-negative guard when the variant is backorderable **or** a pre-order, so oversold units can persist; `process_backorders` fills them on restock (unchanged).++### "Coming soon" — pre-ordering a scheduled product++For a *live* product, pre-order needs nothing beyond the label (it's already visible and its stock is buyable). For a product *scheduled to publish later*, three seams admit it before its publish date:++- **`Quantifier#can_supply?`** — `return false unless variant.available? || variant.preorder?`, then the oversell logic above. Pre-order lifts the publish gate; `backorder_limit` still caps. (`AvailabilityValidator` delegates to `can_supply?`, so a sold-out pre-order is a quantity error, not "inactive".)+- **`Product.available(..., include_preorderable: true)`** — also admits future-published products that have an active pre-order variant (an `EXISTS` against `spree_variants` for `preorderable AND not-past-ships-by`). The Store API products controller passes `include_preorderable: true`, so the listing and the show endpoint surface coming-soon pre-orders.+- **Search** — the index carries a `preorder` flag (`product.preorder?`); the Meilisearch `system_filter_conditions` admits future-published docs when `preorder = true`. The DB provider searches within the pre-order-inclusive scope.++### Fulfillment++Oversold units (backorder or pre-order) flow through existing backorder fulfillment: `StockLocation#fill_status` turns the shortfall into backordered inventory units (for backorderable *or* pre-order variants), `count_on_hand` runs negative at shipment finalize, and `process_backorders` fills the backordered units when stock is added. `StockReservations::Reserve` exempts pre-orders the same way it exempts backorderable stock (the cap lives in `can_supply?`, not in reservations). Nothing else special on the cart or checkout path; payment is captured as usual.++### API surface (read/write symmetry)++- Store `ProductSerializer`: `preorder` + `preorder_ships_at` (latest across pre-order variants). Store `VariantSerializer`: `preorder` + `preorder_ships_at` (only while a pre-order). `LineItemSerializer`: `preorder` + `preorder_ships_at`. The store surface does **not** expose the raw `backorder_limit` (it's back-office); customer-facing buyability is already reflected by `purchasable`/`in_stock`.+- Admin `VariantSerializer`: raw `preorderable` + `preorder_ships_at` + `backorder_limit`. Admin API (`products#permitted_params` → `variants:`) and `Spree::PermittedAttributes.variant_attributes` accept all three.++### Admin UIs++- **Legacy Rails admin** — "Available for pre-order" checkbox + "Ships by" date + "Backorder limit" number in the variant inventory form, beside "Track inventory".+- **React dashboard** — a Switch + a `StoreDatePicker` ("Ships by", shown when the toggle is on) + a "Backorder limit" number input (always shown; placeholder "Unlimited") in the `VariantEditSheet` "Availability" section.++## Migration Path++1. Ship the three additive, nullable columns. No backfill.+2. Ship predicates + serializers + admin write paths + both UIs (inert until a variant is flagged; `backorder_limit` inert until an oversell path is enabled).+3. No data transformation / rake task.++## Constraints on Current Work++- `Variant#preorder?` relaxes **only the publish date** — it still gates on product `active?`/not-deleted and variant not-discontinued, so an archived/draft/discontinued product never becomes supplyable via pre-order. It must not read `available_on`/`published_at` directly. The publishing interaction lives at the edges (`can_supply?`, the `available` scope, the search filter), which consult `preorder?` to admit the coming-soon case.+- **`backorder_limit` is the single oversell ceiling for both backorder and pre-order.** Enforce it only in `Quantifier#can_supply?` (and thus `AvailabilityValidator`); `purchasable?`/`oversellable_now?` reuse `can_supply?` rather than re-deriving the cap. `nil` must always mean unlimited.++## Open Questions++- A future **"Don't sell / Backorder / Pre-order" single selector** in the inventory UI. Once 6.0 moves `backorderable` from `StockItem` onto `Spree::Variant`, `backorderable` + `backorder_limit` + `preorderable` all live on the variant and a unified control becomes natural.+- Deposits / partial payment for pre-orders (cf. Shopify SellingPlans) — out of scope; pay in full at checkout.++## References++- Prior art: Saleor (`ProductVariant.preorder` with `endDate` on the variant + `globalThreshold`/per-channel `preorderThreshold`), Shopify (oversell `inventoryPolicy` `DENY`/`CONTINUE` — binary/unbounded — plus SellingPlan `PRE_ORDER` for the promise), Medusa (`allow_backorder` boolean — unbounded — + a variant-linked `available_date`), Vendure (variant-level `outOfStockThreshold`, negative = oversell floor). All keep the pre-order/ship date on the variant (or selling plan), **never** tied to channel publishing — which this design matches.+- **The oversell cap** follows Saleor/Vendure (both cap; Shopify/Medusa/legacy-Spree are binary/unbounded). Spree's `backorder_limit` is Vendure's variant-level threshold expressed as a positive "units beyond stock" number, and — matching Saleor — it makes the pre-order flag itself a purchasability source (bounded by the limit).diff --git a/packages/admin-sdk/.changeset/preorder-fields.md b/packages/admin-sdk/.changeset/preorder-fields.mdnew file mode 100644index 0000000000..0142e3a9c3--- /dev/null+++ b/packages/admin-sdk/.changeset/preorder-fields.md@@ -0,0 +1,5 @@+---+"@spree/admin-sdk": minor+---++Add pre-order management to the Admin API. `Variant` now exposes the editable `preorderable` flag, `preorder_ships_at` (the "ships by" date), and `backorder_limit` (the universal oversell cap — units sellable beyond available stock as backorders or pre-orders; `null` = unlimited), alongside the computed `preorder` state; `Product` and `LineItem` gain `preorder` + `preorder_ships_at`. `ProductVariantInput`, `VariantCreateParams`, and `VariantUpdateParams` accept `preorderable`, `preorder_ships_at`, and `backorder_limit`, so a variant can be flagged for pre-order and capped in a single write.diff --git a/packages/admin-sdk/src/params.ts b/packages/admin-sdk/src/params.tsindex 15c066befd..010bf30c2e 100644--- a/packages/admin-sdk/src/params.ts+++ b/packages/admin-sdk/src/params.ts@@ -366,6 +366,17 @@ export interface ProductVariantInput {weight_unit?: stringdimensions_unit?: stringtrack_inventory?: boolean+ /** Sell this variant before it's in stock ("Pre-order"). This adds the+ * pre-order label + ships-by promise; the cap comes from `backorder_limit`,+ * an incoming stock count, or backorder. */+ preorderable?: boolean+ /** The "ships by" date shown to customers while the variant is a pre-order+ * (ISO 8601). Once it passes, the variant is no longer treated as a+ * pre-order. Null clears it. */+ preorder_ships_at?: string | null+ /** Maximum units sellable beyond available stock — caps backorders and+ * pre-orders. Null = unlimited. */+ backorder_limit?: number | nulltax_category_id?: stringposition?: numberbarcode?: string@@ -456,6 +467,9 @@ export interface VariantCreateParams {weight_unit?: stringdimensions_unit?: stringtrack_inventory?: boolean+ preorderable?: boolean+ preorder_ships_at?: string | null+ backorder_limit?: number | nulltax_category_id?: stringposition?: numberbarcode?: string@@ -484,6 +498,9 @@ export interface VariantUpdateParams {weight_unit?: stringdimensions_unit?: stringtrack_inventory?: boolean+ preorderable?: boolean+ preorder_ships_at?: string | null+ backorder_limit?: number | nulltax_category_id?: stringposition?: numberbarcode?: stringdiff --git a/packages/admin-sdk/src/types/generated/LineItem.ts b/packages/admin-sdk/src/types/generated/LineItem.tsindex b8649b5514..5b97c498e5 100644--- a/packages/admin-sdk/src/types/generated/LineItem.ts+++ b/packages/admin-sdk/src/types/generated/LineItem.ts@@ -1,4 +1,4 @@-// Typelizer digest 5c0fdc4c5206fbfac144e7ed4197f811+// Typelizer digest 69de5e05b8466098dbd80b2b389511cf//// DO NOT MODIFY: This file was automatically generated by Typelizer.import type {OptionValue, DigitalLink, Variant, TaxCategory, Adjustment} from '@/types'@@ -6,6 +6,8 @@ import type {OptionValue, DigitalLink, Variant, TaxCategory, Adjustment} from '@interface LineItem {id: string;variant_id: string;+ preorder: boolean;+ preorder_ships_at: string | null;quantity: number;currency: string;name: string;diff --git a/packages/admin-sdk/src/types/generated/Product.ts b/packages/admin-sdk/src/types/generated/Product.tsindex 4f35a3c96f..9ee24ccf74 100644--- a/packages/admin-sdk/src/types/generated/Product.ts+++ b/packages/admin-sdk/src/types/generated/Product.ts@@ -1,4 +1,4 @@-// Typelizer digest 47443a1c7df7c3bb43f46bd5e4ba940a+// Typelizer digest d8c7e2d1a99bf854b06e5868a89fb592//// DO NOT MODIFY: This file was automatically generated by Typelizer.import type {Price, PriceHistory, Media, Variant, OptionType, OptionValue, Category, CustomField, ProductPublication, Channel} from '@/types'@@ -12,7 +12,9 @@ interface Product {meta_keywords: string | null;variant_count: number;available_on: string | null;+ preorder_ships_at: string | null;purchasable: boolean;+ preorder: boolean;in_stock: boolean;backorderable: boolean;available: boolean;diff --git a/packages/admin-sdk/src/types/generated/Variant.ts b/packages/admin-sdk/src/types/generated/Variant.tsindex 7dccacabb1..2c2d96942e 100644--- a/packages/admin-sdk/src/types/generated/Variant.ts+++ b/packages/admin-sdk/src/types/generated/Variant.ts@@ -1,4 +1,4 @@-// Typelizer digest 692d624fd37ee24aa94b68337850f457+// Typelizer digest bf292878d4138bfabe39f056fe2dc9d9//// DO NOT MODIFY: This file was automatically generated by Typelizer.import type {Price, PriceHistory, Media, OptionValue, CustomField, StockItem} from '@/types'@@ -10,10 +10,12 @@ interface Variant {options_text: string;track_inventory: boolean;media_count: number;+ preorder_ships_at: string | null;thumbnail_url: string | null;purchasable: boolean;in_stock: boolean;backorderable: boolean;+ preorder: boolean;weight: number | null;height: number | null;width: number | null;@@ -32,9 +34,11 @@ interface Variant {barcode: string | null;weight_unit: string | null;dimensions_unit: string | null;+ backorder_limit: number | null;deleted_at: string | null;created_at: string;updated_at: string;+ preorderable: boolean;tax_category_id: string | null;available_stock: number | null;reserved_quantity: number;diff --git a/packages/dashboard/src/components/spree/products/variant-edit-sheet.tsx b/packages/dashboard/src/components/spree/products/variant-edit-sheet.tsxindex 59bae0c272..1b2452835e 100644--- a/packages/dashboard/src/components/spree/products/variant-edit-sheet.tsx+++ b/packages/dashboard/src/components/spree/products/variant-edit-sheet.tsx@@ -1,3 +1,4 @@+import { StoreDatePicker } from '@spree/dashboard-core'import {Button,Field,@@ -14,6 +15,7 @@ import {SheetFooter,SheetHeader,SheetTitle,+ Switch,} from '@spree/dashboard-ui'import { useEffect, useRef } from 'react'import { Controller, type UseFormReturn } from 'react-hook-form'@@ -266,6 +268,91 @@ export function VariantEditSheet({ form, variantIndex, open, onOpenChange }: Pro</div></Section>+ <Section title={t('admin.products.variants.sheet.availability')}>+ <Field>+ <div className="flex items-start justify-between gap-4">+ <div className="flex flex-col">+ <FieldLabel+ htmlFor={`variant-${variantIndex}-preorderable`}+ className="cursor-pointer"+ >+ {t('admin.fields.variant.preorderable.label')}+ </FieldLabel>+ <span className="text-xs text-muted-foreground">+ {t('admin.fields.variant.preorderable.help')}+ </span>+ </div>+ <Controller+ name={`variants.${variantIndex}.preorderable`}+ control={form.control}+ render={({ field }) => (+ <Switch+ id={`variant-${variantIndex}-preorderable`}+ checked={!!field.value}+ onCheckedChange={field.onChange}+ />+ )}+ />+ </div>+ </Field>++ {variant.preorderable && (+ <Field>+ <FieldLabel>{t('admin.fields.variant.preorder_ships_at.label')}</FieldLabel>+ <Controller+ control={form.control}+ name={`variants.${variantIndex}.preorder_ships_at`}+ render={({ field }) => (+ <StoreDatePicker+ value={field.value ?? null}+ onChange={(next) => field.onChange(next ?? null)}+ placeholder={t('admin.fields.variant.preorder_ships_at.placeholder')}+ includeTime+ inline+ />+ )}+ />+ <span className="text-xs text-muted-foreground">+ {t('admin.fields.variant.preorder_ships_at.help')}+ </span>+ </Field>+ )}++ <Field>+ <FieldLabel htmlFor={`variant-${variantIndex}-backorder-limit`}>+ {t('admin.fields.variant.backorder_limit.label')}+ </FieldLabel>+ <Controller+ control={form.control}+ name={`variants.${variantIndex}.backorder_limit`}+ render={({ field }) => (+ <Input+ id={`variant-${variantIndex}-backorder-limit`}+ type="number"+ min="0"+ step="1"+ placeholder={t('admin.fields.variant.backorder_limit.placeholder')}+ value={field.value ?? ''}+ onChange={(event) => {+ const parsed = Number(event.target.value)+ field.onChange(+ event.target.value === '' || Number.isNaN(parsed)+ ? null+ : Math.max(0, Math.trunc(parsed)),+ )+ }}+ />+ )}+ />+ <span className="text-xs text-muted-foreground">+ {t('admin.fields.variant.backorder_limit.help')}+ </span>+ <FieldError+ errors={[form.formState.errors.variants?.[variantIndex]?.backorder_limit]}+ />+ </Field>+ </Section>+{hasTaxCategories && (<Section title={t('admin.fields.tax.label')}><Field>diff --git a/packages/dashboard/src/locales/ar.json b/packages/dashboard/src/locales/ar.jsonindex 4283fba8fe..875358fe69 100644--- a/packages/dashboard/src/locales/ar.json+++ b/packages/dashboard/src/locales/ar.json@@ -523,6 +523,20 @@},"dimensions_unit": {"label": "الوحدة"+ },+ "preorderable": {+ "label": "متاح للطلب المسبق",+ "help": "بِع هذا الخيار قبل توفره في المخزون. حدِّد العدد عبر حد الطلبات المتأخرة، أو أدخل المخزون الوارد ككمية، أو اتركه فارغًا لعدد غير محدود."+ },+ "preorder_ships_at": {+ "label": "الشحن بحلول",+ "placeholder": "اختر تاريخًا",+ "help": "موعد شحنك المتوقع للطلبات المسبقة. يظهر للعملاء كوعد بالتسليم؛ وينتهي الطلب المسبق بمجرد مرور هذا التاريخ."+ },+ "backorder_limit": {+ "label": "حد الطلبات المتأخرة",+ "placeholder": "غير محدود",+ "help": "الحد الأقصى لعدد الوحدات المباعة بما يتجاوز المخزون المتاح — يحدّ الطلبات المتأخرة والطلبات المسبقة. اتركه فارغًا لعدد غير محدود."}},"api_key": {@@ -2139,6 +2153,7 @@"keep": "احتفظ بالكل","sheet": {"identity": "هوية",+ "availability": "التوفر","tax_category_placeholder": "ترث من المنتج"},"errors": {diff --git a/packages/dashboard/src/locales/de.json b/packages/dashboard/src/locales/de.jsonindex 911ab820a6..ea112f03d2 100644--- a/packages/dashboard/src/locales/de.json+++ b/packages/dashboard/src/locales/de.json@@ -475,6 +475,20 @@},"dimensions_unit": {"label": "Einheit"+ },+ "preorderable": {+ "label": "Für Vorbestellung verfügbar",+ "help": "Verkaufe diese Variante, bevor sie auf Lager ist. Begrenze die Menge mit dem Nachbestellungslimit, gib eingehenden Bestand als Lagerbestand ein oder lass es für unbegrenzt leer."+ },+ "preorder_ships_at": {+ "label": "Versand bis",+ "placeholder": "Datum wählen",+ "help": "Wann du Vorbestellungen voraussichtlich versendest. Wird Kunden als Lieferversprechen angezeigt; die Vorbestellung endet, sobald dieses Datum verstreicht."+ },+ "backorder_limit": {+ "label": "Nachbestellungslimit",+ "placeholder": "Unbegrenzt",+ "help": "Maximale Anzahl an Einheiten, die über den verfügbaren Bestand hinaus verkauft werden — begrenzt Nachbestellungen und Vorbestellungen. Leer lassen für unbegrenzt."}},"api_key": {@@ -2091,6 +2105,7 @@"keep": "Alle behalten","sheet": {"identity": "Identität",+ "availability": "Verfügbarkeit","tax_category_placeholder": "Vom Produkt übernehmen"},"errors": {diff --git a/packages/dashboard/src/locales/en.json b/packages/dashboard/src/locales/en.jsonindex dfcd61ff32..526a17ef59 100644--- a/packages/dashboard/src/locales/en.json+++ b/packages/dashboard/src/locales/en.json@@ -526,6 +526,20 @@},"dimensions_unit": {"label": "Unit"+ },+ "preorderable": {+ "label": "Available for pre-order",+ "help": "Sell this variant before it's in stock. Cap how many you'll take with the backorder limit, enter incoming stock as the count, or leave it blank for unlimited."+ },+ "preorder_ships_at": {+ "label": "Ships by",+ "placeholder": "Select a date",+ "help": "When you expect to ship pre-orders. Shown to customers as the delivery promise; the pre-order ends once this date passes."+ },+ "backorder_limit": {+ "label": "Backorder limit",+ "placeholder": "Unlimited",+ "help": "Maximum number of units sold beyond available stock — caps backorders and pre-orders. Leave blank for unlimited."}},"api_key": {@@ -2139,6 +2153,7 @@"keep": "Keep all","sheet": {"identity": "Identity",+ "availability": "Availability","tax_category_placeholder": "Inherit from product"},"errors": {diff --git a/packages/dashboard/src/locales/fr.json b/packages/dashboard/src/locales/fr.jsonindex 67eeb06857..043f60407b 100644--- a/packages/dashboard/src/locales/fr.json+++ b/packages/dashboard/src/locales/fr.json@@ -475,6 +475,20 @@},"dimensions_unit": {"label": "Unité"+ },+ "preorderable": {+ "label": "Disponible en précommande",+ "help": "Vendez cette variante avant qu'elle soit en stock. Plafonnez les quantités avec la limite de réassort, saisissez le stock à recevoir comme quantité, ou laissez vide pour un nombre illimité."+ },+ "preorder_ships_at": {+ "label": "Expédié avant le",+ "placeholder": "Choisir une date",+ "help": "Date à laquelle vous prévoyez d'expédier les précommandes. Affichée aux clients comme promesse de livraison ; la précommande se termine une fois cette date passée."+ },+ "backorder_limit": {+ "label": "Limite de réassort",+ "placeholder": "Illimité",+ "help": "Nombre maximum d'unités vendues au-delà du stock disponible — plafonne les réassorts et les précommandes. Laissez vide pour illimité."}},"api_key": {@@ -2091,6 +2105,7 @@"keep": "Tout conserver","sheet": {"identity": "Identité",+ "availability": "Disponibilité","tax_category_placeholder": "Hériter du produit"},"errors": {diff --git a/packages/dashboard/src/locales/pl.json b/packages/dashboard/src/locales/pl.jsonindex a038d5fe0f..82722cdf67 100644--- a/packages/dashboard/src/locales/pl.json+++ b/packages/dashboard/src/locales/pl.json@@ -475,6 +475,20 @@},"dimensions_unit": {"label": "Jednostka"+ },+ "preorderable": {+ "label": "Dostępne w przedsprzedaży",+ "help": "Sprzedawaj ten wariant, zanim trafi do magazynu. Ogranicz liczbę limitem zamówień oczekujących, wpisz przychodzący stan jako ilość lub pozostaw puste dla nieograniczonej liczby."+ },+ "preorder_ships_at": {+ "label": "Wysyłka do",+ "placeholder": "Wybierz datę",+ "help": "Kiedy planujesz wysłać zamówienia przedpremierowe. Pokazywane klientom jako obietnica dostawy; przedsprzedaż kończy się po upływie tej daty."+ },+ "backorder_limit": {+ "label": "Limit zamówień oczekujących",+ "placeholder": "Bez limitu",+ "help": "Maksymalna liczba jednostek sprzedanych ponad dostępny stan — ogranicza zamówienia oczekujące i przedsprzedaż. Pozostaw puste dla braku limitu."}},"api_key": {@@ -2121,6 +2135,7 @@"keep": "Zachowaj wszystkie","sheet": {"identity": "Tożsamość",+ "availability": "Dostępność","tax_category_placeholder": "Dziedzicz z produktu"},"errors": {diff --git a/packages/dashboard/src/locales/zh-CN.json b/packages/dashboard/src/locales/zh-CN.jsonindex 02512fd796..22c20eebb4 100644--- a/packages/dashboard/src/locales/zh-CN.json+++ b/packages/dashboard/src/locales/zh-CN.json@@ -523,6 +523,20 @@},"dimensions_unit": {"label": "单位"+ },+ "preorderable": {+ "label": "可预购",+ "help": "在有货之前销售此变体。用缺货下单上限来限制数量,将到货数量填入库存,或留空表示无限量。"+ },+ "preorder_ships_at": {+ "label": "发货时间",+ "placeholder": "选择日期",+ "help": "你预计发出预购订单的时间。作为交付承诺向顾客展示;该日期过后预购结束。"+ },+ "backorder_limit": {+ "label": "缺货下单上限",+ "placeholder": "无限量",+ "help": "超出可用库存销售的最大数量——用于限制缺货下单和预购。留空表示无限量。"}},"api_key": {@@ -2139,6 +2153,7 @@"keep": "全部保留","sheet": {"identity": "标识",+ "availability": "可用性","tax_category_placeholder": "继承自商品"},"errors": {diff --git a/packages/dashboard/src/routes/_authenticated/$storeId/products/$productId.tsx b/packages/dashboard/src/routes/_authenticated/$storeId/products/$productId.tsxindex 3c83637edd..ab35e6b4a3 100644--- a/packages/dashboard/src/routes/_authenticated/$storeId/products/$productId.tsx+++ b/packages/dashboard/src/routes/_authenticated/$storeId/products/$productId.tsx@@ -74,6 +74,9 @@ function variantToFormValues(variant: Variant, position: number): VariantFormValweight_unit: variant.weight_unit ?? null,dimensions_unit: variant.dimensions_unit ?? null,track_inventory: variant.track_inventory,+ preorderable: variant.preorderable ?? false,+ preorder_ships_at: variant.preorder_ships_at ?? null,+ backorder_limit: variant.backorder_limit ?? null,tax_category_id: variant.tax_category_id ?? null,prices: (variant.prices ?? []).filter((p) => p.currency != null)@@ -184,6 +187,9 @@ export function variantToWirePayload(v: VariantFormValues, index: number) {}if (v.id) payload.id = v.idif (v.track_inventory != null) payload.track_inventory = v.track_inventory+ if (v.preorderable != null) payload.preorderable = v.preorderable+ if (v.preorder_ships_at !== undefined) payload.preorder_ships_at = v.preorder_ships_at+ if (v.backorder_limit !== undefined) payload.backorder_limit = v.backorder_limit// Always send `prices` when the form tracks it — including `[]`. The// backend's `Spree::Variant#prices=` treats an empty array as "clear all// base prices"; omitting it would otherwise leave the old amounts indiff --git a/packages/dashboard/src/routes/_authenticated/$storeId/products/new.tsx b/packages/dashboard/src/routes/_authenticated/$storeId/products/new.tsxindex ba05993e1f..c85095bca0 100644--- a/packages/dashboard/src/routes/_authenticated/$storeId/products/new.tsx+++ b/packages/dashboard/src/routes/_authenticated/$storeId/products/new.tsx@@ -110,6 +110,9 @@ function NewProductPage() {v.dimensions_unit != null ||v.tax_category_id != null ||v.track_inventory === false ||+ v.preorderable === true ||+ v.preorder_ships_at != null ||+ v.backorder_limit != null ||(v.stock_items?.length ?? 0) > 0if (hasVariantOnlyData) {// eslint-disable-next-line @typescript-eslint/no-explicit-anydiff --git a/packages/dashboard/src/schemas/product.ts b/packages/dashboard/src/schemas/product.tsindex 473dfa73ad..ea76d8f8ed 100644--- a/packages/dashboard/src/schemas/product.ts+++ b/packages/dashboard/src/schemas/product.ts@@ -46,6 +46,9 @@ export const variantFormSchema = z.object({weight_unit: z.string().nullable().optional(),dimensions_unit: z.string().nullable().optional(),track_inventory: z.boolean().optional(),+ preorderable: z.boolean().optional(),+ preorder_ships_at: z.string().nullable().optional(),+ backorder_limit: z.coerce.number().int().nonnegative().nullable().optional(),tax_category_id: z.string().nullable().optional(),prices: z.array(variantPriceFormSchema).optional(),stock_items: z.array(stockItemFormSchema).optional(),@@ -196,6 +199,9 @@ export function isPlaceholderDefaultVariant(v: VariantFormValues): boolean {v.weight_unit == null &&v.dimensions_unit == null &&v.tax_category_id == null &&+ v.preorderable !== true &&+ v.preorder_ships_at == null &&+ v.backorder_limit == null &&// `track_inventory` defaults to `true` in `newProductFormDefaults`. Only// count an explicit `false` (merchant toggled it off) as non-default.v.track_inventory !== falsediff --git a/packages/sdk/.changeset/preorder-fields.md b/packages/sdk/.changeset/preorder-fields.mdnew file mode 100644index 0000000000..7397869bad--- /dev/null+++ b/packages/sdk/.changeset/preorder-fields.md@@ -0,0 +1,5 @@+---+"@spree/sdk": minor+---++Surface pre-order status on the Store API types. `Variant`, `Product`, and `LineItem` now expose `preorder` (whether the item is currently sold as a pre-order) and `preorder_ships_at` (the customer-facing "ships by" promise, `null` unless it's a live pre-order), so storefronts can render a "Pre-order — ships by …" badge. Both fields are included in the generated Zod schemas.diff --git a/packages/sdk/src/types/generated/LineItem.ts b/packages/sdk/src/types/generated/LineItem.tsindex 9abcfd0640..b842ee3098 100644--- a/packages/sdk/src/types/generated/LineItem.ts+++ b/packages/sdk/src/types/generated/LineItem.ts@@ -1,4 +1,4 @@-// Typelizer digest df075d3eedc9748ec9650add24c2b6a1+// Typelizer digest 0e77b4c357712521007c53211156cde3//// DO NOT MODIFY: This file was automatically generated by Typelizer.import type {OptionValue, DigitalLink} from '@/types'@@ -6,6 +6,8 @@ import type {OptionValue, DigitalLink} from '@/types'interface LineItem {id: string;variant_id: string;+ preorder: boolean;+ preorder_ships_at: string | null;quantity: number;currency: string;name: string;diff --git a/packages/sdk/src/types/generated/Product.ts b/packages/sdk/src/types/generated/Product.tsindex 03c3a6f049..a00c757737 100644--- a/packages/sdk/src/types/generated/Product.ts+++ b/packages/sdk/src/types/generated/Product.ts@@ -1,4 +1,4 @@-// Typelizer digest ef41571c2a6ddef3302e99ef8d160d96+// Typelizer digest a1b4f36ab287f3abedd4060df2a63032//// DO NOT MODIFY: This file was automatically generated by Typelizer.import type {Price, PriceHistory, Media, Variant, OptionType, OptionValue, Category, CustomField} from '@/types'@@ -12,7 +12,9 @@ interface Product {meta_keywords: string | null;variant_count: number;available_on: string | null;+ preorder_ships_at: string | null;purchasable: boolean;+ preorder: boolean;in_stock: boolean;backorderable: boolean;available: boolean;diff --git a/packages/sdk/src/types/generated/Variant.ts b/packages/sdk/src/types/generated/Variant.tsindex 1e67c4f036..7fa215597d 100644--- a/packages/sdk/src/types/generated/Variant.ts+++ b/packages/sdk/src/types/generated/Variant.ts@@ -1,4 +1,4 @@-// Typelizer digest e17442eb4fdbfeeb5bff74dc40dace30+// Typelizer digest 60f48e98014c8bb17ecd142b8f9ae110//// DO NOT MODIFY: This file was automatically generated by Typelizer.import type {Price, PriceHistory, Media, OptionValue, CustomField} from '@/types'@@ -10,10 +10,12 @@ interface Variant {options_text: string;track_inventory: boolean;media_count: number;+ preorder_ships_at: string | null;thumbnail_url: string | null;purchasable: boolean;in_stock: boolean;backorderable: boolean;+ preorder: boolean;weight: number | null;height: number | null;width: number | null;diff --git a/packages/sdk/src/zod/generated/LineItem.ts b/packages/sdk/src/zod/generated/LineItem.tsindex e6b45a301d..0a68ed85c0 100644--- a/packages/sdk/src/zod/generated/LineItem.ts+++ b/packages/sdk/src/zod/generated/LineItem.ts@@ -6,6 +6,8 @@ import { OptionValueSchema } from './OptionValue';export const LineItemSchema = z.object({id: z.string(),variant_id: z.string(),+ preorder: z.boolean(),+ preorder_ships_at: z.string().nullable(),quantity: z.number(),currency: z.string(),name: z.string(),diff --git a/packages/sdk/src/zod/generated/Product.ts b/packages/sdk/src/zod/generated/Product.tsindex a4326f9a92..ad6874108c 100644--- a/packages/sdk/src/zod/generated/Product.ts+++ b/packages/sdk/src/zod/generated/Product.ts@@ -18,7 +18,9 @@ export const ProductSchema = z.object({meta_keywords: z.string().nullable(),variant_count: z.number(),available_on: z.string().nullable(),+ preorder_ships_at: z.string().nullable(),purchasable: z.boolean(),+ preorder: z.boolean(),in_stock: z.boolean(),backorderable: z.boolean(),available: z.boolean(),diff --git a/packages/sdk/src/zod/generated/Variant.ts b/packages/sdk/src/zod/generated/Variant.tsindex 40d11ae725..99ecab5d34 100644--- a/packages/sdk/src/zod/generated/Variant.ts+++ b/packages/sdk/src/zod/generated/Variant.ts@@ -13,10 +13,12 @@ export const VariantSchema = z.object({options_text: z.string(),track_inventory: z.boolean(),media_count: z.number(),+ preorder_ships_at: z.string().nullable(),thumbnail_url: z.string().nullable(),purchasable: z.boolean(),in_stock: z.boolean(),backorderable: z.boolean(),+ preorder: z.boolean(),weight: z.number().nullable(),height: z.number().nullable(),width: z.number().nullable(),diff --git a/spree/admin/app/controllers/spree/admin/base_controller.rb b/spree/admin/app/controllers/spree/admin/base_controller.rbindex 6f6151ee69..d531615cc1 100644--- a/spree/admin/app/controllers/spree/admin/base_controller.rb+++ b/spree/admin/app/controllers/spree/admin/base_controller.rb@@ -120,14 +120,18 @@ module Spreedetect { |locale| supported_admin_locale?(locale) } || default_localeend+ # The store's timezone resolved to an +ActiveSupport::TimeZone+, falling+ # back to +Time.zone+ when the preference holds an unknown zone name.+ # @return [ActiveSupport::TimeZone]def current_timezone- @current_timezone ||= current_store.preferred_timezone+ @current_timezone ||= ActiveSupport::TimeZone[current_store.preferred_timezone] || Time.zoneend+ helper_method :current_timezone# datetime-local inputs submit values without timezone information. Interpret# them in the store's timezone so they match what the admin sees in the form.def parse_datetime_in_store_timezone(attrs, *fields)- zone = ActiveSupport::TimeZone[current_timezone] || Time.zone+ zone = current_timezonefields.each do |field|value = attrs[field]diff --git a/spree/admin/app/controllers/spree/admin/variants_controller.rb b/spree/admin/app/controllers/spree/admin/variants_controller.rbindex e1cdf3e040..3185b8abc2 100644--- a/spree/admin/app/controllers/spree/admin/variants_controller.rb+++ b/spree/admin/app/controllers/spree/admin/variants_controller.rb@@ -96,7 +96,9 @@ module Spreeenddef permitted_resource_params- params.require(:variant).permit(permitted_variant_attributes)+ attrs = params.require(:variant).permit(permitted_variant_attributes)+ parse_datetime_in_store_timezone(attrs, :preorder_ships_at)+ attrsendendenddiff --git a/spree/admin/app/views/spree/admin/products/form/_publishing.html.erb b/spree/admin/app/views/spree/admin/products/form/_publishing.html.erbindex 733f2a18b5..4e920c1597 100644--- a/spree/admin/app/views/spree/admin/products/form/_publishing.html.erb+++ b/spree/admin/app/views/spree/admin/products/form/_publishing.html.erb@@ -13,9 +13,8 @@%><%- store_timezone = ActiveSupport::TimeZone[current_store.preferred_timezone] || Time.zone- to_store_local = ->(value) { value&.in_time_zone(store_timezone)&.strftime('%Y-%m-%dT%H:%M') }- tz_help = Spree.t('admin.datetime_field_timezone_help', zone: store_timezone.name)+ to_store_local = ->(value) { value&.in_time_zone(current_timezone)&.strftime('%Y-%m-%dT%H:%M') }+ tz_help = Spree.t('admin.datetime_field_timezone_help', zone: current_timezone.name)store_channels = current_store.channels.order(:name).to_apublications_by_channel = @product.product_publications.includes(:channel).index_by(&:channel_id)can_manage_publications = can?(:manage, Spree::ProductPublication)diff --git a/spree/admin/app/views/spree/admin/promotions/form/_settings.html.erb b/spree/admin/app/views/spree/admin/promotions/form/_settings.html.erbindex 15a7f0641e..b2c2dfb301 100644--- a/spree/admin/app/views/spree/admin/promotions/form/_settings.html.erb+++ b/spree/admin/app/views/spree/admin/promotions/form/_settings.html.erb@@ -4,15 +4,14 @@<%# datetime-local inputs have no timezone; render values in the store's timezone so admins see and submit values in the store's local time. %><%- store_timezone = ActiveSupport::TimeZone[current_store.preferred_timezone] || Time.zone- to_store_local = ->(value) { value&.in_time_zone(store_timezone)&.strftime('%Y-%m-%dT%H:%M') }+ to_store_local = ->(value) { value&.in_time_zone(current_timezone)&.strftime('%Y-%m-%dT%H:%M') }starts_at_local = to_store_local.call(@promotion.starts_at)expires_at_local = to_store_local.call(@promotion.expires_at)- tz_help = Spree.t('admin.datetime_field_timezone_help', zone: store_timezone.name)+ tz_help = Spree.t('admin.datetime_field_timezone_help', zone: current_timezone.name)%><%= f.spree_datetime_field :starts_at, value: starts_at_local, help: tz_help %><%= f.spree_datetime_field :expires_at,value: expires_at_local,- help: Spree.t('admin.promotions.expires_at_help', zone: store_timezone.name) %>+ help: Spree.t('admin.promotions.expires_at_help', zone: current_timezone.name) %>diff --git a/spree/admin/app/views/spree/admin/reports/new.html.erb b/spree/admin/app/views/spree/admin/reports/new.html.erbindex e44ee694fd..76c674884c 100644--- a/spree/admin/app/views/spree/admin/reports/new.html.erb+++ b/spree/admin/app/views/spree/admin/reports/new.html.erb@@ -28,8 +28,8 @@<div class="flex gap-2"><%= render 'spree/admin/shared/calendar_range_picker',- date_from_value: params[:date_from] || 1.month.ago.in_time_zone(current_store.preferred_timezone).beginning_of_day,- date_to_value: params[:date_to] || Time.current.in_time_zone(current_store.preferred_timezone).end_of_day %>+ date_from_value: params[:date_from] || 1.month.ago.in_time_zone(current_timezone).beginning_of_day,+ date_to_value: params[:date_to] || Time.current.in_time_zone(current_timezone).end_of_day %><div class="form-group"><%= select_tag :currency,diff --git a/spree/admin/app/views/spree/admin/variants/form/_inventory.html.erb b/spree/admin/app/views/spree/admin/variants/form/_inventory.html.erbindex 87fa3585e4..0e06daf882 100644--- a/spree/admin/app/views/spree/admin/variants/form/_inventory.html.erb+++ b/spree/admin/app/views/spree/admin/variants/form/_inventory.html.erb@@ -7,6 +7,23 @@<div class="card-body p-0" data-controller="reveal" data-reveal-hidden-class="hidden!"><div class="p-3"><%= f.spree_check_box :track_inventory, data: { action: 'change->reveal#toggle' } %>+ <div class="mt-2">+ <%= f.spree_check_box :preorderable, label: Spree.t('admin.variants_form.preorderable_label') %>+ <small class="text-muted text-xs d-block"><%= Spree.t('admin.variants_form.preorderable_hint') %></small>+ </div>+ <div class="mt-2">+ <%# datetime-local inputs have no timezone; render in the store's timezone so admins see and submit store-local times (parsed back in VariantsController#permitted_resource_params). %>+ <% preorder_ships_at_local = f.object.preorder_ships_at&.in_time_zone(current_timezone)&.strftime('%Y-%m-%dT%H:%M') %>+ <%= f.spree_datetime_field :preorder_ships_at,+ value: preorder_ships_at_local,+ label: Spree.t('admin.variants_form.preorder_ships_at_label'),+ help: "#{Spree.t('admin.variants_form.preorder_ships_at_hint')} #{Spree.t('admin.datetime_field_timezone_help', zone: current_timezone.name)}" %>+ </div>+ <div class="mt-2">+ <%= f.spree_number_field :backorder_limit, min: 0,+ label: Spree.t('admin.variants_form.backorder_limit_label'),+ help: Spree.t('admin.variants_form.backorder_limit_hint') %>+ </div></div><table class="table border-t <%= 'hidden!' unless f.object.track_inventory? %>" data-reveal-target="item">diff --git a/spree/admin/config/locales/en.yml b/spree/admin/config/locales/en.ymlindex d897916fe0..0823f9f53d 100644--- a/spree/admin/config/locales/en.yml+++ b/spree/admin/config/locales/en.yml@@ -640,7 +640,13 @@ en:add_option:empty: Add options like size or colornot_empty: Add another option+ backorder_limit_hint: Maximum number of units sold beyond available stock — caps backorders and pre-orders. Leave blank for unlimited.+ backorder_limit_label: Backorder limitcompare_at_price_description: This price is used to show marked down price on the product page.+ preorder_ships_at_hint: When you expect to ship pre-orders. Shown to customers as the delivery promise; the pre-order ends once this date passes.+ preorder_ships_at_label: Ships by+ preorderable_hint: Sell this variant before it's in stock. Cap how many you'll take with the backorder limit, enter incoming stock as the count, or leave the limit blank for unlimited.+ preorderable_label: Available for pre-orderstock_locations_link: To add more stock locations please go to <a href="%{link}">Stock Locations</a>total_inventory_html: 'Total inventory at %{stock_location} location: %{count} available'vendors:diff --git a/spree/api/app/controllers/spree/api/v3/admin/products/variants_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/products/variants_controller.rbindex 65304904d5..6400478465 100644--- a/spree/api/app/controllers/spree/api/v3/admin/products/variants_controller.rb+++ b/spree/api/app/controllers/spree/api/v3/admin/products/variants_controller.rb@@ -34,7 +34,7 @@ module Spree:sku, :barcode,:cost_price, :cost_currency,:weight, :height, :width, :depth, :weight_unit, :dimensions_unit,- :track_inventory, :tax_category_id, :position,+ :track_inventory, :preorderable, :preorder_ships_at, :backorder_limit, :tax_category_id, :position,options: [:name, :value],prices: [:amount, :compare_at_amount, :currency],stock_items: [:stock_location_id, :count_on_hand, :backorderable]diff --git a/spree/api/app/controllers/spree/api/v3/admin/products_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/products_controller.rbindex dca02db57c..32687d1e6e 100644--- a/spree/api/app/controllers/spree/api/v3/admin/products_controller.rb+++ b/spree/api/app/controllers/spree/api/v3/admin/products_controller.rb@@ -187,7 +187,7 @@ module Spree:id, :sku, :barcode,:cost_price, :cost_currency,:weight, :height, :width, :depth, :weight_unit, :dimensions_unit,- :track_inventory, :tax_category_id, :position,+ :track_inventory, :preorderable, :preorder_ships_at, :backorder_limit, :tax_category_id, :position,options: [:name, :value],prices: [:amount, :compare_at_amount, :currency],stock_items: [:id, :stock_location_id, :count_on_hand, :backorderable]diff --git a/spree/api/app/controllers/spree/api/v3/store/products/filters_controller.rb b/spree/api/app/controllers/spree/api/v3/store/products/filters_controller.rbindex bfb96e2256..16df648b96 100644--- a/spree/api/app/controllers/spree/api/v3/store/products/filters_controller.rb+++ b/spree/api/app/controllers/spree/api/v3/store/products/filters_controller.rb@@ -29,7 +29,7 @@ module Spreedef filters_cache_keyproducts_table = Spree::Product.table_name- stats = current_store.products.available(Time.current, current_currency)+ stats = current_store.products.available(Time.current, current_currency, include_preorderable: true).pick(Arel.sql("MAX(#{products_table}.updated_at)"), Arel.sql("COUNT(DISTINCT #{products_table}.id)"))max_updated = stats&.first&.to_iproduct_count = stats&.last || 0@@ -50,7 +50,10 @@ module Spreeenddef filters_scope- scope = current_store.products.available(Time.current, current_currency)+ # Mirror ProductsController#scope so facet counts describe the+ # same product set the listing returns (coming-soon pre-orders+ # included).+ scope = current_store.products.available(Time.current, current_currency, include_preorderable: true)scope = scope.in_category(category) if category.present?scope.accessible_by(current_ability, :show)enddiff --git a/spree/api/app/controllers/spree/api/v3/store/products_controller.rb b/spree/api/app/controllers/spree/api/v3/store/products_controller.rbindex 3f78799580..7da57dc165 100644--- a/spree/api/app/controllers/spree/api/v3/store/products_controller.rb+++ b/spree/api/app/controllers/spree/api/v3/store/products_controller.rb@@ -29,7 +29,7 @@ module Spreeenddef scope- super.available(Time.current, Spree::Current.currency)+ super.available(Time.current, Spree::Current.currency, include_preorderable: true)end# these scopes are not automatically picked by ar_lazy_preload gem and we need to explicitly include themdiff --git a/spree/api/app/serializers/spree/api/v3/admin/variant_serializer.rb b/spree/api/app/serializers/spree/api/v3/admin/variant_serializer.rbindex 636d4e8f69..5342abfac6 100644--- a/spree/api/app/serializers/spree/api/v3/admin/variant_serializer.rb+++ b/spree/api/app/serializers/spree/api/v3/admin/variant_serializer.rb@@ -13,13 +13,20 @@ module Spreeweight_unit: [:string, nullable: true], dimensions_unit: [:string, nullable: true],available_stock: [:number, nullable: true],reserved_quantity: :number, total_on_hand: [:number, nullable: true],+ preorderable: :boolean, preorder_ships_at: [:string, nullable: true],+ backorder_limit: [:number, nullable: true],deleted_at: [:string, nullable: true],metadata: 'Record<string, unknown>'attributes :metadata, :position, :cost_price, :cost_currency,- :barcode, :weight_unit, :dimensions_unit, deleted_at: :iso8601,+ :barcode, :weight_unit, :dimensions_unit, :backorder_limit,+ preorder_ships_at: :iso8601, deleted_at: :iso8601,created_at: :iso8601, updated_at: :iso8601+ attribute :preorderable do |variant|+ variant.preorderable?+ end+attribute :tax_category_id do |variant|variant.tax_category&.prefixed_idenddiff --git a/spree/api/app/serializers/spree/api/v3/line_item_serializer.rb b/spree/api/app/serializers/spree/api/v3/line_item_serializer.rbindex 52757a5c0e..a4f9abbb39 100644--- a/spree/api/app/serializers/spree/api/v3/line_item_serializer.rb+++ b/spree/api/app/serializers/spree/api/v3/line_item_serializer.rb@@ -13,12 +13,24 @@ module Spreepre_tax_amount: [:string, nullable: true], display_pre_tax_amount: [:string, nullable: true],discounted_amount: [:string, nullable: true], display_discounted_amount: [:string, nullable: true],compare_at_amount: [:string, nullable: true], display_compare_at_amount: [:string, nullable: true],- thumbnail_url: [:string, nullable: true]+ thumbnail_url: [:string, nullable: true],+ preorder: :boolean, preorder_ships_at: [:string, nullable: true]attribute :variant_id do |line_item|line_item.variant&.prefixed_idend+ # True when the line item's variant is currently a pre-order, so the+ # cart/checkout can flag it as shipping later.+ attribute :preorder do |line_item|+ line_item.variant&.preorder? || false+ end++ # The variant's "ships by" promise while it's a pre-order.+ attribute :preorder_ships_at do |line_item|+ line_item.variant&.preorder_ships_at&.iso8601 if line_item.variant&.preorder?+ end+attributes :quantity, :currency, :name, :slug, :options_text# Nulled for gated (prices_hidden) guests so the cart's line items can'tdiff --git a/spree/api/app/serializers/spree/api/v3/product_serializer.rb b/spree/api/app/serializers/spree/api/v3/product_serializer.rbindex 038cb61529..8494f1ffcd 100644--- a/spree/api/app/serializers/spree/api/v3/product_serializer.rb+++ b/spree/api/app/serializers/spree/api/v3/product_serializer.rb@@ -11,7 +11,9 @@ module Spreedefault_variant_id: :string,thumbnail_url: [:string, nullable: true],available_on: [:string, nullable: true],+ preorder_ships_at: [:string, nullable: true],purchasable: :boolean, in_stock: :boolean, backorderable: :boolean, available: :boolean,+ preorder: :boolean,price: 'Price',original_price: ['Price', nullable: true],tags: [:string, multi: true]@@ -19,12 +21,18 @@ module Spreeattributes :name, :slug,:meta_title, :meta_description, :meta_keywords,:variant_count,- available_on: :iso8601+ available_on: :iso8601, preorder_ships_at: :iso8601attribute :purchasable do |product|product.purchasable?end+ # True when this product is currently offered as a pre-order on the+ # requesting channel.+ attribute :preorder do |product|+ product.preorder?+ end+attribute :in_stock do |product|product.in_stock?enddiff --git a/spree/api/app/serializers/spree/api/v3/variant_serializer.rb b/spree/api/app/serializers/spree/api/v3/variant_serializer.rbindex af63435912..1ca1fce4ad 100644--- a/spree/api/app/serializers/spree/api/v3/variant_serializer.rb+++ b/spree/api/app/serializers/spree/api/v3/variant_serializer.rb@@ -7,7 +7,8 @@ module Spreetypelize product_id: :string, sku: [:string, nullable: true],options_text: :string, track_inventory: :boolean, media_count: :number,thumbnail_url: [:string, nullable: true],- purchasable: :boolean, in_stock: :boolean, backorderable: :boolean,+ purchasable: :boolean, in_stock: :boolean, backorderable: :boolean, preorder: :boolean,+ preorder_ships_at: [:string, nullable: true],weight: [:number, nullable: true], height: [:number, nullable: true], width: [:number, nullable: true], depth: [:number, nullable: true],price: 'Price',original_price: ['Price', nullable: true]@@ -18,6 +19,12 @@ module Spreeattributes :sku, :options_text, :track_inventory, :media_count+ # Customer-facing "ships by" promise — only while the variant is a+ # pre-order (nil otherwise, even if a stale date lingers on the column).+ attribute :preorder_ships_at do |variant|+ variant.preorder_ships_at&.iso8601 if variant.preorder?+ end+# Main variant image URL for listings (cached primary_media)attribute :thumbnail_url do |variant|image_url_for(variant.primary_media)@@ -35,6 +42,10 @@ module Spreevariant.backorderable?end+ attribute :preorder do |variant|+ variant.preorder?+ end+attribute :weight do |variant|variant.weight&.to_fenddiff --git a/spree/core/app/models/concerns/spree/product_scopes.rb b/spree/core/app/models/concerns/spree/product_scopes.rbindex 7498f760ad..1304458f21 100644--- a/spree/core/app/models/concerns/spree/product_scopes.rb+++ b/spree/core/app/models/concerns/spree/product_scopes.rb@@ -308,7 +308,11 @@ module Spree# +.available+ without args returned future-dated products too.# @param currency [String, nil] currency to require a price in; nil# falls back to the default store's default currency.- def self.available(available_on = nil, currency = nil)+ # @param include_preorderable [Boolean] when true (storefront), products+ # scheduled to publish later are still included if they have an active+ # pre-order variant, so a "coming soon" launch can be pre-ordered before+ # its publish date. Channel context only.+ def self.available(available_on = nil, currency = nil, include_preorderable: false)cutoff = available_oncutoff = cutoff.beginning_of_minute if cutoff.respond_to?(:beginning_of_minute)@@ -316,8 +320,22 @@ module Spreeif cutoffscope = if (channel = Spree::Current.channel)- scope.for_channel(channel)- .where(Spree::ProductPublication.table_name => { published_at: [nil, ..cutoff] })+ pub = Spree::ProductPublication.table_name+ channel_scope = scope.for_channel(channel)+ if include_preorderable+ variants = Spree::Variant.quoted_table_name+ products = Product.quoted_table_name+ channel_scope.where(+ "#{pub}.published_at IS NULL OR #{pub}.published_at <= :cutoff OR " \+ "EXISTS (SELECT 1 FROM #{variants} WHERE #{variants}.product_id = #{products}.id " \+ "AND #{variants}.deleted_at IS NULL AND #{variants}.preorderable = :preorderable " \+ "AND (#{variants}.discontinue_on IS NULL OR #{variants}.discontinue_on > :cutoff) " \+ "AND (#{variants}.preorder_ships_at IS NULL OR #{variants}.preorder_ships_at > :cutoff))",+ cutoff: cutoff, preorderable: true+ )+ else+ channel_scope.where(pub => { published_at: [nil, ..cutoff] })+ endelsescope.where(Product.table_name => { available_on: ..cutoff })enddiff --git a/spree/core/app/models/spree/product.rb b/spree/core/app/models/spree/product.rbindex 235d38d962..5ff07545bf 100644--- a/spree/core/app/models/spree/product.rb+++ b/spree/core/app/models/spree/product.rb@@ -523,6 +523,26 @@ module Spreeactive? && !deleted? && (available_on.nil? || available_on <= Time.current)end+ # True when the product is currently offered as a pre-order: at least one+ # variant is sold before it is in stock (see {Variant#preorder?}).+ # Independent of publishing — a pre-order product is live in the catalog,+ # just flagged "buy now, ships later".+ # @return [Boolean]+ def preorder?+ default_variant.preorder? || variants.any?(&:preorder?)+ end++ # The latest "ships by" date across the product's pre-order variants, so a+ # storefront can show a single "ships by" promise for the product. Nil when+ # the product is not a pre-order. Scans the same sellable set {#preorder?}+ # consults (the master only counts when it is the sole, purchasable+ # variant), reading preloaded associations to avoid an N+1.+ # @return [ActiveSupport::TimeWithZone, nil]+ def preorder_ships_at+ candidates = has_variants? ? variants : [master]+ candidates.select(&:preorder?).filter_map(&:preorder_ships_at).max+ end+def discontinue!self.discontinue_on = Time.currentself.status = 'archived'diff --git a/spree/core/app/models/spree/search_provider/meilisearch.rb b/spree/core/app/models/spree/search_provider/meilisearch.rbindex cdc0e84f83..ffe76bd0ec 100644--- a/spree/core/app/models/spree/search_provider/meilisearch.rb+++ b/spree/core/app/models/spree/search_provider/meilisearch.rb@@ -158,6 +158,7 @@ module SpreeRails.logger.debug { "[Meilisearch] index=#{index_name} query=#{query.inspect} #{search_params.compact.inspect}" }+ settings_refreshed = falsebeginif return_facets && grouped_options.any?queries = [{ indexUid: index_name, q: query.to_s, **search_params }]@@ -175,6 +176,16 @@ module Spreefacet_distribution = ms_result['facetDistribution'] || {}endrescue ::Meilisearch::ApiError => e+ # Self-heal when a newly added filterable attribute (e.g. `preorder`)+ # is referenced before the index settings were refreshed — otherwise+ # every search on an upgraded store returns empty until a reindex or+ # the next product write.+ if e.code == 'invalid_search_filter' && !settings_refreshed+ settings_refreshed = true+ ensure_index_settings!+ retry+ end+Rails.logger.warn { "[Meilisearch] Search failed: #{e.message}. Run `rake spree:search:reindex` to initialize the index." }Rails.error.report(e, handled: true, context: { index: index_name, query: query })return nil@@ -233,7 +244,7 @@ module Spreeenddef filterable_attributes- %w[product_id status in_stock store_ids channel_ids locale currency available_on discontinue_on price category_ids tags option_value_ids]+ %w[product_id status in_stock preorder store_ids channel_ids locale currency available_on discontinue_on price category_ids tags option_value_ids]enddef sortable_attributes@@ -266,14 +277,16 @@ module Spreeconditions << "status = 'active'"conditions << "locale = '#{locale.to_s.gsub(/[^a-zA-Z_-]/, '')}'"conditions << "currency = '#{currency.to_s.gsub(/[^A-Z]/, '')}'"- # Exclude future-dated products — mirrors +Product.available(Time.current)+.- # ISO 8601 strings sort lexicographically in chronological order, so the- # string compare is sound. +NOT EXISTS+ catches docs indexed before this- # attribute was emitted (legacy indexes), +IS NULL+ catches docs where- # the field was emitted as explicit null, and the +<=+ clause filters- # the remaining future-dated docs — so the upgrade is non-breaking and- # no reindex is required.- conditions << "(available_on NOT EXISTS OR available_on IS NULL OR available_on <= '#{now.iso8601}')"+ # Exclude future-dated products — mirrors+ # +Product.available(Time.current, include_preorderable: true)+. ISO 8601+ # strings sort lexicographically in chronological order, so the string+ # compare is sound; +NOT EXISTS+/+IS NULL+ keep the available_on clause+ # backward-compatible with legacy docs. The trailing +preorder = true++ # keeps scheduled "coming soon" pre-orders searchable before their+ # publish date. It filters on the new +preorder+ attribute, so a+ # +rake spree:search:reindex+ (or the next product write, which refreshes+ # the index settings) is required after deploy before it takes effect.+ conditions << "(available_on NOT EXISTS OR available_on IS NULL OR available_on <= '#{now.iso8601}' OR preorder = true)"conditions << "(discontinue_on = 0 OR discontinue_on > #{now.to_i})"conditionsenddiff --git a/spree/core/app/models/spree/stock/availability_validator.rb b/spree/core/app/models/spree/stock/availability_validator.rbindex b424b55b58..2c38a07bfb 100644--- a/spree/core/app/models/spree/stock/availability_validator.rb+++ b/spree/core/app/models/spree/stock/availability_validator.rb@@ -14,7 +14,7 @@ module Spreedisplay_name = variant.name.to_sdisplay_name += " (#{variant.options_text})" unless variant.options_text.blank?- if variant.available?+ if variant.available? || variant.preorder?line_item.errors.add(:quantity,:selected_quantity_not_available,message: Spree.t(:selected_quantity_not_available, item: display_name.inspect))diff --git a/spree/core/app/models/spree/stock/quantifier.rb b/spree/core/app/models/spree/stock/quantifier.rbindex abe2e898aa..8f5f1d090e 100644--- a/spree/core/app/models/spree/stock/quantifier.rb+++ b/spree/core/app/models/spree/stock/quantifier.rb@@ -88,8 +88,28 @@ module Spree@backorderable ||= stock_items.any?(&:backorderable)end+ # Whether the requested quantity can be supplied. Beyond on-hand stock a+ # variant may oversell two ways: +backorderable+ stock, or a pre-order+ # (which also lifts the publish gate for a scheduled launch). Either way+ # the variant's +backorder_limit+ caps how far below zero it may go; a nil+ # (empty) limit means unlimited.def can_supply?(required = 1)- variant.available? && (backorderable? || total_on_hand >= required)+ return false unless variant.available? || variant.preorder?+ return true unless variant.should_track_inventory?++ oversellable = backorderable? || variant.preorder?+ limit = variant.backorder_limit+ return true if oversellable && limit.nil?++ # On-hand stock, plus — for a capped oversell — the room to sell below+ # zero down to +-backorder_limit+ (a single clamp of signed on-hand plus+ # the limit).+ supplyable = if oversellable+ [available_stock - reserved_quantity + limit, 0].max+ else+ total_on_hand+ end+ supplyable >= requiredenddef stock_itemsdiff --git a/spree/core/app/models/spree/stock_item.rb b/spree/core/app/models/spree/stock_item.rbindex 3331334c1a..b4abe717f3 100644--- a/spree/core/app/models/spree/stock_item.rb+++ b/spree/core/app/models/spree/stock_item.rb@@ -107,7 +107,8 @@ module Spreeprivatedef verify_count_on_hand?- count_on_hand_changed? && !backorderable? && (count_on_hand < count_on_hand_was) && (count_on_hand < 0)+ count_on_hand_changed? && !backorderable? && !variant.preorder? &&+ (count_on_hand < count_on_hand_was) && (count_on_hand < 0)end# Process backorders based on amount of stock receiveddiff --git a/spree/core/app/models/spree/stock_location.rb b/spree/core/app/models/spree/stock_location.rbindex b3b41efc14..c42927888a 100644--- a/spree/core/app/models/spree/stock_location.rb+++ b/spree/core/app/models/spree/stock_location.rb@@ -157,7 +157,10 @@ module Spreeelseon_hand = item.count_on_handon_hand = 0 if on_hand < 0- backordered = item.backorderable? ? (quantity - on_hand) : 0+ # A pre-order oversells like a backorder: the shortfall becomes+ # backordered inventory units (the backorder_limit cap is enforced+ # upstream by Stock::Quantifier#can_supply?).+ backordered = item.backorderable? || variant.preorder? ? (quantity - on_hand) : 0end[on_hand, backordered]diff --git a/spree/core/app/models/spree/variant.rb b/spree/core/app/models/spree/variant.rbindex ee57c5bde4..1a01bbc2f1 100644--- a/spree/core/app/models/spree/variant.rb+++ b/spree/core/app/models/spree/variant.rb@@ -13,7 +13,7 @@ module Spreepublishes_lifecycle_events- MEMOIZED_METHODS = %w(purchasable in_stock on_sale backorderable tax_category options_text compare_at_price)+ MEMOIZED_METHODS = %w(in_stock on_sale backorderable tax_category options_text compare_at_price)DIMENSION_UNITS = %w[mm cm in ft]WEIGHT_UNITS = %w[g kg lb oz]@@ -88,6 +88,8 @@ module Spreevalidates :dimensions_unit, inclusion: { in: DIMENSION_UNITS }, allow_blank: truevalidates :weight_unit, inclusion: { in: WEIGHT_UNITS }, allow_blank: true+ validates :backorder_limit, numericality: { only_integer: true, greater_than_or_equal_to: 0, allow_nil: true }+after_create :create_stock_itemsafter_create :set_master_out_of_stock, unless: :is_master?after_commit :clear_line_items_cache, on: :update@@ -238,6 +240,19 @@ module Spree!discontinued? && product.available?end+ # Returns true if the variant is sold as a pre-order: the product is active+ # and not deleted, the variant is flagged preorderable and not discontinued,+ # and the "ships by" date is open-ended or still in the future.+ # Pre-order relaxes only the publish-date embargo, not the rest of the+ # availability rules. Like backorder, a pre-order can make the variant+ # purchasable beyond on-hand stock; the oversell cap is +backorder_limit++ # (empty ⇒ unlimited), and it adds the ship-by promise.+ # @return [Boolean] true if the variant is a pre-order+ def preorder?+ !discontinued? && preorderable? && product.active? && !product.deleted? &&+ (preorder_ships_at.nil? || preorder_ships_at > Time.current)+ end+# Returns true if the variant is in stock or backorderable.# @return [Boolean] true if the variant is in stock or backorderabledef in_stock_or_backorderable?@@ -647,7 +662,19 @@ module Spreealias is_backorderable? backorderable?def purchasable?- @purchasable ||= in_stock? || backorderable?+ in_stock? || oversellable_now?+ end++ # Whether the variant can currently be bought by overselling — via+ # backorder or pre-order. Unlimited when +backorder_limit+ is nil (empty =+ # no cap); with a limit, purchasable only while the oversell allowance+ # remains.+ #+ # @return [Boolean]+ def oversellable_now?+ return false unless backorderable? || preorder?++ backorder_limit.nil? || can_supply?(1)end# Shortcut method to determine if inventory tracking is enabled for this variantdiff --git a/spree/core/app/presenters/spree/search_provider/product_presenter.rb b/spree/core/app/presenters/spree/search_provider/product_presenter.rbindex 4a6d020789..c1c5884cb1 100644--- a/spree/core/app/presenters/spree/search_provider/product_presenter.rb+++ b/spree/core/app/presenters/spree/search_provider/product_presenter.rb@@ -58,6 +58,9 @@ module Spreestatus: product.status,sku: product.sku,in_stock: product.in_stock?,+ # True when the product has an active pre-order variant, so a+ # scheduled (future-published) launch still surfaces in search.+ preorder: product.preorder?,store_ids: Array(product.store_id).map(&:to_s),channel_ids: channel_ids_for_store,discontinue_on: product.discontinue_on&.to_i || 0,diff --git a/spree/core/app/services/spree/stock_reservations/reserve.rb b/spree/core/app/services/spree/stock_reservations/reserve.rbindex df2da064e8..4d471dacef 100644--- a/spree/core/app/services/spree/stock_reservations/reserve.rb+++ b/spree/core/app/services/spree/stock_reservations/reserve.rb@@ -65,7 +65,10 @@ module Spreenext unless variant&.should_track_inventory?stock_item = select_stock_item(variant)- next if stock_item.nil? || stock_item.backorderable?+ # Backorderable and pre-order variants oversell past count_on_hand,+ # so a reservation capped at on-hand stock would wrongly reject them;+ # their cap is enforced by Stock::Quantifier#can_supply? instead.+ next if stock_item.nil? || stock_item.backorderable? || variant.preorder?[line_item, stock_item]enddiff --git a/spree/core/bin/rspec b/spree/core/bin/rspecnew file mode 100755index 0000000000..93e191c2ff--- /dev/null+++ b/spree/core/bin/rspec@@ -0,0 +1,16 @@+#!/usr/bin/env ruby+# frozen_string_literal: true++#+# This file was generated by Bundler.+#+# The application 'rspec' is installed as part of a gem, and+# this file is here to facilitate running it.+#++ENV["BUNDLE_GEMFILE"] ||= File.expand_path("../Gemfile", __dir__)++require "rubygems"+require "bundler/setup"++load Gem.bin_path("rspec-core", "rspec")diff --git a/spree/core/db/migrate/20260630000001_add_preorder_fields_to_spree_variants.rb b/spree/core/db/migrate/20260630000001_add_preorder_fields_to_spree_variants.rbnew file mode 100644index 0000000000..de5cc67b68--- /dev/null+++ b/spree/core/db/migrate/20260630000001_add_preorder_fields_to_spree_variants.rb@@ -0,0 +1,7 @@+class AddPreorderFieldsToSpreeVariants < ActiveRecord::Migration[7.2]+ def change+ add_column :spree_variants, :preorderable, :boolean+ add_column :spree_variants, :preorder_ships_at, :datetime+ add_column :spree_variants, :backorder_limit, :integer+ end+enddiff --git a/spree/core/lib/spree/permitted_attributes.rb b/spree/core/lib/spree/permitted_attributes.rbindex ddbe8322a7..26302aa787 100644--- a/spree/core/lib/spree/permitted_attributes.rb+++ b/spree/core/lib/spree/permitted_attributes.rb@@ -308,7 +308,7 @@ module Spree@@variant_attributes = [:name, :presentation, :cost_price, :discontinue_on, :lock_version,- :position, :track_inventory, :tax_category_id,+ :position, :track_inventory, :preorderable, :preorder_ships_at, :backorder_limit, :tax_category_id,:product_id, :product, :option_values_attributes, :price, :compare_at_price,:weight, :height, :width, :depth, :sku, :barcode, :cost_currency,:weight_unit, :dimensions_unit,diff --git a/spree/core/spec/models/spree/product/scopes_spec.rb b/spree/core/spec/models/spree/product/scopes_spec.rbindex 05835400c9..8369d84580 100644--- a/spree/core/spec/models/spree/product/scopes_spec.rb+++ b/spree/core/spec/models/spree/product/scopes_spec.rb@@ -595,6 +595,29 @@ describe 'Product scopes', type: :model doendend+ context '.available(..., include_preorderable: true)' do+ before { active_publication.update_columns(published_at: 1.day.from_now) }++ it 'excludes future-dated products by default' do+ expect(Spree::Product.available(Time.current, 'USD')).not_to include(active_product)+ end++ it 'includes a future-dated product with an active pre-order variant' do+ active_product.master.update_columns(preorderable: true)+ expect(Spree::Product.available(Time.current, 'USD', include_preorderable: true)).to include(active_product)+ end++ it "excludes it when the pre-order's ship date has already passed" do+ active_product.master.update_columns(preorderable: true, preorder_ships_at: 1.day.ago)+ expect(Spree::Product.available(Time.current, 'USD', include_preorderable: true)).not_to include(active_product)+ end++ it 'still excludes a future-dated product with no pre-order variant' do+ active_product.master.update_columns(preorderable: false)+ expect(Spree::Product.available(Time.current, 'USD', include_preorderable: true)).not_to include(active_product)+ end+ end+context '.not_discontinued under Spree::Current.channel' doit 'returns products whose current-channel publication is not unlisted' doexpect(Spree::Product.not_discontinued).to include(active_product)diff --git a/spree/core/spec/models/spree/product_preorder_spec.rb b/spree/core/spec/models/spree/product_preorder_spec.rbnew file mode 100644index 0000000000..306f566584--- /dev/null+++ b/spree/core/spec/models/spree/product_preorder_spec.rb@@ -0,0 +1,186 @@+require 'spec_helper'++# Pre-order is a per-variant "buy before it's in stock" label plus a "ships by"+# date. Overselling — whether framed as a backorder or a pre-order — is bounded+# by the variant's backorder_limit: empty means unlimited, a value caps how many+# units may be sold beyond available stock.+RSpec.describe 'Pre-order', type: :model do+ let(:store) { @default_store }+ let(:product) { create(:product, status: 'active') }+ let(:variant) { create(:variant, product: product, price: 20) }+ let(:stock_item) { variant.stock_items.first }++ def quantifier+ Spree::Stock::Quantifier.new(variant)+ end++ describe 'Spree::Variant#preorder?' do+ it 'is true when flagged with no ships-by date (open-ended)' do+ variant.update!(preorderable: true, preorder_ships_at: nil)+ expect(variant.preorder?).to be true+ end++ it 'is true when flagged and the ships-by date is in the future' do+ variant.update!(preorderable: true, preorder_ships_at: 2.months.from_now)+ expect(variant.preorder?).to be true+ end++ it 'is false once the ships-by date has passed' do+ variant.update!(preorderable: true, preorder_ships_at: 1.day.ago)+ expect(variant.preorder?).to be false+ end++ it 'is false when not flagged' do+ variant.update!(preorderable: false, preorder_ships_at: 2.months.from_now)+ expect(variant.preorder?).to be false+ end++ it 'is independent of the publish date — applies even when the product is already live' do+ variant.update!(preorderable: true)+ expect(product.available?).to be true # live / published+ expect(variant.preorder?).to be true+ end++ it 'is false when the product is not active (relaxes only the publish-date gate)' do+ variant.update!(preorderable: true)+ product.update!(status: 'archived')+ expect(variant.preorder?).to be false+ end+ end++ describe 'pre-order does not bypass the product status' do+ it 'cannot supply an archived product even when the variant is preorderable' do+ variant.update!(preorderable: true)+ stock_item.set_count_on_hand(5)+ product.update!(status: 'archived')+ expect(quantifier.can_supply?(1)).to be false+ end+ end++ # The oversell cap. Empty = unlimited; a value bounds how far below zero the+ # variant may sell, whether the oversell is a backorder or a pre-order.+ describe 'backorder_limit' do+ before do+ stock_item.update!(backorderable: false)+ stock_item.set_count_on_hand(0)+ end++ context 'pre-order with no backorder_limit (empty = unlimited)' do+ before { variant.update!(preorderable: true, backorder_limit: nil) }++ it 'is purchasable with no stock and no backorder' do+ expect(variant.purchasable?).to be true+ end++ it 'can supply any quantity' do+ expect(quantifier.can_supply?(10_000)).to be true+ end+ end++ context 'pre-order with a backorder_limit (capped)' do+ before { variant.update!(preorderable: true, backorder_limit: 5) }++ it 'is purchasable within the limit' do+ expect(variant.purchasable?).to be true+ expect(quantifier.can_supply?(5)).to be true+ end++ it 'cannot supply beyond the limit' do+ expect(quantifier.can_supply?(6)).to be false+ end++ it 'combines on-hand stock with the limit' do+ stock_item.set_count_on_hand(2)+ expect(quantifier.can_supply?(7)).to be true+ expect(quantifier.can_supply?(8)).to be false+ end++ it 'is not purchasable once the limit is used up' do+ stock_item.set_count_on_hand(-5) # 5 units already oversold+ expect(quantifier.can_supply?(1)).to be false+ expect(variant.purchasable?).to be false+ end+ end++ # The limit is universal — it caps a plain backorder too, not just pre-orders.+ context 'plain backorder (not a pre-order)' do+ before { stock_item.update!(backorderable: true) }++ it 'caps the backorder at the limit' do+ variant.update!(backorder_limit: 3)+ expect(quantifier.can_supply?(3)).to be true+ expect(quantifier.can_supply?(4)).to be false+ end++ it 'is unlimited when the limit is empty (legacy behaviour)' do+ variant.update!(backorder_limit: nil)+ expect(quantifier.can_supply?(9_999)).to be true+ end+ end+ end++ describe 'Spree::Product' do+ it '#preorder? is true when a variant is on pre-order' do+ variant.update!(preorderable: true)+ expect(product.reload.preorder?).to be true+ end++ it '#preorder? is false when no variant is on pre-order' do+ variant.update!(preorderable: false)+ expect(product.reload.preorder?).to be false+ end++ it '#preorder_ships_at returns the latest ships-by date among pre-order variants' do+ variant.update!(preorderable: true, preorder_ships_at: 1.month.from_now)+ latest = create(:variant, product: product, price: 20, preorderable: true, preorder_ships_at: 3.months.from_now)+ expect(product.reload.preorder_ships_at).to be_within(1.second).of(latest.preorder_ships_at)+ end+ end++ # Pre-ordered units must flow into fulfillment as backordered inventory+ # units, exactly like backorders, so process_backorders can fill them when+ # stock arrives.+ describe 'fulfillment (StockLocation#fill_status)' do+ let(:stock_location) { stock_item.stock_location }++ before do+ variant.update!(preorderable: true, backorder_limit: 5)+ stock_item.update!(backorderable: false)+ stock_item.set_count_on_hand(2)+ end++ it 'backorders the shortfall for a pre-order variant' do+ expect(stock_location.fill_status(variant, 5)).to eq [2, 3]+ end++ it 'does not backorder once the variant is no longer a pre-order' do+ variant.update!(preorderable: false)+ expect(stock_location.fill_status(variant, 5)).to eq [2, 0]+ end+ end++ # "Coming soon": a product scheduled to publish later (future published_at on+ # the current channel) can still be pre-ordered before its publish date.+ describe 'scheduled launch (future publish date)' do+ let(:channel) { store.default_channel }+ let(:publication) { product.product_publications.find_or_create_by!(channel: channel) }++ before do+ variant.update!(preorderable: true, backorder_limit: 5)+ stock_item.update!(backorderable: false)+ stock_item.set_count_on_hand(0)+ publication.update!(published_at: 2.months.from_now) # not yet published+ product.product_publications.reset+ end++ it 'is embargoed (not available) but is a pre-order' do+ expect(variant.available?).to be false+ expect(variant.preorder?).to be true+ end++ it 'can be supplied before the publish date, capped by the backorder_limit' do+ expect(quantifier.can_supply?(5)).to be true+ expect(quantifier.can_supply?(6)).to be false+ end+ end+enddiff --git a/spree/core/spec/models/spree/search_provider/meilisearch_spec.rb b/spree/core/spec/models/spree/search_provider/meilisearch_spec.rbindex a828afb0d8..e2a73d2976 100644--- a/spree/core/spec/models/spree/search_provider/meilisearch_spec.rb+++ b/spree/core/spec/models/spree/search_provider/meilisearch_spec.rb@@ -146,6 +146,33 @@ module Spreeexpect(result.products).not_to include(product_2)endend++ # A newly added filterable attribute (e.g. `preorder`) referenced before+ # the index settings were refreshed rejects the whole query on upgraded+ # stores — the provider must push settings and retry instead of serving+ # an empty listing until a reindex.+ context 'when a filter attribute is not yet filterable' do+ before do+ error = ::Meilisearch::ApiError.new(+ 400, 'Bad Request',+ { 'code' => 'invalid_search_filter', 'message' => 'Attribute `preorder` is not filterable.' }+ )+ calls = 0+ allow(mock_index).to receive(:search) do+ calls += 1+ raise error if calls == 1++ ms_response+ end+ end++ it 'pushes index settings and retries the search once' do+ expect(mock_index).to receive(:update_filterable_attributes)++ result = provider.search_and_filter(scope: store.products, query: 'shirt')+ expect(result.products).to include(product_1, product_2)+ end+ endenddescribe '#filters' dodiff --git a/spree/core/spec/services/spree/cart/add_item_spec.rb b/spree/core/spec/services/spree/cart/add_item_spec.rbindex 6ab99f136c..55573b1cf7 100644--- a/spree/core/spec/services/spree/cart/add_item_spec.rb+++ b/spree/core/spec/services/spree/cart/add_item_spec.rb@@ -212,6 +212,58 @@ module Spreeendend+ context 'pre-order before the scheduled publish date' do+ let(:store) { @default_store }+ let(:channel) { store.default_channel }+ let(:variant) { create(:variant, price: 20) }++ before do+ # No stock; the backorder_limit is the cap (not backorderable).+ variant.stock_items.first.update!(backorderable: false)+ variant.stock_items.first.set_count_on_hand(0)+ variant.update!(preorderable: true, backorder_limit: 5)++ # Scheduled to publish later — embargoed unless preorderable.+ publication = variant.product.product_publications.find_or_create_by!(channel: channel)+ publication.update!(published_at: 2.months.from_now)+ variant.product.product_publications.reset+ end++ it 'adds the not-yet-published, preorderable item to the cart' do+ expect { execute }.to change { order.line_items.count }.by(1)+ expect(execute).to be_success+ end++ it 'caps the pre-order at the backorder_limit' do+ result = subject.call(order: order, variant: variant, quantity: 6)+ expect(result).to be_failure+ expect(order.reload.line_items).to be_empty+ end++ context 'with no backorder_limit (unlimited)' do+ before { variant.update!(backorder_limit: nil) }++ it 'accepts a pre-order beyond any stock count' do+ result = subject.call(order: order, variant: variant, quantity: 100)+ expect(result).to be_success+ expect(order.reload.line_items.first.quantity).to eq 100+ end+ end++ context 'when the variant is not preorderable' do+ before do+ # Plenty of stock so the publish embargo is the only rejection cause.+ variant.update!(preorderable: false)+ variant.stock_items.first.set_count_on_hand(10)+ end++ it 'is rejected because the product is not yet published' do+ expect(execute).to be_failure+ expect(order.reload.line_items).to be_empty+ end+ end+ end+context 'setting metadata' docontext 'via metadata param' dolet(:metadata) { { 'gift_message' => 'Happy Birthday!' } }@@ -304,6 +356,22 @@ module Spreeexpect(execute).to be_successendend++ context 'when the variant is a capped pre-order with partial stock' do+ let(:order) { create(:order, total: 100, state: 'address') }++ before do+ variant.update!(preorderable: true, backorder_limit: 5)+ variant.stock_items.first.set_count_on_hand(2)+ end++ it 'skips reservation and accepts quantities beyond on-hand stock' do+ result = subject.call(order: order, variant: variant, quantity: 5)++ expect(result).to be_success+ expect(Spree::StockReservation.where(order_id: order.id)).to be_empty+ end+ endendendend