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.

Retire commission rules instead of deleting them

Damian Legawiec74c56bc2fc17
diff --git a/docs/plans/6.0-multi-vendor-marketplace.md b/docs/plans/6.0-multi-vendor-marketplace.md
index ed394140db..c08b73cc49 100644
--- a/docs/plans/6.0-multi-vendor-marketplace.md
+++ b/docs/plans/6.0-multi-vendor-marketplace.md
@@ -706,6 +706,7 @@ Even before this lands, work touching adjacent areas should:
- **Basic Stripe Connect execution → OSS (boundary amendment)** (RESOLVED 2026-07-15). Express onboarding + on-fulfillment transfers ship in the monorepo alongside the pulled-in Stripe gateway, for demo/adoption parity with the surveyed competitor — "money moves automatically" is the demo that sells, and transfers are inseparable from basic onboarding (a `Stripe::Transfer` needs a connected account). Enterprise repositions on money **operations**: automatic refund clawbacks (prorated transfer reversals + negative-balance netting), KYC/account-health workflows, ledger⇄Stripe reconciliation, payout reports incl. DAC7, facilitator taxes. Ledger reversal rows stay OSS in every mode — only the pullback execution is paid. Supersedes #13323's "execution stays Enterprise" framing (amendment by the issue author; update the issue). See `decisions.md` 2026-07-15.
- **`Spree::Vendor` name ownership → marketplace seller; inventory-operations' procurement model renamed `Spree::Supplier`** (RESOLVED 2026-07-14). See the Key Decisions entry and `decisions.md` 2026-07-14.
- **Commission is not a `Spree::Fee`** (RESOLVED 2026-07-14). `Fee` is buyer-facing and rolls into order totals; `CommissionLine` is an off-order platform↔vendor ledger. See Decision 2.
+- **Retiring a rate retires its rules, and keeps them readable** (RESOLVED 2026-08-17, shipped). `CommissionRule` and `CommissionRuleProduct` are `acts_as_paranoid`, so a soft-deleted rate's conditions are retired with it rather than deleted — and an edit that replaces a rule keeps the one it superseded. There is no restore UI for a rate any more than for a price list; soft delete exists to keep the historical picture, and a commission line is explained by the rule that matched it, so "why was this charged" has to stay answerable after the rule stops applying. This is a deliberate departure — no other rule model in core is paranoid — justified by commission lines being settlement records rather than configuration. Two consequences to keep: both uniqueness indexes constrain **live rows only** (partial on PostgreSQL/SQLite, a stored generated column on MySQL/MariaDB, verified against both), and `CommissionRate#rules=` identifies an incoming row against the rule of that kind the rate already carries, since clients send the whole set without ids and a blind build would collide with the live rule it was meant to replace.
- **Commission rules → typed classes, not a polymorphic subject** (RESOLVED 2026-08-17, shipped; supersedes the original shape). A rule was `(subject_type, subject_id)`, which could only ever name a record: a price band, a channel, a promotional window were each a migration plus an edit to the matcher, and a third party could add nothing. It is now STI over `Spree.commission_rules`, matching `Spree::PriceRule` and `Spree::DeliveryMethodRule` — a rule carries its own configuration, declares it through `preference_schema`, and a new kind is a subclass and a registration. Matching semantics are unchanged: every rule must hold, and a rule naming several records means any of them, so the OR moved inside a rule and there is still no `match_policy`. Reference lists follow the house cardinality rule — vendors and categories as `normalize_id_preference` arrays, products in a join table — which also deleted the hand-rolled store check in the controller, since the preference writer scope-checks as it writes. The admin surface follows the delivery-method rules editor: `GET /commission_rates/rule_types` for discovery, one row per condition, a picker where the kind names records and its preference schema otherwise.
- **Commission rule matching → every rule must hold (AND), a rule naming several records means any of them (OR)** (RESOLVED 2026-07-14, restated 2026-08-17 for the typed shape). Expresses plain lists and the vendor × category pairings today's Enterprise sells, with no `match_policy` knob; same semantics as the leading surveyed OSS engine, but precedence stays the operator's own ordering rather than implicit specificity. See Decision 4.
- **Commission on delivery revenue → `include_shipping` on the rate** (RESOLVED 2026-07-14). Per-rate flag, default off (legacy was items-only); a fulfillment-scoped `CommissionLine` (nullable `fulfillment_id`, exactly-one-of with `line_item_id`). Matches the surveyed OSS competitor (global-only there) and Amazon referral-fee behavior. See Decision 4.
diff --git a/spree/core/app/models/spree/commission_rate.rb b/spree/core/app/models/spree/commission_rate.rb
index 9a3aa731d6..ed7eb0b2cf 100644
--- a/spree/core/app/models/spree/commission_rate.rb
+++ b/spree/core/app/models/spree/commission_rate.rb
@@ -43,16 +43,11 @@ module Spree
# Associations
#
belongs_to :store, class_name: 'Spree::Store'
- # No `dependent:`. A rate is paranoid, so `destroy` is a soft delete — and
- # paranoia fires destroy callbacks on it, which would take rules that are
- # not paranoid and so cannot come back with a restore. A rate restored
- # without its rules matches every sale, and sitting at the top of the list
- # would shadow every rate beneath it.
- #
- # Replacing a rate's rules still deletes the ones it dropped: that path is
- # Spree::TypedAssociations, which destroys them explicitly rather than
- # relying on the association.
- has_many :commission_rules, class_name: 'Spree::CommissionRule', inverse_of: :commission_rate
+ # Retired with the rate, not deleted: rules are paranoid too, so a soft
+ # delete cascades to a soft delete and the rate's conditions stay readable
+ # beside the commission lines they explain.
+ has_many :commission_rules, class_name: 'Spree::CommissionRule',
+ dependent: :destroy, inverse_of: :commission_rate
# Never cascaded: a commission line is a settlement record, and "which rate
# charged this" has to stay answerable after the rate is retired. The rate
# itself is still readable through `with_deleted`, which is the point of
@@ -169,16 +164,36 @@ module Spree
# @param rows [Array<Hash>, nil]
# @return [void]
def rules=(rows)
- # Clearing is destroyed explicitly rather than assigned away: without
- # `dependent: :destroy` on the association — see above for why it cannot
- # have one — an empty assignment would try to null a non-null column.
+ # Destroyed rather than assigned away, so clearing retires the rules
+ # instead of trying to null a non-null column.
return commission_rules.destroy_all if persisted? && Array(rows).empty?
- assign_typed_association(:commission_rules, rows)
+ assign_typed_association(:commission_rules, identify_existing_rules(rows))
end
private
+ # Points each incoming row at the rule of its kind the rate already has.
+ #
+ # There is one rule per kind, so a payload naming a kind means "this is
+ # what that condition should now say" — but a row without an `id` builds a
+ # new rule, which then collides with the live one it was meant to replace.
+ # Clients send the whole set without ids (the dashboard rebuilds it from
+ # form state), so identifying by kind is what makes an edit an edit.
+ def identify_existing_rules(rows)
+ return rows unless persisted?
+
+ existing = commission_rules.index_by { |rule| rule.class.api_type }
+
+ Array(rows).map do |row|
+ attributes = row.respond_to?(:to_h) ? row.to_h.with_indifferent_access : row
+ next row if attributes[:id].present?
+
+ match = existing[attributes[:type].to_s]
+ match ? attributes.merge(id: match.id) : row
+ end
+ end
+
# A new rate has no id for its rules to hang off until it is saved.
def apply_pending_rules
flush_pending_typed_association(:commission_rules)
diff --git a/spree/core/app/models/spree/commission_rule.rb b/spree/core/app/models/spree/commission_rule.rb
index 5834a0c7c8..150c487165 100644
--- a/spree/core/app/models/spree/commission_rule.rb
+++ b/spree/core/app/models/spree/commission_rule.rb
@@ -18,6 +18,12 @@ module Spree
has_prefix_id :crule
+ # Retired rather than deleted, with its rate or on its own as an operator
+ # edits a rate's conditions. A commission line is a settlement record, and
+ # "why was this charged" is answered by the rule that matched — which has
+ # to still be readable once the rule no longer applies to anything.
+ acts_as_paranoid
+
belongs_to :commission_rate, class_name: 'Spree::CommissionRate',
inverse_of: :commission_rules, touch: true
@@ -29,7 +35,14 @@ module Spree
# One of each kind per rate: a second rule of the same kind would either
# repeat the first or contradict it, and under AND semantics contradiction
# means the rate silently never applies.
- validates :type, uniqueness: { scope: [:commission_rate_id, *spree_base_uniqueness_scope] }
+ #
+ # Among live rules only, matching the partial index. Retired rules are
+ # history, and a replacement is saved before the rule it supersedes is
+ # retired — counting those would refuse every edit.
+ validates :type, uniqueness: {
+ scope: [:commission_rate_id, *spree_base_uniqueness_scope],
+ conditions: -> { where(deleted_at: nil) }
+ }
validate :type_must_be_registered
registers_subclasses_via { Spree.commission_rules }
diff --git a/spree/core/app/models/spree/commission_rule_product.rb b/spree/core/app/models/spree/commission_rule_product.rb
index fbcae66e13..8c9712a6fe 100644
--- a/spree/core/app/models/spree/commission_rule_product.rb
+++ b/spree/core/app/models/spree/commission_rule_product.rb
@@ -7,6 +7,10 @@ module Spree
class CommissionRuleProduct < Spree.base_class
# No inverse_of: the association lives on the ProductRule subclass, not on
# the base class this points at.
+ # Retired with its rule, so a retired product rule still says which
+ # products it named.
+ acts_as_paranoid
+
belongs_to :commission_rule, class_name: 'Spree::CommissionRule'
belongs_to :product, class_name: 'Spree::Product'
diff --git a/spree/core/app/models/spree/commission_rules/product_rule.rb b/spree/core/app/models/spree/commission_rules/product_rule.rb
index b6a0eaf6a8..c9c0583986 100644
--- a/spree/core/app/models/spree/commission_rules/product_rule.rb
+++ b/spree/core/app/models/spree/commission_rules/product_rule.rb
@@ -9,7 +9,7 @@ module Spree
# thousand ids in a JSON column.
class ProductRule < Spree::CommissionRule
has_many :commission_rule_products, class_name: 'Spree::CommissionRuleProduct',
- foreign_key: :commission_rule_id, dependent: :delete_all
+ foreign_key: :commission_rule_id, dependent: :destroy
has_many :products, class_name: 'Spree::Product', through: :commission_rule_products
def self.additional_permitted_attributes
diff --git a/spree/core/db/migrate/20260816210001_create_spree_commission_rates.rb b/spree/core/db/migrate/20260816210001_create_spree_commission_rates.rb
index d94986c290..9f699fb79f 100644
--- a/spree/core/db/migrate/20260816210001_create_spree_commission_rates.rb
+++ b/spree/core/db/migrate/20260816210001_create_spree_commission_rates.rb
@@ -1,5 +1,7 @@
class CreateSpreeCommissionRates < ActiveRecord::Migration[8.1]
INDEX_NAME = 'index_spree_commission_rates_on_store_id_and_code'.freeze
+ RULE_INDEX_NAME = 'index_commission_rules_on_rate_and_type'.freeze
+ RULE_PRODUCT_INDEX_NAME = 'index_commission_rule_products_on_rule_and_product'.freeze
def change
create_table :spree_commission_rates do |t|
@@ -60,14 +62,19 @@ class CreateSpreeCommissionRates < ActiveRecord::Migration[8.1]
end
t.timestamps
+ # Rules are retired with their rate, and separately as an operator edits
+ # a rate's conditions. Kept rather than deleted so a commission line
+ # stays explainable: "why was this charged" is answered by the rule that
+ # matched, which must still be readable afterwards.
+ t.datetime :deleted_at
end
+ add_index :spree_commission_rules, :deleted_at
# One rule of each kind per rate: a second would repeat the first or
# contradict it, and under AND semantics contradiction means the rate
- # silently never applies.
- add_index :spree_commission_rules, [:commission_rate_id, :type],
- unique: true,
- name: 'index_commission_rules_on_rate_and_type'
+ # silently never applies. Live rows only, or replacing a rule would
+ # collide with the retired one it supersedes.
+ add_rule_uniqueness_index
# Catalog-scale references get a table of their own — a marketplace naming
# a thousand products should not put a thousand ids in a JSON column.
@@ -76,11 +83,14 @@ class CreateSpreeCommissionRates < ActiveRecord::Migration[8.1]
t.references :product, null: false
t.timestamps
+ t.datetime :deleted_at
end
- add_index :spree_commission_rule_products, [:commission_rule_id, :product_id],
- unique: true,
- name: 'index_commission_rule_products_on_rule_and_product'
+ add_index :spree_commission_rule_products, :deleted_at
+ # Unique among live rows only: a rule that named a product, dropped it and
+ # named it again keeps the retired row beside the live one, but must never
+ # hold the same product twice at once.
+ add_rule_product_uniqueness_index
end
private
@@ -99,6 +109,56 @@ class CreateSpreeCommissionRates < ActiveRecord::Migration[8.1]
# deleted_at, CAST(...))`) is MySQL-only, `UNIX_TIMESTAMP` is MariaDB-only,
# and a functional index on COALESCE — the older precedent in this tree — is
# MySQL-only too. This expression is the one both accept.
+ def add_rule_product_uniqueness_index
+ if mysql?
+ reversible do |dir|
+ dir.up do
+ execute <<~SQL.squish
+ ALTER TABLE spree_commission_rule_products
+ ADD COLUMN product_key BIGINT
+ AS (IF(deleted_at IS NULL, product_id, NULL)) STORED
+ SQL
+ add_index :spree_commission_rule_products, [:commission_rule_id, :product_key],
+ unique: true, name: RULE_PRODUCT_INDEX_NAME
+ end
+
+ dir.down do
+ remove_index :spree_commission_rule_products, name: RULE_PRODUCT_INDEX_NAME
+ remove_column :spree_commission_rule_products, :product_key
+ end
+ end
+ else
+ add_index :spree_commission_rule_products, [:commission_rule_id, :product_id],
+ unique: true, where: 'deleted_at IS NULL', name: RULE_PRODUCT_INDEX_NAME
+ end
+ end
+
+ # Same per-adapter split as the rate's code index below, and for the same
+ # reason: only PostgreSQL and SQLite have partial indexes.
+ def add_rule_uniqueness_index
+ if mysql?
+ reversible do |dir|
+ dir.up do
+ execute <<~SQL.squish
+ ALTER TABLE spree_commission_rules
+ ADD COLUMN type_key VARCHAR(255)
+ AS (IF(deleted_at IS NULL, type, NULL)) STORED
+ SQL
+ add_index :spree_commission_rules, [:commission_rate_id, :type_key],
+ unique: true, name: RULE_INDEX_NAME
+ end
+
+ dir.down do
+ remove_index :spree_commission_rules, name: RULE_INDEX_NAME
+ remove_column :spree_commission_rules, :type_key
+ end
+ end
+ else
+ add_index :spree_commission_rules, [:commission_rate_id, :type],
+ unique: true, where: 'deleted_at IS NULL', name: RULE_INDEX_NAME
+ end
+ end
+
def add_code_uniqueness_index
if mysql?
reversible do |dir|
diff --git a/spree/core/spec/models/spree/commission_rate_spec.rb b/spree/core/spec/models/spree/commission_rate_spec.rb
index f3123f1598..3b0d518902 100644
--- a/spree/core/spec/models/spree/commission_rate_spec.rb
+++ b/spree/core/spec/models/spree/commission_rate_spec.rb
@@ -202,6 +202,21 @@ RSpec.describe Spree::CommissionRate, type: :model do
expect(rate.commission_rules.first.preferred_category_ids.map(&:to_s)).to eq([category.id.to_s])
end
+ # One rule per kind, so naming a kind means "this condition should now say
+ # that" — the edit lands on the rule already there rather than building a
+ # second one beside it.
+ it 'edits the rule of a kind the rate already carries' do
+ rate = create(:commission_rate, store: store)
+ first_vendor = create(:vendor, store: store)
+ second_vendor = create(:vendor, store: store)
+ rate.update!(rules: [{ type: 'vendor_rule', preferences: { vendor_ids: [first_vendor.id] } }])
+
+ rate.update!(rules: [{ type: 'vendor_rule', preferences: { vendor_ids: [second_vendor.id] } }])
+
+ expect(rate.reload.commission_rules.count).to eq(1)
+ expect(rate.commission_rules.first.preferred_vendor_ids.map(&:to_s)).to eq([second_vendor.id.to_s])
+ end
+
it 'clears the targeting when given nothing' do
rate = create(:commission_rate, store: store)
create(:commission_vendor_rule, commission_rate: rate, vendors: [vendor])
@@ -276,15 +291,18 @@ RSpec.describe Spree::CommissionRate, type: :model do
describe 'retiring a rate' do
let(:vendor) { create(:vendor, store: store) }
- it 'keeps its rules, so restoring it does not make it charge everything' do
+ # Retired, not deleted: a commission line is explained by the rule that
+ # matched it, so the conditions have to stay readable after the rate stops
+ # applying to anything.
+ it 'retires its rules with it rather than deleting them' do
rate = create(:commission_rate, store: store)
create(:commission_vendor_rule, commission_rate: rate, vendors: [vendor])
rate.destroy
- rate.restore
- expect(rate.reload.commission_rules.count).to eq(1)
- expect(rate).not_to be_global
+ expect(Spree::CommissionRule.where(commission_rate_id: rate.id)).to be_empty
+ retired = Spree::CommissionRule.with_deleted.find_by(commission_rate_id: rate.id)
+ expect(retired.preferred_vendor_ids.map(&:to_s)).to eq([vendor.id.to_s])
end
# "Which rate charged this" has to stay answerable after the rate is