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.

Split adjustments into typed tables with a tax provider seam (core rewrite Wave 3)

Damian Legawiec55e9516ed3b8
diff --git a/docs/plans/6.0-core-rewrite-tasks.md b/docs/plans/6.0-core-rewrite-tasks.md
index 639b3e0317..299f898f08 100644
--- a/docs/plans/6.0-core-rewrite-tasks.md
+++ b/docs/plans/6.0-core-rewrite-tasks.md
@@ -144,34 +144,45 @@ The big mechanical wave. Whole-suite blast radius via factories; one-release con
Runs after Wave 2 (tables born with `fulfillment_id`). Can proceed in parallel with Wave 4.
### T3.1 Order-level freeze (P0 — precondition, built and tested first)
-- [ ] `OrderUpdater` refuses adjustment recalculation on completed orders. This must exist before the Adjustment state machine goes.
+- [x] `OrderUpdater` refuses adjustment recalculation on completed orders. This must exist before the Adjustment state machine goes.
### T3.2 Typed tables (P1)
-- [ ] `spree_tax_lines`: owner XOR `cart_id`/`order_id`, nullable `tax_rate_id`, adjustable XOR `line_item_id`/`fulfillment_id`/`fee_id`, `amount` + `rate` (null: false), `label` (null: false), `included` (null: false), `provider_id`, `data` json, `metadata`. Plain FK indexes, **no** upsert identity.
-- [ ] `spree_discounts`: owner XOR, nullable `promotion_action_id`/`promotion_id`, adjustable XOR, `amount` null: false + **DB CHECK ≤ 0**, `label`, `kind`, `code` (indexed), `value`, `value_type`, `metadata`.
-- [ ] `spree_fees`: owner XOR, `line_item_id`/`fulfillment_id` both-nullable (both nil ⇒ order-level), `amount` null: false + **CHECK ≥ 0**, `label`, `kind` null: false, `metadata`; index `[order_id, kind]`.
-- [ ] `spree_orders.fee_total`.
+- [x] `spree_tax_lines`: owner XOR `cart_id`/`order_id`, nullable `tax_rate_id`, adjustable XOR `line_item_id`/`fulfillment_id`/`fee_id`, `amount` + `rate` (null: false), `label` (null: false), `included` (null: false), `provider_id`, `data` json, `metadata`. Plain FK indexes, **no** upsert identity.
+- [x] `spree_discounts`: owner XOR, nullable `promotion_action_id`/`promotion_id`, adjustable XOR, `amount` null: false + **DB CHECK ≤ 0**, `label`, `kind`, `code` (indexed), `value`, `value_type`, `metadata`.
+- [x] `spree_fees`: owner XOR, `line_item_id`/`fulfillment_id` both-nullable (both nil ⇒ order-level), `amount` null: false + **CHECK ≥ 0**, `label`, `kind` null: false, `metadata`; index `[order_id, kind]`.
+- [x] `spree_orders.fee_total`.
### T3.3 Models + adjusters
-- [ ] `TaxLine` (`tl_`), `Discount` (`disc_`), `Fee` (`fee_`) per plan code blocks (+ `Spree::Metadata`, XOR validations, scopes); Order/Cart/LineItem/Fulfillment associations incl. the through-associations.
-- [ ] `Spree::Adjusters::Base` + `Adjusters::Promotion`: candidate computation returns **all** candidates; winner-only selection isolated in **one method** (6.1 stacking slots in there); clamping so net never goes below zero; provenance snapshots (`code`/`value`/`value_type`); `dependent: :nullify` from the promotion side.
-- [ ] FreeShipping → fulfillment-attached `Discount`, persisted **even at zero**; `Order#has_free_shipping?` tests row existence.
-- [ ] Order-level discount distribution: largest-remainder, prorated over each line's *remaining discounted* base, weights frozen at placement.
-- [ ] Manual paths: `Discount(kind: 'manual')` (line-targeted or order-distributed) and `Fee` (order-level or attached); ad-hoc credits are manual Discounts, never negative Fees.
-- [ ] Promotion STI namespace rename rides here: `Spree::Promotion::Rules::*`→`Spree::PromotionRules::*`, `Actions::*`→`PromotionActions::*`, `CreateItemAdjustments`→`CreateItemDiscounts` (one-release aliases; `type`-column data task in Wave 7).
+- [x] `TaxLine` (`tl_`), `Discount` (`disc_`), `Fee` (`fee_`) per plan code blocks (+ `Spree::Metadata`, XOR validations, scopes); Order/Cart/LineItem/Fulfillment associations incl. the through-associations.
+- [x] `Spree::Adjusters::Base` + `Adjusters::Promotion`: candidate computation returns **all** candidates; winner-only selection isolated in **one method** (6.1 stacking slots in there); clamping so net never goes below zero; provenance snapshots (`code`/`value`/`value_type`); `dependent: :nullify` from the promotion side.
+- [x] FreeShipping → fulfillment-attached `Discount`, persisted **even at zero**; `Order#has_free_shipping?` tests row existence.
+- [x] Order-level discount distribution: largest-remainder, prorated over each line's *remaining discounted* base, weights frozen at placement.
+- [x] Manual paths: `Discount(kind: 'manual')` (line-targeted or order-distributed) and `Fee` (order-level or attached); ad-hoc credits are manual Discounts, never negative Fees.
+- [x] Promotion STI namespace rename rides here: `Spree::Promotion::Rules::*`→`Spree::PromotionRules::*`, `Actions::*`→`PromotionActions::*`, `CreateItemAdjustments`→`CreateItemDiscounts` (one-release aliases; `type`-column data task in Wave 7).
### T3.4 Minimal TaxProvider (the sanctioned TaxLine writer)
-- [ ] `Spree::TaxProvider::Base` (estimate required; commit/void/refund no-op stubs; `exempt?` default) + `Spree::TaxProvider::Internal` computing directly from TaxRate data (rate × discounted base; VAT included-in-price math) — **no `Calculator::DefaultTax` indirection**; zone matching stays as today (`TaxRate.match` over `Spree::Zone`) until the tax plan decouples it.
-- [ ] Write contract: **replace-all set semantics** per estimate (delete target items' TaxLines, insert fresh — kills stale tax after address changes); internal rows keep `tax_rate_id` + snapshot `rate`/`label`/`provider_id: 'internal'`.
-- [ ] `Spree.tax_provider` seam (global default → Internal; per-Market resolution arrives with the full tax plan).
-- [ ] Removed: `TaxRate.adjust`, `AdjustmentSource`, `Calculator::DefaultTax`, `Adjuster::Tax`. TaxRate becomes pure configuration.
+- [x] `Spree::TaxProvider::Base` (estimate required; commit/void/refund no-op stubs; `exempt?` default) + `Spree::TaxProvider::Internal` computing directly from TaxRate data (rate × discounted base; VAT included-in-price math) — **no `Calculator::DefaultTax` indirection**; zone matching stays as today (`TaxRate.match` over `Spree::Zone`) until the tax plan decouples it.
+- [x] Write contract: **replace-all set semantics** per estimate (delete target items' TaxLines, insert fresh — kills stale tax after address changes); internal rows keep `tax_rate_id` + snapshot `rate`/`label`/`provider_id: 'internal'`.
+- [x] `Spree.tax_provider` seam (global default → Internal; per-Market resolution arrives with the full tax plan).
+- [x] Removed: `TaxRate.adjust`, `AdjustmentSource`, `Calculator::DefaultTax`, `Adjuster::Tax`. TaxRate becomes pure configuration.
### T3.5 Typed recalculation + consumer rewrite
-- [ ] `OrderUpdater`: two-pass preserved — discount/fee adjusters persist the discounted taxable base (+ `pre_tax_amount`), then `Spree.tax_provider.estimate`; totals via grouped SUMs from typed tables; all denormalized columns kept (incl. `taxable_adjustment_total`/`non_taxable_adjustment_total`) + new `fee_total`; freeze guard from T3.1.
-- [ ] Consumers rewritten off `source_type`/`eligible`: the ~12 Order readers (`order_level_promo_total`, `shipping_discount`, `valid_promotion_ids`, `cart_promo_total`, `has_free_shipping?`, `fully_discounted?`, `taxable_amount`, …), `Promotion#credits_count` (distinct orders with the promotion's discounts), coupon handlers, `CouponCodesHandler`, `OrderPromotion#amount`, cross-adjustable negative-total guard, `OrderMerger`, `Cart::Empty`, refund calculators (`DefaultRefundAmount` reads the line's own discounts).
-- [ ] Removed: `Spree::Adjustment` model, `Adjustable::AdjustmentsUpdater`, `Adjustable::Adjuster::*`, `PromotionAccumulator` (dead). `spree_adjustments` table **kept read-only** through 6.0 (audit + rollback reference).
-- [ ] CanCanCan: grants on TaxLine/Discount/Fee replace Adjustment grants.
-- [ ] Factories + the ~65 affected spec files.
+- [x] `OrderUpdater`: two-pass preserved — discount/fee adjusters persist the discounted taxable base (+ `pre_tax_amount`), then `Spree.tax_provider.estimate`; totals via grouped SUMs from typed tables; all denormalized columns kept (incl. `taxable_adjustment_total`/`non_taxable_adjustment_total`) + new `fee_total`; freeze guard from T3.1.
+- [x] Consumers rewritten off `source_type`/`eligible`: the ~12 Order readers (`order_level_promo_total`, `shipping_discount`, `valid_promotion_ids`, `cart_promo_total`, `has_free_shipping?`, `fully_discounted?`, `taxable_amount`, …), `Promotion#credits_count` (distinct orders with the promotion's discounts), coupon handlers, `CouponCodesHandler`, `OrderPromotion#amount`, cross-adjustable negative-total guard, `OrderMerger`, `Cart::Empty`, refund calculators (`DefaultRefundAmount` reads the line's own discounts).
+- [x] Removed: `Spree::Adjustment` model, `Adjustable::AdjustmentsUpdater`, `Adjustable::Adjuster::*`, `PromotionAccumulator` (dead). `spree_adjustments` table **kept read-only** through 6.0 (audit + rollback reference).
+- [x] CanCanCan: grants on TaxLine/Discount/Fee replace Adjustment grants.
+- [x] Factories + the ~65 affected spec files.
+
+### Wave 3 outcome notes (2026-07-29)
+
+- **Adjuster is order-scoped, not adjustable-scoped.** `Spree::Adjusters::Base#initialize(order)`; `Adjusters::Promotion` recomputes candidates from connected promotions (plus `extra_promotions:` during activation), competes per group (line / fulfillment / order-wide), and cleans everything it didn't write this pass. Winner-only policy lives solely in `#select_applicable` (the 6.1 stacking seam). Actions share `PromotionAction#apply_via_adjuster`: perform = "does this action yield a candidate?" — losing promotions still connect to the order so they keep competing on later recalculations (reinstatement without stored losers).
+- **Cross-order negative-total guard dropped from `CreateItemDiscounts#compute_amount`** — it double-counted the very rows being recomputed; per-line clamping over the remaining discounted base owns the floor now (order net = Σ line nets ≥ 0 since every discount is line-attached).
+- **Behavior change (spec'd):** an order-level discount distributes nothing when line bases are exhausted (`Order#cart_promo_total` spec updated -110 → -100 with rationale). Legacy let order-level rows ride on top of fully-discounted lines with shipping absorbing the difference.
+- **`Order#discounts` now means typed rows.** The 5.4 `alias discounts order_promotions` is gone; the three API serializers keep the wire shape via `many :order_promotions, key: :discounts`.
+- **Recalculation reentrancy rules:** `LineItem` after_save no longer runs the updater (services own it — running it mid-mutation cached `order.line_items` and hid later items); `Fulfillment#update_adjustments` skips creation (`previously_new_record?` — recursing mid-`fulfillments=` dropped records) and completed orders; `OrderUpdater#update` resets `line_items`/`fulfillments` association caches at entry.
+- **Internal provider details:** fees without a tax category tax against the default TaxCategory; `store_pre_tax_amount` moved into the provider; `TaxRate#adjustment_label` is the public label snapshot; `TaxRate.tax_lines` is `dependent: :nullify` (rows outlive rates; next estimate drops them). `Cart` gained dormant `tax_address`/`tax_zone`. `DeliveryRate#tax_amount` computes inline from rate config (no calculator).
+- **api engine (ahead of Wave 6):** read-only `/admin/orders/:id/adjustments` endpoints + serializer removed; `?expand=adjustments` dropped from admin order/line_item/fulfillment serializers. Typed replacements (tax_lines/discounts/fees CRUD) ship in Wave 6 as planned.
+- **Suite convergence:** core 299 → 112 → 0 (7499 examples), emails 102/0. Twin-cache lesson reconfirmed in factories (`order.shipments.reload` → real names).
---
diff --git a/spree/api/app/controllers/spree/api/v3/admin/orders/adjustments_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/orders/adjustments_controller.rb
deleted file mode 100644
index 741d646178..0000000000
--- a/spree/api/app/controllers/spree/api/v3/admin/orders/adjustments_controller.rb
+++ /dev/null
@@ -1,25 +0,0 @@
-module Spree
- module Api
- module V3
- module Admin
- module Orders
- class AdjustmentsController < BaseController
- protected
-
- def model_class
- Spree::Adjustment
- end
-
- def serializer_class
- Spree.api.admin_adjustment_serializer
- end
-
- def parent_association
- :adjustments
- end
- end
- end
- end
- end
- end
-end
diff --git a/spree/api/app/serializers/spree/api/v3/admin/adjustment_serializer.rb b/spree/api/app/serializers/spree/api/v3/admin/adjustment_serializer.rb
deleted file mode 100644
index 707022b86c..0000000000
--- a/spree/api/app/serializers/spree/api/v3/admin/adjustment_serializer.rb
+++ /dev/null
@@ -1,24 +0,0 @@
-module Spree
- module Api
- module V3
- module Admin
- class AdjustmentSerializer < V3::BaseSerializer
- typelize label: :string, amount: :string, display_amount: :string,
- included: :boolean,
- order_id: [:string, nullable: true]
-
- attributes :label, :display_amount, :included,
- created_at: :iso8601, updated_at: :iso8601
-
- attribute :amount do |adjustment|
- adjustment.amount.to_s
- end
-
- attribute :order_id do |adjustment|
- adjustment.order&.prefixed_id
- end
- end
- end
- end
- end
-end
diff --git a/spree/api/app/serializers/spree/api/v3/admin/fulfillment_serializer.rb b/spree/api/app/serializers/spree/api/v3/admin/fulfillment_serializer.rb
index 89ce047b78..45f8881b46 100644
--- a/spree/api/app/serializers/spree/api/v3/admin/fulfillment_serializer.rb
+++ b/spree/api/app/serializers/spree/api/v3/admin/fulfillment_serializer.rb
@@ -38,9 +38,6 @@ module Spree
resource: proc { Spree.api.admin_order_serializer },
if: proc { expand?('order') }
- many :adjustments,
- resource: proc { Spree.api.admin_adjustment_serializer },
- if: proc { expand?('adjustments') }
end
end
end
diff --git a/spree/api/app/serializers/spree/api/v3/admin/line_item_serializer.rb b/spree/api/app/serializers/spree/api/v3/admin/line_item_serializer.rb
index 07a7e8db3b..870a0b41f0 100644
--- a/spree/api/app/serializers/spree/api/v3/admin/line_item_serializer.rb
+++ b/spree/api/app/serializers/spree/api/v3/admin/line_item_serializer.rb
@@ -43,9 +43,6 @@ module Spree
resource: proc { Spree.api.admin_tax_category_serializer },
if: proc { expand?('tax_category') }
- many :adjustments,
- resource: proc { Spree.api.admin_adjustment_serializer },
- if: proc { expand?('adjustments') }
end
end
end
diff --git a/spree/api/app/serializers/spree/api/v3/admin/order_serializer.rb b/spree/api/app/serializers/spree/api/v3/admin/order_serializer.rb
index fd4baeef73..7e78f709c7 100644
--- a/spree/api/app/serializers/spree/api/v3/admin/order_serializer.rb
+++ b/spree/api/app/serializers/spree/api/v3/admin/order_serializer.rb
@@ -69,7 +69,7 @@ module Spree
end
# Override inherited associations to use admin serializers
- many :discounts, resource: proc { Spree.api.admin_discount_serializer }, if: proc { expand?('discounts') }
+ many :order_promotions, key: :discounts, resource: proc { Spree.api.admin_discount_serializer }, if: proc { expand?('discounts') }
many :line_items, key: :items, resource: proc { Spree.api.admin_line_item_serializer }, if: proc { expand?('items') }
many :fulfillments, resource: proc { Spree.api.admin_fulfillment_serializer }, if: proc { expand?('fulfillments') }
many :payments, resource: proc { Spree.api.admin_payment_serializer }, if: proc { expand?('payments') }
@@ -102,9 +102,6 @@ module Spree
resource: proc { Spree.api.admin_customer_serializer },
if: proc { expand?('created_by') }
- many :adjustments,
- resource: proc { Spree.api.admin_adjustment_serializer },
- if: proc { expand?('adjustments') }
many :return_authorizations,
resource: proc { Spree.api.admin_return_authorization_serializer },
diff --git a/spree/api/app/serializers/spree/api/v3/cart_serializer.rb b/spree/api/app/serializers/spree/api/v3/cart_serializer.rb
index 52648f9b39..e173457d7c 100644
--- a/spree/api/app/serializers/spree/api/v3/cart_serializer.rb
+++ b/spree/api/app/serializers/spree/api/v3/cart_serializer.rb
@@ -83,7 +83,7 @@ module Spree
order.shipping_eq_billing_address?
end
- many :discounts, resource: proc { Spree.api.discount_serializer }
+ many :order_promotions, key: :discounts, resource: proc { Spree.api.discount_serializer }
many :line_items, key: :items, resource: proc { Spree.api.line_item_serializer }
many :fulfillments, resource: proc { Spree.api.fulfillment_serializer }
many :payments, resource: proc { Spree.api.payment_serializer }
diff --git a/spree/api/app/serializers/spree/api/v3/order_serializer.rb b/spree/api/app/serializers/spree/api/v3/order_serializer.rb
index 2fd10ab79f..69b93ff75b 100644
--- a/spree/api/app/serializers/spree/api/v3/order_serializer.rb
+++ b/spree/api/app/serializers/spree/api/v3/order_serializer.rb
@@ -61,7 +61,7 @@ module Spree
order.covered_by_store_credit?
end
- many :discounts, resource: proc { Spree.api.discount_serializer }
+ many :order_promotions, key: :discounts, resource: proc { Spree.api.discount_serializer }
many :line_items, key: :items, resource: proc { Spree.api.line_item_serializer }
many :fulfillments, resource: proc { Spree.api.fulfillment_serializer }
many :payments, resource: proc { Spree.api.payment_serializer }
diff --git a/spree/api/config/routes.rb b/spree/api/config/routes.rb
index f73c77d445..cacbfe58d7 100644
--- a/spree/api/config/routes.rb
+++ b/spree/api/config/routes.rb
@@ -404,7 +404,6 @@ Spree::Core::Engine.add_routes do
end
end
resources :refunds, controller: 'orders/refunds', only: [:index, :create]
- resources :adjustments, controller: 'orders/adjustments', only: [:index, :show]
resources :gift_cards, controller: 'orders/gift_cards', only: [:create, :destroy]
resource :store_credits, controller: 'orders/store_credits', only: [:create, :destroy]
end
diff --git a/spree/api/lib/spree/api/dependencies.rb b/spree/api/lib/spree/api/dependencies.rb
index 42fe3fc65b..9bb3a52918 100644
--- a/spree/api/lib/spree/api/dependencies.rb
+++ b/spree/api/lib/spree/api/dependencies.rb
@@ -110,7 +110,6 @@ module Spree
admin_gift_card_batch_serializer: 'Spree::Api::V3::Admin::GiftCardBatchSerializer',
admin_payment_serializer: 'Spree::Api::V3::Admin::PaymentSerializer',
admin_refund_serializer: 'Spree::Api::V3::Admin::RefundSerializer',
- admin_adjustment_serializer: 'Spree::Api::V3::Admin::AdjustmentSerializer',
admin_shipping_category_serializer: 'Spree::Api::V3::Admin::ShippingCategorySerializer',
admin_tax_category_serializer: 'Spree::Api::V3::Admin::TaxCategorySerializer',
admin_return_authorization_serializer: 'Spree::Api::V3::Admin::ReturnAuthorizationSerializer',
diff --git a/spree/api/spec/controllers/spree/api/v3/admin/orders/adjustments_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/orders/adjustments_controller_spec.rb
deleted file mode 100644
index b57f6d6b8d..0000000000
--- a/spree/api/spec/controllers/spree/api/v3/admin/orders/adjustments_controller_spec.rb
+++ /dev/null
@@ -1,34 +0,0 @@
-require 'spec_helper'
-
-RSpec.describe Spree::Api::V3::Admin::Orders::AdjustmentsController, type: :controller do
- render_views
-
- include_context 'API v3 Admin authenticated'
-
- let!(:order) { create(:order, store: store, state: 'cart') }
-
- before { request.headers.merge!(headers) }
-
- describe 'GET #index' do
- let!(:adjustment) { create(:adjustment, adjustable: order, order: order, amount: 5.00, label: 'Admin discount') }
-
- it 'returns adjustments for the order' do
- get :index, params: { order_id: order.prefixed_id }, as: :json
-
- expect(response).to have_http_status(:ok)
- expect(json_response['data']).to be_an(Array)
- expect(json_response['data'].length).to eq(1)
- end
- end
-
- describe 'GET #show' do
- let!(:adjustment) { create(:adjustment, adjustable: order, order: order, amount: 5.00, label: 'Admin discount') }
-
- it 'returns the adjustment' do
- get :show, params: { order_id: order.prefixed_id, id: adjustment.prefixed_id }, as: :json
-
- expect(response).to have_http_status(:ok)
- expect(json_response['id']).to eq(adjustment.prefixed_id)
- end
- end
-end
diff --git a/spree/api/spec/controllers/spree/api/v3/admin/promotion_actions_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/promotion_actions_controller_spec.rb
index e8d6c997c1..0b3d797903 100644
--- a/spree/api/spec/controllers/spree/api/v3/admin/promotion_actions_controller_spec.rb
+++ b/spree/api/spec/controllers/spree/api/v3/admin/promotion_actions_controller_spec.rb
@@ -18,7 +18,7 @@ RSpec.describe Spree::Api::V3::Admin::PromotionActionsController, type: :control
expect(response).to have_http_status(:created)
expect(promotion.reload.promotion_actions.map(&:type))
- .to include('Spree::Promotion::Actions::CreateAdjustment')
+ .to include('Spree::PromotionActions::CreateAdjustment')
end
it "404s for a promotion that belongs to another store" do
diff --git a/spree/api/spec/controllers/spree/api/v3/admin/promotion_rules_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/promotion_rules_controller_spec.rb
index 698621bb2a..e6cbb4a259 100644
--- a/spree/api/spec/controllers/spree/api/v3/admin/promotion_rules_controller_spec.rb
+++ b/spree/api/spec/controllers/spree/api/v3/admin/promotion_rules_controller_spec.rb
@@ -17,7 +17,7 @@ RSpec.describe Spree::Api::V3::Admin::PromotionRulesController, type: :controlle
}, as: :json
expect(response).to have_http_status(:created)
- expect(promotion.reload.promotion_rules.map(&:type)).to include('Spree::Promotion::Rules::FirstOrder')
+ expect(promotion.reload.promotion_rules.map(&:type)).to include('Spree::PromotionRules::FirstOrder')
end
it 'creates a channel rule, storing the selected channel IDs in preferences' do
@@ -30,7 +30,7 @@ RSpec.describe Spree::Api::V3::Admin::PromotionRulesController, type: :controlle
}, as: :json
expect(response).to have_http_status(:created)
- rule = promotion.reload.promotion_rules.find { |r| r.is_a?(Spree::Promotion::Rules::Channel) }
+ rule = promotion.reload.promotion_rules.find { |r| r.is_a?(Spree::PromotionRules::Channel) }
expect(rule).to be_present
expect(rule.preferred_channel_ids.map(&:to_s)).to eq([channel.id.to_s])
end
@@ -45,7 +45,7 @@ RSpec.describe Spree::Api::V3::Admin::PromotionRulesController, type: :controlle
}, as: :json
expect(response).to have_http_status(:created)
- rule = promotion.reload.promotion_rules.find { |r| r.is_a?(Spree::Promotion::Rules::Market) }
+ rule = promotion.reload.promotion_rules.find { |r| r.is_a?(Spree::PromotionRules::Market) }
expect(rule).to be_present
expect(rule.preferred_market_ids.map(&:to_s)).to eq([market.id.to_s])
end
diff --git a/spree/api/spec/controllers/spree/api/v3/admin/promotions_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/promotions_controller_spec.rb
index 9c0adc97b7..352999ef41 100644
--- a/spree/api/spec/controllers/spree/api/v3/admin/promotions_controller_spec.rb
+++ b/spree/api/spec/controllers/spree/api/v3/admin/promotions_controller_spec.rb
@@ -75,7 +75,7 @@ RSpec.describe Spree::Api::V3::Admin::PromotionsController, type: :controller do
promotion = Spree::Promotion.find_by_prefix_id(json_response['id'])
expect(promotion.rules.size).to eq(1)
rule = promotion.rules.first
- expect(rule).to be_a(Spree::Promotion::Rules::Currency)
+ expect(rule).to be_a(Spree::PromotionRules::Currency)
expect(rule.preferred_currency).to eq('EUR')
end
@@ -91,7 +91,7 @@ RSpec.describe Spree::Api::V3::Admin::PromotionsController, type: :controller do
expect(response).to have_http_status(:created)
rule = Spree::Promotion.find_by_prefix_id(json_response['id']).rules.first
- expect(rule).to be_a(Spree::Promotion::Rules::ItemTotal)
+ expect(rule).to be_a(Spree::PromotionRules::ItemTotal)
expect(rule.preferred_amount_min).to eq(50.0)
expect(rule.preferred_operator_min).to eq('gte')
expect(rule.preferred_amount_max).to eq(500.0)
@@ -115,7 +115,7 @@ RSpec.describe Spree::Api::V3::Admin::PromotionsController, type: :controller do
expect(response).to have_http_status(:created)
promotion = Spree::Promotion.find_by_prefix_id(json_response['id'])
rule = promotion.rules.first
- expect(rule).to be_a(Spree::Promotion::Rules::Product)
+ expect(rule).to be_a(Spree::PromotionRules::Product)
expect(rule.product_ids).to contain_exactly(product_a.id, product_b.id)
expect(rule.preferred_match_policy).to eq('any')
end
@@ -135,7 +135,7 @@ RSpec.describe Spree::Api::V3::Admin::PromotionsController, type: :controller do
expect(response).to have_http_status(:created)
rule = Spree::Promotion.find_by_prefix_id(json_response['id']).rules.first
- expect(rule).to be_a(Spree::Promotion::Rules::Category)
+ expect(rule).to be_a(Spree::PromotionRules::Category)
expect(rule.taxon_ids).to eq([taxon.id])
end
@@ -152,7 +152,7 @@ RSpec.describe Spree::Api::V3::Admin::PromotionsController, type: :controller do
expect(response).to have_http_status(:created)
promotion = Spree::Promotion.find_by_prefix_id(json_response['id'])
types = promotion.rules.map(&:class)
- expect(types).to contain_exactly(Spree::Promotion::Rules::Currency, Spree::Promotion::Rules::FirstOrder)
+ expect(types).to contain_exactly(Spree::PromotionRules::Currency, Spree::PromotionRules::FirstOrder)
end
it 'silently ignores rules with an unknown type' do
@@ -168,7 +168,7 @@ RSpec.describe Spree::Api::V3::Admin::PromotionsController, type: :controller do
expect(response).to have_http_status(:created)
promotion = Spree::Promotion.find_by_prefix_id(json_response['id'])
expect(promotion.rules.size).to eq(1)
- expect(promotion.rules.first).to be_a(Spree::Promotion::Rules::Currency)
+ expect(promotion.rules.first).to be_a(Spree::PromotionRules::Currency)
end
end
@@ -177,7 +177,7 @@ RSpec.describe Spree::Api::V3::Admin::PromotionsController, type: :controller do
post :create,
params: base_params.merge(
actions: [{
- type: 'create_item_adjustments',
+ type: 'create_item_discounts',
calculator: {
type: 'flat_rate',
preferences: { amount: '25.0', currency: 'USD' }
@@ -188,7 +188,7 @@ RSpec.describe Spree::Api::V3::Admin::PromotionsController, type: :controller do
expect(response).to have_http_status(:created)
action = Spree::Promotion.find_by_prefix_id(json_response['id']).actions.first
- expect(action).to be_a(Spree::Promotion::Actions::CreateItemAdjustments)
+ expect(action).to be_a(Spree::PromotionActions::CreateItemDiscounts)
expect(action.calculator).to be_a(Spree::Calculator::FlatRate)
expect(action.calculator.preferred_amount).to eq(25.0)
expect(action.calculator.preferred_currency).to eq('USD')
@@ -203,7 +203,7 @@ RSpec.describe Spree::Api::V3::Admin::PromotionsController, type: :controller do
expect(response).to have_http_status(:created)
action = Spree::Promotion.find_by_prefix_id(json_response['id']).actions.first
- expect(action).to be_a(Spree::Promotion::Actions::FreeShipping)
+ expect(action).to be_a(Spree::PromotionActions::FreeShipping)
end
it 'creates a CreateAdjustment action with FlatPercentItemTotal calculator' do
@@ -232,7 +232,7 @@ RSpec.describe Spree::Api::V3::Admin::PromotionsController, type: :controller do
params: base_params.merge(
rules: [{ type: 'currency', preferences: { currency: 'USD' } }],
actions: [{
- type: 'create_item_adjustments',
+ type: 'create_item_discounts',
calculator: { type: 'flat_rate', preferences: { amount: '5.0' } }
}]
),
@@ -255,7 +255,7 @@ RSpec.describe Spree::Api::V3::Admin::PromotionsController, type: :controller do
expect(response).to have_http_status(:created)
promotion = Spree::Promotion.find_by_prefix_id(json_response['id'])
- expect(promotion.rules.first).to be_a(Spree::Promotion::Rules::Currency)
+ expect(promotion.rules.first).to be_a(Spree::PromotionRules::Currency)
expect(promotion.rules.first.preferred_currency).to eq('EUR')
end
@@ -271,7 +271,7 @@ RSpec.describe Spree::Api::V3::Admin::PromotionsController, type: :controller do
expect(response).to have_http_status(:created)
rule = Spree::Promotion.find_by_prefix_id(json_response['id']).rules.first
- expect(rule).to be_a(Spree::Promotion::Rules::Category)
+ expect(rule).to be_a(Spree::PromotionRules::Category)
expect(rule.taxon_ids).to eq([taxon.id])
end
@@ -279,7 +279,7 @@ RSpec.describe Spree::Api::V3::Admin::PromotionsController, type: :controller do
post :create,
params: base_params.merge(
actions: [{
- type: 'create_item_adjustments',
+ type: 'create_item_discounts',
calculator: { type: 'flat_rate', preferences: { amount: '12.5' } }
}]
),
@@ -287,7 +287,7 @@ RSpec.describe Spree::Api::V3::Admin::PromotionsController, type: :controller do
expect(response).to have_http_status(:created)
action = Spree::Promotion.find_by_prefix_id(json_response['id']).actions.first
- expect(action).to be_a(Spree::Promotion::Actions::CreateItemAdjustments)
+ expect(action).to be_a(Spree::PromotionActions::CreateItemDiscounts)
expect(action.calculator).to be_a(Spree::Calculator::FlatRate)
expect(action.calculator.preferred_amount).to eq(12.5)
end
@@ -346,8 +346,8 @@ RSpec.describe Spree::Api::V3::Admin::PromotionsController, type: :controller do
end
it 'updates an existing rule by prefixed id' do
- rule = create(:promotion_rule, promotion: promotion, type: 'Spree::Promotion::Rules::Currency')
- rule.becomes(Spree::Promotion::Rules::Currency).update!(preferred_currency: 'USD')
+ rule = create(:promotion_rule, promotion: promotion, type: 'Spree::PromotionRules::Currency')
+ rule.becomes(Spree::PromotionRules::Currency).update!(preferred_currency: 'USD')
patch :update,
params: {
@@ -361,12 +361,12 @@ RSpec.describe Spree::Api::V3::Admin::PromotionsController, type: :controller do
as: :json
expect(response).to have_http_status(:ok)
- expect(rule.becomes(Spree::Promotion::Rules::Currency).reload.preferred_currency).to eq('CAD')
+ expect(rule.becomes(Spree::PromotionRules::Currency).reload.preferred_currency).to eq('CAD')
expect(promotion.reload.rules.size).to eq(1)
end
it 'replaces product_ids on an existing Product rule' do
- rule = Spree::Promotion::Rules::Product.create!(promotion: promotion)
+ rule = Spree::PromotionRules::Product.create!(promotion: promotion)
product_a = create(:product)
product_b = create(:product)
rule.products = [product_a]
@@ -388,7 +388,7 @@ RSpec.describe Spree::Api::V3::Admin::PromotionsController, type: :controller do
end
it 'destroys rules omitted from the payload' do
- rule = Spree::Promotion::Rules::Currency.create!(promotion: promotion, preferred_currency: 'USD')
+ rule = Spree::PromotionRules::Currency.create!(promotion: promotion, preferred_currency: 'USD')
patch :update, params: { id: promotion.prefixed_id, rules: [] }, as: :json
@@ -398,8 +398,8 @@ RSpec.describe Spree::Api::V3::Admin::PromotionsController, type: :controller do
end
it 'destroys removed rules while keeping the ones explicitly passed' do
- keep = Spree::Promotion::Rules::Currency.create!(promotion: promotion, preferred_currency: 'USD')
- drop = Spree::Promotion::Rules::FirstOrder.create!(promotion: promotion)
+ keep = Spree::PromotionRules::Currency.create!(promotion: promotion, preferred_currency: 'USD')
+ drop = Spree::PromotionRules::FirstOrder.create!(promotion: promotion)
patch :update,
params: {
@@ -469,7 +469,7 @@ RSpec.describe Spree::Api::V3::Admin::PromotionsController, type: :controller do
expect(response).to have_http_status(:ok)
types = promotion.reload.actions.map(&:class)
- expect(types).to include(Spree::Promotion::Actions::FreeShipping)
+ expect(types).to include(Spree::PromotionActions::FreeShipping)
end
end
end
diff --git a/spree/api/spec/integration/spree/api/v3/admin/promotion_actions_spec.rb b/spree/api/spec/integration/spree/api/v3/admin/promotion_actions_spec.rb
index c13b2f0b6f..780f8b36f3 100644
--- a/spree/api/spec/integration/spree/api/v3/admin/promotion_actions_spec.rb
+++ b/spree/api/spec/integration/spree/api/v3/admin/promotion_actions_spec.rb
@@ -27,7 +27,7 @@ RSpec.describe 'Admin Promotion Actions API', type: :request, swagger_doc: 'api-
let(:'x-spree-api-key') { secret_api_key.plaintext_token }
before do
- Spree::Promotion::Actions::FreeShipping.create!(promotion: promotion)
+ Spree::PromotionActions::FreeShipping.create!(promotion: promotion)
end
run_test! do |response|
@@ -44,7 +44,7 @@ RSpec.describe 'Admin Promotion Actions API', type: :request, swagger_doc: 'api-
produces 'application/json'
consumes 'application/json'
security [api_key: [], bearer_auth: []]
- description 'Adds a new action to a promotion. The `type` is the wire shorthand from `GET /promotion_actions/types` (e.g. `free_shipping`, `create_item_adjustments`). Fully-qualified Ruby class names are also accepted for backward compatibility.'
+ description 'Adds a new action to a promotion. The `type` is the wire shorthand from `GET /promotion_actions/types` (e.g. `free_shipping`, `create_item_discounts`). Fully-qualified Ruby class names are also accepted for backward compatibility.'
admin_scope :write, :promotions
admin_sdk_example 'promotion-actions/create'
@@ -86,7 +86,7 @@ RSpec.describe 'Admin Promotion Actions API', type: :request, swagger_doc: 'api-
parameter name: :promotion_id, in: :path, type: :string, required: true
parameter name: :id, in: :path, type: :string, required: true
- let(:action) { Spree::Promotion::Actions::FreeShipping.create!(promotion: promotion) }
+ let(:action) { Spree::PromotionActions::FreeShipping.create!(promotion: promotion) }
let(:id) { action.prefixed_id }
delete 'Delete an action from a promotion' do
diff --git a/spree/api/spec/integration/spree/api/v3/admin/promotion_rules_spec.rb b/spree/api/spec/integration/spree/api/v3/admin/promotion_rules_spec.rb
index 84cc78022d..66b4af6a14 100644
--- a/spree/api/spec/integration/spree/api/v3/admin/promotion_rules_spec.rb
+++ b/spree/api/spec/integration/spree/api/v3/admin/promotion_rules_spec.rb
@@ -27,7 +27,7 @@ RSpec.describe 'Admin Promotion Rules API', type: :request, swagger_doc: 'api-re
let(:'x-spree-api-key') { secret_api_key.plaintext_token }
before do
- Spree::Promotion::Rules::Currency.create!(promotion: promotion, preferred_currency: 'USD')
+ Spree::PromotionRules::Currency.create!(promotion: promotion, preferred_currency: 'USD')
end
run_test! do |response|
@@ -86,7 +86,7 @@ RSpec.describe 'Admin Promotion Rules API', type: :request, swagger_doc: 'api-re
parameter name: :promotion_id, in: :path, type: :string, required: true
parameter name: :id, in: :path, type: :string, required: true
- let(:rule) { Spree::Promotion::Rules::Currency.create!(promotion: promotion, preferred_currency: 'USD') }
+ let(:rule) { Spree::PromotionRules::Currency.create!(promotion: promotion, preferred_currency: 'USD') }
let(:id) { rule.prefixed_id }
patch 'Update a rule\'s preferences' do
diff --git a/spree/api/spec/integration/spree/api/v3/admin/promotions_spec.rb b/spree/api/spec/integration/spree/api/v3/admin/promotions_spec.rb
index 14c21f5244..ee097bfe01 100644
--- a/spree/api/spec/integration/spree/api/v3/admin/promotions_spec.rb
+++ b/spree/api/spec/integration/spree/api/v3/admin/promotions_spec.rb
@@ -137,7 +137,7 @@ RSpec.describe 'Admin Promotions API', type: :request, swagger_doc: 'api-referen
],
actions: [
{
- type: 'create_item_adjustments',
+ type: 'create_item_discounts',
calculator: {
type: 'percent_on_line_item',
preferences: { percent: 25 }
@@ -153,19 +153,19 @@ RSpec.describe 'Admin Promotions API', type: :request, swagger_doc: 'api-referen
promotion = Spree::Promotion.find_by_prefix_id(data['id'])
expect(promotion.rules.map(&:class)).to contain_exactly(
- Spree::Promotion::Rules::Currency,
- Spree::Promotion::Rules::ItemTotal,
- Spree::Promotion::Rules::Product
+ Spree::PromotionRules::Currency,
+ Spree::PromotionRules::ItemTotal,
+ Spree::PromotionRules::Product
)
expect(promotion.actions.map(&:class)).to contain_exactly(
- Spree::Promotion::Actions::CreateItemAdjustments,
- Spree::Promotion::Actions::FreeShipping
+ Spree::PromotionActions::CreateItemDiscounts,
+ Spree::PromotionActions::FreeShipping
)
- product_rule = promotion.rules.find { |r| r.is_a?(Spree::Promotion::Rules::Product) }
+ product_rule = promotion.rules.find { |r| r.is_a?(Spree::PromotionRules::Product) }
expect(product_rule.product_ids).to contain_exactly(product_a.id, product_b.id)
- adjustment_action = promotion.actions.find { |a| a.is_a?(Spree::Promotion::Actions::CreateItemAdjustments) }
+ adjustment_action = promotion.actions.find { |a| a.is_a?(Spree::PromotionActions::CreateItemDiscounts) }
expect(adjustment_action.calculator).to be_a(Spree::Calculator::PercentOnLineItem)
expect(adjustment_action.calculator.preferred_percent).to eq(25)
end
@@ -284,13 +284,13 @@ RSpec.describe 'Admin Promotions API', type: :request, swagger_doc: 'api-referen
response '200', 'rules and actions reconciled to desired set' do
let(:'x-spree-api-key') { secret_api_key.plaintext_token }
let!(:existing_rule) do
- Spree::Promotion::Rules::Currency.create!(promotion: promotion, preferred_currency: 'USD')
+ Spree::PromotionRules::Currency.create!(promotion: promotion, preferred_currency: 'USD')
end
let!(:existing_action) do
calc = Spree::Calculator::FlatRate.new(preferred_amount: 10)
- Spree::Promotion::Actions::CreateItemAdjustments.create!(promotion: promotion, calculator: calc)
+ Spree::PromotionActions::CreateItemDiscounts.create!(promotion: promotion, calculator: calc)
end
- let!(:dropped_rule) { Spree::Promotion::Rules::FirstOrder.create!(promotion: promotion) }
+ let!(:dropped_rule) { Spree::PromotionRules::FirstOrder.create!(promotion: promotion) }
let(:body) do
{
@@ -313,7 +313,7 @@ RSpec.describe 'Admin Promotions API', type: :request, swagger_doc: 'api-referen
# Swap calculator type on existing action
{
id: existing_action.prefixed_id,
- type: 'create_item_adjustments',
+ type: 'create_item_discounts',
calculator: {
type: 'percent_on_line_item',
preferences: { percent: 15 }
@@ -329,8 +329,8 @@ RSpec.describe 'Admin Promotions API', type: :request, swagger_doc: 'api-referen
# Existing currency rule was updated, FirstOrder dropped, ItemTotal added
expect(promotion.rules.map(&:class)).to contain_exactly(
- Spree::Promotion::Rules::Currency,
- Spree::Promotion::Rules::ItemTotal
+ Spree::PromotionRules::Currency,
+ Spree::PromotionRules::ItemTotal
)
expect(existing_rule.reload.preferred_currency).to eq('EUR')
expect(Spree::PromotionRule.where(id: dropped_rule.id)).to be_empty
@@ -345,7 +345,7 @@ RSpec.describe 'Admin Promotions API', type: :request, swagger_doc: 'api-referen
response '200', 'rules and actions cleared with empty arrays' do
let(:'x-spree-api-key') { secret_api_key.plaintext_token }
let!(:rule_to_drop) do
- Spree::Promotion::Rules::Currency.create!(promotion: promotion, preferred_currency: 'USD')
+ Spree::PromotionRules::Currency.create!(promotion: promotion, preferred_currency: 'USD')
end
let(:body) { { rules: [], actions: [] } }
diff --git a/spree/api/spec/serializers/spree/api/v3/admin/promotion_action_serializer_spec.rb b/spree/api/spec/serializers/spree/api/v3/admin/promotion_action_serializer_spec.rb
index 46ad58ce82..b6731ad660 100644
--- a/spree/api/spec/serializers/spree/api/v3/admin/promotion_action_serializer_spec.rb
+++ b/spree/api/spec/serializers/spree/api/v3/admin/promotion_action_serializer_spec.rb
@@ -13,7 +13,7 @@ RSpec.describe Spree::Api::V3::Admin::PromotionActionSerializer do
# of the example so the masking behaviour can be asserted without
# needing a full new STI subclass + registry registration.
let(:action) do
- action = Spree::Promotion::Actions::FreeShipping.create!(promotion: promotion)
+ action = Spree::PromotionActions::FreeShipping.create!(promotion: promotion)
action.preferences[:api_secret] = 'sk_action_super_secret_value'
action.preferences[:webhook_url] = 'https://example.com/hook'
@@ -42,7 +42,7 @@ RSpec.describe Spree::Api::V3::Admin::PromotionActionSerializer do
describe 'nested calculator preferences masking' do
let(:action) do
- Spree::Promotion::Actions::CreateAdjustment.create!(
+ Spree::PromotionActions::CreateAdjustment.create!(
promotion: promotion,
calculator: Spree::Calculator::FlatRate.new(preferred_amount: 5)
)
diff --git a/spree/api/spec/serializers/spree/api/v3/admin/promotion_rule_serializer_spec.rb b/spree/api/spec/serializers/spree/api/v3/admin/promotion_rule_serializer_spec.rb
index 500a8f64e4..8be6742fb0 100644
--- a/spree/api/spec/serializers/spree/api/v3/admin/promotion_rule_serializer_spec.rb
+++ b/spree/api/spec/serializers/spree/api/v3/admin/promotion_rule_serializer_spec.rb
@@ -13,7 +13,7 @@ RSpec.describe Spree::Api::V3::Admin::PromotionRuleSerializer do
# into its schema for the duration of the example so the masking
# path can be asserted without a full new STI subclass.
let(:rule) do
- rule = Spree::Promotion::Rules::Currency.create!(promotion: promotion, preferred_currency: 'USD')
+ rule = Spree::PromotionRules::Currency.create!(promotion: promotion, preferred_currency: 'USD')
rule.preferences[:api_secret] = 'sk_rule_super_secret_value'
stubbed_schema = [
diff --git a/spree/core/app/models/concerns/spree/adjustment_source.rb b/spree/core/app/models/concerns/spree/adjustment_source.rb
deleted file mode 100644
index 1bde610b10..0000000000
--- a/spree/core/app/models/concerns/spree/adjustment_source.rb
+++ /dev/null
@@ -1,58 +0,0 @@
-module Spree
- module AdjustmentSource
- extend ActiveSupport::Concern
-
- included do
- has_many :adjustments, as: :source
- before_destroy :deals_with_adjustments_for_deleted_source
- end
-
- protected
-
- def create_adjustment(order, adjustable, included = false)
- amount = compute_amount(adjustable)
-
- return if amount.zero?
-
- adjustable.adjustments.new(
- amount: amount,
- included: included,
- label: label,
- order: order,
- source: self
- ).save
- end
-
- def create_unique_adjustment(order, adjustable)
- return if already_adjusted?(adjustable)
-
- create_adjustment(order, adjustable)
- end
-
- def create_unique_adjustments(order, adjustables)
- adjustables.where.not(id: already_adjusted_ids(order)).map do |adjustable|
- create_adjustment(order, adjustable) if !block_given? || yield(adjustable)
- end.any?
- end
-
- private
-
- def already_adjusted_ids(order)
- adjustments.where(order: order).pluck(:adjustable_id)
- end
-
- def already_adjusted?(adjustable)
- adjustments.where(adjustable: adjustable).exists?
- end
-
- def deals_with_adjustments_for_deleted_source
- # For incomplete orders, remove the adjustment completely.
- adjustments.for_incomplete_order.destroy_all
-
- # For complete orders, the source will be invalid.
- # Therefore we nullify the source_id, leaving the adjustment in place.
- # This would mean that the order's total is not altered at all.
- adjustments.for_complete_order.update_all(source_id: nil, updated_at: Time.current)
- end
- end
-end
diff --git a/spree/core/app/models/concerns/spree/typed_adjustment_line.rb b/spree/core/app/models/concerns/spree/typed_adjustment_line.rb
new file mode 100644
index 0000000000..7938a093fb
--- /dev/null
+++ b/spree/core/app/models/concerns/spree/typed_adjustment_line.rb
@@ -0,0 +1,44 @@
+module Spree
+ # Shared shape of the typed adjustment rows (TaxLine, Discount, Fee):
+ # dual-FK cart/order owner (exactly one), consolidated +metadata+ JSON
+ # column, money display and localized amount parsing.
+ module TypedAdjustmentLine
+ extend ActiveSupport::Concern
+
+ included do
+ attribute :metadata, default: -> { {} }
+
+ belongs_to :order, class_name: 'Spree::Order', optional: true
+ belongs_to :cart, class_name: 'Spree::Cart', optional: true
+
+ validates :amount, numericality: true
+ validates :label, presence: true
+ validate :exactly_one_owner
+
+ extend Spree::DisplayMoney
+ money_methods :amount
+ end
+
+ # The exactly-one owner of this row — the cart during checkout, the order
+ # after completion. New code must read +owner+, never assume +order+.
+ #
+ # @return [Spree::Cart, Spree::Order, nil]
+ def owner
+ order || cart
+ end
+
+ def amount=(amount)
+ self[:amount] = Spree::LocalizedNumber.parse(amount)
+ end
+
+ def currency
+ owner&.currency
+ end
+
+ private
+
+ def exactly_one_owner
+ errors.add(:base, Spree.t('errors.messages.exactly_one_of_cart_or_order')) unless [order, cart].compact.one?
+ end
+ end
+end
diff --git a/spree/core/app/models/spree/adjustable/adjuster/base.rb b/spree/core/app/models/spree/adjustable/adjuster/base.rb
deleted file mode 100644
index 81fdcb3079..0000000000
--- a/spree/core/app/models/spree/adjustable/adjuster/base.rb
+++ /dev/null
@@ -1,25 +0,0 @@
-module Spree
- module Adjustable
- module Adjuster
- class Base
- def self.adjust(adjustable, totals)
- new(adjustable, totals).update
- end
-
- def initialize(adjustable, totals)
- @adjustable = adjustable
- @totals = totals
- end
-
- def update
- raise NotImplementedError, "Please implement 'update' in your adjuster: #{self.class.name}"
- end
-
- private
-
- attr_reader :adjustable
- delegate :adjustments, to: :adjustable
- end
- end
- end
-end
diff --git a/spree/core/app/models/spree/adjustable/adjuster/promotion.rb b/spree/core/app/models/spree/adjustable/adjuster/promotion.rb
deleted file mode 100644
index 3edc82a2f5..0000000000
--- a/spree/core/app/models/spree/adjustable/adjuster/promotion.rb
+++ /dev/null
@@ -1,41 +0,0 @@
-module Spree
- module Adjustable
- module Adjuster
- class Promotion < Spree::Adjustable::Adjuster::Base
- def update
- promo_adjustments = adjustments.competing_promos.reload.map { |a| a.update!(adjustable) }
- promos_total = promo_adjustments.compact.sum
- choose_best_promo_adjustment unless promos_total == 0
- promo_total = best_promo_adjustment.try(:amount).to_f if best_promo_adjustment.try(:promotion?)
-
- update_totals(promo_total)
- end
-
- private
-
- # Picks one (and only one) competing discount to be eligible for
- # this order. This adjustment provides the most discount, and if
- # two adjustments have the same amount, then it will pick the
- # latest one.
- def choose_best_promo_adjustment
- if best_promo_adjustment
- other_promotions = adjustments.competing_promos.where.not(id: best_promo_adjustment.id)
- other_promotions.update_all(eligible: false)
- end
- end
-
- def best_promo_adjustment
- @best_promo_adjustment ||= begin
- adjustments.competing_promos.eligible.reorder('amount ASC, created_at DESC, id DESC').first
- end
- end
-
- def update_totals(promo_total)
- promo_total ||= 0.0
- @totals[:promo_total] = promo_total
- @totals[:taxable_adjustment_total] += promo_total
- end
- end
- end
- end
-end
diff --git a/spree/core/app/models/spree/adjustable/adjuster/tax.rb b/spree/core/app/models/spree/adjustable/adjuster/tax.rb
deleted file mode 100644
index 31711b8d8c..0000000000
--- a/spree/core/app/models/spree/adjustable/adjuster/tax.rb
+++ /dev/null
@@ -1,26 +0,0 @@
-module Spree
- module Adjustable
- module Adjuster
- class Tax < Spree::Adjustable::Adjuster::Base
- def update
- tax = adjustments.tax
- included_tax_total = tax.find_all(&:included?).map(&:update!).compact.sum || 0
- additional_tax_total = tax.find_all(&:additional?).map(&:update!).compact.sum || 0
-
- update_totals(included_tax_total, additional_tax_total)
- end
-
- private
-
- def adjustments
- adjustable.try(:all_adjustments) || adjustable.adjustments
- end
-
- def update_totals(included_tax_total, additional_tax_total)
- @totals[:included_tax_total] = included_tax_total
- @totals[:additional_tax_total] = additional_tax_total
- end
- end
- end
- end
-end
diff --git a/spree/core/app/models/spree/adjustable/adjustments_updater.rb b/spree/core/app/models/spree/adjustable/adjustments_updater.rb
deleted file mode 100644
index 7ea84ab4f7..0000000000
--- a/spree/core/app/models/spree/adjustable/adjustments_updater.rb
+++ /dev/null
@@ -1,74 +0,0 @@
-module Spree
- module Adjustable
- class AdjustmentsUpdater
- def self.update(adjustable)
- new(adjustable).update
- end
-
- def initialize(adjustable)
- @adjustable = adjustable
- adjustable.reload if shipment? && adjustable && adjustable.persisted?
- end
-
- def update
- return unless adjustable_still_exists?
-
- totals = {
- non_taxable_adjustment_total: 0,
- taxable_adjustment_total: 0
- }
- non_tax_adjusters.each do |klass|
- klass.adjust(@adjustable, totals)
- end
-
- if tax_adjuster.present?
- # Other adjustments can change the taxable amount so we need to update it first
- update_adjustable_attributes(totals)
- tax_adjuster.adjust(@adjustable, totals)
- end
-
- persist_totals totals
- end
-
- private
-
- def persist_totals(totals)
- attributes = totals
- attributes[:adjustment_total] = totals[:non_taxable_adjustment_total] +
- totals[:taxable_adjustment_total] +
- totals.fetch(:additional_tax_total, 0)
-
- update_adjustable_attributes(attributes)
- end
-
- def update_adjustable_attributes(attributes)
- # Only update if attributes have changed
- current_attributes = @adjustable.attributes.slice(*attributes.keys.map(&:to_s))
- return if attributes.all? { |key, value| current_attributes[key.to_s] == value }
-
- attributes[:updated_at] = Time.current
- @adjustable.update_columns(attributes)
- end
-
- def shipment?
- @adjustable.is_a?(Shipment)
- end
-
- def adjusters
- Spree.adjusters
- end
-
- def tax_adjuster
- @tax_adjuster ||= adjusters.find { |adjuster| adjuster.name == 'Spree::Adjustable::Adjuster::Tax' }
- end
-
- def non_tax_adjusters
- adjusters - [tax_adjuster].compact
- end
-
- def adjustable_still_exists?
- @adjustable&.class&.exists?(@adjustable.id)
- end
- end
- end
-end
diff --git a/spree/core/app/models/spree/adjustable/promotion_accumulator.rb b/spree/core/app/models/spree/adjustable/promotion_accumulator.rb
deleted file mode 100644
index 7dfe49f3e6..0000000000
--- a/spree/core/app/models/spree/adjustable/promotion_accumulator.rb
+++ /dev/null
@@ -1,78 +0,0 @@
-module Spree
- module Adjustable
- class PromotionAccumulator
- attr_reader :adjustments, :sources, :promotions
-
- # Adds accumulator as an attribute of adjustable to
- # avoid changing number of passed arguments to
- # adjustment#update! and concequential methods
- def self.add_to(adjustable)
- class << adjustable
- attr_accessor :promotion_accumulator
- end
-
- adjustable.promotion_accumulator = new(adjustable)
- end
-
- def initialize(adjustable)
- @adjustable = adjustable
- @adjustments = []
- @sources = []
- @promotions = []
- all_adjustments.each { |a| add_adjustment(a) }
- end
-
- def add_adjustment(adjustment, opts = {})
- return unless adjustment.promotion?
-
- source = opts[:source] || adjustment.source
- promotion = opts[:promotion] || source.promotion
-
- add(adjustments, adjustment, adjustment.id)
- add(sources, source, adjustment.source_id)
- add(promotions, promotion, source.promotion_id)
- end
-
- def promotions_adjustments(promotion_id, adjustments = self.adjustments)
- where(sources, promotion_id: promotion_id).map do |source|
- where(adjustments, source_id: source.id)
- end.flatten
- end
-
- def promo_total(*args)
- promotions_adjustments(*args).map(&:amount).reduce(0, &:+)
- end
-
- def total_with_promotion(promotion_id)
- amount + ship_total + promo_total(promotion_id)
- end
-
- def item_total_with_promotion(promotion_id)
- amount + promo_total(promotion_id, item_adjustments)
- end
-
- private
-
- attr_reader :adjustable
- delegate :order, to: :adjustable
- delegate :amount, :ship_total, to: :order
-
- def all_adjustments
- order.all_adjustments.promotion.includes(source: [:promotion]).where.
- not('adjustable_id = ? AND adjustable_type = ?', adjustable.id, adjustable.class.to_s)
- end
-
- def add(array, object, id)
- array << object if array.none? { |a| a.id == id }
- end
-
- def item_adjustments
- adjustments.reject { |a| a.adjustable_type.in?(%w[Spree::Shipment Spree::Fulfillment]) }
- end
-
- def where(array, opts = {})
- array.select { |a| opts.all? { |k, v| a.respond_to?(k) && a.send(k) == v } }
- end
- end
- end
-end
diff --git a/spree/core/app/models/spree/adjusters/base.rb b/spree/core/app/models/spree/adjusters/base.rb
new file mode 100644
index 0000000000..ee36107467
--- /dev/null
+++ b/spree/core/app/models/spree/adjusters/base.rb
@@ -0,0 +1,26 @@
+module Spree
+ module Adjusters
+ # Base class for adjusters registered in +Spree.adjusters+. An adjuster is
+ # invoked once per order recalculation and owns a family of typed rows
+ # (Discount or Fee) — it writes, refreshes and removes them so the rows
+ # always reflect the order's current state. Tax is not an adjuster; it is
+ # written by +Spree.tax_provider+ after all adjusters ran.
+ class Base
+ def self.adjust(order)
+ new(order).update
+ end
+
+ def initialize(order)
+ @order = order
+ end
+
+ def update
+ raise NotImplementedError, "Please implement 'update' in your adjuster: #{self.class.name}"
+ end
+
+ private
+
+ attr_reader :order
+ end
+ end
+end
diff --git a/spree/core/app/models/spree/adjusters/promotion.rb b/spree/core/app/models/spree/adjusters/promotion.rb
new file mode 100644
index 0000000000..3d0b9bb8fd
--- /dev/null
+++ b/spree/core/app/models/spree/adjusters/promotion.rb
@@ -0,0 +1,234 @@
+module Spree
+ module Adjusters
+ # Recomputes all promotion Discount rows for an order from the promotions
+ # connected to it (plus any promotions being activated right now, passed as
+ # +extra_promotions+). Candidates are computed for every eligible promotion
+ # on every recalculation; only applied discounts are persisted — losing
+ # candidates are simply not written, so "reinstatement" needs no stored
+ # rows. Selection policy is isolated in {#select_applicable} (winner-only
+ # in 6.0; 6.1 stacking replaces just that method).
+ #
+ # Competition groups mirror the legacy semantics: line-level actions
+ # compete per line item, fulfillment actions compete per fulfillment, and
+ # order-level actions compete order-wide — the order-wide winner is
+ # distributed proportionally across line items (largest-remainder over
+ # each line's remaining discounted base), so no order-attached rows exist.
+ class Promotion < Base
+ def initialize(order, extra_promotions: [])
+ super(order)
+ @extra_promotions = extra_promotions
+ @applied_row_ids = []
+ end
+
+ def update
+ apply_line_item_discounts
+ apply_fulfillment_discounts
+ apply_order_level_discount
+ cleanup_stale_rows
+ end
+
+ # @param action [Spree::PromotionAction]
+ # @return [Boolean] whether the action currently yields any candidate
+ def candidate_for?(action)
+ case action.discount_scope
+ when :line_item
+ order.line_items.any? { |line_item| line_item_candidates(line_item).any? { |c| c[:action].id == action.id } }
+ when :fulfillment
+ order.fulfillments.any? && eligible_promotions.include?(action.promotion)
+ when :order
+ order_level_candidates.any? { |c| c[:action].id == action.id }
+ else
+ false
+ end
+ end
+
+ private
+
+ attr_reader :extra_promotions
+
+ # THE selection seam: 6.0 is winner-takes-all per competition group.
+ # 6.1 stacking replaces this method with a combines_with partition —
+ # persistence, clamping and proration below already support multiple
+ # applied rows per adjustable.
+ def select_applicable(candidates)
+ return [] if candidates.empty?
+
+ # Most negative amount wins; ties go to the newest action.
+ [candidates.min_by { |candidate| [candidate[:amount], -candidate[:action].id] }]
+ end
+
+ def eligible_promotions
+ @eligible_promotions ||= begin
+ promotions = (order.promotions.includes(:promotion_actions).to_a + extra_promotions).uniq(&:id)
+ promotions.select { |promotion| promotion.eligible?(order) }
+ end
+ end
+
+ def discount_actions(scope)
+ eligible_promotions.flat_map(&:promotion_actions).select { |action| action.discount_scope == scope }
+ end
+
+ def apply_line_item_discounts
+ order.line_items.each do |line_item|
+ applicable = select_applicable(line_item_candidates(line_item))
+ applicable.each do |candidate|
+ amount = clamp(candidate[:amount], discountable_base(line_item))
+ next if amount.zero?
+
+ persist_discount(line_item, candidate, amount)
+ end
+ end
+ end
+
+ def line_item_candidates(line_item)
+ @line_item_candidates ||= {}
+ @line_item_candidates[line_item.id] ||= discount_actions(:line_item).filter_map do |action|
+ next unless action.promotion.line_item_actionable?(order, line_item)
+
+ amount = action.compute_amount(line_item)
+ next if amount.zero?
+
+ candidate(action, amount)
+ end
+ end
+
+ def apply_fulfillment_discounts
+ actions = discount_actions(:fulfillment)
+ return if actions.empty?
+
+ order.fulfillments.each do |fulfillment|
+ candidates = actions.map { |action| candidate(action, action.compute_amount(fulfillment)) }
+ select_applicable(candidates).each do |chosen|
+ amount = clamp(chosen[:amount], fulfillment.cost)
+ # Free shipping rows persist even at zero amount — row existence
+ # is the "this order has free shipping" signal.
+ next if amount.zero? && !chosen[:action].persist_at_zero?
+
+ persist_discount(fulfillment, chosen, amount)
+ end
+ end
+ end
+
+ def order_level_candidates
+ @order_level_candidates ||= discount_actions(:order).filter_map do |action|
+ amount = action.compute_amount(order)
+ next if amount.zero?
+
+ candidate(action, amount)
+ end
+ end
+
+ def apply_order_level_discount
+ select_applicable(order_level_candidates).each do |chosen|
+ distribute_over_line_items(chosen)
+ end
+ end
+
+ # Largest-remainder distribution (in cents) of the order-wide winner over
+ # each line's remaining discounted base, so shares always sum exactly to
+ # the promotion amount and no line goes below zero.
+ def distribute_over_line_items(chosen)
+ line_items = order.line_items.to_a
+ bases = line_items.map { |line_item| [discountable_base(line_item), BigDecimal(0)].max }
+ bases_sum = bases.sum
+ return if bases_sum <= 0
+
+ total_cents = [chosen[:amount].abs, bases_sum].min * 100
+ shares = largest_remainder_shares(total_cents.round, bases)
+
+ line_items.each_with_index do |line_item, index|
+ amount = -BigDecimal(shares[index]) / 100
+ next if amount.zero?
+
+ persist_discount(line_item, chosen, amount)
+ end
+ end
+
+ def largest_remainder_shares(total_cents, weights)
+ weights_sum = weights.sum
+ raw = weights.map { |weight| Rational(total_cents) * Rational(weight) / Rational(weights_sum) }
+ shares = raw.map(&:floor)
+ remainder = total_cents - shares.sum
+ raw.each_with_index.sort_by { |value, index| [shares[index] - value, index] }.first(remainder).each do |_, index|
+ shares[index] += 1
+ end
+ shares
+ end
+
+ # Combined discounts never push an adjustable's net below zero.
+ def clamp(amount, base)
+ [amount, -[base, BigDecimal(0)].max].max
+ end
+
+ # The adjustable's remaining discounted amount: its own base minus
+ # discounts already applied — manual/custom rows plus promotion rows
+ # written earlier in this pass. Stale promotion rows from previous
+ # passes are excluded (they're about to be cleaned up) so recalculation
+ # never compounds against its own output.
+ def discountable_base(adjustable)
+ base = adjustable.is_a?(Spree::LineItem) ? adjustable.amount : adjustable.cost
+ applied = adjustable.discounts.reload.select do |row|
+ !row.promotion? || @applied_row_ids.include?(row.id)
+ end
+ base + applied.sum(&:amount)
+ end
+
+ def candidate(action, amount)
+ value, value_type = value_snapshot(action)
+ {
+ action: action,
+ promotion: action.promotion,
+ amount: amount,
+ label: action.send(:label),
+ code: action.promotion.code_for_order(order),
+ value: value,
+ value_type: value_type
+ }
+ end
+
+ def value_snapshot(action)
+ calculator = action.try(:calculator)
+ return [nil, nil] unless calculator
+
+ if calculator.respond_to?(:preferred_percent)
+ [calculator.preferred_percent, 'percent']
+ elsif calculator.respond_to?(:preferred_flat_percent)
+ [calculator.preferred_flat_percent, 'percent']
+ elsif calculator.respond_to?(:preferred_amount)
+ [calculator.preferred_amount, 'flat']
+ else
+ [nil, nil]
+ end
+ end
+
+ def persist_discount(adjustable, candidate, amount)
+ row = adjustable.discounts.find_or_initialize_by(kind: 'promotion', promotion_action_id: candidate[:action].id)
+ row.assign_attributes(
+ owner_attributes(adjustable).merge(
+ amount: amount,
+ label: candidate[:label],
+ code: candidate[:code],
+ value: candidate[:value],
+ value_type: candidate[:value_type],
+ promotion: candidate[:promotion]
+ )
+ )
+ row.save!
+ @applied_row_ids << row.id
+ row
+ end
+
+ def owner_attributes(adjustable)
+ owner = adjustable.owner
+ owner.is_a?(Spree::Order) ? { order: owner, cart: nil } : { cart: owner, order: nil }
+ end
+
+ # Everything not written in this pass is stale: losing candidates,
+ # promotions that stopped being eligible, and rows whose promotion was
+ # deleted (FKs nullified). Manual and custom-kind discounts are not ours.
+ def cleanup_stale_rows
+ order.discounts.promotion.where.not(id: @applied_row_ids).destroy_all
+ end
+ end
+ end
+end
diff --git a/spree/core/app/models/spree/adjustment.rb b/spree/core/app/models/spree/adjustment.rb
deleted file mode 100644
index f8c1757bba..0000000000
--- a/spree/core/app/models/spree/adjustment.rb
+++ /dev/null
@@ -1,130 +0,0 @@
-# Adjustments represent a change to the +item_total+ of an Order. Each adjustment
-# has an +amount+ that can be either positive or negative.
-#
-# Adjustments can be "opened" or "closed".
-# Once an adjustment is closed, it will not be automatically updated.
-#
-# Boolean attributes:
-#
-# +mandatory+
-#
-# If this flag is set to true then it means the the charge is required and will not
-# be removed from the order, even if the amount is zero. In other words a record
-# will be created even if the amount is zero. This is useful for representing things
-# such as shipping and tax charges where you may want to make it explicitly clear
-# that no charge was made for such things.
-#
-# +eligible?+
-#
-# This boolean attributes stores whether this adjustment is currently eligible
-# for its order. Only eligible adjustments count towards the order's adjustment
-# total. This allows an adjustment to be preserved if it becomes ineligible so
-# it might be reinstated.
-module Spree
- class Adjustment < Spree.base_class
- has_prefix_id :adj # Spree-specific: adjustment
-
- with_options polymorphic: true do
- belongs_to :adjustable, touch: true
- belongs_to :source
- end
- belongs_to :order, class_name: 'Spree::Order', inverse_of: :all_adjustments
- belongs_to :promotion_action, class_name: 'Spree::PromotionAction', foreign_key: :source_id, optional: true # created only for has_free_shipping?
-
- validates :adjustable, :order, :label, presence: true
- validates :amount, numericality: true
-
- state_machine :state, initial: :open do
- event :close do
- transition from: :open, to: :closed
- end
-
- event :open do
- transition from: :closed, to: :open
- end
- end
-
- # FIXME: we should check if we also need to fire this action after update
- after_create :update_adjustable_adjustment_total
- after_destroy :update_adjustable_adjustment_total
-
- class_attribute :competing_promos_source_types
-
- self.competing_promos_source_types = ['Spree::PromotionAction']
-
- scope :not_finalized, -> { where(state: 'open') }
- scope :finalized, -> { where(state: 'closed') }
- scope :tax, -> { where(source_type: 'Spree::TaxRate') }
- scope :non_tax, -> do
- source_type = arel_table[:source_type]
- 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: %w[Spree::Shipment Spree::Fulfillment]) }
- scope :optional, -> { where(mandatory: false) }
- scope :eligible, -> { where(eligible: true) }
- scope :charge, -> { where("#{quoted_table_name}.amount >= 0") }
- scope :credit, -> { where("#{quoted_table_name}.amount < 0") }
- scope :nonzero, -> { where("#{quoted_table_name}.amount != 0") }
- scope :non_zero, -> { where.not(amount: [nil, 0]) }
- scope :promotion, -> { where(source_type: 'Spree::PromotionAction') }
- scope :return_authorization, -> { where(source_type: 'Spree::ReturnAuthorization') }
- scope :is_included, -> { where(included: true) }
- scope :additional, -> { where(included: false) }
- scope :competing_promos, -> { where(source_type: competing_promos_source_types) }
- scope :for_complete_order, -> { joins(:order).merge(Spree::Order.complete) }
- scope :for_incomplete_order, -> { joins(:order).merge(Spree::Order.incomplete) }
-
- extend DisplayMoney
- money_methods :amount
-
- def amount=(amount)
- self[:amount] = Spree::LocalizedNumber.parse(amount)
- end
-
- def currency
- adjustable ? adjustable.currency : order.currency
- end
-
- def promotion?
- source_type == 'Spree::PromotionAction'
- end
-
- def tax?
- source_type == 'Spree::TaxRate'
- end
-
- def additional?
- !included?
- end
-
- # Passing a target here would always be recommended as it would avoid
- # hitting the database again and would ensure you're compute values over
- # the specific object amount passed here.
- def update!(target = adjustable)
- src = source
- return amount if closed? || src.blank?
-
- new_amount = src.compute_amount(target)
- new_eligible = promotion? ? src.promotion.eligible?(target) : eligible
-
- changed_attributes = {}
- changed_attributes[:amount] = new_amount if new_amount != amount
- changed_attributes[:eligible] = new_eligible if new_eligible != eligible
-
- if changed_attributes.any?
- changed_attributes[:updated_at] = Time.current
- update_columns(changed_attributes)
- end
-
- new_amount
- end
-
- private
-
- def update_adjustable_adjustment_total
- # Cause adjustable's total to be recalculated
- Adjustable::AdjustmentsUpdater.update(adjustable)
- end
- end
-end
diff --git a/spree/core/app/models/spree/calculator/default_tax.rb b/spree/core/app/models/spree/calculator/default_tax.rb
deleted file mode 100644
index a52fcf955b..0000000000
--- a/spree/core/app/models/spree/calculator/default_tax.rb
+++ /dev/null
@@ -1,87 +0,0 @@
-require_dependency 'spree/calculator'
-
-module Spree
- class Calculator::DefaultTax < Calculator
- include Spree::VatPriceCalculation
- def self.description
- Spree.t(:default_tax)
- end
-
- # Default tax calculator still needs to support orders for legacy reasons
- # Orders created before Spree 2.1 had tax adjustments applied to the order, as a whole.
- # Orders created with Spree 2.2 and after, have them applied to the line items individually.
- def compute_order(order)
- matched_line_items = order.line_items.select do |line_item|
- line_item.tax_category == rate.tax_category
- end
-
- line_items_total = matched_line_items.sum(&:total)
- if rate.included_in_price
- round_to_two_places(line_items_total - (line_items_total / (1 + rate.amount)))
- else
- round_to_two_places(line_items_total * rate.amount)
- end
- end
-
- # When it comes to computing shipments or line items: same same.
- #
- # Both tax modes are computed from the item's live taxable basis, which
- # follows every discount: item-level promotions and the item's share of
- # whole-order promotions (see LineItem#taxable_basis). Included
- # (VAT-style) tax intentionally does not read the stored pre_tax_amount
- # column — that column is only refreshed by Spree::TaxRate.adjust on
- # checkout transitions, so it goes stale the moment a promotion is
- # applied or removed.
- def compute_shipment_or_line_item(item)
- basis = item.taxable_basis
-
- if rate.included_in_price
- deduced_total_by_rate(net_basis(item, basis), rate)
- else
- round_to_two_places(basis * rate.amount)
- end
- end
-
- alias compute_shipment compute_shipment_or_line_item
- alias compute_line_item compute_shipment_or_line_item
-
- def compute_shipping_rate(shipping_rate)
- if rate.included_in_price
- pre_tax_amount = shipping_rate.cost / (1 + rate.amount)
- deduced_total_by_rate(pre_tax_amount, rate)
- else
- with_tax_amount = shipping_rate.cost * rate.amount
- round_to_two_places(with_tax_amount)
- end
- end
-
- private
-
- def rate
- calculable
- end
-
- def deduced_total_by_rate(pre_tax_amount, rate)
- round_to_two_places(pre_tax_amount * rate.amount)
- end
-
- # Backs all included-in-price rates out of the gross basis, mirroring
- # Spree::TaxRate.store_pre_tax_amount (several rates can share a tax
- # category, e.g. MOSS VAT). Falls back to this rate's amount when no
- # rate matches the item, e.g. in bare setups without matching zones.
- def net_basis(item, basis)
- included = included_rates_amount(item)
- included = rate.amount if included.zero?
-
- basis / (1 + included)
- end
-
- # Memoized per tax category: tax rate and zone rows are configuration,
- # invariant within a recalculation pass.
- def included_rates_amount(item)
- @included_rates_amount ||= {}
- @included_rates_amount[item.tax_category_id] ||=
- Spree::TaxRate.included_tax_amount_for(tax_zone: rate.zone, tax_category: item.tax_category)
- end
- end
-end
diff --git a/spree/core/app/models/spree/calculator/returns/default_refund_amount.rb b/spree/core/app/models/spree/calculator/returns/default_refund_amount.rb
index 1d5496ab9e..09a05a5a2a 100644
--- a/spree/core/app/models/spree/calculator/returns/default_refund_amount.rb
+++ b/spree/core/app/models/spree/calculator/returns/default_refund_amount.rb
@@ -3,37 +3,31 @@ require_dependency 'spree/returns_calculator'
module Spree
module Calculator::Returns
class DefaultRefundAmount < ReturnsCalculator
- attr_reader :inventory_unit
+ attr_reader :fulfillment_item
def self.description
Spree.t(:default_refund_amount)
end
+ # The line item's pre_tax_amount already reflects every discount that
+ # touches the line — including the line's share of whole-order
+ # promotions, which are distributed to line-item Discount rows at
+ # application time — so no separate order-level weighting is needed.
def compute(return_item)
return 0.0.to_d if return_item.exchange_requested?
- @inventory_unit = return_item.inventory_unit
- weighted_order_adjustment_amount(return_item) + weighted_line_item_pre_tax_amount(return_item)
+ @fulfillment_item = return_item.fulfillment_item
+ weighted_line_item_pre_tax_amount(return_item)
end
private
- def weighted_order_adjustment_amount(return_item)
- inventory_unit.order.adjustments.eligible.non_tax.sum(:amount) * percentage_of_order_total(return_item)
- end
-
- def percentage_of_order_total(return_item)
- return 0.0 if inventory_unit.order.pre_tax_item_amount.zero?
-
- weighted_line_item_pre_tax_amount(return_item) / inventory_unit.order.pre_tax_item_amount
- end
-
def weighted_line_item_pre_tax_amount(return_item)
- inventory_unit.line_item.pre_tax_amount * percentage_of_line_item(return_item)
+ fulfillment_item.line_item.pre_tax_amount * percentage_of_line_item(return_item)
end
def percentage_of_line_item(return_item)
- return_item.return_quantity / BigDecimal(inventory_unit.line_item.quantity)
+ return_item.return_quantity / BigDecimal(fulfillment_item.line_item.quantity)
end
end
end
diff --git a/spree/core/app/models/spree/cart.rb b/spree/core/app/models/spree/cart.rb
index 40312ce1f4..86a07d5139 100644
--- a/spree/core/app/models/spree/cart.rb
+++ b/spree/core/app/models/spree/cart.rb
@@ -29,6 +29,9 @@ module Spree
belongs_to :bill_address, class_name: 'Spree::Address', optional: true
has_many :line_items, -> { order(:created_at) }, class_name: 'Spree::LineItem', inverse_of: :cart, dependent: :destroy
+ has_many :tax_lines, class_name: 'Spree::TaxLine', dependent: :destroy, inverse_of: :cart
+ has_many :discounts, class_name: 'Spree::Discount', dependent: :destroy, inverse_of: :cart
+ has_many :fees, class_name: 'Spree::Fee', dependent: :destroy, inverse_of: :cart
has_one :order, class_name: 'Spree::Order', inverse_of: :cart
validates :store, :currency, presence: true
@@ -47,5 +50,18 @@ module Spree
def completing?
completing_at.present?
end
+
+ # The address tax is computed against, honoring the tax_using_ship_address
+ # preference (mirrors Spree::Order#tax_address).
+ #
+ # @return [Spree::Address, nil]
+ def tax_address
+ Spree::Config[:tax_using_ship_address] ? ship_address : bill_address
+ end
+
+ # @return [Spree::Zone, nil]
+ def tax_zone
+ Spree::Zone.match(tax_address) || Spree::Zone.default_tax
+ end
end
end
diff --git a/spree/core/app/models/spree/delivery_rate.rb b/spree/core/app/models/spree/delivery_rate.rb
index 6c56c2c727..bf00394786 100644
--- a/spree/core/app/models/spree/delivery_rate.rb
+++ b/spree/core/app/models/spree/delivery_rate.rb
@@ -42,11 +42,19 @@ module Spree
final_price.zero?
end
- # Returns the tax amount for the shipping rate
+ # Returns the tax amount for the shipping rate, computed directly from
+ # the rate configuration (rates display estimated tax before a
+ # fulfillment exists, so this never reads TaxLine rows).
#
# @return [BigDecimal]
def tax_amount
- @tax_amount ||= tax_rate&.calculator&.compute_shipping_rate(self) || BigDecimal(0)
+ @tax_amount ||= if tax_rate.nil?
+ BigDecimal(0)
+ elsif tax_rate.included_in_price?
+ (cost / (1 + tax_rate.amount) * tax_rate.amount).round(2)
+ else
+ (cost * tax_rate.amount).round(2)
+ end
end
# Returns the additional tax total for the shipping rate
@@ -99,7 +107,7 @@ module Spree
private
def discount_amount
- fulfillment.adjustments.promotion.sum(:amount)
+ fulfillment.discounts.promotion.sum(:amount)
end
end
end
diff --git a/spree/core/app/models/spree/discount.rb b/spree/core/app/models/spree/discount.rb
new file mode 100644
index 0000000000..089753ea6a
--- /dev/null
+++ b/spree/core/app/models/spree/discount.rb
@@ -0,0 +1,47 @@
+module Spree
+ # A promotion or manual discount on a line item or fulfillment. Amount is
+ # enforced non-positive (validation + DB CHECK). Provenance snapshots
+ # (+code+, +value+, +value_type+) keep rows meaningful after the promotion
+ # is deleted — the promotion FKs are nullified, never cascaded.
+ #
+ # Order-level discounts are distributed proportionally across line items at
+ # application time (largest-remainder) — there are no order-attached rows.
+ class Discount < Spree.base_class
+ include Spree::TypedAdjustmentLine
+
+ has_prefix_id :disc
+
+ # Source — nullified on promotion deletion
+ belongs_to :promotion_action, class_name: 'Spree::PromotionAction', optional: true
+ belongs_to :promotion, class_name: 'Spree::Promotion', optional: true
+
+ # Adjustable — exactly one
+ belongs_to :line_item, class_name: 'Spree::LineItem', optional: true
+ belongs_to :fulfillment, class_name: 'Spree::Fulfillment', optional: true
+
+ validates :amount, numericality: { less_than_or_equal_to: 0 }
+ validates :kind, presence: true
+ validate :exactly_one_adjustable
+
+ scope :for_line_items, -> { where.not(line_item_id: nil) }
+ scope :for_fulfillments, -> { where.not(fulfillment_id: nil) }
+ scope :promotion, -> { where(kind: 'promotion') }
+ scope :manual, -> { where(kind: 'manual') }
+ scope :nonzero, -> { where.not(amount: 0) }
+
+ # @return [Spree::LineItem, Spree::Fulfillment, nil]
+ def adjustable
+ line_item || fulfillment
+ end
+
+ def promotion?
+ kind == 'promotion'
+ end
+
+ private
+
+ def exactly_one_adjustable
+ errors.add(:base, Spree.t('errors.messages.exactly_one_adjustable')) unless [line_item, fulfillment].compact.one?
+ end
+ end
+end
diff --git a/spree/core/app/models/spree/fee.rb b/spree/core/app/models/spree/fee.rb
new file mode 100644
index 0000000000..73eee4ee15
--- /dev/null
+++ b/spree/core/app/models/spree/fee.rb
@@ -0,0 +1,34 @@
+module Spree
+ # An extensible charge (surcharge, handling, gift wrap, COD, payment fee).
+ # May target a line item or fulfillment, or be order-level (both adjustable
+ # FKs nil). Fees are taxable — the tax provider writes TaxLine rows against
+ # them. Ad-hoc credits are manual Discounts, never negative fees (amount is
+ # enforced non-negative by validation + DB CHECK).
+ class Fee < Spree.base_class
+ include Spree::TypedAdjustmentLine
+
+ has_prefix_id :fee
+
+ # Adjustable — optional: both nil means an order-level fee
+ belongs_to :line_item, class_name: 'Spree::LineItem', optional: true
+ belongs_to :fulfillment, class_name: 'Spree::Fulfillment', optional: true
+
+ has_many :tax_lines, class_name: 'Spree::TaxLine', dependent: :destroy
+
+ validates :amount, numericality: { greater_than_or_equal_to: 0 }
+ validates :kind, presence: true
+
+ scope :for_line_items, -> { where.not(line_item_id: nil) }
+ scope :for_fulfillments, -> { where.not(fulfillment_id: nil) }
+ scope :order_level, -> { where(line_item_id: nil, fulfillment_id: nil) }
+
+ # @return [Spree::LineItem, Spree::Fulfillment, nil] nil for order-level fees
+ def adjustable
+ line_item || fulfillment
+ end
+
+ def order_level?
+ line_item_id.nil? && fulfillment_id.nil?
+ end
+ end
+end
diff --git a/spree/core/app/models/spree/fulfillment.rb b/spree/core/app/models/spree/fulfillment.rb
index 4f130637d1..363060c7a3 100644
--- a/spree/core/app/models/spree/fulfillment.rb
+++ b/spree/core/app/models/spree/fulfillment.rb
@@ -23,14 +23,17 @@ module Spree
belongs_to :address, class_name: 'Spree::Address'
belongs_to :order, class_name: 'Spree::Order', touch: true
end
+ belongs_to :cart, class_name: 'Spree::Cart', optional: true
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 :tax_lines, class_name: 'Spree::TaxLine', dependent: :destroy, inverse_of: :fulfillment
+ has_many :discounts, class_name: 'Spree::Discount', dependent: :destroy, inverse_of: :fulfillment
+ has_many :fees, class_name: 'Spree::Fee', dependent: :destroy, inverse_of: :fulfillment
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'
@@ -69,6 +72,15 @@ module Spree
scope :digital_delivery, -> { joins(:delivery_methods).merge(Spree::DeliveryMethod.digital) }
delegate :store, :currency, to: :order
+
+ # The exactly-one owner of this fulfillment — the cart during checkout,
+ # the order after completion. New code must read +owner+, never assume
+ # +order+.
+ #
+ # @return [Spree::Cart, Spree::Order, nil]
+ def owner
+ order || cart
+ end
delegate :amount_in_cents, to: :display_cost
state_machine :status, initial: :pending, use_transactions: false do
@@ -285,8 +297,7 @@ module Spree
#
# @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?
+ discounts.promotion.exists?
end
def finalize!
@@ -522,12 +533,9 @@ module Spree
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
- )
+ if selected_delivery_rate && cost != selected_delivery_rate.cost
+ # Typed adjustment columns are refreshed by the order recalculation.
+ update_columns(cost: selected_delivery_rate.cost, updated_at: Time.current)
end
end
@@ -607,16 +615,18 @@ module Spree
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'
+ # A cost change shifts discount and tax bases — rebuild through the
+ # order-level recalculation. Creation is excluded (the surrounding flow
+ # runs the updater itself; recursing mid-assignment breaks collection
+ # replacement) and completed orders are frozen.
+ return if previously_new_record?
+
+ order.update_with_updater! if saved_change_to_cost? && status != 'fulfilled' && order&.persisted? && !order.completed?
end
end
end
diff --git a/spree/core/app/models/spree/line_item.rb b/spree/core/app/models/spree/line_item.rb
index 2e441a71e6..fa34cf8fe8 100644
--- a/spree/core/app/models/spree/line_item.rb
+++ b/spree/core/app/models/spree/line_item.rb
@@ -21,7 +21,9 @@ module Spree
has_one :product, -> { with_deleted }, class_name: 'Spree::Product', through: :variant
- has_many :adjustments, as: :adjustable, dependent: :destroy
+ has_many :tax_lines, class_name: 'Spree::TaxLine', dependent: :destroy, inverse_of: :line_item
+ has_many :discounts, class_name: 'Spree::Discount', dependent: :destroy, inverse_of: :line_item
+ has_many :fees, class_name: 'Spree::Fee', dependent: :destroy, inverse_of: :line_item
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
@@ -158,27 +160,13 @@ module Spree
alias discounted_money display_discounted_amount
alias discounted_amount taxable_amount
- # Returns the amount this line item is taxed on: the discounted amount
- # reduced further by the line item's proportional share of any
- # whole-order promotions, which are adjustments on the order itself and
- # therefore not part of +taxable_adjustment_total+. Never negative.
+ # Returns the amount this line item is taxed on. Whole-order promotions
+ # are distributed to line-item Discount rows at application time, so the
+ # discounted amount already carries the line's share. Never negative.
#
# @return [BigDecimal]
def taxable_basis
- basis = taxable_amount
- return basis if basis <= 0
-
- order_discount = owner.order_level_promo_total
- return basis if order_discount.zero?
-
- # summed in SQL so the allocation uses the persisted adjustment totals
- # of all line items, not a possibly stale cached association
- items_total = owner.line_items.reorder(nil).pick(
- Arel.sql('COALESCE(SUM(price * quantity + taxable_adjustment_total), 0)')
- )
- return basis if items_total <= 0
-
- [basis + (order_discount * basis / items_total), BigDecimal(0)].max
+ [taxable_amount, BigDecimal(0)].max
end
# Returns the final amount of the line item
@@ -337,10 +325,12 @@ module Spree
end
def update_adjustments
- if saved_change_to_quantity?
+ # Typed rows (discounts + tax) are rebuilt by the order-level
+ # recalculation, which every cart/checkout flow runs after the save —
+ # recalculating from here would cache the owner's associations
+ # mid-mutation and hide later changes from that run.
+ if saved_change_to_quantity? && owner&.persisted? && !owner.completed?
recalculate_price if should_update_price? && !previously_new_record?
- recalculate_adjustments
- update_tax_charge # Called to ensure pre_tax_amount is updated.
end
end
@@ -352,14 +342,10 @@ module Spree
!owner.completed?
end
- def recalculate_adjustments
- Spree::Adjustable::AdjustmentsUpdater.update(self)
- end
-
def update_tax_charge
- return unless order
+ return unless owner
- Spree::TaxRate.adjust(order, [self])
+ Spree.tax_provider.estimate(owner, [self])
end
def ensure_proper_currency
diff --git a/spree/core/app/models/spree/order.rb b/spree/core/app/models/spree/order.rb
index 9cad954fce..ca903a63a6 100644
--- a/spree/core/app/models/spree/order.rb
+++ b/spree/core/app/models/spree/order.rb
@@ -186,13 +186,11 @@ module Spree
has_many :payments, class_name: 'Spree::Payment'
has_many :payment_sessions, inverse_of: :order, class_name: 'Spree::PaymentSession'
has_many :return_authorizations, inverse_of: :order, class_name: 'Spree::ReturnAuthorization'
- has_many :adjustments, -> { order(:created_at) }, as: :adjustable, class_name: 'Spree::Adjustment'
has_many :cancellations, -> { order(:created_at) }, inverse_of: :order, class_name: 'Spree::OrderCancellation'
has_many :approvals, -> { order(:created_at) }, inverse_of: :order, class_name: 'Spree::OrderApproval'
end
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 :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
@@ -200,11 +198,15 @@ module Spree
has_many :variants, through: :line_items
has_many :products, through: :variants
has_many :refunds, through: :payments
- has_many :all_adjustments,
- class_name: 'Spree::Adjustment',
- foreign_key: :order_id,
- dependent: :destroy,
- inverse_of: :order
+
+ # Typed adjustment rows owned by this order (line-, fulfillment- and
+ # order-level). See docs/plans/6.0-split-adjustments.md.
+ has_many :tax_lines, class_name: 'Spree::TaxLine', dependent: :destroy, inverse_of: :order
+ has_many :discounts, class_name: 'Spree::Discount', dependent: :destroy, inverse_of: :order
+ has_many :fees, class_name: 'Spree::Fee', dependent: :destroy, inverse_of: :order
+
+ has_many :line_item_tax_lines, through: :line_items, source: :tax_lines
+ has_many :line_item_discounts, through: :line_items, source: :discounts
has_many :order_promotions, class_name: 'Spree::OrderPromotion'
has_many :promotions, through: :order_promotions, class_name: 'Spree::Promotion'
@@ -214,10 +216,10 @@ module Spree
pluck(:status).uniq
end
end
- has_many :shipment_adjustments, through: :fulfillments, source: :adjustments
+ has_many :fulfillment_tax_lines, through: :fulfillments, source: :tax_lines
+ has_many :fulfillment_discounts, through: :fulfillments, source: :discounts
alias items line_items
- alias discounts order_promotions
# 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
@@ -377,13 +379,13 @@ module Spree
end
# Sum of the eligible promotion adjustments applied to the order itself
- # (whole-order discounts created by Promotion::Actions::CreateAdjustment),
- # as opposed to promotions applied to individual line items or shipments.
- # Zero or negative.
+ # (whole-order discounts created by PromotionActions::CreateAdjustment,
+ # distributed proportionally across line items), as opposed to promotions
+ # applied to individual line items or fulfillments. Zero or negative.
#
# @return [BigDecimal]
def order_level_promo_total
- adjustments.promotion.eligible.sum(:amount)
+ discounts.promotion.where(promotion_action_id: promotion_actions_of_scope(:order)).sum(:amount)
end
# Sum of all line item and shipment pre-tax
@@ -391,6 +393,13 @@ module Spree
pre_tax_item_amount + fulfillments.sum(:pre_tax_amount)
end
+ # Promotion actions of the given discount scope, covering both the 6.0
+ # class names and the legacy STI names still present in the type column
+ # until the 6.1 data migration.
+ def promotion_actions_of_scope(scope)
+ Spree::PromotionAction.where(type: Spree::PromotionAction.types_for_discount_scope(scope))
+ end
+
# Returns the subtotal used for analytics integrations
# It's a sum of the item total and the promo total
# @return [Float]
@@ -399,7 +408,7 @@ module Spree
end
def shipping_discount
- shipment_adjustments.non_tax.eligible.sum(:amount) * - 1
+ discounts.for_fulfillments.sum(:amount) * -1
end
def completed?
@@ -594,15 +603,14 @@ module Spree
end
end
- # Creates new tax charges if there are any applicable rates. If prices already
- # include taxes then price adjustments are created instead.
+ # Re-estimates tax through the configured provider (writes TaxLine rows
+ # with replace-all semantics).
def create_tax_charge!
- Spree::TaxRate.adjust(self, line_items)
- Spree::TaxRate.adjust(self, fulfillments) if fulfillments.any?
+ Spree.tax_provider.estimate(self)
end
def create_shipment_tax_charge!
- Spree::TaxRate.adjust(self, fulfillments) if fulfillments.any?
+ Spree.tax_provider.estimate(self, fulfillments.to_a) if fulfillments.any?
end
def update_line_item_prices!
@@ -677,8 +685,9 @@ module Spree
# Finalizes an in progress order after checkout is complete.
# Called after transition to complete state when payments will have been processed
def finalize!
- # lock all adjustments (coupon promotions, etc.)
- all_adjustments.each(&:close)
+ # Typed adjustment rows are frozen by the order-level recalculation
+ # freeze (OrderUpdater#recalculate_adjustments) once completed — no
+ # per-row locking needed.
# update payment and shipment(s) states, and save
updater.update_payment_state
@@ -687,7 +696,7 @@ module Spree
shipment.finalize!
end
- updater.update_shipment_state
+ updater.update_fulfillment_status
self.status = 'placed'
save!
updater.run_hooks
@@ -703,7 +712,7 @@ module Spree
def fulfill!
fulfillments.each { |shipment| shipment.update!(self) if shipment.persisted? }
- updater.update_shipment_state
+ updater.update_fulfillment_status
save!
end
@@ -805,7 +814,9 @@ module Spree
end
def create_proposed_shipments
- all_adjustments.shipping.delete_all
+ discounts.for_fulfillments.delete_all
+ tax_lines.for_fulfillments.delete_all
+ fees.for_fulfillments.delete_all
shipment_ids = fulfillments.map(&:id)
StateChange.where(stateful_type: %w[Spree::Shipment Spree::Fulfillment], stateful_id: shipment_ids).delete_all
@@ -873,8 +884,6 @@ module Spree
def apply_free_shipping_promotions
Spree::PromotionHandler::FreeShipping.new(self).activate
- fulfillments.each { |shipment| Spree::Adjustable::AdjustmentsUpdater.update(shipment) }
- create_shipment_tax_charge!
update_with_updater!
end
@@ -1039,9 +1048,7 @@ module Spree
# Returns the IDs of the valid promotions for the order
# @return [Array<Integer>]
def valid_promotion_ids
- all_adjustments.eligible.nonzero.promotion.promotion.eligible.nonzero.promotion.
- joins("INNER JOIN #{Spree::PromotionAction.table_name} ON #{Spree::PromotionAction.table_name}.id = #{Spree::Adjustment.table_name}.source_id").
- pluck("#{Spree::PromotionAction.table_name}.promotion_id").compact.uniq
+ discounts.promotion.nonzero.where.not(promotion_id: nil).distinct.pluck(:promotion_id)
end
# Returns the valid coupon promotions for the order
@@ -1053,19 +1060,14 @@ module Spree
end
# Returns item and whole order discount amount for Order
- # without Shipment discounts (eg. Free Shipping)
+ # without fulfillment discounts (eg. Free Shipping)
# @return [BigDecimal]
def cart_promo_total
- all_adjustments.eligible.nonzero.promotion.
- where.not(adjustable_type: %w[Spree::Shipment Spree::Fulfillment]).
- sum(:amount)
+ discounts.promotion.nonzero.for_line_items.sum(:amount)
end
def has_free_shipping?
- shipment_adjustments.
- joins(:promotion_action).
- where(spree_adjustments: { eligible: true, source_type: 'Spree::PromotionAction' },
- spree_promotion_actions: { type: 'Spree::Promotion::Actions::FreeShipping' }).exists?
+ discounts.promotion.for_fulfillments.exists?
end
def to_csv(_store = nil)
diff --git a/spree/core/app/models/spree/order_merger.rb b/spree/core/app/models/spree/order_merger.rb
index 9d08ce36e0..efaa71fff4 100644
--- a/spree/core/app/models/spree/order_merger.rb
+++ b/spree/core/app/models/spree/order_merger.rb
@@ -58,7 +58,9 @@ module Spree
handle_error(current_line_item) unless current_line_item.save
else
order.line_items << other_order_line_item
- other_order_line_item.adjustments.update_all(order_id: order.id)
+ other_order_line_item.discounts.update_all(order_id: order.id)
+ other_order_line_item.tax_lines.update_all(order_id: order.id)
+ other_order_line_item.fees.update_all(order_id: order.id)
handle_error(other_order_line_item) unless other_order_line_item.save
end
end
diff --git a/spree/core/app/models/spree/order_promotion.rb b/spree/core/app/models/spree/order_promotion.rb
index 317e358294..b717163002 100644
--- a/spree/core/app/models/spree/order_promotion.rb
+++ b/spree/core/app/models/spree/order_promotion.rb
@@ -15,7 +15,7 @@ module Spree
money_methods :amount
def amount
- order.all_adjustments.promotion.where(source: promotion.actions).sum(:amount)
+ order.discounts.promotion.where(promotion_action_id: promotion.actions.ids).sum(:amount)
end
end
end
diff --git a/spree/core/app/models/spree/order_updater.rb b/spree/core/app/models/spree/order_updater.rb
index cf9e5e749d..efb1241ae1 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, :fulfillments, :update_hooks, :quantity, to: :order
+ delegate :payments, :line_items, :fulfillments, :update_hooks, :quantity, to: :order
def initialize(order)
@order = order
@@ -15,6 +15,11 @@ module Spree
# object with callbacks (otherwise you will end up in an infinite recursion as the
# associations try to save and then in turn try to call +update!+ again.)
def update
+ # Drop possibly stale association caches — an earlier recalculation on
+ # this instance may have loaded them mid-mutation.
+ order.association(:line_items).reset if order.persisted?
+ order.association(:fulfillments).reset if order.persisted?
+
update_item_count
update_totals
if order.completed?
@@ -31,23 +36,35 @@ module Spree
update_hooks.each { |hook| order.send hook }
end
+ # Rebuilds the typed adjustment rows (Discount/Fee via Spree.adjusters,
+ # TaxLine via Spree.tax_provider) and refreshes the denormalized columns
+ # on line items and fulfillments. Two-pass: adjusters persist the
+ # discounted taxable base first, then tax is estimated on it.
+ #
+ # Completed orders are frozen — recalculation refuses to touch them.
+ # Post-placement changes go through explicit admin actions that write
+ # typed rows directly and recompute totals via {#update}.
def recalculate_adjustments
- all_adjustments.includes(:adjustable).map(&:adjustable).uniq.each do |adjustable|
- Adjustable::AdjustmentsUpdater.update(adjustable)
- end
+ return if order.completed?
+
+ Spree.adjusters.each { |adjuster| adjuster.adjust(order) }
+ refresh_discount_and_fee_columns
+ Spree.tax_provider.estimate(order)
+ refresh_tax_columns
end
# Updates the following Order total values:
#
# +payment_total+ The total value of all finalized Payments (NOTE: non-finalized Payments are excluded)
# +item_total+ The total value of all LineItems
- # +adjustment_total+ The total value of all adjustments (promotions, credits, etc.)
- # +promo_total+ The total value of all promotion adjustments
- # +total+ The so-called "order total." This is equivalent to +item_total+ plus +shipment_total+ plus +adjustment_total+.
+ # +adjustment_total+ The total value of all typed adjustment rows (discounts, fees, additional tax)
+ # +promo_total+ The total value of all promotion discounts
+ # +fee_total+ The total value of all fees
+ # +total+ The so-called "order total." Equivalent to +item_total+ plus +delivery_total+ plus +adjustment_total+.
def update_totals
update_payment_total
update_item_total
- update_shipment_total
+ update_delivery_total
update_adjustment_total
end
@@ -55,12 +72,12 @@ module Spree
def update_fulfillments
shipping_method_filter = order.completed? ? DeliveryMethod::DISPLAY_ON_BACK_END : DeliveryMethod::DISPLAY_ON_FRONT_END
- fulfillments.each do |shipment|
- next unless shipment.persisted?
+ fulfillments.each do |fulfillment|
+ next unless fulfillment.persisted?
- shipment.update!(order)
- shipment.refresh_rates(shipping_method_filter)
- shipment.update_amounts
+ fulfillment.update!(order)
+ fulfillment.refresh_rates(shipping_method_filter)
+ fulfillment.update_amounts
end
end
@@ -77,36 +94,31 @@ module Spree
order.total = order.item_total + order.delivery_total + order.adjustment_total
end
+ # Aggregates order totals from the typed tables. On completed orders the
+ # stored sums are left untouched (the recalculation freeze) — only the
+ # roll-up total is refreshed from its parts.
def update_adjustment_total
+ if order.completed?
+ update_order_total
+ return
+ end
+
recalculate_adjustments
- # Fetch all line item totals in a single query
- # Use reorder(nil) to remove default ordering which conflicts with aggregates in PostgreSQL
- line_item_totals = line_items.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)'),
- Arel.sql('COALESCE(SUM(promo_total), 0)')
- ) || [0, 0, 0, 0]
-
- # Fetch all shipment totals in a single query
- 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)'),
- Arel.sql('COALESCE(SUM(promo_total), 0)')
- ) || [0, 0, 0, 0]
-
- # Fetch order-level adjustment totals in a single query
- order_adjustment_totals = adjustments.eligible.reorder(nil).pick(
- Arel.sql('COALESCE(SUM(amount), 0)'),
- Arel.sql("COALESCE(SUM(CASE WHEN source_type = 'Spree::PromotionAction' THEN amount ELSE 0 END), 0)")
- ) || [0, 0]
-
- order.adjustment_total = line_item_totals[0] + shipment_totals[0] + order_adjustment_totals[0]
- order.included_tax_total = line_item_totals[1] + shipment_totals[1]
- order.additional_tax_total = line_item_totals[2] + shipment_totals[2]
- order.promo_total = line_item_totals[3] + shipment_totals[3] + order_adjustment_totals[1]
+ discounts_sum = order.discounts.reload.sum(&:amount)
+ fees = order.fees.reload.to_a
+ tax_sums = order.tax_lines.reload.group_by(&:included?).transform_values { |lines| lines.sum(&:amount) }
+
+ order.promo_total = order.discounts.select(&:promotion?).sum(&:amount)
+ order.fee_total = fees.sum(&:amount)
+ order.included_tax_total = tax_sums.fetch(true, 0)
+ order.additional_tax_total = tax_sums.fetch(false, 0)
+ order.adjustment_total = discounts_sum + order.fee_total + order.additional_tax_total
+
+ # The order's own adjustable columns cover order-level rows only:
+ # discounts distribute to line items, so fees are the only residents.
+ order.taxable_adjustment_total = 0
+ order.non_taxable_adjustment_total = fees.select(&:order_level?).sum(&:amount)
update_order_total
end
@@ -129,9 +141,12 @@ module Spree
adjustment_total: order.adjustment_total,
included_tax_total: order.included_tax_total,
additional_tax_total: order.additional_tax_total,
+ taxable_adjustment_total: order.taxable_adjustment_total,
+ non_taxable_adjustment_total: order.non_taxable_adjustment_total,
payment_total: order.payment_total,
delivery_total: order.delivery_total,
promo_total: order.promo_total,
+ fee_total: order.fee_total,
total: order.total,
updated_at: Time.current
)
@@ -213,5 +228,57 @@ module Spree
order.state_changed('payment') if last_state != order.payment_state
order.payment_state
end
+
+ private
+
+ # Pass one of the two-pass recalculation: persist per-adjustable discount
+ # and fee sums so the tax provider estimates on the discounted base.
+ def refresh_discount_and_fee_columns
+ discounts = order.discounts.reload.to_a
+ fees = order.fees.reload.to_a
+
+ each_adjustable do |adjustable, key|
+ rows = discounts.select { |row| row.public_send(key) == adjustable.id }
+ fee_rows = fees.select { |row| row.public_send(key) == adjustable.id }
+
+ update_adjustable_columns(
+ adjustable,
+ taxable_adjustment_total: rows.sum(&:amount),
+ non_taxable_adjustment_total: fee_rows.sum(&:amount),
+ promo_total: rows.select(&:promotion?).sum(&:amount)
+ )
+ end
+ end
+
+ # Pass two: fold the freshly estimated tax into the per-adjustable columns.
+ def refresh_tax_columns
+ tax_lines = order.tax_lines.reload.to_a
+
+ each_adjustable do |adjustable, key|
+ rows = tax_lines.select { |row| row.public_send(key) == adjustable.id }
+ included, additional = rows.partition(&:included?)
+
+ update_adjustable_columns(
+ adjustable,
+ included_tax_total: included.sum(&:amount),
+ additional_tax_total: additional.sum(&:amount),
+ adjustment_total: adjustable.taxable_adjustment_total +
+ adjustable.non_taxable_adjustment_total +
+ additional.sum(&:amount)
+ )
+ end
+ end
+
+ def each_adjustable
+ line_items.each { |line_item| yield line_item, :line_item_id }
+ fulfillments.each { |fulfillment| yield fulfillment, :fulfillment_id }
+ end
+
+ def update_adjustable_columns(adjustable, attributes)
+ return unless adjustable.persisted?
+ return if attributes.all? { |key, value| adjustable.public_send(key) == value }
+
+ adjustable.update_columns(attributes.merge(updated_at: Time.current))
+ end
end
end
diff --git a/spree/core/app/models/spree/permission_sets/order_display.rb b/spree/core/app/models/spree/permission_sets/order_display.rb
index dd3588f56c..b53924f828 100644
--- a/spree/core/app/models/spree/permission_sets/order_display.rb
+++ b/spree/core/app/models/spree/permission_sets/order_display.rb
@@ -13,7 +13,9 @@ module Spree
can [:read, :admin, :index], Spree::Order
can [:read, :admin], Spree::Payment
can [:read, :admin], Spree::Shipment
- can [:read, :admin], Spree::Adjustment
+ can [:read, :admin], Spree::TaxLine
+ can [:read, :admin], Spree::Discount
+ can [:read, :admin], Spree::Fee
can [:read, :admin], Spree::LineItem
can [:read, :admin], Spree::ReturnAuthorization
can [:read, :admin], Spree::CustomerReturn
diff --git a/spree/core/app/models/spree/permission_sets/order_management.rb b/spree/core/app/models/spree/permission_sets/order_management.rb
index 2d2076cfc0..c004250732 100644
--- a/spree/core/app/models/spree/permission_sets/order_management.rb
+++ b/spree/core/app/models/spree/permission_sets/order_management.rb
@@ -13,7 +13,9 @@ module Spree
can :manage, Spree::Order
can :manage, Spree::Payment
can :manage, Spree::Shipment
- can :manage, Spree::Adjustment
+ can :manage, Spree::TaxLine
+ can :manage, Spree::Discount
+ can :manage, Spree::Fee
can :manage, Spree::LineItem
can :manage, Spree::ReturnAuthorization
can :manage, Spree::CustomerReturn
diff --git a/spree/core/app/models/spree/promotion.rb b/spree/core/app/models/spree/promotion.rb
index dbf723a074..111d3babc8 100644
--- a/spree/core/app/models/spree/promotion.rb
+++ b/spree/core/app/models/spree/promotion.rb
@@ -243,7 +243,7 @@ module Spree
end
def products
- rules.where(type: 'Spree::Promotion::Rules::Product').map(&:products).flatten.uniq
+ rules.where(type: %w[Spree::PromotionRules::Product Spree::Promotion::Rules::Product]).map(&:products).flatten.uniq
end
def usage_limit_exceeded?(promotable)
@@ -251,12 +251,16 @@ module Spree
end
def adjusted_credits_count(promotable)
- adjustments = promotable.is_a?(Order) ? promotable.all_adjustments : promotable.adjustments
- credits_count - adjustments.eligible.promotion.where(source_id: actions.pluck(:id)).select(:order_id).distinct.count
+ own_credits = if promotable.is_a?(Order)
+ credits.where(order_id: promotable.id).select(:order_id).distinct.count
+ else
+ credits.where(line_item_id: promotable.id).select(:order_id).distinct.count
+ end
+ credits_count - own_credits
end
def credits
- Adjustment.eligible.promotion.where(source_id: actions.map(&:id))
+ Spree::Discount.promotion.where(promotion_action_id: actions.map(&:id))
end
def credits_count
@@ -279,10 +283,9 @@ module Spree
end
def used_by?(user, excluded_orders = [])
- user.orders.complete.joins(:promotions).joins(:all_adjustments).
+ user.orders.complete.joins(:discounts).
where.not(spree_orders: { id: excluded_orders.map(&:id) }).
- where(spree_promotions: { id: id }).
- where(spree_adjustments: { source_type: 'Spree::PromotionAction', eligible: true }).any?
+ where(Spree::Discount.table_name => { promotion_id: id, kind: 'promotion' }).any?
end
def name_for_order(order)
diff --git a/spree/core/app/models/spree/promotion/actions/create_adjustment.rb b/spree/core/app/models/spree/promotion/actions/create_adjustment.rb
index bbfe066390..8e66d1381a 100644
--- a/spree/core/app/models/spree/promotion/actions/create_adjustment.rb
+++ b/spree/core/app/models/spree/promotion/actions/create_adjustment.rb
@@ -1,30 +1,2 @@
-module Spree
- class Promotion
- module Actions
- class CreateAdjustment < PromotionAction
- include Spree::CalculatedAdjustments
- include Spree::AdjustmentSource
-
- before_validation -> { self.calculator ||= Calculator::FlatPercentItemTotal.new }
-
- def self.additional_permitted_attributes
- [calculator: [:type, { preferences: {} }]]
- end
-
- def perform(options = {})
- order = options[:order]
-
- create_unique_adjustment(order, order)
- end
-
- def compute_amount(order)
- [order_total(order), compute(order)].min * -1
- end
-
- def order_total(order)
- order.item_total + order.ship_total - order.shipping_discount
- end
- end
- end
- end
-end
+# Legacy constant path — removed in 6.1. Real class: Spree::PromotionActions::CreateAdjustment.
+Spree::Promotion::Actions::CreateAdjustment = Spree::PromotionActions::CreateAdjustment
diff --git a/spree/core/app/models/spree/promotion/actions/create_item_adjustments.rb b/spree/core/app/models/spree/promotion/actions/create_item_adjustments.rb
index 62a5e438c1..09e6f8e0a3 100644
--- a/spree/core/app/models/spree/promotion/actions/create_item_adjustments.rb
+++ b/spree/core/app/models/spree/promotion/actions/create_item_adjustments.rb
@@ -1,37 +1,2 @@
-module Spree
- class Promotion
- module Actions
- class CreateItemAdjustments < PromotionAction
- include Spree::CalculatedAdjustments
- include Spree::AdjustmentSource
-
- before_validation -> { self.calculator ||= Calculator::PercentOnLineItem.new }
-
- def self.additional_permitted_attributes
- [calculator: [:type, { preferences: {} }]]
- end
-
- def perform(options = {})
- order = options[:order]
- promotion = options[:promotion]
-
- create_unique_adjustments(order, order.line_items) do |line_item|
- promotion.line_item_actionable?(order, line_item)
- end
- end
-
- def compute_amount(line_item)
- return 0 unless promotion.line_item_actionable?(line_item.order, line_item)
-
- amounts = [line_item.amount, compute(line_item)]
- order = line_item.order
-
- # Prevent negative order totals
- amounts << order.amount - order.adjustments.eligible.sum(:amount).abs if order.adjustments.eligible.any?
-
- amounts.min * -1
- end
- end
- end
- end
-end
+# Legacy constant path — removed in 6.1. Real class: Spree::PromotionActions::CreateItemDiscounts.
+Spree::Promotion::Actions::CreateItemAdjustments = Spree::PromotionActions::CreateItemDiscounts
diff --git a/spree/core/app/models/spree/promotion/actions/create_line_items.rb b/spree/core/app/models/spree/promotion/actions/create_line_items.rb
index 950ff0f796..6d05b34237 100644
--- a/spree/core/app/models/spree/promotion/actions/create_line_items.rb
+++ b/spree/core/app/models/spree/promotion/actions/create_line_items.rb
@@ -1,138 +1,2 @@
-module Spree
- class Promotion
- module Actions
- class CreateLineItems < PromotionAction
- has_many :promotion_action_line_items, foreign_key: :promotion_action_id, dependent: :destroy
-
- attribute :promotion_action_line_items_attributes
-
- after_save :handle_promotion_action_line_items
-
- def self.additional_permitted_attributes
- [line_items: [:variant_id, :quantity]]
- end
-
- # API v3 flat alias for `promotion_action_line_items_attributes`.
- # Accepts an array of `{ variant_id:, quantity: }` rows; the list
- # is the *desired* set, so anything missing on save is removed.
- def line_items=(rows)
- self.promotion_action_line_items_attributes = rows
- end
-
- delegate :eligible?, to: :promotion
-
- # Adds a line item to the Order if the promotion is eligible
- #
- # This doesn't play right with Add to Cart events because at the moment
- # the item was added to cart the promo may not be eligible. However it
- # might become eligible as the order gets updated.
- #
- # e.g.
- # - A promo adds a line item to cart if order total greater then $30
- # - Customer add 1 item of $10 to cart
- # - This action shouldn't perform because the order is not eligible
- # - Customer increases item quantity to 5 (order total goes to $50)
- # - Now the order is eligible for the promo and the action should perform
- #
- # Another complication is when the same line item created by the promo
- # is also added to cart on a separate action.
- #
- # e.g.
- # - Promo adds 1 item A to cart if order total greater then $30
- # - Customer add 2 items B to cart, current order total is $40
- # - This action performs adding item A to cart since order is eligible
- # - Customer changes his mind and updates item B quantity to 1
- # - At this point order is no longer eligible and one might expect
- # that item A should be removed
- #
- # It doesn't remove items from the order here because there's no way
- # it can know whether that item was added via this promo action or if
- # it was manually populated somewhere else. In that case the item
- # needs to be manually removed from the order by the customer
- def perform(options = {})
- order = options[:order]
- return unless eligible? order
-
- action_taken = false
- promotion_action_line_items.each do |item|
- current_quantity = order.quantity_of(item.variant)
- next unless current_quantity < item.quantity && item_available?(item)
-
- line_item = Spree.cart_add_item_service.call(order: order,
- variant: item.variant,
- quantity: item.quantity - current_quantity).value
- action_taken = true if line_item.try(:valid?)
- end
- action_taken
- end
-
- # Called by promotion handler when a promotion is removed
- # This will find any line item matching the ones defined in the PromotionAction
- # and remove the same quantity as was added by the PromotionAction.
- # Should help to prevent some of cases listed above the #perform method
- def revert(options = {})
- order = options[:order]
- return if eligible?(order)
-
- action_taken = false
- promotion_action_line_items.each do |item|
- line_item = order.find_line_item_by_variant(item.variant)
- next unless line_item.present?
-
- Spree.cart_remove_item_service.call(order: order,
- variant: item.variant,
- quantity: (item.quantity || 1))
- action_taken = true
- end
-
- action_taken
- end
-
- # Checks that there's enough stock to add the line item to the order
- def item_available?(item)
- quantifier = Spree::Stock::Quantifier.new(item.variant)
- quantifier.can_supply? item.quantity
- end
-
- private
-
- # Handles the creation, updating, and pruning of promotion action
- # line items. The submitted list is the *desired* set — variants
- # not present are deleted, ones that are get upserted. Accepts
- # both the legacy Rails admin hash shape (`{ "0" => attrs }`) and
- # a flat array from the API. Variant IDs may be raw or prefixed.
- def handle_promotion_action_line_items
- return unless promotion_action_line_items_attributes
-
- rows = promotion_action_line_items_attributes.is_a?(Hash) ? promotion_action_line_items_attributes.values : promotion_action_line_items_attributes
- rows = rows.map { |row| row.respond_to?(:to_h) ? row.to_h.with_indifferent_access : row.with_indifferent_access }
-
- rows = rows.map do |row|
- variant_id = row['variant_id']
- variant_id = Spree::Variant.find_by_param(variant_id)&.id if Spree::PrefixedId.prefixed_id?(variant_id)
- row.merge('variant_id' => variant_id)
- end
-
- desired_variant_ids = rows.map { |row| row['variant_id'] }.compact
- promotion_action_line_items.where.not(variant_id: desired_variant_ids).delete_all
-
- return if rows.empty?
-
- opts = {}
- opts[:unique_by] = [:promotion_action_id, :variant_id] unless mysql_adapter?
-
- promotion_action_line_items.upsert_all(
- rows.map do |params|
- {
- variant_id: params['variant_id'],
- quantity: params['quantity'],
- promotion_action_id: id
- }
- end,
- **opts
- )
- end
- end
- end
- end
-end
+# Legacy constant path — removed in 6.1. Real class: Spree::PromotionActions::CreateLineItems.
+Spree::Promotion::Actions::CreateLineItems = Spree::PromotionActions::CreateLineItems
diff --git a/spree/core/app/models/spree/promotion/actions/free_shipping.rb b/spree/core/app/models/spree/promotion/actions/free_shipping.rb
index 94e1a1c00c..ce807bc09a 100644
--- a/spree/core/app/models/spree/promotion/actions/free_shipping.rb
+++ b/spree/core/app/models/spree/promotion/actions/free_shipping.rb
@@ -1,32 +1,2 @@
-module Spree
- class Promotion
- module Actions
- class FreeShipping < Spree::PromotionAction
- include Spree::AdjustmentSource
-
- def perform(payload = {})
- order = payload[:order]
-
- create_unique_adjustments(order, order.shipments)
- end
-
- def compute_amount(shipment)
- shipment.cost * -1
- end
-
- # we need to persist 0 amount adjustment
- def create_adjustment(order, adjustable, included = false)
- amount = compute_amount(adjustable)
-
- adjustable.adjustments.new(
- amount: amount,
- included: included,
- label: label,
- order: order,
- source: self
- ).save
- end
- end
- end
- end
-end
+# Legacy constant path — removed in 6.1. Real class: Spree::PromotionActions::FreeShipping.
+Spree::Promotion::Actions::FreeShipping = Spree::PromotionActions::FreeShipping
diff --git a/spree/core/app/models/spree/promotion/rules/category.rb b/spree/core/app/models/spree/promotion/rules/category.rb
index 7569f29a68..58a498e9f5 100644
--- a/spree/core/app/models/spree/promotion/rules/category.rb
+++ b/spree/core/app/models/spree/promotion/rules/category.rb
@@ -1,175 +1,2 @@
-module Spree
- class Promotion
- module Rules
- # Promotion rule matching an order against a set of Spree::Category records.
- # Renamed from Spree::Promotion::Rules::Taxon in 6.0 (alias kept for one
- # release). Existing spree_promotion_rules.type strings are backfilled by the
- # Phase 4 data migration; the alias keeps old rows resolving until then.
- class Category < PromotionRule
- #
- # Associations
- #
- has_many :promotion_rule_categories, class_name: 'Spree::PromotionRuleCategory',
- foreign_key: 'promotion_rule_id',
- dependent: :destroy
- has_many :categories, through: :promotion_rule_categories, class_name: 'Spree::Category', source: :category
-
- def self.additional_permitted_attributes
- [category_ids: []]
- end
-
- # Wire-format shorthand is `category`. `key` (instance) cascades through `api_type`.
- def self.api_type
- 'category'
- end
-
- # Decode prefixed IDs before delegating to the generated setter (direct
- # calls bypass PrefixedId's assign_attributes auto-resolver).
- def category_ids=(ids)
- super(Array(ids).map do |id|
- Spree::PrefixedId.prefixed_id?(id) ? Spree::Category.find_by_param!(id).id : id
- end)
- end
-
- #
- # Preferences
- #
- MATCH_POLICIES = %w(any all)
- preference :match_policy, :string, default: MATCH_POLICIES.first
-
- #
- # Attributes
- #
- attr_accessor :category_ids_to_add
-
- #
- # Callbacks
- #
- after_save :add_categories
-
- def applicable?(promotable)
- promotable.is_a?(Spree::Order)
- end
-
- def eligible_category_ids
- @eligible_category_ids ||= promotion_rule_categories.pluck(:category_id)
- end
-
- def eligible?(order, _options = {})
- return true if eligible_category_ids.empty?
-
- order_category_ids_with_ancestors = category_ids_in_order_including_ancestors(order)
-
- if preferred_match_policy == 'all'
- unless eligible_category_ids.all? { |id| order_category_ids_with_ancestors.include?(id) }
- eligibility_errors.add(:base, eligibility_error_message(:missing_taxon))
- end
- else
- unless eligible_category_ids.any? { |id| order_category_ids_with_ancestors.include?(id) }
- eligibility_errors.add(:base, eligibility_error_message(:no_matching_taxons))
- end
- end
-
- eligibility_errors.empty?
- end
-
- def actionable?(line_item)
- Spree::ProductCategory.where(category_id: eligible_category_ids_including_children, product_id: line_item.product_id).exists?
- end
-
- #
- # Deprecated aliases (removed in 6.1)
- #
- # @deprecated Use #categories.
- def taxons
- Spree::Deprecation.warn('Spree::Promotion::Rules::Category#taxons is deprecated and will be removed in Spree 6.1. Use #categories instead.')
- categories
- end
-
- # @deprecated Use #categories=.
- def taxons=(value)
- Spree::Deprecation.warn('Spree::Promotion::Rules::Category#taxons= is deprecated and will be removed in Spree 6.1. Use #categories= instead.')
- self.categories = value
- end
-
- # @deprecated Use #category_ids.
- def taxon_ids
- Spree::Deprecation.warn('Spree::Promotion::Rules::Category#taxon_ids is deprecated and will be removed in Spree 6.1. Use #category_ids instead.')
- category_ids
- end
-
- # @deprecated Use #category_ids=.
- def taxon_ids=(ids)
- Spree::Deprecation.warn('Spree::Promotion::Rules::Category#taxon_ids= is deprecated and will be removed in Spree 6.1. Use #category_ids= instead.')
- self.category_ids = ids
- end
-
- # @deprecated Use #eligible_category_ids.
- def eligible_taxon_ids
- Spree::Deprecation.warn('Spree::Promotion::Rules::Category#eligible_taxon_ids is deprecated and will be removed in Spree 6.1. Use #eligible_category_ids instead.')
- eligible_category_ids
- end
-
- # @deprecated Use #category_ids_to_add.
- def taxon_ids_to_add
- Spree::Deprecation.warn('Spree::Promotion::Rules::Category#taxon_ids_to_add is deprecated and will be removed in Spree 6.1. Use #category_ids_to_add instead.')
- category_ids_to_add
- end
-
- def taxon_ids_to_add=(ids)
- Spree::Deprecation.warn('Spree::Promotion::Rules::Category#taxon_ids_to_add= is deprecated and will be removed in Spree 6.1. Use #category_ids_to_add= instead.')
- self.category_ids_to_add = ids
- end
-
- def taxon_ids_string
- Spree::Deprecation.warn('Spree::Promotion::Rules::Category#taxon_ids_string is deprecated and will be removed in Spree 6.1. Use #category_ids instead.')
- categories.pluck(:id).join(',')
- end
-
- def taxon_ids_string=(s)
- Spree::Deprecation.warn('Spree::Promotion::Rules::Category#taxon_ids_string= is deprecated and will be removed in Spree 6.1. Use #category_ids= instead.')
- ids = s.to_s.split(',').map(&:strip)
- self.categories = Spree::Category.for_stores(stores).find(ids)
- end
-
- private
-
- # IDs of categories in rule including all their children
- def eligible_category_ids_including_children
- @eligible_category_ids_including_children ||= begin
- return [] if eligible_category_ids.empty?
-
- Spree::Category.where(id: eligible_category_ids).flat_map(&:cached_self_and_descendants_ids).uniq
- end
- end
-
- # IDs of categories in order that match rule categories (or their children), plus all ancestors
- def category_ids_in_order_including_ancestors(order)
- # Get category IDs from order products that are within rule categories or their children
- order_category_ids = Spree::ProductCategory.where(product_id: order.product_ids, category_id: eligible_category_ids_including_children).pluck(:category_id).uniq
-
- return [] if order_category_ids.empty?
-
- # Get those categories plus all their ancestors
- Spree::Category.where(id: order_category_ids).flat_map { |category| category.self_and_ancestors.ids }.uniq
- end
-
- def add_categories
- return if category_ids_to_add.nil?
-
- promotion_rule_categories.delete_all
-
- if category_ids_to_add.any?
- Spree::PromotionRuleCategory.insert_all(
- category_ids_to_add.map { |category_id| { category_id: category_id, promotion_rule_id: id } }
- )
- end
-
- # Clear memoized values
- @eligible_category_ids = nil
- @eligible_category_ids_including_children = nil
- end
- end
- end
- end
-end
+# Legacy constant path — removed in 6.1. Real class: Spree::PromotionRules::Category.
+Spree::Promotion::Rules::Category = Spree::PromotionRules::Category
diff --git a/spree/core/app/models/spree/promotion/rules/channel.rb b/spree/core/app/models/spree/promotion/rules/channel.rb
index dd84344282..504bf581a8 100644
--- a/spree/core/app/models/spree/promotion/rules/channel.rb
+++ b/spree/core/app/models/spree/promotion/rules/channel.rb
@@ -1,37 +1,2 @@
-# A rule to limit a promotion based on the order's channel.
-module Spree
- class Promotion
- module Rules
- class Channel < PromotionRule
- # Stored as raw IDs. Accepts prefixed IDs (`ch_…`) from API
- # callers and decodes them on write so eligibility checks compare
- # against the order's raw `channel_id` directly. Scope confines the
- # existence check to the promotion's store so cross-store channel
- # IDs can't sneak in.
- preference :channel_ids, :array, default: [],
- parse_on_set: normalize_id_preference(
- klass: Spree::Channel,
- scope: ->(rule) { rule.promotion&.store&.channels || Spree::Channel.none }
- )
-
- def applicable?(promotable)
- promotable.is_a?(Spree::Order)
- end
-
- def channels
- return Spree::Channel.none if preferred_channel_ids.blank?
-
- promotion.store.channels.where(id: preferred_channel_ids)
- end
-
- def eligible?(order, _options = {})
- return false if preferred_channel_ids.empty?
- return true if preferred_channel_ids.map(&:to_s).include?(order.channel_id.to_s)
-
- eligibility_errors.add(:base, eligibility_error_message(:no_matching_channel))
- false
- end
- end
- end
- end
-end
+# Legacy constant path — removed in 6.1. Real class: Spree::PromotionRules::Channel.
+Spree::Promotion::Rules::Channel = Spree::PromotionRules::Channel
diff --git a/spree/core/app/models/spree/promotion/rules/country.rb b/spree/core/app/models/spree/promotion/rules/country.rb
index e2654e2e21..dc4a2a438b 100644
--- a/spree/core/app/models/spree/promotion/rules/country.rb
+++ b/spree/core/app/models/spree/promotion/rules/country.rb
@@ -1,63 +1,2 @@
-# A rule to limit a promotion based on shipment country. Stores an
-# array of ISO codes — countries are inherently identified by ISO
-# in the API. The legacy single `country_id` / `country_iso`
-# preferences still work; they fold into the multi-country list.
-module Spree
- class Promotion
- module Rules
- class Country < PromotionRule
- preference :country_isos, :array, default: [], parse_on_set: lambda { |values|
- normalize_id_preference.call(values).map(&:upcase)
- }
- preference :country_id, :integer # legacy single-country shortcut
- preference :country_iso, :string # legacy ISO-based shortcut
-
- def applicable?(promotable)
- promotable.is_a?(Spree::Order)
- end
-
- def countries
- isos = preferred_country_isos.presence || [preferred_country_iso].compact_blank
- return Spree::Country.none if isos.blank?
-
- Spree::Country.where(iso: isos.map { |s| s.to_s.upcase })
- end
-
- def eligible?(order, options = {})
- allowed_isos = eligible_country_isos(order)
- shipping_iso = options[:country_iso] || order.ship_address&.country_iso
-
- return true if allowed_isos.include?(shipping_iso)
-
- eligibility_errors.add(:base, eligibility_error_message(:wrong_country))
- false
- end
-
- # Effective list of eligible country ISOs, merging legacy
- # single-country preferences into the multi-country list.
- # Order-of-precedence: explicit ISO list > legacy single ISO
- # > legacy single ID > store default. Memoized per-instance —
- # eligibility checks fire repeatedly per cart change.
- def eligible_country_isos(order = nil)
- @eligible_country_isos ||= compute_eligible_country_isos(order)
- end
-
- private
-
- def compute_eligible_country_isos(order)
- return preferred_country_isos.map { |v| v.to_s.upcase } if preferred_country_isos.present?
- return [preferred_country_iso.to_s.upcase] if preferred_country_iso.present?
-
- if preferred_country_id.present?
- iso = Spree::Country.where(id: preferred_country_id).pick(:iso)
- return [iso.to_s.upcase] if iso.present?
- end
-
- return [] if order.nil?
-
- [order.store&.default_country&.iso, order.store&.default_market&.default_country&.iso].compact.map(&:upcase).uniq
- end
- end
- end
- end
-end
+# Legacy constant path — removed in 6.1. Real class: Spree::PromotionRules::Country.
+Spree::Promotion::Rules::Country = Spree::PromotionRules::Country
diff --git a/spree/core/app/models/spree/promotion/rules/currency.rb b/spree/core/app/models/spree/promotion/rules/currency.rb
index bb58652fab..12a64a643f 100644
--- a/spree/core/app/models/spree/promotion/rules/currency.rb
+++ b/spree/core/app/models/spree/promotion/rules/currency.rb
@@ -1,21 +1,2 @@
-# A rule to limit a promotion based on order currency.
-module Spree
- class Promotion
- module Rules
- class Currency < PromotionRule
- preference :currency, :string
-
- def applicable?(promotable)
- promotable.is_a?(Spree::Order)
- end
-
- def eligible?(order, options = {})
- return true if order.currency == preferred_currency
-
- eligibility_errors.add(:base, eligibility_error_message(:wrong_currency))
- false
- end
- end
- end
- end
-end
+# Legacy constant path — removed in 6.1. Real class: Spree::PromotionRules::Currency.
+Spree::Promotion::Rules::Currency = Spree::PromotionRules::Currency
diff --git a/spree/core/app/models/spree/promotion/rules/customer_group.rb b/spree/core/app/models/spree/promotion/rules/customer_group.rb
index b25cd191b1..a2c27706e6 100644
--- a/spree/core/app/models/spree/promotion/rules/customer_group.rb
+++ b/spree/core/app/models/spree/promotion/rules/customer_group.rb
@@ -1,31 +1,2 @@
-module Spree
- class Promotion
- module Rules
- class CustomerGroup < PromotionRule
- # Stored as raw IDs. Accepts prefixed IDs (`cg_…`) from API
- # callers and decodes them on write so eligibility checks can
- # compare against raw `customer_group_id` rows directly.
- preference :customer_group_ids, :array, default: [], parse_on_set: normalize_id_preference(klass: Spree::CustomerGroup)
-
- def applicable?(promotable)
- promotable.is_a?(Spree::Order)
- end
-
- def customer_groups
- return Spree::CustomerGroup.none if preferred_customer_group_ids.blank?
-
- Spree::CustomerGroup.where(id: preferred_customer_group_ids)
- end
-
- def eligible?(order, _options = {})
- return false unless order.user_id.present?
- return false if preferred_customer_group_ids.empty?
-
- user_customer_group_ids = Spree::CustomerGroupUser.where(user_id: order.user_id).pluck(:customer_group_id).map(&:to_s)
-
- (preferred_customer_group_ids.map(&:to_s) & user_customer_group_ids).any?
- end
- end
- end
- end
-end
+# Legacy constant path — removed in 6.1. Real class: Spree::PromotionRules::CustomerGroup.
+Spree::Promotion::Rules::CustomerGroup = Spree::PromotionRules::CustomerGroup
diff --git a/spree/core/app/models/spree/promotion/rules/first_order.rb b/spree/core/app/models/spree/promotion/rules/first_order.rb
index a0765bf4f7..099f804b74 100644
--- a/spree/core/app/models/spree/promotion/rules/first_order.rb
+++ b/spree/core/app/models/spree/promotion/rules/first_order.rb
@@ -1,44 +1,2 @@
-module Spree
- class Promotion
- module Rules
- class FirstOrder < PromotionRule
- attr_reader :user, :email, :store
-
- def applicable?(promotable)
- promotable.is_a?(Spree::Order)
- end
-
- def eligible?(order, options = {})
- @user = order.try(:user) || options[:user]
- @email = if options[:email].present?
- order.email = options[:email]
- order.email
- elsif order.email.present?
- order.email
- end
- @store = order.store
-
- if user || email
- if !completed_orders.blank? && completed_orders.first != order
- eligibility_errors.add(:base, eligibility_error_message(:not_first_order))
- end
- else
- eligibility_errors.add(:base, eligibility_error_message(:no_user_or_email_specified))
- end
-
- eligibility_errors.empty?
- end
-
- private
-
- def completed_orders
- user ? user.orders.for_store(store).complete : orders_by_email
- end
-
- def orders_by_email
- store.orders.where(email: email).complete
- end
- end
- end
- end
-end
+# Legacy constant path — removed in 6.1. Real class: Spree::PromotionRules::FirstOrder.
+Spree::Promotion::Rules::FirstOrder = Spree::PromotionRules::FirstOrder
diff --git a/spree/core/app/models/spree/promotion/rules/item_total.rb b/spree/core/app/models/spree/promotion/rules/item_total.rb
index 7537454a53..49be687de8 100644
--- a/spree/core/app/models/spree/promotion/rules/item_total.rb
+++ b/spree/core/app/models/spree/promotion/rules/item_total.rb
@@ -1,68 +1,2 @@
-# A rule to apply to an order greater than (or greater than or equal to)
-# a specific amount
-module Spree
- class Promotion
- module Rules
- class ItemTotal < PromotionRule
- preference :amount_min, :decimal, default: 100.00
- preference :operator_min, :string, default: '>'
- preference :amount_max, :decimal, default: nil, nullable: true
- preference :operator_max, :string, default: '<'
-
- OPERATORS_MIN = ['gt', 'gte']
- OPERATORS_MAX = ['lt', 'lte']
-
- def applicable?(promotable)
- promotable.is_a?(Spree::Order)
- end
-
- def eligible?(order, _options = {})
- item_total = order.item_total
-
- lower_limit_condition = item_total.send(preferred_operator_min == 'gte' ? :>= : :>, BigDecimal(preferred_amount_min.to_s))
-
- if preferred_amount_max.present?
- upper_limit_condition = item_total.send(preferred_operator_max == 'lte' ? :<= : :<, BigDecimal(preferred_amount_max.to_s))
- else
- upper_limit_condition = true
- end
-
- eligibility_errors.add(:base, ineligible_message_max(order)) unless upper_limit_condition
- eligibility_errors.add(:base, ineligible_message_min(order)) unless lower_limit_condition
-
- eligibility_errors.empty?
- end
-
- private
-
- def formatted_amount_min(order)
- Spree::Money.new(preferred_amount_min, currency: order.currency).to_s
- end
-
- def formatted_amount_max(order)
- if preferred_amount_max.present?
- Spree::Money.new(preferred_amount_max, currency: order.currency).to_s
- else
- Spree.t('no_maximum')
- end
- end
-
- def ineligible_message_max(order)
- if preferred_operator_max == 'lt'
- eligibility_error_message(:item_total_more_than_or_equal, amount: formatted_amount_max(order))
- else
- eligibility_error_message(:item_total_more_than, amount: formatted_amount_max(order))
- end
- end
-
- def ineligible_message_min(order)
- if preferred_operator_min == 'gte'
- eligibility_error_message(:item_total_less_than, amount: formatted_amount_min(order))
- else
- eligibility_error_message(:item_total_less_than_or_equal, amount: formatted_amount_min(order))
- end
- end
- end
- end
- end
-end
+# Legacy constant path — removed in 6.1. Real class: Spree::PromotionRules::ItemTotal.
+Spree::Promotion::Rules::ItemTotal = Spree::PromotionRules::ItemTotal
diff --git a/spree/core/app/models/spree/promotion/rules/market.rb b/spree/core/app/models/spree/promotion/rules/market.rb
index 06c2fe503d..42b3fecc45 100644
--- a/spree/core/app/models/spree/promotion/rules/market.rb
+++ b/spree/core/app/models/spree/promotion/rules/market.rb
@@ -1,37 +1,2 @@
-# A rule to limit a promotion based on the order's market.
-module Spree
- class Promotion
- module Rules
- class Market < PromotionRule
- # Stored as raw IDs. Accepts prefixed IDs (`mkt_…`) from API
- # callers and decodes them on write so eligibility checks compare
- # against the order's raw `market_id` directly. Scope confines the
- # existence check to the promotion's store so cross-store market
- # IDs can't sneak in.
- preference :market_ids, :array, default: [],
- parse_on_set: normalize_id_preference(
- klass: Spree::Market,
- scope: ->(rule) { rule.promotion&.store&.markets || Spree::Market.none }
- )
-
- def applicable?(promotable)
- promotable.is_a?(Spree::Order)
- end
-
- def markets
- return Spree::Market.none if preferred_market_ids.blank?
-
- promotion.store.markets.where(id: preferred_market_ids)
- end
-
- def eligible?(order, _options = {})
- return false if preferred_market_ids.empty?
- return true if preferred_market_ids.map(&:to_s).include?(order.market_id.to_s)
-
- eligibility_errors.add(:base, eligibility_error_message(:no_matching_market))
- false
- end
- end
- end
- end
-end
+# Legacy constant path — removed in 6.1. Real class: Spree::PromotionRules::Market.
+Spree::Promotion::Rules::Market = Spree::PromotionRules::Market
diff --git a/spree/core/app/models/spree/promotion/rules/one_use_per_user.rb b/spree/core/app/models/spree/promotion/rules/one_use_per_user.rb
index db9100d88c..d617beb154 100644
--- a/spree/core/app/models/spree/promotion/rules/one_use_per_user.rb
+++ b/spree/core/app/models/spree/promotion/rules/one_use_per_user.rb
@@ -1,23 +1,2 @@
-module Spree
- class Promotion
- module Rules
- class OneUsePerUser < PromotionRule
- def applicable?(promotable)
- promotable.is_a?(Spree::Order)
- end
-
- def eligible?(order, _options = {})
- if order.user.present?
- if promotion.used_by?(order.user, [order])
- eligibility_errors.add(:base, eligibility_error_message(:limit_once_per_user))
- end
- else
- eligibility_errors.add(:base, eligibility_error_message(:no_user_specified))
- end
-
- eligibility_errors.empty?
- end
- end
- end
- end
-end
+# Legacy constant path — removed in 6.1. Real class: Spree::PromotionRules::OneUsePerUser.
+Spree::Promotion::Rules::OneUsePerUser = Spree::PromotionRules::OneUsePerUser
diff --git a/spree/core/app/models/spree/promotion/rules/option_value.rb b/spree/core/app/models/spree/promotion/rules/option_value.rb
index d36bedcde8..f31098bfd6 100644
--- a/spree/core/app/models/spree/promotion/rules/option_value.rb
+++ b/spree/core/app/models/spree/promotion/rules/option_value.rb
@@ -1,38 +1,2 @@
-module Spree
- class Promotion
- module Rules
- class OptionValue < PromotionRule
- MATCH_POLICIES = %w(any)
- preference :match_policy, :string, default: MATCH_POLICIES.first
- preference :eligible_values, :array, default: [], parse_on_set: lambda { |values|
- values.flat_map { |v| v.to_s.split(',').compact_blank.map(&:strip) }
- }
-
- def applicable?(promotable)
- promotable.is_a?(Spree::Order)
- end
-
- def eligible?(promotable, _options = {})
- return false if eligible_option_value_variant_ids.empty?
-
- case preferred_match_policy
- when 'any'
- Spree::OptionValueVariant.where(id: eligible_option_value_variant_ids, variant_id: promotable.variant_ids).exists?
- end
- end
-
- def actionable?(line_item)
- return false if eligible_option_value_variant_ids.empty?
-
- Spree::OptionValueVariant.where(id: eligible_option_value_variant_ids, variant_id: line_item.variant_id).exists?
- end
-
- private
-
- def eligible_option_value_variant_ids
- @eligible_option_value_variant_ids ||= preferred_eligible_values.map(&:to_s)
- end
- end
- end
- end
-end
+# Legacy constant path — removed in 6.1. Real class: Spree::PromotionRules::OptionValue.
+Spree::Promotion::Rules::OptionValue = Spree::PromotionRules::OptionValue
diff --git a/spree/core/app/models/spree/promotion/rules/product.rb b/spree/core/app/models/spree/promotion/rules/product.rb
index 5f854828d1..f3fafe9f6e 100644
--- a/spree/core/app/models/spree/promotion/rules/product.rb
+++ b/spree/core/app/models/spree/promotion/rules/product.rb
@@ -1,116 +1,2 @@
-# A rule to limit a promotion based on products in the order.
-# Can require all or any of the products to be present.
-# Valid products either come from assigned product group or are assigned directly to the rule.
-module Spree
- class Promotion
- module Rules
- class Product < PromotionRule
- #
- # Associations
- #
- has_many :product_promotion_rules, class_name: 'Spree::ProductPromotionRule',
- foreign_key: :promotion_rule_id,
- dependent: :destroy
- has_many :products, through: :product_promotion_rules, class_name: 'Spree::Product'
-
- def self.additional_permitted_attributes
- [product_ids: []]
- end
-
- #
- # Preferences
- #
- MATCH_POLICIES = %w(any all none)
- preference :match_policy, :string, default: MATCH_POLICIES.first
-
- #
- # Attributes
- #
- attr_accessor :product_ids_to_add
-
- #
- # Callbacks
- #
- after_save :add_products
-
- # scope/association that is used to test eligibility
- def eligible_products
- products
- end
-
- def eligible_product_ids
- @eligible_product_ids ||= product_promotion_rules.pluck(:product_id)
- end
-
- def applicable?(promotable)
- promotable.is_a?(Spree::Order)
- end
-
- def eligible?(order, _options = {})
- return true if eligible_product_ids.empty?
-
- if preferred_match_policy == 'all'
- unless eligible_product_ids.all? { |p| order.product_ids.include?(p) }
- eligibility_errors.add(:base, eligibility_error_message(:missing_product))
- end
- elsif preferred_match_policy == 'any'
- unless order.product_ids.any? { |p| eligible_product_ids.include?(p) }
- eligibility_errors.add(:base, eligibility_error_message(:no_applicable_products))
- end
- else
- unless order.product_ids.none? { |p| eligible_product_ids.include?(p) }
- eligibility_errors.add(:base, eligibility_error_message(:has_excluded_product))
- end
- end
-
- eligibility_errors.empty?
- end
-
- def actionable?(line_item)
- case preferred_match_policy
- when 'any', 'all'
- eligible_product_ids.include? line_item.variant.product_id
- when 'none'
- eligible_product_ids.exclude? line_item.variant.product_id
- else
- raise "unexpected match policy: #{preferred_match_policy.inspect}"
- end
- end
-
- def product_ids_string
- ActiveSupport::Deprecation.warn(
- 'Please use `product_ids=` instead.'
- )
- product_ids.join(',')
- end
-
- def product_ids_string=(s)
- ActiveSupport::Deprecation.warn(
- 'Please use `product_ids=` instead.'
- )
- self.product_ids = s
- end
-
- private
-
- def add_products
- return if product_ids_to_add.nil?
-
- product_promotion_rules.delete_all
-
- if product_ids_to_add.any?
- Spree::ProductPromotionRule.insert_all(
- product_ids_to_add.map { |product_id| { product_id: product_id, promotion_rule_id: id } }
- )
- end
-
- # Invalidate cache after bulk operations
- touch
-
- # Clear memoized values
- @eligible_product_ids = nil
- end
- end
- end
- end
-end
+# Legacy constant path — removed in 6.1. Real class: Spree::PromotionRules::Product.
+Spree::Promotion::Rules::Product = Spree::PromotionRules::Product
diff --git a/spree/core/app/models/spree/promotion/rules/taxon.rb b/spree/core/app/models/spree/promotion/rules/taxon.rb
index ed7bff9cad..2095b1ffec 100644
--- a/spree/core/app/models/spree/promotion/rules/taxon.rb
+++ b/spree/core/app/models/spree/promotion/rules/taxon.rb
@@ -1,16 +1,2 @@
-# frozen_string_literal: true
-
-module Spree
- class Promotion
- module Rules
- # Deprecation alias for Spree::Promotion::Rules::Category, renamed from
- # Spree::Promotion::Rules::Taxon in 6.0. A true constant alias, so old STI type
- # strings (`'Spree::Promotion::Rules::Taxon'`) still instantiate correctly until
- # the Phase 4 migration rewrites them. The warning fires when this file loads.
- # Removed in 6.1.
- Taxon = Category
-
- Spree::Deprecation.warn('Spree::Promotion::Rules::Taxon is deprecated and will be removed in Spree 6.1. Use Spree::Promotion::Rules::Category instead.')
- end
- end
-end
+# Legacy constant path — removed in 6.1. Real class: Spree::PromotionRules::Taxon.
+Spree::Promotion::Rules::Taxon = Spree::PromotionRules::Taxon
diff --git a/spree/core/app/models/spree/promotion/rules/user.rb b/spree/core/app/models/spree/promotion/rules/user.rb
index 87e569d349..05c1a0d3f2 100644
--- a/spree/core/app/models/spree/promotion/rules/user.rb
+++ b/spree/core/app/models/spree/promotion/rules/user.rb
@@ -1,94 +1,2 @@
-module Spree
- class Promotion
- module Rules
- class User < PromotionRule
- #
- # Associations
- #
- has_many :promotion_rule_users, class_name: 'Spree::PromotionRuleUser',
- foreign_key: :promotion_rule_id,
- dependent: :destroy
- has_many :users, through: :promotion_rule_users, class_name: "::#{Spree.user_class}"
-
- # Customers, not admin users — the rule keys off `Spree::Order#user_id`.
- # The data layer keeps the `users` association (legacy column name);
- # the API exposes the same set as `customer_ids`.
- def self.additional_permitted_attributes
- [customer_ids: []]
- end
-
- # Wire-format shorthand is `customer` (the model is still `User`
- # pre-6.0 rename, see docs/plans/6.0-platform-auth.md).
- def self.api_type
- 'customer'
- end
-
- def customer_ids
- user_ids
- end
-
- def customer_ids=(ids)
- self.user_ids = ids
- end
-
- #
- # Attributes
- #
- attr_accessor :user_ids_to_add
-
- #
- # Callbacks
- #
- after_save :add_users
-
- def applicable?(promotable)
- promotable.is_a?(Spree::Order)
- end
-
- def eligible_user_ids
- @eligible_user_ids ||= promotion_rule_users.pluck(:user_id)
- end
-
- def eligible?(order, _options = {})
- eligible_user_ids.include?(order.user_id)
- end
-
- def user_ids_string
- ActiveSupport::Deprecation.warn(
- 'Spree::Promotion::Rules::User#user_ids_string is deprecated and will be removed in Spree 5.5. ' \
- 'Please use `user_ids` instead.'
- )
- user_ids.join(',')
- end
-
- def user_ids_string=(s)
- ActiveSupport::Deprecation.warn(
- 'Spree::Promotion::Rules::User#user_ids_string= is deprecated and will be removed in Spree 5.5. ' \
- 'Please use `user_ids=` instead.'
- )
- self.user_ids = s
- end
-
- private
-
- def add_users
- return if user_ids_to_add.nil?
-
- promotion_rule_users.delete_all
-
- if user_ids_to_add.any?
- Spree::PromotionRuleUser.insert_all(
- user_ids_to_add.map { |user_id| { user_id: user_id, promotion_rule_id: id } }
- )
- end
-
- # Invalidate cache after bulk operations
- touch
-
- # Clear memoized values
- @eligible_user_ids = nil
- end
- end
- end
- end
-end
+# Legacy constant path — removed in 6.1. Real class: Spree::PromotionRules::User.
+Spree::Promotion::Rules::User = Spree::PromotionRules::User
diff --git a/spree/core/app/models/spree/promotion/rules/user_logged_in.rb b/spree/core/app/models/spree/promotion/rules/user_logged_in.rb
index 4e028adb1c..e72e8e0c3a 100644
--- a/spree/core/app/models/spree/promotion/rules/user_logged_in.rb
+++ b/spree/core/app/models/spree/promotion/rules/user_logged_in.rb
@@ -1,24 +1,2 @@
-module Spree
- class Promotion
- module Rules
- class UserLoggedIn < PromotionRule
- # Wire-format shorthand is `customer_logged_in` (the model is still
- # `UserLoggedIn` pre-6.0 rename, see docs/plans/6.0-platform-auth.md).
- def self.api_type
- 'customer_logged_in'
- end
-
- def applicable?(promotable)
- promotable.is_a?(Spree::Order)
- end
-
- def eligible?(order, _options = {})
- unless order.user.present?
- eligibility_errors.add(:base, eligibility_error_message(:no_user_specified))
- end
- eligibility_errors.empty?
- end
- end
- end
- end
-end
+# Legacy constant path — removed in 6.1. Real class: Spree::PromotionRules::UserLoggedIn.
+Spree::Promotion::Rules::UserLoggedIn = Spree::PromotionRules::UserLoggedIn
diff --git a/spree/core/app/models/spree/promotion_action.rb b/spree/core/app/models/spree/promotion_action.rb
index e00fe9bd68..9ac9ddb3e8 100644
--- a/spree/core/app/models/spree/promotion_action.rb
+++ b/spree/core/app/models/spree/promotion_action.rb
@@ -29,11 +29,45 @@ module Spree
raise 'perform should be implemented in a sub-class of PromotionAction'
end
+ # Which competition group this action's discounts belong to
+ # (+:line_item+, +:fulfillment+, +:order+), or nil for actions that don't
+ # write Discount rows. Drives Spree::Adjusters::Promotion.
+ #
+ # @return [Symbol, nil]
+ def discount_scope
+ nil
+ end
+
+ # Whether this action's Discount rows persist at zero amount (only
+ # FreeShipping — row existence is the signal).
+ def persist_at_zero?
+ false
+ end
+
# Returns true if the promotion action is a free shipping action
#
# @return [Boolean]
def free_shipping?
- type == 'Spree::Promotion::Actions::FreeShipping'
+ type.to_s.demodulize == 'FreeShipping'
+ end
+
+ # STI type names for a discount scope, covering both the 6.0 names and
+ # the legacy names still present in the type column until the 6.1 data
+ # migration.
+ #
+ # @param scope [Symbol] :line_item, :fulfillment or :order
+ # @return [Array<String>]
+ def self.types_for_discount_scope(scope)
+ case scope
+ when :line_item
+ %w[Spree::PromotionActions::CreateItemDiscounts Spree::Promotion::Actions::CreateItemAdjustments]
+ when :fulfillment
+ %w[Spree::PromotionActions::FreeShipping Spree::Promotion::Actions::FreeShipping]
+ when :order
+ %w[Spree::PromotionActions::CreateAdjustment Spree::Promotion::Actions::CreateAdjustment]
+ else
+ []
+ end
end
def self.human_name
@@ -56,6 +90,20 @@ module Spree
protected
+ # Shared perform for discount-writing actions: report whether this action
+ # currently yields a candidate (that connects the promotion to the order,
+ # so it keeps competing on later recalculations even if it loses now),
+ # then settle rows immediately.
+ def apply_via_adjuster(options)
+ order = options[:order]
+ promotion = options[:promotion] || self.promotion
+
+ adjuster = Spree::Adjusters::Promotion.new(order, extra_promotions: [promotion])
+ produced = adjuster.candidate_for?(self)
+ adjuster.update if produced
+ produced
+ end
+
def label
Spree.t(:promotion_label, name: promotion.name)
end
diff --git a/spree/core/app/models/spree/promotion_action_line_item.rb b/spree/core/app/models/spree/promotion_action_line_item.rb
index 69ba28a003..911cff4184 100644
--- a/spree/core/app/models/spree/promotion_action_line_item.rb
+++ b/spree/core/app/models/spree/promotion_action_line_item.rb
@@ -1,6 +1,6 @@
module Spree
class PromotionActionLineItem < Spree.base_class
- belongs_to :promotion_action, class_name: 'Spree::Promotion::Actions::CreateLineItems'
+ belongs_to :promotion_action, class_name: 'Spree::PromotionActions::CreateLineItems'
belongs_to :variant, class_name: 'Spree::Variant'
validates :promotion_action, :variant, :quantity, presence: true
diff --git a/spree/core/app/models/spree/promotion_actions/create_adjustment.rb b/spree/core/app/models/spree/promotion_actions/create_adjustment.rb
new file mode 100644
index 0000000000..b6409b8506
--- /dev/null
+++ b/spree/core/app/models/spree/promotion_actions/create_adjustment.rb
@@ -0,0 +1,32 @@
+module Spree
+ module PromotionActions
+ # A whole-order discount. The winning order-level amount is distributed
+ # proportionally across line items at application time (largest-remainder
+ # over each line's remaining discounted base) — no order-attached rows.
+ class CreateAdjustment < PromotionAction
+ include Spree::CalculatedAdjustments
+
+ before_validation -> { self.calculator ||= Calculator::FlatPercentItemTotal.new }
+
+ def self.additional_permitted_attributes
+ [calculator: [:type, { preferences: {} }]]
+ end
+
+ def discount_scope
+ :order
+ end
+
+ def perform(options = {})
+ apply_via_adjuster(options)
+ end
+
+ def compute_amount(order)
+ [order_total(order), compute(order)].min * -1
+ end
+
+ def order_total(order)
+ order.item_total + order.ship_total - order.shipping_discount
+ end
+ end
+ end
+end
diff --git a/spree/core/app/models/spree/promotion_actions/create_item_discounts.rb b/spree/core/app/models/spree/promotion_actions/create_item_discounts.rb
new file mode 100644
index 0000000000..73c2f71b6c
--- /dev/null
+++ b/spree/core/app/models/spree/promotion_actions/create_item_discounts.rb
@@ -0,0 +1,32 @@
+module Spree
+ module PromotionActions
+ # Writes per-line-item promotion Discount rows (winner-only competition
+ # handled by Spree::Adjusters::Promotion on every recalculation).
+ class CreateItemDiscounts < PromotionAction
+ include Spree::CalculatedAdjustments
+
+ before_validation -> { self.calculator ||= Calculator::PercentOnLineItem.new }
+
+ def self.additional_permitted_attributes
+ [calculator: [:type, { preferences: {} }]]
+ end
+
+ def discount_scope
+ :line_item
+ end
+
+ def perform(options = {})
+ apply_via_adjuster(options)
+ end
+
+ # Negative-total protection is the adjuster's job: every discount row is
+ # clamped against its line's remaining discounted base, so the order net
+ # can never go below zero.
+ def compute_amount(line_item)
+ return 0 unless promotion.line_item_actionable?(line_item.order, line_item)
+
+ [line_item.amount, compute(line_item)].min * -1
+ end
+ end
+ end
+end
diff --git a/spree/core/app/models/spree/promotion_actions/create_line_items.rb b/spree/core/app/models/spree/promotion_actions/create_line_items.rb
new file mode 100644
index 0000000000..70d3b1f1f4
--- /dev/null
+++ b/spree/core/app/models/spree/promotion_actions/create_line_items.rb
@@ -0,0 +1,136 @@
+module Spree
+ module PromotionActions
+ class CreateLineItems < Spree::PromotionAction
+ has_many :promotion_action_line_items, foreign_key: :promotion_action_id, dependent: :destroy
+
+ attribute :promotion_action_line_items_attributes
+
+ after_save :handle_promotion_action_line_items
+
+ def self.additional_permitted_attributes
+ [line_items: [:variant_id, :quantity]]
+ end
+
+ # API v3 flat alias for `promotion_action_line_items_attributes`.
+ # Accepts an array of `{ variant_id:, quantity: }` rows; the list
+ # is the *desired* set, so anything missing on save is removed.
+ def line_items=(rows)
+ self.promotion_action_line_items_attributes = rows
+ end
+
+ delegate :eligible?, to: :promotion
+
+ # Adds a line item to the Order if the promotion is eligible
+ #
+ # This doesn't play right with Add to Cart events because at the moment
+ # the item was added to cart the promo may not be eligible. However it
+ # might become eligible as the order gets updated.
+ #
+ # e.g.
+ # - A promo adds a line item to cart if order total greater then $30
+ # - Customer add 1 item of $10 to cart
+ # - This action shouldn't perform because the order is not eligible
+ # - Customer increases item quantity to 5 (order total goes to $50)
+ # - Now the order is eligible for the promo and the action should perform
+ #
+ # Another complication is when the same line item created by the promo
+ # is also added to cart on a separate action.
+ #
+ # e.g.
+ # - Promo adds 1 item A to cart if order total greater then $30
+ # - Customer add 2 items B to cart, current order total is $40
+ # - This action performs adding item A to cart since order is eligible
+ # - Customer changes his mind and updates item B quantity to 1
+ # - At this point order is no longer eligible and one might expect
+ # that item A should be removed
+ #
+ # It doesn't remove items from the order here because there's no way
+ # it can know whether that item was added via this promo action or if
+ # it was manually populated somewhere else. In that case the item
+ # needs to be manually removed from the order by the customer
+ def perform(options = {})
+ order = options[:order]
+ return unless eligible? order
+
+ action_taken = false
+ promotion_action_line_items.each do |item|
+ current_quantity = order.quantity_of(item.variant)
+ next unless current_quantity < item.quantity && item_available?(item)
+
+ line_item = Spree.cart_add_item_service.call(order: order,
+ variant: item.variant,
+ quantity: item.quantity - current_quantity).value
+ action_taken = true if line_item.try(:valid?)
+ end
+ action_taken
+ end
+
+ # Called by promotion handler when a promotion is removed
+ # This will find any line item matching the ones defined in the PromotionAction
+ # and remove the same quantity as was added by the PromotionAction.
+ # Should help to prevent some of cases listed above the #perform method
+ def revert(options = {})
+ order = options[:order]
+ return if eligible?(order)
+
+ action_taken = false
+ promotion_action_line_items.each do |item|
+ line_item = order.find_line_item_by_variant(item.variant)
+ next unless line_item.present?
+
+ Spree.cart_remove_item_service.call(order: order,
+ variant: item.variant,
+ quantity: (item.quantity || 1))
+ action_taken = true
+ end
+
+ action_taken
+ end
+
+ # Checks that there's enough stock to add the line item to the order
+ def item_available?(item)
+ quantifier = Spree::Stock::Quantifier.new(item.variant)
+ quantifier.can_supply? item.quantity
+ end
+
+ private
+
+ # Handles the creation, updating, and pruning of promotion action
+ # line items. The submitted list is the *desired* set — variants
+ # not present are deleted, ones that are get upserted. Accepts
+ # both the legacy Rails admin hash shape (`{ "0" => attrs }`) and
+ # a flat array from the API. Variant IDs may be raw or prefixed.
+ def handle_promotion_action_line_items
+ return unless promotion_action_line_items_attributes
+
+ rows = promotion_action_line_items_attributes.is_a?(Hash) ? promotion_action_line_items_attributes.values : promotion_action_line_items_attributes
+ rows = rows.map { |row| row.respond_to?(:to_h) ? row.to_h.with_indifferent_access : row.with_indifferent_access }
+
+ rows = rows.map do |row|
+ variant_id = row['variant_id']
+ variant_id = Spree::Variant.find_by_param(variant_id)&.id if Spree::PrefixedId.prefixed_id?(variant_id)
+ row.merge('variant_id' => variant_id)
+ end
+
+ desired_variant_ids = rows.map { |row| row['variant_id'] }.compact
+ promotion_action_line_items.where.not(variant_id: desired_variant_ids).delete_all
+
+ return if rows.empty?
+
+ opts = {}
+ opts[:unique_by] = [:promotion_action_id, :variant_id] unless mysql_adapter?
+
+ promotion_action_line_items.upsert_all(
+ rows.map do |params|
+ {
+ variant_id: params['variant_id'],
+ quantity: params['quantity'],
+ promotion_action_id: id
+ }
+ end,
+ **opts
+ )
+ end
+ end
+ end
+end
diff --git a/spree/core/app/models/spree/promotion_actions/free_shipping.rb b/spree/core/app/models/spree/promotion_actions/free_shipping.rb
new file mode 100644
index 0000000000..a972835626
--- /dev/null
+++ b/spree/core/app/models/spree/promotion_actions/free_shipping.rb
@@ -0,0 +1,24 @@
+module Spree
+ module PromotionActions
+ # Writes a fulfillment-attached Discount covering the fulfillment cost.
+ # The row persists even at zero amount — Order#has_free_shipping? tests
+ # row existence.
+ class FreeShipping < Spree::PromotionAction
+ def discount_scope
+ :fulfillment
+ end
+
+ def persist_at_zero?
+ true
+ end
+
+ def perform(options = {})
+ apply_via_adjuster(options)
+ end
+
+ def compute_amount(fulfillment)
+ fulfillment.cost * -1
+ end
+ end
+ end
+end
diff --git a/spree/core/app/models/spree/promotion_handler/coupon.rb b/spree/core/app/models/spree/promotion_handler/coupon.rb
index c8887d94f1..9c3fb0c337 100644
--- a/spree/core/app/models/spree/promotion_handler/coupon.rb
+++ b/spree/core/app/models/spree/promotion_handler/coupon.rb
@@ -101,13 +101,13 @@ module Spree
).with_coupon_code(order.coupon_code)
end
- # Returns the amount of adjustments for the promotion
+ # Returns the amount of discounts for the promotion
#
# @return [Numeric]
def adjustments_amount
@adjustments_amount ||=
- @order.all_adjustments.promotion.eligible.
- where(source: promotion&.actions).
+ @order.discounts.promotion.
+ where(promotion_action_id: promotion&.actions&.ids).
sum(:amount)
end
@@ -121,13 +121,12 @@ module Spree
private
def remove_promotion_adjustments(promotion)
- promotion_actions_ids = promotion.actions.pluck(:id)
- order.all_adjustments.where(source_id: promotion_actions_ids,
- source_type: 'Spree::PromotionAction').destroy_all
+ order.discounts.where(promotion_action_id: promotion.actions.pluck(:id)).destroy_all
end
def remove_promotion_line_items(promotion)
- create_line_item_actions_ids = promotion.actions.where(type: 'Spree::Promotion::Actions::CreateLineItems').pluck(:id)
+ create_line_item_actions_ids = promotion.actions.
+ where(type: %w[Spree::PromotionActions::CreateLineItems Spree::Promotion::Actions::CreateLineItems]).pluck(:id)
Spree::PromotionActionLineItem.where(promotion_action: create_line_item_actions_ids).find_each do |item|
line_item = order.find_line_item_by_variant(item.variant)
@@ -175,16 +174,16 @@ module Spree
def determine_promotion_application_result
coupon_code = order.coupon_code.downcase
- # Check for applied adjustments.
- discount = order.all_adjustments.promotion.eligible.detect do |p|
- p.source.promotion.code.try(:downcase) == coupon_code ||
- Spree::CouponCode.unused.where(promotion_id: p.source.promotion_id, code: coupon_code).exists?
+ # Check for applied discounts.
+ discount = order.discounts.promotion.includes(:promotion).detect do |row|
+ row.promotion&.code.try(:downcase) == coupon_code ||
+ Spree::CouponCode.unused.where(promotion_id: row.promotion_id, code: coupon_code).exists?
end
# Check for applied line items.
created_line_items = promotion.actions.detect do |a|
Object.const_get(a.type).ancestors.include?(
- Spree::Promotion::Actions::CreateLineItems
+ Spree::PromotionActions::CreateLineItems
)
end
@@ -209,7 +208,7 @@ module Spree
end
def handle_coupon_code(discount, coupon_code)
- Spree::CouponCode.unused.find_by(promotion_id: discount.source.promotion_id, code: coupon_code)&.apply_order!(order)
+ Spree::CouponCode.unused.find_by(promotion_id: discount.promotion_id, code: coupon_code)&.apply_order!(order)
end
# Whether the coupon handler should also handle gift card codes.
diff --git a/spree/core/app/models/spree/promotion_handler/free_shipping.rb b/spree/core/app/models/spree/promotion_handler/free_shipping.rb
index 200ebba2a0..4d561542e2 100644
--- a/spree/core/app/models/spree/promotion_handler/free_shipping.rb
+++ b/spree/core/app/models/spree/promotion_handler/free_shipping.rb
@@ -23,7 +23,7 @@ module Spree
def promotions
store.promotions.active.joins(:promotion_actions).
- where(Spree::PromotionAction.table_name => { type: 'Spree::Promotion::Actions::FreeShipping' }, path: nil).distinct
+ where(Spree::PromotionAction.table_name => { type: Spree::PromotionAction.types_for_discount_scope(:fulfillment) }, path: nil).distinct
end
end
end
diff --git a/spree/core/app/models/spree/promotion_rule_category.rb b/spree/core/app/models/spree/promotion_rule_category.rb
index b50e0b48ef..3d734bb8f6 100644
--- a/spree/core/app/models/spree/promotion_rule_category.rb
+++ b/spree/core/app/models/spree/promotion_rule_category.rb
@@ -1,5 +1,5 @@
module Spree
- # Join model between a Spree::Promotion::Rules::Category rule and a
+ # Join model between a Spree::PromotionRules::Category rule and a
# Spree::Category. Renamed from Spree::PromotionRuleTaxon in 6.0 (alias kept for
# one release).
class PromotionRuleCategory < Spree.base_class
diff --git a/spree/core/app/models/spree/promotion_rules/category.rb b/spree/core/app/models/spree/promotion_rules/category.rb
new file mode 100644
index 0000000000..0b03cc7811
--- /dev/null
+++ b/spree/core/app/models/spree/promotion_rules/category.rb
@@ -0,0 +1,173 @@
+module Spree
+ module PromotionRules
+ # Promotion rule matching an order against a set of Spree::Category records.
+ # Renamed from Spree::Promotion::Rules::Taxon in 6.0 (alias kept for one
+ # release). Existing spree_promotion_rules.type strings are backfilled by the
+ # Phase 4 data migration; the alias keeps old rows resolving until then.
+ class Category < Spree::PromotionRule
+ #
+ # Associations
+ #
+ has_many :promotion_rule_categories, class_name: 'Spree::PromotionRuleCategory',
+ foreign_key: 'promotion_rule_id',
+ dependent: :destroy
+ has_many :categories, through: :promotion_rule_categories, class_name: 'Spree::Category', source: :category
+
+ def self.additional_permitted_attributes
+ [category_ids: []]
+ end
+
+ # Wire-format shorthand is `category`. `key` (instance) cascades through `api_type`.
+ def self.api_type
+ 'category'
+ end
+
+ # Decode prefixed IDs before delegating to the generated setter (direct
+ # calls bypass PrefixedId's assign_attributes auto-resolver).
+ def category_ids=(ids)
+ super(Array(ids).map do |id|
+ Spree::PrefixedId.prefixed_id?(id) ? Spree::Category.find_by_param!(id).id : id
+ end)
+ end
+
+ #
+ # Preferences
+ #
+ MATCH_POLICIES = %w(any all)
+ preference :match_policy, :string, default: MATCH_POLICIES.first
+
+ #
+ # Attributes
+ #
+ attr_accessor :category_ids_to_add
+
+ #
+ # Callbacks
+ #
+ after_save :add_categories
+
+ def applicable?(promotable)
+ promotable.is_a?(Spree::Order)
+ end
+
+ def eligible_category_ids
+ @eligible_category_ids ||= promotion_rule_categories.pluck(:category_id)
+ end
+
+ def eligible?(order, _options = {})
+ return true if eligible_category_ids.empty?
+
+ order_category_ids_with_ancestors = category_ids_in_order_including_ancestors(order)
+
+ if preferred_match_policy == 'all'
+ unless eligible_category_ids.all? { |id| order_category_ids_with_ancestors.include?(id) }
+ eligibility_errors.add(:base, eligibility_error_message(:missing_taxon))
+ end
+ else
+ unless eligible_category_ids.any? { |id| order_category_ids_with_ancestors.include?(id) }
+ eligibility_errors.add(:base, eligibility_error_message(:no_matching_taxons))
+ end
+ end
+
+ eligibility_errors.empty?
+ end
+
+ def actionable?(line_item)
+ Spree::ProductCategory.where(category_id: eligible_category_ids_including_children, product_id: line_item.product_id).exists?
+ end
+
+ #
+ # Deprecated aliases (removed in 6.1)
+ #
+ # @deprecated Use #categories.
+ def taxons
+ Spree::Deprecation.warn('Spree::PromotionRules::Category#taxons is deprecated and will be removed in Spree 6.1. Use #categories instead.')
+ categories
+ end
+
+ # @deprecated Use #categories=.
+ def taxons=(value)
+ Spree::Deprecation.warn('Spree::PromotionRules::Category#taxons= is deprecated and will be removed in Spree 6.1. Use #categories= instead.')
+ self.categories = value
+ end
+
+ # @deprecated Use #category_ids.
+ def taxon_ids
+ Spree::Deprecation.warn('Spree::PromotionRules::Category#taxon_ids is deprecated and will be removed in Spree 6.1. Use #category_ids instead.')
+ category_ids
+ end
+
+ # @deprecated Use #category_ids=.
+ def taxon_ids=(ids)
+ Spree::Deprecation.warn('Spree::PromotionRules::Category#taxon_ids= is deprecated and will be removed in Spree 6.1. Use #category_ids= instead.')
+ self.category_ids = ids
+ end
+
+ # @deprecated Use #eligible_category_ids.
+ def eligible_taxon_ids
+ Spree::Deprecation.warn('Spree::PromotionRules::Category#eligible_taxon_ids is deprecated and will be removed in Spree 6.1. Use #eligible_category_ids instead.')
+ eligible_category_ids
+ end
+
+ # @deprecated Use #category_ids_to_add.
+ def taxon_ids_to_add
+ Spree::Deprecation.warn('Spree::PromotionRules::Category#taxon_ids_to_add is deprecated and will be removed in Spree 6.1. Use #category_ids_to_add instead.')
+ category_ids_to_add
+ end
+
+ def taxon_ids_to_add=(ids)
+ Spree::Deprecation.warn('Spree::PromotionRules::Category#taxon_ids_to_add= is deprecated and will be removed in Spree 6.1. Use #category_ids_to_add= instead.')
+ self.category_ids_to_add = ids
+ end
+
+ def taxon_ids_string
+ Spree::Deprecation.warn('Spree::PromotionRules::Category#taxon_ids_string is deprecated and will be removed in Spree 6.1. Use #category_ids instead.')
+ categories.pluck(:id).join(',')
+ end
+
+ def taxon_ids_string=(s)
+ Spree::Deprecation.warn('Spree::PromotionRules::Category#taxon_ids_string= is deprecated and will be removed in Spree 6.1. Use #category_ids= instead.')
+ ids = s.to_s.split(',').map(&:strip)
+ self.categories = Spree::Category.for_stores(stores).find(ids)
+ end
+
+ private
+
+ # IDs of categories in rule including all their children
+ def eligible_category_ids_including_children
+ @eligible_category_ids_including_children ||= begin
+ return [] if eligible_category_ids.empty?
+
+ Spree::Category.where(id: eligible_category_ids).flat_map(&:cached_self_and_descendants_ids).uniq
+ end
+ end
+
+ # IDs of categories in order that match rule categories (or their children), plus all ancestors
+ def category_ids_in_order_including_ancestors(order)
+ # Get category IDs from order products that are within rule categories or their children
+ order_category_ids = Spree::ProductCategory.where(product_id: order.product_ids, category_id: eligible_category_ids_including_children).pluck(:category_id).uniq
+
+ return [] if order_category_ids.empty?
+
+ # Get those categories plus all their ancestors
+ Spree::Category.where(id: order_category_ids).flat_map { |category| category.self_and_ancestors.ids }.uniq
+ end
+
+ def add_categories
+ return if category_ids_to_add.nil?
+
+ promotion_rule_categories.delete_all
+
+ if category_ids_to_add.any?
+ Spree::PromotionRuleCategory.insert_all(
+ category_ids_to_add.map { |category_id| { category_id: category_id, promotion_rule_id: id } }
+ )
+ end
+
+ # Clear memoized values
+ @eligible_category_ids = nil
+ @eligible_category_ids_including_children = nil
+ end
+ end
+ end
+end
diff --git a/spree/core/app/models/spree/promotion_rules/channel.rb b/spree/core/app/models/spree/promotion_rules/channel.rb
new file mode 100644
index 0000000000..4b9c80725a
--- /dev/null
+++ b/spree/core/app/models/spree/promotion_rules/channel.rb
@@ -0,0 +1,35 @@
+# A rule to limit a promotion based on the order's channel.
+module Spree
+ module PromotionRules
+ class Channel < Spree::PromotionRule
+ # Stored as raw IDs. Accepts prefixed IDs (`ch_…`) from API
+ # callers and decodes them on write so eligibility checks compare
+ # against the order's raw `channel_id` directly. Scope confines the
+ # existence check to the promotion's store so cross-store channel
+ # IDs can't sneak in.
+ preference :channel_ids, :array, default: [],
+ parse_on_set: normalize_id_preference(
+ klass: Spree::Channel,
+ scope: ->(rule) { rule.promotion&.store&.channels || Spree::Channel.none }
+ )
+
+ def applicable?(promotable)
+ promotable.is_a?(Spree::Order)
+ end
+
+ def channels
+ return Spree::Channel.none if preferred_channel_ids.blank?
+
+ promotion.store.channels.where(id: preferred_channel_ids)
+ end
+
+ def eligible?(order, _options = {})
+ return false if preferred_channel_ids.empty?
+ return true if preferred_channel_ids.map(&:to_s).include?(order.channel_id.to_s)
+
+ eligibility_errors.add(:base, eligibility_error_message(:no_matching_channel))
+ false
+ end
+ end
+ end
+end
diff --git a/spree/core/app/models/spree/promotion_rules/country.rb b/spree/core/app/models/spree/promotion_rules/country.rb
new file mode 100644
index 0000000000..69c7010459
--- /dev/null
+++ b/spree/core/app/models/spree/promotion_rules/country.rb
@@ -0,0 +1,61 @@
+# A rule to limit a promotion based on shipment country. Stores an
+# array of ISO codes — countries are inherently identified by ISO
+# in the API. The legacy single `country_id` / `country_iso`
+# preferences still work; they fold into the multi-country list.
+module Spree
+ module PromotionRules
+ class Country < Spree::PromotionRule
+ preference :country_isos, :array, default: [], parse_on_set: lambda { |values|
+ normalize_id_preference.call(values).map(&:upcase)
+ }
+ preference :country_id, :integer # legacy single-country shortcut
+ preference :country_iso, :string # legacy ISO-based shortcut
+
+ def applicable?(promotable)
+ promotable.is_a?(Spree::Order)
+ end
+
+ def countries
+ isos = preferred_country_isos.presence || [preferred_country_iso].compact_blank
+ return Spree::Country.none if isos.blank?
+
+ Spree::Country.where(iso: isos.map { |s| s.to_s.upcase })
+ end
+
+ def eligible?(order, options = {})
+ allowed_isos = eligible_country_isos(order)
+ shipping_iso = options[:country_iso] || order.ship_address&.country_iso
+
+ return true if allowed_isos.include?(shipping_iso)
+
+ eligibility_errors.add(:base, eligibility_error_message(:wrong_country))
+ false
+ end
+
+ # Effective list of eligible country ISOs, merging legacy
+ # single-country preferences into the multi-country list.
+ # Order-of-precedence: explicit ISO list > legacy single ISO
+ # > legacy single ID > store default. Memoized per-instance —
+ # eligibility checks fire repeatedly per cart change.
+ def eligible_country_isos(order = nil)
+ @eligible_country_isos ||= compute_eligible_country_isos(order)
+ end
+
+ private
+
+ def compute_eligible_country_isos(order)
+ return preferred_country_isos.map { |v| v.to_s.upcase } if preferred_country_isos.present?
+ return [preferred_country_iso.to_s.upcase] if preferred_country_iso.present?
+
+ if preferred_country_id.present?
+ iso = Spree::Country.where(id: preferred_country_id).pick(:iso)
+ return [iso.to_s.upcase] if iso.present?
+ end
+
+ return [] if order.nil?
+
+ [order.store&.default_country&.iso, order.store&.default_market&.default_country&.iso].compact.map(&:upcase).uniq
+ end
+ end
+ end
+end
diff --git a/spree/core/app/models/spree/promotion_rules/currency.rb b/spree/core/app/models/spree/promotion_rules/currency.rb
new file mode 100644
index 0000000000..bf0aef19f2
--- /dev/null
+++ b/spree/core/app/models/spree/promotion_rules/currency.rb
@@ -0,0 +1,19 @@
+# A rule to limit a promotion based on order currency.
+module Spree
+ module PromotionRules
+ class Currency < Spree::PromotionRule
+ preference :currency, :string
+
+ def applicable?(promotable)
+ promotable.is_a?(Spree::Order)
+ end
+
+ def eligible?(order, options = {})
+ return true if order.currency == preferred_currency
+
+ eligibility_errors.add(:base, eligibility_error_message(:wrong_currency))
+ false
+ end
+ end
+ end
+end
diff --git a/spree/core/app/models/spree/promotion_rules/customer_group.rb b/spree/core/app/models/spree/promotion_rules/customer_group.rb
new file mode 100644
index 0000000000..7a1f604318
--- /dev/null
+++ b/spree/core/app/models/spree/promotion_rules/customer_group.rb
@@ -0,0 +1,29 @@
+module Spree
+ module PromotionRules
+ class CustomerGroup < Spree::PromotionRule
+ # Stored as raw IDs. Accepts prefixed IDs (`cg_…`) from API
+ # callers and decodes them on write so eligibility checks can
+ # compare against raw `customer_group_id` rows directly.
+ preference :customer_group_ids, :array, default: [], parse_on_set: normalize_id_preference(klass: Spree::CustomerGroup)
+
+ def applicable?(promotable)
+ promotable.is_a?(Spree::Order)
+ end
+
+ def customer_groups
+ return Spree::CustomerGroup.none if preferred_customer_group_ids.blank?
+
+ Spree::CustomerGroup.where(id: preferred_customer_group_ids)
+ end
+
+ def eligible?(order, _options = {})
+ return false unless order.user_id.present?
+ return false if preferred_customer_group_ids.empty?
+
+ user_customer_group_ids = Spree::CustomerGroupUser.where(user_id: order.user_id).pluck(:customer_group_id).map(&:to_s)
+
+ (preferred_customer_group_ids.map(&:to_s) & user_customer_group_ids).any?
+ end
+ end
+ end
+end
diff --git a/spree/core/app/models/spree/promotion_rules/first_order.rb b/spree/core/app/models/spree/promotion_rules/first_order.rb
new file mode 100644
index 0000000000..5633d128a3
--- /dev/null
+++ b/spree/core/app/models/spree/promotion_rules/first_order.rb
@@ -0,0 +1,42 @@
+module Spree
+ module PromotionRules
+ class FirstOrder < Spree::PromotionRule
+ attr_reader :user, :email, :store
+
+ def applicable?(promotable)
+ promotable.is_a?(Spree::Order)
+ end
+
+ def eligible?(order, options = {})
+ @user = order.try(:user) || options[:user]
+ @email = if options[:email].present?
+ order.email = options[:email]
+ order.email
+ elsif order.email.present?
+ order.email
+ end
+ @store = order.store
+
+ if user || email
+ if !completed_orders.blank? && completed_orders.first != order
+ eligibility_errors.add(:base, eligibility_error_message(:not_first_order))
+ end
+ else
+ eligibility_errors.add(:base, eligibility_error_message(:no_user_or_email_specified))
+ end
+
+ eligibility_errors.empty?
+ end
+
+ private
+
+ def completed_orders
+ user ? user.orders.for_store(store).complete : orders_by_email
+ end
+
+ def orders_by_email
+ store.orders.where(email: email).complete
+ end
+ end
+ end
+end
diff --git a/spree/core/app/models/spree/promotion_rules/item_total.rb b/spree/core/app/models/spree/promotion_rules/item_total.rb
new file mode 100644
index 0000000000..1ed83cfd04
--- /dev/null
+++ b/spree/core/app/models/spree/promotion_rules/item_total.rb
@@ -0,0 +1,66 @@
+# A rule to apply to an order greater than (or greater than or equal to)
+# a specific amount
+module Spree
+ module PromotionRules
+ class ItemTotal < Spree::PromotionRule
+ preference :amount_min, :decimal, default: 100.00
+ preference :operator_min, :string, default: '>'
+ preference :amount_max, :decimal, default: nil, nullable: true
+ preference :operator_max, :string, default: '<'
+
+ OPERATORS_MIN = ['gt', 'gte']
+ OPERATORS_MAX = ['lt', 'lte']
+
+ def applicable?(promotable)
+ promotable.is_a?(Spree::Order)
+ end
+
+ def eligible?(order, _options = {})
+ item_total = order.item_total
+
+ lower_limit_condition = item_total.send(preferred_operator_min == 'gte' ? :>= : :>, BigDecimal(preferred_amount_min.to_s))
+
+ if preferred_amount_max.present?
+ upper_limit_condition = item_total.send(preferred_operator_max == 'lte' ? :<= : :<, BigDecimal(preferred_amount_max.to_s))
+ else
+ upper_limit_condition = true
+ end
+
+ eligibility_errors.add(:base, ineligible_message_max(order)) unless upper_limit_condition
+ eligibility_errors.add(:base, ineligible_message_min(order)) unless lower_limit_condition
+
+ eligibility_errors.empty?
+ end
+
+ private
+
+ def formatted_amount_min(order)
+ Spree::Money.new(preferred_amount_min, currency: order.currency).to_s
+ end
+
+ def formatted_amount_max(order)
+ if preferred_amount_max.present?
+ Spree::Money.new(preferred_amount_max, currency: order.currency).to_s
+ else
+ Spree.t('no_maximum')
+ end
+ end
+
+ def ineligible_message_max(order)
+ if preferred_operator_max == 'lt'
+ eligibility_error_message(:item_total_more_than_or_equal, amount: formatted_amount_max(order))
+ else
+ eligibility_error_message(:item_total_more_than, amount: formatted_amount_max(order))
+ end
+ end
+
+ def ineligible_message_min(order)
+ if preferred_operator_min == 'gte'
+ eligibility_error_message(:item_total_less_than, amount: formatted_amount_min(order))
+ else
+ eligibility_error_message(:item_total_less_than_or_equal, amount: formatted_amount_min(order))
+ end
+ end
+ end
+ end
+end
diff --git a/spree/core/app/models/spree/promotion_rules/market.rb b/spree/core/app/models/spree/promotion_rules/market.rb
new file mode 100644
index 0000000000..b7f75ecd7c
--- /dev/null
+++ b/spree/core/app/models/spree/promotion_rules/market.rb
@@ -0,0 +1,35 @@
+# A rule to limit a promotion based on the order's market.
+module Spree
+ module PromotionRules
+ class Market < Spree::PromotionRule
+ # Stored as raw IDs. Accepts prefixed IDs (`mkt_…`) from API
+ # callers and decodes them on write so eligibility checks compare
+ # against the order's raw `market_id` directly. Scope confines the
+ # existence check to the promotion's store so cross-store market
+ # IDs can't sneak in.
+ preference :market_ids, :array, default: [],
+ parse_on_set: normalize_id_preference(
+ klass: Spree::Market,
+ scope: ->(rule) { rule.promotion&.store&.markets || Spree::Market.none }
+ )
+
+ def applicable?(promotable)
+ promotable.is_a?(Spree::Order)
+ end
+
+ def markets
+ return Spree::Market.none if preferred_market_ids.blank?
+
+ promotion.store.markets.where(id: preferred_market_ids)
+ end
+
+ def eligible?(order, _options = {})
+ return false if preferred_market_ids.empty?
+ return true if preferred_market_ids.map(&:to_s).include?(order.market_id.to_s)
+
+ eligibility_errors.add(:base, eligibility_error_message(:no_matching_market))
+ false
+ end
+ end
+ end
+end
diff --git a/spree/core/app/models/spree/promotion_rules/one_use_per_user.rb b/spree/core/app/models/spree/promotion_rules/one_use_per_user.rb
new file mode 100644
index 0000000000..e9f3746ce4
--- /dev/null
+++ b/spree/core/app/models/spree/promotion_rules/one_use_per_user.rb
@@ -0,0 +1,21 @@
+module Spree
+ module PromotionRules
+ class OneUsePerUser < Spree::PromotionRule
+ def applicable?(promotable)
+ promotable.is_a?(Spree::Order)
+ end
+
+ def eligible?(order, _options = {})
+ if order.user.present?
+ if promotion.used_by?(order.user, [order])
+ eligibility_errors.add(:base, eligibility_error_message(:limit_once_per_user))
+ end
+ else
+ eligibility_errors.add(:base, eligibility_error_message(:no_user_specified))
+ end
+
+ eligibility_errors.empty?
+ end
+ end
+ end
+end
diff --git a/spree/core/app/models/spree/promotion_rules/option_value.rb b/spree/core/app/models/spree/promotion_rules/option_value.rb
new file mode 100644
index 0000000000..7cae2273f5
--- /dev/null
+++ b/spree/core/app/models/spree/promotion_rules/option_value.rb
@@ -0,0 +1,36 @@
+module Spree
+ module PromotionRules
+ class OptionValue < Spree::PromotionRule
+ MATCH_POLICIES = %w(any)
+ preference :match_policy, :string, default: MATCH_POLICIES.first
+ preference :eligible_values, :array, default: [], parse_on_set: lambda { |values|
+ values.flat_map { |v| v.to_s.split(',').compact_blank.map(&:strip) }
+ }
+
+ def applicable?(promotable)
+ promotable.is_a?(Spree::Order)
+ end
+
+ def eligible?(promotable, _options = {})
+ return false if eligible_option_value_variant_ids.empty?
+
+ case preferred_match_policy
+ when 'any'
+ Spree::OptionValueVariant.where(id: eligible_option_value_variant_ids, variant_id: promotable.variant_ids).exists?
+ end
+ end
+
+ def actionable?(line_item)
+ return false if eligible_option_value_variant_ids.empty?
+
+ Spree::OptionValueVariant.where(id: eligible_option_value_variant_ids, variant_id: line_item.variant_id).exists?
+ end
+
+ private
+
+ def eligible_option_value_variant_ids
+ @eligible_option_value_variant_ids ||= preferred_eligible_values.map(&:to_s)
+ end
+ end
+ end
+end
diff --git a/spree/core/app/models/spree/promotion_rules/product.rb b/spree/core/app/models/spree/promotion_rules/product.rb
new file mode 100644
index 0000000000..64f941f85a
--- /dev/null
+++ b/spree/core/app/models/spree/promotion_rules/product.rb
@@ -0,0 +1,114 @@
+# A rule to limit a promotion based on products in the order.
+# Can require all or any of the products to be present.
+# Valid products either come from assigned product group or are assigned directly to the rule.
+module Spree
+ module PromotionRules
+ class Product < Spree::PromotionRule
+ #
+ # Associations
+ #
+ has_many :product_promotion_rules, class_name: 'Spree::ProductPromotionRule',
+ foreign_key: :promotion_rule_id,
+ dependent: :destroy
+ has_many :products, through: :product_promotion_rules, class_name: 'Spree::Product'
+
+ def self.additional_permitted_attributes
+ [product_ids: []]
+ end
+
+ #
+ # Preferences
+ #
+ MATCH_POLICIES = %w(any all none)
+ preference :match_policy, :string, default: MATCH_POLICIES.first
+
+ #
+ # Attributes
+ #
+ attr_accessor :product_ids_to_add
+
+ #
+ # Callbacks
+ #
+ after_save :add_products
+
+ # scope/association that is used to test eligibility
+ def eligible_products
+ products
+ end
+
+ def eligible_product_ids
+ @eligible_product_ids ||= product_promotion_rules.pluck(:product_id)
+ end
+
+ def applicable?(promotable)
+ promotable.is_a?(Spree::Order)
+ end
+
+ def eligible?(order, _options = {})
+ return true if eligible_product_ids.empty?
+
+ if preferred_match_policy == 'all'
+ unless eligible_product_ids.all? { |p| order.product_ids.include?(p) }
+ eligibility_errors.add(:base, eligibility_error_message(:missing_product))
+ end
+ elsif preferred_match_policy == 'any'
+ unless order.product_ids.any? { |p| eligible_product_ids.include?(p) }
+ eligibility_errors.add(:base, eligibility_error_message(:no_applicable_products))
+ end
+ else
+ unless order.product_ids.none? { |p| eligible_product_ids.include?(p) }
+ eligibility_errors.add(:base, eligibility_error_message(:has_excluded_product))
+ end
+ end
+
+ eligibility_errors.empty?
+ end
+
+ def actionable?(line_item)
+ case preferred_match_policy
+ when 'any', 'all'
+ eligible_product_ids.include? line_item.variant.product_id
+ when 'none'
+ eligible_product_ids.exclude? line_item.variant.product_id
+ else
+ raise "unexpected match policy: #{preferred_match_policy.inspect}"
+ end
+ end
+
+ def product_ids_string
+ ActiveSupport::Deprecation.warn(
+ 'Please use `product_ids=` instead.'
+ )
+ product_ids.join(',')
+ end
+
+ def product_ids_string=(s)
+ ActiveSupport::Deprecation.warn(
+ 'Please use `product_ids=` instead.'
+ )
+ self.product_ids = s
+ end
+
+ private
+
+ def add_products
+ return if product_ids_to_add.nil?
+
+ product_promotion_rules.delete_all
+
+ if product_ids_to_add.any?
+ Spree::ProductPromotionRule.insert_all(
+ product_ids_to_add.map { |product_id| { product_id: product_id, promotion_rule_id: id } }
+ )
+ end
+
+ # Invalidate cache after bulk operations
+ touch
+
+ # Clear memoized values
+ @eligible_product_ids = nil
+ end
+ end
+ end
+end
diff --git a/spree/core/app/models/spree/promotion_rules/taxon.rb b/spree/core/app/models/spree/promotion_rules/taxon.rb
new file mode 100644
index 0000000000..d5a3dec4f4
--- /dev/null
+++ b/spree/core/app/models/spree/promotion_rules/taxon.rb
@@ -0,0 +1,14 @@
+# frozen_string_literal: true
+
+module Spree
+ module PromotionRules
+ # Deprecation alias for Spree::Promotion::Rules::Category, renamed from
+ # Spree::Promotion::Rules::Taxon in 6.0. A true constant alias, so old STI type
+ # strings (`'Spree::Promotion::Rules::Taxon'`) still instantiate correctly until
+ # the Phase 4 migration rewrites them. The warning fires when this file loads.
+ # Removed in 6.1.
+ Taxon = Category
+
+ Spree::Deprecation.warn('Spree::PromotionRules::Taxon is deprecated and will be removed in Spree 6.1. Use Spree::PromotionRules::Category instead.')
+ end
+end
diff --git a/spree/core/app/models/spree/promotion_rules/user.rb b/spree/core/app/models/spree/promotion_rules/user.rb
new file mode 100644
index 0000000000..785cdb8844
--- /dev/null
+++ b/spree/core/app/models/spree/promotion_rules/user.rb
@@ -0,0 +1,92 @@
+module Spree
+ module PromotionRules
+ class User < Spree::PromotionRule
+ #
+ # Associations
+ #
+ has_many :promotion_rule_users, class_name: 'Spree::PromotionRuleUser',
+ foreign_key: :promotion_rule_id,
+ dependent: :destroy
+ has_many :users, through: :promotion_rule_users, class_name: "::#{Spree.user_class}"
+
+ # Customers, not admin users — the rule keys off `Spree::Order#user_id`.
+ # The data layer keeps the `users` association (legacy column name);
+ # the API exposes the same set as `customer_ids`.
+ def self.additional_permitted_attributes
+ [customer_ids: []]
+ end
+
+ # Wire-format shorthand is `customer` (the model is still `User`
+ # pre-6.0 rename, see docs/plans/6.0-platform-auth.md).
+ def self.api_type
+ 'customer'
+ end
+
+ def customer_ids
+ user_ids
+ end
+
+ def customer_ids=(ids)
+ self.user_ids = ids
+ end
+
+ #
+ # Attributes
+ #
+ attr_accessor :user_ids_to_add
+
+ #
+ # Callbacks
+ #
+ after_save :add_users
+
+ def applicable?(promotable)
+ promotable.is_a?(Spree::Order)
+ end
+
+ def eligible_user_ids
+ @eligible_user_ids ||= promotion_rule_users.pluck(:user_id)
+ end
+
+ def eligible?(order, _options = {})
+ eligible_user_ids.include?(order.user_id)
+ end
+
+ def user_ids_string
+ ActiveSupport::Deprecation.warn(
+ 'Spree::Promotion::Rules::User#user_ids_string is deprecated and will be removed in Spree 5.5. ' \
+ 'Please use `user_ids` instead.'
+ )
+ user_ids.join(',')
+ end
+
+ def user_ids_string=(s)
+ ActiveSupport::Deprecation.warn(
+ 'Spree::Promotion::Rules::User#user_ids_string= is deprecated and will be removed in Spree 5.5. ' \
+ 'Please use `user_ids=` instead.'
+ )
+ self.user_ids = s
+ end
+
+ private
+
+ def add_users
+ return if user_ids_to_add.nil?
+
+ promotion_rule_users.delete_all
+
+ if user_ids_to_add.any?
+ Spree::PromotionRuleUser.insert_all(
+ user_ids_to_add.map { |user_id| { user_id: user_id, promotion_rule_id: id } }
+ )
+ end
+
+ # Invalidate cache after bulk operations
+ touch
+
+ # Clear memoized values
+ @eligible_user_ids = nil
+ end
+ end
+ end
+end
diff --git a/spree/core/app/models/spree/promotion_rules/user_logged_in.rb b/spree/core/app/models/spree/promotion_rules/user_logged_in.rb
new file mode 100644
index 0000000000..cf63a02690
--- /dev/null
+++ b/spree/core/app/models/spree/promotion_rules/user_logged_in.rb
@@ -0,0 +1,22 @@
+module Spree
+ module PromotionRules
+ class UserLoggedIn < Spree::PromotionRule
+ # Wire-format shorthand is `customer_logged_in` (the model is still
+ # `UserLoggedIn` pre-6.0 rename, see docs/plans/6.0-platform-auth.md).
+ def self.api_type
+ 'customer_logged_in'
+ end
+
+ def applicable?(promotable)
+ promotable.is_a?(Spree::Order)
+ end
+
+ def eligible?(order, _options = {})
+ unless order.user.present?
+ eligibility_errors.add(:base, eligibility_error_message(:no_user_specified))
+ end
+ eligibility_errors.empty?
+ end
+ end
+ end
+end
diff --git a/spree/core/app/models/spree/tax_line.rb b/spree/core/app/models/spree/tax_line.rb
new file mode 100644
index 0000000000..b3a13d3079
--- /dev/null
+++ b/spree/core/app/models/spree/tax_line.rb
@@ -0,0 +1,51 @@
+module Spree
+ # A single tax charge on a line item, fulfillment or fee. Written exclusively
+ # by the tax provider (see Spree.tax_provider) with replace-all set semantics
+ # per estimate. Snapshot columns (+rate+, +label+, +provider_id+) keep rows
+ # self-describing after a TaxRate is deleted or when an external provider
+ # computed them.
+ class TaxLine < Spree.base_class
+ include Spree::TypedAdjustmentLine
+
+ has_prefix_id :tl
+
+ # Source — nil for externally-computed tax
+ belongs_to :tax_rate, class_name: 'Spree::TaxRate', optional: true
+
+ # Adjustable — exactly one
+ belongs_to :line_item, class_name: 'Spree::LineItem', optional: true
+ belongs_to :fulfillment, class_name: 'Spree::Fulfillment', optional: true
+ belongs_to :fee, class_name: 'Spree::Fee', optional: true
+
+ # Tax included in price vs additional. Per-row (mixed regimes on one order).
+ attribute :included, :boolean, default: false
+
+ validates :rate, numericality: { greater_than_or_equal_to: 0 }
+ validate :exactly_one_adjustable
+
+ scope :included_in_price, -> { where(included: true) }
+ scope :additional, -> { where(included: false) }
+ scope :for_line_items, -> { where.not(line_item_id: nil) }
+ scope :for_fulfillments, -> { where.not(fulfillment_id: nil) }
+ scope :for_fees, -> { where.not(fee_id: nil) }
+
+ # @return [Spree::LineItem, Spree::Fulfillment, Spree::Fee, nil]
+ def adjustable
+ line_item || fulfillment || fee
+ end
+
+ def included?
+ included
+ end
+
+ def additional?
+ !included
+ end
+
+ private
+
+ def exactly_one_adjustable
+ errors.add(:base, Spree.t('errors.messages.exactly_one_adjustable')) unless [line_item, fulfillment, fee].compact.one?
+ end
+ end
+end
diff --git a/spree/core/app/models/spree/tax_provider/base.rb b/spree/core/app/models/spree/tax_provider/base.rb
new file mode 100644
index 0000000000..c38e4a0dce
--- /dev/null
+++ b/spree/core/app/models/spree/tax_provider/base.rb
@@ -0,0 +1,33 @@
+module Spree
+ module TaxProvider
+ # Contract for tax providers — the only sanctioned writers of
+ # {Spree::TaxLine} rows. +estimate+ must use replace-all set semantics per
+ # target item (delete the item's stale lines, insert fresh ones); that is
+ # what keeps tax correct after address or item changes. Commit/void/refund
+ # are lifecycle no-ops for providers without a remote ledger.
+ class Base
+ # Recomputes tax for the given items (defaults to all taxable items of
+ # the owner: line items, fulfillments and fees).
+ #
+ # @param owner [Spree::Order, Spree::Cart]
+ # @param items [Array<Spree::LineItem, Spree::Fulfillment, Spree::Fee>, nil]
+ def estimate(owner, items = nil)
+ raise NotImplementedError, "Please implement 'estimate' in your tax provider: #{self.class.name}"
+ end
+
+ # Finalizes tax with the provider at completion (no-op by default).
+ def commit(owner); end
+
+ # Cancels a previously committed tax document (no-op by default).
+ def void(owner); end
+
+ # Reports a refund against committed tax (no-op by default).
+ def refund(owner, amount); end
+
+ # @return [Boolean] whether the owner is tax-exempt
+ def exempt?(_owner)
+ false
+ end
+ end
+ end
+end
diff --git a/spree/core/app/models/spree/tax_provider/internal.rb b/spree/core/app/models/spree/tax_provider/internal.rb
new file mode 100644
index 0000000000..43baa35eed
--- /dev/null
+++ b/spree/core/app/models/spree/tax_provider/internal.rb
@@ -0,0 +1,102 @@
+module Spree
+ module TaxProvider
+ # Computes tax directly from TaxRate configuration: rate × discounted
+ # base, with VAT included-in-price math backed out of the gross basis.
+ # Zone matching is unchanged from 5.x (TaxRate.match over the owner's tax
+ # zone). Fees without a tax category are taxed with the default tax
+ # category's rates.
+ class Internal < Base
+ def estimate(owner, items = nil)
+ items ||= owner.line_items.to_a + owner.fulfillments.to_a + owner.fees.to_a
+ return if items.empty?
+
+ rates = Spree::TaxRate.match(owner.tax_zone)
+
+ items.group_by(&:class).each do |klass, group|
+ # Replace-all set semantics per estimate: stale lines die with the
+ # address/items change that triggered the re-estimate.
+ Spree::TaxLine.where(tax_line_foreign_key(klass) => group.map(&:id)).delete_all
+ end
+
+ items.each do |item|
+ relevant_rates = rates.select { |rate| rate.tax_category_id == tax_category_id_for(item) }
+ store_pre_tax_amount(item, relevant_rates)
+
+ relevant_rates.each do |rate|
+ amount = compute_tax(rate, item, relevant_rates)
+ next if amount.zero?
+
+ write_tax_line(owner, item, rate, amount)
+ end
+ end
+ end
+
+ private
+
+ def tax_line_foreign_key(klass)
+ case klass.name
+ when 'Spree::LineItem' then :line_item_id
+ when 'Spree::Fulfillment' then :fulfillment_id
+ when 'Spree::Fee' then :fee_id
+ else raise ArgumentError, "#{klass} is not taxable"
+ end
+ end
+
+ def tax_category_id_for(item)
+ if item.respond_to?(:tax_category_id) && item.tax_category_id
+ item.tax_category_id
+ else
+ default_tax_category&.id
+ end
+ end
+
+ def default_tax_category
+ return @default_tax_category if defined?(@default_tax_category)
+
+ @default_tax_category = Spree::TaxCategory.find_by(is_default: true)
+ end
+
+ def taxable_basis(item)
+ item.respond_to?(:taxable_basis) ? item.taxable_basis : item.amount
+ end
+
+ def compute_tax(rate, item, relevant_rates)
+ basis = taxable_basis(item)
+
+ if rate.included_in_price
+ included_sum = relevant_rates.select(&:included_in_price).sum(&:amount)
+ included_sum = rate.amount if included_sum.zero?
+ (basis / (1 + included_sum) * rate.amount).round(2)
+ else
+ (basis * rate.amount).round(2)
+ end
+ end
+
+ # Pre-tax amounts are stored so refund and reporting code can weigh
+ # discounted, tax-exclusive values later (see #4318).
+ def store_pre_tax_amount(item, rates)
+ return unless item.respond_to?(:pre_tax_amount)
+
+ pre_tax_amount = taxable_basis(item)
+ included_rates = rates.select(&:included_in_price)
+ pre_tax_amount /= (1 + included_rates.sum(&:amount)) if included_rates.any?
+
+ item.update_column(:pre_tax_amount, pre_tax_amount)
+ end
+
+ def write_tax_line(owner, item, rate, amount)
+ owner_key = owner.is_a?(Spree::Order) ? :order : :cart
+ Spree::TaxLine.create!(
+ tax_line_foreign_key(item.class) => item.id,
+ owner_key => owner,
+ tax_rate: rate,
+ amount: amount,
+ rate: rate.amount,
+ label: rate.adjustment_label,
+ included: rate.included_in_price,
+ provider_id: 'internal'
+ )
+ end
+ end
+ end
+end
diff --git a/spree/core/app/models/spree/tax_rate.rb b/spree/core/app/models/spree/tax_rate.rb
index d36f7dc330..3a8cb95400 100644
--- a/spree/core/app/models/spree/tax_rate.rb
+++ b/spree/core/app/models/spree/tax_rate.rb
@@ -1,11 +1,12 @@
module Spree
+ # Pure tax configuration read by the internal tax provider
+ # (Spree::TaxProvider::Internal). Since 6.0 tax rates have no write path of
+ # their own — TaxLine rows are written exclusively by Spree.tax_provider.
class TaxRate < Spree.base_class
has_prefix_id :tax
acts_as_paranoid
- include Spree::CalculatedAdjustments
- include Spree::AdjustmentSource
include Spree::Metafields
include Spree::Metadata
@@ -15,6 +16,8 @@ module Spree
class_name: 'Spree::TaxCategory'
end
+ has_many :tax_lines, class_name: 'Spree::TaxLine', dependent: :nullify
+
with_options presence: true do
validates :amount, numericality: { allow_nil: true }
validates :tax_category, :name
@@ -51,66 +54,6 @@ module Spree
potential_rates_for_zone(order_tax_zone)
end
- # Pre-tax amounts must be stored so that we can calculate
- # correct rate amounts in the future. For example:
- # https://github.com/spree/spree/issues/4318#issuecomment-34723428
- #
- # NOTE: this deliberately excludes the item's share of whole-order
- # promotions and is therefore NOT the basis tax is computed on (that is
- # LineItem#taxable_basis / Shipment#taxable_basis). Refund and reporting
- # code (e.g. Calculator::Returns::DefaultRefundAmount) weighs order-level
- # adjustments separately on top of this column, so allocating them here
- # would double-count discounts.
- 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', 'Spree::Fulfillment' then item.discounted_cost
- end
-
- included_rates = rates.select(&:included_in_price)
- if included_rates.any?
- pre_tax_amount /= (1 + included_rates.sum(&:amount))
- end
-
- item.update_column(:pre_tax_amount, pre_tax_amount)
- end
-
- # Deletes all tax adjustments, then applies all applicable rates
- # to relevant items.
- def self.adjust(order, items)
- return if items.none?
-
- rates = match(order.tax_zone)
- tax_category_ids = rates.map(&:tax_category_id)
-
- # using destroy_all to ensure adjustment destroy callback fires.
- Spree::Adjustment.where(adjustable: items).tax.destroy_all
-
- relevant_items = if tax_category_ids.any?
- items.select do |item|
- tax_category_ids.include?(item.tax_category_id)
- end
- else
- []
- end
-
- relevant_items.each do |item|
- relevant_rates = rates.select do |rate|
- rate.tax_category_id == item.tax_category_id
- end
- store_pre_tax_amount(item, relevant_rates)
- relevant_rates.each do |rate|
- rate.adjust(order, item)
- end
- end
-
- # updates pre_tax for items without any tax rates
- remaining_items = items - relevant_items
- remaining_items.each do |item|
- store_pre_tax_amount(item, [])
- end
- end
-
def self.included_tax_amount_for(options)
return 0 unless options[:tax_zone] && options[:tax_category]
@@ -120,14 +63,6 @@ module Spree
sum(:amount)
end
- def adjust(order, item)
- create_adjustment(order, item, included_in_price)
- end
-
- def compute_amount(item)
- compute(item)
- end
-
def included?
included_in_price
end
@@ -136,15 +71,18 @@ module Spree
!included_in_price
end
- private
-
- def label
+ # The customer-facing label snapshotted onto TaxLine rows.
+ #
+ # @return [String]
+ def adjustment_label
Spree.t included_in_price? ? :including_tax : :excluding_tax,
scope: 'adjustment_labels.tax_rates',
name: name.presence || tax_category.name,
amount: amount_for_label
end
+ private
+
def amount_for_label
return '' unless show_rate_in_label?
return '' if amount.zero?
diff --git a/spree/core/app/services/spree/carts/add_item.rb b/spree/core/app/services/spree/carts/add_item.rb
index 4ba29c3c2d..9f0e6e9e11 100644
--- a/spree/core/app/services/spree/carts/add_item.rb
+++ b/spree/core/app/services/spree/carts/add_item.rb
@@ -46,7 +46,7 @@ module Spree
line_item.reload.recalculate_price
- ::Spree::TaxRate.adjust(order, [line_item]) if line_item_created
+ ::Spree.tax_provider.estimate(line_item.owner, [line_item]) if line_item_created
success(order: order, line_item: line_item, line_item_created: line_item_created, options: options)
end
diff --git a/spree/core/app/services/spree/carts/empty.rb b/spree/core/app/services/spree/carts/empty.rb
index 37c7476f4d..55636cd871 100644
--- a/spree/core/app/services/spree/carts/empty.rb
+++ b/spree/core/app/services/spree/carts/empty.rb
@@ -20,7 +20,9 @@ module Spree
ActiveRecord::Base.transaction do
order.line_items.destroy_all
order.updater.update_item_count
- order.adjustments.destroy_all
+ order.tax_lines.destroy_all
+ order.discounts.destroy_all
+ order.fees.destroy_all
order.fulfillments.destroy_all
order.state_changes.destroy_all
order.order_promotions.destroy_all
diff --git a/spree/core/app/services/spree/carts/recalculate.rb b/spree/core/app/services/spree/carts/recalculate.rb
index 9f340da24c..6d684f83da 100644
--- a/spree/core/app/services/spree/carts/recalculate.rb
+++ b/spree/core/app/services/spree/carts/recalculate.rb
@@ -25,8 +25,8 @@ module Spree
end
::Spree::PromotionHandler::Cart.new(order, line_item).activate
- ::Spree::Adjustable::AdjustmentsUpdater.update(line_item)
- ::Spree::TaxRate.adjust(order, [line_item.reload]) if line_item_created
+ # Typed rows (discounts + tax) are rebuilt by the order-level
+ # recalculation inside the updater.
order_updater.update
success(line_item)
end
diff --git a/spree/core/app/services/spree/coupon_codes/coupon_codes_handler.rb b/spree/core/app/services/spree/coupon_codes/coupon_codes_handler.rb
index f2b3d212e1..72755bc21c 100644
--- a/spree/core/app/services/spree/coupon_codes/coupon_codes_handler.rb
+++ b/spree/core/app/services/spree/coupon_codes/coupon_codes_handler.rb
@@ -19,8 +19,7 @@ module Spree
private
def find_current_promotions_ids
- order.all_adjustments.promotion.eligible.joins("INNER JOIN #{Spree::PromotionAction.table_name} ON #{Spree::PromotionAction.table_name}.id = #{Spree::Adjustment.table_name}.source_id").
- pluck("#{Spree::PromotionAction.table_name}.promotion_id").compact.uniq
+ order.discounts.promotion.where.not(promotion_id: nil).distinct.pluck(:promotion_id)
end
def use_all_current(promotion_ids)
diff --git a/spree/core/config/locales/en.yml b/spree/core/config/locales/en.yml
index 7aec316a2c..66013e17db 100644
--- a/spree/core/config/locales/en.yml
+++ b/spree/core/config/locales/en.yml
@@ -924,6 +924,7 @@ en:
delivery_zone_prefix_and_range_exclusive: cannot be combined with a from/to range
delivery_zone_range_inverted: must be greater than or equal to postal_code_from
delivery_zone_range_not_supported: postal code ranges are not supported for this country — use prefixes
+ exactly_one_adjustable: must be attached to exactly one adjustable
exactly_one_of_cart_or_order: must belong to exactly one of cart or order
invalid_order_routing_rule: is not a registered order routing rule
invalid_order_routing_strategy: is not a registered order routing strategy
diff --git a/spree/core/db/migrate/20260729000001_create_typed_adjustment_tables.rb b/spree/core/db/migrate/20260729000001_create_typed_adjustment_tables.rb
new file mode 100644
index 0000000000..1f1878e7a9
--- /dev/null
+++ b/spree/core/db/migrate/20260729000001_create_typed_adjustment_tables.rb
@@ -0,0 +1,87 @@
+class CreateTypedAdjustmentTables < ActiveRecord::Migration[7.2]
+ def change
+ create_table :spree_tax_lines do |t|
+ # Owner — exactly one of cart/order (enforced at model level)
+ t.references :cart, null: true
+ t.references :order, null: true
+
+ # Source — nil for externally-computed tax; snapshots keep rows self-describing
+ t.references :tax_rate, null: true
+
+ # Adjustable — exactly one (enforced at model level)
+ t.references :line_item, null: true
+ t.references :fulfillment, null: true
+ t.references :fee, null: true
+
+ t.decimal :amount, precision: 10, scale: 2, null: false
+ t.decimal :rate, precision: 8, scale: 5, null: false
+ t.string :label, null: false
+ t.boolean :included, null: false
+ t.string :provider_id
+ if t.respond_to?(:jsonb)
+ t.jsonb :data
+ t.jsonb :metadata
+ else
+ t.json :data
+ t.json :metadata
+ end
+
+ t.timestamps
+ end
+
+ create_table :spree_discounts do |t|
+ t.references :cart, null: true
+ t.references :order, null: true
+
+ # Source — nullified on promotion deletion; code/value snapshots keep history meaningful
+ t.references :promotion_action, null: true
+ t.references :promotion, null: true
+
+ # Adjustable — exactly one (enforced at model level)
+ t.references :line_item, null: true
+ t.references :fulfillment, null: true
+
+ t.decimal :amount, precision: 10, scale: 2, null: false
+ t.string :label, null: false
+ t.string :kind, null: false
+ t.string :code
+ t.decimal :value, precision: 10, scale: 2
+ t.string :value_type
+ if t.respond_to?(:jsonb)
+ t.jsonb :metadata
+ else
+ t.json :metadata
+ end
+
+ t.timestamps
+
+ t.check_constraint 'amount <= 0', name: 'chk_spree_discounts_amount_nonpositive'
+ end
+ add_index :spree_discounts, :code
+
+ create_table :spree_fees do |t|
+ t.references :cart, null: true
+ t.references :order, null: true, index: false
+
+ # Adjustable — both nil means an order-level fee (payment surcharge, COD, ...)
+ t.references :line_item, null: true
+ t.references :fulfillment, null: true
+
+ t.decimal :amount, precision: 10, scale: 2, null: false
+ t.string :label, null: false
+ t.string :kind, null: false
+ if t.respond_to?(:jsonb)
+ t.jsonb :metadata
+ else
+ t.json :metadata
+ end
+
+ t.timestamps
+
+ t.check_constraint 'amount >= 0', name: 'chk_spree_fees_amount_nonnegative'
+ end
+ add_index :spree_fees, [:order_id, :kind]
+
+ add_column :spree_orders, :fee_total, :decimal, precision: 10, scale: 2
+ end
+end
diff --git a/spree/core/lib/spree/core.rb b/spree/core/lib/spree/core.rb
index b846274f8a..e2e03472c9 100644
--- a/spree/core/lib/spree/core.rb
+++ b/spree/core/lib/spree/core.rb
@@ -272,6 +272,19 @@ module Spree
Rails.application.config.spree.adjusters = value
end
+ # The configured tax provider instance — the only sanctioned writer of
+ # {Spree::TaxLine} rows. Global default is {Spree::TaxProvider::Internal};
+ # per-Market resolution arrives with docs/plans/6.0-tax-provider.md.
+ #
+ # @return [Spree::TaxProvider::Base]
+ def self.tax_provider
+ Rails.application.config.spree.tax_provider.new
+ end
+
+ def self.tax_provider=(value)
+ Rails.application.config.spree.tax_provider = value
+ end
+
def self.stock_splitters
Rails.application.config.spree.stock_splitters
end
diff --git a/spree/core/lib/spree/core/controller_helpers/order.rb b/spree/core/lib/spree/core/controller_helpers/order.rb
index e58369c904..3a5a58e9c2 100644
--- a/spree/core/lib/spree/core/controller_helpers/order.rb
+++ b/spree/core/lib/spree/core/controller_helpers/order.rb
@@ -137,7 +137,7 @@ module Spree
token_order_params = current_order_params.except(:user_id)
order = if with_adjustments
- incomplete_orders.includes(:adjustments).lock(options[:lock]).find_by(token_order_params)
+ incomplete_orders.includes(:discounts, :fees).lock(options[:lock]).find_by(token_order_params)
else
incomplete_orders.lock(options[:lock]).find_by(token_order_params)
end
diff --git a/spree/core/lib/spree/core/engine.rb b/spree/core/lib/spree/core/engine.rb
index 73336d9d5e..642a98313a 100644
--- a/spree/core/lib/spree/core/engine.rb
+++ b/spree/core/lib/spree/core/engine.rb
@@ -10,6 +10,7 @@ module Spree
:dependencies,
:payment_methods,
:adjusters,
+ :tax_provider,
:stock_splitters,
:order_routing,
:promotions,
@@ -36,7 +37,7 @@ module Spree
:subscribers,
:store_authentication_strategies,
:admin_authentication_strategies)
- SpreeCalculators = Struct.new(:shipping_methods, :tax_rates, :promotion_actions_create_adjustments, :promotion_actions_create_item_adjustments)
+ SpreeCalculators = Struct.new(:shipping_methods, :tax_rates, :promotion_actions_create_adjustments, :promotion_actions_create_item_discounts, :promotion_actions_create_item_adjustments)
PromoEnvironment = Struct.new(:rules, :actions)
PricingEnvironment = Struct.new(:rules)
OrderRoutingEnvironment = Struct.new(:strategies, :rules)
@@ -145,10 +146,6 @@ module Spree
Spree::Calculator::Shipping::DigitalDelivery,
]
- Rails.application.config.spree.calculators.tax_rates = [
- Spree::Calculator::DefaultTax
- ]
-
Rails.application.config.spree.stock_splitters = [
Spree::Stock::Splitter::FulfillmentType,
Spree::Stock::Splitter::Backordered
@@ -162,10 +159,12 @@ module Spree
]
Rails.application.config.spree.adjusters = [
- Spree::Adjustable::Adjuster::Promotion,
- Spree::Adjustable::Adjuster::Tax
+ Spree::Adjusters::Promotion
]
+ # The sanctioned TaxLine writer (see docs/plans/6.0-tax-provider.md).
+ Rails.application.config.spree.tax_provider = Spree::TaxProvider::Internal
+
# Selectable order routing strategies. The internal Reducer collaborator
# is intentionally NOT listed — it is not a Strategy::Base. Plugins add
# their own (or remove Legacy) via this array.
@@ -191,26 +190,30 @@ module Spree
Spree::Calculator::TieredFlatRate
]
- Rails.application.config.spree.calculators.promotion_actions_create_item_adjustments = [
+ Rails.application.config.spree.calculators.promotion_actions_create_item_discounts = [
Spree::Calculator::PercentOnLineItem,
Spree::Calculator::FlatRate,
Spree::Calculator::FlexiRate
]
+ # Legacy registry key — removed in 6.1. Kept so extensions appending
+ # to it keep working; CreateItemDiscounts reads the new key above.
+ Rails.application.config.spree.calculators.promotion_actions_create_item_adjustments =
+ Rails.application.config.spree.calculators.promotion_actions_create_item_discounts
Rails.application.config.spree.promotions.rules.concat [
- Spree::Promotion::Rules::Currency,
- Spree::Promotion::Rules::Country,
- Spree::Promotion::Rules::Channel,
- Spree::Promotion::Rules::Market,
- Spree::Promotion::Rules::ItemTotal,
- Spree::Promotion::Rules::Product,
- Spree::Promotion::Rules::User,
- Spree::Promotion::Rules::CustomerGroup,
- Spree::Promotion::Rules::FirstOrder,
- Spree::Promotion::Rules::UserLoggedIn,
- Spree::Promotion::Rules::OneUsePerUser,
- Spree::Promotion::Rules::Category,
- Spree::Promotion::Rules::OptionValue,
+ Spree::PromotionRules::Currency,
+ Spree::PromotionRules::Country,
+ Spree::PromotionRules::Channel,
+ Spree::PromotionRules::Market,
+ Spree::PromotionRules::ItemTotal,
+ Spree::PromotionRules::Product,
+ Spree::PromotionRules::User,
+ Spree::PromotionRules::CustomerGroup,
+ Spree::PromotionRules::FirstOrder,
+ Spree::PromotionRules::UserLoggedIn,
+ Spree::PromotionRules::OneUsePerUser,
+ Spree::PromotionRules::Category,
+ Spree::PromotionRules::OptionValue,
]
# Default registry. MarketRule is included so existing installs
@@ -229,10 +232,10 @@ module Spree
]
Rails.application.config.spree.promotions.actions = [
- Promotion::Actions::CreateAdjustment,
- Promotion::Actions::CreateItemAdjustments,
- Promotion::Actions::CreateLineItems,
- Promotion::Actions::FreeShipping
+ PromotionActions::CreateAdjustment,
+ PromotionActions::CreateItemDiscounts,
+ PromotionActions::CreateLineItems,
+ PromotionActions::FreeShipping
]
Rails.application.config.spree.data_feed_types = [
diff --git a/spree/core/lib/spree/testing_support/factories/adjustment_factory.rb b/spree/core/lib/spree/testing_support/factories/adjustment_factory.rb
deleted file mode 100644
index 0c5014cea1..0000000000
--- a/spree/core/lib/spree/testing_support/factories/adjustment_factory.rb
+++ /dev/null
@@ -1,28 +0,0 @@
-FactoryBot.define do
- factory :adjustment, class: Spree::Adjustment do
- association(:adjustable, factory: :order)
- association(:source, factory: :tax_rate)
-
- amount { 100.0 }
- label { 'Shipping' }
- eligible { true }
- end
-
- factory :tax_adjustment, class: Spree::Adjustment do
- association(:adjustable, factory: :line_item)
- association(:source, factory: :tax_rate)
-
- amount { 10.0 }
- label { 'VAT 5%' }
- eligible { true }
-
- after(:create) do |adjustment|
- # Set correct tax category, so that adjustment amount is not 0
- if adjustment.adjustable.is_a?(Spree::LineItem)
- adjustment.source.tax_category = adjustment.adjustable.tax_category
- adjustment.source.save
- adjustment.update!
- end
- end
- end
-end
diff --git a/spree/core/lib/spree/testing_support/factories/calculator_factory.rb b/spree/core/lib/spree/testing_support/factories/calculator_factory.rb
index 19eea18943..00346f9704 100644
--- a/spree/core/lib/spree/testing_support/factories/calculator_factory.rb
+++ b/spree/core/lib/spree/testing_support/factories/calculator_factory.rb
@@ -7,9 +7,6 @@ FactoryBot.define do
preferred_amount { 0 }
end
- factory :default_tax_calculator, class: Spree::Calculator::DefaultTax do
- end
-
factory :shipping_calculator, class: Spree::Calculator::Shipping::FlatRate do
preferred_amount { 10.0 }
end
diff --git a/spree/core/lib/spree/testing_support/factories/customer_return_factory.rb b/spree/core/lib/spree/testing_support/factories/customer_return_factory.rb
index b3c499c079..068e23465d 100644
--- a/spree/core/lib/spree/testing_support/factories/customer_return_factory.rb
+++ b/spree/core/lib/spree/testing_support/factories/customer_return_factory.rb
@@ -21,7 +21,7 @@ FactoryBot.define do
before(:create) do |customer_return, evaluator|
shipped_order = create(:shipped_order, line_items_count: evaluator.line_items_count, store: customer_return.store)
- shipped_order.inventory_units.take(evaluator.return_items_count).each do |inventory_unit|
+ shipped_order.fulfillment_items.take(evaluator.return_items_count).each do |inventory_unit|
customer_return.return_items << build(:return_item, inventory_unit: inventory_unit)
end
end
diff --git a/spree/core/lib/spree/testing_support/factories/discount_factory.rb b/spree/core/lib/spree/testing_support/factories/discount_factory.rb
new file mode 100644
index 0000000000..017f67f1c7
--- /dev/null
+++ b/spree/core/lib/spree/testing_support/factories/discount_factory.rb
@@ -0,0 +1,9 @@
+FactoryBot.define do
+ factory :discount, class: Spree::Discount do
+ line_item { fulfillment ? nil : create(:order_with_line_items, line_items_count: 1).line_items.first }
+ order { line_item&.order || fulfillment&.order }
+ amount { -5.0 }
+ label { 'Discount' }
+ kind { 'manual' }
+ end
+end
diff --git a/spree/core/lib/spree/testing_support/factories/fee_factory.rb b/spree/core/lib/spree/testing_support/factories/fee_factory.rb
new file mode 100644
index 0000000000..ed3b6d00b9
--- /dev/null
+++ b/spree/core/lib/spree/testing_support/factories/fee_factory.rb
@@ -0,0 +1,8 @@
+FactoryBot.define do
+ factory :fee, class: Spree::Fee do
+ association :order
+ amount { 5.0 }
+ label { 'Handling fee' }
+ kind { 'handling' }
+ 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 e266505e12..9ef17950d1 100644
--- a/spree/core/lib/spree/testing_support/factories/order_factory.rb
+++ b/spree/core/lib/spree/testing_support/factories/order_factory.rb
@@ -67,7 +67,7 @@ FactoryBot.define do
stock_location = order.line_items&.first&.variant&.stock_items&.first&.stock_location || create(:stock_location)
create(:shipment, order: order, cost: evaluator.shipment_cost, stock_location: stock_location)
- order.shipments.reload
+ order.fulfillments.reload
order.update_with_updater!
end
@@ -108,8 +108,8 @@ FactoryBot.define do
after(:create) do |order, evaluator|
create(:payment, amount: order.total, order: order, state: 'completed') if evaluator.with_payment
- order.shipments.each do |shipment|
- shipment.inventory_units.update_all state: 'on_hand'
+ order.fulfillments.each do |shipment|
+ shipment.fulfillment_items.update_all state: 'on_hand'
shipment.update_column('state', 'ready')
end
order.reload
diff --git a/spree/core/lib/spree/testing_support/factories/promotion_action_factory.rb b/spree/core/lib/spree/testing_support/factories/promotion_action_factory.rb
index de49278899..5a98042983 100644
--- a/spree/core/lib/spree/testing_support/factories/promotion_action_factory.rb
+++ b/spree/core/lib/spree/testing_support/factories/promotion_action_factory.rb
@@ -3,12 +3,12 @@ FactoryBot.define do
association :promotion
end
- factory :promotion_action_create_adjustment, class: Spree::Promotion::Actions::CreateAdjustment do
+ factory :promotion_action_create_adjustment, class: Spree::PromotionActions::CreateAdjustment do
association :promotion
association :calculator, factory: :flat_rate_calculator
end
- factory :promotion_action_create_line_items, class: Spree::Promotion::Actions::CreateLineItems do
+ factory :promotion_action_create_line_items, class: Spree::PromotionActions::CreateLineItems do
association :promotion
end
end
diff --git a/spree/core/lib/spree/testing_support/factories/promotion_factory.rb b/spree/core/lib/spree/testing_support/factories/promotion_factory.rb
index 0998179bcf..b73cd07971 100644
--- a/spree/core/lib/spree/testing_support/factories/promotion_factory.rb
+++ b/spree/core/lib/spree/testing_support/factories/promotion_factory.rb
@@ -30,7 +30,7 @@ FactoryBot.define do
after(:create) do |promotion, evaluator|
calculator = Spree::Calculator::FlatRate.new
calculator.preferred_amount = evaluator.adjustment_rate
- Spree::Promotion::Actions::CreateItemAdjustments.create!(calculator: calculator, promotion: promotion)
+ Spree::PromotionActions::CreateItemDiscounts.create!(calculator: calculator, promotion: promotion)
end
end
@@ -52,7 +52,7 @@ FactoryBot.define do
after(:create) do |promotion, evaluator|
calculator = Spree::Calculator::FlatRate.new
calculator.preferred_amount = evaluator.weighted_order_adjustment_amount
- Spree::Promotion::Actions::CreateAdjustment.create!(calculator: calculator, promotion: promotion)
+ Spree::PromotionActions::CreateAdjustment.create!(calculator: calculator, promotion: promotion)
end
end
@@ -63,7 +63,7 @@ FactoryBot.define do
name { 'Free Shipping Promotion' }
after(:create) do |promotion|
- Spree::Promotion::Actions::FreeShipping.create!(promotion: promotion)
+ Spree::PromotionActions::FreeShipping.create!(promotion: promotion)
end
factory :free_shipping_promotion_with_item_total_rule, traits: [:with_item_total_rule]
diff --git a/spree/core/lib/spree/testing_support/factories/tax_line_factory.rb b/spree/core/lib/spree/testing_support/factories/tax_line_factory.rb
new file mode 100644
index 0000000000..b8ec34f8be
--- /dev/null
+++ b/spree/core/lib/spree/testing_support/factories/tax_line_factory.rb
@@ -0,0 +1,11 @@
+FactoryBot.define do
+ factory :tax_line, class: Spree::TaxLine do
+ line_item { create(:order_with_line_items, line_items_count: 1).line_items.first }
+ order { line_item&.order || fulfillment&.order || fee&.order }
+ amount { 1.0 }
+ rate { 0.05 }
+ label { 'Tax 5%' }
+ included { false }
+ provider_id { 'internal' }
+ end
+end
diff --git a/spree/core/lib/spree/testing_support/factories/tax_rate_factory.rb b/spree/core/lib/spree/testing_support/factories/tax_rate_factory.rb
index 9a58ebbb3c..e97238ff10 100644
--- a/spree/core/lib/spree/testing_support/factories/tax_rate_factory.rb
+++ b/spree/core/lib/spree/testing_support/factories/tax_rate_factory.rb
@@ -4,7 +4,5 @@ FactoryBot.define do
zone
tax_category
amount { 0.1 }
-
- association(:calculator, factory: :default_tax_calculator)
end
end
diff --git a/spree/core/lib/tasks/categories_and_collections.rake b/spree/core/lib/tasks/categories_and_collections.rake
index 2fcf86bef9..7db7bca910 100644
--- a/spree/core/lib/tasks/categories_and_collections.rake
+++ b/spree/core/lib/tasks/categories_and_collections.rake
@@ -163,7 +163,8 @@ namespace :spree do
# surviving categories keep their rich-text description without this.
[ActionText::RichText, :record_type, 'Spree::Taxon', 'Spree::Category'],
[FriendlyId::Slug, :sluggable_type, 'Spree::Taxon', 'Spree::Category'],
- [Spree::PromotionRule, :type, 'Spree::Promotion::Rules::Taxon', 'Spree::Promotion::Rules::Category']
+ [Spree::PromotionRule, :type, 'Spree::Promotion::Rules::Taxon', 'Spree::Promotion::Rules::Category'],
+ [Spree::PromotionRule, :type, 'Spree::PromotionRules::Taxon', 'Spree::PromotionRules::Category']
].each do |model, column, from, to|
count = model.where(column => from).update_all(column => to)
puts " #{model.table_name}.#{column}: #{count} rows #{from} -> #{to}"
diff --git a/spree/core/spec/lib/spree/core_environment_spec.rb b/spree/core/spec/lib/spree/core_environment_spec.rb
index f43e3ec84f..5def77168b 100644
--- a/spree/core/spec/lib/spree/core_environment_spec.rb
+++ b/spree/core/spec/lib/spree/core_environment_spec.rb
@@ -130,11 +130,6 @@ RSpec.describe 'Spree environment accessors' do
expect(Spree.calculators.shipping_methods).to include(Spree::Calculator::Shipping::FlatRate)
end
- it 'allows access to calculators.tax_rates' do
- expect(Spree.calculators.tax_rates).to eq(Rails.application.config.spree.calculators.tax_rates)
- expect(Spree.calculators.tax_rates).to be_an(Array)
- end
-
it 'allows access to promotions.rules' do
expect(Spree.promotions.rules).to eq(Rails.application.config.spree.promotions.rules)
expect(Spree.promotions.rules).to be_an(Array)
diff --git a/spree/core/spec/lib/tasks/categories_and_collections_spec.rb b/spree/core/spec/lib/tasks/categories_and_collections_spec.rb
index 13c8ad9b63..dc768592b9 100644
--- a/spree/core/spec/lib/tasks/categories_and_collections_spec.rb
+++ b/spree/core/spec/lib/tasks/categories_and_collections_spec.rb
@@ -83,14 +83,14 @@ describe 'spree:migrate_taxons_to_categories_and_collections' do
create(:metafield).tap { |m| m.update_column(:resource_type, 'Spree::Taxon') }
end
let!(:promotion_rule) do
- create(:promotion_rule_taxon).tap { |r| r.update_column(:type, 'Spree::Promotion::Rules::Taxon') }
+ create(:promotion_rule_taxon).tap { |r| r.update_column(:type, 'Spree::PromotionRules::Taxon') }
end
it 'rewrites Spree::Taxon* strings to Spree::Category*' do
subject.invoke
expect(metafield.reload.resource_type).to eq('Spree::Category')
- expect(Spree::PromotionRule.where(id: promotion_rule.id).pick(:type)).to eq('Spree::Promotion::Rules::Category')
+ expect(Spree::PromotionRule.where(id: promotion_rule.id).pick(:type)).to eq('Spree::PromotionRules::Category')
end
end
diff --git a/spree/core/spec/models/spree/adjustable/adjuster/base_spec.rb b/spree/core/spec/models/spree/adjustable/adjuster/base_spec.rb
deleted file mode 100644
index 4cac0dd430..0000000000
--- a/spree/core/spec/models/spree/adjustable/adjuster/base_spec.rb
+++ /dev/null
@@ -1,10 +0,0 @@
-require 'spec_helper'
-
-describe Spree::Adjustable::Adjuster::Base, type: :model do
- let(:line_item) { create(:line_item) }
- let(:subject) { Spree::Adjustable::Adjuster::Base }
-
- it 'raises missing update method' do
- expect { subject.adjust(line_item, {}) }.to raise_error(NotImplementedError)
- end
-end
diff --git a/spree/core/spec/models/spree/adjustable/adjuster/promotion_spec.rb b/spree/core/spec/models/spree/adjustable/adjuster/promotion_spec.rb
deleted file mode 100644
index b0b863bd6a..0000000000
--- a/spree/core/spec/models/spree/adjustable/adjuster/promotion_spec.rb
+++ /dev/null
@@ -1,220 +0,0 @@
-require 'spec_helper'
-
-class CustomPromotionAction < Spree::PromotionAction
- include Spree::AdjustmentSource
-end
-
-describe Spree::Adjustable::Adjuster::Promotion, type: :model do
- let(:order) { create :order_with_line_items, line_items_count: 1 }
- let(:line_item) { order.line_items.first }
- let(:subject) { Spree::Adjustable::AdjustmentsUpdater.new(line_item) }
- let(:order_subject) { Spree::Adjustable::AdjustmentsUpdater.new(order) }
-
- context 'best promotion is always applied' do
- let(:calculator) { Spree::Calculator::FlatRate.new(preferred_amount: 10) }
- let(:promotion) { create(:promotion) }
- let(:source) { Spree::Promotion::Actions::CreateItemAdjustments.create!(calculator: calculator, promotion: promotion) }
-
- def create_adjustment(label, amount)
- create(:adjustment,
- order: order,
- adjustable: line_item,
- source: source,
- amount: amount,
- state: 'closed',
- label: label,
- mandatory: false)
- end
-
- describe 'competing promos' do
- before { Spree::Adjustment.competing_promos_source_types = ['Spree::PromotionAction', 'CustomPromotionAction'] }
-
- it 'do not update promo_total' do
- create(:adjustment,
- order: order,
- adjustable: line_item,
- source_type: 'CustomPromotionAction',
- source_id: nil,
- amount: -3.50,
- label: 'Other',
- mandatory: false)
- create_adjustment('Promotion A', -2.50)
-
- subject.update
- expect(line_item.promo_total).to eq(0.0)
- end
- end
-
- it 'uses only the most valuable promotion' do
- create_adjustment('Promotion A', -100)
- create_adjustment('Promotion B', -200)
- create_adjustment('Promotion C', -300)
- create(:adjustment,
- order: order,
- adjustable: line_item,
- source: nil,
- amount: -500,
- state: 'closed',
- label: 'Some other credit')
- line_item.adjustments.each { |a| a.update_column(:eligible, true) }
-
- subject.update
-
- expect(line_item.adjustments.promotion.eligible.count).to eq(1)
- expect(line_item.adjustments.promotion.eligible.first.label).to eq('Promotion C')
- end
-
- it 'chooses the most recent promotion adjustment when amounts are equal' do
- # Using Timecop is a regression test
- Timecop.freeze do
- create_adjustment('Promotion A', -200)
- create_adjustment('Promotion B', -200)
- end
- line_item.adjustments.each { |a| a.update_column(:eligible, true) }
-
- subject.update
-
- expect(line_item.adjustments.promotion.eligible.count).to eq(1)
- expect(line_item.adjustments.promotion.eligible.first.label).to eq('Promotion B')
- end
-
- context 'when previously ineligible promotions become available' do
- let(:order_promo1) do
- create(:promotion,
- :with_order_adjustment,
- :with_item_total_rule,
- kind: :automatic,
- weighted_order_adjustment_amount: 5,
- item_total_threshold_amount: 10)
- end
-
- let(:order_promo2) do
- create(:promotion,
- :with_order_adjustment,
- :with_item_total_rule,
- kind: :automatic,
- weighted_order_adjustment_amount: 10,
- item_total_threshold_amount: 20)
- end
-
- let(:order_promos) { [order_promo1, order_promo2] }
-
- let(:line_item_promo1) do
- create(:promotion,
- :with_line_item_adjustment,
- :with_item_total_rule,
- kind: :automatic,
- adjustment_rate: 2.5,
- item_total_threshold_amount: 10)
- end
-
- let(:line_item_promo2) do
- create(:promotion,
- :with_line_item_adjustment,
- :with_item_total_rule,
- kind: :automatic,
- adjustment_rate: 5,
- item_total_threshold_amount: 20)
- end
-
- let(:line_item_promos) { [line_item_promo1, line_item_promo2] }
- let(:order) { create(:order_with_line_items, line_items_count: 1) }
-
- # Apply promotions in different sequences. Results should be the same.
- promo_sequences = [[0, 1], [1, 0]]
-
- promo_sequences.each do |promo_sequence|
- it 'picks the best order-level promo according to current eligibility' do
- # apply both promos to the order, even though only promo1 is eligible
- order_promos[promo_sequence[0]].activate order: order
- order_promos[promo_sequence[1]].activate order: order
-
- order.reload
- msg = "Expected two adjustments (using sequence #{promo_sequence})"
- expect(order.all_adjustments.count).to eq(2), msg
-
- msg = "Expected one eligible adjustment (using sequence #{promo_sequence})"
- expect(order.all_adjustments.eligible.count).to eq(1), msg
-
- msg = "Expected promo1 to be used (using sequence #{promo_sequence})"
- expect(order.all_adjustments.eligible.first.source.promotion).to eq(order_promo1), msg
-
- Spree::Carts::AddItem.call(order: order, variant: create(:variant, price: 10))
- order.save
-
- order.reload
- msg = "Expected two adjustments (using sequence #{promo_sequence})"
- expect(order.all_adjustments.count).to eq(2), msg
-
- msg = "Expected one eligible adjustment (using sequence #{promo_sequence})"
- expect(order.all_adjustments.eligible.count).to eq(1), msg
-
- msg = "Expected promo2 to be used (using sequence #{promo_sequence})"
- expect(order.all_adjustments.eligible.first.source.promotion).to eq(order_promo2), msg
- end
- end
-
- promo_sequences.each do |promo_sequence|
- it 'picks the best line-item-level promo according to current eligibility' do
- # apply both promos to the order, even though only promo1 is eligible
- line_item_promos[promo_sequence[0]].reload.activate order: order
- line_item_promos[promo_sequence[1]].reload.activate order: order
-
- order.reload
- msg = "Expected one adjustment (using sequence #{promo_sequence})"
- expect(order.all_adjustments.count).to eq(1), msg
-
- msg = "Expected one eligible adjustment (using sequence #{promo_sequence})"
- expect(order.all_adjustments.eligible.count).to eq(1), msg
-
- # line_item_promo1 is the only one that has thus far met the order total threshold,
- # it is the only promo which should be applied.
- msg = "Expected line_item_promo1 to be used (using sequence #{promo_sequence})"
- expect(order.all_adjustments.first.source.promotion).to eq(line_item_promo1), msg
-
- Spree::Carts::AddItem.call(order: order, variant: create(:variant, price: 10))
- order.save
-
- order.reload
- msg = "Expected four adjustments (using sequence #{promo_sequence})"
- expect(order.all_adjustments.count).to eq(4), msg
-
- msg = "Expected two eligible adjustments (using sequence #{promo_sequence})"
- expect(order.all_adjustments.eligible.count).to eq(2), msg
-
- order.all_adjustments.eligible.each do |adjustment|
- msg = "Expected line_item_promo2 to be used (using sequence #{promo_sequence})"
- expect(adjustment.source.promotion).to eq(line_item_promo2), msg
- end
- end
- end
- end
-
- context 'multiple adjustments and the best one is not eligible' do
- let!(:promo_a) { create_adjustment('Promotion A', -100) }
- let!(:promo_c) { create_adjustment('Promotion C', -300) }
-
- before do
- promo_a.update_column(:eligible, true)
- promo_c.update_column(:eligible, false)
- end
-
- # regression for #3274
- it 'still makes the previous best eligible adjustment valid' do
- subject.update
- expect(line_item.adjustments.promotion.eligible.first.label).to eq('Promotion A')
- end
- end
-
- it 'only leaves one adjustment even if 2 have the same amount' do
- create_adjustment('Promotion A', -100)
- create_adjustment('Promotion B', -200)
- create_adjustment('Promotion C', -200)
-
- subject.update
-
- expect(line_item.adjustments.promotion.eligible.count).to eq(1)
- expect(line_item.adjustments.promotion.eligible.first.amount.to_i).to eq(-200)
- end
- end
-end
diff --git a/spree/core/spec/models/spree/adjustable/adjuster/tax_spec.rb b/spree/core/spec/models/spree/adjustable/adjuster/tax_spec.rb
deleted file mode 100644
index c0464fc903..0000000000
--- a/spree/core/spec/models/spree/adjustable/adjuster/tax_spec.rb
+++ /dev/null
@@ -1,86 +0,0 @@
-require 'spec_helper'
-
-describe Spree::Adjustable::Adjuster::Tax, type: :model do
- let(:order) { create :order_with_line_items, line_items_count: 1 }
- let(:line_item) { order.line_items.first }
-
- let(:subject) { Spree::Adjustable::AdjustmentsUpdater.new(line_item) }
- let(:order_subject) { Spree::Adjustable::AdjustmentsUpdater.new(order) }
-
- context 'taxes with promotions' do
- let!(:tax_rate) do
- create(:tax_rate, amount: 0.05)
- end
-
- let!(:promotion) do
- create(:promotion, name: '$10 off')
- end
-
- let!(:promotion_action) do
- calculator = Spree::Calculator::FlatRate.new(preferred_amount: 10)
- Spree::Promotion::Actions::CreateItemAdjustments.create(calculator: calculator,
- promotion: promotion)
- end
-
- before do
- line_item.price = 20
- line_item.tax_category = tax_rate.tax_category
- line_item.save
- create(:adjustment, order: order, source: promotion_action, adjustable: line_item)
- end
-
- context 'tax included in price' do
- before do
- create(:adjustment,
- source: tax_rate,
- adjustable: line_item,
- order: order,
- included: true)
- end
-
- it 'tax has no bearing on final price' do
- subject.update
- line_item.reload
- expect(line_item.included_tax_total).to eq(0.5)
- expect(line_item.additional_tax_total).to eq(0)
- expect(line_item.promo_total).to eq(-10)
- expect(line_item.adjustment_total).to eq(-10)
- end
-
- it 'tax linked to order' do
- order_subject.update
- order.reload
- expect(order.included_tax_total).to eq(0.5)
- expect(order.additional_tax_total).to eq(0o0)
- end
- end
-
- context 'tax excluded from price' do
- before do
- create(:adjustment,
- source: tax_rate,
- adjustable: line_item,
- order: order,
- included: false)
- end
-
- it 'tax applies to line item' do
- subject.update
- line_item.reload
- # Taxable amount is: $20 (base) - $10 (promotion) = $10
- # Tax rate is 5% (of $10).
- expect(line_item.included_tax_total).to eq(0)
- expect(line_item.additional_tax_total).to eq(0.5)
- expect(line_item.promo_total).to eq(-10)
- expect(line_item.adjustment_total).to eq(-9.5)
- end
-
- it 'tax linked to order' do
- order_subject.update
- order.reload
- expect(order.included_tax_total).to eq(0)
- expect(order.additional_tax_total).to eq(0.5)
- end
- end
- end
-end
diff --git a/spree/core/spec/models/spree/adjustable/adjustments_updater_spec.rb b/spree/core/spec/models/spree/adjustable/adjustments_updater_spec.rb
deleted file mode 100644
index b52c8e1aac..0000000000
--- a/spree/core/spec/models/spree/adjustable/adjustments_updater_spec.rb
+++ /dev/null
@@ -1,105 +0,0 @@
-require 'spec_helper'
-
-module Spree
- module Adjustable
- describe AdjustmentsUpdater do
- let(:order) { create :order_with_line_items, line_items_count: 1 }
- let(:line_item) { order.line_items.first }
- let(:tax_rate) { create(:tax_rate, amount: 0.05) }
-
- let(:promotion) { create(:promotion, :with_line_item_adjustment, adjustment_rate: 2) }
- let(:promotion_action) { promotion.actions.first }
-
- describe '#update' do
- let(:promo_total) { -2 }
- let(:tax_total) { 0.4 }
-
- let(:adjustments) do
- [
- create(:adjustment, order: order, source: promotion_action, adjustable: line_item),
- create(:adjustment, order: order, source: tax_rate, adjustable: line_item)
- ]
- end
-
- context 'persisted object' do
- subject { AdjustmentsUpdater.new(line_item) }
-
- it 'updates all linked adjusters' do
- adjustments
-
- line_item.price = 10
- line_item.tax_category = tax_rate.tax_category
- line_item.adjustment_total = 0
- line_item.additional_tax_total = 0
- old_updated_at = line_item.updated_at
-
- subject.update
- expect(line_item.promo_total).to eq(promo_total)
- expect(line_item.additional_tax_total).to eq(tax_total)
- expect(line_item.adjustment_total).to eq(tax_total + promo_total)
- expect(line_item.updated_at).not_to eq(old_updated_at)
-
- old_updated_at = line_item.updated_at
-
- subject.update
- # skipping the update because the totals have not changed
- line_item.reload
- expect(line_item.promo_total).to eq(promo_total)
- expect(line_item.additional_tax_total).to eq(tax_total)
- expect(line_item.adjustment_total).to eq(tax_total + promo_total)
- expect(line_item.updated_at).to eq(old_updated_at)
- end
-
- context 'when there is no tax adjuster' do
- before do
- allow(Rails.application.config.spree).to receive(:adjusters).and_return([Spree::Adjustable::Adjuster::Promotion])
- end
-
- it 'updates all linked adjusters without tax' do
- adjustments
-
- line_item.price = 10
- line_item.tax_category = tax_rate.tax_category
- line_item.adjustment_total = 0
- line_item.additional_tax_total = 0
- old_updated_at = line_item.updated_at
-
- subject.update
- expect(line_item.promo_total).to eq(promo_total)
- expect(line_item.additional_tax_total).to eq(0)
- expect(line_item.adjustment_total).to eq(promo_total)
- expect(line_item.updated_at).not_to eq(old_updated_at)
-
- old_updated_at = line_item.updated_at
-
- subject.update
- # skipping the update because the totals have not changed
- line_item.reload
- expect(line_item.promo_total).to eq(promo_total)
- expect(line_item.additional_tax_total).to eq(0)
- expect(line_item.adjustment_total).to eq(promo_total)
- expect(line_item.updated_at).to eq(old_updated_at)
- end
- end
- end
-
- context 'non-persisted object' do
- let(:new_line_item) { order.line_items.new }
- let(:subject) { AdjustmentsUpdater.new(new_line_item) }
-
- it 'does nothing' do
- expect { subject.update }.not_to change(new_line_item, :adjustment_total)
- end
- end
-
- context 'nil' do
- let(:subject) { AdjustmentsUpdater.new(nil) }
-
- it 'does not raise an error' do
- expect { subject.update }.not_to raise_error
- end
- end
- end
- end
- end
-end
diff --git a/spree/core/spec/models/spree/adjusters/promotion_spec.rb b/spree/core/spec/models/spree/adjusters/promotion_spec.rb
new file mode 100644
index 0000000000..62c11a684a
--- /dev/null
+++ b/spree/core/spec/models/spree/adjusters/promotion_spec.rb
@@ -0,0 +1,111 @@
+require 'spec_helper'
+
+describe Spree::Adjusters::Promotion, type: :model do
+ let(:order) { create(:order_with_line_items, line_items_count: 2) }
+ let(:store) { order.store }
+
+ def line_promo(rate, code: nil)
+ kind = code ? :coupon_code : :automatic
+ create(:promotion_with_item_adjustment, adjustment_rate: rate, code: code, kind: kind, stores: [store])
+ end
+
+ it 'writes a discount row per line item for an applied promotion' do
+ promo = line_promo(5)
+ promo.activate(order: order)
+
+ rows = order.discounts.reload
+ expect(rows.size).to eq(2)
+ expect(rows.map(&:amount)).to all(eq(-5))
+ expect(rows.map(&:kind).uniq).to eq(['promotion'])
+ expect(rows.map(&:promotion_id).uniq).to eq([promo.id])
+ end
+
+ it 'keeps only the winning promotion per line item' do
+ weak = line_promo(2)
+ strong = line_promo(7)
+ weak.activate(order: order)
+ strong.activate(order: order)
+ described_class.adjust(order)
+
+ rows = order.discounts.reload
+ expect(rows.map(&:promotion_id).uniq).to eq([strong.id])
+ expect(rows.map(&:amount)).to all(eq(-7))
+ end
+
+ it 'reinstates the losing promotion when the winner stops being eligible' do
+ weak = line_promo(2)
+ strong = line_promo(7)
+ weak.activate(order: order)
+ strong.activate(order: order)
+ described_class.adjust(order)
+
+ strong.update!(expires_at: 1.day.ago, starts_at: 2.days.ago)
+ described_class.adjust(order)
+
+ rows = order.discounts.reload
+ expect(rows.map(&:promotion_id).uniq).to eq([weak.id])
+ expect(rows.map(&:amount)).to all(eq(-2))
+ end
+
+ it 'removes rows whose promotion was deleted' do
+ promo = line_promo(5)
+ promo.activate(order: order)
+ expect(order.discounts.reload.size).to eq(2)
+
+ promo.promotion_actions.each { |action| action.update_column(:deleted_at, Time.current) }
+ order.order_promotions.destroy_all
+ described_class.adjust(order)
+
+ expect(order.discounts.reload).to be_empty
+ end
+
+ it 'clamps so a line never goes below zero' do
+ promo = create(:promotion, kind: :automatic, code: nil, stores: [store])
+ action = Spree::PromotionActions::CreateItemDiscounts.create!(
+ promotion: promo,
+ calculator: Spree::Calculator::FlatRate.new(preferred_amount: 999)
+ )
+ promo.activate(order: order)
+
+ order.discounts.reload.each do |row|
+ expect(row.amount).to eq(-row.line_item.amount)
+ end
+ expect(action.reload).to be_present
+ end
+
+ describe 'order-level distribution' do
+ let(:order) { create(:order_with_line_items, line_items_count: 3) }
+
+ it 'distributes the winner across line items with largest-remainder' do
+ promo = create(:promotion_with_order_adjustment, weighted_order_adjustment_amount: 10, code: nil, kind: :automatic, stores: [store])
+ promo.activate(order: order)
+
+ rows = order.discounts.reload
+ expect(rows.size).to eq(3)
+ expect(rows.sum(&:amount)).to eq(-10)
+ expect(rows.map(&:line_item_id)).to match_array(order.line_items.ids)
+ end
+
+ it 'never distributes more than the remaining line bases' do
+ promo = create(:promotion_with_order_adjustment, weighted_order_adjustment_amount: 9_999, code: nil, kind: :automatic, stores: [store])
+ promo.activate(order: order)
+
+ expect(order.discounts.reload.sum(&:amount)).to eq(-order.line_items.sum(&:amount))
+ end
+ end
+
+ describe 'free shipping' do
+ let(:order) { create(:order_with_line_items, line_items_count: 1) }
+
+ it 'persists a fulfillment discount even at zero cost' do
+ order.fulfillments.each { |fulfillment| fulfillment.update_column(:cost, 0) }
+ promo = create(:free_shipping_promotion, code: nil, kind: :automatic, stores: [store])
+ promo.activate(order: order)
+
+ rows = order.discounts.reload.select(&:fulfillment_id)
+ expect(rows.size).to eq(order.fulfillments.count)
+ expect(rows.map(&:amount)).to all(eq(0))
+ expect(order.has_free_shipping?).to be(true)
+ end
+ end
+end
diff --git a/spree/core/spec/models/spree/adjustment_spec.rb b/spree/core/spec/models/spree/adjustment_spec.rb
deleted file mode 100644
index 70b1d5002a..0000000000
--- a/spree/core/spec/models/spree/adjustment_spec.rb
+++ /dev/null
@@ -1,234 +0,0 @@
-require 'spec_helper'
-
-describe Spree::Adjustment, type: :model do
- let(:order) { Spree::Order.new }
- let(:adjustment) { Spree::Adjustment.create!(label: 'Adjustment', adjustable: order, order: order, amount: 5) }
-
- before do
- allow(order).to receive(:update_with_updater!)
- end
-
- describe '#amount=' do
- let(:amount) { '1,599,99' }
-
- before { adjustment.amount = amount }
-
- it 'is expected to equal to localized number' do
- expect(adjustment.amount).to eq(Spree::LocalizedNumber.parse(amount))
- end
- end
-
- describe 'scopes' do
- describe '.for_complete_order' do
- subject { Spree::Adjustment.for_complete_order }
-
- let(:complete_order) { Spree::Order.create! completed_at: Time.current }
- let(:incomplete_order) { Spree::Order.create! completed_at: nil }
- let(:adjustment_for_complete_order) { Spree::Adjustment.create!(label: 'Adjustment', adjustable: complete_order, order: complete_order, amount: 5) }
- let(:adjustment_for_incomplete_order) { Spree::Adjustment.create!(label: 'Adjustment', adjustable: incomplete_order, order: incomplete_order, amount: 5) }
-
- it { is_expected.to include(adjustment_for_complete_order) }
- it { is_expected.not_to include(adjustment_for_incomplete_order) }
- end
-
- describe '.for_incomplete_order' do
- subject { Spree::Adjustment.for_incomplete_order }
-
- let(:complete_order) { Spree::Order.create! completed_at: Time.current }
- let(:incomplete_order) { Spree::Order.create! completed_at: nil }
- let(:adjustment_for_complete_order) { Spree::Adjustment.create!(label: 'Adjustment', adjustable: complete_order, order: complete_order, amount: 5) }
- let(:adjustment_for_incomplete_order) { Spree::Adjustment.create!(label: 'Adjustment', adjustable: incomplete_order, order: incomplete_order, amount: 5) }
-
- it { is_expected.not_to include(adjustment_for_complete_order) }
- it { is_expected.to include(adjustment_for_incomplete_order) }
- end
- end
-
- context '#create & #destroy' do
- let(:adjustment) { Spree::Adjustment.new(label: 'Adjustment', amount: 5, order: order, adjustable: create(:line_item)) }
-
- it 'calls #update_adjustable_adjustment_total' do
- expect(adjustment).to receive(:update_adjustable_adjustment_total).twice
- adjustment.save
- adjustment.destroy
- end
- end
-
- context '#save' do
- let(:order) { create(:order) }
- let!(:adjustment) { Spree::Adjustment.create(label: 'Adjustment', amount: 5, order: order, adjustable: order) }
-
- it 'touches the adjustable' do
- expect(adjustment.adjustable).to receive(:touch)
- adjustment.amount = 3
- adjustment.save
- end
- end
-
- describe 'non_tax scope' do
- subject do
- Spree::Adjustment.non_tax.to_a
- end
-
- let!(:tax_adjustment) { create(:adjustment, order: order, source: create(:tax_rate)) }
- let!(:non_tax_adjustment_with_source) { create(:adjustment, order: order, source_type: 'Spree::Order', source_id: nil) }
- let!(:non_tax_adjustment_without_source) { create(:adjustment, order: order, source: nil) }
-
- it 'select non-tax adjustments' do
- expect(subject).not_to include tax_adjustment
- expect(subject).to include non_tax_adjustment_with_source
- expect(subject).to include non_tax_adjustment_without_source
- end
- end
-
- describe 'competing_promos scope' do
- subject do
- Spree::Adjustment.competing_promos.to_a
- end
-
- before do
- allow_any_instance_of(Spree::Adjustment).to receive(:update_adjustable_adjustment_total).and_return(true)
- end
-
- let!(:promotion_adjustment) { create(:adjustment, order: order, source_type: 'Spree::PromotionAction', source_id: nil) }
- let!(:custom_adjustment_with_source) { create(:adjustment, order: order, source_type: 'Custom', source_id: nil) }
- let!(:non_promotion_adjustment_with_source) { create(:adjustment, order: order, source_type: 'Spree::Order', source_id: nil) }
- let!(:non_promotion_adjustment_without_source) { create(:adjustment, order: order, source: nil) }
-
- context 'no custom source_types have been added to competing_promos' do
- before { Spree::Adjustment.competing_promos_source_types = ['Spree::PromotionAction'] }
-
- it 'selects promotion adjustments by default' do
- expect(subject).to include promotion_adjustment
- expect(subject).not_to include custom_adjustment_with_source
- expect(subject).not_to include non_promotion_adjustment_with_source
- expect(subject).not_to include non_promotion_adjustment_without_source
- end
- end
-
- context 'a custom source_type has been added to competing_promos' do
- before { Spree::Adjustment.competing_promos_source_types = ['Spree::PromotionAction', 'Custom'] }
-
- it 'selects adjustments with registered source_types' do
- expect(subject).to include promotion_adjustment
- expect(subject).to include custom_adjustment_with_source
- expect(subject).not_to include non_promotion_adjustment_with_source
- expect(subject).not_to include non_promotion_adjustment_without_source
- end
- end
- end
-
- context 'adjustment state' do
- let(:adjustment) { create(:adjustment, order: order, state: 'open') }
-
- context '#closed?' do
- it 'is true when adjustment state is closed' do
- adjustment.state = 'closed'
- expect(adjustment).to be_closed
- end
-
- it 'is false when adjustment state is open' do
- adjustment.state = 'open'
- expect(adjustment).not_to be_closed
- end
- end
- end
-
- context '#currency' do
- let(:order) { Spree::Order.new(currency: 'EUR') }
-
- it 'returns the order currency' do
- expect(adjustment.currency).to eq 'EUR'
- end
- end
-
- context '#display_amount' do
- before { adjustment.amount = 10.55 }
-
- it 'shows the amount' do
- expect(adjustment.display_amount.to_s).to eq '$10.55'
- end
-
- context 'with currency set to JPY' do
- context 'when adjustable is set to an order' do
- before do
- expect(order).to receive(:currency).and_return('JPY')
- adjustment.adjustable = order
- end
-
- it 'displays in JPY' do
- expect(adjustment.display_amount.to_s).to eq '¥11'
- end
- end
-
- context 'when adjustable is nil' do
- it 'displays in the default currency' do
- expect(adjustment.display_amount.to_s).to eq '$10.55'
- end
- end
- end
- end
-
- context '#update!' do
- let(:adjustment) { Spree::Adjustment.create!(label: 'Adjustment', order: order, adjustable: order, amount: 5, state: state, source: source) }
- let(:source) { mock_model(Spree::TaxRate, compute_amount: 10) }
-
- subject { adjustment.update! }
-
- context "when adjustment is closed" do
- let(:state) { 'closed' }
-
- it "does not update the adjustment" do
- expect(adjustment).to_not receive(:update_column)
- subject
- end
- end
-
- context "when adjustment is open" do
- let(:state) { 'open' }
-
- it "updates the amount" do
- expect { subject }.to change { adjustment.amount }.to(10)
- end
-
- context "it is a promotion adjustment" do
- let(:promotion) { create(:promotion, :with_order_adjustment, code: promotion_code) }
- let(:promotion_code) { 'somecode' }
- let(:order1) { create(:order_with_line_items, line_items_count: 1) }
-
- let!(:adjustment) do
- promotion.activate(order: order1, promotion_code: promotion_code)
- expect(order1.adjustments.size).to eq 1
- order1.adjustments.first
- end
-
- context "the promotion is eligible" do
- it "sets the adjustment eligible to true" do
- subject
- expect(adjustment.eligible).to eq true
- end
- end
-
- context "the promotion is not eligible" do
- before { promotion.update!(starts_at: 1.day.from_now) }
-
- it "sets the adjustment eligible to false" do
- subject
- expect(adjustment.eligible).to eq false
- end
- end
- end
-
- context 'when amount and eligible are the same' do
- it "does not update the adjustment" do
- expect(adjustment).to_not receive(:update_column)
- adjustment.amount = 10
- adjustment.eligible = true
- subject
- expect(adjustment.amount).to eq(10)
- expect(adjustment.eligible).to eq(true)
- end
- end
- end
- end
-end
diff --git a/spree/core/spec/models/spree/calculator/default_tax_spec.rb b/spree/core/spec/models/spree/calculator/default_tax_spec.rb
deleted file mode 100644
index c7b4940e13..0000000000
--- a/spree/core/spec/models/spree/calculator/default_tax_spec.rb
+++ /dev/null
@@ -1,154 +0,0 @@
-require 'spec_helper'
-
-describe Spree::Calculator::DefaultTax, type: :model do
- let!(:country) { create(:country) }
- let!(:zone) { create(:zone, name: 'Country Zone', default_tax: true, zone_members: []) }
- let!(:tax_category) { create(:tax_category, tax_rates: []) }
- let!(:rate) { create(:tax_rate, tax_category: tax_category, amount: 0.05, included_in_price: included_in_price) }
- let(:included_in_price) { false }
- let!(:calculator) { Spree::Calculator::DefaultTax.new(calculable: rate) }
- let!(:order) { create(:order) }
- let!(:line_item) { create(:line_item, price: 10, quantity: 3, tax_category: tax_category) }
- let!(:shipment) { create(:shipment, cost: 15) }
-
- context '#compute' do
- context 'when given an order' do
- let!(:line_item_1) { line_item }
- let!(:line_item_2) { create(:line_item, price: 10, quantity: 3, tax_category: tax_category) }
-
- before do
- allow(order).to receive_messages line_items: [line_item_1, line_item_2]
- end
-
- context 'when no line items match the tax category' do
- before do
- line_item_1.tax_category = nil
- line_item_2.tax_category = nil
- end
-
- it 'is 0' do
- expect(calculator.compute(order)).to eq(0)
- end
- end
-
- context 'when one item matches the tax category' do
- before do
- line_item_1.tax_category = tax_category
- line_item_2.tax_category = nil
- end
-
- it 'is equal to the item total * rate' do
- expect(calculator.compute(order)).to eq(1.5)
- end
-
- context 'correctly rounds to within two decimal places' do
- before do
- line_item_1.price = 10.333
- line_item_1.quantity = 1
- end
-
- specify do
- # Amount is 0.51665, which will be rounded to...
- expect(calculator.compute(order)).to eq(0.52)
- end
- end
- end
-
- context 'when more than one item matches the tax category' do
- it 'is equal to the sum of the item totals * rate' do
- expect(calculator.compute(order)).to eq(3)
- end
- end
-
- context 'when tax is included in price' do
- let(:included_in_price) { true }
-
- it 'will return the deducted amount from the totals' do
- # total price including 5% tax = $60
- # ex pre-tax = $57.14
- # 57.14 + %5 = 59.997 (or "close enough" to $60)
- # 60 - 57.14 = $2.86
- expect(calculator.compute(order).to_f).to eq(2.86)
- end
- end
- end
-
- context 'when tax is included in price' do
- let(:included_in_price) { true }
-
- context 'when the variant matches the tax category' do
- context 'when line item is discounted' do
- before do
- line_item.taxable_adjustment_total = -1
- Spree::TaxRate.store_pre_tax_amount(line_item, [rate])
- end
-
- it "is equal to the item's discounted total * rate" do
- expect(calculator.compute(line_item)).to eq(1.38)
- end
- end
-
- it "is equal to the item's full price * rate" do
- Spree::TaxRate.store_pre_tax_amount(line_item, [rate])
- expect(calculator.compute(line_item)).to eq(1.43)
- end
- end
- end
-
- context 'when tax is not included in price' do
- context 'when the line item is discounted' do
- before { line_item.taxable_adjustment_total = -1 }
-
- it "is equal to the item's pre-tax total * rate" do
- expect(calculator.compute(line_item)).to eq(1.45)
- end
- end
-
- context 'when the variant matches the tax category' do
- it 'is equal to the item pre-tax total * rate' do
- expect(calculator.compute(line_item)).to eq(1.50)
- end
- end
- end
-
- context 'when given a shipment' do
- it 'is 5% of 15' do
- expect(calculator.compute(shipment)).to eq(0.75)
- end
-
- it 'takes discounts into consideration' do
- shipment.promo_total = -1
- # 5% of 14
- expect(calculator.compute(shipment)).to eq(0.7)
- end
- end
- end
-
- context 'when given a line_item' do
- subject do
- Spree::Calculator::DefaultTax.new(calculable: rate).
- compute_line_item(line_item)
- end
-
- let(:rate) { create(:tax_rate, amount: 0.07, included_in_price: true) }
- let(:line_item) { create(:line_item, quantity: 50, price: 8.50) }
-
- describe '#compute_line_item' do
- it 'computes the line item right' do
- Spree::TaxRate.store_pre_tax_amount(line_item, [rate])
- expect(subject).to eq(27.80)
- end
-
- context 'with a 40$ promo' do
- before do
- allow(line_item).to receive(:taxable_adjustment_total).and_return(BigDecimal('-40'))
- Spree::TaxRate.store_pre_tax_amount(line_item, [rate])
- end
-
- it 'computes the line item right' do
- expect(subject).to eq(25.19)
- end
- end
- end
- end
-end
diff --git a/spree/core/spec/models/spree/calculator/refunds/default_refund_amount_spec.rb b/spree/core/spec/models/spree/calculator/refunds/default_refund_amount_spec.rb
index 86f978e4e0..3a20133946 100644
--- a/spree/core/spec/models/spree/calculator/refunds/default_refund_amount_spec.rb
+++ b/spree/core/spec/models/spree/calculator/refunds/default_refund_amount_spec.rb
@@ -19,23 +19,29 @@ describe Spree::Calculator::Returns::DefaultRefundAmount, type: :model do
it { is_expected.to eq pre_tax_amount / line_item_quantity }
end
- context 'order adjustments' do
- let(:adjustment_amount) { -10.0 }
+ context 'with a discount on the line item' do
+ let(:discount_amount) { -10.0 }
before do
- order.adjustments << create(:adjustment, order: order, amount: adjustment_amount, eligible: true, label: 'Adjustment', source_type: 'Spree::Order')
- order.adjustments.first.update(amount: adjustment_amount)
+ create(:discount, order: order, line_item: line_item, amount: discount_amount, label: 'Discount', kind: 'manual')
+ order.update_with_updater!
+ line_item.reload
end
- it { is_expected.to eq (pre_tax_amount - adjustment_amount.abs) / line_item_quantity }
+ it { is_expected.to eq (pre_tax_amount - discount_amount.abs) / line_item_quantity }
end
- context 'shipping adjustments' do
- let(:adjustment_total) { -50.0 }
+ context 'with a fulfillment-level discount' do
+ let!(:shipment) { create(:shipment, order: order, cost: 50) }
- before { order.shipments << Spree::Shipment.new(adjustment_total: adjustment_total) }
+ before do
+ create(:discount, order: order, fulfillment: shipment, amount: -50, label: 'Free shipping', kind: 'promotion')
+ order.update_with_updater!
+ end
- it { is_expected.to eq pre_tax_amount / line_item_quantity }
+ it 'does not affect the line item refund' do
+ is_expected.to eq pre_tax_amount / line_item_quantity
+ end
end
end
diff --git a/spree/core/spec/models/spree/discount_spec.rb b/spree/core/spec/models/spree/discount_spec.rb
new file mode 100644
index 0000000000..89190c81f1
--- /dev/null
+++ b/spree/core/spec/models/spree/discount_spec.rb
@@ -0,0 +1,59 @@
+require 'spec_helper'
+
+describe Spree::Discount, type: :model do
+ let(:order) { create(:order_with_line_items, line_items_count: 1) }
+ let(:line_item) { order.line_items.first }
+
+ it 'is valid with an order owner and a line item adjustable' do
+ discount = described_class.new(order: order, line_item: line_item, amount: -2, label: 'Promo', kind: 'manual')
+ expect(discount).to be_valid
+ end
+
+ it 'requires exactly one owner' do
+ discount = described_class.new(line_item: line_item, amount: -2, label: 'Promo', kind: 'manual')
+ expect(discount).not_to be_valid
+ expect(discount.errors[:base]).to include(Spree.t('errors.messages.exactly_one_of_cart_or_order'))
+ end
+
+ it 'requires exactly one adjustable' do
+ discount = described_class.new(order: order, amount: -2, label: 'Promo', kind: 'manual')
+ expect(discount).not_to be_valid
+ expect(discount.errors[:base]).to include(Spree.t('errors.messages.exactly_one_adjustable'))
+
+ discount.line_item = line_item
+ discount.fulfillment = create(:fulfillment, order: order)
+ expect(discount).not_to be_valid
+ end
+
+ it 'rejects positive amounts' do
+ discount = described_class.new(order: order, line_item: line_item, amount: 2, label: 'Promo', kind: 'manual')
+ expect(discount).not_to be_valid
+ expect(discount.errors[:amount]).to be_present
+ end
+
+ it 'keeps provenance snapshots when the promotion is gone' do
+ discount = create(:discount, order: order, line_item: line_item, amount: -2, kind: 'promotion',
+ code: 'SUMMER10', value: 10, value_type: 'percent')
+ expect(discount.reload.code).to eq('SUMMER10')
+ expect(discount.promotion).to be_nil
+ end
+
+ describe 'scopes' do
+ let!(:line_discount) { create(:discount, order: order, line_item: line_item, kind: 'promotion') }
+ let!(:manual_discount) { create(:discount, order: order, line_item: line_item, kind: 'manual') }
+
+ it 'filters by kind and adjustable' do
+ expect(described_class.promotion).to contain_exactly(line_discount)
+ expect(described_class.manual).to contain_exactly(manual_discount)
+ expect(described_class.for_line_items).to contain_exactly(line_discount, manual_discount)
+ expect(described_class.for_fulfillments).to be_empty
+ end
+ end
+
+ describe '#owner' do
+ it 'returns the order' do
+ discount = build(:discount, order: order, line_item: line_item)
+ expect(discount.owner).to eq(order)
+ end
+ end
+end
diff --git a/spree/core/spec/models/spree/fee_spec.rb b/spree/core/spec/models/spree/fee_spec.rb
new file mode 100644
index 0000000000..a7c1b6e9db
--- /dev/null
+++ b/spree/core/spec/models/spree/fee_spec.rb
@@ -0,0 +1,36 @@
+require 'spec_helper'
+
+describe Spree::Fee, type: :model do
+ let(:order) { create(:order_with_line_items, line_items_count: 1) }
+
+ it 'is valid order-level (no adjustable)' do
+ fee = described_class.new(order: order, amount: 5, label: 'COD', kind: 'payment')
+ expect(fee).to be_valid
+ expect(fee).to be_order_level
+ end
+
+ it 'may target a line item' do
+ fee = described_class.new(order: order, line_item: order.line_items.first, amount: 3, label: 'Gift wrap', kind: 'gift_wrap')
+ expect(fee).to be_valid
+ expect(fee).not_to be_order_level
+ end
+
+ it 'rejects negative amounts — credits are manual discounts' do
+ fee = described_class.new(order: order, amount: -5, label: 'Credit', kind: 'surcharge')
+ expect(fee).not_to be_valid
+ expect(fee.errors[:amount]).to be_present
+ end
+
+ it 'requires kind and label' do
+ fee = described_class.new(order: order, amount: 5)
+ expect(fee).not_to be_valid
+ expect(fee.errors[:kind]).to be_present
+ expect(fee.errors[:label]).to be_present
+ end
+
+ it 'destroys its tax lines with it' do
+ fee = create(:fee, order: order)
+ create(:tax_line, order: order, fee: fee, line_item: nil)
+ expect { fee.destroy! }.to change(Spree::TaxLine, :count).by(-1)
+ end
+end
diff --git a/spree/core/spec/models/spree/line_item_spec.rb b/spree/core/spec/models/spree/line_item_spec.rb
index 5a1258b512..8d11770570 100644
--- a/spree/core/spec/models/spree/line_item_spec.rb
+++ b/spree/core/spec/models/spree/line_item_spec.rb
@@ -182,16 +182,20 @@ describe Spree::LineItem, type: :model do
line_item.quantity = line_item.quantity + 1
end
- it 'triggers adjustment total recalculation' do
- expect(line_item).to receive(:update_tax_charge) # Regression test for https://github.com/spree/spree/issues/4671
- expect(line_item).to receive(:recalculate_adjustments)
+ # Regression guard for #4671 — a quantity change must move the tax
+ # basis. Typed rows are rebuilt by the order-level recalculation that
+ # every cart/checkout flow runs after the save.
+ it 'refreshes tax through the order recalculation' do
line_item.save
+ line_item.order.update_with_updater!
+
+ expect(line_item.reload.pre_tax_amount).to eq(line_item.price * line_item.quantity)
end
end
context 'line item does not change' do
- it 'does not trigger adjustment total recalculation' do
- expect(line_item).not_to receive(:recalculate_adjustments)
+ it 'does not trigger price recalculation' do
+ expect(line_item).not_to receive(:recalculate_price)
line_item.save
end
end
@@ -226,7 +230,7 @@ describe Spree::LineItem, type: :model do
it 'creates a tax adjustment' do
Spree::Carts::AddItem.call(order: order, variant: variant)
line_item = order.find_line_item_by_variant(variant)
- expect(line_item.adjustments.tax.count).to eq(1)
+ expect(line_item.tax_lines.count).to eq(1)
end
end
@@ -244,7 +248,7 @@ describe Spree::LineItem, type: :model do
Spree::Carts::AddItem.call(order: order, variant: variant)
line_item = order.find_line_item_by_variant(variant)
- expect(line_item.adjustments.tax.count).to eq(0)
+ expect(line_item.tax_lines.count).to eq(0)
end
end
end
diff --git a/spree/core/spec/models/spree/order/adjustments_spec.rb b/spree/core/spec/models/spree/order/adjustments_spec.rb
index 9c97c9ecb7..f86522acbb 100644
--- a/spree/core/spec/models/spree/order/adjustments_spec.rb
+++ b/spree/core/spec/models/spree/order/adjustments_spec.rb
@@ -1,7 +1,7 @@
require 'spec_helper'
describe Spree::Order do
- context 'when an order has an adjustment that zeroes the total, but another adjustment for shipping that raises it above zero' do
+ context 'when a discount zeroes the item total, but shipping raises the total above zero' do
let!(:persisted_order) { create(:order) }
let!(:line_item) { create(:line_item) }
let!(:shipping_method) do
@@ -15,7 +15,8 @@ describe Spree::Order do
# Don't care about available payment methods in this test
allow(persisted_order).to receive_messages(has_available_payment: false)
persisted_order.line_items << line_item
- create(:adjustment, amount: -line_item.amount, label: 'Promotion', adjustable: line_item, order: persisted_order)
+ create(:discount, order: persisted_order, line_item: line_item, amount: -line_item.amount, label: 'Promotion', kind: 'manual')
+ persisted_order.update_with_updater!
persisted_order.state = 'delivery'
persisted_order.save # To ensure new state_change event
end
@@ -65,13 +66,12 @@ describe Spree::Order do
order.create_shipment_tax_charge!
end
- it 'removes the shipment tax adjustment' do
+ it 'removes the fulfillment tax lines' do
order.coupon_code = free_shipping_promotion.code
Spree::PromotionHandler::Coupon.new(order).apply
order.apply_free_shipping_promotions
- shipment_tax_adjustments = order.shipment_adjustments.where(source_type: 'Spree::TaxRate')
- expect(shipment_tax_adjustments.blank?).to be true
+ expect(order.tax_lines.for_fulfillments).to be_blank
end
end
end
diff --git a/spree/core/spec/models/spree/order/checkout_spec.rb b/spree/core/spec/models/spree/order/checkout_spec.rb
index 5c4a02adea..96f1769b05 100644
--- a/spree/core/spec/models/spree/order/checkout_spec.rb
+++ b/spree/core/spec/models/spree/order/checkout_spec.rb
@@ -201,7 +201,6 @@ describe Spree::Order, type: :model do
order.line_items << line_item
tax_rate = create(:tax_rate, tax_category: line_item.tax_category, amount: 0.05)
allow(Spree::TaxRate).to receive_messages match: [tax_rate]
- FactoryBot.create(:tax_adjustment, adjustable: line_item, source: tax_rate, order: order)
order.email = '[email protected]'
order.next!
expect(order.adjustment_total).to eq(0.5)
@@ -220,10 +219,6 @@ describe Spree::Order, type: :model do
tax_category: line_item.tax_category,
amount: 0.05
allow(Spree::TaxRate).to receive_messages(match: [tax_rate])
- FactoryBot.create :tax_adjustment,
- adjustable: line_item,
- source: tax_rate,
- order: order
order.email = '[email protected]'
order.next!
expect(order.adjustment_total).to eq(0)
diff --git a/spree/core/spec/models/spree/order/finalizing_spec.rb b/spree/core/spec/models/spree/order/finalizing_spec.rb
index 434074e37b..612644464e 100644
--- a/spree/core/spec/models/spree/order/finalizing_spec.rb
+++ b/spree/core/spec/models/spree/order/finalizing_spec.rb
@@ -49,11 +49,10 @@ describe Spree::Order, type: :model do
order.finalize!
end
- it 'freezes all adjustments' do
- adjustments = [double]
- expect(order).to receive(:all_adjustments).and_return(adjustments)
- expect(adjustments).to all(receive(:close))
+ it 'freezes adjustment recalculation (order-level freeze)' do
order.finalize!
+ expect(Spree::Adjusters::Promotion).not_to receive(:adjust)
+ order.update_with_updater!
end
context 'order is considered risky' 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 fbc805e7fa..3fb78394c6 100644
--- a/spree/core/spec/models/spree/order/state_machine_spec.rb
+++ b/spree/core/spec/models/spree/order/state_machine_spec.rb
@@ -58,17 +58,12 @@ describe Spree::Order, type: :model do
order.state = 'delivery'
end
- it 'adjusts tax rates when transitioning to delivery' do
- # Once for the line items
- expect(Spree::TaxRate).to receive(:adjust).once
- allow(order).to receive :set_shipments_cost
- order.next!
- end
+ it 'estimates tax when leaving delivery' do
+ provider = instance_double(Spree::TaxProvider::Internal, estimate: nil)
+ allow(Spree).to receive(:tax_provider).and_return(provider)
- it 'adjusts tax rates twice if there are any shipments' do
- # Once for the line items, once for the shipments
- order.fulfillments.build stock_location: create(:stock_location)
- expect(Spree::TaxRate).to receive(:adjust).twice
+ # A single estimate covers line items, fulfillments and fees.
+ expect(provider).to receive(:estimate).at_least(:once)
allow(order).to receive :set_shipments_cost
order.next!
end
diff --git a/spree/core/spec/models/spree/order/totals_spec.rb b/spree/core/spec/models/spree/order/totals_spec.rb
index 93eaaa0645..4b04632db8 100644
--- a/spree/core/spec/models/spree/order/totals_spec.rb
+++ b/spree/core/spec/models/spree/order/totals_spec.rb
@@ -9,7 +9,7 @@ module Spree
context 'adds item to cart and activates promo' do
let(:promotion) { create(:promotion, name: 'Huhu', kind: :automatic) }
let(:calculator) { Calculator::FlatPercentItemTotal.new(preferred_flat_percent: 10) }
- let!(:action) { Promotion::Actions::CreateAdjustment.create(promotion: promotion, calculator: calculator) }
+ let!(:action) { PromotionActions::CreateAdjustment.create(promotion: promotion, calculator: calculator) }
before { Spree::Carts::AddItem.call(order: order, variant: shirt).value }
@@ -17,7 +17,7 @@ module Spree
it 'recalculates order adjustments' do
expect do
Spree::Carts::AddItem.call(order: order, variant: shirt, quantity: 3)
- end.to change { order.adjustments.eligible.pluck(:amount) }
+ end.to change { order.discounts.pluck(:amount) }
end
end
end
diff --git a/spree/core/spec/models/spree/order_inventory_spec.rb b/spree/core/spec/models/spree/order_inventory_spec.rb
index b45d886bfc..032ef8fb2d 100644
--- a/spree/core/spec/models/spree/order_inventory_spec.rb
+++ b/spree/core/spec/models/spree/order_inventory_spec.rb
@@ -11,7 +11,7 @@ describe Spree::OrderInventory, type: :model do
it 'creates the proper number of inventory units' do
subject.verify
- expect(subject.inventory_units.reload.sum(&:quantity)).to eq 2
+ expect(subject.fulfillment_items.reload.sum(&:quantity)).to eq 2
end
end
@@ -28,7 +28,7 @@ describe Spree::OrderInventory, type: :model do
end
context 'inventory units state' do
- before { shipment.inventory_units.delete_all }
+ before { shipment.fulfillment_items.delete_all }
it 'sets inventory_units state as per stock location availability' do
expect(shipment.stock_location).to receive(:fill_status).with(subject.variant, 5).and_return([3, 2])
@@ -97,15 +97,15 @@ describe Spree::OrderInventory, type: :model do
allow(line_item).to receive(:changed?).and_return(true)
subject.verify
- order.shipments.create(stock_location_id: stock_location.id, cost: 5)
+ order.fulfillments.create(stock_location_id: stock_location.id, cost: 5)
- shipped = order.shipments.create(stock_location_id: order.shipments.first.stock_location.id, cost: 10)
- shipped.update_column(:state, 'shipped')
+ shipped = order.fulfillments.create(stock_location_id: order.fulfillments.first.stock_location.id, cost: 10)
+ shipped.update_column(:status, 'fulfilled')
end
it 'selects first non-shipped shipment that already contains given variant' do
shipment = subject.send(:determine_target_shipment)
- expect(shipment.shipped?).to be false
+ expect(shipment.fulfilled?).to be false
expect(shipment.inventory_units_for(variant)).not_to be_empty
expect(variant.stock_location_ids.include?(shipment.stock_location_id)).to be true
@@ -114,13 +114,13 @@ describe Spree::OrderInventory, type: :model do
context 'when no shipments already contain this varint' do
before do
subject.line_item.reload
- subject.inventory_units.delete_all
+ subject.fulfillment_items.delete_all
end
it 'selects first non-shipped shipment that leaves from same stock_location' do
shipment = subject.send(:determine_target_shipment)
shipment.reload
- expect(shipment.shipped?).to be false
+ expect(shipment.fulfilled?).to be false
expect(shipment.inventory_units_for(variant)).to be_empty
expect(variant.stock_location_ids.include?(shipment.stock_location_id)).to be true
end
@@ -137,17 +137,17 @@ describe Spree::OrderInventory, type: :model do
end
it 'is a messed up order' do
- expect(order.shipments.first.inventory_units_for(line_item.variant).sum(&:quantity)).to eq(3)
+ expect(order.fulfillments.first.inventory_units_for(line_item.variant).sum(&:quantity)).to eq(3)
expect(line_item.quantity).to eq(2)
end
it 'decreases the number of inventory units' do
subject.verify
- expect(subject.inventory_units.reload.sum(:quantity)).to eq 2
+ expect(subject.fulfillment_items.reload.sum(:quantity)).to eq 2
end
context '#remove_from_shipment' do
- let!(:shipment) { order.shipments.first }
+ let!(:shipment) { order.fulfillments.first }
let!(:variant) { subject.variant }
let!(:inventory_units_for_item) do
[
@@ -224,7 +224,7 @@ describe Spree::OrderInventory, type: :model do
before { order.touch :completed_at }
it 'removes only units that match both line item and variant' do
- subject.send(:remove_from_shipment, shipment, shipment.inventory_units.sum(&:quantity))
+ subject.send(:remove_from_shipment, shipment, shipment.fulfillment_items.sum(&:quantity))
expect(different_inventory.reload).to be_persisted
end
end
@@ -244,10 +244,10 @@ describe Spree::OrderInventory, type: :model do
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 }
+ before { shipment.fulfillment_items.where(line_item_id: line_item.id).delete_all }
it 'does not create new inventory units (which would be orphaned by the destroy cascade)' do
- expect { subject.verify(nil, removing: true) }.not_to change { shipment.inventory_units.count }
+ expect { subject.verify(nil, removing: true) }.not_to change { shipment.fulfillment_items.count }
end
end
diff --git a/spree/core/spec/models/spree/order_promotion_spec.rb b/spree/core/spec/models/spree/order_promotion_spec.rb
index 9df86a07ce..66a61bf1ec 100644
--- a/spree/core/spec/models/spree/order_promotion_spec.rb
+++ b/spree/core/spec/models/spree/order_promotion_spec.rb
@@ -10,7 +10,7 @@ describe Spree::OrderPromotion, type: :model do
order.coupon_code = promotion.code
Spree::PromotionHandler::Coupon.new(order).apply
order.save!
- order.all_adjustments.promotion.update_all(amount: -5.0)
+ order.discounts.promotion.update_all(amount: -5.0)
end
context '#name' do
diff --git a/spree/core/spec/models/spree/order_spec.rb b/spree/core/spec/models/spree/order_spec.rb
index 5f57653715..bce10bbdc7 100644
--- a/spree/core/spec/models/spree/order_spec.rb
+++ b/spree/core/spec/models/spree/order_spec.rb
@@ -438,11 +438,10 @@ describe Spree::Order, type: :model do
order.finalize!
end
- it 'freezes all adjustments' do
- adjustments = [double]
- expect(order).to receive(:all_adjustments).and_return(adjustments)
- expect(adjustments).to all(receive(:close))
+ it 'freezes adjustment recalculation (order-level freeze)' do
order.finalize!
+ expect(Spree::Adjusters::Promotion).not_to receive(:adjust)
+ order.update_with_updater!
end
context 'order is considered risky' do
@@ -592,7 +591,9 @@ describe Spree::Order, type: :model do
it 'clears out line items, adjustments and update totals' do
expect(order.line_items.count).to be_zero
- expect(order.adjustments.count).to be_zero
+ expect(order.discounts.count).to be_zero
+ expect(order.tax_lines.count).to be_zero
+ expect(order.fees.count).to be_zero
expect(order.shipments.count).to be_zero
expect(order.order_promotions.count).to be_zero
expect(order.promo_total).to be_zero
@@ -904,16 +905,10 @@ 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 fulfillments: [shipment]
expect(Spree::PromotionHandler::FreeShipping).to receive(:new).and_return(handler = double)
expect(handler).to receive(:activate)
+ expect(order).to receive(:update_with_updater!)
- expect(Spree::Adjustable::AdjustmentsUpdater).to receive(:update).with(shipment)
-
- expect(Spree::TaxRate).to receive(:adjust).with(order, [shipment])
-
- expect(order.updater).to receive(:update)
order.apply_free_shipping_promotions
end
end
@@ -1840,28 +1835,24 @@ describe Spree::Order, type: :model do
end
describe '#create_shipment_tax_charge!' do
- let(:order_shipments) { double }
+ let(:provider) { instance_double(Spree::TaxProvider::Internal, estimate: nil) }
- after { order.create_shipment_tax_charge! }
+ before { allow(Spree).to receive(:tax_provider).and_return(provider) }
context 'when order has shipments' do
- before do
- 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
+ let!(:shipment) { create(:shipment, order: order) }
- it { expect(order_shipments).to receive(:any?).and_return(true) }
- it { expect(order).to receive(:fulfillments).and_return(order_shipments) }
- it { expect(Spree::TaxRate).to receive(:adjust).with(order, order_shipments) }
+ it 'estimates tax over the fulfillments' do
+ expect(provider).to receive(:estimate).with(order, [shipment])
+ order.create_shipment_tax_charge!
+ end
end
context 'when order has no shipments' do
- before do
- allow(order).to receive_message_chain(:fulfillments, :any?).and_return(false)
+ it 'does not call the provider' do
+ expect(provider).not_to receive(:estimate)
+ order.create_shipment_tax_charge!
end
-
- it { expect(order).to receive_message_chain(:fulfillments, :any?).and_return(false) }
end
end
@@ -1898,29 +1889,23 @@ describe Spree::Order, type: :model do
end
describe '#valid_promotions' do
- def create_adjustment(label, order_or_line_item, amount, source)
- create(:adjustment,
+ def create_discount(label, line_item, amount, action)
+ create(:discount,
order: order,
- adjustable: order_or_line_item,
- source: source,
+ line_item: line_item,
+ promotion_action: action,
+ promotion: action.promotion,
amount: amount,
- state: 'closed',
label: label,
- mandatory: false)
+ kind: 'promotion')
end
let!(:order) { create(:order_with_line_items, line_items_count: 10) }
let(:line_item) { order.line_items.first }
- let(:zero_promo) { create :promotion_with_order_adjustment, weighted_order_adjustment_amount: 0, starts_at: Time.now, code: 'Zero', id: 1 }
- let(:order_promo) { create :promotion_with_order_adjustment, weighted_order_adjustment_amount: 10, starts_at: Time.now, code: 'Order1', id: 2 }
- let(:line_item_promo) { create :promotion_with_item_adjustment, adjustment_rate: 10, starts_at: Time.now, code: 'LineItem', id: 3 }
-
- let(:calculator) { Spree::Calculator::FlatRate.new(preferred_amount: 10) }
- let(:source) { Spree::Promotion::Actions::CreateItemAdjustments.create(calculator: calculator, promotion_id: order_promo.id) }
- let(:zero_calculator) { Spree::Calculator::FlatRate.new(preferred_amount: 0) }
- let(:zero_source) { Spree::Promotion::Actions::CreateItemAdjustments.create calculator: zero_calculator, promotion_id: zero_promo.id }
- let(:line_item_source) { Spree::Promotion::Actions::CreateItemAdjustments.create calculator: calculator, promotion_id: line_item_promo.id }
+ let(:zero_promo) { create :promotion_with_order_adjustment, weighted_order_adjustment_amount: 0, starts_at: Time.now, code: 'Zero' }
+ let(:order_promo) { create :promotion_with_order_adjustment, weighted_order_adjustment_amount: 10, starts_at: Time.now, code: 'Order1' }
+ let(:line_item_promo) { create :promotion_with_item_adjustment, adjustment_rate: 10, starts_at: Time.now, code: 'LineItem' }
context 'without promotions' do
it 'expect to return an empty array' do
@@ -1929,22 +1914,13 @@ describe Spree::Order, type: :model do
end
context 'with promotions' do
- let!(:zero_adjustment) { create_adjustment('Zero adjustment', order, -0, zero_source) }
- let!(:adjustment) { create_adjustment('Adjustment', order, -50, source) }
- let!(:non_eligible_adjustment) { create_adjustment('Non Eligible Adjustment', order, -100, source) }
- let!(:line_item_adjustment) { create_adjustment('Adjustment', line_item, -200, line_item_source) }
+ let!(:zero_discount) { create_discount('Zero discount', order.line_items.second, 0, zero_promo.actions.first) }
+ let!(:order_discount) { create_discount('Discount', line_item, -50, order_promo.actions.first) }
+ let!(:line_item_discount) { create_discount('Discount', order.line_items.third, -200, line_item_promo.actions.first) }
before do
- promotions = [zero_promo, order_promo, line_item_promo]
- promotions.each do |promotion|
+ [zero_promo, order_promo, line_item_promo].each do |promotion|
promotion.orders << order
- promotion.actions << Spree::Promotion::Actions::CreateAdjustment.new
- promotion.rules << Spree::Promotion::Rules::FirstOrder.new
- promotion.save!
- end
-
- order.all_adjustments.where(amount: [0, -50, -200]).each do |adjustment|
- adjustment.update_column(:eligible, true)
end
end
@@ -2028,8 +2004,11 @@ describe Spree::Order, type: :model do
expect(order.promotions).to include(free_shipping_promotion, line_item_promotion, order_promotion)
end
- it 'returns -110.00' do
- expect(subject).to eq(BigDecimal('-110.00'))
+ # The line-item promotion fully discounts every line, so the
+ # order-level promotion has no remaining base to distribute over —
+ # discounts are clamped so no line goes below zero (6.0 behavior).
+ it 'returns -100.00' do
+ expect(subject).to eq(BigDecimal('-100.00'))
end
end
end
diff --git a/spree/core/spec/models/spree/order_updater_spec.rb b/spree/core/spec/models/spree/order_updater_spec.rb
index 418f9c4b68..144f381f33 100644
--- a/spree/core/spec/models/spree/order_updater_spec.rb
+++ b/spree/core/spec/models/spree/order_updater_spec.rb
@@ -36,13 +36,14 @@ module Spree
let(:calculator) { Calculator::FlatPercentItemTotal.new(preferred_flat_percent: 10) }
let(:promotion_action) do
- Promotion::Actions::CreateAdjustment.create!(calculator: calculator,
+ PromotionActions::CreateAdjustment.create!(calculator: calculator,
promotion: promotion)
end
before do
updater.update
- create(:adjustment, source: promotion_action, adjustable: order, order: order)
+ promotion_action
+ order.promotions << promotion
create(:line_item, order: order, price: 10) # in addition to the two already created
order.reload
updater.update
@@ -54,15 +55,19 @@ module Spree
end
it 'update order adjustments' do
- # A line item will not have both additional and included tax,
- # so please just humour me for now.
- order.line_items.first.update_columns(adjustment_total: 10.05,
- additional_tax_total: 0.05,
- included_tax_total: 0.05)
+ # Tax is provider-written; stub it out so the synthetic tax line survives.
+ allow(Spree).to receive(:tax_provider).and_return(instance_double(Spree::TaxProvider::Internal, estimate: nil))
+
+ line_item = order.line_items.first
+ create(:discount, order: order, line_item: line_item, amount: -2.50, kind: 'manual')
+ create(:fee, order: order, amount: 5, kind: 'handling')
+ create(:tax_line, order: order, line_item: line_item, amount: 0.05, included: false)
+
updater.update_adjustment_total
- expect(order.adjustment_total).to eq(10.05)
+ expect(order.adjustment_total).to eq(2.55)
expect(order.additional_tax_total).to eq(0.05)
- expect(order.included_tax_total).to eq(0.05)
+ expect(order.fee_total).to eq(5)
+ expect(order.promo_total).to eq(0)
end
end
diff --git a/spree/core/spec/models/spree/permission_sets/order_management_spec.rb b/spree/core/spec/models/spree/permission_sets/order_management_spec.rb
index 0c99650ae3..5a13eb163e 100644
--- a/spree/core/spec/models/spree/permission_sets/order_management_spec.rb
+++ b/spree/core/spec/models/spree/permission_sets/order_management_spec.rb
@@ -23,7 +23,9 @@ RSpec.describe Spree::PermissionSets::OrderManagement do
end
it 'grants manage access to Adjustment' do
- expect(ability.can?(:manage, Spree::Adjustment)).to be true
+ expect(ability.can?(:manage, Spree::Discount)).to be true
+ expect(ability.can?(:manage, Spree::Fee)).to be true
+ expect(ability.can?(:manage, Spree::TaxLine)).to be true
end
it 'grants manage access to LineItem' do
diff --git a/spree/core/spec/models/spree/promotion/actions/create_adjustment_spec.rb b/spree/core/spec/models/spree/promotion/actions/create_adjustment_spec.rb
deleted file mode 100644
index e45022f413..0000000000
--- a/spree/core/spec/models/spree/promotion/actions/create_adjustment_spec.rb
+++ /dev/null
@@ -1,113 +0,0 @@
-require 'spec_helper'
-
-describe Spree::Promotion::Actions::CreateAdjustment, type: :model do
- let(:order) { create(:order_with_line_items, line_items_count: 1) }
- let(:promotion) { create(:promotion) }
- let(:action) { Spree::Promotion::Actions::CreateAdjustment.new(promotion: promotion) }
- let(:payload) { { order: order } }
-
- it_behaves_like 'an adjustment source'
-
- describe '#compute_amount' do
- subject { described_class.new }
-
- let(:shipping_discount) { 10 }
- let(:order) do
- double(:order, item_total: 30, ship_total: 10, shipping_discount: shipping_discount)
- end
-
- context 'when shipping_discount is applied' do
- context 'and total is less than discount' do
- it 'returns discount amount eq to total' do
- allow(subject).to receive(:compute).with(order).and_return(100)
-
- expect(subject.compute_amount(order)).to eq(-30)
- end
- end
-
- context 'and total is equal to discount' do
- it 'returns discount amount' do
- allow(subject).to receive(:compute).with(order).and_return(30)
-
- expect(subject.compute_amount(order)).to eq(-30)
- end
- end
-
- context 'and total is greater than discount' do
- it 'returns discount amount' do
- allow(subject).to receive(:compute).with(order).and_return(10)
-
- expect(subject.compute_amount(order)).to eq(-10)
- end
- end
- end
-
- context 'when shipping_discount is not applied' do
- let(:shipping_discount) { 0 }
-
- context 'and total is less than discount' do
- it 'returns discount amount eq to total' do
- allow(subject).to receive(:compute).with(order).and_return(100)
-
- expect(subject.compute_amount(order)).to eq(-40)
- end
- end
-
- context 'and total is equal to discount' do
- it 'returns discount amount' do
- allow(subject).to receive(:compute).with(order).and_return(40)
-
- expect(subject.compute_amount(order)).to eq(-40)
- end
- end
-
- context 'and total is greater than discount' do
- it 'returns discount amount' do
- allow(subject).to receive(:compute).with(order).and_return(10)
-
- expect(subject.compute_amount(order)).to eq(-10)
- end
- end
- end
- end
-
- # From promotion spec:
- context '#perform' do
- before do
- action.calculator = Spree::Calculator::FlatRate.new(preferred_amount: 10)
- promotion.promotion_actions = [action]
- allow(action).to receive_messages(promotion: promotion)
- end
-
- # Regression test for #3966
- it 'does not apply an adjustment if the amount is 0' do
- action.calculator.preferred_amount = 0
- action.perform(payload)
- expect(promotion.credits_count).to eq(0)
- expect(order.adjustments.count).to eq(0)
- end
-
- it 'creates a discount with correct negative amount' do
- order.shipments.create!(cost: 10, stock_location: create(:stock_location))
-
- action.perform(payload)
- expect(promotion.credits_count).to eq(1)
- expect(order.adjustments.count).to eq(1)
- expect(order.adjustments.first.amount.to_i).to eq(-10)
- end
-
- it 'creates a discount accessible through both order_id and adjustable_id' do
- action.perform(payload)
- expect(order.adjustments.count).to eq(1)
- expect(order.all_adjustments.count).to eq(1)
- end
-
- it 'does not create a discount when order already has one from this promotion' do
- order.shipments.create!(cost: 10, stock_location: create(:stock_location))
-
- action.perform(payload)
- action.perform(payload)
- expect(promotion.credits_count).to eq(1)
- end
- end
-end
diff --git a/spree/core/spec/models/spree/promotion/actions/create_item_adjustments_spec.rb b/spree/core/spec/models/spree/promotion/actions/create_item_adjustments_spec.rb
deleted file mode 100644
index 6f3181d6a3..0000000000
--- a/spree/core/spec/models/spree/promotion/actions/create_item_adjustments_spec.rb
+++ /dev/null
@@ -1,175 +0,0 @@
-require 'spec_helper'
-
-module Spree
- class Promotion
- module Actions
- describe CreateItemAdjustments, type: :model do
- let(:order) { create(:order) }
- let(:promotion) { create(:promotion) }
- let(:action) { CreateItemAdjustments.new }
- let!(:line_item) { create(:line_item, order: order) }
- let(:payload) { { order: order, promotion: promotion } }
-
- before do
- allow(action).to receive(:promotion).and_return(promotion)
- promotion.promotion_actions = [action]
- end
-
- it_behaves_like 'an adjustment source'
-
- context '#perform' do
- # Regression test for #3966
- context 'when calculator computes 0' do
- before do
- allow(action).to receive_messages compute_amount: 0
- end
-
- it 'does not create an adjustment when calculator returns 0' do
- action.perform(payload)
- expect(action.adjustments).to be_empty
- end
- end
-
- context 'when calculator returns a non-zero value' do
- before do
- promotion.promotion_actions = [action]
- allow(action).to receive_messages compute_amount: 10
- end
-
- it 'creates adjustment with item as adjustable' do
- action.perform(payload)
- expect(action.adjustments.count).to eq(1)
- expect(line_item.reload.adjustments).to eq(action.adjustments)
- end
-
- it 'creates adjustment with self as source' do
- action.perform(payload)
- expect(line_item.reload.adjustments.first.source).to eq action
- end
-
- it 'does not perform twice on the same item' do
- 2.times { action.perform(payload) }
- expect(action.adjustments.count).to eq(1)
- end
-
- context 'with products rules' do
- let!(:second_line_item) { create(:line_item, order: order) }
- let(:rule) { double Spree::Promotion::Rules::Product }
-
- before do
- allow(promotion).to receive(:eligible_rules) { [rule] }
- allow(rule).to receive(:actionable?).and_return(true, false)
- end
-
- it 'does not create adjustments for line_items not in product rule' do
- action.perform(payload)
- expect(action.adjustments.count).to be 1
- expect(line_item.reload.adjustments).to match_array action.adjustments
- expect(second_line_item.reload.adjustments).to be_empty
- end
- end
- end
- end
-
- context '#compute_amount' do
- before { promotion.promotion_actions = [action] }
-
- context 'when the adjustable is actionable' do
- it 'calls compute on the calculator' do
- allow(action.calculator).to receive(:compute).and_return(10)
- expect(action.calculator).to receive(:compute).with(line_item)
- action.compute_amount(line_item)
- end
-
- context 'calculator returns amount greater than item total' do
- before do
- expect(action.calculator).to receive(:compute).with(line_item).and_return(300)
- allow(line_item).to receive_messages(amount: 100)
- end
-
- it 'does not exceed it' do
- expect(action.compute_amount(line_item)).to be(-100)
- end
- end
-
- context 'given other promotions with order adjustment' do
- let!(:line_item) { create :line_item, order: order, price: 15 }
-
- before do
- order.update_with_updater!
-
- 2.times { create :promotion_with_order_adjustment, kind: :automatic }
- Spree::PromotionHandler::Cart.new(order).activate
-
- allow(action.calculator).to receive(:compute).and_return(3)
- end
-
- it 'should not consider not eligible adjustments' do
- expect(action.compute_amount(line_item)).to eq -3
- end
-
- context 'when adjustments total is greater than item total' do
- let!(:line_item) { create :line_item, order: order, price: 12 }
-
- it 'does not exceed it' do
- expect(action.compute_amount(line_item)).to eq -2
- end
- end
- end
- end
-
- context 'when the adjustable is not actionable' do
- before { allow(promotion).to receive(:line_item_actionable?).and_return(false) }
-
- it 'returns 0' do
- expect(action.compute_amount(line_item)).to be(0)
- end
- end
- end
-
- context '#destroy' do
- let(:other_promotion) { create(:promotion) }
- let!(:action) { CreateItemAdjustments.create!(promotion: promotion) }
- let!(:other_action) { CreateItemAdjustments.create!(promotion: other_promotion) }
-
- before { promotion.promotion_actions = [other_action] }
-
- it 'destroys adjustments for incompleted orders' do
- order = Order.create
- action.adjustments.create!(label: 'Check',
- amount: 0,
- order: order,
- adjustable: line_item)
-
- expect do
- action.destroy
- end.to change(Adjustment, :count).by(-1)
- end
-
- it 'nullifies adjustments for completed orders' do
- order = Order.create(completed_at: Time.current)
- adjustment = action.adjustments.create!(label: 'Check',
- amount: 0,
- order: order,
- adjustable: line_item)
-
- expect do
- action.destroy
- end.to change { adjustment.reload.source_id }.from(action.id).to nil
- end
-
- it 'doesnt mess with unrelated adjustments' do
- other_action.adjustments.create!(label: 'Check',
- amount: 0,
- order: order,
- adjustable: line_item)
-
- expect do
- action.destroy
- end.not_to change { other_action.adjustments.count }
- end
- end
- end
- end
- end
-end
diff --git a/spree/core/spec/models/spree/promotion/actions/free_shipping_spec.rb b/spree/core/spec/models/spree/promotion/actions/free_shipping_spec.rb
deleted file mode 100644
index e18b1cc2cf..0000000000
--- a/spree/core/spec/models/spree/promotion/actions/free_shipping_spec.rb
+++ /dev/null
@@ -1,56 +0,0 @@
-require 'spec_helper'
-
-describe Spree::Promotion::Actions::FreeShipping, type: :model do
- let(:order) { create(:completed_order_with_totals) }
- let(:promotion) { create(:promotion) }
- let(:action) { Spree::Promotion::Actions::FreeShipping.create!(promotion: promotion) }
- let(:payload) { { order: order } }
-
- it_behaves_like 'an adjustment source'
-
- # From promotion spec:
- context '#perform' do
- before do
- order.shipments << create(:shipment)
- promotion.promotion_actions << action
- end
-
- it 'creates a discount with correct negative amount' do
- expect(order.shipments.count).to eq(2)
- # Costs are determined by the shipping calculator (default: 10.0)
- first_shipment_cost = order.shipments.first.cost
- last_shipment_cost = order.shipments.last.cost
- expect(first_shipment_cost).to be > 0
- expect(last_shipment_cost).to be > 0
- expect(action.perform(payload)).to be true
- expect(promotion.credits_count).to eq(1)
- expect(order.shipment_adjustments.count).to eq(2)
- expect(order.shipment_adjustments.first.amount.to_i).to eq(-first_shipment_cost.to_i)
- expect(order.shipment_adjustments.last.amount.to_i).to eq(-last_shipment_cost.to_i)
- end
-
- it 'does not create a discount when order already has one from this promotion' do
- expect(action.perform(payload)).to be true
- expect(action.perform(payload)).to be false
- expect(promotion.credits_count).to eq(1)
- expect(order.shipment_adjustments.count).to eq(2)
- end
-
- context 'when shipping methods are configured to be free' do
- before do
- order.shipments.update_all(cost: 0)
- end
-
- it 'can create adjustment with amount equal to 0' do
- expect(order.shipments.count).to eq(2)
- expect(order.shipments.first.cost).to eq(0)
- expect(order.shipments.last.cost).to eq(0)
- expect(action.perform(payload)).to be true
- expect(promotion.credits_count).to eq(1)
- expect(order.shipment_adjustments.count).to eq(2)
- expect(order.shipment_adjustments.first.amount.to_i).to eq(0)
- expect(order.shipment_adjustments.last.amount.to_i).to eq(0)
- end
- end
- end
-end
diff --git a/spree/core/spec/models/spree/promotion_actions/create_adjustment_spec.rb b/spree/core/spec/models/spree/promotion_actions/create_adjustment_spec.rb
new file mode 100644
index 0000000000..f70b22e717
--- /dev/null
+++ b/spree/core/spec/models/spree/promotion_actions/create_adjustment_spec.rb
@@ -0,0 +1,35 @@
+require 'spec_helper'
+
+describe Spree::PromotionActions::CreateAdjustment, type: :model do
+ let(:order) { create(:order_with_line_items, line_items_count: 2) }
+ let(:promotion) { create(:promotion, kind: :automatic, code: nil, stores: [order.store]) }
+ let(:action) do
+ described_class.create!(promotion: promotion, calculator: Spree::Calculator::FlatRate.new(preferred_amount: 4))
+ end
+
+ describe '#perform' do
+ it 'distributes the order-level discount across line items' do
+ expect(action.perform(order: order, promotion: promotion)).to be(true)
+
+ rows = order.discounts.reload
+ expect(rows.map(&:line_item_id)).to match_array(order.line_items.ids)
+ expect(rows.sum(&:amount)).to eq(-4)
+ end
+
+ it 'reports no action at zero amount' do
+ zero = described_class.create!(promotion: promotion, calculator: Spree::Calculator::FlatRate.new(preferred_amount: 0))
+ expect(zero.perform(order: order, promotion: promotion)).to be(false)
+ end
+ end
+
+ describe '#compute_amount' do
+ it 'caps at the order total' do
+ huge = described_class.create!(promotion: promotion, calculator: Spree::Calculator::FlatRate.new(preferred_amount: 99_999))
+ expect(huge.compute_amount(order)).to eq(-action.order_total(order))
+ end
+ end
+
+ it 'has order discount scope' do
+ expect(action.discount_scope).to eq(:order)
+ end
+end
diff --git a/spree/core/spec/models/spree/promotion_actions/create_item_discounts_spec.rb b/spree/core/spec/models/spree/promotion_actions/create_item_discounts_spec.rb
new file mode 100644
index 0000000000..6ed0430256
--- /dev/null
+++ b/spree/core/spec/models/spree/promotion_actions/create_item_discounts_spec.rb
@@ -0,0 +1,52 @@
+require 'spec_helper'
+
+describe Spree::PromotionActions::CreateItemDiscounts, type: :model do
+ let(:order) { create(:order_with_line_items, line_items_count: 2) }
+ let(:promotion) { create(:promotion, kind: :automatic, code: nil, stores: [order.store]) }
+ let(:action) do
+ described_class.create!(promotion: promotion, calculator: Spree::Calculator::FlatRate.new(preferred_amount: 3))
+ end
+
+ describe '#perform' do
+ it 'writes a discount per actionable line item and reports action taken' do
+ expect(action.perform(order: order, promotion: promotion)).to be(true)
+
+ rows = order.discounts.reload
+ expect(rows.size).to eq(2)
+ expect(rows.map(&:amount)).to all(eq(-3))
+ expect(rows.map(&:promotion_action_id).uniq).to eq([action.id])
+ end
+
+ it 'is idempotent' do
+ action.perform(order: order, promotion: promotion)
+ action.perform(order: order, promotion: promotion)
+
+ expect(order.discounts.reload.size).to eq(2)
+ end
+
+ it 'reports no action when nothing is actionable' do
+ allow(promotion).to receive(:line_item_actionable?).and_return(false)
+ expect(action.perform(order: order, promotion: promotion)).to be(false)
+ expect(order.discounts.reload).to be_empty
+ end
+ end
+
+ describe '#compute_amount' do
+ it 'caps at the line item amount' do
+ expensive = described_class.create!(promotion: promotion, calculator: Spree::Calculator::FlatRate.new(preferred_amount: 999))
+ allow(promotion).to receive(:line_item_actionable?).and_return(true)
+
+ line_item = order.line_items.first
+ expect(expensive.compute_amount(line_item)).to eq(-line_item.amount)
+ end
+
+ it 'returns 0 for non-actionable line items' do
+ allow(promotion).to receive(:line_item_actionable?).and_return(false)
+ expect(action.compute_amount(order.line_items.first)).to eq(0)
+ end
+ end
+
+ it 'has line_item discount scope' do
+ expect(action.discount_scope).to eq(:line_item)
+ end
+end
diff --git a/spree/core/spec/models/spree/promotion/actions/create_line_items_spec.rb b/spree/core/spec/models/spree/promotion_actions/create_line_items_spec.rb
similarity index 96%
rename from spree/core/spec/models/spree/promotion/actions/create_line_items_spec.rb
rename to spree/core/spec/models/spree/promotion_actions/create_line_items_spec.rb
index b3857249af..7860dbc00c 100644
--- a/spree/core/spec/models/spree/promotion/actions/create_line_items_spec.rb
+++ b/spree/core/spec/models/spree/promotion_actions/create_line_items_spec.rb
@@ -1,8 +1,8 @@
require 'spec_helper'
-describe Spree::Promotion::Actions::CreateLineItems, type: :model do
+describe Spree::PromotionActions::CreateLineItems, type: :model do
let(:order) { create(:order) }
- let(:action) { Spree::Promotion::Actions::CreateLineItems.create!(promotion: promotion) }
+ let(:action) { Spree::PromotionActions::CreateLineItems.create!(promotion: promotion) }
let(:promotion) { create(:promotion) }
let(:shirt) { create(:variant) }
let(:mug) { create(:variant) }
diff --git a/spree/core/spec/models/spree/promotion_actions/free_shipping_spec.rb b/spree/core/spec/models/spree/promotion_actions/free_shipping_spec.rb
new file mode 100644
index 0000000000..dc546fc7ef
--- /dev/null
+++ b/spree/core/spec/models/spree/promotion_actions/free_shipping_spec.rb
@@ -0,0 +1,38 @@
+require 'spec_helper'
+
+describe Spree::PromotionActions::FreeShipping, type: :model do
+ let(:order) { create(:order_with_line_items, line_items_count: 1) }
+ let(:promotion) { create(:promotion, kind: :automatic, code: nil, stores: [order.store]) }
+ let(:action) { described_class.create!(promotion: promotion) }
+
+ describe '#perform' do
+ it 'writes a fulfillment discount covering the cost' do
+ expect(action.perform(order: order, promotion: promotion)).to be(true)
+
+ rows = order.discounts.reload
+ expect(rows.map(&:fulfillment_id)).to match_array(order.fulfillments.ids)
+ rows.each do |row|
+ expect(row.amount).to eq(-row.fulfillment.cost)
+ end
+ end
+
+ it 'persists rows even at zero cost' do
+ order.fulfillments.each { |fulfillment| fulfillment.update_column(:cost, 0) }
+
+ expect(action.perform(order: order, promotion: promotion)).to be(true)
+ expect(order.discounts.reload.map(&:amount)).to all(eq(0))
+ expect(order.has_free_shipping?).to be(true)
+ end
+
+ it 'reports no action without fulfillments' do
+ order.fulfillments.destroy_all
+ expect(action.perform(order: order, promotion: promotion)).to be(false)
+ end
+ end
+
+ it 'has fulfillment discount scope and persists at zero' do
+ expect(action.discount_scope).to eq(:fulfillment)
+ expect(action.persist_at_zero?).to be(true)
+ expect(action.free_shipping?).to be(true)
+ end
+end
diff --git a/spree/core/spec/models/spree/promotion_handler/cart_spec.rb b/spree/core/spec/models/spree/promotion_handler/cart_spec.rb
index 4550566252..d6e8ee5037 100644
--- a/spree/core/spec/models/spree/promotion_handler/cart_spec.rb
+++ b/spree/core/spec/models/spree/promotion_handler/cart_spec.rb
@@ -12,14 +12,14 @@ module Spree
let(:calculator) { Calculator::FlatPercentItemTotal.new(preferred_flat_percent: 10) }
context 'activates in LineItem level' do
- let!(:action) { Promotion::Actions::CreateItemAdjustments.create(promotion: promotion, calculator: calculator) }
+ let!(:action) { PromotionActions::CreateItemDiscounts.create(promotion: promotion, calculator: calculator) }
let(:adjustable) { line_item }
shared_context 'creates the adjustment' do
it 'creates the adjustment' do
expect do
subject.activate
- end.to change { adjustable.adjustments.count }.by(1)
+ end.to change { adjustable.discounts.count }.by(1)
end
end
@@ -28,14 +28,14 @@ module Spree
end
context 'promotion includes item involved' do
- let!(:rule) { Promotion::Rules::Product.create(products: [line_item.product], promotion: promotion) }
+ let!(:rule) { PromotionRules::Product.create(products: [line_item.product], promotion: promotion) }
include_context 'creates the adjustment'
end
context 'promotion has item total rule' do
let(:shirt) { create(:product, store: order.store) }
- let!(:rule) { Promotion::Rules::ItemTotal.create(preferred_operator_min: 'gt', preferred_amount_min: 50, preferred_operator_max: 'lt', preferred_amount_max: 150, promotion: promotion) }
+ let!(:rule) { PromotionRules::ItemTotal.create(preferred_operator_min: 'gt', preferred_amount_min: 50, preferred_operator_max: 'lt', preferred_amount_max: 150, promotion: promotion) }
before do
# Makes the order eligible for this promotion
@@ -48,14 +48,14 @@ module Spree
end
context 'activates in Order level' do
- let!(:action) { Promotion::Actions::CreateAdjustment.create(promotion: promotion, calculator: calculator) }
+ let!(:action) { PromotionActions::CreateAdjustment.create(promotion: promotion, calculator: calculator) }
let(:adjustable) { order }
shared_context 'creates the adjustment' do
it 'creates the adjustment' do
expect do
subject.activate
- end.to change { adjustable.adjustments.count }.by(1)
+ end.to change { adjustable.discounts.count }.by(1)
end
end
@@ -71,7 +71,7 @@ module Spree
context 'promotion has item total rule' do
let(:shirt) { create(:product, store: order.store) }
- let!(:rule) { Promotion::Rules::ItemTotal.create(preferred_operator_min: 'gt', preferred_amount_min: 50, preferred_operator_max: 'lt', preferred_amount_max: 150, promotion: promotion) }
+ let!(:rule) { PromotionRules::ItemTotal.create(preferred_operator_min: 'gt', preferred_amount_min: 50, preferred_operator_max: 'lt', preferred_amount_max: 150, promotion: promotion) }
before do
# Makes the order eligible for this promotion
@@ -94,7 +94,7 @@ module Spree
it 'creates the adjustment' do
expect do
subject.activate
- end.to change { adjustable.adjustments.count }.by(1)
+ end.to change { adjustable.discounts.count }.by(1)
end
end
end
diff --git a/spree/core/spec/models/spree/promotion_handler/coupon_spec.rb b/spree/core/spec/models/spree/promotion_handler/coupon_spec.rb
index 5edb3682d8..3a6ac0e1f9 100644
--- a/spree/core/spec/models/spree/promotion_handler/coupon_spec.rb
+++ b/spree/core/spec/models/spree/promotion_handler/coupon_spec.rb
@@ -84,7 +84,7 @@ module Spree
subject.apply
expect(subject.success).to be_present
order.line_items.each do |line_item|
- expect(line_item.adjustments.count).to eq(1)
+ expect(line_item.discounts.count).to eq(1)
end
# Ensure that applying the adjustment actually affects the order's total!
expect(order.reload.total).to eq(100)
@@ -112,7 +112,7 @@ module Spree
subject.apply
expect(subject.success).to be_present
order.line_items.each do |line_item|
- expect(line_item.adjustments.count).to eq(1)
+ expect(line_item.discounts.count).to eq(1)
end
# Ensure that applying the adjustment actually affects the order's total!
expect(order.reload.total).to eq(100)
@@ -127,7 +127,7 @@ module Spree
allow(order).to receive_messages coupon_code: '10off'
calculator = Calculator::FlatRate.new(preferred_amount: 10)
general_promo = create(:promotion, name: 'General Promo', store: order.store)
- Promotion::Actions::CreateItemAdjustments.create(promotion: general_promo, calculator: calculator) # general_action
+ PromotionActions::CreateItemDiscounts.create(promotion: general_promo, calculator: calculator) # general_action
Spree::Carts::AddItem.call(order: order, variant: create(:variant))
end
@@ -141,7 +141,7 @@ module Spree
end
context 'with a free-shipping adjustment action' do
- let!(:action) { Promotion::Actions::FreeShipping.create(promotion: promotion) }
+ let!(:action) { PromotionActions::FreeShipping.create(promotion: promotion) }
context 'right coupon code given' do
let(:order) { create(:order_with_line_items, line_items_count: 3, store: store) }
@@ -153,7 +153,7 @@ module Spree
subject.apply
expect(subject.success).to be_present
- expect(order.shipment_adjustments.count).to eq(1)
+ expect(order.fulfillment_discounts.count).to eq(1)
end
it 'coupon already applied to the order' do
@@ -166,23 +166,21 @@ module Spree
end
context 'with a whole-order adjustment action' do
- let!(:action) { Promotion::Actions::CreateAdjustment.create(promotion: promotion, calculator: calculator) }
+ let!(:action) { PromotionActions::CreateAdjustment.create(promotion: promotion, calculator: calculator) }
context 'right coupon given' do
- let(:order) { create(:order, store: store) }
+ let(:order) { create(:order_with_line_items, store: store, line_items_count: 1) }
let(:calculator) { Calculator::FlatRate.new(preferred_amount: 10) }
before do
- allow(order).to receive_messages(coupon_code: '10off',
- # These need to be here so that promotion adjustment "wins"
- item_total: 50,
- ship_total: 10)
+ allow(order).to receive_messages(coupon_code: '10off')
end
- it 'successfully activates promo' do
+ it 'successfully activates promo and distributes the discount to line items' do
subject.apply
expect(subject.success).to be_present
- expect(order.adjustments.count).to eq(1)
+ expect(order.discounts.count).to eq(1)
+ expect(order.discounts.sum(:amount)).to eq(-10)
end
it 'coupon already applied to the order' do
@@ -287,7 +285,7 @@ module Spree
context 'with a CreateLineItems action' do
let!(:variant) { create(:variant) }
- let!(:action) { Promotion::Actions::CreateLineItems.create(promotion: promotion) }
+ let!(:action) { PromotionActions::CreateLineItems.create(promotion: promotion) }
let(:order) { create(:order, store: store) }
before do
@@ -315,7 +313,7 @@ module Spree
end
let!(:promotion) { create(:promotion, name: 'promo', code: nil, multi_codes: true, number_of_codes: 1) }
let!(:coupon_code) { promotion.coupon_codes.first }
- let!(:action) { Spree::Promotion::Actions::CreateItemAdjustments.create(promotion: promotion, calculator: calculator) }
+ let!(:action) { Spree::PromotionActions::CreateItemDiscounts.create(promotion: promotion, calculator: calculator) }
context 'valid coupon' do
before { order.coupon_code = coupon_code.code }
@@ -329,7 +327,7 @@ module Spree
expect(coupon_code.order).to eq(order)
order.line_items.each do |line_item|
- expect(line_item.adjustments.count).to eq(1)
+ expect(line_item.discounts.count).to eq(1)
end
expect(order.reload.total).to eq(100)
end
@@ -370,7 +368,7 @@ module Spree
expect(coupon_code.order).to be_nil
expect(order.promotions).to be_empty
- expect(order.line_item_adjustments).to be_empty
+ expect(order.line_item_discounts).to be_empty
end
it 'touches the promotion' do
@@ -389,7 +387,7 @@ module Spree
context 'one common promotion code' do
let!(:promotion) { create(:promotion, name: 'promo', code: '10off', usage_limit: 1) }
let!(:action) do
- Spree::Promotion::Actions::CreateItemAdjustments.create(promotion: promotion,
+ Spree::PromotionActions::CreateItemDiscounts.create(promotion: promotion,
calculator: calculator)
end
let!(:order_2) { create(:order_with_line_items, line_items_count: 3, user: user) }
@@ -429,7 +427,7 @@ module Spree
end
let!(:action) do
- Spree::Promotion::Actions::CreateItemAdjustments.create(promotion: promotion,
+ Spree::PromotionActions::CreateItemDiscounts.create(promotion: promotion,
calculator: calculator)
end
diff --git a/spree/core/spec/models/spree/promotion_handler/free_shipping_spec.rb b/spree/core/spec/models/spree/promotion_handler/free_shipping_spec.rb
index 57de6af8d4..95283d8556 100644
--- a/spree/core/spec/models/spree/promotion_handler/free_shipping_spec.rb
+++ b/spree/core/spec/models/spree/promotion_handler/free_shipping_spec.rb
@@ -12,49 +12,49 @@ module Spree
context 'activates in Shipment level' do
let(:promotion) { create(:promotion, name: 'Free Shipping', store: order.store, kind: :automatic) }
- let!(:action) { Promotion::Actions::FreeShipping.create(promotion: promotion) }
+ let!(:action) { PromotionActions::FreeShipping.create(promotion: promotion) }
it 'creates the adjustment' do
- expect { subject.activate }.to change { shipment.adjustments.count }.by(1)
+ expect { subject.activate }.to change { shipment.discounts.count }.by(1)
end
end
context 'if promo has a code' do
let(:promotion) { create(:promotion, name: 'Free Shipping', store: order.store, code: 'code') }
- let!(:action) { Spree::Promotion::Actions::FreeShipping.create(promotion: promotion) }
+ let!(:action) { Spree::PromotionActions::FreeShipping.create(promotion: promotion) }
it 'does adjust the shipment when applied to order' do
order.promotions << promotion
- expect { subject.activate }.to change { shipment.adjustments.count }
+ expect { subject.activate }.to change { shipment.discounts.count }
end
it 'does not adjust the shipment when not applied to order' do
- expect { subject.activate }.not_to change { shipment.adjustments.count }
+ expect { subject.activate }.not_to change { shipment.discounts.count }
end
end
context 'if promo has multiple codes' do
let(:promotion) { create(:promotion, name: 'Free Shipping', store: order.store, multi_codes: true, number_of_codes: 1) }
- let!(:action) { Spree::Promotion::Actions::FreeShipping.create(promotion: promotion) }
+ let!(:action) { Spree::PromotionActions::FreeShipping.create(promotion: promotion) }
it 'does adjust the shipment when applied to order' do
order.promotions << promotion
- expect { subject.activate }.to change { shipment.adjustments.count }
+ expect { subject.activate }.to change { shipment.discounts.count }
end
it 'does not adjust the shipment when not applied to order' do
- expect { subject.activate }.not_to change { shipment.adjustments.count }
+ expect { subject.activate }.not_to change { shipment.discounts.count }
end
end
context 'if promo has a path' do
let(:promotion) { create(:promotion, name: 'Free Shipping', store: order.store, kind: :automatic, path: 'path') }
- let!(:action) { Promotion::Actions::FreeShipping.create(promotion: promotion) }
+ let!(:action) { PromotionActions::FreeShipping.create(promotion: promotion) }
it 'does not adjust the shipment' do
- expect { subject.activate }.not_to change { shipment.adjustments.count }
+ expect { subject.activate }.not_to change { shipment.discounts.count }
end
end
end
diff --git a/spree/core/spec/models/spree/promotion_handler/page_spec.rb b/spree/core/spec/models/spree/promotion_handler/page_spec.rb
index 0342277349..6cb8cd253a 100644
--- a/spree/core/spec/models/spree/promotion_handler/page_spec.rb
+++ b/spree/core/spec/models/spree/promotion_handler/page_spec.rb
@@ -9,14 +9,14 @@ module Spree
before do
calculator = Calculator::FlatPercentItemTotal.new(preferred_flat_percent: 10)
- action = Promotion::Actions::CreateItemAdjustments.create(calculator: calculator)
+ action = PromotionActions::CreateItemDiscounts.create(calculator: calculator)
promotion.actions << action
end
it 'activates at the right path' do
- expect(order.line_item_adjustments.count).to eq(0)
+ expect(order.line_item_discounts.count).to eq(0)
Spree::PromotionHandler::Page.new(order, '10off').activate
- expect(order.line_item_adjustments.count).to eq(1)
+ expect(order.line_item_discounts.count).to eq(1)
end
context 'when promotion is expired' do
@@ -28,16 +28,16 @@ module Spree
end
it 'is not activated' do
- expect(order.line_item_adjustments.count).to eq(0)
+ expect(order.line_item_discounts.count).to eq(0)
Spree::PromotionHandler::Page.new(order, '10off').activate
- expect(order.line_item_adjustments.count).to eq(0)
+ expect(order.line_item_discounts.count).to eq(0)
end
end
it 'does not activate at the wrong path' do
- expect(order.line_item_adjustments.count).to eq(0)
+ expect(order.line_item_discounts.count).to eq(0)
Spree::PromotionHandler::Page.new(order, 'wrongpath').activate
- expect(order.line_item_adjustments.count).to eq(0)
+ expect(order.line_item_discounts.count).to eq(0)
end
end
end
diff --git a/spree/core/spec/models/spree/promotion_handler/promotion_duplicator_spec.rb b/spree/core/spec/models/spree/promotion_handler/promotion_duplicator_spec.rb
index 8e75e967e4..04866ebc07 100644
--- a/spree/core/spec/models/spree/promotion_handler/promotion_duplicator_spec.rb
+++ b/spree/core/spec/models/spree/promotion_handler/promotion_duplicator_spec.rb
@@ -22,7 +22,7 @@ describe Spree::PromotionHandler::PromotionDuplicator do
end
before do
- Spree::Promotion::Actions::CreateItemAdjustments.create!(calculator: calculator, promotion: promotion)
+ Spree::PromotionActions::CreateItemDiscounts.create!(calculator: calculator, promotion: promotion)
end
describe '#duplicate' do
diff --git a/spree/core/spec/models/spree/promotion/rules/channel_spec.rb b/spree/core/spec/models/spree/promotion_rules/channel_spec.rb
similarity index 97%
rename from spree/core/spec/models/spree/promotion/rules/channel_spec.rb
rename to spree/core/spec/models/spree/promotion_rules/channel_spec.rb
index 813c8bb9f5..fddd71af98 100644
--- a/spree/core/spec/models/spree/promotion/rules/channel_spec.rb
+++ b/spree/core/spec/models/spree/promotion_rules/channel_spec.rb
@@ -1,6 +1,6 @@
require 'spec_helper'
-describe Spree::Promotion::Rules::Channel, type: :model do
+describe Spree::PromotionRules::Channel, type: :model do
let(:store) { @default_store }
let(:promotion) { create(:promotion, store: store) }
let(:rule) { described_class.new(promotion: promotion) }
diff --git a/spree/core/spec/models/spree/promotion/rules/country_spec.rb b/spree/core/spec/models/spree/promotion_rules/country_spec.rb
similarity index 97%
rename from spree/core/spec/models/spree/promotion/rules/country_spec.rb
rename to spree/core/spec/models/spree/promotion_rules/country_spec.rb
index 4315504d04..fd41c2a5d0 100644
--- a/spree/core/spec/models/spree/promotion/rules/country_spec.rb
+++ b/spree/core/spec/models/spree/promotion_rules/country_spec.rb
@@ -1,6 +1,6 @@
require 'spec_helper'
-describe Spree::Promotion::Rules::Country, type: :model do
+describe Spree::PromotionRules::Country, type: :model do
let!(:store) { create(:store, default_country: other_country) }
let(:rule) { described_class.new }
let(:order) { create(:order, store: store) }
diff --git a/spree/core/spec/models/spree/promotion/rules/currency_spec.rb b/spree/core/spec/models/spree/promotion_rules/currency_spec.rb
similarity index 94%
rename from spree/core/spec/models/spree/promotion/rules/currency_spec.rb
rename to spree/core/spec/models/spree/promotion_rules/currency_spec.rb
index de95e7a619..e6d8ee8ec3 100644
--- a/spree/core/spec/models/spree/promotion/rules/currency_spec.rb
+++ b/spree/core/spec/models/spree/promotion_rules/currency_spec.rb
@@ -1,6 +1,6 @@
require 'spec_helper'
-describe Spree::Promotion::Rules::Currency, type: :model do
+describe Spree::PromotionRules::Currency, type: :model do
let(:store) { @default_store }
let(:rule) { described_class.new }
let(:order) { create(:order, store: store) }
diff --git a/spree/core/spec/models/spree/promotion/rules/customer_group_spec.rb b/spree/core/spec/models/spree/promotion_rules/customer_group_spec.rb
similarity index 94%
rename from spree/core/spec/models/spree/promotion/rules/customer_group_spec.rb
rename to spree/core/spec/models/spree/promotion_rules/customer_group_spec.rb
index d2e1441674..ea38a3c2e8 100644
--- a/spree/core/spec/models/spree/promotion/rules/customer_group_spec.rb
+++ b/spree/core/spec/models/spree/promotion_rules/customer_group_spec.rb
@@ -1,8 +1,8 @@
require 'spec_helper'
-describe Spree::Promotion::Rules::CustomerGroup, type: :model do
+describe Spree::PromotionRules::CustomerGroup, type: :model do
let(:store) { @default_store }
- let(:rule) { Spree::Promotion::Rules::CustomerGroup.new }
+ let(:rule) { Spree::PromotionRules::CustomerGroup.new }
let(:customer_group) { create(:customer_group, store: store) }
let(:other_customer_group) { create(:customer_group, store: store) }
let(:user) { create(:user) }
diff --git a/spree/core/spec/models/spree/promotion/rules/first_order_spec.rb b/spree/core/spec/models/spree/promotion_rules/first_order_spec.rb
similarity index 97%
rename from spree/core/spec/models/spree/promotion/rules/first_order_spec.rb
rename to spree/core/spec/models/spree/promotion_rules/first_order_spec.rb
index e1fced8443..842e5f38b1 100644
--- a/spree/core/spec/models/spree/promotion/rules/first_order_spec.rb
+++ b/spree/core/spec/models/spree/promotion_rules/first_order_spec.rb
@@ -1,6 +1,6 @@
require 'spec_helper'
-describe Spree::Promotion::Rules::FirstOrder, type: :model do
+describe Spree::PromotionRules::FirstOrder, type: :model do
let(:store) { @default_store }
let(:rule) { described_class.new }
let(:user) { create(:user) }
diff --git a/spree/core/spec/models/spree/promotion/rules/item_total_spec.rb b/spree/core/spec/models/spree/promotion_rules/item_total_spec.rb
similarity index 98%
rename from spree/core/spec/models/spree/promotion/rules/item_total_spec.rb
rename to spree/core/spec/models/spree/promotion_rules/item_total_spec.rb
index 303b318a33..13d385f870 100644
--- a/spree/core/spec/models/spree/promotion/rules/item_total_spec.rb
+++ b/spree/core/spec/models/spree/promotion_rules/item_total_spec.rb
@@ -1,8 +1,8 @@
require 'spec_helper'
-describe Spree::Promotion::Rules::ItemTotal, type: :model do
+describe Spree::PromotionRules::ItemTotal, type: :model do
let!(:store) { @default_store }
- let(:rule) { Spree::Promotion::Rules::ItemTotal.new }
+ let(:rule) { Spree::PromotionRules::ItemTotal.new }
let(:order) { build(:order, store: store) }
before do
diff --git a/spree/core/spec/models/spree/promotion/rules/market_spec.rb b/spree/core/spec/models/spree/promotion_rules/market_spec.rb
similarity index 97%
rename from spree/core/spec/models/spree/promotion/rules/market_spec.rb
rename to spree/core/spec/models/spree/promotion_rules/market_spec.rb
index 92ffca4059..b7c2531b22 100644
--- a/spree/core/spec/models/spree/promotion/rules/market_spec.rb
+++ b/spree/core/spec/models/spree/promotion_rules/market_spec.rb
@@ -1,6 +1,6 @@
require 'spec_helper'
-describe Spree::Promotion::Rules::Market, type: :model do
+describe Spree::PromotionRules::Market, type: :model do
let(:store) { @default_store }
let(:promotion) { create(:promotion, store: store) }
let(:rule) { described_class.new(promotion: promotion) }
diff --git a/spree/core/spec/models/spree/promotion/rules/one_use_per_user_spec.rb b/spree/core/spec/models/spree/promotion_rules/one_use_per_user_spec.rb
similarity index 95%
rename from spree/core/spec/models/spree/promotion/rules/one_use_per_user_spec.rb
rename to spree/core/spec/models/spree/promotion_rules/one_use_per_user_spec.rb
index 802ee13881..18ee7860ab 100644
--- a/spree/core/spec/models/spree/promotion/rules/one_use_per_user_spec.rb
+++ b/spree/core/spec/models/spree/promotion_rules/one_use_per_user_spec.rb
@@ -1,6 +1,6 @@
require 'spec_helper'
-describe Spree::Promotion::Rules::OneUsePerUser, type: :model do
+describe Spree::PromotionRules::OneUsePerUser, type: :model do
let(:rule) { described_class.new }
describe '#eligible?(order)' do
diff --git a/spree/core/spec/models/spree/promotion/rules/option_value_spec.rb b/spree/core/spec/models/spree/promotion_rules/option_value_spec.rb
similarity index 98%
rename from spree/core/spec/models/spree/promotion/rules/option_value_spec.rb
rename to spree/core/spec/models/spree/promotion_rules/option_value_spec.rb
index 1a16596f1c..97bc305ea0 100644
--- a/spree/core/spec/models/spree/promotion/rules/option_value_spec.rb
+++ b/spree/core/spec/models/spree/promotion_rules/option_value_spec.rb
@@ -1,6 +1,6 @@
require 'spec_helper'
-describe Spree::Promotion::Rules::OptionValue do
+describe Spree::PromotionRules::OptionValue do
let(:rule) { described_class.new }
describe 'setting eligible values' do
diff --git a/spree/core/spec/models/spree/promotion/rules/product_spec.rb b/spree/core/spec/models/spree/promotion_rules/product_spec.rb
similarity index 98%
rename from spree/core/spec/models/spree/promotion/rules/product_spec.rb
rename to spree/core/spec/models/spree/promotion_rules/product_spec.rb
index 32617b2642..c13c4263be 100644
--- a/spree/core/spec/models/spree/promotion/rules/product_spec.rb
+++ b/spree/core/spec/models/spree/promotion_rules/product_spec.rb
@@ -1,7 +1,7 @@
require 'spec_helper'
-describe Spree::Promotion::Rules::Product, type: :model do
- let(:rule) { Spree::Promotion::Rules::Product.new(rule_options) }
+describe Spree::PromotionRules::Product, type: :model do
+ let(:rule) { Spree::PromotionRules::Product.new(rule_options) }
let(:rule_options) { {} }
describe '#eligible?(order)' do
diff --git a/spree/core/spec/models/spree/promotion/rules/taxon_spec.rb b/spree/core/spec/models/spree/promotion_rules/taxon_spec.rb
similarity index 98%
rename from spree/core/spec/models/spree/promotion/rules/taxon_spec.rb
rename to spree/core/spec/models/spree/promotion_rules/taxon_spec.rb
index db016c6132..6d062f127e 100644
--- a/spree/core/spec/models/spree/promotion/rules/taxon_spec.rb
+++ b/spree/core/spec/models/spree/promotion_rules/taxon_spec.rb
@@ -1,6 +1,6 @@
require 'spec_helper'
-describe Spree::Promotion::Rules::Category, type: :model do
+describe Spree::PromotionRules::Category, type: :model do
let(:store) { @default_store }
let(:promotion) { create(:promotion) }
let(:rule) { create(:promotion_rule_taxon, promotion: promotion) }
diff --git a/spree/core/spec/models/spree/promotion/rules/user_logged_in_spec.rb b/spree/core/spec/models/spree/promotion_rules/user_logged_in_spec.rb
similarity index 84%
rename from spree/core/spec/models/spree/promotion/rules/user_logged_in_spec.rb
rename to spree/core/spec/models/spree/promotion_rules/user_logged_in_spec.rb
index 4985ec3cd2..86b4ff3238 100644
--- a/spree/core/spec/models/spree/promotion/rules/user_logged_in_spec.rb
+++ b/spree/core/spec/models/spree/promotion_rules/user_logged_in_spec.rb
@@ -1,7 +1,7 @@
require 'spec_helper'
-describe Spree::Promotion::Rules::UserLoggedIn, type: :model do
- let(:rule) { Spree::Promotion::Rules::UserLoggedIn.new }
+describe Spree::PromotionRules::UserLoggedIn, type: :model do
+ let(:rule) { Spree::PromotionRules::UserLoggedIn.new }
context '#eligible?(order)' do
let(:order) { Spree::Order.new }
diff --git a/spree/core/spec/models/spree/promotion/rules/user_spec.rb b/spree/core/spec/models/spree/promotion_rules/user_spec.rb
similarity index 95%
rename from spree/core/spec/models/spree/promotion/rules/user_spec.rb
rename to spree/core/spec/models/spree/promotion_rules/user_spec.rb
index 5a1ac30740..a3b2fb662a 100644
--- a/spree/core/spec/models/spree/promotion/rules/user_spec.rb
+++ b/spree/core/spec/models/spree/promotion_rules/user_spec.rb
@@ -1,7 +1,7 @@
require 'spec_helper'
-describe Spree::Promotion::Rules::User, type: :model do
- let(:rule) { Spree::Promotion::Rules::User.new }
+describe Spree::PromotionRules::User, type: :model do
+ let(:rule) { Spree::PromotionRules::User.new }
let(:random_user) { create :user }
let(:user_placing_order) { create :user }
diff --git a/spree/core/spec/models/spree/promotion_spec.rb b/spree/core/spec/models/spree/promotion_spec.rb
index 6baa6c42ad..6cb5ee737d 100644
--- a/spree/core/spec/models/spree/promotion_spec.rb
+++ b/spree/core/spec/models/spree/promotion_spec.rb
@@ -169,8 +169,8 @@ describe Spree::Promotion, type: :model do
let(:promotion) { create(:promotion, name: 'delete me', kind: :automatic) }
before do
- promotion.actions << Spree::Promotion::Actions::CreateAdjustment.new
- promotion.rules << Spree::Promotion::Rules::FirstOrder.new
+ promotion.actions << Spree::PromotionActions::CreateAdjustment.new
+ promotion.rules << Spree::PromotionRules::FirstOrder.new
promotion.save!
end
@@ -201,8 +201,8 @@ describe Spree::Promotion, type: :model do
let(:promotion) { create(:promotion, name: 'delete me', kind: :automatic) }
before do
- promotion.actions << Spree::Promotion::Actions::CreateAdjustment.new
- promotion.rules << Spree::Promotion::Rules::FirstOrder.new
+ promotion.actions << Spree::PromotionActions::CreateAdjustment.new
+ promotion.rules << Spree::PromotionRules::FirstOrder.new
promotion.save!
end
@@ -256,8 +256,8 @@ describe Spree::Promotion, type: :model do
end
describe '#activate' do
- let(:action1) { Spree::Promotion::Actions::CreateAdjustment.create!(promotion: promotion) }
- let(:action2) { Spree::Promotion::Actions::CreateAdjustment.create!(promotion: promotion) }
+ let(:action1) { Spree::PromotionActions::CreateAdjustment.create!(promotion: promotion) }
+ let(:action2) { Spree::PromotionActions::CreateAdjustment.create!(promotion: promotion) }
let(:user) { create(:user) }
let(:order) { create(:order, user: user) }
let(:payload) { { order: order, user: user } }
@@ -377,31 +377,30 @@ describe Spree::Promotion, type: :model do
let!(:action) do
calculator = Spree::Calculator::FlatRate.new
- action_params = { promotion: promotion, calculator: calculator }
- action = Spree::Promotion::Actions::CreateAdjustment.create(action_params)
+ action = Spree::PromotionActions::CreateAdjustment.create(promotion: promotion, calculator: calculator)
promotion.actions << action
action
end
- let!(:adjustment) do
- order = create(:order)
- Spree::Adjustment.create!(
- order: order,
- adjustable: order,
- source: action,
- amount: 10,
- label: 'Promotional adjustment'
- )
+ let(:order) { create(:order_with_line_items, line_items_count: 1) }
+
+ let!(:discount) do
+ create(:discount,
+ order: order,
+ line_item: order.line_items.first,
+ promotion_action: action,
+ promotion: promotion,
+ kind: 'promotion',
+ amount: -10,
+ label: 'Promotional discount')
end
- it 'counts eligible adjustments' do
- adjustment.update_column(:eligible, true)
+ it 'counts applied discounts' do
expect(promotion.credits_count).to eq(1)
end
- # Regression test for #4112
- it 'does not count ineligible adjustments' do
- adjustment.update_column(:eligible, false)
+ it 'does not count manual discounts' do
+ discount.update!(kind: 'manual', promotion_action: nil, promotion: nil)
expect(promotion.credits_count).to eq(0)
end
@@ -409,43 +408,40 @@ describe Spree::Promotion, type: :model do
context 'with multiple actions on the same order' do
let!(:second_action) do
calculator = Spree::Calculator::FlatRate.new
- action = Spree::Promotion::Actions::CreateAdjustment.create(promotion: promotion, calculator: calculator)
+ action = Spree::PromotionActions::CreateAdjustment.create(promotion: promotion, calculator: calculator)
promotion.actions << action
action
end
before do
- order = adjustment.order
- Spree::Adjustment.create!(
- order: order,
- adjustable: order,
- source: second_action,
- amount: -5,
- label: 'Second promotional adjustment'
- )
- # mark both adjustments eligible
- order.all_adjustments.update_all(eligible: true)
+ create(:discount,
+ order: order,
+ line_item: order.line_items.first,
+ promotion_action: second_action,
+ promotion: promotion,
+ kind: 'promotion',
+ amount: -5,
+ label: 'Second promotional discount')
end
- it 'counts unique orders, not individual adjustments' do
+ it 'counts unique orders, not individual discounts' do
expect(promotion.credits_count).to eq(1)
end
end
# Regression test for #11879
context 'with the same action applied to multiple orders' do
- let!(:second_order) { create(:order) }
+ let!(:second_order) { create(:order_with_line_items, line_items_count: 1) }
before do
- Spree::Adjustment.create!(
- order: second_order,
- adjustable: second_order,
- source: action,
- amount: 10,
- label: 'Promotional adjustment'
- )
- adjustment.update_column(:eligible, true)
- second_order.all_adjustments.update_all(eligible: true)
+ create(:discount,
+ order: second_order,
+ line_item: second_order.line_items.first,
+ promotion_action: action,
+ promotion: promotion,
+ kind: 'promotion',
+ amount: -10,
+ label: 'Promotional discount')
end
it 'counts each order separately' do
@@ -459,42 +455,44 @@ describe Spree::Promotion, type: :model do
let(:line_item) { create :line_item, order: order }
let(:promotion) { create(:promotion, name: 'promo', code: '10off') }
let(:order_action) do
- action = Spree::Promotion::Actions::CreateAdjustment.create(calculator: Spree::Calculator::FlatPercentItemTotal.new)
+ action = Spree::PromotionActions::CreateAdjustment.create(calculator: Spree::Calculator::FlatPercentItemTotal.new)
promotion.actions << action
action
end
let(:item_action) do
- action = Spree::Promotion::Actions::CreateItemAdjustments.create(calculator: Spree::Calculator::FlatPercentItemTotal.new)
+ action = Spree::PromotionActions::CreateItemDiscounts.create(calculator: Spree::Calculator::FlatPercentItemTotal.new)
promotion.actions << action
action
end
- let(:order_adjustment) do
- Spree::Adjustment.create!(
- source: order_action,
- amount: 10,
- adjustable: order,
- order: order,
- label: 'Promotional adjustment'
- )
- end
- let(:item_adjustment) do
- Spree::Adjustment.create!(
- source: item_action,
- amount: 10,
- adjustable: line_item,
- order: order,
- label: 'Promotional adjustment'
- )
- end
-
- it 'counts order level adjustments' do
- expect(order_adjustment.adjustable).to eq(order)
+ let(:order_discount) do
+ create(:discount,
+ order: order,
+ line_item: line_item,
+ promotion_action: order_action,
+ promotion: promotion,
+ kind: 'promotion',
+ amount: -10,
+ label: 'Promotional discount')
+ end
+ let(:item_discount) do
+ create(:discount,
+ order: order,
+ line_item: line_item,
+ promotion_action: item_action,
+ promotion: promotion,
+ kind: 'promotion',
+ amount: -10,
+ label: 'Promotional discount')
+ end
+
+ it 'does not count the current order against its own limit (order-level action)' do
+ expect(order_discount.order).to eq(order)
expect(promotion.credits_count).to eq(1)
expect(promotion.adjusted_credits_count(order)).to eq(0)
end
- it 'counts item level adjustments' do
- expect(item_adjustment.adjustable).to eq(line_item)
+ it 'does not count the current order against its own limit (item-level action)' do
+ expect(item_discount.line_item).to eq(line_item)
expect(promotion.credits_count).to eq(1)
expect(promotion.adjusted_credits_count(order)).to eq(0)
end
@@ -505,7 +503,7 @@ describe Spree::Promotion, type: :model do
let(:promotion) { create(:promotion, kind: :automatic) }
context 'when it has product rules with products associated' do
- let(:promotion_rule) { create(:promotion_rule, promotion: promotion, type: 'Spree::Promotion::Rules::Product') }
+ let(:promotion_rule) { create(:promotion_rule, promotion: promotion, type: 'Spree::PromotionRules::Product') }
before do
promotion.promotion_rules << promotion_rule
@@ -606,8 +604,8 @@ describe Spree::Promotion, type: :model do
context "with 'all' match policy" do
# Two distinct STI subclasses — uniqueness scopes on `(promotion_id, type)`,
# so re-using the abstract base would fail validation for the second row.
- let(:promo1) { Spree::Promotion::Rules::FirstOrder.create!(promotion: promotion) }
- let(:promo2) { Spree::Promotion::Rules::OneUsePerUser.create!(promotion: promotion) }
+ let(:promo1) { Spree::PromotionRules::FirstOrder.create!(promotion: promotion) }
+ let(:promo2) { Spree::PromotionRules::OneUsePerUser.create!(promotion: promotion) }
before { promotion.match_policy = 'all' }
@@ -818,12 +816,9 @@ describe Spree::Promotion, type: :model do
context 'when the order is complete' do
it { is_expected.to be true }
- context 'when the promotion is not eligible' do
- let(:adjustment) { order.adjustments.first }
-
+ context 'when the promotion discount was removed' do
before do
- adjustment.eligible = false
- adjustment.save!
+ order.discounts.destroy_all
end
it { is_expected.to be false }
@@ -855,20 +850,20 @@ describe Spree::Promotion, type: :model do
let(:variant) { create :variant }
it 'updates the promotions for new line items' do
- expect(line_item.adjustments).to be_empty
+ expect(line_item.discounts).to be_empty
expect(order.adjustment_total).to eq 0
promo.activate(order: order)
order.update_with_updater!
line_item.reload
- expect(line_item.adjustments.size).to eq(1)
+ expect(line_item.discounts.size).to eq(1)
expect(order.adjustment_total).to eq(-5)
other_line_item = Spree::Carts::AddItem.call(order: order, variant: variant, options: { currency: order.currency }).value
expect(other_line_item).not_to eq line_item
- expect(other_line_item.adjustments.size).to eq(1)
+ expect(other_line_item.discounts.size).to eq(1)
expect(order.adjustment_total).to eq(-10)
end
end
@@ -933,12 +928,12 @@ describe Spree::Promotion, type: :model do
promotion.reload
expect(promotion.rules.size).to eq(1)
- expect(promotion.rules.first).to be_a(Spree::Promotion::Rules::ItemTotal)
+ expect(promotion.rules.first).to be_a(Spree::PromotionRules::ItemTotal)
expect(promotion.rules.first.preferred_amount_min).to eq(50)
end
it 'updates an existing rule when matched by id' do
- existing = promotion.rules.create!(type: 'Spree::Promotion::Rules::ItemTotal', preferences: { amount_min: 10 })
+ existing = promotion.rules.create!(type: 'Spree::PromotionRules::ItemTotal', preferences: { amount_min: 10 })
promotion.rules = [{ id: existing.id, type: 'item_total', preferences: { amount_min: 99 } }]
promotion.reload
@@ -949,8 +944,8 @@ describe Spree::Promotion, type: :model do
end
it 'destroys rules omitted from the payload' do
- kept = promotion.rules.create!(type: 'Spree::Promotion::Rules::ItemTotal', preferences: { amount_min: 10 })
- removed = promotion.rules.create!(type: 'Spree::Promotion::Rules::FirstOrder')
+ kept = promotion.rules.create!(type: 'Spree::PromotionRules::ItemTotal', preferences: { amount_min: 10 })
+ removed = promotion.rules.create!(type: 'Spree::PromotionRules::FirstOrder')
promotion.rules = [{ id: kept.id, type: 'item_total' }]
promotion.reload
@@ -960,7 +955,7 @@ describe Spree::Promotion, type: :model do
end
it 'destroys all rules when given an empty array' do
- promotion.rules.create!(type: 'Spree::Promotion::Rules::ItemTotal')
+ promotion.rules.create!(type: 'Spree::PromotionRules::ItemTotal')
promotion.rules = []
promotion.reload
@@ -972,8 +967,8 @@ describe Spree::Promotion, type: :model do
# the in-memory collection WITHOUT a reload, since the admin serializer
# renders `rule_ids` off the loaded association on the same object.
it 'reflects a partial removal in the loaded collection without reload' do
- kept = promotion.rules.create!(type: 'Spree::Promotion::Rules::ItemTotal', preferences: { amount_min: 10 })
- removed = promotion.rules.create!(type: 'Spree::Promotion::Rules::FirstOrder')
+ kept = promotion.rules.create!(type: 'Spree::PromotionRules::ItemTotal', preferences: { amount_min: 10 })
+ removed = promotion.rules.create!(type: 'Spree::PromotionRules::FirstOrder')
promotion.promotion_rules.load # eager-load, as the controller scope does
@@ -995,13 +990,13 @@ describe Spree::Promotion, type: :model do
promotion.reload
rule = promotion.rules.first
- expect(rule).to be_a(Spree::Promotion::Rules::Product)
+ expect(rule).to be_a(Spree::PromotionRules::Product)
expect(rule.products).to contain_exactly(product, other_product)
expect(rule.preferred_match_policy).to eq('any')
end
it 'replaces product_ids on an existing Product rule' do
- rule = promotion.rules.create!(type: 'Spree::Promotion::Rules::Product')
+ rule = promotion.rules.create!(type: 'Spree::PromotionRules::Product')
rule.products = [product]
promotion.rules = [{ id: rule.id, type: 'product', product_ids: [other_product.id] }]
@@ -1015,7 +1010,7 @@ describe Spree::Promotion, type: :model do
promotion.reload
rule = promotion.rules.first
- expect(rule).to be_a(Spree::Promotion::Rules::Category)
+ expect(rule).to be_a(Spree::PromotionRules::Category)
expect(rule.taxons).to contain_exactly(taxon)
end
@@ -1029,7 +1024,7 @@ describe Spree::Promotion, type: :model do
fresh.save!
rule = fresh.reload.rules.first
- expect(rule).to be_a(Spree::Promotion::Rules::Category)
+ expect(rule).to be_a(Spree::PromotionRules::Category)
expect(rule.taxons).to contain_exactly(taxon)
end
@@ -1055,7 +1050,7 @@ describe Spree::Promotion, type: :model do
end
it 'falls through to AR when assigned PromotionRule instances' do
- rule = Spree::Promotion::Rules::FirstOrder.new
+ rule = Spree::PromotionRules::FirstOrder.new
promotion.rules = [rule]
expect(promotion.rules).to include(rule)
@@ -1076,7 +1071,7 @@ describe Spree::Promotion, type: :model do
promotion.reload
action = promotion.actions.first
- expect(action).to be_a(Spree::Promotion::Actions::CreateAdjustment)
+ expect(action).to be_a(Spree::PromotionActions::CreateAdjustment)
expect(action.calculator).to be_a(Spree::Calculator::FlatRate)
expect(action.calculator.preferred_amount).to eq(7.5)
expect(action.calculator.preferred_currency).to eq('USD')
@@ -1084,7 +1079,7 @@ describe Spree::Promotion, type: :model do
it 'updates the calculator type on an existing action' do
action = promotion.actions.create!(
- type: 'Spree::Promotion::Actions::CreateAdjustment',
+ type: 'Spree::PromotionActions::CreateAdjustment',
calculator: Spree::Calculator::FlatRate.new(preferred_amount: 5)
)
@@ -1105,12 +1100,12 @@ describe Spree::Promotion, type: :model do
promotion.actions = [{ type: 'free_shipping' }]
promotion.reload
- expect(promotion.actions.first).to be_a(Spree::Promotion::Actions::FreeShipping)
+ expect(promotion.actions.first).to be_a(Spree::PromotionActions::FreeShipping)
end
it 'destroys actions omitted from the payload' do
- kept = promotion.actions.create!(type: 'Spree::Promotion::Actions::FreeShipping')
- removed = promotion.actions.create!(type: 'Spree::Promotion::Actions::CreateAdjustment')
+ kept = promotion.actions.create!(type: 'Spree::PromotionActions::FreeShipping')
+ removed = promotion.actions.create!(type: 'Spree::PromotionActions::CreateAdjustment')
promotion.actions = [{ id: kept.id, type: 'free_shipping' }]
promotion.reload
diff --git a/spree/core/spec/models/spree/promotion_tax_recalculation_spec.rb b/spree/core/spec/models/spree/promotion_tax_recalculation_spec.rb
index a7b8da020f..c12871d69e 100644
--- a/spree/core/spec/models/spree/promotion_tax_recalculation_spec.rb
+++ b/spree/core/spec/models/spree/promotion_tax_recalculation_spec.rb
@@ -33,13 +33,13 @@ describe 'Promotion discounts and the taxable basis', type: :model do
def line_item_promotion(calculator)
create(:promotion, code: 'DISCOUNT', store: store).tap do |promotion|
- Spree::Promotion::Actions::CreateItemAdjustments.create!(calculator: calculator, promotion: promotion)
+ Spree::PromotionActions::CreateItemDiscounts.create!(calculator: calculator, promotion: promotion)
end
end
def whole_order_promotion(calculator)
create(:promotion, code: 'DISCOUNT', store: store).tap do |promotion|
- Spree::Promotion::Actions::CreateAdjustment.create!(calculator: calculator, promotion: promotion)
+ Spree::PromotionActions::CreateAdjustment.create!(calculator: calculator, promotion: promotion)
end
end
diff --git a/spree/core/spec/models/spree/shipment_spec.rb b/spree/core/spec/models/spree/shipment_spec.rb
index c8e6f20e3c..cb0ab2d283 100644
--- a/spree/core/spec/models/spree/shipment_spec.rb
+++ b/spree/core/spec/models/spree/shipment_spec.rb
@@ -197,7 +197,8 @@ describe Spree::Shipment, type: :model do
create_shipment(order, stock_location)
create_shipment(order, stock_location)
- create :tax_adjustment, adjustable: order.line_items.first, order: order
+ # 10% additional tax on the 20.00 line
+ order.line_items.first.update_columns(adjustment_total: 2.0, additional_tax_total: 2.0)
expect(order.shipments.first.item_cost).to eq(11.0)
expect(order.shipments.last.item_cost).to eq(11.0)
@@ -205,7 +206,7 @@ describe Spree::Shipment, type: :model do
it 'equals line items final amount with tax' do
shipment = create(:shipment, order: create(:order_with_line_item_quantity, line_items_quantity: 2))
- create :tax_adjustment, adjustable: shipment.order.line_items.first, order: shipment.order
+ shipment.order.line_items.first.update_columns(adjustment_total: 2.0, additional_tax_total: 2.0)
expect(shipment.item_cost).to eq(22.0)
end
end
@@ -609,14 +610,14 @@ describe Spree::Shipment, type: :model do
end
# Regression test for #4347
- context 'with adjustments' do
+ context 'with fees' do
before do
- shipment.adjustments << Spree::Adjustment.create(order: order, label: 'Label', amount: 5)
+ create(:fee, order: order, fulfillment: shipment, label: 'Label', amount: 5)
end
it 'transitions to shipped' do
- shipment.update_column(:state, 'ready')
- expect { shipment.ship! }.not_to raise_error
+ shipment.update_column(:status, 'ready')
+ expect { shipment.fulfill! }.not_to raise_error
end
end
end
@@ -772,11 +773,6 @@ describe Spree::Shipment, type: :model do
expect(shipment.fulfilled_at).not_to be_nil
end
- it 'finalizes adjustments' do
-
- expect(shipment.adjustments).to all(receive(:finalize!))
- shipment.fulfill!
- end
end
end
end
@@ -851,29 +847,11 @@ describe Spree::Shipment, type: :model do
expect(shipment.reload.cost).to eq(5)
end
- it 'factors in additional adjustments to adjustment total' do
- shipment.adjustments.create!(
- order: order,
- label: 'Additional',
- amount: 5,
- included: false,
- state: 'closed'
- )
- shipment.update_amounts
+ it 'leaves typed adjustment columns to the order recalculation' do
+ create(:fee, order: shipment.order, fulfillment: shipment, label: 'Additional', amount: 5)
+ shipment.order.update_with_updater!
expect(shipment.reload.adjustment_total).to eq(5)
end
-
- it 'does not factor in included adjustments to adjustment total' do
- shipment.adjustments.create!(
- order: order,
- label: 'Included',
- amount: 5,
- included: true,
- state: 'closed'
- )
- shipment.update_amounts
- expect(shipment.reload.adjustment_total).to eq(0)
- end
end
context 'changes shipping rate via general update' do
@@ -981,26 +959,28 @@ describe Spree::Shipment, type: :model do
end
context 'after_save' do
- context 'line item changes' do
+ context 'cost changes' do
before do
+ shipment.save!
shipment.cost = shipment.cost + 10
end
- it 'triggers adjustment total recalculation' do
- expect(shipment).to receive(:recalculate_adjustments)
+ it 'triggers the order recalculation' do
+ expect(shipment.order).to receive(:update_with_updater!)
shipment.save
end
- it 'does not trigger adjustment recalculation if shipment has shipped' do
- shipment.state = 'shipped'
- expect(shipment).not_to receive(:recalculate_adjustments)
+ it 'does not trigger recalculation if shipment is fulfilled' do
+ shipment.status = 'fulfilled'
+ expect(shipment.order).not_to receive(:update_with_updater!)
shipment.save
end
end
- context 'line item does not change' do
- it 'does not trigger adjustment total recalculation' do
- expect(shipment).not_to receive(:recalculate_adjustments)
+ context 'cost does not change' do
+ it 'does not trigger the order recalculation' do
+ shipment.save!
+ expect(shipment.order).not_to receive(:update_with_updater!)
shipment.save
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 4c5fac277a..30b278ba86 100644
--- a/spree/core/spec/models/spree/shipping_method_spec.rb
+++ b/spree/core/spec/models/spree/shipping_method_spec.rb
@@ -51,12 +51,12 @@ describe Spree::ShippingMethod, type: :model do
allow(Spree::ShippingMethod).to receive_message_chain(:spree_calculators, :shipping_methods).and_return([
Spree::Calculator::Shipping::FlatPercentItemTotal,
Spree::Calculator::Shipping::PriceSack,
- Spree::Calculator::DefaultTax,
+ Spree::Calculator::FlatRate,
DummyShippingCalculator # included as regression test for https://github.com/spree/spree/issues/3109
])
expect(Spree::ShippingMethod.calculators).to eq([Spree::Calculator::Shipping::FlatPercentItemTotal, Spree::Calculator::Shipping::PriceSack, DummyShippingCalculator])
- expect(Spree::ShippingMethod.calculators).not_to eq([Spree::Calculator::DefaultTax])
+ expect(Spree::ShippingMethod.calculators).not_to eq([Spree::Calculator::FlatRate])
end
end
diff --git a/spree/core/spec/models/spree/tax_line_spec.rb b/spree/core/spec/models/spree/tax_line_spec.rb
new file mode 100644
index 0000000000..1996924aec
--- /dev/null
+++ b/spree/core/spec/models/spree/tax_line_spec.rb
@@ -0,0 +1,45 @@
+require 'spec_helper'
+
+describe Spree::TaxLine, type: :model do
+ let(:order) { create(:order_with_line_items, line_items_count: 1) }
+ let(:line_item) { order.line_items.first }
+
+ it 'is valid on a line item' do
+ tax_line = described_class.new(order: order, line_item: line_item, amount: 1, rate: 0.1, label: 'VAT')
+ expect(tax_line).to be_valid
+ end
+
+ it 'accepts a fee as adjustable' do
+ fee = create(:fee, order: order)
+ tax_line = described_class.new(order: order, fee: fee, amount: 0.4, rate: 0.2, label: 'VAT')
+ expect(tax_line).to be_valid
+ expect(tax_line.adjustable).to eq(fee)
+ end
+
+ it 'requires exactly one adjustable' do
+ tax_line = described_class.new(order: order, amount: 1, rate: 0.1, label: 'VAT')
+ expect(tax_line).not_to be_valid
+
+ tax_line.line_item = line_item
+ tax_line.fulfillment = create(:fulfillment, order: order)
+ expect(tax_line).not_to be_valid
+ end
+
+ it 'stays meaningful without a tax rate' do
+ tax_line = create(:tax_line, order: order, line_item: line_item, tax_rate: nil, provider_id: 'avalara', rate: 0.0825)
+ expect(tax_line.reload.rate).to eq(0.0825)
+ expect(tax_line.tax_rate).to be_nil
+ end
+
+ describe 'included vs additional' do
+ let!(:included_line) { create(:tax_line, order: order, line_item: line_item, included: true) }
+ let!(:additional_line) { create(:tax_line, order: order, line_item: line_item, included: false) }
+
+ it 'partitions by the included flag' do
+ expect(described_class.included_in_price).to contain_exactly(included_line)
+ expect(described_class.additional).to contain_exactly(additional_line)
+ expect(included_line).to be_included
+ expect(additional_line).to be_additional
+ end
+ end
+end
diff --git a/spree/core/spec/models/spree/tax_provider/internal_spec.rb b/spree/core/spec/models/spree/tax_provider/internal_spec.rb
new file mode 100644
index 0000000000..939dc5de72
--- /dev/null
+++ b/spree/core/spec/models/spree/tax_provider/internal_spec.rb
@@ -0,0 +1,91 @@
+require 'spec_helper'
+
+describe Spree::TaxProvider::Internal, type: :model do
+ subject(:provider) { described_class.new }
+
+ let(:order) { create(:order_with_line_items, line_items_count: 1) }
+ let(:line_item) { order.line_items.first }
+ let(:zone) do
+ create(:zone, kind: 'country', default_tax: true).tap do |zone|
+ zone.members.create!(zoneable: order.tax_address.country)
+ end
+ end
+
+ describe '#estimate' do
+ context 'with an additional rate' do
+ let!(:rate) { create(:tax_rate, zone: zone, amount: 0.1, tax_category: line_item.tax_category, included_in_price: false) }
+
+ it 'writes a tax line with snapshots' do
+ provider.estimate(order)
+
+ tax_line = order.tax_lines.reload.sole
+ expect(tax_line.amount).to eq(1.0)
+ expect(tax_line.rate).to eq(0.1)
+ expect(tax_line.included).to be(false)
+ expect(tax_line.provider_id).to eq('internal')
+ expect(tax_line.tax_rate).to eq(rate)
+ expect(tax_line.line_item).to eq(line_item)
+ end
+
+ it 'stores the pre-tax amount' do
+ provider.estimate(order)
+ expect(line_item.reload.pre_tax_amount).to eq(10)
+ end
+
+ it 'replaces stale lines on re-estimate' do
+ provider.estimate(order)
+ first_ids = order.tax_lines.reload.ids
+
+ provider.estimate(order)
+ expect(order.tax_lines.reload.ids).not_to eq(first_ids)
+ expect(order.tax_lines.count).to eq(1)
+ end
+
+ it 'removes lines when the zone stops matching' do
+ provider.estimate(order)
+ expect(order.tax_lines.reload.count).to eq(1)
+
+ zone.members.delete_all
+ allow(order).to receive(:tax_zone).and_return(nil)
+ provider.estimate(order)
+ expect(order.tax_lines.reload).to be_empty
+ end
+
+ it 'estimates on the discounted base' do
+ create(:discount, order: order, line_item: line_item, amount: -5, kind: 'manual')
+ line_item.update_column(:taxable_adjustment_total, -5)
+
+ provider.estimate(order)
+ expect(order.tax_lines.reload.sole.amount).to eq(0.5)
+ end
+ end
+
+ context 'with an included (VAT) rate' do
+ let!(:rate) { create(:tax_rate, zone: zone, amount: 0.2, tax_category: line_item.tax_category, included_in_price: true) }
+
+ it 'backs the tax out of the gross basis' do
+ provider.estimate(order)
+
+ tax_line = order.tax_lines.reload.sole
+ expect(tax_line.amount).to eq(1.67)
+ expect(tax_line.included).to be(true)
+ expect(line_item.reload.pre_tax_amount.round(2)).to eq(8.33)
+ end
+ end
+
+ context 'with a taxable fee' do
+ let!(:rate) do
+ create(:tax_rate, zone: zone, amount: 0.1, tax_category: create(:tax_category, is_default: true), included_in_price: false)
+ end
+ let!(:fee) { create(:fee, order: order, amount: 5, kind: 'surcharge', label: 'Handling') }
+
+ it 'writes a tax line against the fee using the default tax category' do
+ provider.estimate(order, [fee])
+
+ tax_line = order.tax_lines.reload.sole
+ expect(tax_line.fee).to eq(fee)
+ expect(tax_line.amount).to eq(0.5)
+ end
+ end
+ end
+end
diff --git a/spree/core/spec/models/spree/tax_rate_spec.rb b/spree/core/spec/models/spree/tax_rate_spec.rb
index 69a8d102ac..e4a4d372f1 100644
--- a/spree/core/spec/models/spree/tax_rate_spec.rb
+++ b/spree/core/spec/models/spree/tax_rate_spec.rb
@@ -5,7 +5,6 @@ describe Spree::TaxRate, type: :model do
let(:order) { create(:order) }
let(:country) { create(:country) }
let(:tax_category) { create(:tax_category) }
- let(:calculator) { Spree::Calculator::FlatRate.new }
it 'returns an empty array when tax_zone is nil' do
allow(order).to receive_messages tax_zone: nil
@@ -33,8 +32,7 @@ describe Spree::TaxRate, type: :model do
name: 'Tax Rate #1',
amount: 1,
zone: @zone,
- tax_category: tax_category,
- calculator: calculator
+ tax_category: tax_category
)
allow(order).to receive_messages tax_zone: @zone
@@ -46,16 +44,14 @@ describe Spree::TaxRate, type: :model do
name: 'Tax Rate #1',
amount: 1,
zone: @zone,
- tax_category: tax_category,
- calculator: calculator
+ tax_category: tax_category
)
rate2 = Spree::TaxRate.create(
name: 'Tax Rate #2',
amount: 2,
zone: @zone,
- tax_category: tax_category,
- calculator: Spree::Calculator::FlatRate.new
+ tax_category: tax_category
)
allow(order).to receive_messages tax_zone: @zone
@@ -71,8 +67,7 @@ describe Spree::TaxRate, type: :model do
name: 'Tax Rate #1',
amount: 1,
zone: @zone,
- tax_category: tax_category,
- calculator: calculator
+ tax_category: tax_category
)
end
@@ -96,7 +91,6 @@ describe Spree::TaxRate, type: :model do
amount: 1,
zone: @zone,
tax_category: tax_category,
- calculator: calculator,
included_in_price: included_in_price)
end
@@ -142,50 +136,7 @@ describe Spree::TaxRate, type: :model do
end
end
- describe '.adjust' do
- let!(:order) { create(:order) }
- let!(:tax_category_1) { create(:tax_category) }
- let!(:tax_category_2) { create(:tax_category) }
- let!(:rate_1) { create(:tax_rate, tax_category: tax_category_1) }
- let!(:rate_2) { create(:tax_rate, tax_category: tax_category_2) }
- let(:line_items) { [line_item] }
-
- context 'with line items' do
- let!(:line_item) { create(:line_item, price: 10.0, quantity: 1, tax_category: tax_category_1, order: order) }
-
- before { allow(Spree::TaxRate).to receive_messages match: [rate_1, rate_2] }
-
- it 'applies adjustments for two tax rates to the order' do
- expect(rate_1).to receive(:adjust)
- expect(rate_2).not_to receive(:adjust)
- Spree::TaxRate.adjust(order, line_items)
- end
- end
-
- context 'without tax rates' do
- let!(:line_item) { create(:line_item, price: 10.0, quantity: 2, tax_category: nil, order: order) }
-
- it 'updates pre_tax_total to match line item cost if no taxes' do
- Spree::TaxRate.adjust(order, line_items)
- expect(line_item.pre_tax_amount).to eq line_item.price * line_item.quantity
- end
- end
-
- context 'with shipments' do
- let(:shipment) { create(:shipment, order: order) }
-
- before do
- allow(Spree::TaxRate).to receive_messages match: [rate_1, rate_2]
- allow(shipment).to receive_messages cost: 10.0, tax_category: tax_category_1, tax_category_id: tax_category_1.id
- end
-
- it 'applies adjustments for two tax rates to the order' do
- expect(rate_1).to receive(:adjust)
- expect(rate_2).not_to receive(:adjust)
- Spree::TaxRate.adjust(order, [shipment])
- end
- end
-
+ describe 'estimating through the tax provider' do
context 'for MOSS taxation in Europe' do
let(:germany) { create :country, name: 'Germany' }
let(:india) { create :country, name: 'India' }
@@ -201,7 +152,6 @@ describe Spree::TaxRate, type: :model do
Spree::TaxRate.create(
name: 'German VAT',
amount: 0.19,
- calculator: Spree::Calculator::DefaultTax.create,
tax_category: moss_category,
zone: germany_zone,
included_in_price: true
@@ -211,7 +161,6 @@ describe Spree::TaxRate, type: :model do
Spree::TaxRate.create(
name: 'French VAT',
amount: 0.25,
- calculator: Spree::Calculator::DefaultTax.create,
tax_category: moss_category,
zone: france_zone,
included_in_price: true
@@ -221,7 +170,6 @@ describe Spree::TaxRate, type: :model do
Spree::TaxRate.create(
name: 'EU_VAT',
amount: 0.19,
- calculator: Spree::Calculator::DefaultTax.create,
tax_category: normal_category,
zone: eu_zone,
included_in_price: true
@@ -246,7 +194,6 @@ describe Spree::TaxRate, type: :model do
end
it 'without an address costs 100 euros including tax' do
- Spree::TaxRate.adjust(order, order.line_items)
order.update_with_updater!
expect(order.display_total).to eq(Spree::Money.new(100))
expect(order.included_tax_total).to eq(15.97)
@@ -254,7 +201,6 @@ describe Spree::TaxRate, type: :model do
it 'to germany costs 100 euros including tax' do
allow(order).to receive(:tax_zone).and_return(germany_zone)
- Spree::TaxRate.adjust(order, order.line_items)
order.update_with_updater!
expect(order.display_total).to eq(Spree::Money.new(100))
expect(order.included_tax_total).to eq(15.97)
@@ -263,7 +209,6 @@ describe Spree::TaxRate, type: :model do
it 'to france costs more including tax' do
allow(order).to receive(:tax_zone).and_return(france_zone)
order.update_line_item_prices!
- Spree::TaxRate.adjust(order, order.line_items)
order.update_with_updater!
expect(order.display_total).to eq(Spree::Money.new(105.04))
expect(order.included_tax_total).to eq(21.01)
@@ -273,10 +218,8 @@ describe Spree::TaxRate, type: :model do
it 'to somewhere else costs the net amount' do
allow(order).to receive(:tax_zone).and_return(india_zone)
order.update_line_item_prices!
- Spree::TaxRate.adjust(order, order.line_items)
order.update_with_updater!
expect(order.included_tax_total).to eq(0)
- expect(order.included_tax_total).to eq(0)
expect(order.display_total).to eq(Spree::Money.new(84.03))
end
end
@@ -285,7 +228,6 @@ describe Spree::TaxRate, type: :model do
it 'to germany costs 100 euros including tax' do
allow(order).to receive(:tax_zone).and_return(germany_zone)
Spree::Carts::AddItem.call(order: order, variant: tshirt.default_variant)
- Spree::TaxRate.adjust(order, order.line_items)
order.update_with_updater!
expect(order.display_total).to eq(Spree::Money.new(100))
expect(order.included_tax_total).to eq(15.97)
@@ -295,7 +237,6 @@ describe Spree::TaxRate, type: :model do
allow(order).to receive(:tax_zone).and_return(france_zone)
Spree::Carts::AddItem.call(order: order, variant: tshirt.default_variant)
order.update_line_item_prices!
- Spree::TaxRate.adjust(order, order.line_items)
order.update_with_updater!
expect(order.display_total).to eq(Spree::Money.new(100.00))
expect(order.included_tax_total).to eq(15.97)
@@ -306,13 +247,47 @@ describe Spree::TaxRate, type: :model do
allow(order).to receive(:tax_zone).and_return(india_zone)
Spree::Carts::AddItem.call(order: order, variant: tshirt.default_variant)
order.update_line_item_prices!
- Spree::TaxRate.adjust(order, order.line_items)
order.update_with_updater!
expect(order.included_tax_total).to eq(0)
expect(order.display_total).to eq(Spree::Money.new(84.03))
end
end
end
+
+ describe 'tax line lifecycle around rate deletion' do
+ let!(:order) { create(:order) }
+ let(:zone) do
+ create(:zone, name: 'Country Zone', kind: 'country', default_tax: true, zone_members: []).tap do |zone|
+ zone.zone_members.create(zoneable: create(:country))
+ end
+ end
+ let(:category) { Spree::TaxCategory.create(name: 'Taxable Foo') }
+ let!(:rate) do
+ Spree::TaxRate.create(name: 'Tax Rate #1', amount: 0.1, tax_category: category, zone: zone)
+ end
+ let(:taxable) { create(:product, tax_category: category) }
+ let!(:line_item) { Spree::Carts::AddItem.call(order: order, variant: taxable.default_variant).value }
+
+ before do
+ allow_any_instance_of(Spree::Order).to receive(:tax_zone).and_return(zone)
+ Spree.tax_provider.estimate(order)
+ end
+
+ it 'keeps the tax line with snapshots when the rate is deleted' do
+ expect(order.tax_lines.reload.count).to eq(1)
+
+ rate.destroy!
+ tax_line = order.tax_lines.reload.sole
+ expect(tax_line.tax_rate_id).to be_nil
+ expect(tax_line.rate).to eq(0.1)
+ end
+
+ it 'drops the line on the next estimate after the rate is gone' do
+ rate.destroy!
+ Spree.tax_provider.estimate(order)
+ expect(order.tax_lines.reload).to be_empty
+ end
+ end
end
describe '.included_tax_amount_for' do
@@ -369,195 +344,10 @@ describe Spree::TaxRate, type: :model do
end
end
- describe '#adjust' do
- before do
- @country = create(:country)
- @zone = create(:zone, name: 'Country Zone', kind: 'country', default_tax: true, zone_members: [])
- @zone.zone_members.create(zoneable: @country)
- @category = Spree::TaxCategory.create name: 'Taxable Foo'
- @category2 = Spree::TaxCategory.create(name: 'Non Taxable')
- @rate1 = Spree::TaxRate.create(
- name: 'Tax Rate #1',
- amount: 0.10,
- calculator: Spree::Calculator::DefaultTax.create,
- tax_category: @category,
- zone: @zone
- )
- @rate2 = Spree::TaxRate.create(
- name: 'Tax Rate #2',
- amount: 0.05,
- calculator: Spree::Calculator::DefaultTax.create,
- tax_category: @category,
- zone: @zone
- )
- @order = Spree::Order.create!
- @taxable = create(:product, tax_category: @category)
- @nontaxable = create(:product, tax_category: @category2)
- end
-
- context 'not taxable line item ' do
- let!(:line_item) { Spree::Carts::AddItem.call(order: @order, variant: @nontaxable.default_variant).value }
-
- it 'does not create a tax adjustment' do
- Spree::TaxRate.adjust(@order, @order.line_items)
- expect(line_item.adjustments.tax.charge.count).to eq(0)
- end
-
- it 'does not create a refund' do
- Spree::TaxRate.adjust(@order, @order.line_items)
- expect(line_item.adjustments.credit.count).to eq(0)
- end
- end
-
- context 'taxable line item' do
- let!(:line_item) { Spree::Carts::AddItem.call(order: @order, variant: @taxable.default_variant).value }
-
- context 'when price includes tax' do
- before do
- @rate1.update_column(:included_in_price, true)
- @rate2.update_column(:included_in_price, true)
- Spree::TaxRate.store_pre_tax_amount(line_item, [@rate1, @rate2])
- end
-
- context 'when zone is contained by default tax zone' do
- it 'creates two adjustments, one for each tax rate' do
- Spree::TaxRate.adjust(@order, @order.line_items)
- expect(line_item.adjustments.count).to eq(2)
- end
-
- it 'does not create a tax refund' do
- Spree::TaxRate.adjust(@order, @order.line_items)
- expect(line_item.adjustments.credit.count).to eq(0)
- end
- end
-
- context "when order's zone is neither the default zone, or included in the default zone, but matches the rate's zone" do
- before do
- new_rate = Spree::TaxRate.create(
- name: 'New Tax Rate',
- amount: 0.2,
- included_in_price: true,
- calculator: Spree::Calculator::DefaultTax.create,
- tax_category: @category,
- zone: create(:zone_with_country)
- )
- allow(@order).to receive(:tax_zone).and_return(new_rate.zone)
- end
-
- it 'creates an adjustment' do
- Spree::TaxRate.adjust(@order, @order.line_items)
- expect(line_item.adjustments.charge.count).to eq(1)
- end
-
- it 'does not create a tax refund for each tax rate' do
- Spree::TaxRate.adjust(@order, @order.line_items)
- expect(line_item.adjustments.credit.count).to eq(0)
- end
- end
-
- context "when order's zone does not match default zone, is not included in the default zone, AND does not match the rate's zone" do
- before do
- @new_zone = create(:zone, name: 'New Zone', default_tax: false)
- @new_country = create(:country, name: 'New Country')
- @new_zone.zone_members.create(zoneable: @new_country)
- @order.ship_address = create(:address, country: @new_country)
- @order.save
- @order.reload
- end
-
- it 'does not create positive adjustments' do
- Spree::TaxRate.adjust(@order, @order.line_items)
- expect(line_item.adjustments.charge.count).to eq(0)
- end
-
- it 'does not create a tax refund for each tax rate' do
- Spree::TaxRate.adjust(@order, @order.line_items)
- expect(line_item.adjustments.credit.count).to eq(0)
- end
- end
-
- context 'when price does not include tax' do
- before do
- allow(@order).to receive_messages tax_zone: @zone
- [@rate1, @rate2].each do |rate|
- rate.included_in_price = false
- rate.zone = @zone
- rate.save
- end
- Spree::TaxRate.adjust(@order, @order.line_items)
- end
-
- it 'deletes adjustments for open order when taxrate is deleted' do
- @rate1.destroy!
- @rate2.destroy!
- expect(line_item.adjustments.count).to eq(0)
- end
-
- it 'does not delete adjustments for complete order when taxrate is deleted' do
- @order.update_column :completed_at, Time.current
- @rate1.destroy!
- @rate2.destroy!
- expect(line_item.adjustments.count).to eq(2)
- end
-
- it 'creates an adjustment' do
- expect(line_item.adjustments.count).to eq(2)
- end
-
- it 'does not create a tax refund' do
- expect(line_item.adjustments.credit.count).to eq(0)
- end
-
- describe 'tax adjustments' do
- before { Spree::TaxRate.adjust(@order, @order.line_items) }
-
- it 'applies adjustments when a tax zone is present' do
- expect(line_item.adjustments.count).to eq(2)
- line_item.adjustments.each do |adjustment|
- expect(adjustment.label).to eq("#{adjustment.source.name} #{(adjustment.source.amount * 100).to_i}%")
- end
- end
-
- describe 'when the tax zone is removed' do
- before { allow(@order).to receive_messages tax_zone: nil }
-
- it 'does not apply any adjustments' do
- Spree::TaxRate.adjust(@order, @order.line_items)
- expect(line_item.adjustments.count).to eq(0)
- end
- end
- end
- end
-
- context 'when two rates apply' do
- before do
- @price_before_taxes = line_item.price / (1 + @rate1.amount + @rate2.amount)
- # Use the same rounding method as in DefaultTax calculator
- @price_before_taxes = BigDecimal(@price_before_taxes).round(2, BigDecimal::ROUND_HALF_UP)
- line_item.update_column(:pre_tax_amount, @price_before_taxes)
- # Clear out any previously automatically-applied adjustments
- @order.all_adjustments.delete_all
- @rate1.adjust(@order, line_item)
- @rate2.adjust(@order, line_item)
- end
-
- it 'creates two price adjustments' do
- expect(@order.line_item_adjustments.count).to eq(2)
- end
-
- it 'price adjustments should be accurate' do
- included_tax = @order.line_item_adjustments.sum(:amount)
- expect(@price_before_taxes + included_tax).to eq(line_item.total)
- end
- end
- end
- end
- end
-
- describe '#label' do
+ describe '#adjustment_label' do
it 'returns the name and amount for the tax rate' do
tax_rate = Spree::TaxRate.new(name: 'Sales Tax', amount: 0.1)
- expect(tax_rate.send(:label)).to eq('Sales Tax 10%')
+ expect(tax_rate.adjustment_label).to eq('Sales Tax 10%')
end
end
diff --git a/spree/core/spec/models/spree/taxon_category_aliases_spec.rb b/spree/core/spec/models/spree/taxon_category_aliases_spec.rb
index af48dfea13..4d8128cd78 100644
--- a/spree/core/spec/models/spree/taxon_category_aliases_spec.rb
+++ b/spree/core/spec/models/spree/taxon_category_aliases_spec.rb
@@ -9,7 +9,7 @@ RSpec.describe 'Taxon -> Category deprecation aliases' do
expect(Spree::Taxon).to equal(Spree::Category)
expect(Spree::Classification).to equal(Spree::ProductCategory)
expect(Spree::PromotionRuleTaxon).to equal(Spree::PromotionRuleCategory)
- expect(Spree::Promotion::Rules::Taxon).to equal(Spree::Promotion::Rules::Category)
+ expect(Spree::PromotionRules::Taxon).to equal(Spree::PromotionRules::Category)
end
end
diff --git a/spree/core/spec/services/spree/carts/legacy_add_item_spec.rb b/spree/core/spec/services/spree/carts/legacy_add_item_spec.rb
index b9eecd9a89..2476481ff0 100644
--- a/spree/core/spec/services/spree/carts/legacy_add_item_spec.rb
+++ b/spree/core/spec/services/spree/carts/legacy_add_item_spec.rb
@@ -69,7 +69,7 @@ module Spree
let(:calculator) { Spree::Calculator::FlatRate.new(preferred_amount: 10) }
context 'one active order promotion' do
- let!(:action) { Spree::Promotion::Actions::CreateAdjustment.create(promotion: promotion, calculator: calculator) }
+ let!(:action) { Spree::PromotionActions::CreateAdjustment.create(promotion: promotion, calculator: calculator) }
before do
subject.call(order: order, variant: variant, quantity: 1)
@@ -78,13 +78,13 @@ module Spree
it 'creates valid discount on order' do
subject.call(order: order, variant: variant, quantity: 1)
- expect(order.adjustments.to_a.sum(&:amount)).not_to eq 0
+ expect(order.discounts.to_a.sum(&:amount)).not_to eq 0
expect(order.total).to eq 30
end
end
context 'one active line item promotion' do
- let!(:action) { Spree::Promotion::Actions::CreateItemAdjustments.create(promotion: promotion, calculator: calculator) }
+ let!(:action) { Spree::PromotionActions::CreateItemDiscounts.create(promotion: promotion, calculator: calculator) }
before do
subject.call(order: order, variant: variant, quantity: 1)
@@ -93,7 +93,7 @@ module Spree
it 'creates valid discount on order' do
subject.call(order: order, variant: variant, quantity: 1)
- expect(order.line_item_adjustments.to_a.sum(&:amount)).not_to eq 0
+ expect(order.line_item_discounts.to_a.sum(&:amount)).not_to eq 0
expect(order.total).to eq 30
end
end
@@ -105,14 +105,13 @@ module Spree
name: 'Tax Rate 1',
amount: 0.25,
included_in_price: true,
- calculator: Spree::Calculator::DefaultTax.create,
tax_category: category,
zone: create(:zone_with_country, default_tax: true)
)
end
let(:variant) { create(:variant, price: 1000) }
let(:calculator) { Spree::Calculator::PercentOnLineItem.new(preferred_percent: 50) }
- let!(:action) { Spree::Promotion::Actions::CreateItemAdjustments.create(promotion: promotion, calculator: calculator) }
+ let!(:action) { Spree::PromotionActions::CreateItemDiscounts.create(promotion: promotion, calculator: calculator) }
it 'updates included_tax_total' do
expect(order.included_tax_total.to_f).to eq(0.00)
diff --git a/spree/core/spec/services/spree/carts/legacy_empty_spec.rb b/spree/core/spec/services/spree/carts/legacy_empty_spec.rb
index de73ffbd97..cf1002a8d8 100644
--- a/spree/core/spec/services/spree/carts/legacy_empty_spec.rb
+++ b/spree/core/spec/services/spree/carts/legacy_empty_spec.rb
@@ -33,7 +33,7 @@ module Spree
it 'clears out line items, adjustments and update totals' do
expect(order.line_items.count).to be_zero
- expect(order.adjustments.count).to be_zero
+ expect(order.discounts.count).to be_zero
expect(order.shipments.count).to be_zero
expect(order.order_promotions.count).to be_zero
expect(order.promo_total).to be_zero
diff --git a/spree/core/spec/services/spree/orders/create_spec.rb b/spree/core/spec/services/spree/orders/create_spec.rb
index 8effb299cc..b87e145561 100644
--- a/spree/core/spec/services/spree/orders/create_spec.rb
+++ b/spree/core/spec/services/spree/orders/create_spec.rb
@@ -164,7 +164,7 @@ module Spree
# Promo created a -5 adjustment on the shipment
shipment = order.shipments.first
expect(shipment.adjustment_total).to eq(-5)
- expect(shipment.adjustments.promotion.size).to eq(1)
+ expect(shipment.discounts.promotion.size).to eq(1)
expect(order.shipping_discount).to eq(5)
# Promotion is associated with the order
diff --git a/spree/emails/app/views/spree/shared/_purchased_items_table.html.erb b/spree/emails/app/views/spree/shared/_purchased_items_table.html.erb
index 3cb47c75e1..3720dd7631 100644
--- a/spree/emails/app/views/spree/shared/_purchased_items_table.html.erb
+++ b/spree/emails/app/views/spree/shared/_purchased_items_table.html.erb
@@ -3,13 +3,11 @@
<% if local_assigns.fetch(:totals, true) %>
<table class="summary purchase_content" width="100%" cellpadding="0" cellspacing="0" role="presentation">
<%= render 'spree/shared/purchased_items_table/subtotal', order: order %>
- <% if order.line_item_adjustments.exists? %>
- <% order.all_adjustments.promotion.eligible.to_a.group_by(&:label).each do |label, adjustments| %>
- <%= render 'spree/shared/purchased_items_table/summary_row',
- label: Spree.t(:promotion),
- sub: label,
- value: Spree::Money.new(adjustments.sum(&:amount), currency: order.currency) %>
- <% end %>
+ <% order.discounts.promotion.to_a.group_by(&:label).each do |label, discounts| %>
+ <%= render 'spree/shared/purchased_items_table/summary_row',
+ label: Spree.t(:promotion),
+ sub: label,
+ value: Spree::Money.new(discounts.sum(&:amount), currency: order.currency) %>
<% end %>
<% order.shipments.group_by { |s| s.selected_shipping_rate&.name }.each do |name, shipments| %>
<%= render 'spree/shared/purchased_items_table/summary_row',
@@ -27,9 +25,16 @@
label: Spree.t(:gift_card),
value: safe_join(['-', order.display_gift_card_total.to_html]) %>
<% end %>
- <% order.adjustments.eligible.each do |adjustment| %>
- <% next if (adjustment.source_type == 'Spree::TaxRate') || (adjustment.amount == 0) %>
- <%= render 'spree/shared/purchased_items_table/adjustment', adjustment: adjustment, order: order %>
+ <% order.discounts.manual.to_a.group_by(&:label).each do |label, discounts| %>
+ <%= render 'spree/shared/purchased_items_table/summary_row',
+ label: label,
+ value: Spree::Money.new(discounts.sum(&:amount), currency: order.currency) %>
+ <% end %>
+ <% order.fees.each do |fee| %>
+ <% next if fee.amount == 0 %>
+ <%= render 'spree/shared/purchased_items_table/summary_row',
+ label: fee.label,
+ value: Spree::Money.new(fee.amount, currency: order.currency) %>
<% end %>
<%= render 'spree/shared/purchased_items_table/total', order: order %>
</table>
diff --git a/spree/emails/app/views/spree/shared/_purchased_items_table.text.erb b/spree/emails/app/views/spree/shared/_purchased_items_table.text.erb
index fe45501e99..e91793a598 100644
--- a/spree/emails/app/views/spree/shared/_purchased_items_table.text.erb
+++ b/spree/emails/app/views/spree/shared/_purchased_items_table.text.erb
@@ -3,12 +3,8 @@
<% end %>
============================================================
<%= Spree.t('order_mailer.subtotal') %> <%= order.display_item_total %>
-<% if order.line_item_adjustments.exists? %>
- <% if order.all_adjustments.promotion.eligible.exists? %>
- <% order.all_adjustments.promotion.eligible.group_by(&:label).each do |label, adjustments| %>
- <%= Spree.t(:promotion) %>: <%= label %> <%= Spree::Money.new(adjustments.sum(&:amount), currency: order.currency) %>
- <% end %>
- <% end %>
+<% order.discounts.promotion.to_a.group_by(&:label).each do |label, discounts| %>
+ <%= Spree.t(:promotion) %>: <%= label %> <%= Spree::Money.new(discounts.sum(&:amount), currency: order.currency) %>
<% end %>
<% order.shipments.group_by { |s| s.selected_shipping_rate.try(:name) }.each do |name, shipments| %>
@@ -23,7 +19,10 @@
<%= Spree.t(:gift_card) %>: -<%= order.display_gift_card_total.to_html %>
<% end %>
-<% order.adjustments.eligible.each do |adjustment| %>
- <% next if (adjustment.source_type == 'Spree::TaxRate') and (adjustment.amount == 0) %>
- <%= adjustment.label %> <%= adjustment.display_amount %>
+<% order.discounts.manual.to_a.group_by(&:label).each do |label, discounts| %>
+ <%= label %> <%= Spree::Money.new(discounts.sum(&:amount), currency: order.currency) %>
+<% end %>
+<% order.fees.each do |fee| %>
+ <% next if fee.amount == 0 %>
+ <%= fee.label %> <%= fee.display_amount %>
<% end %>
diff --git a/spree/emails/app/views/spree/shared/purchased_items_table/_adjustment.html.erb b/spree/emails/app/views/spree/shared/purchased_items_table/_adjustment.html.erb
deleted file mode 100644
index e61af50603..0000000000
--- a/spree/emails/app/views/spree/shared/purchased_items_table/_adjustment.html.erb
+++ /dev/null
@@ -1,3 +0,0 @@
-<%= render 'spree/shared/purchased_items_table/summary_row',
- label: adjustment.label,
- value: Spree::Money.new(adjustment.amount, currency: order.currency) %>
diff --git a/spree/emails/spec/mailers/spree/order_mailer_spec.rb b/spree/emails/spec/mailers/spree/order_mailer_spec.rb
index 5876fd6851..2805f834f1 100644
--- a/spree/emails/spec/mailers/spree/order_mailer_spec.rb
+++ b/spree/emails/spec/mailers/spree/order_mailer_spec.rb
@@ -123,21 +123,23 @@ describe Spree::OrderMailer, type: :mailer do
end
end
- context 'only shows eligible adjustments in emails' do
+ context 'shows manual discounts and fees in emails' do
before do
- create(:adjustment, order: order, eligible: true, label: 'Eligible Adjustment')
- create(:adjustment, order: order, eligible: false, label: 'Ineligible Adjustment')
+ line_item = order.line_items.first
+ order.discounts.create!(line_item: line_item, amount: -2, kind: 'manual', label: 'Loyal Customer Discount')
+ order.fees.create!(amount: 3, kind: 'handling', label: 'Handling Fee')
end
let!(:confirmation_email) { described_class.confirm_email(order) }
let!(:cancel_email) { described_class.cancel_email(order) }
specify do
- expect(confirmation_email.body).not_to include('Ineligible Adjustment')
+ expect(confirmation_email).to have_body_text('Loyal Customer Discount')
+ expect(confirmation_email).to have_body_text('Handling Fee')
end
specify do
- expect(cancel_email.body).not_to include('Ineligible Adjustment')
+ expect(cancel_email).to have_body_text('Loyal Customer Discount')
end
end