Skip to content

armgit / spree

Public Imported from GitHub
0

Open Source Platform for DTC, B2B Commerce, Marketplaces & Omnichannel. REST APIs, TypeScript SDKs, and production-ready Next.js storefront. Self-host it. Own your data. No vendor lock-in. Zero platform fees.

Fixed setting preferred stock location with Carts

Damian Legawiecb8721ea26fc3
diff --git a/docs/plans/6.0-core-rewrite-tasks.md b/docs/plans/6.0-core-rewrite-tasks.md
index 78db0bb4be..aa98edee4f 100644
--- a/docs/plans/6.0-core-rewrite-tasks.md
+++ b/docs/plans/6.0-core-rewrite-tasks.md
@@ -257,9 +257,9 @@ The point of no return; biggest single wave. Everything before it exists so this
### Wave 6 outcome notes (2026-07-29 — COMPLETE)
-**Backend (T6.1/T6.2).** Admin nested `/orders/:id/{tax_lines,discounts,fees}` (tax read-only; discounts manual-CRUD with `422 discount_not_editable` on promotion rows; fees full CRUD, `kind` defaults `surcharge`) — all mutations run `OrderUpdater#resum_typed_totals!`, the sanctioned post-placement edit path (re-sums rows into totals WITHOUT re-running promotion competition/tax estimation; works on completed orders). `Spree::Orders::Discounts::Create` (DI `order_discount_create_service`; originally shipped as `Orders::AddManualDiscount`, renamed pre-release to match the `Fees::Create` naming) computes flat/percent line-item rows or distributes order-level via the extracted `Spree::Adjusters::LargestRemainder`. Net-new admin `delivery_methods` CRUD (+`/calculators` discovery with preference schemas; flat `calculator_type`/`calculator_preferences` params; prefixed `tax_category_id`/`delivery_zone_ids`) + `delivery_zones` CRUD (typed members by `country_iso`/`state_abbr`/postal prefix-or-range; `members` replaces the set atomically). Store `delivery_methods` discovery (`storefront_visible` scope, `fulfillment_type` filter) + `/:id/pickup_locations` (pickup-enabled stock locations, `cart_id` narrows to full-cart local coverage) + `/:id/pickup_points?latitude&longitude` via `DeliveryMethod#pickup_point_provider_instance`. Cart pickup selection: `preferred_stock_location_id` — **a preference (`preference :stock_location_id`), not a column (Damian 2026-07-29)** — prefixed-ID writer validating pickup_enabled, copied to the order column at completion; `pickup_point_external_id` on cart fulfillment update validated via provider and frozen into `pickup_point_data`. FulfillmentSerializer: `status` column-backed, `fulfillment_type` column-with-fallback, `pickup_point_data` + `selected_delivery_rate_id` exposed, real-name associations. Admin orders scope excludes transient completion drafts (`draft` + `cart_id` set). `AppliedPromotionSerializer` rename frees `DiscountSerializer` (+`TaxLine`/`Fee`/`DeliveryZone`/`DeliveryZoneMember` serializers, registry keys, payment-session serializer gets `cart_id` + owner-bridged `order_id`). `ConfigurationManagement` grants DeliveryMethod/DeliveryZone/Member.
+**Backend (T6.1/T6.2).** Admin nested `/orders/:id/{tax_lines,discounts,fees}` (tax read-only; discounts manual-CRUD with `422 discount_not_editable` on promotion rows; fees full CRUD, `kind` defaults `surcharge`) — all mutations run `OrderUpdater#resum_typed_totals!`, the sanctioned post-placement edit path (re-sums rows into totals WITHOUT re-running promotion competition/tax estimation; works on completed orders). `Spree::Orders::Discounts::Create` (DI `order_discount_create_service`; originally shipped as `Orders::AddManualDiscount`, renamed pre-release to match the `Fees::Create` naming) computes flat/percent line-item rows or distributes order-level via the extracted `Spree::Adjusters::LargestRemainder`. Net-new admin `delivery_methods` CRUD (+`/calculators` discovery with preference schemas; flat `calculator_type`/`calculator_preferences` params; prefixed `tax_category_id`/`delivery_zone_ids`) + `delivery_zones` CRUD (typed members by `country_iso`/`state_abbr`/postal prefix-or-range; `members` replaces the set atomically). Store `delivery_methods` discovery (`storefront_visible` scope, `fulfillment_type` filter) + `/:id/pickup_locations` (pickup-enabled stock locations, `cart_id` narrows to full-cart local coverage) + `/:id/pickup_points?latitude&longitude` via `DeliveryMethod#pickup_point_provider_instance`. Cart pickup selection: `preferred_stock_location_id` — **a real column + `belongs_to`, same shape as Order** (the 2026-07-29 preference approach was reversed 2026-08-01: `spree_carts` has no `preferences` column, so the preference never persisted); prefixed-ID resolution + the pickup-enabled/store-scoping rule live in `Carts::Update`, mirroring `Orders::Create`; copied to the order column at completion; `pickup_point_external_id` on cart fulfillment update validated via provider and frozen into `pickup_point_data`. FulfillmentSerializer: `status` column-backed, `fulfillment_type` column-with-fallback, `pickup_point_data` + `selected_delivery_rate_id` exposed, real-name associations. Admin orders scope excludes transient completion drafts (`draft` + `cart_id` set). `AppliedPromotionSerializer` rename frees `DiscountSerializer` (+`TaxLine`/`Fee`/`DeliveryZone`/`DeliveryZoneMember` serializers, registry keys, payment-session serializer gets `cart_id` + owner-bridged `order_id`). `ConfigurationManagement` grants DeliveryMethod/DeliveryZone/Member.
-**Directives landed mid-wave (Damian):** (1) `market` + `channel` **required** on Cart AND Order (`belongs_to` without optional). Supporting invariant: **every store owns a bootstrap default market** — `Stores::Markets#ensure_default_market` is unconditional (country fallback: creation param → legacy default_country column → US, created if the countries table is empty), inherits the store's column configuration (currency/locale/supported_locales), and is flagged `bootstrap_default` so the MarketCountry shipping-coverage validation skips it (plus a `DeliveryMethod.none?` bootstrap exemption). Store column edits to default_locale/default_currency **sync onto the default market** (diff-based, not dirty-tracking); `supported_currencies_list`/`supported_locales_list` are now the **union of markets + legacy columns**; `Market#ensure_single_default` resets the owning store's association caches; markets cascade-delete with their store via `destroyed_by_association`; `Current.market` always resolves. `defined_preferences` no longer picks up `preferred_*` association writers (Order#preferred_stock_location= phantom), preference readers/writers tolerate NULL preferences columns. (2) **Promotion STI namespace rename REVERTED** — classes stay `Spree::Promotion::Rules::*`/`Spree::Promotion::Actions::*` incl. `CreateItemAdjustments` (typed-Discount behavior under legacy names; wire type back to `create_item_adjustments`; single calculator registry key; T7.5 type-column task dropped; decisions.md 2026-03-16 marked reversed). (3) Cart totals columns get **DB-level defaults** (0/0.0) in migration 100001; dummy apps rebuilt. (4) `preferred_stock_location_id` on Cart is a **preference** (`preference :stock_location_id`), not a column — migration dropped. (5) `docs/developer` updates skipped (full Spree 6 docs rewrite comes separately).
+**Directives landed mid-wave (Damian):** (1) `market` + `channel` **required** on Cart AND Order (`belongs_to` without optional). Supporting invariant: **every store owns a bootstrap default market** — `Stores::Markets#ensure_default_market` is unconditional (country fallback: creation param → legacy default_country column → US, created if the countries table is empty), inherits the store's column configuration (currency/locale/supported_locales), and is flagged `bootstrap_default` so the MarketCountry shipping-coverage validation skips it (plus a `DeliveryMethod.none?` bootstrap exemption). Store column edits to default_locale/default_currency **sync onto the default market** (diff-based, not dirty-tracking); `supported_currencies_list`/`supported_locales_list` are now the **union of markets + legacy columns**; `Market#ensure_single_default` resets the owning store's association caches; markets cascade-delete with their store via `destroyed_by_association`; `Current.market` always resolves. `defined_preferences` no longer picks up `preferred_*` association writers (Order#preferred_stock_location= phantom), preference readers/writers tolerate NULL preferences columns. (2) **Promotion STI namespace rename REVERTED** — classes stay `Spree::Promotion::Rules::*`/`Spree::Promotion::Actions::*` incl. `CreateItemAdjustments` (typed-Discount behavior under legacy names; wire type back to `create_item_adjustments`; single calculator registry key; T7.5 type-column task dropped; decisions.md 2026-03-16 marked reversed). (3) Cart totals columns get **DB-level defaults** (0/0.0) in migration 100001; dummy apps rebuilt. (4) `preferred_stock_location_id` on Cart was briefly a **preference**, reversed 2026-08-01 to a real column (`create_spree_carts` migration): `spree_carts` carries no `preferences` column, so preference writes were in-memory only and the pickup choice was silently lost on save. (5) `docs/developer` updates skipped (full Spree 6 docs rewrite comes separately).
**Final gates after directives:** core 7438/0, api 2525/0, emails 103/0 (all parallel where applicable), dashboard tsc+vitest+e2e green, both SDK suites green.
@@ -309,7 +309,7 @@ Four rake tasks + the T7.5 backfill, all wired into `lib/spree/upgrades/5_6_to_6
- **`spree:migrate_shipping_to_delivery`** (`lib/tasks/delivery_migration.rake`): polymorphic strings (StateChange.stateful_type, StockMovement.originator_type, legacy spree_adjustments.adjustable_type via a table-bound anonymous AR class), StateChange name 'shipment'→'fulfillment' + prev/next 'shipped'→'fulfilled', fulfillments.status 'shipped'→'fulfilled', delivery-method `fulfillment_type`/`fulfillment_provider` backfill (DigitalDelivery calculators → digital + Digital provider, rest shipping/Manual) copied onto existing fulfillments via their selected rate, digital shipping categories → per-store Digital ProductType assignment (created on demand), display_on → storefront_visible boolean. Batched (BATCH_SIZE env), value-narrowed idempotency.
- **`spree:migrate_zones_to_delivery_zones`**: legacy Zone ids in `spree_delivery_method_zones.delivery_zone_id` (the rename migration reuses the column) → new DeliveryZones with country/state members + join re-point; `metadata.migrated_from_zone_id` marker for idempotency; id-collision ambiguity logged + skipped (run right after db:migrate, before creating new zones); tax zones untouched; unreferenced shipping zones logged.
- **`spree:migrate_adjustments_to_typed_rows`**: per-order transactional mapping (TaxRate→TaxLine w/ rate snapshot + provider_id internal; eligible PromotionAction→Discount with promotion/code snapshots, order-level distributed largest-remainder via the shared `Spree::Adjusters::LargestRemainder`; nil-source by sign → manual Discount / surcharge Fee; unknown sources → Fee with provenance metadata; ReturnAuthorization → skip + freeze). **Totals never touched**; reconciliation (promo vs discounts, additional tax vs tax lines, 1-cent tolerance) freezes + logs non-reconciling orders in private_metadata. spree_adjustments intact as rollback source. Skips orders with any typed rows.
-- **`spree:migrate_incomplete_orders_to_carts`** (the final flip): incomplete = completed_at nil AND canceled_at nil; one Cart per order (token/binding/addresses/totals copied, timestamps preserved, market/channel resolved via the ensure_* helpers since save skips validation, pickup preference written raw); ALL dual-FK records re-owned in place (LineItem, Fulfillment, Payment, PaymentSession, StockReservation, CouponCode, OrderPromotion, TaxLine, Discount, Fee — `update_all(cart_id:, order_id: nil)`, money moves never copies); FulfillmentItem.order_id nulled, Order StateChanges deleted, hollow order row deleted. Payment-session orders convert LAST. Completed + canceled orders untouched.
+- **`spree:migrate_incomplete_orders_to_carts`** (the final flip): incomplete = completed_at nil AND canceled_at nil; one Cart per order (token/binding/addresses/totals copied, timestamps preserved, market/channel resolved via the ensure_* helpers since save skips validation, pickup column copied directly); ALL dual-FK records re-owned in place (LineItem, Fulfillment, Payment, PaymentSession, StockReservation, CouponCode, OrderPromotion, TaxLine, Discount, Fee — `update_all(cart_id:, order_id: nil)`, money moves never copies); FulfillmentItem.order_id nulled, Order StateChanges deleted, hollow order row deleted. Payment-session orders convert LAST. Completed + canceled orders untouched.
- **`spree:product_types:backfill`** (T7.5, in products.rake): store-less product types → default store, orphaned option-type joins removed, product counters reset. (Promotion STI type-column task DROPPED — namespace rename reverted in Wave 6.)
- **T7.6 manifest**: five new steps appended to the 5.6→6.0 manifest in dependency order (shipping→delivery, zones, adjustments→typed, orders→carts, product-types) with operator notes incl. the zones-before-new-delivery-zones ordering constraint and the typed-rows-before-carts dependency. Developer-facing upgrade doc deferred with the rest of the Spree 6 docs rewrite.
diff --git a/packages/admin-sdk/src/types/generated/Cart.ts b/packages/admin-sdk/src/types/generated/Cart.ts
index 5cecf3ff5d..9d2f4952f3 100644
--- a/packages/admin-sdk/src/types/generated/Cart.ts
+++ b/packages/admin-sdk/src/types/generated/Cart.ts
@@ -1,4 +1,4 @@
-// Typelizer digest 2557adc5a29a1a4d28e7906e5cc35332
+// Typelizer digest 93d568755a6d5504b7dda3f27223bebc
//
// DO NOT MODIFY: This file was automatically generated by Typelizer.
import type {LineItem, Address, Market, AppliedPromotion} from '@/types'
@@ -7,6 +7,7 @@ interface Cart {
id: string;
market_id: string | null;
channel_id: string | null;
+ preferred_stock_location_id: string | null;
number: string;
token: string;
email: string | null;
diff --git a/packages/sdk/src/types/generated/Cart.ts b/packages/sdk/src/types/generated/Cart.ts
index b33257ebfc..7fea95208d 100644
--- a/packages/sdk/src/types/generated/Cart.ts
+++ b/packages/sdk/src/types/generated/Cart.ts
@@ -1,4 +1,4 @@
-// Typelizer digest 29e31fed91907dd0ccb46f7d0e051df2
+// Typelizer digest 684c7e4938ebafd739eb5b02f197bf36
//
// DO NOT MODIFY: This file was automatically generated by Typelizer.
import type {AppliedPromotion, LineItem, Fulfillment, Payment, Address, PaymentMethod, GiftCard, Market} from '@/types'
@@ -7,6 +7,7 @@ interface Cart {
id: string;
market_id: string | null;
channel_id: string | null;
+ preferred_stock_location_id: string | null;
number: string;
token: string;
email: string | null;
diff --git a/packages/sdk/src/zod/generated/Cart.ts b/packages/sdk/src/zod/generated/Cart.ts
index e14f03cc80..6cf797157d 100644
--- a/packages/sdk/src/zod/generated/Cart.ts
+++ b/packages/sdk/src/zod/generated/Cart.ts
@@ -13,6 +13,7 @@ export const CartSchema = z.object({
id: z.string(),
market_id: z.string().nullable(),
channel_id: z.string().nullable(),
+ preferred_stock_location_id: z.string().nullable(),
number: z.string(),
token: z.string(),
email: z.string().nullable(),
diff --git a/spree/api/app/serializers/spree/api/v3/cart_serializer.rb b/spree/api/app/serializers/spree/api/v3/cart_serializer.rb
index c50f07d89a..e097cb9e95 100644
--- a/spree/api/app/serializers/spree/api/v3/cart_serializer.rb
+++ b/spree/api/app/serializers/spree/api/v3/cart_serializer.rb
@@ -8,6 +8,7 @@ module Spree
customer_note: [:string, nullable: true], market_id: [:string, nullable: true], channel_id: [:string, nullable: true],
currency: :string, locale: [:string, nullable: true], total_quantity: :number,
coupon_code: [:string, nullable: true],
+ preferred_stock_location_id: [:string, nullable: true],
requirements: 'Array<{step: string, field: string, code: string, message: string}>',
item_total: [:string, nullable: true], display_item_total: [:string, nullable: true],
delivery_total: [:string, nullable: true], display_delivery_total: [:string, nullable: true],
@@ -37,6 +38,11 @@ module Spree
order.channel&.prefixed_id
end
+ # Pickup selection — mirrors the writable param on cart update.
+ attribute :preferred_stock_location_id do |cart|
+ cart.preferred_stock_location&.prefixed_id
+ end
+
# @deprecated `number` mirrors `id` (carts have no order-style
# number) — kept one release for 5.x clients; removed in 6.1.
attributes :number, :token, :email, :customer_note,
diff --git a/spree/api/spec/controllers/spree/api/v3/store/carts_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/store/carts_controller_spec.rb
index 1c62c4c1b0..3b365c6273 100644
--- a/spree/api/spec/controllers/spree/api/v3/store/carts_controller_spec.rb
+++ b/spree/api/spec/controllers/spree/api/v3/store/carts_controller_spec.rb
@@ -615,6 +615,27 @@ RSpec.describe Spree::Api::V3::Store::CartsController, type: :controller do
expect(order.reload.ship_address_id).to eq(existing_address.id)
end
+ context 'selecting a pickup location' do
+ let!(:pickup_location) { create(:stock_location, pickup_enabled: true, store: store) }
+
+ it 'persists the choice and returns it as a prefixed id' do
+ patch :update, params: { id: order.prefixed_id, preferred_stock_location_id: pickup_location.prefixed_id }
+
+ expect(response).to have_http_status(:ok)
+ expect(order.reload.preferred_stock_location).to eq(pickup_location)
+ expect(json_response['preferred_stock_location_id']).to eq(pickup_location.prefixed_id)
+ end
+
+ it 'returns 404 for a location that is not pickup-enabled' do
+ not_pickup = create(:stock_location, pickup_enabled: false, store: store)
+
+ patch :update, params: { id: order.prefixed_id, preferred_stock_location_id: not_pickup.prefixed_id }
+
+ expect(response).to have_http_status(:not_found)
+ expect(order.reload.preferred_stock_location_id).to be_nil
+ end
+ end
+
context 'when a line item cannot be delivered to the address' do
let(:address) { user.addresses.first || create(:address, user: user, country: country, state: us_state) }
let(:unserved_type) { create(:product_type, name: 'Pickup Only', fulfillment_types: ['pickup']) }
diff --git a/spree/core/app/models/spree/cart.rb b/spree/core/app/models/spree/cart.rb
index 41ae3e86cb..4c23cb9574 100644
--- a/spree/core/app/models/spree/cart.rb
+++ b/spree/core/app/models/spree/cart.rb
@@ -63,32 +63,10 @@ module Spree
# normalizes also applies to finder values.
normalizes :coupon_code, with: ->(code) { code.to_s.strip.downcase.presence }
- # Pickup location choice is a preference (mirrors the admin-user
- # preference of the same name), copied to the order column at completion.
- preference :stock_location_id, :integer, nullable: true
- alias_method :assign_stock_location_id_preference, :preferred_stock_location_id=
-
- # Accepts the public prefixed ID (+sloc_...+) or a raw ID; validates the
- # location is pickup-enabled so the storefront can only select real
- # pickup locations.
- def preferred_stock_location_id=(value)
- if value.blank?
- assign_stock_location_id_preference(nil)
- return
- end
-
- location = if Spree::PrefixedId.prefixed_id?(value)
- Spree::StockLocation.pickup_enabled.find_by_prefix_id!(value)
- else
- Spree::StockLocation.pickup_enabled.find(value)
- end
- assign_stock_location_id_preference(location.id)
- end
-
- # @return [Spree::StockLocation, nil]
- def preferred_stock_location
- Spree::StockLocation.find_by(id: preferred_stock_location_id)
- end
+ # Pickup location choice, copied to the order at completion. Prefixed-ID
+ # resolution and the pickup-enabled rule live in Spree::Carts::Update,
+ # matching the Orders::Create twin.
+ belongs_to :preferred_stock_location, class_name: 'Spree::StockLocation', optional: true
has_many :line_items, -> { order(:created_at) }, class_name: 'Spree::LineItem', inverse_of: :cart, dependent: :destroy
has_many :variants, through: :line_items
diff --git a/spree/core/app/services/spree/carts/update.rb b/spree/core/app/services/spree/carts/update.rb
index 5b82bf661f..e9cc90c5a4 100644
--- a/spree/core/app/services/spree/carts/update.rb
+++ b/spree/core/app/services/spree/carts/update.rb
@@ -48,6 +48,17 @@ module Spree
cart.locale = params[:locale] if params[:locale].present?
cart.metadata = cart.metadata.merge(params[:metadata].to_h) if params[:metadata].present?
cart.use_shipping = params[:use_shipping] if params.key?(:use_shipping)
+ assign_preferred_stock_location if params.key?(:preferred_stock_location_id)
+ end
+
+ # Storefront pickup selection: resolves the public prefixed ID (or raw
+ # ID) against the store's pickup-enabled locations — the eligibility
+ # rule is enforced here at the API seam, mirroring Orders::Create.
+ def assign_preferred_stock_location
+ value = params[:preferred_stock_location_id]
+
+ cart.preferred_stock_location_id =
+ value.blank? ? nil : cart.store.stock_locations.pickup_enabled.find_by_param!(value).id
end
def assign_address(address_type)
diff --git a/spree/core/db/migrate/20260728000003_create_spree_carts.rb b/spree/core/db/migrate/20260728000003_create_spree_carts.rb
index 38e859b0f6..5dedf3c64e 100644
--- a/spree/core/db/migrate/20260728000003_create_spree_carts.rb
+++ b/spree/core/db/migrate/20260728000003_create_spree_carts.rb
@@ -19,6 +19,7 @@ class CreateSpreeCarts < ActiveRecord::Migration[7.2]
t.datetime :completing_at
t.string :coupon_code
t.references :gift_card, null: true
+ t.references :preferred_stock_location, null: true, index: false
t.decimal :item_total, precision: 10, scale: 2, default: 0.0
t.decimal :adjustment_total, precision: 10, scale: 2, default: 0.0
diff --git a/spree/core/lib/tasks/carts_migration.rake b/spree/core/lib/tasks/carts_migration.rake
index 5115008ead..212af66fb9 100644
--- a/spree/core/lib/tasks/carts_migration.rake
+++ b/spree/core/lib/tasks/carts_migration.rake
@@ -52,9 +52,7 @@ namespace :spree do
payment_total: order.payment_total,
total: order.total
)
- # Raw preference write — the public setter validates pickup_enabled,
- # which must not reject historical selections.
- cart.assign_stock_location_id_preference(order.preferred_stock_location_id) if order.preferred_stock_location_id.present?
+ cart.preferred_stock_location_id = order.preferred_stock_location_id if order.preferred_stock_location_id.present?
# save!(validate: false) skips before_validation, so resolve the now
# mandatory market/channel explicitly (legacy rows may have neither).
cart.send(:ensure_market_presence)
diff --git a/spree/core/spec/models/spree/cart_spec.rb b/spree/core/spec/models/spree/cart_spec.rb
index 556f4118a0..931e8807b8 100644
--- a/spree/core/spec/models/spree/cart_spec.rb
+++ b/spree/core/spec/models/spree/cart_spec.rb
@@ -266,34 +266,14 @@ describe Spree::Cart, type: :model do
end
end
- describe '#preferred_stock_location_id=' do
+ describe '#preferred_stock_location' do
let(:cart) { create(:cart, store: store) }
let(:pickup_location) { create(:stock_location, pickup_enabled: true) }
- it 'accepts a raw id of a pickup-enabled location' do
- cart.preferred_stock_location_id = pickup_location.id
+ it 'persists the pickup choice' do
+ cart.update!(preferred_stock_location_id: pickup_location.id)
- expect(cart.preferred_stock_location_id).to eq(pickup_location.id)
- expect(cart.preferred_stock_location).to eq(pickup_location)
- end
-
- it 'accepts a prefixed id' do
- cart.preferred_stock_location_id = pickup_location.prefixed_id
-
- expect(cart.preferred_stock_location_id).to eq(pickup_location.id)
- end
-
- it 'clears the preference on blank' do
- cart.preferred_stock_location_id = pickup_location.id
- cart.preferred_stock_location_id = ''
-
- expect(cart.preferred_stock_location_id).to be_nil
- end
-
- it 'rejects a location that is not pickup-enabled' do
- not_pickup = create(:stock_location, pickup_enabled: false)
-
- expect { cart.preferred_stock_location_id = not_pickup.id }.to raise_error(ActiveRecord::RecordNotFound)
+ expect(cart.reload.preferred_stock_location).to eq(pickup_location)
end
end
diff --git a/spree/core/spec/services/spree/carts/update_spec.rb b/spree/core/spec/services/spree/carts/update_spec.rb
index 2dd130b57a..af5b33f2f5 100644
--- a/spree/core/spec/services/spree/carts/update_spec.rb
+++ b/spree/core/spec/services/spree/carts/update_spec.rb
@@ -45,6 +45,51 @@ module Spree
end
end
+ describe 'updating preferred_stock_location_id (pickup selection)' do
+ let(:pickup_location) { create(:stock_location, pickup_enabled: true, store: store) }
+
+ it 'resolves a prefixed id against the store pickup-enabled locations' do
+ result = described_class.call(cart: cart, params: { preferred_stock_location_id: pickup_location.prefixed_id })
+
+ expect(result).to be_success
+ expect(cart.reload.preferred_stock_location_id).to eq(pickup_location.id)
+ expect(cart.preferred_stock_location).to eq(pickup_location)
+ end
+
+ it 'accepts a raw id' do
+ result = described_class.call(cart: cart, params: { preferred_stock_location_id: pickup_location.id })
+
+ expect(result).to be_success
+ expect(cart.reload.preferred_stock_location_id).to eq(pickup_location.id)
+ end
+
+ it 'clears the selection on blank' do
+ cart.preferred_stock_location_id = pickup_location.id
+ cart.save!
+
+ result = described_class.call(cart: cart, params: { preferred_stock_location_id: '' })
+
+ expect(result).to be_success
+ expect(cart.reload.preferred_stock_location_id).to be_nil
+ end
+
+ it 'rejects a location that is not pickup-enabled' do
+ not_pickup = create(:stock_location, pickup_enabled: false)
+
+ expect {
+ described_class.call(cart: cart, params: { preferred_stock_location_id: not_pickup.prefixed_id })
+ }.to raise_error(ActiveRecord::RecordNotFound)
+ end
+
+ it 'rejects a pickup location belonging to another store' do
+ other_store_location = create(:stock_location, pickup_enabled: true, store: create(:store))
+
+ expect {
+ described_class.call(cart: cart, params: { preferred_stock_location_id: other_store_location.prefixed_id })
+ }.to raise_error(ActiveRecord::RecordNotFound)
+ end
+ end
+
describe 'updating currency' do
context 'with supported currency' do
let(:params) { { currency: 'EUR' } }