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.

Added `Spree::TypedAssociations`

Damian Legawiec4b6b71fad3ae
diff --git a/spree/core/app/models/concerns/spree/typed_associations.rb b/spree/core/app/models/concerns/spree/typed_associations.rb
new file mode 100644
index 0000000000..c3ca155aa5
--- /dev/null
+++ b/spree/core/app/models/concerns/spree/typed_associations.rb
@@ -0,0 +1,116 @@
+module Spree
+ # Shared flat-payload writer for `has_many` associations whose rows
+ # are STI-typed and carry preferences/calculator metadata. Used by
+ # {Spree::Promotion} (rules, actions) and {Spree::PriceList} (rules).
+ #
+ # The wire shape is `[{ type:, id?, preferences: {...}, calculator?: {...}, *_ids?: [...] }]`
+ # and the reconciliation is: existing rows update by `id`, new rows
+ # build via `find_by_api_type`, missing rows destroy. Falls through
+ # to AR's standard writer when assigned model instances (Rails
+ # internals do this on association swap).
+ #
+ # New-record parents defer the work into an `@pending_<assoc>` ivar
+ # so child rows can FK to a persisted parent — the consumer model
+ # is responsible for flushing those in an `after_save`.
+ module TypedAssociations
+ extend ActiveSupport::Concern
+
+ private
+
+ # Routes a flat-payload assignment to either the deferred buffer
+ # (new record) or {#reconcile_typed_association}.
+ #
+ # @param association [Symbol] e.g. `:promotion_rules`, `:price_rules`
+ # @param rows [Array<Hash>, Array<Spree::Base>, nil]
+ # @return [void]
+ def assign_typed_association(association, rows)
+ first = Array(rows).first
+ return public_send(:"#{association}=", rows) if first.nil? || first.is_a?(Spree.base_class)
+
+ pending = Array(rows).map { |entry| entry.respond_to?(:to_h) ? entry.to_h.with_indifferent_access : entry.with_indifferent_access }
+
+ if new_record?
+ instance_variable_set(:"@pending_#{association}", pending)
+ return
+ end
+
+ reconcile_typed_association(association, pending)
+ end
+
+ # Flushes a pending payload from `@pending_<assoc>` (typically from
+ # an `after_save` hook) and clears the ivar.
+ #
+ # @param association [Symbol]
+ # @return [void]
+ def flush_pending_typed_association(association)
+ ivar = :"@pending_#{association}"
+ pending = instance_variable_get(ivar)
+ return unless pending
+
+ instance_variable_set(ivar, nil)
+ reconcile_typed_association(association, pending)
+ end
+
+ def reconcile_typed_association(association, rows)
+ collection = public_send(association)
+ kept_ids = rows.filter_map { |row| save_typed_association_row(collection, row) }
+ collection.where.not(id: kept_ids).destroy_all if kept_ids.any? || rows.empty?
+ end
+
+ def save_typed_association_row(collection, row)
+ record = find_or_build_typed_association_row(collection, row)
+ return nil unless record
+
+ preferences = row[:preferences]
+ calculator = row[:calculator]
+ attrs = row.except(:id, :type, :preferences, :calculator)
+
+ # `*_ids` mass-assignment on a new record builds join rows with a
+ # nil parent FK and fails `presence: true` on autosave. Defer
+ # those until after the row itself is persisted.
+ deferred_ids, scalar_attrs = attrs.partition { |k, _| record.new_record? && k.to_s.end_with?('_ids') }
+ record.assign_attributes(scalar_attrs.to_h) if scalar_attrs.any?
+
+ preferences&.each do |key, value|
+ next unless record.has_preference?(key.to_sym)
+
+ record.set_preference(key.to_sym, decode_preference_value(key, value))
+ end
+ record.assign_calculator_attributes(calculator) if calculator.present? && record.respond_to?(:assign_calculator_attributes)
+
+ # Always save — `record.changed?` doesn't reflect preferences
+ # (serialized hash) or calculator association changes.
+ record.save!
+
+ deferred_ids.each { |key, value| record.public_send("#{key}=", value) }
+ record.save! if record.changed?
+
+ record.id
+ end
+
+ # Decode `*_ids` array preferences (`customer_group_ids`, `user_ids`,
+ # …) from prefixed strings to raw PKs. Plain-scalar / non-id
+ # preferences pass through unchanged.
+ def decode_preference_value(key, value)
+ return value unless key.to_s.end_with?('_ids') && value.is_a?(Array)
+
+ value.map do |v|
+ Spree::PrefixedId.prefixed_id?(v) ? Spree::PrefixedId.decode_prefixed_id(v) : v
+ end
+ end
+
+ def find_or_build_typed_association_row(collection, row)
+ if row[:id].present?
+ id = Spree::PrefixedId.prefixed_id?(row[:id]) ? Spree::PrefixedId.decode_prefixed_id(row[:id]) : row[:id]
+ existing = collection.find { |r| r.id == id } || collection.find_by(id: id)
+ return existing if existing
+ end
+
+ klass = collection.proxy_association.klass.find_by_api_type(row[:type])
+ return nil unless klass
+
+ record = collection.build(type: klass.to_s)
+ record.class == klass ? record : record.becomes(klass)
+ end
+ end
+end
diff --git a/spree/core/app/models/spree/base.rb b/spree/core/app/models/spree/base.rb
index a85dfa5b59..d11d8d655f 100644
--- a/spree/core/app/models/spree/base.rb
+++ b/spree/core/app/models/spree/base.rb
@@ -1,10 +1,12 @@
class Spree::Base < ApplicationRecord
include Spree::Preferences::Preferable
+ include Spree::PreferenceSchema
include Spree::RansackableAttributes
include Spree::TranslatableResourceScopes
include Spree::IntegrationsConcern
include Spree::Publishable
include Spree::PrefixedId
+ include Spree::TypedAssociations
after_initialize do
if has_attribute?(:preferences) && !preferences.nil?
diff --git a/spree/core/app/models/spree/calculator.rb b/spree/core/app/models/spree/calculator.rb
index 91a8b769e3..e7144602fe 100644
--- a/spree/core/app/models/spree/calculator.rb
+++ b/spree/core/app/models/spree/calculator.rb
@@ -1,7 +1,5 @@
module Spree
class Calculator < Spree.base_class
- include Spree::PreferenceSchema
-
has_prefix_id :calc
acts_as_paranoid
diff --git a/spree/core/app/models/spree/payment_method.rb b/spree/core/app/models/spree/payment_method.rb
index 2e7bf95fd1..0dcdbe1f00 100644
--- a/spree/core/app/models/spree/payment_method.rb
+++ b/spree/core/app/models/spree/payment_method.rb
@@ -9,7 +9,6 @@ module Spree
include Spree::Metafields
include Spree::Metadata
include Spree::DisplayOn
- include Spree::PreferenceSchema
if defined?(Spree::Security::PaymentMethods)
include Spree::Security::PaymentMethods
end
diff --git a/spree/core/app/models/spree/promotion.rb b/spree/core/app/models/spree/promotion.rb
index 5cbde115a1..e0dc062568 100644
--- a/spree/core/app/models/spree/promotion.rb
+++ b/spree/core/app/models/spree/promotion.rb
@@ -116,19 +116,15 @@ module Spree
end
end
- # Flat-payload writer for `rules`. Accepts an array of hashes like
- # `[{ type:, preferences:, product_ids:, ... }]` and reconciles to
- # the desired set: existing rows update by `id`, new rows build,
- # missing rows destroy. Falls through to AR's standard writer
- # when assigned `Spree::PromotionRule` instances (Rails internals
- # do this on association swap).
+ # Flat-payload writer for `rules`. See
+ # {Spree::TypedAssociations#assign_typed_association}.
def rules=(rows)
- assign_subclassed(:promotion_rules, rows)
+ assign_typed_association(:promotion_rules, rows)
end
# Mirrors `rules=` for promotion actions.
def actions=(rows)
- assign_subclassed(:promotion_actions, rows)
+ assign_typed_association(:promotion_actions, rows)
end
def pending_rules_or_actions?
@@ -303,93 +299,9 @@ module Spree
private
- # Reconciles `association` (`:promotion_rules` or `:promotion_actions`)
- # to the desired set of `rows`. Each row is a `{type, id, preferences,
- # calculator, <assoc>_ids}` hash. New rows are built, existing rows
- # (matched by `id`) updated, anything missing destroyed.
- #
- # When the promotion is a new record the work is deferred until
- # `after_save` so child rows can FK to a persisted parent.
- def assign_subclassed(association, rows)
- first = Array(rows).first
- return public_send(:"#{association}=", rows) if first.nil? || first.is_a?(Spree.base_class)
-
- pending = Array(rows).map { |entry| entry.respond_to?(:to_h) ? entry.to_h.with_indifferent_access : entry.with_indifferent_access }
-
- if new_record?
- instance_variable_set(:"@pending_#{association}", pending)
- return
- end
-
- reconcile_subclassed(association, pending)
- end
-
def apply_pending_rules_and_actions
- if (pending = @pending_promotion_rules)
- reconcile_subclassed(:promotion_rules, pending)
- @pending_promotion_rules = nil
- end
- if (pending = @pending_promotion_actions)
- reconcile_subclassed(:promotion_actions, pending)
- @pending_promotion_actions = nil
- end
- end
-
- def reconcile_subclassed(association, rows)
- collection = public_send(association)
- kept_ids = rows.filter_map { |row| save_subclassed_row(collection, row) }
- collection.where.not(id: kept_ids).destroy_all if kept_ids.any? || rows.empty?
- end
-
- def save_subclassed_row(collection, row)
- record = find_or_build_subclassed(collection, row)
- return nil unless record
-
- preferences = row[:preferences]
- calculator = row[:calculator]
- attrs = row.except(:id, :type, :preferences, :calculator)
-
- # Any `*_ids` mass-assignment on a new record builds join rows with
- # a nil FK to the parent — they fail `presence: true` on autosave.
- # Defer those assignments until after the rule itself is persisted.
- deferred_ids, scalar_attrs = attrs.partition { |k, _| record.new_record? && k.to_s.end_with?('_ids') }
- record.assign_attributes(scalar_attrs.to_h) if scalar_attrs.any?
-
- preferences&.each do |key, value|
- record.set_preference(key.to_sym, value) if record.has_preference?(key.to_sym)
- end
- record.assign_calculator_attributes(calculator) if calculator.present? && record.respond_to?(:assign_calculator_attributes)
-
- # Always save — `record.changed?` doesn't reflect changes to
- # preferences (stored in a serialized hash) or to the calculator
- # association, and we may have built a new record above.
- record.save!
-
- deferred_ids.each { |key, value| record.public_send("#{key}=", value) }
- record.save! if record.changed?
-
- record.id
- end
-
- def find_or_build_subclassed(collection, row)
- if row[:id].present?
- id = decode_id(row[:id])
- existing = collection.find { |r| r.id == id } || collection.find_by(id: id)
- return existing if existing
- end
-
- klass = collection.proxy_association.klass.find_by_api_type(row[:type])
- return nil unless klass
-
- record = collection.build(type: klass.to_s)
- record.class == klass ? record : record.becomes(klass)
- end
-
- def decode_id(value)
- return nil if value.blank?
- return value.to_i if value.is_a?(Integer) || value.to_s.match?(/\A\d+\z/)
-
- Spree::PrefixedId.decode_prefixed_id(value)
+ flush_pending_typed_association(:promotion_rules)
+ flush_pending_typed_association(:promotion_actions)
end
def not_used?
diff --git a/spree/core/app/models/spree/promotion_action.rb b/spree/core/app/models/spree/promotion_action.rb
index 5b7a05461e..e00fe9bd68 100644
--- a/spree/core/app/models/spree/promotion_action.rb
+++ b/spree/core/app/models/spree/promotion_action.rb
@@ -2,8 +2,6 @@
# PromotionActions perform the necessary tasks when a promotion is activated by an event and determined to be eligible.
module Spree
class PromotionAction < Spree.base_class
- include Spree::PreferenceSchema
-
has_prefix_id :pact
acts_as_paranoid
diff --git a/spree/core/app/models/spree/promotion_rule.rb b/spree/core/app/models/spree/promotion_rule.rb
index af7e50aa65..bcef04278b 100644
--- a/spree/core/app/models/spree/promotion_rule.rb
+++ b/spree/core/app/models/spree/promotion_rule.rb
@@ -1,8 +1,6 @@
# Base class for all promotion rules
module Spree
class PromotionRule < Spree.base_class
- include Spree::PreferenceSchema
-
has_prefix_id :prorule
belongs_to :promotion, class_name: 'Spree::Promotion', inverse_of: :promotion_rules, touch: true