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.

Introduce `BaseAnalyticsEventHandler` and new client-side tracking in… (#12417)

Damian Legawiec70e9a2c7eb5d
diff --git a/core/app/models/spree/base_analytics_event_handler.rb b/core/app/models/spree/base_analytics_event_handler.rb
new file mode 100644
index 0000000000..d1d0b26135
--- /dev/null
+++ b/core/app/models/spree/base_analytics_event_handler.rb
@@ -0,0 +1,76 @@
+module Spree
+ class BaseAnalyticsEventHandler
+ SUPPORTED_EVENTS = {
+ product_viewed: 'Product Viewed',
+ product_list_viewed: 'Product List Viewed',
+ product_searched: 'Product Searched',
+ product_added: 'Product Added',
+ product_removed: 'Product Removed',
+
+ payment_info_entered: 'Payment Info Entered',
+ coupon_entered: 'Coupon Entered',
+ coupon_removed: 'Coupon Removed',
+ coupon_applied: 'Coupon Applied',
+ coupon_denied: 'Coupon Denied',
+
+ checkout_started: 'Checkout Started',
+ checkout_email_entered: 'Checkout Email Entered',
+ checkout_step_viewed: 'Checkout Step Viewed',
+ checkout_step_completed: 'Checkout Step Completed',
+
+ order_completed: 'Order Completed',
+ order_cancelled: 'Order Cancelled',
+ order_refunded: 'Order Refunded',
+ package_shipped: 'Package Shipped',
+ order_fulfilled: 'Order Fulfilled',
+
+ gift_card_issued: 'Gift Card Issued'
+ }.freeze
+
+ # Returns the client method
+ # @return [Symbol] eg. :ahoy
+ def self.client_method
+ raise NotImplementedError, 'Subclasses must implement the client_method method'
+ end
+
+ # Initializes the event handler
+ # @param client [Object] The client object
+ # @param opts [Hash] The options
+ # @option opts [User] :user
+ # @option opts [String] :session_id
+ def initialize(client, opts = {})
+ @client = client
+ @user = opts[:user]
+ @session_id = opts[:session_id]
+ end
+
+ attr_reader :client, :user, :session_id
+
+ # Handles the event
+ # @param event_name [String] eg. 'order_completed'
+ # @param properties [Hash] eg. { product: Spree::Product, taxon: Spree::Taxon, query: String }
+ # rubocop:disable Lint/UnusedMethodArgument
+ def handle_event(event_name, properties = {})
+ raise NotImplementedError, 'Subclasses must implement the handle method'
+ end
+ # rubocop:enable Lint/UnusedMethodArgument
+
+ # Returns the label for the event
+ # @param event_name [String] eg. 'order_completed'
+ # @return [String] eg. 'Order Completed'
+ def event_label(event_name)
+ SUPPORTED_EVENTS[event_name.to_sym]
+ end
+
+ protected
+
+ # Returns the identity hash for the event
+ # @return [Hash] eg. { user_id: 1, session_id: '123' }
+ def identity_hash
+ {
+ user_id: user&.id,
+ session_id: session_id
+ }
+ end
+ end
+end
diff --git a/core/app/models/spree/promotion_action.rb b/core/app/models/spree/promotion_action.rb
index 3e141a3ff1..2dec273490 100644
--- a/core/app/models/spree/promotion_action.rb
+++ b/core/app/models/spree/promotion_action.rb
@@ -18,6 +18,13 @@ module Spree
raise 'perform should be implemented in a sub-class of PromotionAction'
end
+ # Returns true if the promotion action is a free shipping action
+ #
+ # @return [Boolean]
+ def free_shipping?
+ type == 'Spree::Promotion::Actions::FreeShipping'
+ end
+
protected
def label
diff --git a/core/app/models/spree/promotion_handler/coupon.rb b/core/app/models/spree/promotion_handler/coupon.rb
index c5ae20428a..ae26427f56 100644
--- a/core/app/models/spree/promotion_handler/coupon.rb
+++ b/core/app/models/spree/promotion_handler/coupon.rb
@@ -59,12 +59,28 @@ module Spree
@error = Spree.t(code, locale_options)
end
+ # Returns the promotion for the order
+ #
+ # @return [Spree::Promotion]
def promotion
@promotion ||= store.promotions.active.includes(
:promotion_rules, :promotion_actions
).with_coupon_code(order.coupon_code)
end
+ # Returns the amount of adjustments for the promotion
+ #
+ # @return [Numeric]
+ def adjustments_amount
+ @adjustments_amount ||=
+ @order.all_adjustments.promotion.eligible.
+ where(source: promotion&.actions).
+ sum(:amount)
+ end
+
+ # Returns true if the code was applied successfully
+ #
+ # @return [Boolean]
def successful?
success.present? && error.blank?
end
diff --git a/core/app/services/spree/error_handler.rb b/core/app/services/spree/error_handler.rb
index 68d2859a56..b20010d691 100644
--- a/core/app/services/spree/error_handler.rb
+++ b/core/app/services/spree/error_handler.rb
@@ -2,6 +2,12 @@ module Spree
class ErrorHandler
prepend ::Spree::ServiceModule::Base
+ # Handles errors and logs them to the console.
+ #
+ # @param exception [Exception]
+ # @param opts [Hash]
+ # @option opts [Hash] :report_context
+ # @option opts [User] :user
def call(exception:, opts: {})
run :format_message
run :log_error
@@ -32,7 +38,7 @@ module Spree
# overwrite this method in your application to support different error handlers
# eg. Sentry, Rollbar, etc
if defined?(Sentry)
- if opts[:sentry_context].present?
+ if opts[:report_context].present?
Sentry.configure_scope do |scope|
scope.set_context(:extra, opts[:report_context])
end
diff --git a/core/lib/spree/core/engine.rb b/core/lib/spree/core/engine.rb
index 55bc83ed98..5fd592db6b 100644
--- a/core/lib/spree/core/engine.rb
+++ b/core/lib/spree/core/engine.rb
@@ -20,7 +20,8 @@ module Spree
:pages,
:page_sections,
:page_blocks,
- :reports)
+ :reports,
+ :analytics_event_handlers)
SpreeCalculators = Struct.new(:shipping_methods, :tax_rates, :promotion_actions_create_adjustments, :promotion_actions_create_item_adjustments)
PromoEnvironment = Struct.new(:rules, :actions)
isolate_namespace Spree
@@ -32,6 +33,7 @@ module Spree
initializer 'spree.environment', before: :load_config_initializers do |app|
app.config.spree = Environment.new(SpreeCalculators.new, Spree::Core::Configuration.new, Spree::Core::Dependencies.new)
+
app.config.active_record.yaml_column_permitted_classes ||= []
app.config.active_record.yaml_column_permitted_classes.concat([Symbol, BigDecimal, ActiveSupport::HashWithIndifferentAccess])
Spree::Config = app.config.spree.preferences
@@ -229,6 +231,8 @@ module Spree
Spree::Reports::ProductsPerformance,
Spree::Reports::SalesTotal
]
+
+ Rails.application.config.spree.analytics_event_handlers = []
end
initializer 'spree.promo.register.promotions.actions' do |app|
diff --git a/core/spec/models/spree/base_analytics_event_handler_spec.rb b/core/spec/models/spree/base_analytics_event_handler_spec.rb
new file mode 100644
index 0000000000..9c6a57a293
--- /dev/null
+++ b/core/spec/models/spree/base_analytics_event_handler_spec.rb
@@ -0,0 +1,62 @@
+require 'spec_helper'
+
+RSpec.describe Spree::BaseAnalyticsEventHandler do
+ let(:client) { double('client') }
+ let(:user) { create(:user) }
+ let(:session_id) { 'test-session-123' }
+ let(:handler) { described_class.new(client, user: user, session_id: session_id) }
+
+ describe '.client_method' do
+ it 'raises NotImplementedError' do
+ expect { described_class.client_method }.to raise_error(NotImplementedError)
+ end
+ end
+
+ describe '#initialize' do
+ it 'sets client, user and session_id' do
+ expect(handler.client).to eq(client)
+ expect(handler.user).to eq(user)
+ expect(handler.session_id).to eq(session_id)
+ end
+ end
+
+ describe '#handle_event' do
+ it 'raises NotImplementedError' do
+ expect { handler.handle_event('test_event') }.to raise_error(NotImplementedError)
+ end
+ end
+
+ describe '#event_label' do
+ it 'returns the label for supported events' do
+ expect(handler.event_label('product_viewed')).to eq('Product Viewed')
+ expect(handler.event_label('order_completed')).to eq('Order Completed')
+ expect(handler.event_label('checkout_started')).to eq('Checkout Started')
+ end
+
+ it 'returns nil for unsupported events' do
+ expect(handler.event_label('unsupported_event')).to be_nil
+ end
+ end
+
+ describe '#identity_hash' do
+ context 'when user is present' do
+ it 'returns hash with user_id and session_id' do
+ expect(handler.send(:identity_hash)).to eq({
+ user_id: user.id,
+ session_id: session_id
+ })
+ end
+ end
+
+ context 'when user is not present' do
+ let(:handler) { described_class.new(client, session_id: session_id) }
+
+ it 'returns hash with nil user_id and session_id' do
+ expect(handler.send(:identity_hash)).to eq({
+ user_id: nil,
+ session_id: session_id
+ })
+ end
+ end
+ end
+end
diff --git a/storefront/lib/spree/storefront/engine.rb b/storefront/lib/spree/storefront/engine.rb
index 83d0e759b1..5e9fd07fb8 100644
--- a/storefront/lib/spree/storefront/engine.rb
+++ b/storefront/lib/spree/storefront/engine.rb
@@ -7,6 +7,8 @@ module Spree
:head_partials,
:body_start_partials,
:body_end_partials,
+ :add_to_cart_partials,
+ :remove_from_cart_partials,
:checkout_partials,
:checkout_complete_partials
)
@@ -32,6 +34,8 @@ module Spree
Rails.application.config.spree_storefront.head_partials = []
Rails.application.config.spree_storefront.body_start_partials = []
Rails.application.config.spree_storefront.body_end_partials = []
+ Rails.application.config.spree_storefront.add_to_cart_partials = []
+ Rails.application.config.spree_storefront.remove_from_cart_partials = []
Rails.application.config.spree_storefront.checkout_partials = []
Rails.application.config.spree_storefront.checkout_complete_partials = []
end