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.

Rename shipping stack to fulfillment & delivery (core rewrite Wave 2)

Damian Legawiec73fed7dc02f4
diff --git a/docs/plans/6.0-core-rewrite-tasks.md b/docs/plans/6.0-core-rewrite-tasks.md
index 9e1e713c79..639b3e0317 100644
--- a/docs/plans/6.0-core-rewrite-tasks.md
+++ b/docs/plans/6.0-core-rewrite-tasks.md
@@ -90,42 +90,52 @@ Checkout keeps running on Order through Waves 1–4. The Cart table/model exist
The big mechanical wave. Whole-suite blast radius via factories; one-release constant aliases keep `spree/admin` and `spree/emails` compiling until their sweeps.
-### T2.1 Rename migrations (schema only — P1a)
-- [ ] Tables per rename map: `spree_shipments`→`spree_fulfillments`, `spree_shipping_methods`→`spree_delivery_methods`, `spree_shipping_rates`→`spree_delivery_rates`, `spree_inventory_units`→`spree_fulfillment_items`, `spree_shipping_method_zones`→`spree_delivery_method_zones`.
-- [ ] FK/column renames: `delivery_rates.{shipment_id→fulfillment_id, shipping_method_id→delivery_method_id}`, `fulfillment_items.shipment_id→fulfillment_id`, `delivery_method_zones.{shipping_method_id→delivery_method_id, zone_id→delivery_zone_id}` (born joining DeliveryZone), **`return_items.inventory_unit_id→fulfillment_item_id`**.
-- [ ] `state`→`status` on `spree_fulfillments` and `spree_fulfillment_items` (this wave owns these two normalize renames).
-- [ ] `spree_orders.shipment_state`→`fulfillment_status`, `shipment_total`→`delivery_total` — removing the shipped `alias_attribute` bridges in the same change (one-release deprecation aliases the other way).
-- [ ] `display_on` → `storefront_visible` boolean on `spree_delivery_methods` (schema here; value backfill in Wave 7; scopes/`available_to_display?` swap to the boolean; factories set it directly).
-- [ ] Index renames — `spree_shipping_rates_join_index` keeps its **uniqueness** (one-rate-per-method invariant).
-
-### T2.2 New columns/tables (P1b)
-- [ ] `spree_delivery_methods`: `fulfillment_type` (null: false, default `'shipping'`, indexed), `fulfillment_provider` (null: false, default Manual), `pickup_point_provider`.
-- [ ] `spree_fulfillments`: `fulfillment_type`, `pickup_point_data` (json/jsonb-guarded), `cart_id` (nullable — owner pattern).
-- [ ] `spree_delivery_method_stock_locations` join (unique on the pair) + model with vendor-consistency validation stubbed for the marketplace wave.
-- [ ] `spree_products.excluded_delivery_method_ids` (json/jsonb-guarded).
-- [ ] Settled (Decision 4): no owner columns on `spree_delivery_rates` — owner derives through `fulfillment.owner`.
-- [ ] **Not here** (shipped or other plans): StockLocation pickup columns, `store_id` (delivery-rate plan), `vendor_id` (marketplace wave).
-
-### T2.3 Model renames + behavior (P3)
-- [ ] Models/files: `Fulfillment` (`ful_`), `DeliveryMethod` (`dm_`), `DeliveryRate` (`dr_`), `FulfillmentItem` (`fi_`), `DeliveryMethodZone`; one-release aliases (`Spree::Shipment = Spree::Fulfillment` etc.). **ShippingCategory gets no alias** — `NameError` on reference.
-- [ ] `FulfilmentChanger` → `FulfillmentChanger`; `ShipmentHandler` removed (providers replace it in Wave 4).
-- [ ] Status machine preserved exactly: `ready` guard (#2040), `pend`, conditional `resume`, `ready_for_pickup` reachable from `ready` + cancelable, all `after_transition` hooks (restock/unstock, StateChange rows, `set_fulfilled_at`); `shipped`→`fulfilled`, `shipped_at`→`fulfilled_at`; the three `update_columns` escape hatches rewritten through the machine or documented freeze-safe. New numbers `F`-prefixed; existing `H` numbers untouched.
-- [ ] Raw-SQL/table-literal fixes that survive renames silently: `reverse_chronological`, `with_free_shipping_promotion?`, `Package#shipping_categories` SQL, `determine_state` string literals.
-- [ ] Order side: association renames (`fulfillments`, `delivery_total`), rollup rename with **`backorder` preserved** (domain: `backorder|canceled|partial|pending|ready|fulfilled` + nil; `ready_for_pickup`/`picked_up` roll up as `ready`/`fulfilled`), `not_shipped`-scope and `allow_cancel?` reads updated.
-- [ ] CanCanCan grants, PermittedAttributes, seeds (incl. `Seeds::DigitalDelivery` + the hardcoded `'Digital'`/`'Default'` category readers), factories (`shipment_factory`→`fulfillment_factory` etc. with aliases; `product_factory` stops assigning shipping categories — whole-suite impact).
-
-### T2.4 Eligibility rework — ShippingCategory retired from behavior (needs T0.1)
-- [ ] `Package#eligible_delivery_methods` replaces `Package#shipping_methods`: intersect package items' `fulfillment_types` (via ProductType, `['shipping']` fallback when typeless) with `DeliveryMethod#fulfillment_type`, minus per-product `excluded_delivery_method_ids`. Seam stays **inside `Stock::Estimator#shipping_methods`**.
-- [ ] `Stock::Splitter::ShippingCategory` → `Splitter::FulfillmentType` (homogeneous packages by fulfillment type); `Splitter::Digital` folds in.
-- [ ] Digital discriminator to columns: `DeliveryMethod#digital?/pickup?/pickup_point?/requires_address?`; `.digital` scope; `Product#digital?` + net-new `Product#fulfillment_types` via ProductType; `DigitalDelivery` calculator demoted to plain zero-cost (calculators stay — decisions.md 2026-07-27).
-- [ ] Remove ShippingCategory presence-validation/auto-assign from Product **now** (tables/columns drop in 6.1; products must stay saveable in between).
-- [ ] Parity spec target: mixed carts still split + get rates (`order_routing/strategy/parity_spec.rb:426-452` rewritten to the new inputs).
-
-### T2.5 Delivery-zones shipping consumers (delivery-zones Phase C, shipping slice)
-- [ ] `DeliveryMethod has_many :delivery_zones`; `#include?(address)` over DeliveryZone; Estimator zone-check swap.
-- [ ] `Store#countries_with_shipping_coverage` rewritten on DeliveryZone members.
-- [ ] Factories: delivery methods worldwide-by-default (no zones); `Zone.global` monkey-patch retired from the shipping path (zone factories stay for tax until the tax plan). Permission sets grant DeliveryZone.
-- [ ] `Spree::Zone` itself **stays** (tax + legacy admin) — its removal is tax-provider Phase 5 + delivery-zones Phase D, out of scope.
+### T2.1 Rename migrations (schema only — P1a) — ✅ done 2026-07-29
+- [x] Tables per rename map: `spree_shipments`→`spree_fulfillments`, `spree_shipping_methods`→`spree_delivery_methods`, `spree_shipping_rates`→`spree_delivery_rates`, `spree_inventory_units`→`spree_fulfillment_items`, `spree_shipping_method_zones`→`spree_delivery_method_zones`.
+- [x] FK/column renames: `delivery_rates.{shipment_id→fulfillment_id, shipping_method_id→delivery_method_id}`, `fulfillment_items.shipment_id→fulfillment_id`, `delivery_method_zones.{shipping_method_id→delivery_method_id, zone_id→delivery_zone_id}` (born joining DeliveryZone), **`return_items.inventory_unit_id→fulfillment_item_id`**.
+- [x] `state`→`status` on `spree_fulfillments` and `spree_fulfillment_items` (this wave owns these two normalize renames).
+- [x] `spree_orders.shipment_state`→`fulfillment_status`, `shipment_total`→`delivery_total` — removing the shipped `alias_attribute` bridges in the same change (one-release deprecation aliases the other way).
+- [x] `display_on` → `storefront_visible` boolean on `spree_delivery_methods` (schema here; value backfill in Wave 7; scopes/`available_to_display?` swap to the boolean; factories set it directly).
+- [x] Index renames — `spree_shipping_rates_join_index` keeps its **uniqueness** (one-rate-per-method invariant).
+
+### T2.2 New columns/tables (P1b) — ✅ done 2026-07-29 (no DB defaults per Decision; model-level)
+- [x] `spree_delivery_methods`: `fulfillment_type` (nullable, indexed; model-level default `'shipping'`), `fulfillment_provider` (nullable; model-level default Manual + blank-fallback in `#provider`), `pickup_point_provider`. DB defaults deliberately avoided (house rule); existing rows ride the T7.1 backfill.
+- [x] `spree_fulfillments`: `fulfillment_type`, `pickup_point_data` (json/jsonb-guarded), `cart_id` (nullable — owner pattern).
+- [x] `spree_delivery_method_stock_locations` join (unique on the pair) + model with vendor-consistency validation stubbed for the marketplace wave.
+- [x] `spree_products.excluded_delivery_method_ids` (json/jsonb-guarded).
+- [x] Settled (Decision 4): no owner columns on `spree_delivery_rates` — owner derives through `fulfillment.owner`.
+- [x] **Not here** (shipped or other plans): StockLocation pickup columns, `store_id` (delivery-rate plan), `vendor_id` (marketplace wave).
+
+### T2.3 Model renames + behavior (P3) — ✅ done 2026-07-29
+- [x] Models/files: `Fulfillment` (`ful_`), `DeliveryMethod` (`dm_`), `DeliveryRate` (`dr_`), `FulfillmentItem` (`fi_`), `DeliveryMethodZone`; one-release aliases (`Spree::Shipment = Spree::Fulfillment` etc.). **ShippingCategory gets no alias** — `NameError` on reference.
+- [x] `FulfilmentChanger` → `FulfillmentChanger`; `ShipmentHandler` removed (providers replace it in Wave 4).
+- [x] Status machine preserved exactly: `ready` guard (#2040), `pend`, conditional `resume`, `ready_for_pickup` reachable from `ready` + cancelable, all `after_transition` hooks (restock/unstock, StateChange rows, `set_fulfilled_at`); `shipped`→`fulfilled`, `shipped_at`→`fulfilled_at`; the three `update_columns` escape hatches rewritten through the machine or documented freeze-safe. New numbers `F`-prefixed; existing `H` numbers untouched.
+- [x] Raw-SQL/table-literal fixes that survive renames silently: `reverse_chronological`, `with_free_shipping_promotion?`, `Package#shipping_categories` SQL, `determine_state` string literals.
+- [x] Order side: association renames (`fulfillments`, `delivery_total`), rollup rename with **`backorder` preserved** (domain: `backorder|canceled|partial|pending|ready|fulfilled` + nil; `ready_for_pickup`/`picked_up` roll up as `ready`/`fulfilled`), `not_shipped`-scope and `allow_cancel?` reads updated.
+- [x] CanCanCan grants, PermittedAttributes, seeds (incl. `Seeds::DigitalDelivery` + the hardcoded `'Digital'`/`'Default'` category readers), factories (`shipment_factory`→`fulfillment_factory` etc. with aliases; `product_factory` stops assigning shipping categories — whole-suite impact).
+
+### T2.4 Eligibility rework — ShippingCategory retired from behavior (needs T0.1) — ✅ done 2026-07-29
+- [x] `Package#eligible_delivery_methods` replaces `Package#shipping_methods`: intersect package items' `fulfillment_types` (via ProductType, `['shipping']` fallback when typeless) with `DeliveryMethod#fulfillment_type`, minus per-product `excluded_delivery_method_ids`. Seam stays **inside `Stock::Estimator#shipping_methods`**.
+- [x] `Stock::Splitter::ShippingCategory` → `Splitter::FulfillmentType` (homogeneous packages by fulfillment type); `Splitter::Digital` folds in.
+- [x] Digital discriminator to columns: `DeliveryMethod#digital?/pickup?/pickup_point?/requires_address?`; `.digital` scope; `Product#digital?` + net-new `Product#fulfillment_types` via ProductType; `DigitalDelivery` calculator demoted to plain zero-cost (calculators stay — decisions.md 2026-07-27).
+- [x] Remove ShippingCategory presence-validation/auto-assign from Product **now** (tables/columns drop in 6.1; products must stay saveable in between).
+- [x] Parity spec target: mixed carts still split + get rates (`order_routing/strategy/parity_spec.rb:426-452` rewritten to the new inputs).
+
+### T2.5 Delivery-zones shipping consumers (delivery-zones Phase C, shipping slice) — ✅ done 2026-07-29
+- [x] `DeliveryMethod has_many :delivery_zones`; `#include?(address)` over DeliveryZone; Estimator zone-check swap.
+- [x] `Store#countries_with_shipping_coverage` rewritten on DeliveryZone members.
+- [x] Factories: delivery methods worldwide-by-default (no zones); `Zone.global` monkey-patch retired from the shipping path (zone factories stay for tax until the tax plan). Permission sets grant DeliveryZone.
+- [x] `Spree::Zone` itself **stays** (tax + legacy admin) — its removal is tax-provider Phase 5 + delivery-zones Phase D, out of scope.
+
+### Wave 2 outcome notes (2026-07-29)
+
+- **Deprecation bridges are the standing convention** (Damian): legacy associations are Rails 8.1 `deprecated: true` twins (core gemspec floor bumped to `>= 8.1` for rails/rails#55285); legacy methods/scopes warn via `Spree::Deprecation` then delegate; `alias_attribute` for columns; constant-assignment aliases for classes. Internal Spree code uses **real names only** — twin associations carry separate AR caches, and mixing names inside one flow caused real stale-object bugs (auto-capture, `set_shipments_cost`, `Prioritizer#hash_item`, `Exchange#perform!`, unsaved `to_shipment` graphs).
+- Rails 8.1's strict association resolution rejects alias constants in `class_name:` **and** inference — every `class_name:` now names the real class.
+- `Calculator#compute` dispatches by class name, so Fulfillment objects route through a new `compute_fulfillment` → `compute_shipment` bridge preserving the historical calculator extension point.
+- Retired with no bridge (plan-sanctioned): `ShipmentHandler` (inlined into `after_fulfill` until Wave 4 providers), `Stock::Splitter::ShippingCategory` + `Splitter::Digital` (classes + specs deleted; `Splitter::FulfillmentType` registered), `ShippingCategory#includes_digital_shipping_method?` (zero callers), `Zone`↔shipping-method associations, the market factory's zone scaffolding.
+- **Wave 7 additions discovered:** T7.1 must also convert status *values* (`spree_fulfillments.status` and `spree_orders.fulfillment_status`: `'shipped'` → `'fulfilled'`); FulfillmentItem unit statuses keep `'shipped'`.
+- `Fulfillments::Create` keeps accepting `status: 'shipped'` (registers as `fulfilled`); the machine gained `ready_for_pickup` + `mark_ready_for_pickup` per plan; new numbers `F`-prefixed.
+- Suite convergence: 371 → 298 → 173 → 83 → 44 → 9 → 0 across six full-suite iterations.
---
diff --git a/docs/plans/6.0-fulfillment-and-delivery.md b/docs/plans/6.0-fulfillment-and-delivery.md
index 9df6163309..39808db1f8 100644
--- a/docs/plans/6.0-fulfillment-and-delivery.md
+++ b/docs/plans/6.0-fulfillment-and-delivery.md
@@ -246,7 +246,7 @@ Phase 1 as previously drafted was one ~20-operation migration; per CLAUDE.md (da
### Phase 1b — new columns/tables (additive)
-- `delivery_methods`: `fulfillment_type` (null: false, default 'shipping', indexed), `fulfillment_provider` (null: false, default Manual), `pickup_point_provider`.
+- `delivery_methods`: `fulfillment_type` (nullable, indexed — default `'shipping'` lives on the model per house rule; existing rows backfilled by the Phase 2 data task), `fulfillment_provider` (nullable — model default Manual, `#provider` falls back on blank), `pickup_point_provider`.
- `fulfillments`: `fulfillment_type`, `pickup_point_data` (JSON, jsonb-guarded), `cart_id` (per owner decision).
- `spree_delivery_method_stock_locations` join (unique on the pair).
- `products.excluded_delivery_method_ids` (JSON, jsonb-guarded).
diff --git a/spree/api/spec/controllers/spree/api/v3/admin/orders/fulfillments_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/orders/fulfillments_controller_spec.rb
index 773e65ddf2..a7e037aea7 100644
--- a/spree/api/spec/controllers/spree/api/v3/admin/orders/fulfillments_controller_spec.rb
+++ b/spree/api/spec/controllers/spree/api/v3/admin/orders/fulfillments_controller_spec.rb
@@ -88,10 +88,10 @@ RSpec.describe Spree::Api::V3::Admin::Orders::FulfillmentsController, type: :con
}, as: :json
expect(response).to have_http_status(:created)
- expect(json_response['status']).to eq('shipped')
+ expect(json_response['status']).to eq('fulfilled')
expect(json_response['fulfilled_at']).to be_present
expect(BigDecimal(json_response['cost'])).to eq(BigDecimal('7.42'))
- expect(order.reload.shipment_state).to eq('shipped')
+ expect(order.reload.fulfillment_status).to eq('fulfilled')
end
it 'returns 422 for a non-completed order' do
@@ -183,7 +183,7 @@ RSpec.describe Spree::Api::V3::Admin::Orders::FulfillmentsController, type: :con
expect(response).to have_http_status(:ok)
expect(shipment.reload.state).to eq(original_state)
- expect(shipment.state).not_to eq('shipped')
+ expect(shipment.status).not_to eq('fulfilled')
end
end
@@ -197,7 +197,7 @@ RSpec.describe Spree::Api::V3::Admin::Orders::FulfillmentsController, type: :con
}, as: :json
expect(response).to have_http_status(:ok)
- expect(json_response['status']).to eq('shipped')
+ expect(json_response['status']).to eq('fulfilled')
end
end
diff --git a/spree/api/spec/controllers/spree/api/v3/admin/orders_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/orders_controller_spec.rb
index 93e59a664a..dad9f4a8a0 100644
--- a/spree/api/spec/controllers/spree/api/v3/admin/orders_controller_spec.rb
+++ b/spree/api/spec/controllers/spree/api/v3/admin/orders_controller_spec.rb
@@ -210,7 +210,7 @@ RSpec.describe Spree::Api::V3::Admin::OrdersController, type: :controller do
let!(:zone) { create(:zone) }
let!(:zone_member) { create(:zone_member, zone: zone, zoneable: country) }
let!(:shipping_method) do
- create(:shipping_method, zones: [zone]).tap do |sm|
+ create(:shipping_method).tap do |sm|
sm.calculator.preferred_amount = 5
sm.calculator.save
end
@@ -306,7 +306,7 @@ RSpec.describe Spree::Api::V3::Admin::OrdersController, type: :controller do
let!(:zone) { create(:zone) }
let!(:zone_member) { create(:zone_member, zone: zone, zoneable: country) }
let!(:shipping_method) do
- create(:shipping_method, zones: [zone]).tap do |sm|
+ create(:shipping_method).tap do |sm|
sm.calculator.preferred_amount = 5
sm.calculator.save
end
@@ -466,7 +466,7 @@ RSpec.describe Spree::Api::V3::Admin::OrdersController, type: :controller do
let!(:zone) { create(:zone) }
let!(:zone_member) { create(:zone_member, zone: zone, zoneable: country) }
let!(:shipping_method) do
- create(:shipping_method, zones: [zone]).tap do |sm|
+ create(:shipping_method).tap do |sm|
sm.calculator.preferred_amount = 5
sm.calculator.save
end
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 f7812464a8..b2a5baf95d 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
@@ -487,7 +487,7 @@ RSpec.describe Spree::Api::V3::Store::CartsController, type: :controller do
let(:country) { Spree::Country.find_by(iso: 'US') || create(:country, iso: 'US') }
let!(:us_state) { country.states.find_by(abbr: 'NY') || create(:state, country: country, abbr: 'NY', name: 'New York') }
let!(:zone) { create(:zone, zone_members: [Spree::ZoneMember.new(zoneable: country)]) }
- let!(:shipping_method) { create(:shipping_method, zones: [zone]) }
+ let!(:shipping_method) { create(:shipping_method) }
before do
request.headers['Authorization'] = "Bearer #{jwt_token}"
@@ -514,9 +514,9 @@ RSpec.describe Spree::Api::V3::Store::CartsController, type: :controller do
cart.shipments.delete_all
cart.update_column(:state, 'address')
- # Move the products into a shipping category no shipping method serves.
- unserved_category = create(:shipping_category, name: 'Unserved')
- cart.line_items.each { |line_item| line_item.variant.product.update!(shipping_category: unserved_category) }
+ # Give the products a fulfillment type no delivery method serves.
+ unserved_type = create(:product_type, name: 'Pickup Only', fulfillment_types: ['pickup'])
+ cart.line_items.each { |line_item| line_item.variant.product.update!(product_type: unserved_type) }
cart.reload
get :show, params: { id: cart.prefixed_id }
@@ -575,7 +575,7 @@ RSpec.describe Spree::Api::V3::Store::CartsController, type: :controller do
let(:country) { Spree::Country.find_by(iso: 'US') || create(:country, iso: 'US') }
let!(:us_state) { country.states.find_by(abbr: 'NY') || create(:state, country: country, abbr: 'NY', name: 'New York') }
let!(:zone) { create(:zone, zone_members: [Spree::ZoneMember.new(zoneable: country)]) }
- let!(:shipping_method) { create(:shipping_method, zones: [zone]) }
+ let!(:shipping_method) { create(:shipping_method) }
before do
request.headers['Authorization'] = "Bearer #{jwt_token}"
@@ -593,11 +593,11 @@ RSpec.describe Spree::Api::V3::Store::CartsController, type: :controller do
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_category) { create(:shipping_category, name: 'Unserved') }
+ let(:unserved_type) { create(:product_type, name: 'Pickup Only', fulfillment_types: ['pickup']) }
before do
order.update!(email: '[email protected]')
- order.line_items.each { |line_item| line_item.variant.product.update!(shipping_category: unserved_category) }
+ order.line_items.each { |line_item| line_item.variant.product.update!(product_type: unserved_type) }
end
it 'returns ok with a delivery_unavailable warning, an unmet delivery requirement, and no fulfillments' do
diff --git a/spree/api/spec/integration/spree/api/v3/admin/markets_spec.rb b/spree/api/spec/integration/spree/api/v3/admin/markets_spec.rb
index 28786946b8..826656ced5 100644
--- a/spree/api/spec/integration/spree/api/v3/admin/markets_spec.rb
+++ b/spree/api/spec/integration/spree/api/v3/admin/markets_spec.rb
@@ -15,14 +15,8 @@ RSpec.describe 'Admin Markets API', type: :request, swagger_doc: 'api-reference/
# The market factory does this for its own countries; we mirror that for the
# other countries this spec assigns directly through the API.
before do
- shipping_zone = Spree::Zone.find_or_create_by!(name: 'Test Shipping Zone') { |z| z.kind = 'country' }
- [country, other_country].each do |c|
- shipping_zone.zone_members.find_or_create_by!(zoneable: c)
- end
- if shipping_zone.shipping_methods.empty?
- shipping_category = Spree::ShippingCategory.first || create(:shipping_category)
- create(:shipping_method, zones: [shipping_zone], shipping_categories: [shipping_category])
- end
+ # Delivery methods are worldwide by default; one method covers all countries.
+ create(:shipping_method) unless Spree::DeliveryMethod.where.missing(:delivery_method_zones).exists?
end
path '/api/v3/admin/markets' do
diff --git a/spree/api/spec/integration/spree/api/v3/admin/orders/fulfillments_spec.rb b/spree/api/spec/integration/spree/api/v3/admin/orders/fulfillments_spec.rb
index c9b6ff63c8..34a6859542 100644
--- a/spree/api/spec/integration/spree/api/v3/admin/orders/fulfillments_spec.rb
+++ b/spree/api/spec/integration/spree/api/v3/admin/orders/fulfillments_spec.rb
@@ -102,7 +102,7 @@ RSpec.describe 'Admin Order Fulfillments API', type: :request, swagger_doc: 'api
data = JSON.parse(response.body)
expect(data['id']).to start_with('ful_')
expect(data['tracking']).to eq('INPOST-12345')
- expect(data['status']).to eq('shipped')
+ expect(data['status']).to eq('fulfilled')
end
end
@@ -222,7 +222,7 @@ RSpec.describe 'Admin Order Fulfillments API', type: :request, swagger_doc: 'api
run_test! do |response|
data = JSON.parse(response.body)
- expect(data['status']).to eq('shipped')
+ expect(data['status']).to eq('fulfilled')
end
end
end
diff --git a/spree/core/app/models/spree/address.rb b/spree/core/app/models/spree/address.rb
index 1f31d5139b..b63401b6c0 100644
--- a/spree/core/app/models/spree/address.rb
+++ b/spree/core/app/models/spree/address.rb
@@ -44,7 +44,8 @@ module Spree
# we need a safe operator here as Address is added to metafield_enabled_resources in Engine
belongs_to :user, class_name: Spree.user_class&.name, optional: true, touch: true
- has_many :shipments, inverse_of: :address
+ has_many :fulfillments, class_name: 'Spree::Fulfillment', inverse_of: :address
+ has_many :shipments, class_name: 'Spree::Fulfillment', foreign_key: :address_id, deprecated: true
after_initialize :set_default_values, if: -> { new_record? && user.present? }
diff --git a/spree/core/app/models/spree/adjustable/promotion_accumulator.rb b/spree/core/app/models/spree/adjustable/promotion_accumulator.rb
index fd00697e6b..7dfe49f3e6 100644
--- a/spree/core/app/models/spree/adjustable/promotion_accumulator.rb
+++ b/spree/core/app/models/spree/adjustable/promotion_accumulator.rb
@@ -67,7 +67,7 @@ module Spree
end
def item_adjustments
- adjustments.reject { |a| a.adjustable_type == 'Spree::Shipment' }
+ adjustments.reject { |a| a.adjustable_type.in?(%w[Spree::Shipment Spree::Fulfillment]) }
end
def where(array, opts = {})
diff --git a/spree/core/app/models/spree/adjustment.rb b/spree/core/app/models/spree/adjustment.rb
index 923d0ca7ac..f8c1757bba 100644
--- a/spree/core/app/models/spree/adjustment.rb
+++ b/spree/core/app/models/spree/adjustment.rb
@@ -60,7 +60,7 @@ module Spree
where(source_type.not_eq('Spree::TaxRate').or(source_type.eq(nil)))
end
scope :price, -> { where(adjustable_type: 'Spree::LineItem') }
- scope :shipping, -> { where(adjustable_type: 'Spree::Shipment') }
+ scope :shipping, -> { where(adjustable_type: %w[Spree::Shipment Spree::Fulfillment]) }
scope :optional, -> { where(mandatory: false) }
scope :eligible, -> { where(eligible: true) }
scope :charge, -> { where("#{quoted_table_name}.amount >= 0") }
diff --git a/spree/core/app/models/spree/calculator.rb b/spree/core/app/models/spree/calculator.rb
index e7144602fe..59f36a57b5 100644
--- a/spree/core/app/models/spree/calculator.rb
+++ b/spree/core/app/models/spree/calculator.rb
@@ -21,6 +21,16 @@ module Spree
end
end
+ # Fulfillment replaced Shipment in 6.0; calculators keep their historical
+ # compute_shipment extension point, so fulfillments dispatch to it.
+ def compute_fulfillment(fulfillment)
+ unless respond_to?(:compute_shipment)
+ raise NotImplementedError, "Please implement 'compute_shipment(shipment)' in your calculator: #{self.class.name}"
+ end
+
+ compute_shipment(fulfillment)
+ end
+
# overwrite to provide description for your calculators
def self.description
'Base Calculator'
diff --git a/spree/core/app/models/spree/delivery_method.rb b/spree/core/app/models/spree/delivery_method.rb
new file mode 100644
index 0000000000..c453f242c0
--- /dev/null
+++ b/spree/core/app/models/spree/delivery_method.rb
@@ -0,0 +1,169 @@
+module Spree
+ class DeliveryMethod < Spree.base_class
+ has_prefix_id :dm
+
+ acts_as_paranoid
+ include Spree::CalculatedAdjustments
+ include Spree::Metafields
+ include Spree::Metadata
+ include Spree::DisplayOn
+ if defined?(Spree::VendorConcern)
+ include Spree::VendorConcern
+ end
+ include Spree::MemoizedData
+
+ extend Spree::DisplayMoney
+
+ MEMOIZED_METHODS = %w[display_estimated_price]
+
+ # Used for #refresh_rates
+ DISPLAY_ON_FRONT_END = 1
+ DISPLAY_ON_BACK_END = 2
+
+ default_scope { where(deleted_at: nil) }
+
+ has_many :shipping_method_categories, foreign_key: :shipping_method_id, dependent: :destroy
+ has_many :shipping_categories, through: :shipping_method_categories
+ has_many :delivery_rates, class_name: 'Spree::DeliveryRate', inverse_of: :delivery_method
+ has_many :fulfillments, through: :delivery_rates, class_name: 'Spree::Fulfillment'
+
+ has_many :delivery_method_zones, class_name: 'Spree::DeliveryMethodZone',
+ foreign_key: 'delivery_method_id'
+ has_many :delivery_zones, through: :delivery_method_zones, class_name: 'Spree::DeliveryZone'
+
+ belongs_to :tax_category, -> { with_deleted }, class_name: 'Spree::TaxCategory', optional: true
+
+ attribute :fulfillment_type, :string, default: 'shipping'
+ attribute :fulfillment_provider, :string, default: 'Spree::FulfillmentProvider::Manual'
+
+ scope :by_fulfillment_type, ->(type) { where(fulfillment_type: type) }
+
+ # Legacy association names — removed in 6.1.
+ has_many :shipping_rates, class_name: 'Spree::DeliveryRate', foreign_key: :delivery_method_id, deprecated: true
+ has_many :shipments, through: :delivery_rates, source: :fulfillment, deprecated: true
+ has_many :zones, through: :delivery_method_zones, source: :delivery_zone, deprecated: true
+
+ validates :name, :display_on, :fulfillment_type, presence: true
+ validates :estimated_transit_business_days_min, numericality: { greater_than_or_equal_to: 1 }, allow_nil: true
+ validates :estimated_transit_business_days_max, numericality: { greater_than_or_equal_to: 1 }, allow_nil: true
+
+ scope :digital, -> { by_fulfillment_type('digital') }
+
+ scope :search_by_name, ->(query) { where(arel_table[:name].lower.matches("%#{query}%")) }
+
+ def include?(address)
+ return true unless requires_zone_check?
+ return false unless address
+ return true if delivery_zones.empty?
+
+ delivery_zones.includes(:members).any? do |zone|
+ zone.include?(address)
+ end
+ end
+
+ def requires_zone_check?
+ !digital? && !pickup?
+ end
+
+ def build_tracking_url(tracking)
+ return if tracking.blank?
+
+ tracking = tracking.upcase
+
+ # build tracking url automatically
+ if tracking_url.blank?
+ # use tracking number gem to build tracking url
+ # we need to upcase the tracking number
+ # https://github.com/jkeen/tracking_number/pull/85
+ tracking_number_service(tracking).tracking_url if tracking_number_service(tracking).valid?
+ else
+ # build tracking url manually
+ tracking_url.gsub(/:tracking/, ERB::Util.url_encode(tracking)) # :url_encode exists in 1.8.7 through 2.1.0
+ end
+ end
+
+ # your shipping method subclasses can override this method to provide a custom tracking number service
+ def tracking_number_service(tracking)
+ @tracking_number_service ||= Spree.tracking_number_service.new(tracking)
+ end
+
+ def pickup?
+ fulfillment_type == 'pickup'
+ end
+
+ def pickup_point?
+ fulfillment_type == 'pickup_point'
+ end
+
+ def requires_address?
+ !digital? && !pickup?
+ end
+
+ # The FulfillmentProvider strategy handling this method's fulfillments.
+ # Falls back to Manual for rows created before the 6.0 backfill ran.
+ def provider
+ @provider ||= (fulfillment_provider.presence || 'Spree::FulfillmentProvider::Manual').constantize.new
+ end
+
+ def self.calculators
+ # calculator registry key keeps its historical name
+ spree_calculators.shipping_methods.
+ select { |c| c.to_s.constantize < Spree::ShippingCalculator }
+ end
+
+ def available_to_display?(display_filter)
+ (frontend? && display_filter == DISPLAY_ON_FRONT_END) ||
+ (backend? && display_filter == DISPLAY_ON_BACK_END)
+ end
+
+ def delivery_range
+ return unless estimated_transit_business_days_min || estimated_transit_business_days_max
+
+ if estimated_transit_business_days_min == estimated_transit_business_days_max
+ estimated_transit_business_days_min.to_s
+ else
+ [estimated_transit_business_days_min, estimated_transit_business_days_max].compact.join("-")
+ end
+ end
+
+ def display_estimated_price
+ return unless calculator
+
+ @display_estimated_price ||= begin
+ calculator.description + ': ' +
+
+ if calculator.is_a?(Spree::Calculator::Shipping::FlatRate)
+ if calculator.preferred_amount == 0
+ Spree.t(:free)
+ else
+ Spree::Money.new(calculator.preferred_amount, { currency: calculator.preferred_currency }).to_s
+ end
+ elsif calculator.is_a?(Spree::Calculator::Shipping::FlexiRate)
+ Spree::Money.new(calculator.preferred_first_item, { currency: calculator.preferred_currency }).to_s
+ elsif calculator.is_a?(Spree::Calculator::Shipping::FlatPercentItemTotal)
+ ActionController::Base.helpers.number_to_percentage(calculator.preferred_flat_percent, precision: 2)
+ else
+ ''
+ end
+ end
+ end
+
+ # Returns true if the delivery method delivers digitally
+ #
+ # @return [Boolean]
+ def digital?
+ fulfillment_type == 'digital'
+ end
+
+ private
+
+ # Some shipping methods are only meant to be set via backend
+ def frontend?
+ display_on.in?(['both', 'front_end'])
+ end
+
+ def backend?
+ display_on.in?(['both', 'back_end'])
+ end
+ end
+end
diff --git a/spree/core/app/models/spree/delivery_method_zone.rb b/spree/core/app/models/spree/delivery_method_zone.rb
new file mode 100644
index 0000000000..14a7a65009
--- /dev/null
+++ b/spree/core/app/models/spree/delivery_method_zone.rb
@@ -0,0 +1,8 @@
+module Spree
+ class DeliveryMethodZone < Spree.base_class
+ belongs_to :delivery_method, -> { with_deleted }, inverse_of: :delivery_method_zones, class_name: 'Spree::DeliveryMethod'
+ belongs_to :delivery_zone, inverse_of: :delivery_method_zones, class_name: 'Spree::DeliveryZone'
+
+ validates :delivery_method, uniqueness: { scope: :delivery_zone }
+ end
+end
diff --git a/spree/core/app/models/spree/delivery_rate.rb b/spree/core/app/models/spree/delivery_rate.rb
new file mode 100644
index 0000000000..6c56c2c727
--- /dev/null
+++ b/spree/core/app/models/spree/delivery_rate.rb
@@ -0,0 +1,105 @@
+module Spree
+ class DeliveryRate < Spree.base_class
+ has_prefix_id :dr
+
+ belongs_to :fulfillment, class_name: 'Spree::Fulfillment'
+ belongs_to :tax_rate, -> { with_deleted }, class_name: 'Spree::TaxRate'
+ belongs_to :delivery_method, -> { with_deleted }, class_name: 'Spree::DeliveryMethod', inverse_of: :delivery_rates
+ # Legacy names — removed in 6.1.
+ belongs_to :shipment, class_name: 'Spree::Fulfillment', foreign_key: :fulfillment_id, optional: true, deprecated: true
+ belongs_to :shipping_method, -> { with_deleted }, class_name: 'Spree::DeliveryMethod', foreign_key: :delivery_method_id, optional: true, deprecated: true
+ alias_attribute :shipment_id, :fulfillment_id
+ alias_attribute :shipping_method_id, :delivery_method_id
+
+ extend Spree::DisplayMoney
+
+ money_methods :base_price, :final_price, :tax_amount, :additional_tax_total, :included_tax_total, :tax_total
+
+ delegate :order, :currency, :with_free_shipping_promotion?, to: :fulfillment
+ delegate :name, to: :delivery_method
+ delegate :code, to: :delivery_method, prefix: true
+
+ def display_price
+ price = display_base_price.to_s
+
+ return price if tax_rate.nil? || tax_amount.zero? || !tax_rate.show_rate_in_label
+
+ Spree.t(
+ tax_rate.included_in_price? ? :including_tax : :excluding_tax,
+ scope: 'shipping_rates.display_price',
+ price: price,
+ tax_amount: display_tax_amount,
+ tax_rate_name: tax_rate.name
+ )
+ end
+ alias display_cost display_price
+ alias_attribute :base_price, :cost
+
+ # Returns true if the shipping rate is free
+ #
+ # @return [Boolean]
+ def free?
+ final_price.zero?
+ end
+
+ # Returns the tax amount for the shipping rate
+ #
+ # @return [BigDecimal]
+ def tax_amount
+ @tax_amount ||= tax_rate&.calculator&.compute_shipping_rate(self) || BigDecimal(0)
+ end
+
+ # Returns the additional tax total for the shipping rate
+ #
+ # @return [BigDecimal]
+ def additional_tax_total
+ tax_rate&.included_in_price? ? BigDecimal(0) : tax_amount
+ end
+
+ # Returns the included tax total for the shipping rate
+ #
+ # @return [BigDecimal]
+ def included_tax_total
+ tax_rate&.included_in_price? ? tax_amount : BigDecimal(0)
+ end
+
+ alias tax_total tax_amount
+ alias display_tax_total display_tax_amount
+
+ # returns base price - any available discounts for this Shipment
+ # useful when you want to present a list of available shipping rates
+ def final_price
+ if with_free_shipping_promotion? || cost < -discount_amount
+ BigDecimal(0)
+ else
+ cost + discount_amount
+ end
+ end
+ alias total final_price
+ alias display_total display_final_price
+
+ # Returns the delivery range for the shipping method
+ #
+ # @return [String]
+ def delivery_range
+ return unless delivery_method.delivery_range
+
+ delivery_method.delivery_range
+ end
+
+ # Returns the display delivery range for the shipping method
+ #
+ # @return [String]
+ def display_delivery_range
+ return unless delivery_range
+
+ Spree.t(:display_delivery_range, delivery_range: delivery_range)
+ end
+
+ private
+
+ def discount_amount
+ fulfillment.adjustments.promotion.sum(:amount)
+ end
+ end
+end
diff --git a/spree/core/app/models/spree/delivery_zone.rb b/spree/core/app/models/spree/delivery_zone.rb
index 4359c6923d..36b335a729 100644
--- a/spree/core/app/models/spree/delivery_zone.rb
+++ b/spree/core/app/models/spree/delivery_zone.rb
@@ -7,6 +7,8 @@ module Spree
attribute :metadata, default: -> { {} }
has_many :members, class_name: 'Spree::DeliveryZoneMember', dependent: :destroy, inverse_of: :delivery_zone
+ has_many :delivery_method_zones, class_name: 'Spree::DeliveryMethodZone', dependent: :destroy, inverse_of: :delivery_zone
+ has_many :delivery_methods, through: :delivery_method_zones, class_name: 'Spree::DeliveryMethod'
validates :name, presence: true, uniqueness: { scope: spree_base_uniqueness_scope }
diff --git a/spree/core/app/models/spree/exchange.rb b/spree/core/app/models/spree/exchange.rb
index d417270a46..7185840e34 100644
--- a/spree/core/app/models/spree/exchange.rb
+++ b/spree/core/app/models/spree/exchange.rb
@@ -20,13 +20,13 @@ module Spree
def perform!
new_exchange_inventory_units = @reimbursement_objects.map(&:build_default_exchange_inventory_unit)
shipments = Spree::Stock::Coordinator.new(@order, new_exchange_inventory_units).shipments
- shipments_units = shipments.flat_map(&:inventory_units)
+ shipments_units = shipments.flat_map(&:fulfillment_items)
if shipments_units.sum(&:quantity) != new_exchange_inventory_units.sum(&:quantity)
raise UnableToCreateShipments, 'Could not generate shipments for all items. Out of stock?'
end
- @order.shipments += shipments
+ @order.fulfillments += shipments
@order.save!
shipments.each do |shipment|
diff --git a/spree/core/app/models/spree/fulfillment.rb b/spree/core/app/models/spree/fulfillment.rb
new file mode 100644
index 0000000000..4f130637d1
--- /dev/null
+++ b/spree/core/app/models/spree/fulfillment.rb
@@ -0,0 +1,622 @@
+require 'ostruct'
+
+module Spree
+ class Fulfillment < Spree.base_class
+ has_prefix_id :ful
+
+ include Spree::Core::NumberGenerator.new(prefix: 'F', length: 11)
+ include Spree::NumberIdentifier
+ include Spree::Metafields
+ include Spree::Metadata
+ if defined?(Spree::Security::Shipments)
+ include Spree::Security::Shipments
+ end
+ if defined?(Spree::VendorConcern)
+ include Spree::VendorConcern
+ end
+ include Spree::Fulfillment::Webhooks
+ include Spree::Fulfillment::CustomEvents
+
+ publishes_lifecycle_events
+
+ with_options inverse_of: :fulfillments do
+ belongs_to :address, class_name: 'Spree::Address'
+ belongs_to :order, class_name: 'Spree::Order', touch: true
+ end
+ belongs_to :stock_location, -> { with_deleted }, class_name: 'Spree::StockLocation'
+
+ with_options dependent: :delete_all do
+ has_many :adjustments, as: :adjustable
+ has_many :fulfillment_items, class_name: 'Spree::FulfillmentItem', inverse_of: :fulfillment
+ has_many :delivery_rates, -> { order(:cost) }, class_name: 'Spree::DeliveryRate'
+ has_many :state_changes, as: :stateful
+ end
+ has_many :delivery_methods, through: :delivery_rates
+ has_many :variants, through: :fulfillment_items
+ has_one :selected_delivery_rate, -> { where(selected: true).order(:cost) }, class_name: 'Spree::DeliveryRate'
+
+ after_save :update_adjustments
+
+ before_validation :set_cost_zero_when_nil
+
+ validates :stock_location, presence: true
+
+ attr_accessor :special_instructions
+
+ accepts_nested_attributes_for :address
+ accepts_nested_attributes_for :fulfillment_items
+
+ scope :pending, -> { with_state('pending') }
+ scope :ready, -> { with_state('ready') }
+ scope :fulfilled, -> { with_state('fulfilled') }
+ # @deprecated legacy name — remove in 6.1
+ scope :shipped, -> { fulfilled }
+ scope :ready_or_pending, -> { where(status: %w(ready pending)) }
+ scope :trackable, -> { where("tracking IS NOT NULL AND tracking != ''") }
+ scope :with_state, ->(*s) { where(status: s) }
+ # sort by most recent fulfilled_at, falling back to created_at. add "id desc" to make specs that involve this scope more deterministic.
+ scope :reverse_chronological, -> { order(Arel.sql("coalesce(#{table_name}.fulfilled_at, #{table_name}.created_at) desc"), id: :desc) }
+ scope :valid, -> { where.not(status: :canceled) }
+ scope :canceled, -> { with_state('canceled') }
+ scope :not_canceled, -> { where.not(status: 'canceled') }
+ scope :shipped_but_canceled, -> { canceled.where.not(fulfilled_at: nil) }
+ # This scope will select the delivery_method_id from the fulfillments' selected delivery rate
+ scope :with_selected_delivery_method, lambda {
+ joins(:selected_delivery_rate).
+ where(Spree::DeliveryRate.arel_table[:delivery_method_id].not_eq(nil)).
+ select(Spree::DeliveryRate.arel_table[:delivery_method_id])
+ }
+ scope :digital_delivery, -> { joins(:delivery_methods).merge(Spree::DeliveryMethod.digital) }
+
+ delegate :store, :currency, to: :order
+ delegate :amount_in_cents, to: :display_cost
+
+ state_machine :status, initial: :pending, use_transactions: false do
+ event :ready do
+ transition from: :pending, to: :ready, if: lambda { |fulfillment|
+ # Fix for #2040
+ fulfillment.determine_state(fulfillment.order) == 'ready'
+ }
+ end
+
+ event :pend do
+ transition from: :ready, to: :pending
+ end
+
+ event :mark_ready_for_pickup do
+ transition from: :ready, to: :ready_for_pickup
+ end
+
+ event :fulfill do
+ transition from: %i(ready ready_for_pickup canceled), to: :fulfilled
+ end
+ after_transition to: :fulfilled, do: [:after_fulfill, :send_shipment_shipped_webhook, :publish_shipment_shipped_event]
+
+ event :cancel do
+ transition to: :canceled, from: %i(pending ready ready_for_pickup)
+ end
+ after_transition to: :canceled, do: [:after_cancel, :publish_shipment_canceled_event]
+
+ event :resume do
+ transition from: :canceled, to: :ready, if: lambda { |fulfillment|
+ fulfillment.determine_state(fulfillment.order) == 'ready'
+ }
+ transition from: :canceled, to: :pending
+ end
+ after_transition from: :canceled, to: %i(pending ready fulfilled), do: [:after_resume, :publish_shipment_resumed_event]
+
+ after_transition do |fulfillment, transition|
+ fulfillment.state_changes.create!(
+ previous_state: transition.from,
+ next_state: transition.to,
+ name: 'fulfillment'
+ )
+ end
+ end
+
+ # @deprecated Use {#fulfill}; removed in 6.1.
+ def ship(*args)
+ Spree::Deprecation.warn('Spree::Fulfillment#ship is deprecated and will be removed in Spree 6.1. Use #fulfill instead.')
+ fulfill(*args)
+ end
+
+ # @deprecated Use {#fulfill!}; removed in 6.1.
+ def ship!(*args)
+ Spree::Deprecation.warn('Spree::Fulfillment#ship! is deprecated and will be removed in Spree 6.1. Use #fulfill! instead.')
+ fulfill!(*args)
+ end
+
+ # @deprecated Use {#can_fulfill?}; removed in 6.1.
+ def can_ship?
+ Spree::Deprecation.warn('Spree::Fulfillment#can_ship? is deprecated and will be removed in Spree 6.1. Use #can_fulfill? instead.')
+ can_fulfill?
+ end
+
+ # @deprecated Use {#fulfilled?}; removed in 6.1.
+ def shipped?
+ Spree::Deprecation.warn('Spree::Fulfillment#shipped? is deprecated and will be removed in Spree 6.1. Use #fulfilled? instead.')
+ fulfilled?
+ end
+ # @deprecated the column is +status+ since 6.0
+ alias_attribute :state, :status
+ alias_attribute :shipped_at, :fulfilled_at
+ # Legacy association names — removed in 6.1.
+ has_many :inventory_units, class_name: 'Spree::FulfillmentItem', foreign_key: :fulfillment_id, inverse_of: :fulfillment, deprecated: true
+ has_many :shipping_rates, -> { order(:cost) }, class_name: 'Spree::DeliveryRate', foreign_key: :fulfillment_id, deprecated: true
+ has_one :selected_shipping_rate, -> { where(selected: true).order(:cost) }, class_name: 'Spree::DeliveryRate', foreign_key: :fulfillment_id, deprecated: true
+ has_many :shipping_methods, through: :delivery_rates, source: :delivery_method, deprecated: true
+
+ self.whitelisted_ransackable_attributes = ['number']
+
+ extend DisplayMoney
+ money_methods :cost, :discounted_cost, :final_price, :item_cost, :additional_tax_total, :included_tax_total, :tax_total, :promo_total
+ alias display_amount display_cost
+ alias_attribute :discount_total, :promo_total
+ alias display_discount_total display_promo_total
+
+ normalizes :tracking, with: ->(value) { value&.to_s&.squish&.presence }
+
+ # Returns the shipment number and shipping method name
+ #
+ # @return [String]
+ def name
+ [number, delivery_method&.name].compact.join(' ').strip
+ end
+
+ def amount
+ cost
+ end
+
+ # Strict decimal bridge for string input — raises ArgumentError on
+ # malformed values instead of letting Rails' cast silently truncate
+ # ("12 boxes" would otherwise become 12.0). Blank strings cast to nil,
+ # matching the default Rails behavior.
+ #
+ # @param value [String, Numeric, nil]
+ def cost=(value)
+ value = value.blank? ? nil : BigDecimal(value.strip) if value.is_a?(String)
+ super
+ end
+
+ def digital?
+ delivery_method&.digital? || false
+ end
+
+ # @deprecated Use {#delivery_method}; removed in 6.1.
+ def shipping_method
+ Spree::Deprecation.warn('Spree::Fulfillment#shipping_method is deprecated and will be removed in Spree 6.1. Use #delivery_method instead.')
+ delivery_method
+ end
+
+ def add_delivery_method(delivery_method, selected = false)
+ delivery_rates.create(delivery_method: delivery_method, selected: selected, cost: cost)
+ end
+
+ # @deprecated Use {#add_delivery_method}; removed in 6.1.
+ def add_shipping_method(delivery_method, selected = false)
+ Spree::Deprecation.warn('Spree::Fulfillment#add_shipping_method is deprecated and will be removed in Spree 6.1. Use #add_delivery_method instead.')
+ add_delivery_method(delivery_method, selected)
+ end
+
+ def after_cancel
+ manifest.each { |item| manifest_restock(item) }
+ end
+
+ def after_resume
+ manifest.each { |item| manifest_unstock(item) }
+ end
+
+ # Returns true if the shipment has any backordered inventory units
+ #
+ # @return [Boolean]
+ def backordered?
+ fulfillment_items.any?(&:backordered?)
+ end
+
+ # Returns true if the shipment is tracked
+ #
+ # @return [Boolean]
+ def tracked?
+ tracking.present? || tracking_url.present?
+ end
+
+ # Returns true if the shipment is shippable
+ #
+ # @return [Boolean]
+ def shippable?
+ can_fulfill? && (tracked? || digital?)
+ end
+
+ # Returns true if not all of the shipment's line items are fully shipped
+ #
+ # @return [Boolean]
+ def partial?
+ manifest.any? do |manifest_item|
+ line_item = manifest_item.line_item
+ line_item.quantity > manifest_item.quantity
+ end
+ end
+
+ # Determines the appropriate +state+ according to the following logic:
+ #
+ # pending unless order is complete and +order.payment_state+ is +paid+
+ # shipped if already shipped (ie. does not change the state)
+ # ready all other cases
+ def determine_state(order)
+ return 'canceled' if canceled? || order.canceled?
+ return 'pending' unless order.can_ship?
+ return 'pending' if fulfillment_items.any?(&:backordered?)
+ return 'fulfilled' if fulfilled?
+
+ order.paid? || Spree::Config[:auto_capture_on_dispatch] ? 'ready' : 'pending'
+ end
+
+ def discounted_cost
+ cost + promo_total
+ end
+ alias discounted_amount discounted_cost
+
+ # Returns the amount this shipment is taxed on: its discounted cost,
+ # never negative (stacked shipping promotions can push discounted_cost
+ # below zero). Whole-order promotions are not allocated to shipments.
+ #
+ # @return [BigDecimal]
+ def taxable_basis
+ [discounted_cost, BigDecimal(0)].max
+ end
+
+ def final_price
+ cost + adjustment_total
+ end
+ alias total final_price
+ alias display_total display_final_price
+
+ def final_price_with_items
+ item_cost + final_price
+ end
+
+ def free?
+ return true if final_price == BigDecimal(0)
+
+ with_free_shipping_promotion?
+ end
+
+ # Returns true if the shipment has a free shipping promotion applied
+ #
+ # @return [Boolean]
+ def with_free_shipping_promotion?
+ adjustments.promotion.joins("INNER JOIN #{Spree::PromotionAction.table_name} ON #{Spree::PromotionAction.table_name}.id = #{Spree::Adjustment.table_name}.source_id").
+ where("#{Spree::PromotionAction.table_name}.type = 'Spree::Promotion::Actions::FreeShipping'").exists?
+ end
+
+ def finalize!
+ fulfillment_items.finalize_units!
+ after_resume
+ end
+
+ def include?(variant)
+ inventory_units_for(variant).present?
+ end
+
+ def inventory_units_for(variant)
+ fulfillment_items.where(variant_id: variant.id)
+ end
+
+ def inventory_units_for_item(line_item, variant = nil)
+ fulfillment_items.where(line_item_id: line_item.id, variant_id: line_item.variant_id || variant.id)
+ end
+
+ # Returns the total quantity of all line items in the shipment
+ def item_quantity
+ manifest.sum(&:quantity)
+ end
+
+ # Returns the cost of the shipment
+ #
+ # @return [BigDecimal]
+ def item_cost
+ manifest.map { |m| (m.line_item.price + (m.line_item.adjustment_total / m.line_item.quantity)) * m.quantity }.sum
+ end
+
+ # Returns the weight of the shipment
+ #
+ # @return [BigDecimal]
+ def item_weight
+ manifest.map { |m| m.line_item.item_weight }.sum
+ end
+
+ # Returns the weight unit of the shipment
+ #
+ # @return [String]
+ def weight_unit
+ manifest.first.line_item.weight_unit
+ end
+
+ def line_items
+ fulfillment_items.includes(:line_item).map(&:line_item).uniq
+ end
+
+ ManifestItem = Struct.new(:line_item, :variant, :quantity, :states)
+
+ def manifest
+ # Grouping by the ID means that we don't have to call out to the association accessor
+ # This makes the grouping by faster because it results in less SQL cache hits.
+ fulfillment_items.group_by(&:variant_id).flat_map do |_variant_id, units|
+ units.group_by(&:line_item_id).filter_map do |_line_item_id, units|
+ line_item = units.first.line_item
+ # Defensively skip orphaned inventory units (line item destroyed
+ # without cascading) so a single bad row doesn't crash callers that
+ # rely on line_item being present (item_cost, item_weight, the admin
+ # shipment manifest view, etc.).
+ next if line_item.nil?
+
+ states = {}
+ units.group_by(&:status).each { |status, iu| states[status] = iu.sum(&:quantity) }
+
+ variant = units.first.variant
+ ManifestItem.new(line_item, variant, units.sum(&:quantity), states)
+ end
+ end
+ end
+
+ def process_order_payments
+ pending_payments = order.pending_payments.
+ sort_by(&:uncaptured_amount).reverse
+
+ shipment_to_pay = final_price_with_items
+ payments_amount = 0
+
+ payments_pool = pending_payments.each_with_object([]) do |payment, pool|
+ break if payments_amount >= shipment_to_pay
+
+ payments_amount += payment.uncaptured_amount
+ pool << payment
+ end
+
+ payments_pool.each do |payment|
+ capturable_amount = if payment.amount >= shipment_to_pay
+ shipment_to_pay
+ else
+ payment.amount
+ end
+
+ cents = (capturable_amount * 100).to_i
+ payment.capture!(cents)
+ shipment_to_pay -= capturable_amount
+ end
+ end
+
+ def ready_or_pending?
+ ready? || pending?
+ end
+
+ def refresh_rates(shipping_method_filter = DeliveryMethod::DISPLAY_ON_FRONT_END)
+ return delivery_rates if fulfilled?
+ return [] unless can_get_rates?
+
+ # StockEstimator.new assignment below will replace the current delivery_method
+ original_shipping_method_id = delivery_method.try(:id)
+
+ self.delivery_rates = Stock::Estimator.new(order).
+ shipping_rates(to_package, shipping_method_filter)
+
+ if delivery_method
+ selected_rate = delivery_rates.detect do |rate|
+ if original_shipping_method_id
+ rate.delivery_method_id == original_shipping_method_id
+ else
+ rate.selected
+ end
+ end
+ save!
+ self.selected_shipping_rate_id = selected_rate.id if selected_rate
+ reload
+ end
+
+ delivery_rates
+ end
+
+ # Public API v3 name for the selected rate (see docs/plans/6.0-fulfillment-and-delivery.md).
+ #
+ # @return [String, nil] the selected delivery rate's prefixed ID
+ def selected_delivery_rate_id
+ selected_delivery_rate&.prefixed_id
+ end
+
+ # Selects a delivery rate by its public prefixed ID (+dr_...+); raw IDs
+ # are accepted for internal callers. The model owns this naming bridge so
+ # API clients never deal with the legacy shipping-rate name.
+ #
+ # @param id [String, Integer] delivery rate prefixed or raw ID
+ def selected_delivery_rate_id=(id)
+ rate = Spree::PrefixedId.prefixed_id?(id) ? delivery_rates.find_by_prefix_id!(id) : delivery_rates.find(id)
+ self.selected_shipping_rate_id = rate.id
+ end
+
+ def selected_shipping_rate_id
+ selected_delivery_rate.try(:id)
+ end
+
+ def selected_shipping_rate_id=(id)
+ # Explicitly updates the timestamp in order to bust cache dependent on "updated_at"
+ delivery_rates.update_all(selected: false, updated_at: Time.current)
+ delivery_rates.update(id, selected: true)
+ save!
+ # Reload associations to pick up the new selected shipping rate
+ delivery_rates.reset
+ association(:selected_delivery_rate).reset
+ # Update shipment cost and order totals only for incomplete orders (during checkout)
+ # For completed orders, totals are managed separately (e.g., in tests or admin adjustments)
+ return if order.completed?
+
+ update_amounts
+ reload # reload to pick up cost set by update_columns in update_amounts
+ order.set_shipments_cost
+ end
+
+ def set_up_inventory(status, variant, order, line_item, quantity = 1)
+ return if quantity <= 0
+
+ fulfillment_items.create(
+ status: status,
+ variant_id: variant.id,
+ order_id: order.id,
+ line_item_id: line_item.id,
+ quantity: quantity
+ )
+ end
+
+ def shipped=(value)
+ return unless value == '1' && fulfilled_at.nil?
+
+ self.fulfilled_at = Time.current
+ end
+
+ # Returns the shipping method of the selected shipping rate
+ #
+ # @return [Spree::DeliveryMethod]
+ def delivery_method
+ selected_delivery_rate&.delivery_method || delivery_rates.first&.delivery_method
+ end
+
+ # Returns the tax category of the selected shipping rate
+ #
+ # @return [Spree::TaxCategory]
+ def tax_category
+ selected_delivery_rate.try(:tax_rate).try(:tax_category)
+ end
+
+ # Returns the tax category ID of the selected shipping rate
+ #
+ # @return [Integer]
+ def tax_category_id
+ selected_delivery_rate.try(:tax_rate).try(:tax_category_id)
+ end
+
+ # Only one of either included_tax_total or additional_tax_total is set
+ # This method returns the total of the two. Saves having to check if
+ # tax is included or additional.
+ def tax_total
+ included_tax_total + additional_tax_total
+ end
+
+ def to_package
+ package = Stock::Package.new(stock_location)
+ fulfillment_items.includes(:variant).joins(:variant).group_by(&:status).each do |status, units|
+ package.add_multiple units, status.to_sym
+ end
+ package
+ end
+
+ # External systems (3PLs, courier APIs) often hand over a complete
+ # tracking link rather than a bare tracking code — returned as-is
+ # instead of being templated into the delivery method's tracking URL.
+ #
+ # @return [String, nil]
+ def tracking_url
+ @tracking_url ||= if tracking&.start_with?('https://')
+ tracking
+ else
+ delivery_method&.build_tracking_url(tracking)
+ end
+ end
+
+ def update_amounts
+ if selected_delivery_rate
+ update_columns(
+ cost: selected_delivery_rate.cost,
+ adjustment_total: adjustments.additional.map(&:update!).compact.sum,
+ updated_at: Time.current
+ )
+ end
+ end
+
+ def update_attributes_and_order(params = {})
+ Shipments::Update.call(shipment: self, shipment_attributes: params).success?
+ end
+
+ # Updates various aspects of the Shipment while bypassing any callbacks. Note that this method takes an explicit reference to the
+ # Order object. This is necessary because the association actually has a stale (and unsaved) copy of the Order and so it will not
+ # yield the correct results.
+ def update!(order)
+ old_status = status
+ new_status = determine_state(order)
+ update_columns(
+ status: new_status,
+ updated_at: Time.current
+ )
+ after_fulfill if new_status == 'fulfilled' && old_status != 'fulfilled'
+ end
+
+ def transfer_to_location(variant, quantity, stock_location)
+ transfer_to_shipment(
+ variant,
+ quantity,
+ order.shipments.build(stock_location: stock_location)
+ )
+ end
+
+ def transfer_to_shipment(variant, quantity, shipment_to_transfer_to)
+ Spree::FulfillmentChanger.new(
+ current_stock_location: stock_location,
+ desired_stock_location: shipment_to_transfer_to.stock_location,
+ current_shipment: self,
+ desired_shipment: shipment_to_transfer_to,
+ variant: variant,
+ quantity: quantity
+ )
+ end
+
+ private
+
+ # Inlined from the removed ShipmentHandler (its name-constantize factory
+ # could never match a real subclass); FulfillmentProvider takes over the
+ # type-specific mechanics in the provider wave.
+ def after_fulfill
+ fulfillment_items.each(&:ship!)
+ process_order_payments if Spree::Config[:auto_capture_on_dispatch]
+ touch :fulfilled_at
+ update_order_fulfillment_status
+ end
+
+ def update_order_fulfillment_status
+ new_status = OrderUpdater.new(order).update_fulfillment_status
+ order.update_columns(fulfillment_status: new_status, updated_at: Time.current)
+ end
+
+ # publish_shipment_shipped_event, publish_shipment_canceled_event, and
+ # publish_shipment_resumed_event are defined in Spree::Fulfillment::CustomEvents
+
+ def can_get_rates?
+ return true unless order.requires_ship_address?
+
+ order.ship_address&.valid?
+ end
+
+ def manifest_restock(item)
+ if item.states['on_hand'].to_i.positive?
+ stock_location.restock item.variant, item.states['on_hand'], self
+ end
+
+ if item.states['backordered'].to_i.positive?
+ stock_location.restock_backordered item.variant, item.states['backordered']
+ end
+ end
+
+ def manifest_unstock(item)
+ stock_location.unstock(item.variant, item.quantity, self) if item.variant.track_inventory?
+ end
+
+ def recalculate_adjustments
+ Adjustable::AdjustmentsUpdater.update(self)
+ end
+
+ def set_cost_zero_when_nil
+ self.cost = 0 unless cost
+ end
+
+ def update_adjustments
+ recalculate_adjustments if saved_change_to_cost? && state != 'fulfilled'
+ end
+ end
+end
diff --git a/spree/core/app/models/spree/shipment/custom_events.rb b/spree/core/app/models/spree/fulfillment/custom_events.rb
similarity index 97%
rename from spree/core/app/models/spree/shipment/custom_events.rb
rename to spree/core/app/models/spree/fulfillment/custom_events.rb
index 2ede330c7e..1ca760aff5 100644
--- a/spree/core/app/models/spree/shipment/custom_events.rb
+++ b/spree/core/app/models/spree/fulfillment/custom_events.rb
@@ -1,7 +1,7 @@
# frozen_string_literal: true
module Spree
- class Shipment < Spree.base_class
+ class Fulfillment < Spree.base_class
# Publishes custom shipment events beyond basic lifecycle events.
#
# Events:
diff --git a/spree/core/app/models/spree/shipment/webhooks.rb b/spree/core/app/models/spree/fulfillment/webhooks.rb
similarity index 81%
rename from spree/core/app/models/spree/shipment/webhooks.rb
rename to spree/core/app/models/spree/fulfillment/webhooks.rb
index a9c0553772..af5cff1c6f 100644
--- a/spree/core/app/models/spree/shipment/webhooks.rb
+++ b/spree/core/app/models/spree/fulfillment/webhooks.rb
@@ -1,5 +1,5 @@
module Spree
- class Shipment < Spree.base_class
+ class Fulfillment < Spree.base_class
module Webhooks
extend ActiveSupport::Concern
diff --git a/spree/core/app/models/spree/fulfillment_changer.rb b/spree/core/app/models/spree/fulfillment_changer.rb
new file mode 100644
index 0000000000..9f975399e9
--- /dev/null
+++ b/spree/core/app/models/spree/fulfillment_changer.rb
@@ -0,0 +1,166 @@
+module Spree
+ class FulfillmentChanger
+ include ActiveModel::Validations
+
+ validates :quantity, numericality: { greater_than: 0 }
+ validates :desired_stock_location, presence: true
+ validate :current_shipment_not_already_shipped
+ validate :desired_shipment_different_from_current
+ validate :enough_stock_at_desired_location, if: :handle_stock_counts?
+
+ def initialize(params = {})
+ @current_stock_location = params[:current_stock_location]
+ @desired_stock_location = params[:desired_stock_location]
+ @current_shipment = params[:current_shipment]
+ @desired_shipment = params[:desired_shipment]
+ @variant = params[:variant]
+ @quantity = params[:quantity]
+ @available_quantity = [
+ desired_stock_location.try(:count_on_hand, variant).to_i,
+ current_quantity
+ ].max
+ end
+
+ def run!
+ return false if invalid?
+
+ desired_shipment.save! if desired_shipment.new_record?
+
+ handle_stock
+ reload_shipment_inventory_units
+ after_process_shipments
+
+ true
+ end
+
+ private
+
+ attr_reader :variant, :quantity, :current_stock_location, :desired_stock_location,
+ :current_shipment, :desired_shipment, :available_quantity
+
+ def handle_stock
+ ActiveRecord::Base.transaction do
+ if handle_stock_counts?
+ current_stock_location.restock(variant, current_on_hand_quantity, current_shipment)
+ desired_stock_location.unstock(variant, unstock_quantity, desired_shipment)
+ end
+
+ move_inventory_units_between_shipments
+ end
+ end
+
+ def move_inventory_units_between_shipments
+ update_desired_shipment_inventory_units
+ update_current_shipment_inventory_units
+ end
+
+ def current_shipment_units
+ @current_shipment_units ||= current_shipment.fulfillment_items.on_hand_or_backordered.where(variant_id: variant.id)
+ end
+
+ def update_desired_shipment_inventory_units
+ on_hand_unit = get_desired_shipment_inventory_unit(:on_hand)
+ on_hand_unit.update(quantity: on_hand_unit.quantity + new_on_hand_quantity)
+
+ new_backorder_quantity = current_on_hand_quantity - new_on_hand_quantity
+ if new_backorder_quantity > 0
+ backordered_unit = get_desired_shipment_inventory_unit(:backordered)
+ backordered_unit.update(quantity: backordered_unit.quantity + new_backorder_quantity)
+ end
+ end
+
+ def update_current_shipment_inventory_units
+ reduced_quantity = current_on_hand_quantity
+
+ # Reduce quantities from all backordered units first in case there is more than one.
+ backorder_units = current_shipment_units.backordered
+ reduced_quantity = reduce_units_quantities(reduced_quantity, backorder_units) if backorder_units.any?
+
+ # Reduce quantities from all on_hand units in case there is more than one.
+ if reduced_quantity > 0
+ on_hand_units = current_shipment_units.on_hand
+ reduce_units_quantities(reduced_quantity, on_hand_units) if on_hand_units.any?
+ end
+ end
+
+ def reduce_units_quantities(reduced_quantity, units)
+ units.each do |unit|
+ if unit.quantity > reduced_quantity
+ unit.update(quantity: unit.quantity - reduced_quantity)
+ reduced_quantity = 0
+ else
+ reduced_quantity -= unit.quantity
+ unit.destroy!
+ end
+ break if reduced_quantity.zero?
+ end
+ reduced_quantity
+ end
+
+ def get_desired_shipment_inventory_unit(state)
+ desired_shipment.fulfillment_items.find_or_create_by(status: state, variant: variant) do |unit|
+ current_shipment_unit = current_shipment_units.first
+ unit.variant_id = current_shipment_unit.variant_id
+ unit.order_id = current_shipment_unit.order_id
+ unit.line_item_id = current_shipment_unit.line_item_id
+ unit.quantity = 0
+ end
+ end
+
+ def after_process_shipments
+ if current_shipment.fulfillment_items.sum(:quantity).zero?
+ current_shipment.destroy!
+ else
+ current_shipment.refresh_rates
+ end
+
+ desired_shipment.refresh_rates
+ desired_shipment.update_amounts
+
+ desired_shipment.order.reload
+ desired_shipment.order.update_with_updater!
+ end
+
+ def new_on_hand_quantity
+ [available_quantity, current_on_hand_quantity].min
+ end
+
+ def unstock_quantity
+ desired_stock_location.backorderable?(variant) ? quantity : new_on_hand_quantity
+ end
+
+ def current_on_hand_quantity
+ [current_shipment.fulfillment_items.on_hand_or_backordered.sum(:quantity), quantity].min
+ end
+
+ def reload_shipment_inventory_units
+ [current_shipment, desired_shipment].each { |shipment| shipment.fulfillment_items.reload }
+ end
+
+ def current_quantity
+ desired_stock_location == current_stock_location ? quantity : 0
+ end
+
+ def handle_stock_counts?
+ current_shipment.order.completed? && current_stock_location != desired_stock_location
+ end
+
+ def current_shipment_not_already_shipped
+ return unless current_shipment.shipped?
+
+ errors.add(:current_shipment, :has_already_been_shipped)
+ end
+
+ def enough_stock_at_desired_location
+ return if Spree::Stock::Quantifier.new(variant, desired_stock_location).can_supply?(quantity)
+
+ errors.add(:desired_shipment, :has_not_enough_stock_at_desired_location)
+ end
+
+ def desired_shipment_different_from_current
+ return unless desired_shipment.id == current_shipment.id
+
+ errors.add(:desired_shipment, :can_not_transfer_within_same_shipment)
+ end
+ end
+end
diff --git a/spree/core/app/models/spree/fulfillment_item.rb b/spree/core/app/models/spree/fulfillment_item.rb
new file mode 100644
index 0000000000..049189b4f5
--- /dev/null
+++ b/spree/core/app/models/spree/fulfillment_item.rb
@@ -0,0 +1,147 @@
+module Spree
+ class FulfillmentItem < Spree.base_class
+ has_prefix_id :fi
+
+ extend Spree::DisplayMoney
+
+ with_options inverse_of: :fulfillment_items do
+ belongs_to :variant, -> { with_deleted }, class_name: 'Spree::Variant'
+ belongs_to :order, class_name: 'Spree::Order'
+ belongs_to :fulfillment, class_name: 'Spree::Fulfillment', touch: true, optional: true
+ has_many :return_items, class_name: 'Spree::ReturnItem', inverse_of: :fulfillment_item
+ has_many :return_authorizations, class_name: 'Spree::ReturnAuthorization', through: :return_items
+ belongs_to :line_item, class_name: 'Spree::LineItem'
+ end
+
+ belongs_to :original_return_item, class_name: 'Spree::ReturnItem'
+
+ scope :backordered, -> { where status: 'backordered' }
+ scope :on_hand, -> { where status: 'on_hand' }
+ scope :on_hand_or_backordered, -> { where status: ['backordered', 'on_hand'] }
+ scope :shipped, -> { where status: 'shipped' }
+ scope :returned, -> { where status: 'returned' }
+ scope :backordered_per_variant, ->(stock_item) do
+ includes(:fulfillment, :order).
+ where.not(Spree::Fulfillment.table_name => { status: 'canceled' }).
+ where(variant_id: stock_item.variant_id).
+ where.not(spree_orders: { completed_at: nil }).
+ backordered.order('spree_orders.completed_at ASC')
+ end
+
+ # Legacy names — removed in 6.1.
+ belongs_to :shipment, class_name: 'Spree::Fulfillment', foreign_key: :fulfillment_id, optional: true, touch: true, deprecated: true
+ alias_attribute :shipment_id, :fulfillment_id
+ # @deprecated the column is +status+ since 6.0
+ alias_attribute :state, :status
+
+ validates :quantity, numericality: { greater_than: 0 }
+
+ money_methods :charged_amount
+
+ # state machine (see http://github.com/pluginaweek/state_machine/tree/master for details)
+ state_machine :status, initial: :on_hand do
+ event :fill_backorder do
+ transition to: :on_hand, from: :backordered
+ end
+ after_transition on: :fill_backorder, do: :fulfill_order
+
+ event :ship do
+ transition to: :shipped, if: :allow_ship?
+ end
+
+ event :return do
+ transition to: :returned, from: :shipped
+ end
+ end
+
+ # This was refactored from a simpler query because the previous implementation
+ # led to issues once users tried to modify the objects returned. That's due
+ # to ActiveRecord `joins(shipment: :stock_location)` only returning readonly
+ # objects
+ #
+ # Returns an array of backordered inventory units as per a given stock item
+ def self.backordered_for_stock_item(stock_item)
+ backordered_per_variant(stock_item).select do |unit|
+ unit.fulfillment.stock_location == stock_item.stock_location
+ end
+ end
+
+ def self.finalize_units!
+ update_all(pending: false, updated_at: Time.current)
+ end
+
+ def find_stock_item
+ fulfillment.stock_location.stock_item_or_create(variant)
+ end
+
+ def self.split(original_inventory_unit, extract_quantity)
+ split = original_inventory_unit.dup
+ split.quantity = extract_quantity
+ original_inventory_unit.quantity -= extract_quantity
+ split
+ end
+
+ # This will fail if extract >= available_quantity
+ def split_inventory!(extract_quantity)
+ split = self.class.split(self, extract_quantity)
+ transaction do
+ split.save!
+ save!
+ end
+ split
+ end
+
+ def extract_singular_inventory!
+ split_inventory!(1)
+ end
+
+ def current_or_new_return_item
+ Spree::ReturnItem.from_inventory_unit(self)
+ end
+
+ def additional_tax_total
+ line_item.additional_tax_total * percentage_of_line_item
+ end
+
+ def included_tax_total
+ line_item.included_tax_total * percentage_of_line_item
+ end
+
+ def required_quantity
+ return @required_quantity unless @required_quantity.nil?
+
+ @required_quantity = if exchanged_unit?
+ original_return_item.return_quantity
+ else
+ line_item.quantity
+ end
+ end
+
+ def exchanged_unit?
+ original_return_item_id?
+ end
+
+ def charged_amount
+ percentage_of_line_item * line_item.pre_tax_amount
+ end
+
+ def percentage_of_line_item
+ quantity / BigDecimal(line_item.quantity)
+ end
+
+ private
+
+ def allow_ship?
+ on_hand?
+ end
+
+ def fulfill_order
+ reload
+ order.fulfill!
+ end
+
+ def current_return_item
+ return_items.not_cancelled.first
+ end
+ end
+end
diff --git a/spree/core/app/models/spree/fulfilment_changer.rb b/spree/core/app/models/spree/fulfilment_changer.rb
index b420d77313..3463e43cf7 100644
--- a/spree/core/app/models/spree/fulfilment_changer.rb
+++ b/spree/core/app/models/spree/fulfilment_changer.rb
@@ -1,166 +1,5 @@
module Spree
- class FulfilmentChanger
- include ActiveModel::Validations
-
- validates :quantity, numericality: { greater_than: 0 }
- validates :desired_stock_location, presence: true
- validate :current_shipment_not_already_shipped
- validate :desired_shipment_different_from_current
- validate :enough_stock_at_desired_location, if: :handle_stock_counts?
-
- def initialize(params = {})
- @current_stock_location = params[:current_stock_location]
- @desired_stock_location = params[:desired_stock_location]
- @current_shipment = params[:current_shipment]
- @desired_shipment = params[:desired_shipment]
- @variant = params[:variant]
- @quantity = params[:quantity]
- @available_quantity = [
- desired_stock_location.try(:count_on_hand, variant).to_i,
- current_quantity
- ].max
- end
-
- def run!
- return false if invalid?
-
- desired_shipment.save! if desired_shipment.new_record?
-
- handle_stock
- reload_shipment_inventory_units
- after_process_shipments
-
- true
- end
-
- private
-
- attr_reader :variant, :quantity, :current_stock_location, :desired_stock_location,
- :current_shipment, :desired_shipment, :available_quantity
-
- def handle_stock
- ActiveRecord::Base.transaction do
- if handle_stock_counts?
- current_stock_location.restock(variant, current_on_hand_quantity, current_shipment)
- desired_stock_location.unstock(variant, unstock_quantity, desired_shipment)
- end
-
- move_inventory_units_between_shipments
- end
- end
-
- def move_inventory_units_between_shipments
- update_desired_shipment_inventory_units
- update_current_shipment_inventory_units
- end
-
- def current_shipment_units
- @current_shipment_units ||= current_shipment.inventory_units.on_hand_or_backordered.where(variant_id: variant.id)
- end
-
- def update_desired_shipment_inventory_units
- on_hand_unit = get_desired_shipment_inventory_unit(:on_hand)
- on_hand_unit.update(quantity: on_hand_unit.quantity + new_on_hand_quantity)
-
- new_backorder_quantity = current_on_hand_quantity - new_on_hand_quantity
- if new_backorder_quantity > 0
- backordered_unit = get_desired_shipment_inventory_unit(:backordered)
- backordered_unit.update(quantity: backordered_unit.quantity + new_backorder_quantity)
- end
- end
-
- def update_current_shipment_inventory_units
- reduced_quantity = current_on_hand_quantity
-
- # Reduce quantities from all backordered units first in case there is more than one.
- backorder_units = current_shipment_units.backordered
- reduced_quantity = reduce_units_quantities(reduced_quantity, backorder_units) if backorder_units.any?
-
- # Reduce quantities from all on_hand units in case there is more than one.
- if reduced_quantity > 0
- on_hand_units = current_shipment_units.on_hand
- reduce_units_quantities(reduced_quantity, on_hand_units) if on_hand_units.any?
- end
- end
-
- def reduce_units_quantities(reduced_quantity, units)
- units.each do |unit|
- if unit.quantity > reduced_quantity
- unit.update(quantity: unit.quantity - reduced_quantity)
- reduced_quantity = 0
- else
- reduced_quantity -= unit.quantity
- unit.destroy!
- end
- break if reduced_quantity.zero?
- end
- reduced_quantity
- end
-
- def get_desired_shipment_inventory_unit(state)
- desired_shipment.inventory_units.find_or_create_by(state: state, variant: variant) do |unit|
- current_shipment_unit = current_shipment_units.first
- unit.variant_id = current_shipment_unit.variant_id
- unit.order_id = current_shipment_unit.order_id
- unit.line_item_id = current_shipment_unit.line_item_id
- unit.quantity = 0
- end
- end
-
- def after_process_shipments
- if current_shipment.inventory_units.sum(:quantity).zero?
- current_shipment.destroy!
- else
- current_shipment.refresh_rates
- end
-
- desired_shipment.refresh_rates
- desired_shipment.update_amounts
-
- desired_shipment.order.reload
- desired_shipment.order.update_with_updater!
- end
-
- def new_on_hand_quantity
- [available_quantity, current_on_hand_quantity].min
- end
-
- def unstock_quantity
- desired_stock_location.backorderable?(variant) ? quantity : new_on_hand_quantity
- end
-
- def current_on_hand_quantity
- [current_shipment.inventory_units.on_hand_or_backordered.sum(:quantity), quantity].min
- end
-
- def reload_shipment_inventory_units
- [current_shipment, desired_shipment].each { |shipment| shipment.inventory_units.reload }
- end
-
- def current_quantity
- desired_stock_location == current_stock_location ? quantity : 0
- end
-
- def handle_stock_counts?
- current_shipment.order.completed? && current_stock_location != desired_stock_location
- end
-
- def current_shipment_not_already_shipped
- return unless current_shipment.shipped?
-
- errors.add(:current_shipment, :has_already_been_shipped)
- end
-
- def enough_stock_at_desired_location
- return if Spree::Stock::Quantifier.new(variant, desired_stock_location).can_supply?(quantity)
-
- errors.add(:desired_shipment, :has_not_enough_stock_at_desired_location)
- end
-
- def desired_shipment_different_from_current
- return unless desired_shipment.id == current_shipment.id
-
- errors.add(:desired_shipment, :can_not_transfer_within_same_shipment)
- end
- end
+ # Constant alias for the misspelled legacy Spree::FulfilmentChanger,
+ # renamed to Spree::FulfillmentChanger in 6.0. Remove in 6.1.
+ FulfilmentChanger = FulfillmentChanger
end
diff --git a/spree/core/app/models/spree/inventory_unit.rb b/spree/core/app/models/spree/inventory_unit.rb
index 39da3d202d..d91172fc5c 100644
--- a/spree/core/app/models/spree/inventory_unit.rb
+++ b/spree/core/app/models/spree/inventory_unit.rb
@@ -1,141 +1,5 @@
module Spree
- class InventoryUnit < Spree.base_class
- has_prefix_id :fi
-
- extend Spree::DisplayMoney
-
- with_options inverse_of: :inventory_units do
- belongs_to :variant, -> { with_deleted }, class_name: 'Spree::Variant'
- belongs_to :order, class_name: 'Spree::Order'
- belongs_to :shipment, class_name: 'Spree::Shipment', touch: true, optional: true
- has_many :return_items, class_name: 'Spree::ReturnItem', inverse_of: :inventory_unit
- has_many :return_authorizations, class_name: 'Spree::ReturnAuthorization', through: :return_items
- belongs_to :line_item, class_name: 'Spree::LineItem'
- end
-
- belongs_to :original_return_item, class_name: 'Spree::ReturnItem'
-
- scope :backordered, -> { where state: 'backordered' }
- scope :on_hand, -> { where state: 'on_hand' }
- scope :on_hand_or_backordered, -> { where state: ['backordered', 'on_hand'] }
- scope :shipped, -> { where state: 'shipped' }
- scope :returned, -> { where state: 'returned' }
- scope :backordered_per_variant, ->(stock_item) do
- includes(:shipment, :order).
- where.not(spree_shipments: { state: 'canceled' }).
- where(variant_id: stock_item.variant_id).
- where.not(spree_orders: { completed_at: nil }).
- backordered.order('spree_orders.completed_at ASC')
- end
-
- validates :quantity, numericality: { greater_than: 0 }
-
- money_methods :charged_amount
-
- # state machine (see http://github.com/pluginaweek/state_machine/tree/master for details)
- state_machine initial: :on_hand do
- event :fill_backorder do
- transition to: :on_hand, from: :backordered
- end
- after_transition on: :fill_backorder, do: :fulfill_order
-
- event :ship do
- transition to: :shipped, if: :allow_ship?
- end
-
- event :return do
- transition to: :returned, from: :shipped
- end
- end
-
- # This was refactored from a simpler query because the previous implementation
- # led to issues once users tried to modify the objects returned. That's due
- # to ActiveRecord `joins(shipment: :stock_location)` only returning readonly
- # objects
- #
- # Returns an array of backordered inventory units as per a given stock item
- def self.backordered_for_stock_item(stock_item)
- backordered_per_variant(stock_item).select do |unit|
- unit.shipment.stock_location == stock_item.stock_location
- end
- end
-
- def self.finalize_units!
- update_all(pending: false, updated_at: Time.current)
- end
-
- def find_stock_item
- shipment.stock_location.stock_item_or_create(variant)
- end
-
- def self.split(original_inventory_unit, extract_quantity)
- split = original_inventory_unit.dup
- split.quantity = extract_quantity
- original_inventory_unit.quantity -= extract_quantity
- split
- end
-
- # This will fail if extract >= available_quantity
- def split_inventory!(extract_quantity)
- split = self.class.split(self, extract_quantity)
- transaction do
- split.save!
- save!
- end
- split
- end
-
- def extract_singular_inventory!
- split_inventory!(1)
- end
-
- def current_or_new_return_item
- Spree::ReturnItem.from_inventory_unit(self)
- end
-
- def additional_tax_total
- line_item.additional_tax_total * percentage_of_line_item
- end
-
- def included_tax_total
- line_item.included_tax_total * percentage_of_line_item
- end
-
- def required_quantity
- return @required_quantity unless @required_quantity.nil?
-
- @required_quantity = if exchanged_unit?
- original_return_item.return_quantity
- else
- line_item.quantity
- end
- end
-
- def exchanged_unit?
- original_return_item_id?
- end
-
- def charged_amount
- percentage_of_line_item * line_item.pre_tax_amount
- end
-
- def percentage_of_line_item
- quantity / BigDecimal(line_item.quantity)
- end
-
- private
-
- def allow_ship?
- on_hand?
- end
-
- def fulfill_order
- reload
- order.fulfill!
- end
-
- def current_return_item
- return_items.not_cancelled.first
- end
- end
+ # Constant alias for the legacy Spree::InventoryUnit, renamed to
+ # Spree::FulfillmentItem in 6.0. Remove in 6.1.
+ InventoryUnit = FulfillmentItem
end
diff --git a/spree/core/app/models/spree/line_item.rb b/spree/core/app/models/spree/line_item.rb
index 1fd94bfdd9..2e441a71e6 100644
--- a/spree/core/app/models/spree/line_item.rb
+++ b/spree/core/app/models/spree/line_item.rb
@@ -22,8 +22,10 @@ module Spree
has_one :product, -> { with_deleted }, class_name: 'Spree::Product', through: :variant
has_many :adjustments, as: :adjustable, dependent: :destroy
- has_many :inventory_units, class_name: 'Spree::InventoryUnit', inverse_of: :line_item, dependent: :destroy
- has_many :shipments, through: :inventory_units, source: :shipment
+ has_many :fulfillment_items, class_name: 'Spree::FulfillmentItem', inverse_of: :line_item, dependent: :destroy
+ has_many :fulfillments, through: :fulfillment_items, source: :fulfillment
+ has_many :inventory_units, class_name: 'Spree::FulfillmentItem', inverse_of: :line_item, deprecated: true
+ has_many :shipments, through: :fulfillment_items, source: :fulfillment, deprecated: true
has_many :digital_links, dependent: :destroy
has_many :stock_reservations, class_name: 'Spree::StockReservation', inverse_of: :line_item, dependent: :destroy
@@ -218,21 +220,21 @@ module Spree
#
# @return [Boolean]
def any_shipped?
- inventory_units.any?(&:shipped?)
+ fulfillment_items.any?(&:shipped?)
end
# returns true if all of the inventory units are shipped
#
# @return [Boolean]
def fully_shipped?
- inventory_units.all?(&:shipped?)
+ fulfillment_items.all?(&:shipped?)
end
# Returns the shipping cost for the line item
#
# @return [BigDecimal]
def shipping_cost
- shipments.sum do |shipment|
+ fulfillments.sum do |shipment|
# Skip cancelled shipments
return BigDecimal('0') if shipment.canceled?
@@ -240,13 +242,13 @@ module Spree
return BigDecimal('0') if shipment.cost.zero?
# Get total inventory units in this shipment
- total_units = shipment.inventory_units
+ total_units = shipment.fulfillment_items
# Calculate proportional shipping cost
return BigDecimal('0') if total_units.empty?
# Get all inventory units in this shipment for this line item
- line_item_units = shipment.inventory_units.find_all { |unit| unit.line_item_id == id }.count
+ line_item_units = shipment.fulfillment_items.find_all { |unit| unit.line_item_id == id }.count
# Calculate proportional shipping cost
return BigDecimal('0') if line_item_units.zero?
diff --git a/spree/core/app/models/spree/order.rb b/spree/core/app/models/spree/order.rb
index 153d4ded4b..9cad954fce 100644
--- a/spree/core/app/models/spree/order.rb
+++ b/spree/core/app/models/spree/order.rb
@@ -15,7 +15,9 @@ module Spree
self.ignored_columns += ['channel']
PAYMENT_STATES = %w(balance_due credit_owed failed paid void)
- SHIPMENT_STATES = %w(backorder canceled partial pending ready shipped)
+ FULFILLMENT_STATUSES = %w(backorder canceled partial pending ready fulfilled shipped)
+ # @deprecated legacy name — remove in 6.1 together with the 'shipped' value
+ SHIPMENT_STATES = FULFILLMENT_STATUSES
LINE_ITEM_REMOVABLE_STATES = %w(cart address delivery payment confirm resumed)
extend Spree::DisplayMoney
@@ -52,12 +54,12 @@ module Spree
money_methods :outstanding_balance, :item_total, :adjustment_total,
:included_tax_total, :additional_tax_total, :tax_total,
- :shipment_total, :promo_total, :total,
+ :delivery_total, :promo_total, :total,
:cart_promo_total, :pre_tax_item_amount, :pre_tax_total,
:payment_total, :amount_due
- alias display_ship_total display_shipment_total
- alias_attribute :ship_total, :shipment_total
+ alias display_ship_total display_delivery_total
+ alias_attribute :ship_total, :delivery_total
def amount_due
[outstanding_balance - total_applied_store_credit, 0].max
end
@@ -117,9 +119,9 @@ module Spree
# Rails auto-locking must not raise on internal saves.
self.lock_optimistically = false
- self.whitelisted_ransackable_associations = %w[shipments user created_by approver canceler promotions bill_address ship_address line_items store channel tags]
+ self.whitelisted_ransackable_associations = %w[fulfillments shipments user created_by approver canceler promotions bill_address ship_address line_items store channel tags]
self.whitelisted_ransackable_attributes = %w[
- completed_at email number state status payment_status payment_state shipment_state
+ completed_at email number state status payment_status payment_state fulfillment_status shipment_state delivery_total
total item_total item_count considered_risky channel_id currency
]
self.whitelisted_ransackable_scopes = %w[complete incomplete refunded partially_refunded search multi_search]
@@ -191,9 +193,10 @@ module Spree
has_many :reimbursements, inverse_of: :order, class_name: 'Spree::Reimbursement'
has_many :customer_returns, class_name: 'Spree::CustomerReturn', through: :return_authorizations
has_many :line_item_adjustments, through: :line_items, source: :adjustments
- has_many :inventory_units, inverse_of: :order, class_name: 'Spree::InventoryUnit'
+ has_many :fulfillment_items, inverse_of: :order, class_name: 'Spree::FulfillmentItem'
+ has_many :inventory_units, class_name: 'Spree::FulfillmentItem', inverse_of: :order, deprecated: true
has_many :stock_reservations, class_name: 'Spree::StockReservation', inverse_of: :order, dependent: :destroy
- has_many :return_items, through: :inventory_units, class_name: 'Spree::ReturnItem'
+ has_many :return_items, through: :fulfillment_items, class_name: 'Spree::ReturnItem'
has_many :variants, through: :line_items
has_many :products, through: :variants
has_many :refunds, through: :payments
@@ -206,19 +209,21 @@ module Spree
has_many :order_promotions, class_name: 'Spree::OrderPromotion'
has_many :promotions, through: :order_promotions, class_name: 'Spree::Promotion'
- has_many :shipments, class_name: 'Spree::Shipment', dependent: :destroy, inverse_of: :order do
+ has_many :fulfillments, class_name: 'Spree::Fulfillment', dependent: :destroy, inverse_of: :order do
def states
- pluck(:state).uniq
+ pluck(:status).uniq
end
end
- has_many :shipment_adjustments, through: :shipments, source: :adjustments
+ has_many :shipment_adjustments, through: :fulfillments, source: :adjustments
alias items line_items
alias discounts order_promotions
- alias fulfillments shipments
- alias_attribute :delivery_total, :shipment_total
- alias display_delivery_total display_shipment_total
- alias_attribute :fulfillment_status, :shipment_state
+ # Legacy names — removed in 6.1 (real names: fulfillments, delivery_total,
+ # fulfillment_status since 6.0)
+ has_many :shipments, class_name: 'Spree::Fulfillment', inverse_of: :order, deprecated: true
+ alias_attribute :shipment_total, :delivery_total
+ alias display_shipment_total display_delivery_total
+ alias_attribute :shipment_state, :fulfillment_status
# Deprecated alias — the column is payment_status since 6.0; remove in 6.1.
alias_attribute :payment_state, :payment_status
@@ -230,7 +235,9 @@ module Spree
alias shipping_address_attributes= ship_address_attributes=
alias billing_address_attributes= bill_address_attributes=
accepts_nested_attributes_for :payments, reject_if: :credit_card_nil_payment?
- accepts_nested_attributes_for :shipments
+ accepts_nested_attributes_for :fulfillments
+ # @deprecated legacy writer — removed in 6.1
+ alias shipments_attributes= fulfillments_attributes=
# Needs to happen before save_permalink is called
before_validation :ensure_market_presence
@@ -256,13 +263,13 @@ module Spree
validates :locale
end
validates :payment_status, inclusion: { in: PAYMENT_STATES, allow_blank: true }
- validates :shipment_state, inclusion: { in: SHIPMENT_STATES, allow_blank: true }
+ validates :fulfillment_status, inclusion: { in: FULFILLMENT_STATUSES, allow_blank: true }
validates :item_total, POSITIVE_MONEY_VALIDATION
validates :adjustment_total, MONEY_VALIDATION
validates :included_tax_total, POSITIVE_MONEY_VALIDATION
validates :additional_tax_total, POSITIVE_MONEY_VALIDATION
validates :payment_total, MONEY_VALIDATION
- validates :shipment_total, MONEY_VALIDATION
+ validates :delivery_total, MONEY_VALIDATION
validates :promo_total, NEGATIVE_MONEY_VALIDATION
validates :total, MONEY_VALIDATION
validates :market, presence: true, if: :store_has_markets?
@@ -282,10 +289,10 @@ module Spree
scope :incomplete, -> { where(completed_at: nil) }
scope :canceled, -> { where(state: %w[canceled partially_canceled]) }
scope :not_canceled, -> { where.not(state: %w[canceled partially_canceled]) }
- scope :ready_to_ship, -> { where(shipment_state: %w[ready pending]) }
- scope :partially_shipped, -> { where(shipment_state: %w[partial]) }
- scope :not_shipped, -> { where(shipment_state: %w[ready pending partial]) }
- scope :shipped, -> { where(shipment_state: %w[shipped]) }
+ scope :ready_to_ship, -> { where(fulfillment_status: %w[ready pending]) }
+ scope :partially_shipped, -> { where(fulfillment_status: %w[partial]) }
+ scope :not_shipped, -> { where(fulfillment_status: %w[ready pending partial]) }
+ scope :shipped, -> { where(fulfillment_status: %w[fulfilled shipped]) }
scope :refunded, lambda {
joins(:refunds).group(:id).having("sum(#{Spree::Refund.table_name}.amount) = #{Spree::Order.table_name}.total")
}
@@ -381,7 +388,7 @@ module Spree
# Sum of all line item and shipment pre-tax
def pre_tax_total
- pre_tax_item_amount + shipments.sum(:pre_tax_amount)
+ pre_tax_item_amount + fulfillments.sum(:pre_tax_amount)
end
# Returns the subtotal used for analytics integrations
@@ -469,7 +476,7 @@ module Spree
end
def backordered?
- shipments.any?(&:backordered?)
+ fulfillments.any?(&:backordered?)
end
# Check if the shipping address is a quick checkout address
@@ -484,7 +491,7 @@ module Spree
# Either fully digital or not digital at all
# @return [Boolean]
def quick_checkout_available?
- payment_required? && shipments.count <= 1 && (digital? || !some_digital? || !delivery_required?)
+ payment_required? && fulfillments.count <= 1 && (digital? || !some_digital? || !delivery_required?)
end
# Check if quick checkout requires an address collection
@@ -552,7 +559,7 @@ module Spree
def allow_cancel?
return false if !completed? || canceled?
- shipment_state.nil? || %w{ready backorder pending canceled}.include?(shipment_state)
+ fulfillment_status.nil? || %w{ready backorder pending canceled}.include?(fulfillment_status)
end
def all_inventory_units_returned?
@@ -591,11 +598,11 @@ module Spree
# include taxes then price adjustments are created instead.
def create_tax_charge!
Spree::TaxRate.adjust(self, line_items)
- Spree::TaxRate.adjust(self, shipments) if shipments.any?
+ Spree::TaxRate.adjust(self, fulfillments) if fulfillments.any?
end
def create_shipment_tax_charge!
- Spree::TaxRate.adjust(self, shipments) if shipments.any?
+ Spree::TaxRate.adjust(self, fulfillments) if fulfillments.any?
end
def update_line_item_prices!
@@ -675,7 +682,7 @@ module Spree
# update payment and shipment(s) states, and save
updater.update_payment_state
- shipments.each do |shipment|
+ fulfillments.each do |shipment|
shipment.update!(self)
shipment.finalize!
end
@@ -695,7 +702,7 @@ module Spree
end
def fulfill!
- shipments.each { |shipment| shipment.update!(self) if shipment.persisted? }
+ fulfillments.each { |shipment| shipment.update!(self) if shipment.persisted? }
updater.update_shipment_state
save!
end
@@ -790,27 +797,27 @@ module Spree
end
def shipped?
- %w(partial shipped).include?(shipment_state)
+ %w(partial shipped fulfilled).include?(fulfillment_status)
end
def fully_shipped?
- shipments.shipped.size == shipments.size
+ fulfillments.fulfilled.size == fulfillments.size
end
def create_proposed_shipments
all_adjustments.shipping.delete_all
- shipment_ids = shipments.map(&:id)
- StateChange.where(stateful_type: 'Spree::Shipment', stateful_id: shipment_ids).delete_all
- ShippingRate.where(shipment_id: shipment_ids).delete_all
+ shipment_ids = fulfillments.map(&:id)
+ StateChange.where(stateful_type: %w[Spree::Shipment Spree::Fulfillment], stateful_id: shipment_ids).delete_all
+ DeliveryRate.where(fulfillment_id: shipment_ids).delete_all
- shipments.delete_all
+ fulfillments.delete_all
# Inventory Units which are not associated to any shipment (unshippable)
# and are not returned or shipped should be deleted
- inventory_units.on_hand_or_backordered.delete_all
+ fulfillment_items.on_hand_or_backordered.delete_all
- self.shipments = order_routing_strategy.for_allocation.map do |package|
+ self.fulfillments = order_routing_strategy.for_allocation.map do |package|
package.to_shipment.tap { |s| s.address_id = ship_address_id }
end
end
@@ -852,7 +859,7 @@ module Spree
#
# @return [Array<Spree::LineItem>]
def line_items_without_shipping_rates
- @line_items_without_shipping_rates ||= shipments.map do |shipment|
+ @line_items_without_shipping_rates ||= fulfillments.map do |shipment|
shipment.manifest.map(&:line_item) if shipment.shipping_rates.blank?
end.flatten.compact
end
@@ -866,7 +873,7 @@ module Spree
def apply_free_shipping_promotions
Spree::PromotionHandler::FreeShipping.new(self).activate
- shipments.each { |shipment| Spree::Adjustable::AdjustmentsUpdater.update(shipment) }
+ fulfillments.each { |shipment| Spree::Adjustable::AdjustmentsUpdater.update(shipment) }
create_shipment_tax_charge!
update_with_updater!
end
@@ -882,9 +889,9 @@ module Spree
# to delivery again so that proper updated shipments are created.
# e.g. customer goes back from payment step and changes order items
def ensure_updated_shipments
- if shipments.any? && !completed?
- shipments.destroy_all
- update_column(:shipment_total, 0)
+ if fulfillments.any? && !completed?
+ fulfillments.destroy_all
+ update_column(:delivery_total, 0)
# Manually publish update event since update_column bypasses callbacks
publish_event('order.updated')
@@ -905,8 +912,8 @@ module Spree
next! unless line_items.empty?
end
- def refresh_shipment_rates(shipping_method_filter = ShippingMethod::DISPLAY_ON_FRONT_END)
- shipments.map { |s| s.refresh_rates(shipping_method_filter) }
+ def refresh_shipment_rates(shipping_method_filter = DeliveryMethod::DISPLAY_ON_FRONT_END)
+ fulfillments.map { |s| s.refresh_rates(shipping_method_filter) }
end
def shipping_eq_billing_address?
@@ -914,8 +921,8 @@ module Spree
end
def set_shipments_cost
- shipments.each(&:update_amounts)
- updater.update_shipment_total
+ fulfillments.each(&:update_amounts)
+ updater.update_delivery_total
updater.update_adjustment_total
persist_totals
end
@@ -923,8 +930,8 @@ module Spree
def shipping_method
# This query will select the first available shipping method from the shipments.
# It will use subquery to first select the shipping method id from the shipments' selected_shipping_rate.
- Spree::ShippingMethod.
- where(id: shipments.with_selected_shipping_method.limit(1).pluck(:shipping_method_id)).
+ Spree::DeliveryMethod.
+ where(id: fulfillments.with_selected_delivery_method.limit(1).pluck(:delivery_method_id)).
limit(1).
first
end
@@ -1050,7 +1057,7 @@ module Spree
# @return [BigDecimal]
def cart_promo_total
all_adjustments.eligible.nonzero.promotion.
- where.not(adjustable_type: 'Spree::Shipment').
+ where.not(adjustable_type: %w[Spree::Shipment Spree::Fulfillment]).
sum(:amount)
end
@@ -1113,10 +1120,10 @@ module Spree
end
def ensure_available_shipping_rates
- if shipments.empty? || line_items_without_shipping_rates.present?
+ if fulfillments.empty? || line_items_without_shipping_rates.present?
# After this point, order redirects back to 'address' state and asks user to pick a proper address
# Therefore, shipments are not necessary at this point.
- shipments.destroy_all
+ fulfillments.destroy_all
if line_items_without_shipping_rates.present?
errors.add(:base, Spree.t(:products_cannot_be_shipped, product_names: line_items_without_shipping_rates.map(&:name).to_sentence))
@@ -1140,7 +1147,7 @@ module Spree
def after_cancel
update_column(:status, 'canceled')
- shipments.each(&:cancel!)
+ fulfillments.each(&:cancel!)
# payments fully covered by gift card won't be refunded
# we want to only void the payment
@@ -1159,7 +1166,7 @@ module Spree
def after_resume
update_column(:status, 'placed')
- shipments.each(&:resume!)
+ fulfillments.each(&:resume!)
consider_risk
send_order_resumed_webhook
publish_order_resumed_event
diff --git a/spree/core/app/models/spree/order_inventory.rb b/spree/core/app/models/spree/order_inventory.rb
index 600e26e549..fb9947363e 100644
--- a/spree/core/app/models/spree/order_inventory.rb
+++ b/spree/core/app/models/spree/order_inventory.rb
@@ -8,7 +8,13 @@ module Spree
@variant = line_item.variant
end
- delegate :inventory_units, to: :line_item
+ delegate :fulfillment_items, to: :line_item
+
+ # @deprecated Use {#fulfillment_items}; removed in 6.1.
+ def inventory_units
+ Spree::Deprecation.warn('Spree::OrderInventory#inventory_units is deprecated and will be removed in Spree 6.1. Use #fulfillment_items instead.')
+ fulfillment_items
+ end
# Only verify inventory for completed orders (as orders in frontend checkout
# have inventory assigned via +order.create_proposed_shipment+) or when
@@ -20,13 +26,13 @@ module Spree
def verify(shipment = nil, is_updated: false, removing: false)
return unless order.completed? || shipment.present?
- units_count = inventory_units.reload.sum(&:quantity)
+ units_count = fulfillment_items.reload.sum(&:quantity)
line_item_changed = is_updated ? !line_item.saved_changes? : !line_item.changed?
if removing
# When the line item is being destroyed, only remove existing inventory.
# Adding here would create units that the LineItem `dependent: :destroy`
- # cascade can't see (set_up_inventory writes through shipment.inventory_units,
+ # cascade can't see (set_up_inventory writes through shipment.fulfillment_items,
# leaving line_item.inventory_units stale), producing an orphaned unit.
#
# Bypass `remove` because it routes through `set_quantity_to_remove` which
@@ -51,7 +57,7 @@ module Spree
if target_shipment.present?
remove_from_shipment(target_shipment, quantity)
else
- order.shipments.each do |shipment|
+ order.fulfillments.each do |shipment|
break if quantity.zero?
quantity -= remove_from_shipment(shipment, quantity)
@@ -63,7 +69,7 @@ module Spree
if target_shipment.present?
remove_from_shipment(target_shipment, quantity)
else
- order.shipments.each do |shipment|
+ order.fulfillments.each do |shipment|
break if quantity.zero?
quantity -= remove_from_shipment(shipment, quantity)
@@ -84,11 +90,11 @@ module Spree
# first unshipped that already includes this variant
# first unshipped that's leaving from a stock_location that stocks this variant
def determine_target_shipment
- target_shipment = order.shipments.detect do |shipment|
+ target_shipment = order.fulfillments.detect do |shipment|
shipment.ready_or_pending? && shipment.include?(variant)
end
- target_shipment || order.shipments.detect do |shipment|
+ target_shipment || order.fulfillments.detect do |shipment|
shipment.ready_or_pending? && variant.stock_location_ids.include?(shipment.stock_location_id)
end
end
@@ -116,7 +122,7 @@ module Spree
def remove_from_shipment(shipment, quantity)
return 0 if quantity.zero? || shipment.shipped?
- shipment_units = shipment.inventory_units_for_item(line_item, variant).reject(&:shipped?).sort_by(&:state)
+ shipment_units = shipment.inventory_units_for_item(line_item, variant).reject(&:shipped?).sort_by(&:status)
removed_quantity = 0
removed_backordered = 0
@@ -136,7 +142,7 @@ module Spree
inventory_unit.save! if inventory_unit.persisted?
end
- shipment.destroy if shipment.inventory_units.sum(:quantity).zero?
+ shipment.destroy if shipment.fulfillment_items.sum(:quantity).zero?
# removing this from shipment, and adding to stock_location
if order.completed?
diff --git a/spree/core/app/models/spree/order_updater.rb b/spree/core/app/models/spree/order_updater.rb
index d66b4958c2..cf9e5e749d 100644
--- a/spree/core/app/models/spree/order_updater.rb
+++ b/spree/core/app/models/spree/order_updater.rb
@@ -1,7 +1,7 @@
module Spree
class OrderUpdater
attr_reader :order
- delegate :payments, :line_items, :adjustments, :all_adjustments, :shipments, :update_hooks, :quantity, to: :order
+ delegate :payments, :line_items, :adjustments, :all_adjustments, :fulfillments, :update_hooks, :quantity, to: :order
def initialize(order)
@order = order
@@ -19,9 +19,9 @@ module Spree
update_totals
if order.completed?
update_payment_state
- update_shipments
- update_shipment_state
- update_shipment_total
+ update_fulfillments
+ update_fulfillment_status
+ update_delivery_total
end
run_hooks
persist_totals
@@ -51,11 +51,11 @@ module Spree
update_adjustment_total
end
- # give each of the shipments a chance to update themselves
- def update_shipments
- shipping_method_filter = order.completed? ? ShippingMethod::DISPLAY_ON_BACK_END : ShippingMethod::DISPLAY_ON_FRONT_END
+ # give each of the fulfillments a chance to update themselves
+ def update_fulfillments
+ shipping_method_filter = order.completed? ? DeliveryMethod::DISPLAY_ON_BACK_END : DeliveryMethod::DISPLAY_ON_FRONT_END
- shipments.each do |shipment|
+ fulfillments.each do |shipment|
next unless shipment.persisted?
shipment.update!(order)
@@ -68,13 +68,13 @@ module Spree
order.payment_total = payments.completed.includes(:refunds).inject(0) { |sum, payment| sum + payment.amount - payment.refunds.sum(:amount) }
end
- def update_shipment_total
- order.shipment_total = shipments.to_a.sum(&:cost)
+ def update_delivery_total
+ order.delivery_total = fulfillments.to_a.sum(&:cost)
update_order_total
end
def update_order_total
- order.total = order.item_total + order.shipment_total + order.adjustment_total
+ order.total = order.item_total + order.delivery_total + order.adjustment_total
end
def update_adjustment_total
@@ -90,7 +90,7 @@ module Spree
) || [0, 0, 0, 0]
# Fetch all shipment totals in a single query
- shipment_totals = shipments.reorder(nil).pick(
+ shipment_totals = fulfillments.reorder(nil).pick(
Arel.sql('COALESCE(SUM(adjustment_total), 0)'),
Arel.sql('COALESCE(SUM(included_tax_total), 0)'),
Arel.sql('COALESCE(SUM(additional_tax_total), 0)'),
@@ -122,59 +122,72 @@ module Spree
def persist_totals
order.update_columns(
- payment_state: order.payment_state,
- shipment_state: order.shipment_state,
+ payment_status: order.payment_status,
+ fulfillment_status: order.fulfillment_status,
item_total: order.item_total,
item_count: order.item_count,
adjustment_total: order.adjustment_total,
included_tax_total: order.included_tax_total,
additional_tax_total: order.additional_tax_total,
payment_total: order.payment_total,
- shipment_total: order.shipment_total,
+ delivery_total: order.delivery_total,
promo_total: order.promo_total,
total: order.total,
updated_at: Time.current
)
end
- # Updates the +shipment_state+ attribute according to the following logic:
+ # Updates the +fulfillment_status+ attribute according to the following logic:
#
- # shipped when all Shipments are in the "shipped" state
- # partial when at least one Shipment has a state of "shipped" and there is another Shipment with a state other than "shipped"
- # or there are InventoryUnits associated with the order that have a state of "sold" but are not associated with a Shipment.
- # ready when all Shipments are in the "ready" state
+ # fulfilled when all Fulfillments are in the "fulfilled" status
+ # partial when at least one Fulfillment is "fulfilled" and there is another
+ # Fulfillment with a status other than "fulfilled"
+ # ready when all Fulfillments are "ready" (ready_for_pickup rolls up as ready)
# backorder when there is backordered inventory associated with an order
- # pending when all Shipments are in the "pending" state
+ # pending when all Fulfillments are "pending"
#
- # The +shipment_state+ value helps with reporting, etc. since it provides a quick and easy way to locate Orders needing attention.
- def update_shipment_state
+ # The +fulfillment_status+ value helps with reporting, etc. since it provides a quick and easy way to locate Orders needing attention.
+ def update_fulfillment_status
if order.backordered?
- order.shipment_state = 'backorder'
+ order.fulfillment_status = 'backorder'
else
- # get all the shipment states for this order
- shipment_states = shipments.states.uniq
-
- order.shipment_state = if shipment_states.size > 1
- if shipment_states.include?('shipped')
- 'partial'
- elsif shipment_states.include?('pending')
- 'pending'
- else
- 'ready'
- end
- else
- # will return nil if no shipments are found
- shipment_states.first
- # TODO: inventory unit states?
- # if order.shipment_state && order.inventory_units.where(shipment_id: nil).exists?
- # shipments exist but there are unassigned inventory units
- # order.shipment_state = 'partial'
- # end
- end
+ # ready_for_pickup is customer-actionable on the fulfillment itself but
+ # rolls up as ready at the order level
+ statuses = fulfillments.states.uniq.map { |status| status == 'ready_for_pickup' ? 'ready' : status }.uniq
+
+ order.fulfillment_status = if statuses.size > 1
+ if statuses.include?('fulfilled')
+ 'partial'
+ elsif statuses.include?('pending')
+ 'pending'
+ else
+ 'ready'
+ end
+ else
+ # will return nil if no fulfillments are found
+ statuses.first
+ end
end
order.state_changed('shipment')
- order.shipment_state
+ order.fulfillment_status
+ end
+ # @deprecated Use {#update_fulfillment_status}; removed in 6.1.
+ def update_shipment_state
+ Spree::Deprecation.warn('Spree::OrderUpdater#update_shipment_state is deprecated and will be removed in Spree 6.1. Use #update_fulfillment_status instead.')
+ update_fulfillment_status
+ end
+
+ # @deprecated Use {#update_delivery_total}; removed in 6.1.
+ def update_shipment_total
+ Spree::Deprecation.warn('Spree::OrderUpdater#update_shipment_total is deprecated and will be removed in Spree 6.1. Use #update_delivery_total instead.')
+ update_delivery_total
+ end
+
+ # @deprecated Use {#update_fulfillments}; removed in 6.1.
+ def update_shipments
+ Spree::Deprecation.warn('Spree::OrderUpdater#update_shipments is deprecated and will be removed in Spree 6.1. Use #update_fulfillments instead.')
+ update_fulfillments
end
# Updates the +payment_state+ attribute according to the following logic:
diff --git a/spree/core/app/models/spree/payment.rb b/spree/core/app/models/spree/payment.rb
index 892c55d861..fbe1722420 100644
--- a/spree/core/app/models/spree/payment.rb
+++ b/spree/core/app/models/spree/payment.rb
@@ -371,8 +371,8 @@ module Spree
if order.completed?
order.updater.update_payment_state
- order.updater.update_shipments
- order.updater.update_shipment_state
+ order.updater.update_fulfillments
+ order.updater.update_fulfillment_status
end
order.persist_totals if completed? || order.completed?
diff --git a/spree/core/app/models/spree/product.rb b/spree/core/app/models/spree/product.rb
index e7012704ae..af3d95d05c 100644
--- a/spree/core/app/models/spree/product.rb
+++ b/spree/core/app/models/spree/product.rb
@@ -123,9 +123,9 @@ module Spree
source: :promotion
belongs_to :tax_category, class_name: 'Spree::TaxCategory'
- belongs_to :shipping_category, class_name: 'Spree::ShippingCategory', inverse_of: :products
+ belongs_to :shipping_category, class_name: 'Spree::ShippingCategory', inverse_of: :products, optional: true
belongs_to :product_type, class_name: 'Spree::ProductType', optional: true, counter_cache: :products_count
- has_many :shipping_methods, through: :shipping_category, class_name: 'Spree::ShippingMethod'
+ has_many :shipping_methods, through: :shipping_category, class_name: 'Spree::DeliveryMethod'
# Every product has at least one variant. `default_variant` is the "face" of
# the product (price display, default add-to-cart, property delegation).
@@ -158,8 +158,6 @@ module Spree
after_initialize :assign_default_tax_category
- before_validation :ensure_default_shipping_category
-
after_create :sync_associations_from_product_type
after_create :apply_pending_variants, if: :pending_variants?
after_create :ensure_default_variant
@@ -178,7 +176,6 @@ module Spree
end
with_options presence: true do
validates :name
- validates :shipping_category, if: :requires_shipping_category?
end
# Every persisted product must keep a default variant. It's assigned on
@@ -655,7 +652,15 @@ module Spree
#
# @return [Boolean]
def digital?
- @digital ||= shipping_category&.includes_digital_shipping_method?
+ @digital ||= fulfillment_types == ['digital']
+ end
+
+ # The fulfillment types this product may be delivered by, from its
+ # ProductType; typeless products default to physical shipping.
+ #
+ # @return [Array<String>]
+ def fulfillment_types
+ product_type&.fulfillment_types.presence || ['shipping']
end
def auto_match_collections
@@ -898,15 +903,6 @@ module Spree
self.tax_category = Spree::TaxCategory.default if new_record? && self[:tax_category_id].blank?
end
- def ensure_default_shipping_category
- return if shipping_category.present?
-
- if new_record?
- name = I18n.t('spree.seed.shipping.categories.default')
- self.shipping_category = Spree::ShippingCategory.find_or_create_by!(name: name)
- end
- end
-
def run_touch_callbacks
run_callbacks(:touch)
end
@@ -943,10 +939,6 @@ module Spree
end
end
- def requires_shipping_category?
- true
- end
-
def eligible_for_collection_matching?
previously_new_record? || tag_list_previously_changed? || available_on_previously_changed?
end
diff --git a/spree/core/app/models/spree/reimbursement_tax_calculator.rb b/spree/core/app/models/spree/reimbursement_tax_calculator.rb
index ddd8c51871..a0aeb41c58 100644
--- a/spree/core/app/models/spree/reimbursement_tax_calculator.rb
+++ b/spree/core/app/models/spree/reimbursement_tax_calculator.rb
@@ -10,7 +10,7 @@ module Spree
class ReimbursementTaxCalculator
class << self
def call(reimbursement)
- reimbursement.return_items.includes(:inventory_unit).each do |return_item|
+ reimbursement.return_items.includes(:fulfillment_item).each do |return_item|
set_tax!(return_item)
end
end
diff --git a/spree/core/app/models/spree/return_authorization.rb b/spree/core/app/models/spree/return_authorization.rb
index d69e5982c9..b5fbdd1f69 100644
--- a/spree/core/app/models/spree/return_authorization.rb
+++ b/spree/core/app/models/spree/return_authorization.rb
@@ -11,9 +11,10 @@ module Spree
has_many :return_items, inverse_of: :return_authorization, dependent: :destroy
with_options through: :return_items do
- has_many :inventory_units
+ has_many :fulfillment_items, class_name: 'Spree::FulfillmentItem'
has_many :customer_returns
end
+ has_many :inventory_units, through: :return_items, source: :fulfillment_item, deprecated: true
has_many :reimbursements, through: :customer_returns
has_many :refunds, through: :reimbursements
diff --git a/spree/core/app/models/spree/return_item.rb b/spree/core/app/models/spree/return_item.rb
index 85dd03f316..0c7969099a 100644
--- a/spree/core/app/models/spree/return_item.rb
+++ b/spree/core/app/models/spree/return_item.rb
@@ -27,22 +27,26 @@ module Spree
with_options inverse_of: :return_items do
belongs_to :return_authorization
- belongs_to :inventory_unit
+ belongs_to :fulfillment_item, class_name: 'Spree::FulfillmentItem'
belongs_to :customer_return
belongs_to :reimbursement
end
- has_many :exchange_inventory_units, class_name: 'Spree::InventoryUnit',
+ # @deprecated legacy names — remove in 6.1
+ alias_method :inventory_unit, :fulfillment_item
+ alias_method :inventory_unit=, :fulfillment_item=
+ alias_attribute :inventory_unit_id, :fulfillment_item_id
+ has_many :exchange_inventory_units, class_name: 'Spree::FulfillmentItem',
foreign_key: :original_return_item_id,
inverse_of: :original_return_item
belongs_to :exchange_variant, class_name: 'Spree::Variant'
belongs_to :preferred_reimbursement_type, class_name: 'Spree::ReimbursementType'
belongs_to :override_reimbursement_type, class_name: 'Spree::ReimbursementType'
- has_one :line_item, through: :inventory_unit
+ has_one :line_item, through: :fulfillment_item
validate :eligible_exchange_variant
validate :belongs_to_same_customer_order
validate :validate_acceptance_status_for_reimbursement
- validates :inventory_unit, presence: true
+ validates :fulfillment_item, presence: true
validate :validate_no_other_completed_return_items, on: :create
validates :return_quantity, numericality: { greater_than_or_equal_to: 1 }
validate :sufficient_quantity_for_return
@@ -62,7 +66,7 @@ module Spree
scope :not_reimbursed, -> { where(reimbursement_id: nil) }
scope :exchange_requested, -> { where.not(exchange_variant: nil) }
scope :exchange_processed, -> { joins(:exchange_inventory_units).distinct }
- scope :exchange_required, -> { eager_load(:exchange_inventory_units).where(spree_inventory_units: { original_return_item_id: nil }).distinct }
+ scope :exchange_required, -> { eager_load(:exchange_inventory_units).where(Spree::FulfillmentItem.table_name => { original_return_item_id: nil }).distinct }
scope :resellable, -> { where resellable: true }
if Rails::VERSION::STRING >= '7.1.0'
@@ -134,8 +138,8 @@ module Spree
end
def self.from_inventory_unit(inventory_unit)
- not_cancelled.find_by(inventory_unit: inventory_unit) ||
- new(inventory_unit: inventory_unit).tap(&:set_default_pre_tax_amount)
+ not_cancelled.find_by(fulfillment_item: inventory_unit) ||
+ new(fulfillment_item: inventory_unit).tap(&:set_default_pre_tax_amount)
end
def exchange_requested?
diff --git a/spree/core/app/models/spree/return_item/eligibility_validator/no_reimbursements.rb b/spree/core/app/models/spree/return_item/eligibility_validator/no_reimbursements.rb
index 61a10ca93a..29fbce37c0 100644
--- a/spree/core/app/models/spree/return_item/eligibility_validator/no_reimbursements.rb
+++ b/spree/core/app/models/spree/return_item/eligibility_validator/no_reimbursements.rb
@@ -1,7 +1,7 @@
module Spree
class ReturnItem::EligibilityValidator::NoReimbursements < Spree::ReturnItem::EligibilityValidator::BaseValidator
def eligible_for_return?
- if Spree::ReturnItem.where(inventory_unit: @return_item.inventory_unit).where.not(reimbursement_id: nil).any?
+ if Spree::ReturnItem.where(fulfillment_item: @return_item.fulfillment_item).where.not(reimbursement_id: nil).any?
add_error(:inventory_unit_reimbursed, Spree.t('return_item_inventory_unit_reimbursed'))
false
else
diff --git a/spree/core/app/models/spree/shipment.rb b/spree/core/app/models/spree/shipment.rb
index 8e7a5f60bf..74f6a5df65 100644
--- a/spree/core/app/models/spree/shipment.rb
+++ b/spree/core/app/models/spree/shipment.rb
@@ -1,562 +1,5 @@
-require 'ostruct'
-
module Spree
- class Shipment < Spree.base_class
- has_prefix_id :ful
-
- include Spree::Core::NumberGenerator.new(prefix: 'H', length: 11)
- include Spree::NumberIdentifier
- include Spree::Metafields
- include Spree::Metadata
- if defined?(Spree::Security::Shipments)
- include Spree::Security::Shipments
- end
- if defined?(Spree::VendorConcern)
- include Spree::VendorConcern
- end
- include Spree::Shipment::Webhooks
- include Spree::Shipment::CustomEvents
-
- publishes_lifecycle_events
-
- with_options inverse_of: :shipments do
- belongs_to :address, class_name: 'Spree::Address'
- belongs_to :order, class_name: 'Spree::Order', touch: true
- end
- belongs_to :stock_location, -> { with_deleted }, class_name: 'Spree::StockLocation'
-
- with_options dependent: :delete_all do
- has_many :adjustments, as: :adjustable
- has_many :inventory_units, inverse_of: :shipment
- has_many :shipping_rates, -> { order(:cost) }
- has_many :state_changes, as: :stateful
- end
- has_many :shipping_methods, through: :shipping_rates
- has_many :variants, through: :inventory_units
- has_one :selected_shipping_rate, -> { where(selected: true).order(:cost) }, class_name: Spree::ShippingRate.to_s
-
- after_save :update_adjustments
-
- before_validation :set_cost_zero_when_nil
-
- validates :stock_location, presence: true
-
- attr_accessor :special_instructions
-
- accepts_nested_attributes_for :address
- accepts_nested_attributes_for :inventory_units
-
- scope :pending, -> { with_state('pending') }
- scope :ready, -> { with_state('ready') }
- scope :shipped, -> { with_state('shipped') }
- scope :ready_or_pending, -> { where(state: %w(ready pending)) }
- scope :trackable, -> { where("tracking IS NOT NULL AND tracking != ''") }
- scope :with_state, ->(*s) { where(state: s) }
- # sort by most recent shipped_at, falling back to created_at. add "id desc" to make specs that involve this scope more deterministic.
- scope :reverse_chronological, -> { order(Arel.sql('coalesce(spree_shipments.shipped_at, spree_shipments.created_at) desc'), id: :desc) }
- scope :valid, -> { where.not(state: :canceled) }
- scope :canceled, -> { with_state('canceled') }
- scope :not_canceled, -> { where.not(state: 'canceled') }
- scope :shipped_but_canceled, -> { canceled.where.not(shipped_at: nil) }
- # This scope will select the shipping_method_id from the shipments' selected shipping rate
- scope :with_selected_shipping_method, lambda {
- joins(:selected_shipping_rate).
- where(Spree::ShippingRate.arel_table[:shipping_method_id].not_eq(nil)).
- select(Spree::ShippingRate.arel_table[:shipping_method_id])
- }
- scope :digital_delivery, -> { joins(:shipping_methods).merge(Spree::ShippingMethod.digital) }
-
- delegate :store, :currency, to: :order
- delegate :amount_in_cents, to: :display_cost
-
- # shipment state machine (see http://github.com/pluginaweek/state_machine/tree/master for details)
- state_machine initial: :pending, use_transactions: false do
- event :ready do
- transition from: :pending, to: :ready, if: lambda { |shipment|
- # Fix for #2040
- shipment.determine_state(shipment.order) == 'ready'
- }
- end
-
- event :pend do
- transition from: :ready, to: :pending
- end
-
- event :ship do
- transition from: %i(ready canceled), to: :shipped
- end
- after_transition to: :shipped, do: [:after_ship, :send_shipment_shipped_webhook, :publish_shipment_shipped_event]
-
- event :cancel do
- transition to: :canceled, from: %i(pending ready)
- end
- after_transition to: :canceled, do: [:after_cancel, :publish_shipment_canceled_event]
-
- event :resume do
- transition from: :canceled, to: :ready, if: lambda { |shipment|
- shipment.determine_state(shipment.order) == 'ready'
- }
- transition from: :canceled, to: :pending
- end
- after_transition from: :canceled, to: %i(pending ready shipped), do: [:after_resume, :publish_shipment_resumed_event]
-
- after_transition do |shipment, transition|
- shipment.state_changes.create!(
- previous_state: transition.from,
- next_state: transition.to,
- name: 'shipment'
- )
- end
- end
-
- self.whitelisted_ransackable_attributes = ['number']
-
- extend DisplayMoney
- money_methods :cost, :discounted_cost, :final_price, :item_cost, :additional_tax_total, :included_tax_total, :tax_total, :promo_total
- alias display_amount display_cost
- alias_attribute :discount_total, :promo_total
- alias display_discount_total display_promo_total
-
- normalizes :tracking, with: ->(value) { value&.to_s&.squish&.presence }
-
- # Returns the shipment number and shipping method name
- #
- # @return [String]
- def name
- [number, shipping_method&.name].compact.join(' ').strip
- end
-
- def amount
- cost
- end
-
- # Strict decimal bridge for string input — raises ArgumentError on
- # malformed values instead of letting Rails' cast silently truncate
- # ("12 boxes" would otherwise become 12.0). Blank strings cast to nil,
- # matching the default Rails behavior.
- #
- # @param value [String, Numeric, nil]
- def cost=(value)
- value = value.blank? ? nil : BigDecimal(value.strip) if value.is_a?(String)
- super
- end
-
- def digital?
- shipping_method&.digital? || false
- end
-
- def add_shipping_method(shipping_method, selected = false)
- shipping_rates.create(shipping_method: shipping_method, selected: selected, cost: cost)
- end
-
- def after_cancel
- manifest.each { |item| manifest_restock(item) }
- end
-
- def after_resume
- manifest.each { |item| manifest_unstock(item) }
- end
-
- # Returns true if the shipment has any backordered inventory units
- #
- # @return [Boolean]
- def backordered?
- inventory_units.any?(&:backordered?)
- end
-
- # Returns true if the shipment is tracked
- #
- # @return [Boolean]
- def tracked?
- tracking.present? || tracking_url.present?
- end
-
- # Returns true if the shipment is shippable
- #
- # @return [Boolean]
- def shippable?
- can_ship? && (tracked? || digital?)
- end
-
- # Returns true if not all of the shipment's line items are fully shipped
- #
- # @return [Boolean]
- def partial?
- manifest.any? do |manifest_item|
- line_item = manifest_item.line_item
- line_item.quantity > manifest_item.quantity
- end
- end
-
- # Determines the appropriate +state+ according to the following logic:
- #
- # pending unless order is complete and +order.payment_state+ is +paid+
- # shipped if already shipped (ie. does not change the state)
- # ready all other cases
- def determine_state(order)
- return 'canceled' if canceled? || order.canceled?
- return 'pending' unless order.can_ship?
- return 'pending' if inventory_units.any?(&:backordered?)
- return 'shipped' if shipped?
-
- order.paid? || Spree::Config[:auto_capture_on_dispatch] ? 'ready' : 'pending'
- end
-
- def discounted_cost
- cost + promo_total
- end
- alias discounted_amount discounted_cost
-
- # Returns the amount this shipment is taxed on: its discounted cost,
- # never negative (stacked shipping promotions can push discounted_cost
- # below zero). Whole-order promotions are not allocated to shipments.
- #
- # @return [BigDecimal]
- def taxable_basis
- [discounted_cost, BigDecimal(0)].max
- end
-
- def final_price
- cost + adjustment_total
- end
- alias total final_price
- alias display_total display_final_price
-
- def final_price_with_items
- item_cost + final_price
- end
-
- def free?
- return true if final_price == BigDecimal(0)
-
- with_free_shipping_promotion?
- end
-
- # Returns true if the shipment has a free shipping promotion applied
- #
- # @return [Boolean]
- def with_free_shipping_promotion?
- adjustments.promotion.joins("INNER JOIN #{Spree::PromotionAction.table_name} ON #{Spree::PromotionAction.table_name}.id = #{Spree::Adjustment.table_name}.source_id").
- where("#{Spree::PromotionAction.table_name}.type = 'Spree::Promotion::Actions::FreeShipping'").exists?
- end
-
- def finalize!
- inventory_units.finalize_units!
- after_resume
- end
-
- def include?(variant)
- inventory_units_for(variant).present?
- end
-
- def inventory_units_for(variant)
- inventory_units.where(variant_id: variant.id)
- end
-
- def inventory_units_for_item(line_item, variant = nil)
- inventory_units.where(line_item_id: line_item.id, variant_id: line_item.variant_id || variant.id)
- end
-
- # Returns the total quantity of all line items in the shipment
- def item_quantity
- manifest.sum(&:quantity)
- end
-
- # Returns the cost of the shipment
- #
- # @return [BigDecimal]
- def item_cost
- manifest.map { |m| (m.line_item.price + (m.line_item.adjustment_total / m.line_item.quantity)) * m.quantity }.sum
- end
-
- # Returns the weight of the shipment
- #
- # @return [BigDecimal]
- def item_weight
- manifest.map { |m| m.line_item.item_weight }.sum
- end
-
- # Returns the weight unit of the shipment
- #
- # @return [String]
- def weight_unit
- manifest.first.line_item.weight_unit
- end
-
- def line_items
- inventory_units.includes(:line_item).map(&:line_item).uniq
- end
-
- ManifestItem = Struct.new(:line_item, :variant, :quantity, :states)
-
- def manifest
- # Grouping by the ID means that we don't have to call out to the association accessor
- # This makes the grouping by faster because it results in less SQL cache hits.
- inventory_units.group_by(&:variant_id).flat_map do |_variant_id, units|
- units.group_by(&:line_item_id).filter_map do |_line_item_id, units|
- line_item = units.first.line_item
- # Defensively skip orphaned inventory units (line item destroyed
- # without cascading) so a single bad row doesn't crash callers that
- # rely on line_item being present (item_cost, item_weight, the admin
- # shipment manifest view, etc.).
- next if line_item.nil?
-
- states = {}
- units.group_by(&:state).each { |state, iu| states[state] = iu.sum(&:quantity) }
-
- variant = units.first.variant
- ManifestItem.new(line_item, variant, units.sum(&:quantity), states)
- end
- end
- end
-
- def process_order_payments
- pending_payments = order.pending_payments.
- sort_by(&:uncaptured_amount).reverse
-
- shipment_to_pay = final_price_with_items
- payments_amount = 0
-
- payments_pool = pending_payments.each_with_object([]) do |payment, pool|
- break if payments_amount >= shipment_to_pay
-
- payments_amount += payment.uncaptured_amount
- pool << payment
- end
-
- payments_pool.each do |payment|
- capturable_amount = if payment.amount >= shipment_to_pay
- shipment_to_pay
- else
- payment.amount
- end
-
- cents = (capturable_amount * 100).to_i
- payment.capture!(cents)
- shipment_to_pay -= capturable_amount
- end
- end
-
- def ready_or_pending?
- ready? || pending?
- end
-
- def refresh_rates(shipping_method_filter = ShippingMethod::DISPLAY_ON_FRONT_END)
- return shipping_rates if shipped?
- return [] unless can_get_rates?
-
- # StockEstimator.new assignment below will replace the current shipping_method
- original_shipping_method_id = shipping_method.try(:id)
-
- self.shipping_rates = Stock::Estimator.new(order).
- shipping_rates(to_package, shipping_method_filter)
-
- if shipping_method
- selected_rate = shipping_rates.detect do |rate|
- if original_shipping_method_id
- rate.shipping_method_id == original_shipping_method_id
- else
- rate.selected
- end
- end
- save!
- self.selected_shipping_rate_id = selected_rate.id if selected_rate
- reload
- end
-
- shipping_rates
- end
-
- # Public API v3 name for the selected rate (see docs/plans/6.0-fulfillment-and-delivery.md).
- #
- # @return [String, nil] the selected delivery rate's prefixed ID
- def selected_delivery_rate_id
- selected_shipping_rate&.prefixed_id
- end
-
- # Selects a delivery rate by its public prefixed ID (+dr_...+); raw IDs
- # are accepted for internal callers. The model owns this naming bridge so
- # API clients never deal with the legacy shipping-rate name.
- #
- # @param id [String, Integer] delivery rate prefixed or raw ID
- def selected_delivery_rate_id=(id)
- rate = Spree::PrefixedId.prefixed_id?(id) ? shipping_rates.find_by_prefix_id!(id) : shipping_rates.find(id)
- self.selected_shipping_rate_id = rate.id
- end
-
- def selected_shipping_rate_id
- selected_shipping_rate.try(:id)
- end
-
- def selected_shipping_rate_id=(id)
- # Explicitly updates the timestamp in order to bust cache dependent on "updated_at"
- shipping_rates.update_all(selected: false, updated_at: Time.current)
- shipping_rates.update(id, selected: true)
- save!
- # Reload associations to pick up the new selected shipping rate
- shipping_rates.reset
- association(:selected_shipping_rate).reset
- # Update shipment cost and order totals only for incomplete orders (during checkout)
- # For completed orders, totals are managed separately (e.g., in tests or admin adjustments)
- return if order.completed?
-
- update_amounts
- reload # reload to pick up cost set by update_columns in update_amounts
- order.set_shipments_cost
- end
-
- def set_up_inventory(state, variant, order, line_item, quantity = 1)
- return if quantity <= 0
-
- inventory_units.create(
- state: state,
- variant_id: variant.id,
- order_id: order.id,
- line_item_id: line_item.id,
- quantity: quantity
- )
- end
-
- def shipped=(value)
- return unless value == '1' && shipped_at.nil?
-
- self.shipped_at = Time.current
- end
-
- # Returns the shipping method of the selected shipping rate
- #
- # @return [Spree::ShippingMethod]
- def shipping_method
- selected_shipping_rate&.shipping_method || shipping_rates.first&.shipping_method
- end
-
- # Returns the tax category of the selected shipping rate
- #
- # @return [Spree::TaxCategory]
- def tax_category
- selected_shipping_rate.try(:tax_rate).try(:tax_category)
- end
-
- # Returns the tax category ID of the selected shipping rate
- #
- # @return [Integer]
- def tax_category_id
- selected_shipping_rate.try(:tax_rate).try(:tax_category_id)
- end
-
- # Only one of either included_tax_total or additional_tax_total is set
- # This method returns the total of the two. Saves having to check if
- # tax is included or additional.
- def tax_total
- included_tax_total + additional_tax_total
- end
-
- def to_package
- package = Stock::Package.new(stock_location)
- inventory_units.includes(:variant).joins(:variant).group_by(&:state).each do |state, state_inventory_units|
- package.add_multiple state_inventory_units, state.to_sym
- end
- package
- end
-
- # External systems (3PLs, courier APIs) often hand over a complete
- # tracking link rather than a bare tracking code — returned as-is
- # instead of being templated into the delivery method's tracking URL.
- #
- # @return [String, nil]
- def tracking_url
- @tracking_url ||= if tracking&.start_with?('https://')
- tracking
- else
- shipping_method&.build_tracking_url(tracking)
- end
- end
-
- def update_amounts
- if selected_shipping_rate
- update_columns(
- cost: selected_shipping_rate.cost,
- adjustment_total: adjustments.additional.map(&:update!).compact.sum,
- updated_at: Time.current
- )
- end
- end
-
- def update_attributes_and_order(params = {})
- Shipments::Update.call(shipment: self, shipment_attributes: params).success?
- end
-
- # Updates various aspects of the Shipment while bypassing any callbacks. Note that this method takes an explicit reference to the
- # Order object. This is necessary because the association actually has a stale (and unsaved) copy of the Order and so it will not
- # yield the correct results.
- def update!(order)
- old_state = state
- new_state = determine_state(order)
- update_columns(
- state: new_state,
- updated_at: Time.current
- )
- after_ship if new_state == 'shipped' && old_state != 'shipped'
- end
-
- def transfer_to_location(variant, quantity, stock_location)
- transfer_to_shipment(
- variant,
- quantity,
- order.shipments.build(stock_location: stock_location)
- )
- end
-
- def transfer_to_shipment(variant, quantity, shipment_to_transfer_to)
- Spree::FulfilmentChanger.new(
- current_stock_location: stock_location,
- desired_stock_location: shipment_to_transfer_to.stock_location,
- current_shipment: self,
- desired_shipment: shipment_to_transfer_to,
- variant: variant,
- quantity: quantity
- )
- end
-
- private
-
- def after_ship
- ShipmentHandler.factory(self).perform
- end
-
- # publish_shipment_shipped_event, publish_shipment_canceled_event, and
- # publish_shipment_resumed_event are defined in Spree::Shipment::CustomEvents
-
- def can_get_rates?
- return true unless order.requires_ship_address?
-
- order.ship_address&.valid?
- end
-
- def manifest_restock(item)
- if item.states['on_hand'].to_i.positive?
- stock_location.restock item.variant, item.states['on_hand'], self
- end
-
- if item.states['backordered'].to_i.positive?
- stock_location.restock_backordered item.variant, item.states['backordered']
- end
- end
-
- def manifest_unstock(item)
- stock_location.unstock(item.variant, item.quantity, self) if item.variant.track_inventory?
- end
-
- def recalculate_adjustments
- Adjustable::AdjustmentsUpdater.update(self)
- end
-
- def set_cost_zero_when_nil
- self.cost = 0 unless cost
- end
-
- def update_adjustments
- recalculate_adjustments if saved_change_to_cost? && state != 'shipped'
- end
- end
+ # Constant alias for the legacy Spree::Shipment, renamed to
+ # Spree::Fulfillment in 6.0. Remove in 6.1.
+ Shipment = Fulfillment
end
diff --git a/spree/core/app/models/spree/shipment_handler.rb b/spree/core/app/models/spree/shipment_handler.rb
deleted file mode 100644
index 6871f04fb6..0000000000
--- a/spree/core/app/models/spree/shipment_handler.rb
+++ /dev/null
@@ -1,38 +0,0 @@
-module Spree
- class ShipmentHandler
- include Spree::IntegrationsConcern
-
- class << self
- def factory(shipment)
- # Do we have a specialized shipping-method-specific handler? e.g:
- # Given shipment.shipping_method = Spree::ShippingMethod::DigitalDownload
- # do we have Spree::ShipmentHandler::DigitalDownload?
- if sm_handler = "Spree::ShipmentHandler::#{shipment.shipping_method&.name&.split('::')&.last}".safe_constantize
- sm_handler.new(shipment)
- else
- new(shipment)
- end
- end
- end
-
- def initialize(shipment)
- @shipment = shipment
- end
-
- def perform
- @shipment.inventory_units.each &:ship!
- @shipment.process_order_payments if Spree::Config[:auto_capture_on_dispatch]
- @shipment.touch :shipped_at
- update_order_shipment_state
- end
-
- protected
-
- def update_order_shipment_state
- order = @shipment.order
-
- new_state = OrderUpdater.new(order).update_shipment_state
- order.update_columns(shipment_state: new_state, updated_at: Time.current)
- end
- end
-end
diff --git a/spree/core/app/models/spree/shipping_category.rb b/spree/core/app/models/spree/shipping_category.rb
index 9b2b580148..1993e16b79 100644
--- a/spree/core/app/models/spree/shipping_category.rb
+++ b/spree/core/app/models/spree/shipping_category.rb
@@ -10,16 +10,10 @@ module Spree
has_many :products
has_many :shipping_method_categories
end
- has_many :shipping_methods, through: :shipping_method_categories
+ has_many :shipping_methods, through: :shipping_method_categories, class_name: 'Spree::DeliveryMethod'
def self.digital
find_by(name: DIGITAL_NAME)
end
-
- # Returns true if this shipping category includes a digital shipping method
- # @return [Boolean]
- def includes_digital_shipping_method?
- @includes_digital_shipping_method ||= shipping_methods.digital.exists?
- end
end
end
diff --git a/spree/core/app/models/spree/shipping_method.rb b/spree/core/app/models/spree/shipping_method.rb
index d42784b92a..ce5b67e30b 100644
--- a/spree/core/app/models/spree/shipping_method.rb
+++ b/spree/core/app/models/spree/shipping_method.rb
@@ -1,148 +1,5 @@
module Spree
- class ShippingMethod < Spree.base_class
- has_prefix_id :dm
-
- acts_as_paranoid
- include Spree::CalculatedAdjustments
- include Spree::Metafields
- include Spree::Metadata
- include Spree::DisplayOn
- if defined?(Spree::VendorConcern)
- include Spree::VendorConcern
- end
- include Spree::MemoizedData
-
- extend Spree::DisplayMoney
-
- MEMOIZED_METHODS = %w[display_estimated_price digital?]
-
- # Used for #refresh_rates
- DISPLAY_ON_FRONT_END = 1
- DISPLAY_ON_BACK_END = 2
-
- default_scope { where(deleted_at: nil) }
-
- has_many :shipping_method_categories, dependent: :destroy
- has_many :shipping_categories, through: :shipping_method_categories
- has_many :shipping_rates, inverse_of: :shipping_method
- has_many :shipments, through: :shipping_rates
-
- has_many :shipping_method_zones, class_name: 'Spree::ShippingMethodZone',
- foreign_key: 'shipping_method_id'
- has_many :zones, through: :shipping_method_zones, class_name: 'Spree::Zone'
-
- belongs_to :tax_category, -> { with_deleted }, class_name: 'Spree::TaxCategory', optional: true
-
- validates :name, :display_on, presence: true
- validates :estimated_transit_business_days_min, numericality: { greater_than_or_equal_to: 1 }, allow_nil: true
- validates :estimated_transit_business_days_max, numericality: { greater_than_or_equal_to: 1 }, allow_nil: true
- validate :at_least_one_shipping_category
-
- scope :digital, lambda {
- joins(:calculator).where(spree_calculators: { type: Spree::Calculator::Shipping::DigitalDelivery.to_s })
- }
-
- scope :search_by_name, ->(query) { where(arel_table[:name].lower.matches("%#{query}%")) }
-
- def include?(address)
- return true unless requires_zone_check?
- return false unless address
-
- zones.includes(:zone_members).any? do |zone|
- zone.include?(address)
- end
- end
-
- def requires_zone_check?
- !calculator.is_a?(Spree::Calculator::Shipping::DigitalDelivery)
- end
-
- def build_tracking_url(tracking)
- return if tracking.blank?
-
- tracking = tracking.upcase
-
- # build tracking url automatically
- if tracking_url.blank?
- # use tracking number gem to build tracking url
- # we need to upcase the tracking number
- # https://github.com/jkeen/tracking_number/pull/85
- tracking_number_service(tracking).tracking_url if tracking_number_service(tracking).valid?
- else
- # build tracking url manually
- tracking_url.gsub(/:tracking/, ERB::Util.url_encode(tracking)) # :url_encode exists in 1.8.7 through 2.1.0
- end
- end
-
- # your shipping method subclasses can override this method to provide a custom tracking number service
- def tracking_number_service(tracking)
- @tracking_number_service ||= Spree.tracking_number_service.new(tracking)
- end
-
- def self.calculators
- spree_calculators.send(model_name_without_spree_namespace).
- select { |c| c.to_s.constantize < Spree::ShippingCalculator }
- end
-
- def available_to_display?(display_filter)
- (frontend? && display_filter == DISPLAY_ON_FRONT_END) ||
- (backend? && display_filter == DISPLAY_ON_BACK_END)
- end
-
- def delivery_range
- return unless estimated_transit_business_days_min || estimated_transit_business_days_max
-
- if estimated_transit_business_days_min == estimated_transit_business_days_max
- estimated_transit_business_days_min.to_s
- else
- [estimated_transit_business_days_min, estimated_transit_business_days_max].compact.join("-")
- end
- end
-
- def display_estimated_price
- return unless calculator
-
- @display_estimated_price ||= begin
- calculator.description + ': ' +
-
- if calculator.is_a?(Spree::Calculator::Shipping::FlatRate)
- if calculator.preferred_amount == 0
- Spree.t(:free)
- else
- Spree::Money.new(calculator.preferred_amount, { currency: calculator.preferred_currency }).to_s
- end
- elsif calculator.is_a?(Spree::Calculator::Shipping::FlexiRate)
- Spree::Money.new(calculator.preferred_first_item, { currency: calculator.preferred_currency }).to_s
- elsif calculator.is_a?(Spree::Calculator::Shipping::FlatPercentItemTotal)
- ActionController::Base.helpers.number_to_percentage(calculator.preferred_flat_percent, precision: 2)
- else
- ''
- end
- end
- end
-
- # Returns true if the shipping method is digital
- #
- # @return [Boolean]
- def digital?
- @digital ||= calculator.is_a?(Spree::Calculator::Shipping::DigitalDelivery)
- end
-
- private
-
- # Some shipping methods are only meant to be set via backend
- def frontend?
- display_on.in?(['both', 'front_end'])
- end
-
- def backend?
- display_on.in?(['both', 'back_end'])
- end
-
- def at_least_one_shipping_category
- if shipping_categories.empty?
- errors.add(:base, :required_shipping_category)
- end
- end
- end
+ # Constant alias for the legacy Spree::ShippingMethod, renamed to
+ # Spree::DeliveryMethod in 6.0. Remove in 6.1.
+ ShippingMethod = DeliveryMethod
end
diff --git a/spree/core/app/models/spree/shipping_method_category.rb b/spree/core/app/models/spree/shipping_method_category.rb
index d657910145..6b56820ac7 100644
--- a/spree/core/app/models/spree/shipping_method_category.rb
+++ b/spree/core/app/models/spree/shipping_method_category.rb
@@ -2,7 +2,7 @@ module Spree
class ShippingMethodCategory < Spree.base_class
has_prefix_id :smcat
- belongs_to :shipping_method, class_name: 'Spree::ShippingMethod'
+ belongs_to :shipping_method, class_name: 'Spree::DeliveryMethod'
belongs_to :shipping_category, class_name: 'Spree::ShippingCategory', inverse_of: :shipping_method_categories
end
end
diff --git a/spree/core/app/models/spree/shipping_method_zone.rb b/spree/core/app/models/spree/shipping_method_zone.rb
index b968498211..740411fcad 100644
--- a/spree/core/app/models/spree/shipping_method_zone.rb
+++ b/spree/core/app/models/spree/shipping_method_zone.rb
@@ -1,8 +1,5 @@
module Spree
- class ShippingMethodZone < Spree.base_class
- belongs_to :shipping_method, -> { with_deleted }, inverse_of: :shipping_method_zones, class_name: 'Spree::ShippingMethod'
- belongs_to :zone, inverse_of: :shipping_method_zones, class_name: 'Spree::Zone'
-
- validates :shipping_method, uniqueness: { scope: :zone }
- end
+ # Constant alias for the legacy Spree::ShippingMethodZone, renamed to
+ # Spree::DeliveryMethodZone in 6.0. Remove in 6.1.
+ ShippingMethodZone = DeliveryMethodZone
end
diff --git a/spree/core/app/models/spree/shipping_rate.rb b/spree/core/app/models/spree/shipping_rate.rb
index e56d226034..3b2564fc45 100644
--- a/spree/core/app/models/spree/shipping_rate.rb
+++ b/spree/core/app/models/spree/shipping_rate.rb
@@ -1,99 +1,5 @@
module Spree
- class ShippingRate < Spree.base_class
- has_prefix_id :dr
-
- belongs_to :shipment, class_name: 'Spree::Shipment'
- belongs_to :tax_rate, -> { with_deleted }, class_name: 'Spree::TaxRate'
- belongs_to :shipping_method, -> { with_deleted }, class_name: 'Spree::ShippingMethod', inverse_of: :shipping_rates
- extend Spree::DisplayMoney
-
- money_methods :base_price, :final_price, :tax_amount, :additional_tax_total, :included_tax_total, :tax_total
-
- delegate :order, :currency, :with_free_shipping_promotion?, to: :shipment
- delegate :name, to: :shipping_method
- delegate :code, to: :shipping_method, prefix: true
-
- def display_price
- price = display_base_price.to_s
-
- return price if tax_rate.nil? || tax_amount.zero? || !tax_rate.show_rate_in_label
-
- Spree.t(
- tax_rate.included_in_price? ? :including_tax : :excluding_tax,
- scope: 'shipping_rates.display_price',
- price: price,
- tax_amount: display_tax_amount,
- tax_rate_name: tax_rate.name
- )
- end
- alias display_cost display_price
- alias_attribute :base_price, :cost
-
- # Returns true if the shipping rate is free
- #
- # @return [Boolean]
- def free?
- final_price.zero?
- end
-
- # Returns the tax amount for the shipping rate
- #
- # @return [BigDecimal]
- def tax_amount
- @tax_amount ||= tax_rate&.calculator&.compute_shipping_rate(self) || BigDecimal(0)
- end
-
- # Returns the additional tax total for the shipping rate
- #
- # @return [BigDecimal]
- def additional_tax_total
- tax_rate&.included_in_price? ? BigDecimal(0) : tax_amount
- end
-
- # Returns the included tax total for the shipping rate
- #
- # @return [BigDecimal]
- def included_tax_total
- tax_rate&.included_in_price? ? tax_amount : BigDecimal(0)
- end
-
- alias tax_total tax_amount
- alias display_tax_total display_tax_amount
-
- # returns base price - any available discounts for this Shipment
- # useful when you want to present a list of available shipping rates
- def final_price
- if with_free_shipping_promotion? || cost < -discount_amount
- BigDecimal(0)
- else
- cost + discount_amount
- end
- end
- alias total final_price
- alias display_total display_final_price
-
- # Returns the delivery range for the shipping method
- #
- # @return [String]
- def delivery_range
- return unless shipping_method.delivery_range
-
- shipping_method.delivery_range
- end
-
- # Returns the display delivery range for the shipping method
- #
- # @return [String]
- def display_delivery_range
- return unless delivery_range
-
- Spree.t(:display_delivery_range, delivery_range: delivery_range)
- end
-
- private
-
- def discount_amount
- shipment.adjustments.promotion.sum(:amount)
- end
- end
+ # Constant alias for the legacy Spree::ShippingRate, renamed to
+ # Spree::DeliveryRate in 6.0. Remove in 6.1.
+ ShippingRate = DeliveryRate
end
diff --git a/spree/core/app/models/spree/stock/availability_validator.rb b/spree/core/app/models/spree/stock/availability_validator.rb
index 2c38a07bfb..1cdb62f712 100644
--- a/spree/core/app/models/spree/stock/availability_validator.rb
+++ b/spree/core/app/models/spree/stock/availability_validator.rb
@@ -2,7 +2,7 @@ module Spree
module Stock
class AvailabilityValidator < ActiveModel::Validator
def validate(line_item)
- unit_count = line_item.inventory_units.reject(&:pending?).sum(&:quantity)
+ unit_count = line_item.fulfillment_items.reject(&:pending?).sum(&:quantity)
return if unit_count >= line_item.quantity
quantity = line_item.quantity - unit_count
diff --git a/spree/core/app/models/spree/stock/estimator.rb b/spree/core/app/models/spree/stock/estimator.rb
index c9931b0d2a..8f244c1fff 100644
--- a/spree/core/app/models/spree/stock/estimator.rb
+++ b/spree/core/app/models/spree/stock/estimator.rb
@@ -59,7 +59,7 @@ module Spree
end
def shipping_methods(package, display_filter)
- package.shipping_methods.select do |ship_method|
+ package.eligible_delivery_methods.select do |ship_method|
calculator = ship_method.calculator
ship_method.available_to_display?(display_filter) &&
diff --git a/spree/core/app/models/spree/stock/package.rb b/spree/core/app/models/spree/stock/package.rb
index ad719eaf7e..006776eb20 100644
--- a/spree/core/app/models/spree/stock/package.rb
+++ b/spree/core/app/models/spree/stock/package.rb
@@ -70,13 +70,34 @@ module Spree
order.currency
end
- def shipping_categories
- Spree::ShippingCategory.joins(products: :variants).
- where(spree_variants: { id: variant_ids }).distinct
- end
-
+ # The fulfillment types every item in this package supports — the
+ # intersection across products (splitters keep packages homogeneous,
+ # so this is normally one product-type's set).
+ #
+ # @return [Array<String>]
+ def fulfillment_types
+ contents.map { |item| item.variant.product.fulfillment_types }.reduce(:&) || []
+ end
+
+ # Delivery methods eligible to serve this package: the method's
+ # fulfillment_type must be supported by every item, minus any
+ # per-product exclusions. Replaces the ShippingCategory-based
+ # Package#shipping_methods.
+ #
+ # @return [ActiveRecord::Relation<Spree::DeliveryMethod>]
+ def eligible_delivery_methods
+ types = fulfillment_types
+ return Spree::DeliveryMethod.none if types.empty?
+
+ methods = Spree::DeliveryMethod.by_fulfillment_type(types)
+ excluded_ids = contents.flat_map { |item| item.variant.product.excluded_delivery_method_ids || [] }.uniq
+ excluded_ids.any? ? methods.where.not(id: excluded_ids) : methods
+ end
+
+ # @deprecated Use {#eligible_delivery_methods}; removed in 6.1.
def shipping_methods
- shipping_categories.includes(:shipping_methods).map(&:shipping_methods).reduce(:&).to_a
+ Spree::Deprecation.warn('Spree::Stock::Package#shipping_methods is deprecated and will be removed in Spree 6.1. Use #eligible_delivery_methods instead.')
+ eligible_delivery_methods.to_a
end
def inspect
@@ -89,12 +110,12 @@ module Spree
# At this point we should only have one content item per inventory unit
# across the entire set of inventory units to be shipped, which has been
# taken care of by the Prioritizer
- contents.each { |content_item| content_item.inventory_unit.state = content_item.state.to_s }
+ contents.each { |content_item| content_item.inventory_unit.status = content_item.state.to_s }
- Spree::Shipment.new(
+ Spree::Fulfillment.new(
stock_location: stock_location,
- shipping_rates: shipping_rates,
- inventory_units: contents.map(&:inventory_unit)
+ delivery_rates: shipping_rates,
+ fulfillment_items: contents.map(&:inventory_unit)
)
end
diff --git a/spree/core/app/models/spree/stock/prioritizer.rb b/spree/core/app/models/spree/stock/prioritizer.rb
index c91bbe620c..0011d96cb2 100644
--- a/spree/core/app/models/spree/stock/prioritizer.rb
+++ b/spree/core/app/models/spree/stock/prioritizer.rb
@@ -45,7 +45,7 @@ module Spree
end
def hash_item(item)
- shipment = item.inventory_unit.shipment
+ shipment = item.inventory_unit.fulfillment
variant = item.inventory_unit.variant
if shipment.present?
variant.hash ^ shipment.hash
diff --git a/spree/core/app/models/spree/stock/splitter/digital.rb b/spree/core/app/models/spree/stock/splitter/digital.rb
deleted file mode 100644
index 8f7884b230..0000000000
--- a/spree/core/app/models/spree/stock/splitter/digital.rb
+++ /dev/null
@@ -1,35 +0,0 @@
-module Spree
- module Stock
- module Splitter
- class Digital < Spree::Stock::Splitter::Base
- def split(packages)
- split_packages = []
- packages.each do |package|
- split_packages += split_by_digital(package)
- end
-
- return_next(split_packages)
- end
-
- private
-
- def split_by_digital(package)
- digitals = Hash.new { |hash, key| hash[key] = [] }
- package.contents.each do |item|
- digitals[item.variant.digital?] << item
- end
-
- hash_to_packages(digitals)
- end
-
- def hash_to_packages(digitals)
- packages = []
- digitals.each do |_id, contents|
- packages << build_package(contents)
- end
- packages
- end
- end
- end
- end
-end
diff --git a/spree/core/app/models/spree/stock/splitter/fulfillment_type.rb b/spree/core/app/models/spree/stock/splitter/fulfillment_type.rb
new file mode 100644
index 0000000000..d62ff4d9aa
--- /dev/null
+++ b/spree/core/app/models/spree/stock/splitter/fulfillment_type.rb
@@ -0,0 +1,28 @@
+module Spree
+ module Stock
+ module Splitter
+ # Keeps packages homogeneous by fulfillment-type set, so mixed carts
+ # (physical + digital, shippable + pickup-only) split automatically.
+ # Replaces the ShippingCategory and Digital splitters.
+ class FulfillmentType < Spree::Stock::Splitter::Base
+ def split(packages)
+ split_packages = packages.flat_map { |package| split_by_fulfillment_types(package) }
+ return_next(split_packages)
+ end
+
+ private
+
+ def split_by_fulfillment_types(package)
+ grouped = package.contents.group_by { |item| fulfillment_types_for(item) }
+ grouped.values.map { |contents| build_package(contents) }
+ end
+
+ # optimization: save product -> fulfillment_types correspondence
+ def fulfillment_types_for(item)
+ @item_fulfillment_types ||= {}
+ @item_fulfillment_types[item.variant.product_id] ||= item.variant.product.fulfillment_types.sort
+ end
+ end
+ end
+ end
+end
diff --git a/spree/core/app/models/spree/stock/splitter/shipping_category.rb b/spree/core/app/models/spree/stock/splitter/shipping_category.rb
deleted file mode 100644
index 029f6a01e2..0000000000
--- a/spree/core/app/models/spree/stock/splitter/shipping_category.rb
+++ /dev/null
@@ -1,31 +0,0 @@
-module Spree
- module Stock
- module Splitter
- class ShippingCategory < Spree::Stock::Splitter::Base
- def split(packages)
- split_packages = packages.flat_map(&method(:split_by_category))
- return_next(split_packages)
- end
-
- private
-
- def split_by_category(package)
- # group package items by shipping category
- grouped_packages = package.contents.group_by(&method(:shipping_category_for))
- hash_to_packages(grouped_packages)
- end
-
- def hash_to_packages(grouped_packages)
- # select values from packages grouped by shipping categories and build new packages
- grouped_packages.values.map(&method(:build_package))
- end
-
- # optimization: save variant -> shipping_category correspondence
- def shipping_category_for(item)
- @item_shipping_category ||= {}
- @item_shipping_category[item.inventory_unit.variant_id] ||= item.variant.shipping_category_id
- end
- end
- end
- end
-end
diff --git a/spree/core/app/models/spree/stock_location.rb b/spree/core/app/models/spree/stock_location.rb
index c42927888a..8936e3b81d 100644
--- a/spree/core/app/models/spree/stock_location.rb
+++ b/spree/core/app/models/spree/stock_location.rb
@@ -21,7 +21,8 @@ module Spree
acts_as_paranoid
- has_many :shipments
+ has_many :fulfillments, class_name: 'Spree::Fulfillment'
+ has_many :shipments, class_name: 'Spree::Fulfillment', foreign_key: :stock_location_id, deprecated: true
has_many :stock_items, dependent: :delete_all, inverse_of: :stock_location
has_many :variants, through: :stock_items
has_many :stock_movements, through: :stock_items
diff --git a/spree/core/app/models/spree/store.rb b/spree/core/app/models/spree/store.rb
index 3d6f3bee29..9c1aef2122 100644
--- a/spree/core/app/models/spree/store.rb
+++ b/spree/core/app/models/spree/store.rb
@@ -76,7 +76,8 @@ module Spree
has_many :orders, class_name: 'Spree::Order'
has_many :line_items, through: :orders, class_name: 'Spree::LineItem'
has_many :digital_links, through: :line_items, class_name: 'Spree::DigitalLink'
- has_many :shipments, through: :orders, class_name: 'Spree::Shipment'
+ has_many :fulfillments, through: :orders, class_name: 'Spree::Fulfillment'
+ has_many :shipments, through: :orders, class_name: 'Spree::Fulfillment', source: :fulfillments, deprecated: true
has_many :payments, through: :orders, class_name: 'Spree::Payment'
has_many :return_authorizations, through: :orders, class_name: 'Spree::ReturnAuthorization'
# has_many :reimbursements, through: :orders, class_name: 'Spree::Reimbursement' FIXME: we should fetch this via Customer Return
@@ -91,7 +92,8 @@ module Spree
has_many :stock_items, through: :variants, class_name: 'Spree::StockItem'
has_many :prices, through: :variants, class_name: 'Spree::Price'
has_many :price_lists, class_name: 'Spree::PriceList', inverse_of: :store
- has_many :inventory_units, through: :variants, class_name: 'Spree::InventoryUnit'
+ has_many :fulfillment_items, through: :variants, class_name: 'Spree::FulfillmentItem'
+ has_many :inventory_units, through: :variants, class_name: 'Spree::FulfillmentItem', source: :fulfillment_items, deprecated: true
has_many :option_value_variants, through: :variants, class_name: 'Spree::OptionValueVariant'
has_many :customer_returns, class_name: 'Spree::CustomerReturn', inverse_of: :store
@@ -344,30 +346,24 @@ module Spree
end
end
- # Returns countries covered by at least one shipping zone
- # that has an active shipping method attached.
- # Handles both country-type zones (direct membership) and
- # state-type zones (country inferred from state).
+ # Returns countries covered by delivery methods. Methods without delivery
+ # zones are worldwide, so any such method means every country is covered;
+ # otherwise coverage is the union of the attached zones' country, state,
+ # and postal-code members.
#
# @return [ActiveRecord::Relation<Spree::Country>]
def countries_with_shipping_coverage
- zone_ids = Spree::Zone
- .joins(:shipping_methods)
- .select(:id)
+ return Spree::Country.order(:name) if Spree::DeliveryMethod.where.missing(:delivery_method_zones).exists?
- country_zone_country_ids = Spree::ZoneMember
- .where(zone_id: zone_ids, zoneable_type: 'Spree::Country')
- .select(:zoneable_id)
+ zone_ids = Spree::DeliveryMethodZone.select(:delivery_zone_id)
+ members = Spree::DeliveryZoneMember.where(delivery_zone_id: zone_ids)
- state_zone_country_ids = Spree::State
- .where(id: Spree::ZoneMember
- .where(zone_id: zone_ids, zoneable_type: 'Spree::State')
- .select(:zoneable_id))
- .select(:country_id)
+ country_ids = members.where(member_type: %w[country postal_code]).select(:country_id)
+ state_country_ids = Spree::State.where(id: members.where(member_type: 'state').select(:state_id)).select(:country_id)
Spree::Country
- .where(id: country_zone_country_ids)
- .or(Spree::Country.where(id: state_zone_country_ids))
+ .where(id: country_ids)
+ .or(Spree::Country.where(id: state_country_ids))
.order(:name)
end
diff --git a/spree/core/app/models/spree/tax_rate.rb b/spree/core/app/models/spree/tax_rate.rb
index d9bc6f1c9d..d36f7dc330 100644
--- a/spree/core/app/models/spree/tax_rate.rb
+++ b/spree/core/app/models/spree/tax_rate.rb
@@ -64,7 +64,7 @@ module Spree
def self.store_pre_tax_amount(item, rates)
pre_tax_amount = case item.class.to_s
when 'Spree::LineItem' then item.discounted_amount
- when 'Spree::Shipment' then item.discounted_cost
+ when 'Spree::Shipment', 'Spree::Fulfillment' then item.discounted_cost
end
included_rates = rates.select(&:included_in_price)
diff --git a/spree/core/app/models/spree/variant.rb b/spree/core/app/models/spree/variant.rb
index e77d4bc0d5..af7dd8a735 100644
--- a/spree/core/app/models/spree/variant.rb
+++ b/spree/core/app/models/spree/variant.rb
@@ -35,10 +35,11 @@ module Spree
include Spree::DefaultPrice
with_options inverse_of: :variant do
- has_many :inventory_units
+ has_many :fulfillment_items, class_name: 'Spree::FulfillmentItem'
has_many :line_items
has_many :stock_items, dependent: :destroy, autosave: true
end
+ has_many :inventory_units, class_name: 'Spree::FulfillmentItem', inverse_of: :variant, deprecated: true
has_many :orders, through: :line_items
with_options through: :stock_items do
diff --git a/spree/core/app/models/spree/zone.rb b/spree/core/app/models/spree/zone.rb
index 1e3039114f..08e1fd559c 100644
--- a/spree/core/app/models/spree/zone.rb
+++ b/spree/core/app/models/spree/zone.rb
@@ -13,9 +13,6 @@ module Spree
has_many :states, source_type: 'Spree::State'
end
- has_many :shipping_method_zones, class_name: 'Spree::ShippingMethodZone'
- has_many :shipping_methods, through: :shipping_method_zones, class_name: 'Spree::ShippingMethod'
-
scope :with_default_tax, -> { where(default_tax: true) }
after_save :remove_defunct_members
diff --git a/spree/core/app/presenters/spree/csv/order_line_item_presenter.rb b/spree/core/app/presenters/spree/csv/order_line_item_presenter.rb
index dba9c50716..3ae3752280 100644
--- a/spree/core/app/presenters/spree/csv/order_line_item_presenter.rb
+++ b/spree/core/app/presenters/spree/csv/order_line_item_presenter.rb
@@ -121,7 +121,7 @@ module Spree
index.zero? ? order.ship_address&.country&.name : nil,
index.zero? ? order.ship_address&.phone : nil,
index.zero? ? format_date(order.completed_at) : nil,
- format_date(line_item.order.shipments.first&.shipped_at),
+ format_date(line_item.order.fulfillments.first&.fulfilled_at),
index.zero? ? format_date(order.canceled_at) : nil,
index.zero? ? order.canceler&.email : nil,
index.zero? ? order.special_instructions : nil
diff --git a/spree/core/app/services/spree/carts/destroy.rb b/spree/core/app/services/spree/carts/destroy.rb
index d18c2561d3..81dcc38b88 100644
--- a/spree/core/app/services/spree/carts/destroy.rb
+++ b/spree/core/app/services/spree/carts/destroy.rb
@@ -20,7 +20,7 @@ module Spree
end
def cancel_shipments(order:)
- order.shipments.each(&:cancel)
+ order.fulfillments.each(&:cancel)
success(order: order)
end
diff --git a/spree/core/app/services/spree/carts/empty.rb b/spree/core/app/services/spree/carts/empty.rb
index 71797d2b3c..37c7476f4d 100644
--- a/spree/core/app/services/spree/carts/empty.rb
+++ b/spree/core/app/services/spree/carts/empty.rb
@@ -21,7 +21,7 @@ module Spree
order.line_items.destroy_all
order.updater.update_item_count
order.adjustments.destroy_all
- order.shipments.destroy_all
+ order.fulfillments.destroy_all
order.state_changes.destroy_all
order.order_promotions.destroy_all
order.update_totals
diff --git a/spree/core/app/services/spree/carts/recalculate.rb b/spree/core/app/services/spree/carts/recalculate.rb
index e6acb1dee0..9f340da24c 100644
--- a/spree/core/app/services/spree/carts/recalculate.rb
+++ b/spree/core/app/services/spree/carts/recalculate.rb
@@ -18,7 +18,7 @@ module Spree
# refresh shipments to ensure correct shipment amount is calculated when using price sack calculator
# for calculating shipment rates.
# Currently shipment rate is calculated on previous order total instead of current order total when updating a shipment from admin end.
- order.refresh_shipment_rates(::Spree::ShippingMethod::DISPLAY_ON_BACK_END)
+ order.refresh_shipment_rates(::Spree::DeliveryMethod::DISPLAY_ON_BACK_END)
shipment.update_amounts
else
order.ensure_updated_shipments
diff --git a/spree/core/app/services/spree/checkout/advance.rb b/spree/core/app/services/spree/checkout/advance.rb
index 6addcd6dbb..04bf177acb 100644
--- a/spree/core/app/services/spree/checkout/advance.rb
+++ b/spree/core/app/services/spree/checkout/advance.rb
@@ -25,7 +25,7 @@ module Spree
if order.delivery? &&
shipping_method_id.present? &&
- order.shipments.count == 1 &&
+ order.fulfillments.count == 1 &&
order.shipping_method.id != shipping_method_id
result = Spree::Checkout::SelectShippingMethod.call(order: order, params: { shipping_method_id: shipping_method_id })
@@ -36,7 +36,7 @@ module Spree
end
if order.state != old_state && !order_updater_ran
- order.updater.update_shipment_state
+ order.updater.update_fulfillment_status
order.updater.update_payment_state
order.save! if order.changed?
end
diff --git a/spree/core/app/services/spree/checkout/get_shipping_rates.rb b/spree/core/app/services/spree/checkout/get_shipping_rates.rb
index 9f70d41869..97dc6b1569 100644
--- a/spree/core/app/services/spree/checkout/get_shipping_rates.rb
+++ b/spree/core/app/services/spree/checkout/get_shipping_rates.rb
@@ -30,7 +30,7 @@ module Spree
end
def generate_or_return_shipping_rates(order:)
- generate_shipping_rates(order: order) if order.shipments.empty?
+ generate_shipping_rates(order: order) if order.fulfillments.empty?
return_shipments(order: order)
end
diff --git a/spree/core/app/services/spree/checkout/select_shipping_method.rb b/spree/core/app/services/spree/checkout/select_shipping_method.rb
index d8381c5b6b..8b77491add 100644
--- a/spree/core/app/services/spree/checkout/select_shipping_method.rb
+++ b/spree/core/app/services/spree/checkout/select_shipping_method.rb
@@ -14,7 +14,7 @@ module Spree
caller_locations(2)
)
if params[:shipment_id].present?
- shipment = order.shipments.valid.find_by(id: params[:shipment_id])
+ shipment = order.fulfillments.valid.find_by(id: params[:shipment_id])
return failure(:shipment_not_found) if shipment.nil?
end
@@ -28,7 +28,7 @@ module Spree
return failure(result.value, result.error) unless result.success?
else
# set shipping method for all shipments
- order.shipments.valid.each do |s|
+ order.fulfillments.valid.each do |s|
result = set_shipping_rate_based_on_method(shipment: s, shipping_method: shipping_method)
return failure(result.value, result.error) unless result.success?
@@ -44,7 +44,7 @@ module Spree
end
def set_shipping_rate_based_on_method(shipment:, shipping_method:)
- selected_shipping_rate = shipment.shipping_rates.find_by(shipping_method: shipping_method)
+ selected_shipping_rate = shipment.delivery_rates.find_by(delivery_method: shipping_method)
if selected_shipping_rate.nil?
return failure(
diff --git a/spree/core/app/services/spree/fulfillments/create.rb b/spree/core/app/services/spree/fulfillments/create.rb
index eea77a1832..fcf22468eb 100644
--- a/spree/core/app/services/spree/fulfillments/create.rb
+++ b/spree/core/app/services/spree/fulfillments/create.rb
@@ -59,7 +59,7 @@ module Spree
requested = normalize_items(order, items, units_by_line_item)
return requested if requested.is_a?(Spree::ServiceModule::Result)
- fulfillment = order.shipments.new(
+ fulfillment = order.fulfillments.new(
stock_location: stock_location,
address_id: order.ship_address_id,
tracking: tracking
@@ -91,12 +91,12 @@ module Spree
# in one query, on-hand first so moved units stay shippable, grouped
# by line item for both validation and moving.
def fulfillable_units(order)
- order.inventory_units.
+ order.fulfillment_items.
on_hand_or_backordered.
- joins(:shipment).
- merge(Spree::Shipment.ready_or_pending).
- preload(:shipment, :variant).
- order(Arel.sql("CASE WHEN #{Spree::InventoryUnit.table_name}.state = 'on_hand' THEN 0 ELSE 1 END"), :id).
+ joins(:fulfillment).
+ merge(Spree::Fulfillment.ready_or_pending).
+ preload(:fulfillment, :variant).
+ order(Arel.sql("CASE WHEN #{Spree::FulfillmentItem.table_name}.status = 'on_hand' THEN 0 ELSE 1 END"), :id).
group_by(&:line_item_id)
end
@@ -159,11 +159,11 @@ module Spree
break if remaining.zero?
take = [unit.quantity, remaining].min
- source_shipments << unit.shipment
- stock_moves[[unit.shipment, unit.variant]] += take
+ source_shipments << unit.fulfillment
+ stock_moves[[unit.fulfillment, unit.variant]] += take
- target = fulfillment.inventory_units.find_or_initialize_by(
- state: unit.state,
+ target = fulfillment.fulfillment_items.find_or_initialize_by(
+ status: unit.status,
variant_id: unit.variant_id,
line_item_id: unit.line_item_id,
order_id: order.id
@@ -206,7 +206,7 @@ module Spree
inherited = { cost: 0, delivery_method: nil }
source_shipments.each do |shipment|
- next unless shipment.inventory_units.sum(:quantity).zero?
+ next unless shipment.fulfillment_items.sum(:quantity).zero?
inherited[:cost] += shipment.cost
inherited[:delivery_method] ||= shipment.shipping_method if capture_delivery_method
@@ -250,9 +250,9 @@ module Spree
# (the external location evidently had the goods) and the paid-order
# readiness gate is bypassed deliberately — the goods already left.
def mark_shipped(fulfillment)
- fulfillment.inventory_units.backordered.each(&:fill_backorder!)
- fulfillment.update_columns(state: 'ready') unless fulfillment.ready?
- fulfillment.reload.ship!
+ fulfillment.fulfillment_items.backordered.each(&:fill_backorder!)
+ fulfillment.update_columns(status: 'ready') unless fulfillment.ready?
+ fulfillment.reload.fulfill!
end
end
end
diff --git a/spree/core/app/services/spree/seeds/digital_delivery.rb b/spree/core/app/services/spree/seeds/digital_delivery.rb
index ba6ec49628..d59d111489 100644
--- a/spree/core/app/services/spree/seeds/digital_delivery.rb
+++ b/spree/core/app/services/spree/seeds/digital_delivery.rb
@@ -4,16 +4,12 @@ module Spree
prepend Spree::ServiceModule::Base
def call
- digital_shipping_category = Spree::ShippingCategory.find_or_create_by!(name: 'Digital')
- zones = Spree::Zone.all
+ digital_delivery_method = Spree::DeliveryMethod.find_or_initialize_by(name: Spree.t('digital.digital_delivery'))
- digital_shipping_method = Spree::ShippingMethod.find_or_initialize_by(name: Spree.t('digital.digital_delivery'))
-
- digital_shipping_method.display_on = 'both'
- digital_shipping_method.shipping_categories = [digital_shipping_category]
- digital_shipping_method.calculator ||= Spree::Calculator::Shipping::DigitalDelivery.create!
- digital_shipping_method.zones = zones
- digital_shipping_method.save!
+ digital_delivery_method.display_on = 'both'
+ digital_delivery_method.fulfillment_type = 'digital'
+ digital_delivery_method.calculator ||= Spree::Calculator::Shipping::DigitalDelivery.create!
+ digital_delivery_method.save!
end
end
end
diff --git a/spree/core/app/services/spree/shipments/create.rb b/spree/core/app/services/spree/shipments/create.rb
index ede7bb4823..d941b01d4d 100644
--- a/spree/core/app/services/spree/shipments/create.rb
+++ b/spree/core/app/services/spree/shipments/create.rb
@@ -35,7 +35,7 @@ module Spree
end
def create_shipment(order:, stock_location:, variant:, quantity:)
- shipment = order.shipments.create(
+ shipment = order.fulfillments.create(
order_id: order.id,
stock_location_id: stock_location.id
)
diff --git a/spree/core/app/services/spree/shipments/remove_item.rb b/spree/core/app/services/spree/shipments/remove_item.rb
index 959b5c3dcc..737383305c 100644
--- a/spree/core/app/services/spree/shipments/remove_item.rb
+++ b/spree/core/app/services/spree/shipments/remove_item.rb
@@ -40,7 +40,7 @@ module Spree
# `OrderInventory#remove_from_shipment` is called in `remove_item_service`
# which will delete the shipment if all inventory units were removed
- if shipment.inventory_units.any?
+ if shipment.fulfillment_items.any?
success(shipment)
else
shipment.destroy!
diff --git a/spree/core/app/services/spree/shipments/update.rb b/spree/core/app/services/spree/shipments/update.rb
index fc0dd9578f..a1de7b6191 100644
--- a/spree/core/app/services/spree/shipments/update.rb
+++ b/spree/core/app/services/spree/shipments/update.rb
@@ -17,7 +17,7 @@ module Spree
# might change the Order#payment_state)
shipment.update_amounts
- order.updater.update_shipment_total
+ order.updater.update_delivery_total
order.updater.update_payment_state
# Update shipment state only after order total is updated because it
@@ -29,7 +29,7 @@ module Spree
# And then it's time to update shipment states and finally persist
# order changes
- order.updater.update_shipment_state
+ order.updater.update_fulfillment_status
order.updater.persist_totals
end
end
diff --git a/spree/core/config/locales/en.yml b/spree/core/config/locales/en.yml
index 9b363e68d3..7aec316a2c 100644
--- a/spree/core/config/locales/en.yml
+++ b/spree/core/config/locales/en.yml
@@ -5,7 +5,7 @@ en:
messages:
blank: can't be blank
models:
- spree/fulfilment_changer:
+ spree/fulfillment_changer:
attributes:
current_shipment:
can_not_have_backordered_inventory_units: has backordered inventory units
diff --git a/spree/core/db/migrate/20260728000004_rename_shipping_to_fulfillment_and_delivery.rb b/spree/core/db/migrate/20260728000004_rename_shipping_to_fulfillment_and_delivery.rb
new file mode 100644
index 0000000000..c737bcec61
--- /dev/null
+++ b/spree/core/db/migrate/20260728000004_rename_shipping_to_fulfillment_and_delivery.rb
@@ -0,0 +1,82 @@
+class RenameShippingToFulfillmentAndDelivery < ActiveRecord::Migration[7.2]
+ def change
+ # Old-name indexes are dropped up front and re-added under stable names
+ # after the renames — several carry non-generated names (e.g.
+ # index_inventory_units_on_order_id) that Rails' automatic index renaming
+ # would leave stale, and the generated replacements stay well under
+ # PostgreSQL's 63-char identifier limit only when added fresh.
+ remove_index :spree_shipments, column: :address_id, name: 'index_spree_shipments_on_address_id', if_exists: true
+ remove_index :spree_shipments, column: :number, unique: true, name: 'index_spree_shipments_on_number', if_exists: true
+ remove_index :spree_shipments, column: :order_id, name: 'index_spree_shipments_on_order_id', if_exists: true
+ remove_index :spree_shipments, column: :stock_location_id, name: 'index_spree_shipments_on_stock_location_id', if_exists: true
+
+ remove_index :spree_inventory_units, column: :line_item_id, name: 'index_spree_inventory_units_on_line_item_id', if_exists: true
+ remove_index :spree_inventory_units, column: :order_id, name: 'index_inventory_units_on_order_id', if_exists: true
+ remove_index :spree_inventory_units, column: :original_return_item_id, name: 'index_spree_inventory_units_on_original_return_item_id', if_exists: true
+ remove_index :spree_inventory_units, column: :shipment_id, name: 'index_inventory_units_on_shipment_id', if_exists: true
+ remove_index :spree_inventory_units, column: :variant_id, name: 'index_inventory_units_on_variant_id', if_exists: true
+
+ remove_index :spree_shipping_rates, column: :selected, name: 'index_spree_shipping_rates_on_selected', if_exists: true
+ remove_index :spree_shipping_rates, column: [:shipment_id, :shipping_method_id], unique: true, name: 'spree_shipping_rates_join_index', if_exists: true
+ remove_index :spree_shipping_rates, column: :shipment_id, name: 'index_spree_shipping_rates_on_shipment_id', if_exists: true
+ remove_index :spree_shipping_rates, column: :shipping_method_id, name: 'index_spree_shipping_rates_on_shipping_method_id', if_exists: true
+ remove_index :spree_shipping_rates, column: :tax_rate_id, name: 'index_spree_shipping_rates_on_tax_rate_id', if_exists: true
+
+ remove_index :spree_shipping_methods, column: :deleted_at, name: 'index_spree_shipping_methods_on_deleted_at', if_exists: true
+ remove_index :spree_shipping_methods, column: :tax_category_id, name: 'index_spree_shipping_methods_on_tax_category_id', if_exists: true
+
+ remove_index :spree_shipping_method_zones, column: :shipping_method_id, name: 'index_spree_shipping_method_zones_on_shipping_method_id', if_exists: true
+ remove_index :spree_shipping_method_zones, column: :zone_id, name: 'index_spree_shipping_method_zones_on_zone_id', if_exists: true
+
+ remove_index :spree_return_items, column: :inventory_unit_id, name: 'index_spree_return_items_on_inventory_unit_id', if_exists: true
+
+ rename_table :spree_shipments, :spree_fulfillments
+ rename_table :spree_shipping_methods, :spree_delivery_methods
+ rename_table :spree_shipping_rates, :spree_delivery_rates
+ rename_table :spree_inventory_units, :spree_fulfillment_items
+ rename_table :spree_shipping_method_zones, :spree_delivery_method_zones
+
+ rename_column :spree_fulfillments, :state, :status
+ rename_column :spree_fulfillments, :shipped_at, :fulfilled_at
+ rename_column :spree_fulfillment_items, :state, :status
+ rename_column :spree_fulfillment_items, :shipment_id, :fulfillment_id
+ rename_column :spree_delivery_rates, :shipment_id, :fulfillment_id
+ rename_column :spree_delivery_rates, :shipping_method_id, :delivery_method_id
+ rename_column :spree_delivery_method_zones, :shipping_method_id, :delivery_method_id
+ rename_column :spree_delivery_method_zones, :zone_id, :delivery_zone_id
+ rename_column :spree_return_items, :inventory_unit_id, :fulfillment_item_id
+ rename_column :spree_orders, :shipment_state, :fulfillment_status
+ rename_column :spree_orders, :shipment_total, :delivery_total
+
+ # display_on stays until the Wave 7 data task converts its values; the
+ # column drop rides the 6.1 cleanup.
+ add_column :spree_delivery_methods, :storefront_visible, :boolean
+
+ add_index :spree_fulfillments, :address_id
+ add_index :spree_fulfillments, :number, unique: true
+ add_index :spree_fulfillments, :order_id
+ add_index :spree_fulfillments, :stock_location_id
+
+ add_index :spree_fulfillment_items, :line_item_id
+ add_index :spree_fulfillment_items, :order_id
+ add_index :spree_fulfillment_items, :original_return_item_id
+ add_index :spree_fulfillment_items, :fulfillment_id
+ add_index :spree_fulfillment_items, :variant_id
+
+ add_index :spree_delivery_rates, :selected
+ add_index :spree_delivery_rates, [:fulfillment_id, :delivery_method_id], unique: true, name: 'spree_delivery_rates_join_index'
+ add_index :spree_delivery_rates, :fulfillment_id
+ add_index :spree_delivery_rates, :delivery_method_id
+ add_index :spree_delivery_rates, :tax_rate_id
+
+ add_index :spree_delivery_methods, :deleted_at
+ add_index :spree_delivery_methods, :tax_category_id
+
+ add_index :spree_delivery_method_zones, :delivery_method_id
+ add_index :spree_delivery_method_zones, :delivery_zone_id
+
+ add_index :spree_return_items, :fulfillment_item_id
+
+ add_index :spree_orders, :fulfillment_status
+ end
+end
diff --git a/spree/core/db/migrate/20260728000005_add_fulfillment_type_columns.rb b/spree/core/db/migrate/20260728000005_add_fulfillment_type_columns.rb
new file mode 100644
index 0000000000..3ad8b4414f
--- /dev/null
+++ b/spree/core/db/migrate/20260728000005_add_fulfillment_type_columns.rb
@@ -0,0 +1,33 @@
+class AddFulfillmentTypeColumns < ActiveRecord::Migration[7.2]
+ def change
+ # Defaults live on the model, not the DB; existing rows are backfilled by
+ # the spree:migrate_shipping_to_delivery data task.
+ add_column :spree_delivery_methods, :fulfillment_type, :string
+ add_index :spree_delivery_methods, :fulfillment_type
+ add_column :spree_delivery_methods, :fulfillment_provider, :string
+ add_column :spree_delivery_methods, :pickup_point_provider, :string
+
+ add_column :spree_fulfillments, :fulfillment_type, :string
+ if connection.adapter_name.downcase.include?('postgresql')
+ add_column :spree_fulfillments, :pickup_point_data, :jsonb
+ else
+ add_column :spree_fulfillments, :pickup_point_data, :json
+ end
+ add_reference :spree_fulfillments, :cart, null: true, if_not_exists: true
+
+ create_table :spree_delivery_method_stock_locations do |t|
+ t.references :delivery_method, null: false, index: false
+ t.references :stock_location, null: false
+
+ t.timestamps
+ end
+ add_index :spree_delivery_method_stock_locations, [:delivery_method_id, :stock_location_id],
+ unique: true, name: 'idx_delivery_method_stock_locations_uniqueness'
+
+ if connection.adapter_name.downcase.include?('postgresql')
+ add_column :spree_products, :excluded_delivery_method_ids, :jsonb
+ else
+ add_column :spree_products, :excluded_delivery_method_ids, :json
+ end
+ end
+end
diff --git a/spree/core/db/sample_data/shipping_methods.rb b/spree/core/db/sample_data/shipping_methods.rb
index c26a73353b..c3d2d561f6 100644
--- a/spree/core/db/sample_data/shipping_methods.rb
+++ b/spree/core/db/sample_data/shipping_methods.rb
@@ -1,41 +1,52 @@
+# Delivery zones are built from the seeded (tax) zones' geography — the Zone
+# model itself no longer links to delivery methods.
+def delivery_zone_from(zone)
+ return nil if zone.nil?
+
+ delivery_zone = Spree::DeliveryZone.find_or_create_by!(name: zone.name) do |dz|
+ dz.description = zone.description
+ end
+ zone.countries.each { |country| delivery_zone.members.find_or_create_by!(member_type: 'country', country: country) }
+ zone.states.each { |state| delivery_zone.members.find_or_create_by!(member_type: 'state', state: state) }
+ delivery_zone
+end
+
begin
- north_america = Spree::Zone.find_by!(name: 'North America')
+ north_america = delivery_zone_from(Spree::Zone.find_by!(name: 'North America'))
rescue ActiveRecord::RecordNotFound
puts "Couldn't find 'North America' zone. Did you run `rake db:seed` first?"
exit
end
-europe_vat = Spree::Zone.find_by!(name: 'EU_VAT')
-central_america_and_caribbean = Spree::Zone.find_by(name: 'Central America and Caribbean')
-south_america = Spree::Zone.find_by(name: 'South America')
-middle_east = Spree::Zone.find_by(name: 'Middle East')
-africa = Spree::Zone.find_by(name: 'Africa')
-asia = Spree::Zone.find_by(name: 'Asia')
-australia_and_oceania = Spree::Zone.find_by(name: 'Australia and Oceania')
-shipping_category = Spree::ShippingCategory.find_or_create_by!(name: 'Default')
-
-shipping_methods = [
- { name: 'UPS Ground (USD)', zones: [north_america], display_on: 'both', shipping_categories: [shipping_category] },
- { name: 'UPS Two Day (USD)', zones: [north_america], display_on: 'both', shipping_categories: [shipping_category] },
- { name: 'UPS One Day (USD)', zones: [north_america], display_on: 'both', shipping_categories: [shipping_category] },
- { name: 'UPS Ground (EU)', zones: [europe_vat], display_on: 'both', shipping_categories: [shipping_category] },
- { name: 'UPS Ground (EUR)', zones: [europe_vat], display_on: 'both', shipping_categories: [shipping_category] },
- { name: 'DHL Standard (Central America and Caribbean)', zones: [central_america_and_caribbean].compact, display_on: 'both', shipping_categories: [shipping_category] },
- { name: 'DHL Standard (South America)', zones: [south_america].compact, display_on: 'both', shipping_categories: [shipping_category] },
- { name: 'DHL Standard (Middle East)', zones: [middle_east].compact, display_on: 'both', shipping_categories: [shipping_category] },
- { name: 'DHL Standard (Africa)', zones: [africa].compact, display_on: 'both', shipping_categories: [shipping_category] },
- { name: 'DHL Standard (Asia)', zones: [asia].compact, display_on: 'both', shipping_categories: [shipping_category] },
- { name: 'DHL Standard (Australia and Oceania)', zones: [australia_and_oceania].compact, display_on: 'both', shipping_categories: [shipping_category] }
+europe_vat = delivery_zone_from(Spree::Zone.find_by!(name: 'EU_VAT'))
+central_america_and_caribbean = delivery_zone_from(Spree::Zone.find_by(name: 'Central America and Caribbean'))
+south_america = delivery_zone_from(Spree::Zone.find_by(name: 'South America'))
+middle_east = delivery_zone_from(Spree::Zone.find_by(name: 'Middle East'))
+africa = delivery_zone_from(Spree::Zone.find_by(name: 'Africa'))
+asia = delivery_zone_from(Spree::Zone.find_by(name: 'Asia'))
+australia_and_oceania = delivery_zone_from(Spree::Zone.find_by(name: 'Australia and Oceania'))
+
+delivery_methods = [
+ { name: 'UPS Ground (USD)', delivery_zones: [north_america], display_on: 'both' },
+ { name: 'UPS Two Day (USD)', delivery_zones: [north_america], display_on: 'both' },
+ { name: 'UPS One Day (USD)', delivery_zones: [north_america], display_on: 'both' },
+ { name: 'UPS Ground (EU)', delivery_zones: [europe_vat], display_on: 'both' },
+ { name: 'UPS Ground (EUR)', delivery_zones: [europe_vat], display_on: 'both' },
+ { name: 'DHL Standard (Central America and Caribbean)', delivery_zones: [central_america_and_caribbean].compact, display_on: 'both' },
+ { name: 'DHL Standard (South America)', delivery_zones: [south_america].compact, display_on: 'both' },
+ { name: 'DHL Standard (Middle East)', delivery_zones: [middle_east].compact, display_on: 'both' },
+ { name: 'DHL Standard (Africa)', delivery_zones: [africa].compact, display_on: 'both' },
+ { name: 'DHL Standard (Asia)', delivery_zones: [asia].compact, display_on: 'both' },
+ { name: 'DHL Standard (Australia and Oceania)', delivery_zones: [australia_and_oceania].compact, display_on: 'both' }
]
-shipping_methods.each do |attributes|
- next if attributes[:zones].empty?
+delivery_methods.each do |attributes|
+ next if attributes[:delivery_zones].empty?
- Spree::ShippingMethod.where(name: attributes[:name]).first_or_create! do |shipping_method|
- shipping_method.calculator = Spree::Calculator::Shipping::FlatRate.create!
- shipping_method.zones = attributes[:zones]
- shipping_method.display_on = attributes[:display_on]
- shipping_method.shipping_categories = attributes[:shipping_categories]
+ Spree::DeliveryMethod.where(name: attributes[:name]).first_or_create! do |delivery_method|
+ delivery_method.calculator = Spree::Calculator::Shipping::FlatRate.create!
+ delivery_method.delivery_zones = attributes[:delivery_zones]
+ delivery_method.display_on = attributes[:display_on]
end
end
@@ -51,11 +62,11 @@ end
'DHL Standard (Africa)' => [25, 'USD'],
'DHL Standard (Asia)' => [20, 'USD'],
'DHL Standard (Australia and Oceania)' => [25, 'USD']
-}.each do |shipping_method_name, (price, currency)|
- shipping_method = Spree::ShippingMethod.find_by(name: shipping_method_name)
- next unless shipping_method
+}.each do |delivery_method_name, (price, currency)|
+ delivery_method = Spree::DeliveryMethod.find_by(name: delivery_method_name)
+ next unless delivery_method
- shipping_method.calculator.preferences = { amount: price, currency: currency }
- shipping_method.calculator.save!
- shipping_method.save!
+ delivery_method.calculator.preferences = { amount: price, currency: currency }
+ delivery_method.calculator.save!
+ delivery_method.save!
end
diff --git a/spree/core/lib/spree/core/engine.rb b/spree/core/lib/spree/core/engine.rb
index d5087a4f7e..73336d9d5e 100644
--- a/spree/core/lib/spree/core/engine.rb
+++ b/spree/core/lib/spree/core/engine.rb
@@ -150,9 +150,8 @@ module Spree
]
Rails.application.config.spree.stock_splitters = [
- Spree::Stock::Splitter::ShippingCategory,
- Spree::Stock::Splitter::Backordered,
- Spree::Stock::Splitter::Digital
+ Spree::Stock::Splitter::FulfillmentType,
+ Spree::Stock::Splitter::Backordered
]
Rails.application.config.spree.payment_methods = [
@@ -335,8 +334,8 @@ module Spree
Spree::ProductType,
Spree::Promotion,
Spree::Refund,
- Spree::Shipment,
- Spree::ShippingMethod,
+ Spree::Fulfillment,
+ Spree::DeliveryMethod,
Spree::StockItem,
Spree::StockTransfer,
Spree::Store,
diff --git a/spree/core/lib/spree/testing_support/factories/delivery_method_factory.rb b/spree/core/lib/spree/testing_support/factories/delivery_method_factory.rb
new file mode 100644
index 0000000000..ad64d34946
--- /dev/null
+++ b/spree/core/lib/spree/testing_support/factories/delivery_method_factory.rb
@@ -0,0 +1,22 @@
+FactoryBot.define do
+ # Delivery methods are worldwide by default — geographic restriction is
+ # opt-in via an explicit :delivery_zone (empty zone list = no restriction).
+ factory :base_delivery_method, aliases: [:base_shipping_method], class: Spree::DeliveryMethod do
+ name { 'UPS Ground' }
+ code { 'UPS_GROUND' }
+ display_on { 'both' }
+
+ factory :delivery_method, aliases: [:shipping_method], class: Spree::DeliveryMethod do
+ association(:calculator, factory: :shipping_calculator, strategy: :build)
+ end
+
+ factory :free_delivery_method, aliases: [:free_shipping_method], class: Spree::DeliveryMethod do
+ association(:calculator, factory: :shipping_no_amount_calculator, strategy: :build)
+ end
+
+ factory :digital_delivery_method, aliases: [:digital_shipping_method], class: Spree::DeliveryMethod do
+ fulfillment_type { 'digital' }
+ association(:calculator, factory: :digital_shipping_calculator, strategy: :build)
+ end
+ end
+end
diff --git a/spree/core/lib/spree/testing_support/factories/delivery_rate_factory.rb b/spree/core/lib/spree/testing_support/factories/delivery_rate_factory.rb
new file mode 100644
index 0000000000..4d849f6845
--- /dev/null
+++ b/spree/core/lib/spree/testing_support/factories/delivery_rate_factory.rb
@@ -0,0 +1,7 @@
+FactoryBot.define do
+ factory :delivery_rate, aliases: [:shipping_rate], class: Spree::DeliveryRate do
+ cost { BigDecimal(10) }
+ delivery_method
+ fulfillment
+ end
+end
diff --git a/spree/core/lib/spree/testing_support/factories/fulfillment_factory.rb b/spree/core/lib/spree/testing_support/factories/fulfillment_factory.rb
new file mode 100644
index 0000000000..f0d0154c8f
--- /dev/null
+++ b/spree/core/lib/spree/testing_support/factories/fulfillment_factory.rb
@@ -0,0 +1,21 @@
+FactoryBot.define do
+ factory :fulfillment, aliases: [:shipment], class: Spree::Fulfillment do
+ tracking { 'U10000' }
+ cost { 100.00 }
+ status { 'pending' }
+ order
+ stock_location
+
+ after(:create) do |fulfillment, _evalulator|
+ fulfillment.add_delivery_method(create(:delivery_method), true)
+ fulfillment.order.line_items.map do |line_item|
+ fulfillment.fulfillment_items.create(
+ order_id: fulfillment.order_id,
+ variant_id: line_item.variant_id,
+ line_item_id: line_item.id,
+ quantity: line_item.quantity
+ )
+ end
+ end
+ end
+end
diff --git a/spree/core/lib/spree/testing_support/factories/fulfillment_item_factory.rb b/spree/core/lib/spree/testing_support/factories/fulfillment_item_factory.rb
new file mode 100644
index 0000000000..038daf7b79
--- /dev/null
+++ b/spree/core/lib/spree/testing_support/factories/fulfillment_item_factory.rb
@@ -0,0 +1,17 @@
+FactoryBot.define do
+ factory :fulfillment_item, aliases: [:inventory_unit], class: Spree::FulfillmentItem do
+ variant
+ order
+ line_item
+ status { 'on_hand' }
+
+ association(:fulfillment, factory: :fulfillment, status: 'pending')
+
+ # this trait usage increases build speed ~ 2x
+ trait :without_assoc do
+ fulfillment { nil }
+ order { nil }
+ line_item { nil }
+ end
+ end
+end
diff --git a/spree/core/lib/spree/testing_support/factories/inventory_unit_factory.rb b/spree/core/lib/spree/testing_support/factories/inventory_unit_factory.rb
deleted file mode 100644
index c6676c9ed6..0000000000
--- a/spree/core/lib/spree/testing_support/factories/inventory_unit_factory.rb
+++ /dev/null
@@ -1,18 +0,0 @@
-FactoryBot.define do
- factory :inventory_unit, class: Spree::InventoryUnit do
- variant
- order
- line_item
- state { 'on_hand' }
-
- association(:shipment, factory: :shipment, state: 'pending')
- # return_authorization
-
- # this trait usage increases build speed ~ 2x
- trait :without_assoc do
- shipment { nil }
- order { nil }
- line_item { nil }
- end
- end
-end
diff --git a/spree/core/lib/spree/testing_support/factories/market_factory.rb b/spree/core/lib/spree/testing_support/factories/market_factory.rb
index 8dd3e0480c..1be0e90e93 100644
--- a/spree/core/lib/spree/testing_support/factories/market_factory.rb
+++ b/spree/core/lib/spree/testing_support/factories/market_factory.rb
@@ -4,20 +4,13 @@ FactoryBot.define do
currency { 'USD' }
default_locale { 'en' }
store
- countries { [association(:country)] }
+ countries { [create(:country)] }
after(:build) do |market|
- if market.countries.any?
- zone = Spree::Zone.find_or_create_by!(name: 'Test Shipping Zone') do |z|
- z.kind = 'country'
- end
- market.countries.each do |country|
- zone.zone_members.find_or_create_by!(zoneable: country)
- end
- if zone.shipping_methods.empty?
- shipping_category = Spree::ShippingCategory.first || FactoryBot.create(:shipping_category)
- FactoryBot.create(:shipping_method, zones: [zone], shipping_categories: [shipping_category])
- end
+ # Delivery methods are worldwide by default (no zones), so serving the
+ # market's countries only requires that a method exists at all.
+ if market.countries.any? && !Spree::DeliveryMethod.where.missing(:delivery_method_zones).exists?
+ FactoryBot.create(:delivery_method)
end
end
diff --git a/spree/core/lib/spree/testing_support/factories/order_factory.rb b/spree/core/lib/spree/testing_support/factories/order_factory.rb
index f8a255555c..e266505e12 100644
--- a/spree/core/lib/spree/testing_support/factories/order_factory.rb
+++ b/spree/core/lib/spree/testing_support/factories/order_factory.rb
@@ -116,13 +116,13 @@ FactoryBot.define do
end
factory :shipped_order do
- shipment_state { 'shipped' }
+ shipment_state { 'fulfilled' }
after(:create) do |order|
- order.shipments.each do |shipment|
- shipment.inventory_units.update_all state: 'shipped'
+ order.fulfillments.each do |shipment|
+ shipment.fulfillment_items.update_all status: 'shipped'
shipment.update_columns(
- state: 'shipped',
+ status: 'fulfilled',
tracking: '1234567890'
)
end
diff --git a/spree/core/lib/spree/testing_support/factories/product_factory.rb b/spree/core/lib/spree/testing_support/factories/product_factory.rb
index 7601ce3fa1..ed0e83458b 100644
--- a/spree/core/lib/spree/testing_support/factories/product_factory.rb
+++ b/spree/core/lib/spree/testing_support/factories/product_factory.rb
@@ -99,7 +99,7 @@ FactoryBot.define do
factory :digital_product do
track_inventory { false }
- shipping_category { |r| Spree::ShippingCategory.digital || r.association(:digital_shipping_category) }
+ product_type { create(:product_type, name: "Digital #{SecureRandom.hex(4)}", fulfillment_types: ['digital']) }
end
end
end
diff --git a/spree/core/lib/spree/testing_support/factories/shipment_factory.rb b/spree/core/lib/spree/testing_support/factories/shipment_factory.rb
deleted file mode 100644
index 8d20df9715..0000000000
--- a/spree/core/lib/spree/testing_support/factories/shipment_factory.rb
+++ /dev/null
@@ -1,21 +0,0 @@
-FactoryBot.define do
- factory :shipment, class: Spree::Shipment do
- tracking { 'U10000' }
- cost { 100.00 }
- state { 'pending' }
- order
- stock_location
-
- after(:create) do |shipment, _evalulator|
- shipment.add_shipping_method(create(:shipping_method), true)
- shipment.order.line_items.map do |line_item|
- shipment.inventory_units.create(
- order_id: shipment.order_id,
- variant_id: line_item.variant_id,
- line_item_id: line_item.id,
- quantity: line_item.quantity
- )
- end
- end
- end
-end
diff --git a/spree/core/lib/spree/testing_support/factories/shipping_method_factory.rb b/spree/core/lib/spree/testing_support/factories/shipping_method_factory.rb
deleted file mode 100644
index 49da9a48f1..0000000000
--- a/spree/core/lib/spree/testing_support/factories/shipping_method_factory.rb
+++ /dev/null
@@ -1,31 +0,0 @@
-FactoryBot.define do
- factory :base_shipping_method, class: Spree::ShippingMethod do
- zones { |_a| [Spree::Zone.global] }
- name { 'UPS Ground' }
- code { 'UPS_GROUND' }
- display_on { 'both' }
-
- before(:create) do |shipping_method, _evaluator|
- if shipping_method.shipping_categories.empty?
- shipping_method.shipping_categories << (Spree::ShippingCategory.first || create(:shipping_category))
- end
- end
-
- factory :shipping_method, class: Spree::ShippingMethod do
- association(:calculator, factory: :shipping_calculator, strategy: :build)
- end
-
- factory :free_shipping_method, class: Spree::ShippingMethod do
- association(:calculator, factory: :shipping_no_amount_calculator, strategy: :build)
- end
-
- factory :digital_shipping_method, class: Spree::ShippingMethod do
- association(:calculator, factory: :digital_shipping_calculator, strategy: :build)
-
- before(:create) do |shipping_method|
- shipping_method.shipping_categories.delete_all
- shipping_method.shipping_categories << create(:digital_shipping_category)
- end
- end
- end
-end
diff --git a/spree/core/lib/spree/testing_support/factories/shipping_rate_factory.rb b/spree/core/lib/spree/testing_support/factories/shipping_rate_factory.rb
deleted file mode 100644
index 1ad027b902..0000000000
--- a/spree/core/lib/spree/testing_support/factories/shipping_rate_factory.rb
+++ /dev/null
@@ -1,7 +0,0 @@
-FactoryBot.define do
- factory :shipping_rate, class: Spree::ShippingRate do
- cost { BigDecimal(10) }
- shipping_method
- shipment
- end
-end
diff --git a/spree/core/spec/models/spree/base_spec.rb b/spree/core/spec/models/spree/base_spec.rb
index bb29e020bf..3d47e6bff4 100644
--- a/spree/core/spec/models/spree/base_spec.rb
+++ b/spree/core/spec/models/spree/base_spec.rb
@@ -47,7 +47,7 @@ describe Spree::Base do
end
describe '.api_type' do
- it { expect(Spree::InventoryUnit.api_type).to eq('inventory_unit') }
+ it { expect(Spree::FulfillmentItem.api_type).to eq('fulfillment_item') }
it { expect(Spree::Address.api_type).to eq('address') }
end
@@ -79,7 +79,7 @@ describe Spree::Base do
# Backwards-compatible alias retained for extensions that still call
# the old name; must delegate so subclass overrides (e.g.
# `Spree::Gateway.api_type`) propagate.
- it { expect(Spree::InventoryUnit.json_api_type).to eq('inventory_unit') }
+ it { expect(Spree::FulfillmentItem.json_api_type).to eq('fulfillment_item') }
it { expect(Spree::Address.json_api_type).to eq('address') }
it 'honors subclass overrides of .api_type' do
diff --git a/spree/core/spec/models/spree/calculator/shipping/digital_delivery_spec.rb b/spree/core/spec/models/spree/calculator/shipping/digital_delivery_spec.rb
index 308b33727c..eae3d1ccf9 100644
--- a/spree/core/spec/models/spree/calculator/shipping/digital_delivery_spec.rb
+++ b/spree/core/spec/models/spree/calculator/shipping/digital_delivery_spec.rb
@@ -23,7 +23,7 @@ RSpec.describe Spree::Calculator::Shipping::DigitalDelivery do
describe '#available?' do
let(:digital_shipping_method) { create(:digital_shipping_method) }
- let(:digital_product) { create(:product, shipping_category: digital_shipping_method.shipping_categories.first) }
+ let(:digital_product) { create(:digital_product) }
let(:digital_order) do
order = create(:order)
diff --git a/spree/core/spec/models/spree/line_item_spec.rb b/spree/core/spec/models/spree/line_item_spec.rb
index 262f127a0f..5a1258b512 100644
--- a/spree/core/spec/models/spree/line_item_spec.rb
+++ b/spree/core/spec/models/spree/line_item_spec.rb
@@ -209,10 +209,16 @@ describe Spree::LineItem, type: :model do
let(:variant) { create(:variant) }
before do
- create(:tax_rate, zone: order.tax_zone, tax_category: variant.tax_category)
+ create(:tax_rate, zone: tax_rate_zone, tax_category: variant.tax_category)
end
context 'when order has a tax zone' do
+ let(:tax_rate_zone) do
+ create(:zone, default_tax: true, kind: 'country').tap do |zone|
+ zone.zone_members.create!(zoneable: order.tax_address.country)
+ end
+ end
+
before do
expect(order.tax_zone).to be_present
end
@@ -225,6 +231,8 @@ describe Spree::LineItem, type: :model do
end
context 'when order does not have a tax zone' do
+ let(:tax_rate_zone) { create(:zone, kind: 'country') }
+
before do
order.bill_address = nil
order.ship_address = nil
diff --git a/spree/core/spec/models/spree/market_country_spec.rb b/spree/core/spec/models/spree/market_country_spec.rb
index 0be1a84e6c..9ba983c470 100644
--- a/spree/core/spec/models/spree/market_country_spec.rb
+++ b/spree/core/spec/models/spree/market_country_spec.rb
@@ -8,11 +8,11 @@ RSpec.describe Spree::MarketCountry, type: :model do
context 'when country is in a zone with a shipping method' do
let(:country) { create(:country) }
- let!(:zone) { create(:zone, kind: 'country') }
+ let!(:zone) { create(:delivery_zone) }
before do
- zone.zone_members.create!(zoneable: country)
- create(:shipping_method, zones: [zone])
+ zone.members.create!(member_type: 'country', country: country)
+ create(:shipping_method, delivery_zones: [zone])
end
it 'is valid' do
@@ -24,6 +24,14 @@ RSpec.describe Spree::MarketCountry, type: :model do
context 'when country has no shipping zone coverage' do
let(:country) { create(:country) }
+ before do
+ market # instantiate first — the factory may add a worldwide method
+ # scope any worldwide methods (e.g. the market factory's) elsewhere
+ elsewhere = create(:delivery_zone)
+ elsewhere.members.create!(member_type: 'country', country: create(:country))
+ Spree::DeliveryMethod.find_each { |dm| dm.delivery_zones = [elsewhere] if dm.delivery_zones.empty? }
+ end
+
it 'is invalid' do
market_country = Spree::MarketCountry.new(market: market, country: country)
expect(market_country).not_to be_valid
@@ -33,10 +41,14 @@ RSpec.describe Spree::MarketCountry, type: :model do
context 'when country is in a zone without a shipping method' do
let(:country) { create(:country) }
- let!(:zone) { create(:zone, kind: 'country') }
+ let!(:zone) { create(:delivery_zone) }
before do
- zone.zone_members.create!(zoneable: country)
+ market # instantiate first — the factory may add a worldwide method
+ zone.members.create!(member_type: 'country', country: country)
+ elsewhere = create(:delivery_zone)
+ elsewhere.members.create!(member_type: 'country', country: create(:country))
+ Spree::DeliveryMethod.find_each { |dm| dm.delivery_zones = [elsewhere] if dm.delivery_zones.empty? }
end
it 'is invalid' do
@@ -49,11 +61,11 @@ RSpec.describe Spree::MarketCountry, type: :model do
context 'when country is covered via a state-type zone' do
let(:country) { create(:country) }
let(:state) { create(:state, country: country) }
- let!(:zone) { create(:zone, kind: 'state') }
+ let!(:zone) { create(:delivery_zone) }
before do
- zone.zone_members.create!(zoneable: state)
- create(:shipping_method, zones: [zone])
+ zone.members.create!(member_type: 'state', state: state)
+ create(:shipping_method, delivery_zones: [zone])
end
it 'is valid' do
diff --git a/spree/core/spec/models/spree/order/adjustments_spec.rb b/spree/core/spec/models/spree/order/adjustments_spec.rb
index 1ecf826c98..9c97c9ecb7 100644
--- a/spree/core/spec/models/spree/order/adjustments_spec.rb
+++ b/spree/core/spec/models/spree/order/adjustments_spec.rb
@@ -48,7 +48,6 @@ describe Spree::Order do
let!(:shipping_method) do
sm = create(:shipping_method, tax_category: tax_category)
sm.calculator.preferred_amount = 10
- sm.zones = [zone]
sm.save
sm
end
diff --git a/spree/core/spec/models/spree/order/digital_spec.rb b/spree/core/spec/models/spree/order/digital_spec.rb
index 6052f98284..a1a4f63e17 100644
--- a/spree/core/spec/models/spree/order/digital_spec.rb
+++ b/spree/core/spec/models/spree/order/digital_spec.rb
@@ -2,7 +2,7 @@ require 'spec_helper'
describe Spree::Order, type: :model do
let(:digital_shipping_method) { create(:digital_shipping_method) }
- let(:digital_product) { create(:product, shipping_category: digital_shipping_method.shipping_categories.first) }
+ let(:digital_product) { create(:digital_product) }
context 'line_item analysis' do
it 'understands that all products are digital' do
diff --git a/spree/core/spec/models/spree/order/state_machine_spec.rb b/spree/core/spec/models/spree/order/state_machine_spec.rb
index d6d34dccaa..fbc805e7fa 100644
--- a/spree/core/spec/models/spree/order/state_machine_spec.rb
+++ b/spree/core/spec/models/spree/order/state_machine_spec.rb
@@ -67,7 +67,7 @@ describe Spree::Order, type: :model do
it 'adjusts tax rates twice if there are any shipments' do
# Once for the line items, once for the shipments
- order.shipments.build stock_location: create(:stock_location)
+ order.fulfillments.build stock_location: create(:stock_location)
expect(Spree::TaxRate).to receive(:adjust).twice
allow(order).to receive :set_shipments_cost
order.next!
diff --git a/spree/core/spec/models/spree/order_inventory_spec.rb b/spree/core/spec/models/spree/order_inventory_spec.rb
index db6bdbdac4..b45d886bfc 100644
--- a/spree/core/spec/models/spree/order_inventory_spec.rb
+++ b/spree/core/spec/models/spree/order_inventory_spec.rb
@@ -16,7 +16,7 @@ describe Spree::OrderInventory, type: :model do
end
context '#add_to_shipment' do
- let(:shipment) { order.shipments.first }
+ let(:shipment) { order.fulfillments.first }
context 'order is not completed' do
before { allow(order).to receive_messages completed?: false }
@@ -206,8 +206,8 @@ describe Spree::OrderInventory, type: :model do
end
it 'destroys self if not inventory units remain' do
- allow(shipment).to receive(:inventory_units).and_return(shipment.inventory_units)
- allow(shipment.inventory_units).to receive_messages(sum: 0)
+ allow(shipment).to receive(:fulfillment_items).and_return(shipment.fulfillment_items)
+ allow(shipment.fulfillment_items).to receive_messages(sum: 0)
expect(shipment).to receive(:destroy)
expect(subject.send(:remove_from_shipment, shipment, 1)).to eq(1)
@@ -241,7 +241,7 @@ describe Spree::OrderInventory, type: :model do
end
context '#verify with removing: true' do
- let(:shipment) { order.shipments.first }
+ let(:shipment) { order.fulfillments.first }
context 'when the line item has no inventory units yet' do
before { shipment.inventory_units.where(line_item_id: line_item.id).delete_all }
diff --git a/spree/core/spec/models/spree/order_routing/strategy/parity_spec.rb b/spree/core/spec/models/spree/order_routing/strategy/parity_spec.rb
index bf46748389..3c69b5b3db 100644
--- a/spree/core/spec/models/spree/order_routing/strategy/parity_spec.rb
+++ b/spree/core/spec/models/spree/order_routing/strategy/parity_spec.rb
@@ -419,38 +419,35 @@ RSpec.describe 'OrderRouting strategy parity', type: :model do
end
# ---------------------------------------------------------------
- # Splitter chain: shipping category split runs per-location
+ # Splitter chain: fulfillment-type split runs per-location
# ---------------------------------------------------------------
- context 'two variants with different shipping categories at same location' do
- let(:cat_light) { create(:shipping_category, name: 'Light') }
- let(:cat_heavy) { create(:shipping_category, name: 'Heavy') }
-
- let(:variant_light) { create(:variant, product: create(:product, shipping_category: cat_light)) }
- let(:variant_heavy) { create(:variant, product: create(:product, shipping_category: cat_heavy)) }
+ context 'two variants with different fulfillment types at same location' do
+ let(:variant_shipping) { create(:variant, product: create(:product)) }
+ let(:variant_digital) { create(:variant, product: create(:digital_product, track_inventory: true)) }
let(:order) do
o = create(:order, store: store, ship_address: create(:ship_address))
- create(:line_item, order: o, variant: variant_light, quantity: 1)
- create(:line_item, order: o, variant: variant_heavy, quantity: 1)
+ create(:line_item, order: o, variant: variant_shipping, quantity: 1)
+ create(:line_item, order: o, variant: variant_digital, quantity: 1)
o.reload
end
before do
- nyc.stock_item_or_create(variant_light).update!(count_on_hand: 10)
- nyc.stock_item_or_create(variant_heavy).update!(count_on_hand: 10)
+ nyc.stock_item_or_create(variant_shipping).update!(count_on_hand: 10)
+ nyc.stock_item_or_create(variant_digital).update!(count_on_hand: 10)
end
- # The ShippingCategory splitter is in the default Spree.stock_splitters
+ # The FulfillmentType splitter is in the default Spree.stock_splitters
# chain — Coordinator and Rules both pass it to the Packer, so each
- # location's allocation gets fanned out into one package per shipping
- # category. Both pipelines should produce 2 NYC packages here.
- it 'produces two NYC packages, one per shipping category' do
+ # location's allocation gets fanned out into one package per
+ # fulfillment-type set. Both pipelines should produce 2 NYC packages here.
+ it 'produces two NYC packages, one per fulfillment-type set' do
packages = strategy.for_allocation
nyc_packages = packages.select { |p| p.stock_location.id == nyc.id }
expect(nyc_packages.size).to eq(2)
- categories = nyc_packages.flat_map { |p| p.contents.map { |c| c.variant.product.shipping_category_id } }.uniq
- expect(categories).to contain_exactly(cat_light.id, cat_heavy.id)
+ type_sets = nyc_packages.map { |p| p.fulfillment_types.sort }
+ expect(type_sets).to contain_exactly(['digital'], ['shipping'])
expect(total_on_hand(packages)).to eq(2)
expect(total_backordered(packages)).to eq(0)
end
diff --git a/spree/core/spec/models/spree/order_spec.rb b/spree/core/spec/models/spree/order_spec.rb
index 12ca4b0b2c..5f57653715 100644
--- a/spree/core/spec/models/spree/order_spec.rb
+++ b/spree/core/spec/models/spree/order_spec.rb
@@ -213,7 +213,7 @@ describe Spree::Order, type: :model do
context 'when all shipments are canceled or ready' do
before do
order.update_columns(state: 'complete', completed_at: Time.current)
- order.shipments.delete_all
+ order.fulfillments.delete_all
create(:shipment, order: order, state: 'canceled')
create(:shipment, order: order, state: 'ready')
@@ -382,11 +382,11 @@ describe Spree::Order, type: :model do
let(:shipment) { double }
let(:order) { create(:order_with_line_items) }
- let(:shipment) { order.shipments.first }
+ let(:shipment) { order.fulfillments.first }
it 'update and persist totals' do
expect(shipment).to receive :update_amounts
- expect(order.updater).to receive :update_shipment_total
+ expect(order.updater).to receive :update_delivery_total
expect(order.updater).to receive :persist_totals
order.set_shipments_cost
@@ -905,7 +905,7 @@ describe Spree::Order, type: :model do
describe '#apply_free_shipping_promotions' do
it 'calls out to the FreeShipping promotion handler' do
shipment = double('Shipment')
- allow(order).to receive_messages shipments: [shipment]
+ allow(order).to receive_messages fulfillments: [shipment]
expect(Spree::PromotionHandler::FreeShipping).to receive(:new).and_return(handler = double)
expect(handler).to receive(:activate)
@@ -1350,7 +1350,7 @@ describe Spree::Order, type: :model do
before do
allow(shipments.first).to receive_messages(backordered?: true)
allow(shipments.second).to receive_messages(backordered?: false)
- allow(order).to receive_messages(shipments: shipments)
+ allow(order).to receive_messages(fulfillments: shipments)
end
it 'is backordered if one of the shipments is backordered' do
@@ -1562,7 +1562,7 @@ describe Spree::Order, type: :model do
allow(subject).to receive(:order_routing_strategy).and_return(strategy)
subject.create_proposed_shipments
- expect(subject.shipments).to eq [shipment]
+ expect(subject.fulfillments).to eq [shipment]
end
end
@@ -1705,7 +1705,7 @@ describe Spree::Order, type: :model do
before do
allow(order).to receive(:line_items) { [line_item] }
- allow(order).to receive(:shipments) { [shipment] }
+ allow(order).to receive(:fulfillments) { [shipment] }
allow(order).to receive(:payments) { [payment] }
end
@@ -1846,22 +1846,22 @@ describe Spree::Order, type: :model do
context 'when order has shipments' do
before do
- allow(order).to receive(:shipments).and_return(order_shipments)
+ allow(order).to receive(:fulfillments).and_return(order_shipments)
allow(order_shipments).to receive(:any?).and_return(true)
allow(Spree::TaxRate).to receive(:adjust).with(order, order_shipments)
end
it { expect(order_shipments).to receive(:any?).and_return(true) }
- it { expect(order).to receive(:shipments).and_return(order_shipments) }
+ it { expect(order).to receive(:fulfillments).and_return(order_shipments) }
it { expect(Spree::TaxRate).to receive(:adjust).with(order, order_shipments) }
end
context 'when order has no shipments' do
before do
- allow(order).to receive_message_chain(:shipments, :any?).and_return(false)
+ allow(order).to receive_message_chain(:fulfillments, :any?).and_return(false)
end
- it { expect(order).to receive_message_chain(:shipments, :any?).and_return(false) }
+ it { expect(order).to receive_message_chain(:fulfillments, :any?).and_return(false) }
end
end
@@ -2695,7 +2695,7 @@ describe Spree::Order, type: :model do
context 'when order has no shipments' do
before do
- order.shipments.delete_all
+ order.fulfillments.delete_all
end
it 'returns false and adds an error to the order' do
@@ -2758,8 +2758,7 @@ describe Spree::Order, type: :model do
end
context 'quick checkout' do
- let(:digital_shipping_method) { create(:digital_shipping_method) }
- let(:digital_product) { create(:product, shipping_category: digital_shipping_method.shipping_categories.first) }
+ let(:digital_product) { create(:digital_product) }
let(:digital_variant) { create(:variant, product: digital_product, digitals: [create(:digital)]) }
let(:digital_line_item) { create(:line_item, variant: digital_variant, quantity: 1, order: order) }
let(:physical_line_item) { create(:line_item, quantity: 1, order: order) }
diff --git a/spree/core/spec/models/spree/order_updater_spec.rb b/spree/core/spec/models/spree/order_updater_spec.rb
index e17436b3b3..418f9c4b68 100644
--- a/spree/core/spec/models/spree/order_updater_spec.rb
+++ b/spree/core/spec/models/spree/order_updater_spec.rb
@@ -80,38 +80,44 @@ module Spree
context 'updating shipment state' do
before do
allow(order).to receive_messages backordered?: false
- allow(order).to receive_message_chain(:shipments, :shipped, :count).and_return(0)
- allow(order).to receive_message_chain(:shipments, :ready, :count).and_return(0)
- allow(order).to receive_message_chain(:shipments, :pending, :count).and_return(0)
+ allow(order).to receive_message_chain(:fulfillments, :shipped, :count).and_return(0)
+ allow(order).to receive_message_chain(:fulfillments, :ready, :count).and_return(0)
+ allow(order).to receive_message_chain(:fulfillments, :pending, :count).and_return(0)
end
it 'is backordered' do
allow(order).to receive_messages backordered?: true
- updater.update_shipment_state
+ updater.update_fulfillment_status
- expect(order.shipment_state).to eq('backorder')
+ expect(order.fulfillment_status).to eq('backorder')
end
it 'is nil' do
- allow(order).to receive_message_chain(:shipments, :states).and_return([])
- allow(order).to receive_message_chain(:shipments, :count).and_return(0)
+ allow(order).to receive_message_chain(:fulfillments, :states).and_return([])
+ allow(order).to receive_message_chain(:fulfillments, :count).and_return(0)
- updater.update_shipment_state
- expect(order.shipment_state).to be_nil
+ updater.update_fulfillment_status
+ expect(order.fulfillment_status).to be_nil
end
- ['shipped', 'ready', 'pending'].each do |state|
- it "is #{state}" do
- allow(order).to receive_message_chain(:shipments, :states).and_return([state])
- updater.update_shipment_state
- expect(order.shipment_state).to eq(state.to_s)
+ ['fulfilled', 'ready', 'pending'].each do |status|
+ it "is #{status}" do
+ allow(order).to receive_message_chain(:fulfillments, :states).and_return([status])
+ updater.update_fulfillment_status
+ expect(order.fulfillment_status).to eq(status.to_s)
end
end
+ it 'rolls ready_for_pickup up as ready' do
+ allow(order).to receive_message_chain(:fulfillments, :states).and_return(['ready_for_pickup'])
+ updater.update_fulfillment_status
+ expect(order.fulfillment_status).to eq('ready')
+ end
+
it 'is partial' do
- allow(order).to receive_message_chain(:shipments, :states).and_return(['pending', 'shipped'])
- updater.update_shipment_state
- expect(order.shipment_state).to eq('partial')
+ allow(order).to receive_message_chain(:fulfillments, :states).and_return(['pending', 'fulfilled'])
+ updater.update_fulfillment_status
+ expect(order.fulfillment_status).to eq('partial')
end
end
@@ -228,15 +234,15 @@ module Spree
updater.update
end
- it 'updates shipment state' do
- expect(updater).to receive(:update_shipment_state)
+ it 'updates fulfillment status' do
+ expect(updater).to receive(:update_fulfillment_status)
updater.update
end
- it 'updates shipments total again after updating shipments' do
- expect(updater).to receive(:update_shipment_total).ordered
- expect(updater).to receive(:update_shipments).ordered
- expect(updater).to receive(:update_shipment_total).ordered
+ it 'updates delivery total again after updating fulfillments' do
+ expect(updater).to receive(:update_delivery_total).ordered
+ expect(updater).to receive(:update_fulfillments).ordered
+ expect(updater).to receive(:update_delivery_total).ordered
updater.update
end
end
@@ -246,28 +252,28 @@ module Spree
let(:shipments) { [shipment] }
it 'updates each shipment' do
- allow(order).to receive_messages shipments: shipments
+ allow(order).to receive_messages fulfillments: shipments
allow(shipments).to receive_messages states: []
allow(shipments).to receive_messages ready: []
allow(shipments).to receive_messages pending: []
allow(shipments).to receive_messages shipped: []
expect(shipment).to receive(:update!).with(order)
- updater.update_shipments
+ updater.update_fulfillments
end
it 'refreshes shipment rates' do
- allow(order).to receive_messages shipments: shipments
+ allow(order).to receive_messages fulfillments: shipments
expect(shipment).to receive(:refresh_rates)
- updater.update_shipments
+ updater.update_fulfillments
end
it 'updates the shipment amount' do
- allow(order).to receive_messages shipments: shipments
+ allow(order).to receive_messages fulfillments: shipments
expect(shipment).to receive(:update_amounts)
- updater.update_shipments
+ updater.update_fulfillments
end
context 'refresh rates' do
diff --git a/spree/core/spec/models/spree/payment_spec.rb b/spree/core/spec/models/spree/payment_spec.rb
index 46abcd8d92..a1a35889cd 100644
--- a/spree/core/spec/models/spree/payment_spec.rb
+++ b/spree/core/spec/models/spree/payment_spec.rb
@@ -819,7 +819,7 @@ describe Spree::Payment, type: :model do
it 'updates payment_state and shipments' do
expect(order.updater).to receive(:update_payment_state)
- expect(order.updater).to receive(:update_shipment_state)
+ expect(order.updater).to receive(:update_fulfillment_status)
Spree::Payment.create(amount: 100, order: order, payment_method: gateway, source: card)
end
end
diff --git a/spree/core/spec/models/spree/product_spec.rb b/spree/core/spec/models/spree/product_spec.rb
index 88883e538f..0e63c0eae9 100644
--- a/spree/core/spec/models/spree/product_spec.rb
+++ b/spree/core/spec/models/spree/product_spec.rb
@@ -35,36 +35,15 @@ describe Spree::Product, type: :model do
end
end
- describe 'before_validation :ensure_default_shipping_category' do
- subject { product.valid? }
+ describe 'shipping category' do
+ # ShippingCategory is retired from behavior in 6.0 (delivery eligibility
+ # comes from ProductType#fulfillment_types); the association is optional
+ # until the 6.1 column drop.
+ it 'is not required' do
+ product = build(:product, shipping_category: nil)
- let(:product) { build(:product, shipping_category: nil) }
-
- let!(:shipping_category_1) { create(:shipping_category, name: I18n.t('spree.seed.shipping.categories.digital')) }
- let!(:shipping_category_2) { create(:shipping_category, name: I18n.t('spree.seed.shipping.categories.default')) }
-
- it 'assigns the default shipping category' do
- subject
- expect(product.shipping_category).to eq(shipping_category_2)
- end
-
- context 'when product has a shipping category' do
- let(:product) { build(:product, shipping_category: shipping_category_1) }
-
- it 'keeps the assigned shipping category' do
- subject
- expect(product.shipping_category).to eq(shipping_category_1)
- end
- end
-
- context 'when product is persisted' do
- let(:product) { create(:product) }
-
- it 'does not assign the default shipping category' do
- product.update(shipping_category: nil)
- expect(subject).to be(false)
- expect(product.shipping_category).to be(nil)
- end
+ expect(product).to be_valid
+ expect(product.shipping_category).to be_nil
end
end
@@ -1186,19 +1165,18 @@ describe Spree::Product, type: :model do
end
describe '#digital?' do
- let(:product) { create(:product, shipping_category: shipping_category) }
- let(:shipping_category) { create(:shipping_category) }
-
- context 'when product has a shipping method with DigitalDelivery calculator' do
- let!(:shipping_method) { create(:shipping_method, calculator: Spree::Calculator::Shipping::DigitalDelivery.new, shipping_categories: [shipping_category]) }
+ context 'when the product type is digital-only' do
+ let(:product) { create(:digital_product) }
it { expect(product.digital?).to eq(true) }
+ it { expect(product.fulfillment_types).to eq(['digital']) }
end
- context 'when product does not have a shipping method with DigitalDelivery calculator' do
- let!(:shipping_method) { create(:shipping_method, calculator: Spree::Calculator::Shipping::FlatRate.new, shipping_categories: [shipping_category]) }
+ context 'when the product has no type' do
+ let(:product) { create(:product) }
it { expect(product.digital?).to eq(false) }
+ it { expect(product.fulfillment_types).to eq(['shipping']) }
end
end
end
diff --git a/spree/core/spec/models/spree/shipment_spec.rb b/spree/core/spec/models/spree/shipment_spec.rb
index c8131bae53..c8e6f20e3c 100644
--- a/spree/core/spec/models/spree/shipment_spec.rb
+++ b/spree/core/spec/models/spree/shipment_spec.rb
@@ -9,7 +9,7 @@ describe Spree::Shipment, type: :model do
let(:shipment) do
create(:shipment, number: 'H21265865494', cost: 1, state: 'pending', stock_location: create(:stock_location)).tap do |shipment|
allow(shipment).to receive_messages order: order
- allow(shipment).to receive_messages shipping_method: shipping_method
+ allow(shipment).to receive_messages(delivery_method: shipping_method, shipping_method: shipping_method)
end
end
let(:shipping_method) { create(:shipping_method, name: 'UPS') }
@@ -35,12 +35,12 @@ describe Spree::Shipment, type: :model do
end
describe '#digital?' do
- it 'returns true if shipping method has a digital calculator' do
- shipment.shipping_method.calculator = Spree::Calculator::Shipping::DigitalDelivery.new
+ it 'returns true if the delivery method is digital' do
+ shipment.delivery_method.fulfillment_type = 'digital'
expect(shipment.digital?).to eq(true)
end
- it 'returns false if shipping method does not have a digital calculator' do
+ it 'returns false if the delivery method is not digital' do
expect(shipment.digital?).to eq(false)
end
@@ -96,19 +96,21 @@ describe Spree::Shipment, type: :model do
# Regression test for #4063
context 'number generation' do
+ let(:shipment) { create(:shipment, stock_location: create(:stock_location)) }
+
before do
allow(order).to receive :update_with_updater!
end
it 'generates a number containing a letter + 11 numbers' do
- expect(shipment.number[0]).to eq('H')
+ expect(shipment.number[0]).to eq('F')
expect(/\d{11}/.match(shipment.number)).not_to be_nil
expect(shipment.number.length).to eq(12)
end
end
it 'is backordered if one if its inventory_units is backordered' do
- allow(shipment).to receive_messages(inventory_units: inventory_units)
+ allow(shipment).to receive_messages(fulfillment_items: inventory_units)
expect(shipment).to be_backordered
end
@@ -137,9 +139,9 @@ describe Spree::Shipment, type: :model do
expect(shipment.determine_state(order)).to eq 'pending'
end
- it 'returns shipped when already shipped' do
- allow(shipment).to receive_messages state: 'shipped'
- expect(shipment.determine_state(order)).to eq 'shipped'
+ it 'returns fulfilled when already fulfilled' do
+ allow(shipment).to receive_messages fulfilled?: true
+ expect(shipment.determine_state(order)).to eq 'fulfilled'
end
it 'returns pending when unpaid' do
@@ -422,7 +424,7 @@ describe Spree::Shipment, type: :model do
describe '#can_get_rates?' do
let(:digital_shipping_method) { create(:digital_shipping_method) }
- let(:digital_product) { create(:product, shipping_category: digital_shipping_method.shipping_categories.first) }
+ let(:digital_product) { create(:digital_product) }
let(:digital_line_item) { create(:line_item, variant: create(:variant, product: digital_product)) }
it 'returns true if order is digital and it does not have a ship address' do
@@ -476,7 +478,7 @@ describe Spree::Shipment, type: :model do
it 'requests new rates, and maintain shipping_method selection' do
expect(Spree::Stock::Estimator).to receive(:new).with(shipment.order).and_return(mock_estimator)
- allow(shipment).to receive_messages(shipping_method: shipping_method2)
+ allow(shipment).to receive_messages(delivery_method: shipping_method2)
expect(shipment.refresh_rates).to eq(shipping_rates)
expect(shipment.reload.selected_shipping_rate.shipping_method_id).to eq(shipping_method2.id)
@@ -484,7 +486,7 @@ describe Spree::Shipment, type: :model do
it 'handles no shipping_method selection' do
expect(Spree::Stock::Estimator).to receive(:new).with(shipment.order).and_return(mock_estimator)
- allow(shipment).to receive_messages(shipping_method: nil)
+ allow(shipment).to receive_messages(delivery_method: nil)
expect(shipment.refresh_rates).to eq(shipping_rates)
expect(shipment.reload.selected_shipping_rate).not_to be_nil
end
@@ -492,7 +494,7 @@ describe Spree::Shipment, type: :model do
it 'does not refresh if shipment is shipped' do
expect(Spree::Stock::Estimator).not_to receive(:new)
shipment.shipping_rates.delete_all
- allow(shipment).to receive_messages(shipped?: true)
+ allow(shipment).to receive_messages(fulfilled?: true)
expect(shipment.refresh_rates).to eq([])
end
@@ -508,7 +510,7 @@ describe Spree::Shipment, type: :model do
end
before do
- allow(shipment).to receive(:inventory_units) { inventory_units }
+ allow(shipment).to receive(:fulfillment_items) { inventory_units }
allow(inventory_units).to receive_message_chain(:includes, :joins).and_return inventory_units
end
@@ -522,18 +524,18 @@ describe Spree::Shipment, type: :model do
end
describe '#update!' do
- shared_examples_for 'immutable once shipped' do
- it 'remains in shipped state once shipped' do
- shipment.state = 'shipped'
- expect(shipment).to receive(:update_columns).with(state: 'shipped', updated_at: kind_of(Time))
+ shared_examples_for 'immutable once fulfilled' do
+ it 'remains in fulfilled status once fulfilled' do
+ shipment.status = 'fulfilled'
+ expect(shipment).to receive(:update_columns).with(status: 'fulfilled', updated_at: kind_of(Time))
shipment.update!(order)
end
end
shared_examples_for 'pending if backordered' do
- it 'has a state of pending if backordered' do
- allow(shipment).to receive_messages(inventory_units: inventory_units)
- expect(shipment).to receive(:update_columns).with(state: 'pending', updated_at: kind_of(Time))
+ it 'has a status of pending if backordered' do
+ allow(shipment).to receive_messages(fulfillment_items: inventory_units)
+ expect(shipment).to receive(:update_columns).with(status: 'pending', updated_at: kind_of(Time))
shipment.update!(order)
end
end
@@ -542,7 +544,7 @@ describe Spree::Shipment, type: :model do
before { allow(order).to receive_messages can_ship?: false }
it "results in a 'pending' state" do
- expect(shipment).to receive(:update_columns).with(state: 'pending', updated_at: kind_of(Time))
+ expect(shipment).to receive(:update_columns).with(status: 'pending', updated_at: kind_of(Time))
shipment.update!(order)
end
end
@@ -551,11 +553,11 @@ describe Spree::Shipment, type: :model do
before { allow(order).to receive_messages paid?: true }
it "results in a 'ready' state" do
- expect(shipment).to receive(:update_columns).with(state: 'ready', updated_at: kind_of(Time))
+ expect(shipment).to receive(:update_columns).with(status: 'ready', updated_at: kind_of(Time))
shipment.update!(order)
end
- it_behaves_like 'immutable once shipped'
+ it_behaves_like 'immutable once fulfilled'
it_behaves_like 'pending if backordered'
end
@@ -563,12 +565,12 @@ describe Spree::Shipment, type: :model do
before { allow(order).to receive_messages paid?: false }
it "results in a 'pending' state" do
- shipment.state = 'ready'
- expect(shipment).to receive(:update_columns).with(state: 'pending', updated_at: kind_of(Time))
+ shipment.status = 'ready'
+ expect(shipment).to receive(:update_columns).with(status: 'pending', updated_at: kind_of(Time))
shipment.update!(order)
end
- it_behaves_like 'immutable once shipped'
+ it_behaves_like 'immutable once fulfilled'
it_behaves_like 'pending if backordered'
end
@@ -576,60 +578,34 @@ describe Spree::Shipment, type: :model do
before { allow(order).to receive_messages payment_state: 'credit_owed', paid?: true }
it "results in a 'ready' state" do
- shipment.state = 'pending'
- expect(shipment).to receive(:update_columns).with(state: 'ready', updated_at: kind_of(Time))
+ shipment.status = 'pending'
+ expect(shipment).to receive(:update_columns).with(status: 'ready', updated_at: kind_of(Time))
shipment.update!(order)
end
- it_behaves_like 'immutable once shipped'
+ it_behaves_like 'immutable once fulfilled'
it_behaves_like 'pending if backordered'
end
- context 'when shipment state changes to shipped' do
- before do
- allow_any_instance_of(Spree::ShipmentHandler).to receive(:update_order_shipment_state)
- end
-
- it 'calls after_ship' do
- shipment.state = 'pending'
- expect(shipment).to receive :after_ship
- allow(shipment).to receive_messages determine_state: 'shipped'
- expect(shipment).to receive(:update_columns).with(state: 'shipped', updated_at: kind_of(Time))
+ context 'when fulfillment status changes to fulfilled' do
+ it 'calls after_fulfill' do
+ shipment.status = 'pending'
+ expect(shipment).to receive :after_fulfill
+ allow(shipment).to receive_messages determine_state: 'fulfilled'
+ expect(shipment).to receive(:update_columns).with(status: 'fulfilled', updated_at: kind_of(Time))
shipment.update!(order)
end
- context 'when using the default shipment handler' do
- it "calls the 'perform' method" do
- shipment.state = 'pending'
- allow(shipment).to receive_messages determine_state: 'shipped'
- expect_any_instance_of(Spree::ShipmentHandler).to receive(:perform)
- shipment.update!(order)
- end
- end
+ # ShipmentHandler was removed in 6.0 — after_fulfill owns the mechanics
+ # until FulfillmentProvider takes over type-specific behavior.
+ it 'ships the items and stamps fulfilled_at' do
+ shipment.status = 'pending'
+ allow(shipment).to receive_messages determine_state: 'fulfilled'
- context 'when using a custom shipment handler' do
- before do
- Spree::ShipmentHandler::UPS = Class.new do
- def initialize(_shipment)
- true
- end
-
- def perform
- true
- end
- end
- end
-
- after do
- Spree::ShipmentHandler.send(:remove_const, :UPS)
- end
+ shipment.update!(order)
- it "calls the custom handler's 'perform' method" do
- shipment.state = 'pending'
- allow(shipment).to receive_messages determine_state: 'shipped'
- expect_any_instance_of(Spree::ShipmentHandler::UPS).to receive(:perform)
- shipment.update!(order)
- end
+ expect(shipment.reload.fulfilled_at).to be_present
+ expect(shipment.fulfillment_items.reload).to all(be_shipped)
end
# Regression test for #4347
@@ -685,7 +661,7 @@ describe Spree::Shipment, type: :model do
end
it 'restocks the items' do
- allow(shipment).to receive(:inventory_units).and_return([inventory_unit])
+ allow(shipment).to receive(:fulfillment_items).and_return([inventory_unit])
shipment.stock_location = create(:stock_location)
expect(shipment.stock_location).to receive(:restock).with(variant, 1, shipment)
shipment.after_cancel
@@ -745,7 +721,7 @@ describe Spree::Shipment, type: :model do
end
it 'unstocks them items' do
- allow(shipment).to receive(:inventory_units).and_return([inventory_unit])
+ allow(shipment).to receive(:fulfillment_items).and_return([inventory_unit])
shipment.stock_location = create(:stock_location)
expect(shipment.stock_location).to receive(:unstock).with(variant, 1, shipment)
shipment.after_resume
@@ -755,7 +731,7 @@ describe Spree::Shipment, type: :model do
before { variant.update(track_inventory: false) }
it 'skips unstocking the shipment item' do
- allow(shipment).to receive(:inventory_units).and_return([inventory_unit])
+ allow(shipment).to receive(:fulfillment_items).and_return([inventory_unit])
shipment.stock_location = create(:stock_location)
expect(shipment.stock_location).not_to receive(:unstock)
shipment.after_resume
@@ -774,35 +750,32 @@ describe Spree::Shipment, type: :model do
end
it 'unstocks them items' do
- allow_any_instance_of(Spree::ShipmentHandler).to receive(:update_order_shipment_state)
expect(shipment_with_inventory_units.stock_location).to receive(:unstock)
subject
end
end
- ['ready', 'canceled'].each do |state|
- context "from #{state}" do
+ ['ready', 'canceled'].each do |status|
+ context "from #{status}" do
before do
allow(order).to receive(:update_with_updater!)
- allow(shipment).to receive_messages(require_inventory: false, update_order: true, state: state)
+ allow(shipment).to receive_messages(require_inventory: false, update_order: true, status: status)
end
- it 'updates shipped_at timestamp' do
- allow_any_instance_of(Spree::ShipmentHandler).to receive(:update_order_shipment_state)
+ it 'updates fulfilled_at timestamp' do
- shipment.ship!
- expect(shipment.shipped_at).not_to be_nil
+ shipment.fulfill!
+ expect(shipment.fulfilled_at).not_to be_nil
# Ensure value is persisted
shipment.reload
- expect(shipment.shipped_at).not_to be_nil
+ expect(shipment.fulfilled_at).not_to be_nil
end
it 'finalizes adjustments' do
- allow_any_instance_of(Spree::ShipmentHandler).to receive(:update_order_shipment_state)
expect(shipment.adjustments).to all(receive(:finalize!))
- shipment.ship!
+ shipment.fulfill!
end
end
end
@@ -821,7 +794,7 @@ describe Spree::Shipment, type: :model do
before do
Spree::Config[:auto_capture_on_dispatch] = true
@order = create :completed_order_with_pending_payment
- @shipment = @order.shipments.first
+ @shipment = @order.fulfillments.first
@shipment.cost = @order.ship_total
end
@@ -871,7 +844,7 @@ describe Spree::Shipment, type: :model do
context 'updates cost when selected shipping rate is present' do
let(:shipment) { create(:shipment) }
- before { allow(shipment).to receive_message_chain :selected_shipping_rate, cost: 5 }
+ before { allow(shipment).to receive_message_chain :selected_delivery_rate, cost: 5 }
it 'updates shipment totals' do
shipment.update_amounts
@@ -1120,10 +1093,10 @@ describe Spree::Shipment, type: :model do
let(:variant) { double('Variant', id: 9) }
let(:params) do
- { variant_id: variant.id, state: 'on_hand', order_id: order.id, line_item_id: line_item.id, quantity: 1 }
+ { variant_id: variant.id, status: 'on_hand', order_id: order.id, line_item_id: line_item.id, quantity: 1 }
end
- before { allow(shipment).to receive_messages inventory_units: inventory_units }
+ before { allow(shipment).to receive_messages fulfillment_items: inventory_units }
it 'associates variant and order' do
expect(inventory_units).to receive(:create).with(params)
@@ -1133,8 +1106,8 @@ describe Spree::Shipment, type: :model do
# Regression test for #3349
describe '#destroy' do
- it 'destroys linked shipping_rates' do
- reflection = Spree::Shipment.reflect_on_association(:shipping_rates)
+ it 'destroys linked delivery_rates' do
+ reflection = Spree::Fulfillment.reflect_on_association(:delivery_rates)
expect(reflection.options[:dependent]).to be(:delete_all)
end
end
@@ -1162,7 +1135,7 @@ describe Spree::Shipment, type: :model do
let!(:ready_shipments) { create_list(:shipment, 2, state: 'ready') }
let!(:pending_shipments) { create_list(:shipment, 2, state: 'pending') }
- let!(:shipped_shipments) { create_list(:shipment, 2, state: 'shipped') }
+ let!(:shipped_shipments) { create_list(:shipment, 2, status: 'fulfilled') }
it 'returns shipments with state ready or pending' do
expect(subject.pluck(:state).uniq).to contain_exactly('ready', 'pending')
diff --git a/spree/core/spec/models/spree/shipping_category_spec.rb b/spree/core/spec/models/spree/shipping_category_spec.rb
index abf1df8eae..55c0dbc4f0 100644
--- a/spree/core/spec/models/spree/shipping_category_spec.rb
+++ b/spree/core/spec/models/spree/shipping_category_spec.rb
@@ -16,11 +16,4 @@ describe Spree::ShippingCategory, type: :model do
end
end
- describe '#includes_digital_shipping_method?' do
- it 'returns true if the shipping category includes a digital shipping method' do
- shipping_category = create(:shipping_category)
- create(:shipping_method, shipping_categories: [shipping_category], calculator: create(:digital_shipping_calculator))
- expect(shipping_category.includes_digital_shipping_method?).to be_truthy
- end
- end
end
diff --git a/spree/core/spec/models/spree/shipping_method_spec.rb b/spree/core/spec/models/spree/shipping_method_spec.rb
index c3a7d4e2cc..4c5fac277a 100644
--- a/spree/core/spec/models/spree/shipping_method_spec.rb
+++ b/spree/core/spec/models/spree/shipping_method_spec.rb
@@ -85,52 +85,6 @@ describe Spree::ShippingMethod, type: :model do
expect(subject.errors.messages[:display_on].size).not_to be_zero
end
- context 'shipping category' do
- context 'is required' do
- before { subject.valid? }
-
- it { expect(subject.errors.messages[:base].size).to eq(1) }
- it 'adds error to base' do
- expect(subject.errors.messages[:base]).to include(I18n.t(:required_shipping_category,
- scope: [
- :activerecord, :errors, :models,
- 'spree/shipping_method', :attributes, :base
- ]))
- end
- end
-
- context 'one associated' do
- before { subject.shipping_categories.push(create(:shipping_category)) }
-
- it { expect(subject.errors.messages[:base]).to be_empty }
- end
- end
- end
-
- context 'factory' do
- it 'sets calculable correctly' do
- expect(shipping_method.calculator.calculable).to eq(shipping_method)
- end
- end
-
- describe '#build_tracking_url' do
- context 'shipping method has a tracking URL mask on file' do
- let(:tracking_url) { 'https://track-o-matic.com/:tracking' }
-
- before { allow(subject).to receive(:tracking_url) { tracking_url } }
-
- context 'tracking number has spaces' do
- let(:tracking_numbers) { ['1234 5678 9012 3456', 'a bcdef'] }
- let(:expectations) { %w[https://track-o-matic.com/1234%205678%209012%203456 https://track-o-matic.com/A%20BCDEF] }
-
- it "returns a single URL with '%20' in lieu of spaces" do
- tracking_numbers.each_with_index do |num, i|
- expect(subject.build_tracking_url(num)).to eq(expectations[i])
- end
- end
- end
- end
-
context 'shipping method does not have a tracking URL mask on file' do
let(:usps_tracking_number) { '1Z879E930346834440' }
diff --git a/spree/core/spec/models/spree/stock/availability_validator_spec.rb b/spree/core/spec/models/spree/stock/availability_validator_spec.rb
index d2d95a9882..fc7fd8d5df 100644
--- a/spree/core/spec/models/spree/stock/availability_validator_spec.rb
+++ b/spree/core/spec/models/spree/stock/availability_validator_spec.rb
@@ -31,7 +31,7 @@ module Spree
it 'considers existing inventory_units sufficient' do
allow_any_instance_of(Stock::Quantifier).to receive_messages(can_supply?: false)
expect(line_item).not_to receive(:errors)
- allow(line_item).to receive_messages(inventory_units: inventory_units)
+ allow(line_item).to receive_messages(fulfillment_items: inventory_units)
subject.validate(line_item)
end
diff --git a/spree/core/spec/models/spree/stock/estimator_spec.rb b/spree/core/spec/models/spree/stock/estimator_spec.rb
index 4bf4d47beb..e38bebf892 100644
--- a/spree/core/spec/models/spree/stock/estimator_spec.rb
+++ b/spree/core/spec/models/spree/stock/estimator_spec.rb
@@ -13,13 +13,12 @@ module Spree
context '#shipping rates' do
before do
- shipping_method.zones.first.members.create(zoneable: order.ship_address.country)
allow_any_instance_of(ShippingMethod).to receive_message_chain(:calculator, :available?).and_return(true)
allow_any_instance_of(ShippingMethod).to receive_message_chain(:calculator, :compute).and_return(4.00)
allow_any_instance_of(ShippingMethod).to receive_message_chain(:calculator, :preferences).and_return(currency: currency)
allow_any_instance_of(ShippingMethod).to receive_message_chain(:calculator, :marked_for_destruction?)
- allow(package).to receive_messages(shipping_methods: [shipping_method])
+ allow(package).to receive_messages(eligible_delivery_methods: [shipping_method])
end
let(:currency) { 'USD' }
@@ -43,7 +42,12 @@ module Spree
end
context "when the order's ship address is in a different zone" do
- before { shipping_method.zones.each { |z| z.members.delete_all } }
+ before do
+ other_country = create(:country, iso: 'XZ', iso3: 'XZZ', name: 'Elsewhere', iso_name: 'ELSEWHERE')
+ zone = create(:delivery_zone)
+ zone.members.create!(member_type: 'country', country: other_country)
+ shipping_method.delivery_zones = [zone]
+ end
it_behaves_like "shipping rate doesn't match"
end
@@ -116,7 +120,7 @@ module Spree
before do
allow(backend_method).to receive_message_chain(:calculator, :compute).and_return(0.00)
allow(generic_method).to receive_message_chain(:calculator, :compute).and_return(5.00)
- allow(package).to receive(:shipping_methods).and_return([backend_method, generic_method])
+ allow(package).to receive(:eligible_delivery_methods).and_return([backend_method, generic_method])
end
it 'does not return backend rates at all' do
@@ -130,7 +134,12 @@ module Spree
end
context 'includes tax adjustments if applicable' do
- let!(:tax_rate) { create(:tax_rate, zone: order.tax_zone) }
+ let!(:default_tax_zone) do
+ create(:zone, default_tax: true, kind: 'country').tap do |zone|
+ zone.zone_members.create!(zoneable: ship_address.country)
+ end
+ end
+ let!(:tax_rate) { create(:tax_rate, zone: default_tax_zone) }
before do
Spree::ShippingMethod.all.each do |sm|
diff --git a/spree/core/spec/models/spree/stock/package_spec.rb b/spree/core/spec/models/spree/stock/package_spec.rb
index f72831a597..0f73d17122 100644
--- a/spree/core/spec/models/spree/stock/package_spec.rb
+++ b/spree/core/spec/models/spree/stock/package_spec.rb
@@ -57,33 +57,39 @@ module Spree
expect(item.quantity).to eq 1
end
- # Contains regression test for #2804
- it 'builds a list of shipping methods common to all categories' do
- category1 = create(:shipping_category)
- category2 = create(:shipping_category)
- method1 = create(:shipping_method)
- method2 = create(:shipping_method)
- method1.shipping_categories = [category1, category2]
- method2.shipping_categories = [category1]
- variant1 = create(:product, shipping_category: category1).default_variant
- variant2 = create(:product, shipping_category: category2).default_variant
- contents = [ContentItem.new(build(:inventory_unit, variant_id: variant1.id)),
- ContentItem.new(build(:inventory_unit, variant_id: variant1.id)),
- ContentItem.new(build(:inventory_unit, variant_id: variant2.id))]
-
- package = Package.new(stock_location, contents)
- expect(package.shipping_methods).to eq([method1])
- end
+ # Replaces the ShippingCategory intersection (#2804) with the 6.0
+ # fulfillment-type eligibility semantics.
+ describe '#eligible_delivery_methods' do
+ let!(:shipping_dm) { create(:shipping_method) }
+ let!(:digital_dm) { create(:digital_shipping_method) }
+
+ it 'returns methods whose fulfillment type every item supports' do
+ variant1 = create(:product).default_variant
+ variant2 = create(:product).default_variant
+ contents = [ContentItem.new(build(:inventory_unit, variant_id: variant1.id)),
+ ContentItem.new(build(:inventory_unit, variant_id: variant2.id))]
+
+ package = Package.new(stock_location, contents)
+ expect(package.eligible_delivery_methods).to eq([shipping_dm])
+ end
- context 'when no categories' do
- let(:variant) { create(:variant) }
- let(:contents) { [ContentItem.new(build(:inventory_unit, variant: variant))] }
- let(:package) { Package.new(stock_location, contents) }
+ it 'returns nothing when the items share no fulfillment type' do
+ physical = create(:product).default_variant
+ digital = create(:digital_product).default_variant
+ contents = [ContentItem.new(build(:inventory_unit, variant_id: physical.id)),
+ ContentItem.new(build(:inventory_unit, variant_id: digital.id))]
- before { allow(variant).to receive_messages shipping_category: nil }
+ package = Package.new(stock_location, contents)
+ expect(package.eligible_delivery_methods).to be_empty
+ end
- it 'builds an empty list of shipping methods' do
- expect(package.shipping_methods).to be_empty
+ it 'subtracts per-product exclusions' do
+ excluded = create(:shipping_method)
+ variant = create(:product, excluded_delivery_method_ids: [excluded.id]).default_variant
+ contents = [ContentItem.new(build(:inventory_unit, variant_id: variant.id))]
+
+ package = Package.new(stock_location, contents)
+ expect(package.eligible_delivery_methods).to eq([shipping_dm])
end
end
@@ -92,18 +98,18 @@ module Spree
subject.add build_inventory_unit, :backordered
shipping_method = build(:shipping_method)
- subject.shipping_rates = [Spree::ShippingRate.new(shipping_method: shipping_method, cost: 10.00, selected: true)]
+ subject.shipping_rates = [Spree::DeliveryRate.new(delivery_method: shipping_method, cost: 10.00, selected: true)]
shipment = subject.to_shipment
expect(shipment.stock_location).to eq subject.stock_location
- expect(shipment.inventory_units.size).to eq 3
+ expect(shipment.fulfillment_items.size).to eq 3
- first_unit = shipment.inventory_units.first
+ first_unit = shipment.fulfillment_items.first
expect(first_unit.variant).to eq variant
expect(first_unit.state).to eq 'on_hand'
expect(first_unit).to be_pending
- last_unit = shipment.inventory_units.last
+ last_unit = shipment.fulfillment_items.last
expect(last_unit.variant).to eq variant
expect(last_unit.state).to eq 'backordered'
diff --git a/spree/core/spec/models/spree/stock/splitter/digital_spec.rb b/spree/core/spec/models/spree/stock/splitter/digital_spec.rb
deleted file mode 100644
index a6457940bf..0000000000
--- a/spree/core/spec/models/spree/stock/splitter/digital_spec.rb
+++ /dev/null
@@ -1,37 +0,0 @@
-require 'spec_helper'
-
-module Spree
- module Stock
- module Splitter
- describe Digital, type: :model do
- subject { described_class.new(packer) }
-
- let(:packer) { build(:stock_packer) }
-
- let(:digital_shipping_method) { create(:digital_shipping_method) }
- let(:product1) { create(:product, shipping_category: digital_shipping_method.shipping_categories.first) }
- let(:product2) { create(:product) }
-
- let(:item1) { create(:inventory_unit, variant: create(:variant, product: product1, digitals: [create(:digital)])) }
- let(:item2) { create(:inventory_unit, variant: create(:variant, product: product2)) }
- let(:item3) { create(:inventory_unit, variant: create(:variant, product: product2)) }
- let(:item4) { create(:inventory_unit, variant: create(:variant, product: product1, digitals: [create(:digital)])) }
- let(:item5) { create(:inventory_unit, variant: create(:variant, product: product1, digitals: [create(:digital)])) }
-
- it 'splits each package by product digital status' do
- package1 = Package.new(packer.stock_location)
- package1.add item1, :on_hand
- package1.add item2, :on_hand
- package1.add item3, :on_hand
- package1.add item4, :on_hand
- package1.add item5, :on_hand
-
- packages = subject.split([package1])
-
- expect(packages[0].quantity).to eq 3
- expect(packages[1].quantity).to eq 2
- end
- end
- end
- end
-end
diff --git a/spree/core/spec/models/spree/stock/splitter/fulfillment_type_spec.rb b/spree/core/spec/models/spree/stock/splitter/fulfillment_type_spec.rb
new file mode 100644
index 0000000000..b406a6f594
--- /dev/null
+++ b/spree/core/spec/models/spree/stock/splitter/fulfillment_type_spec.rb
@@ -0,0 +1,45 @@
+require 'spec_helper'
+
+module Spree
+ module Stock
+ module Splitter
+ describe FulfillmentType, type: :model do
+ subject { described_class.new(packer) }
+
+ let(:packer) { build(:stock_packer) }
+
+ let(:digital_product) { create(:digital_product) }
+ let(:physical_product) { create(:product) }
+
+ let(:item1) { create(:inventory_unit, variant: create(:variant, product: digital_product, digitals: [create(:digital)])) }
+ let(:item2) { create(:inventory_unit, variant: create(:variant, product: physical_product)) }
+ let(:item3) { create(:inventory_unit, variant: create(:variant, product: physical_product)) }
+ let(:item4) { create(:inventory_unit, variant: create(:variant, product: digital_product, digitals: [create(:digital)])) }
+
+ it 'splits packages so fulfillment-type sets stay homogeneous' do
+ package = Package.new(packer.stock_location)
+ package.add item1, :on_hand
+ package.add item2, :on_hand
+ package.add item3, :on_hand
+ package.add item4, :on_hand
+
+ packages = subject.split([package])
+
+ expect(packages.size).to eq(2)
+ expect(packages.map { |p| p.fulfillment_types.sort }).to match_array([['digital'], ['shipping']])
+ expect(packages.sum { |p| p.contents.size }).to eq(4)
+ end
+
+ it 'keeps a single package when every item shares the same types' do
+ package = Package.new(packer.stock_location)
+ package.add item2, :on_hand
+ package.add item3, :on_hand
+
+ packages = subject.split([package])
+
+ expect(packages.size).to eq(1)
+ end
+ end
+ end
+ end
+end
diff --git a/spree/core/spec/models/spree/stock/splitter/shipping_category_spec.rb b/spree/core/spec/models/spree/stock/splitter/shipping_category_spec.rb
deleted file mode 100644
index 0e33522c3b..0000000000
--- a/spree/core/spec/models/spree/stock/splitter/shipping_category_spec.rb
+++ /dev/null
@@ -1,42 +0,0 @@
-require 'spec_helper'
-
-module Spree
- module Stock
- module Splitter
- describe ShippingCategory, type: :model do
- subject(:result) do
- described_class.new(packer).split(packages)
- end
-
- let(:packer) { build(:stock_packer) }
-
- let(:packages) { [package1, package2] }
- let(:package1) { Spree::Stock::Package.new(packer.stock_location) }
- let(:package2) { Spree::Stock::Package.new(packer.stock_location) }
-
- let(:variant1) { build_stubbed(:variant, product: product1) }
- let(:product1) { build_stubbed(:product, shipping_category: shipping_category_1) }
- let(:variant2) { build_stubbed(:variant, product: product2) }
- let(:product2) { build_stubbed(:product, shipping_category: shipping_category_2) }
-
- let(:shipping_category_1) { build_stubbed(:shipping_category, name: 'A') }
- let(:shipping_category_2) { build_stubbed(:shipping_category, name: 'B') }
-
- before do
- package1.add_multiple(build_stubbed_list(:inventory_unit, 4, :without_assoc, variant: variant1))
- package1.add_multiple(build_stubbed_list(:inventory_unit, 8, :without_assoc, variant: variant2))
-
- package2.add_multiple(build_stubbed_list(:inventory_unit, 6, :without_assoc, variant: variant1))
- package2.add_multiple(build_stubbed_list(:inventory_unit, 9, :without_assoc, variant: variant2), :backordered)
- end
-
- it 'splits each package by shipping category' do
- expect(result[0].quantity).to eq 4
- expect(result[1].quantity).to eq 8
- expect(result[2].quantity).to eq 6
- expect(result[3].quantity).to eq 9
- end
- end
- end
- end
-end
diff --git a/spree/core/spec/models/spree/store_spec.rb b/spree/core/spec/models/spree/store_spec.rb
index da9b3657cd..95374863c9 100644
--- a/spree/core/spec/models/spree/store_spec.rb
+++ b/spree/core/spec/models/spree/store_spec.rb
@@ -225,9 +225,9 @@ describe Spree::Store, type: :model, without_global_store: true do
let(:store) { build(:store) }
before do
- zone = create(:zone, name: 'Test Zone', kind: 'country')
- zone.zone_members.create!(zoneable: country)
- create(:shipping_method, zones: [zone])
+ zone = create(:delivery_zone)
+ zone.members.create!(member_type: 'country', country: country)
+ create(:shipping_method, delivery_zones: [zone])
store.default_country_iso = country.iso
end
@@ -762,12 +762,12 @@ describe Spree::Store, type: :model, without_global_store: true do
context 'with country-type zones with shipping methods' do
let(:country1) { create(:country) }
let(:country2) { create(:country) }
- let!(:zone) { create(:zone, kind: 'country') }
+ let!(:zone) { create(:delivery_zone) }
before do
- zone.zone_members.create!(zoneable: country1)
- zone.zone_members.create!(zoneable: country2)
- create(:shipping_method, zones: [zone])
+ zone.members.create!(member_type: 'country', country: country1)
+ zone.members.create!(member_type: 'country', country: country2)
+ create(:shipping_method, delivery_zones: [zone])
end
it 'returns countries from those zones' do
@@ -779,11 +779,11 @@ describe Spree::Store, type: :model, without_global_store: true do
context 'with state-type zones with shipping methods' do
let(:country) { create(:country) }
let(:state) { create(:state, country: country) }
- let!(:zone) { create(:zone, kind: 'state') }
+ let!(:zone) { create(:delivery_zone) }
before do
- zone.zone_members.create!(zoneable: state)
- create(:shipping_method, zones: [zone])
+ zone.members.create!(member_type: 'state', state: state)
+ create(:shipping_method, delivery_zones: [zone])
end
it 'returns countries inferred from state-type zones' do
@@ -794,10 +794,10 @@ describe Spree::Store, type: :model, without_global_store: true do
context 'when zone has no shipping method' do
let(:country) { create(:country) }
- let!(:zone) { create(:zone, kind: 'country') }
+ let!(:zone) { create(:delivery_zone) }
before do
- zone.zone_members.create!(zoneable: country)
+ zone.members.create!(member_type: 'country', country: country)
end
it 'does not include countries from that zone' do
@@ -815,14 +815,14 @@ describe Spree::Store, type: :model, without_global_store: true do
context 'when country appears in multiple zones' do
let(:country) { create(:country) }
- let!(:zone1) { create(:zone, kind: 'country') }
- let!(:zone2) { create(:zone, kind: 'country') }
+ let!(:zone1) { create(:delivery_zone) }
+ let!(:zone2) { create(:delivery_zone) }
before do
- zone1.zone_members.create!(zoneable: country)
- zone2.zone_members.create!(zoneable: country)
- create(:shipping_method, zones: [zone1])
- create(:shipping_method, zones: [zone2])
+ zone1.members.create!(member_type: 'country', country: country)
+ zone2.members.create!(member_type: 'country', country: country)
+ create(:shipping_method, delivery_zones: [zone1])
+ create(:shipping_method, delivery_zones: [zone2])
end
it 'deduplicates countries' do
diff --git a/spree/core/spec/models/spree/tax_rate_spec.rb b/spree/core/spec/models/spree/tax_rate_spec.rb
index 2542cad326..69a8d102ac 100644
--- a/spree/core/spec/models/spree/tax_rate_spec.rb
+++ b/spree/core/spec/models/spree/tax_rate_spec.rb
@@ -319,6 +319,11 @@ describe Spree::TaxRate, type: :model do
subject(:included_tax_amount) { Spree::TaxRate.included_tax_amount_for(price_options) }
let!(:order) { create :order_with_line_items }
+ let!(:default_tax_zone) do
+ create(:zone, default_tax: true, kind: 'country').tap do |zone|
+ zone.zone_members.create!(zoneable: order.tax_address.country)
+ end
+ end
let!(:included_tax_rate) do
create :tax_rate,
included_in_price: true,
diff --git a/spree/core/spec/services/spree/carts/update_spec.rb b/spree/core/spec/services/spree/carts/update_spec.rb
index cca4da892e..b4c255f3d3 100644
--- a/spree/core/spec/services/spree/carts/update_spec.rb
+++ b/spree/core/spec/services/spree/carts/update_spec.rb
@@ -555,7 +555,7 @@ module Spree
let(:country) { Spree::Country.find_by(iso: 'US') || create(:country, iso: 'US') }
let!(:us_state) { country.states.find_by(abbr: 'NY') || create(:state, country: country, abbr: 'NY', name: 'New York') }
let!(:zone) { create(:zone, zone_members: [Spree::ZoneMember.new(zoneable: country)]) }
- let!(:shipping_method) { create(:shipping_method, zones: [zone]) }
+ let!(:shipping_method) { create(:shipping_method) }
let(:address_params) do
{
first_name: 'Buyer', last_name: 'McGee',
@@ -630,10 +630,11 @@ module Spree
describe 'when the cart cannot be delivered' do
let!(:order) { create(:order_with_line_items, user: user, store: store, state: 'address') }
let(:params) { { email: '[email protected]' } }
- let(:unserved_category) { create(:shipping_category, name: 'Unserved') }
+ # no delivery method serves the pickup fulfillment type in this suite
+ let(:pickup_only_type) { create(:product_type, name: "Pickup #{SecureRandom.hex(4)}", fulfillment_types: ['pickup']) }
before do
- order.line_items.each { |line_item| line_item.variant.product.update!(shipping_category: unserved_category) }
+ order.line_items.each { |line_item| line_item.variant.product.update!(product_type: pickup_only_type) }
order.reload
end
diff --git a/spree/core/spec/services/spree/checkout/advance_spec.rb b/spree/core/spec/services/spree/checkout/advance_spec.rb
index 29b26c25b2..f5747a24c5 100644
--- a/spree/core/spec/services/spree/checkout/advance_spec.rb
+++ b/spree/core/spec/services/spree/checkout/advance_spec.rb
@@ -164,7 +164,7 @@ RSpec.describe Spree::Checkout::Advance do
def ensure_states_updated_only_once
updater_spy = order.updater
allow(order).to receive(:updater).and_return(updater_spy)
- expect(updater_spy).to receive(:update_shipment_state).once.and_call_original
+ expect(updater_spy).to receive(:update_fulfillment_status).once.and_call_original
expect(updater_spy).to receive(:update_payment_state).once.and_call_original
end
end
diff --git a/spree/core/spec/services/spree/checkout/get_shipping_rates_spec.rb b/spree/core/spec/services/spree/checkout/get_shipping_rates_spec.rb
index 2e583c7ee3..7d8bdf2d05 100644
--- a/spree/core/spec/services/spree/checkout/get_shipping_rates_spec.rb
+++ b/spree/core/spec/services/spree/checkout/get_shipping_rates_spec.rb
@@ -17,7 +17,6 @@ module Spree
create(:shipping_method).tap do |shipping_method|
shipping_method.calculator.preferred_amount = 10
shipping_method.calculator.save
- shipping_method.zones = [zone]
end
end
let!(:zone) { create(:zone) }
diff --git a/spree/core/spec/services/spree/checkout/select_shipping_method_spec.rb b/spree/core/spec/services/spree/checkout/select_shipping_method_spec.rb
index 32fc7379a8..cabbdba768 100644
--- a/spree/core/spec/services/spree/checkout/select_shipping_method_spec.rb
+++ b/spree/core/spec/services/spree/checkout/select_shipping_method_spec.rb
@@ -19,21 +19,25 @@ module Spree
let(:zone) { create(:zone_with_country) }
let(:shipping_category) { order.products.first.shipping_category }
let!(:shipping_method) do
- create(:shipping_method, zones: [zone], shipping_categories: [shipping_category]) do |shipping_method|
+ create(:shipping_method, shipping_categories: [shipping_category]) do |shipping_method|
shipping_method.calculator.preferred_amount = 10
shipping_method.calculator.save
end
end
let!(:shipping_method_2) do
- create(:shipping_method, zones: [zone], shipping_categories: [shipping_category]) do |shipping_method|
+ create(:shipping_method, shipping_categories: [shipping_category]) do |shipping_method|
shipping_method.calculator.preferred_amount = 15
shipping_method.calculator.save
end
end
let!(:shipping_method_3) do
- create(:shipping_method, zones: [create(:zone)], shipping_categories: [shipping_category]) do |shipping_method|
+ create(:shipping_method, shipping_categories: [shipping_category]) do |shipping_method|
shipping_method.calculator.preferred_amount = 5
shipping_method.calculator.save
+ # scoped to an unrelated delivery zone so it never serves this order
+ elsewhere = create(:delivery_zone)
+ elsewhere.members.create!(member_type: 'country', country: create(:country))
+ shipping_method.delivery_zones = [elsewhere]
end
end
let(:shipment) { order.shipments.last }
diff --git a/spree/core/spec/services/spree/fulfillments/create_spec.rb b/spree/core/spec/services/spree/fulfillments/create_spec.rb
index 49a4e85c3e..7bef6d3a5b 100644
--- a/spree/core/spec/services/spree/fulfillments/create_spec.rb
+++ b/spree/core/spec/services/spree/fulfillments/create_spec.rb
@@ -193,10 +193,10 @@ module Spree
it 'registers the fulfillment as already shipped' do
expect(execute.success?).to eq(true)
- expect(fulfillment.state).to eq('shipped')
+ expect(fulfillment.status).to eq('fulfilled')
expect(fulfillment.shipped_at).to be_present
- expect(fulfillment.inventory_units.all? { |unit| unit.state == 'shipped' }).to eq(true)
- expect(order.reload.shipment_state).to eq('shipped')
+ expect(fulfillment.fulfillment_items.all? { |unit| unit.status == 'shipped' }).to eq(true)
+ expect(order.reload.fulfillment_status).to eq('fulfilled')
end
it 'freezes the inherited cost and carrier, keeping the order total unchanged' do
@@ -220,10 +220,10 @@ module Spree
it 'bypasses the paid-order readiness gate' do
order.payments.delete_all
- order.update_column(:payment_state, 'balance_due')
+ order.update_column(:payment_status, 'balance_due')
expect(execute.success?).to eq(true)
- expect(fulfillment.state).to eq('shipped')
+ expect(fulfillment.status).to eq('fulfilled')
end
end
@@ -234,8 +234,8 @@ module Spree
it 'fills backorders before shipping' do
expect(execute.success?).to eq(true)
- expect(fulfillment.state).to eq('shipped')
- expect(fulfillment.inventory_units.all? { |unit| unit.state == 'shipped' }).to eq(true)
+ expect(fulfillment.status).to eq('fulfilled')
+ expect(fulfillment.fulfillment_items.all? { |unit| unit.status == 'shipped' }).to eq(true)
end
end
end
diff --git a/spree/core/spec/services/spree/imports/row_processors/product_variant_spec.rb b/spree/core/spec/services/spree/imports/row_processors/product_variant_spec.rb
index de687fb6e7..1466156820 100644
--- a/spree/core/spec/services/spree/imports/row_processors/product_variant_spec.rb
+++ b/spree/core/spec/services/spree/imports/row_processors/product_variant_spec.rb
@@ -831,9 +831,8 @@ RSpec.describe Spree::Imports::RowProcessors::ProductVariant, type: :service do
)
end
- it 'assigns the default shipping category' do
- expect(product.shipping_category).to be_present
- expect(product.shipping_category.name).to eq 'Default'
+ it 'leaves the shipping category unset' do
+ expect(product.shipping_category).to be_nil
end
end
@@ -872,9 +871,8 @@ RSpec.describe Spree::Imports::RowProcessors::ProductVariant, type: :service do
)
end
- it 'assigns the default shipping category' do
- expect(product.shipping_category).to be_present
- expect(product.shipping_category.name).to eq 'Default'
+ it 'leaves the shipping category unset' do
+ expect(product.shipping_category).to be_nil
end
end
end
diff --git a/spree/core/spec/services/spree/orders/create_spec.rb b/spree/core/spec/services/spree/orders/create_spec.rb
index 314a829e91..8effb299cc 100644
--- a/spree/core/spec/services/spree/orders/create_spec.rb
+++ b/spree/core/spec/services/spree/orders/create_spec.rb
@@ -11,7 +11,7 @@ module Spree
let!(:zone) { create(:zone) }
let!(:zone_member) { create(:zone_member, zone: zone, zoneable: country) }
let!(:shipping_method) do
- create(:shipping_method, zones: [zone]).tap do |sm|
+ create(:shipping_method).tap do |sm|
sm.calculator.preferred_amount = 5
sm.calculator.save
end
diff --git a/spree/core/spec/services/spree/orders/update_spec.rb b/spree/core/spec/services/spree/orders/update_spec.rb
index 8142bc9a27..de7368e772 100644
--- a/spree/core/spec/services/spree/orders/update_spec.rb
+++ b/spree/core/spec/services/spree/orders/update_spec.rb
@@ -18,7 +18,7 @@ module Spree
let!(:other_zone) { create(:zone) }
let!(:other_zone_member) { create(:zone_member, zone: other_zone, zoneable: other_country) }
let!(:shipping_method) do
- create(:shipping_method, zones: [zone, other_zone]).tap do |sm|
+ create(:shipping_method).tap do |sm|
sm.calculator.preferred_amount = 5
sm.calculator.save
end
diff --git a/spree/core/spec/services/spree/seeds/digital_delivery_spec.rb b/spree/core/spec/services/spree/seeds/digital_delivery_spec.rb
index d953ad3e61..b80548ca02 100644
--- a/spree/core/spec/services/spree/seeds/digital_delivery_spec.rb
+++ b/spree/core/spec/services/spree/seeds/digital_delivery_spec.rb
@@ -3,32 +3,30 @@ require 'spec_helper'
RSpec.describe Spree::Seeds::DigitalDelivery do
subject { described_class.call }
- describe 'ShippingMethod' do
- it 'creates a Digital Delivery shipping method' do
- expect { subject }.to change(Spree::ShippingMethod, :count).by(1)
+ describe 'DeliveryMethod' do
+ it 'creates a Digital Delivery delivery method' do
+ expect { subject }.to change(Spree::DeliveryMethod, :count).by(1)
- shipping_method = Spree::ShippingMethod.find_by(name: Spree.t('digital.digital_delivery'))
- expect(shipping_method).to be_present
- expect(shipping_method.display_on).to eq('both')
- expect(shipping_method.shipping_categories.first.name).to eq('Digital')
- expect(shipping_method.calculator).to be_a(Spree::Calculator::Shipping::DigitalDelivery)
- expect(shipping_method.zones).to match_array(Spree::Zone.all)
+ delivery_method = Spree::DeliveryMethod.find_by(name: Spree.t('digital.digital_delivery'))
+ expect(delivery_method).to be_present
+ expect(delivery_method.display_on).to eq('both')
+ expect(delivery_method.fulfillment_type).to eq('digital')
+ expect(delivery_method).to be_digital
+ expect(delivery_method.calculator).to be_a(Spree::Calculator::Shipping::DigitalDelivery)
end
- context 'when Digital Delivery shipping method already exists' do
+ context 'when Digital Delivery delivery method already exists' do
before do
- shipping_category = Spree::ShippingCategory.find_or_create_by(name: 'Digital')
- Spree::ShippingMethod.create!(
+ Spree::DeliveryMethod.create!(
name: Spree.t('digital.digital_delivery'),
display_on: 'both',
- shipping_categories: [shipping_category],
- calculator: Spree::Calculator::Shipping::DigitalDelivery.create!,
- zones: Spree::Zone.all
+ fulfillment_type: 'digital',
+ calculator: Spree::Calculator::Shipping::DigitalDelivery.create!
)
end
- it "doesn't create a new shipping method" do
- expect { subject }.not_to change(Spree::ShippingMethod, :count)
+ it "doesn't create a new delivery method" do
+ expect { subject }.not_to change(Spree::DeliveryMethod, :count)
end
end
end
diff --git a/spree/core/spree_core.gemspec b/spree/core/spree_core.gemspec
index 6cb7298003..390e36dd9a 100644
--- a/spree/core/spree_core.gemspec
+++ b/spree/core/spree_core.gemspec
@@ -28,7 +28,7 @@ Gem::Specification.new do |s|
s.add_development_dependency 'i18n-tasks'
- s.add_dependency 'rails', '>= 7.2', '< 8.2'
+ s.add_dependency 'rails', '>= 8.1', '< 8.2'
s.add_dependency 'acts_as_list', '>= 0.8'
diff --git a/spree/emails/spec/models/spree/shipment_spec.rb b/spree/emails/spec/models/spree/shipment_spec.rb
index a6a2fa7f7d..0d6b77cb3a 100644
--- a/spree/emails/spec/models/spree/shipment_spec.rb
+++ b/spree/emails/spec/models/spree/shipment_spec.rb
@@ -3,7 +3,7 @@ require 'spec_helper'
describe Spree::Shipment, type: :model do
let(:order) { create(:order) }
let(:shipping_method) { create(:shipping_method, name: 'UPS') }
- let(:shipment) { create(:shipment, cost: 1, state: 'pending', stock_location: create(:stock_location), order: order) }
+ let(:shipment) { create(:shipment, cost: 1, status: 'pending', stock_location: create(:stock_location), order: order) }
before do
allow(order).to receive_messages backordered?: false,
@@ -12,23 +12,21 @@ describe Spree::Shipment, type: :model do
paid?: false,
touch_later: false
- allow(shipment).to receive_messages shipping_method: shipping_method
+ allow(shipment).to receive_messages(delivery_method: shipping_method, shipping_method: shipping_method)
end
- ['ready', 'canceled'].each do |state|
- context "from #{state}" do
+ ['ready', 'canceled'].each do |status|
+ context "from #{status}" do
before do
allow(order).to receive(:update_with_updater!)
- allow(shipment).to receive_messages(require_inventory: false, update_order: true, state: state)
+ allow(shipment).to receive_messages(require_inventory: false, update_order: true, status: status)
end
- it 'publishes shipment.shipped event when shipping', events: true do
- allow_any_instance_of(Spree::ShipmentHandler).to receive(:update_order_shipment_state)
-
+ it 'publishes shipment.shipped event when fulfilling', events: true do
expect(shipment).to receive(:publish_event).with('shipment.shipped')
allow(shipment).to receive(:publish_event).with(anything)
- shipment.ship!
+ shipment.fulfill!
end
end
end