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.
Ruby b2b-commercee-commerceecommerceecommerce-apiecommerce-frameworkecommerce-platformheadlessheadless-commerceheadless-ecommercemarketplacemulti-tenantmulti-vendormulti-vendor-ecommerceopen-sourcespree-commerce
Implement base for Bulk Promo Codes
Tomasz Donarski7f0f1445e249
diff --git a/api/app/controllers/spree/api/v2/platform/promotion_batches_controller.rb b/api/app/controllers/spree/api/v2/platform/promotion_batches_controller.rbnew file mode 100644index 0000000000..dea53e6361--- /dev/null+++ b/api/app/controllers/spree/api/v2/platform/promotion_batches_controller.rb@@ -0,0 +1,74 @@+module Spree+ module Api+ module V2+ module Platform+ class PromotionBatchesController < ResourceController+ def create+ super+ rescue ActiveRecord::InvalidForeignKey => e+ render json: { error: e.message }, status: :unprocessable_entity+ end++ def destroy+ result = destroy_service.call(promotion_batch: resource)++ if result.success?+ head 204+ else+ render_error_payload(result.error)+ end+ end++ def csv_export+ send_data Spree::PromotionBatches::PromotionCodesExporter.new(params).call,+ filename: "promo_codes_from_batch_id_#{params[:id]}.csv",+ disposition: :attachment,+ type: 'text/csv'+ end++ def csv_import+ file = params[:file]+ Spree::PromotionBatches::PromotionCodesImporter.new(file: file, promotion_batch_id: params[:id]).call+ render json: { message: Spree.t('code_upload') }, status: :ok+ rescue Spree::PromotionBatches::PromotionCodesImporter::Error => e+ render json: { error: e.message }, status: :unprocessable_entity+ end++ def populate+ batch_id = params[:id]+ options = {+ batch_size: params[:batch_size].to_i,+ affix: params.dig(:code, :affix)&.to_sym,+ content: params[:affix_content],+ deny_list: params[:forbidden_phrases].split,+ random_part_bytes: params[:random_part_bytes].to_i+ }++ Spree::Promotions::PopulatePromotionBatch.new(batch_id, options).call+ render json: { message: Spree.t('promotion_batch_populated') }, status: :ok+ rescue Spree::Promotions::PopulatePromotionBatch::TemplateNotFoundError => e+ render json: { error: e.message }, status: :unprocessable_entity+ end++ private++ def model_class+ Spree::PromotionBatch+ end++ def scope_includes+ [:promotion]+ end++ def spree_permitted_attributes+ [:template_promotion_id]+ end++ def destroy_service+ Spree::Api::Dependencies.platform_promotion_batch_destroy_service.constantize+ end+ end+ end+ end+ end+enddiff --git a/api/app/serializers/spree/api/v2/platform/promotion_batch_serializer.rb b/api/app/serializers/spree/api/v2/platform/promotion_batch_serializer.rbnew file mode 100644index 0000000000..93c34885e9--- /dev/null+++ b/api/app/serializers/spree/api/v2/platform/promotion_batch_serializer.rb@@ -0,0 +1,15 @@+module Spree+ module Api+ module V2+ module Platform+ class PromotionBatchSerializer < BaseSerializer+ include ResourceSerializerConcern++ belongs_to :template_promotion, serializer: PromotionSerializer++ has_many :promotions+ end+ end+ end+ end+enddiff --git a/api/config/routes.rb b/api/config/routes.rbindex 88641f65e2..58e92a9bb5 100644--- a/api/config/routes.rb+++ b/api/config/routes.rb@@ -72,6 +72,15 @@ Spree::Core::Engine.add_routes doresources :promotion_categoriesresources :promotion_rules+ # Promotion Batches API+ resources :promotion_batches do+ member do+ get :csv_export, to: 'promotion_batches#csv_export'+ post :csv_import, to: 'promotion_batches#csv_import'+ post :populate+ end+ end+# Returns APIresources :customer_returnsresources :reimbursementsdiff --git a/api/lib/spree/api/dependencies.rb b/api/lib/spree/api/dependencies.rbindex ca6ab43655..df84c35418 100644--- a/api/lib/spree/api/dependencies.rb+++ b/api/lib/spree/api/dependencies.rb@@ -114,6 +114,9 @@ module Spreeplatform_shipment_change_state_service: -> { Spree::Dependencies.shipment_change_state_service },platform_shipment_add_item_service: -> { Spree::Dependencies.shipment_add_item_service },platform_shipment_remove_item_service: -> { Spree::Dependencies.shipment_remove_item_service },++ # promotion batches services+ platform_promotion_batch_destroy_service: -> { Spree::Dependencies.promotion_batch_destroy_service },}include Spree::DependenciesHelperdiff --git a/api/spec/requests/spree/api/v2/platform/promotion_batches_spec.rb b/api/spec/requests/spree/api/v2/platform/promotion_batches_spec.rbnew file mode 100644index 0000000000..617169d8c3--- /dev/null+++ b/api/spec/requests/spree/api/v2/platform/promotion_batches_spec.rb@@ -0,0 +1,112 @@+require 'spec_helper'++describe 'Promotion API v2 spec', type: :request do+ include_context 'API v2 tokens'+ include_context 'Platform API v2'++ let(:bearer_token) { { 'Authorization' => valid_authorization } }++ describe 'promotion_batches#create' do+ context 'with valid params' do+ before { post '/api/v2/platform/promotion_batches', params: params, headers: bearer_token }++ let(:new_promotion_batch_attributes) do+ {+ template_promotion_id: nil+ }+ end++ let(:params) { { promotion_batch: new_promotion_batch_attributes } }++ it 'creates and returns a promotion batch' do+ expect(json_response['data']).to have_relationship(:template_promotion).with_data(nil)+ end+ end++ context 'when assigning a non-existing template' do+ before { post '/api/v2/platform/promotion_batches', params: params, headers: bearer_token }++ let(:new_promotion_batch_attributes) do+ {+ template_promotion_id: 123+ }+ end++ let(:params) { { promotion_batch: new_promotion_batch_attributes } }++ it 'does not create and returns an error' do+ expect(json_response.has_key?('error')).to eq(true)+ end+ end+ end++ describe 'promotion_batches#update' do+ context 'with valid params' do+ before { put "/api/v2/platform/promotion_batches/#{existing_promotion_batch.id}", params: params, headers: bearer_token }++ let(:existing_promotion) { create(:promotion) }+ let(:existing_promotion_batch) { create(:promotion_batch, template_promotion_id: nil) }++ let(:update_promotion_attributes) do+ {+ template_promotion_id: existing_promotion.id+ }+ end++ let(:params) { { promotion_batch: update_promotion_attributes } }++ it 'updates and returns a promotion batch' do+ expect(json_response['data']).to have_relationship(:template_promotion).with_data({ 'id' => existing_promotion.id.to_s, 'type' => 'promotion' })+ end+ end++ context 'when trying to override an assigned template' do+ before do+ existing_promotion+ other_existing_promotion+ existing_promotion_batch+ put "/api/v2/platform/promotion_batches/#{existing_promotion_batch.id}", params: params, headers: bearer_token+ end++ let(:existing_promotion) { create(:promotion) }+ let(:other_existing_promotion) { create(:promotion) }+ let(:existing_promotion_batch) { create(:promotion_batch, template_promotion: existing_promotion) }++ let(:update_promotion_attributes) do+ {+ template_promotion_id: other_existing_promotion.id+ }+ end++ let(:params) { { promotion_batch: update_promotion_attributes } }++ it 'does not update and returns an error' do+ expect(json_response.dig(:errors, :template_promotion_id)).to eq(['Template promotion has already been assigned!'])+ end+ end+ end++ describe 'promotion_batches#populate' do+ context 'with valid params' do+ before { post "/api/v2/platform/promotion_batches/#{existing_promotion_batch.id}/populate", params: params, headers: bearer_token }++ let(:existing_promotion_batch) { create(:promotion_batch) }++ let(:params) do+ {+ batch_size: 2,+ code: {+ affix: 'prefix'+ },+ affix_content: 'BLACKWEEK_',+ forbidden_phrases: 'forbidden phrases',+ random_part_bytes: 4+ }+ end++ it 'is successful' do+ expect(json_response[:message]).to eq('Promotion Batch is being populated.')+ end+ end+ end+enddiff --git a/core/app/jobs/spree/promotions/duplicate_promotion_job.rb b/core/app/jobs/spree/promotions/duplicate_promotion_job.rbnew file mode 100644index 0000000000..fb2fe2a240--- /dev/null+++ b/core/app/jobs/spree/promotions/duplicate_promotion_job.rb@@ -0,0 +1,12 @@+module Spree+ module Promotions+ class DuplicatePromotionJob < Spree::BaseJob+ def perform(template_promotion_id:, batch_id:, options: {}, code: nil)+ promotion = Spree::Promotion.find(template_promotion_id)+ code = code || Spree::PromotionBatches::BatchCodeGenerator.build(batch_id, options)++ Spree::PromotionHandler::PromotionBatchDuplicator.new(promotion, batch_id, code: code).duplicate+ end+ end+ end+enddiff --git a/core/app/jobs/spree/promotions/handle_descendant_promotion_job.rb b/core/app/jobs/spree/promotions/handle_descendant_promotion_job.rbnew file mode 100644index 0000000000..00d2df4c82--- /dev/null+++ b/core/app/jobs/spree/promotions/handle_descendant_promotion_job.rb@@ -0,0 +1,22 @@+module Spree+ module Promotions+ class HandleDescendantPromotionJob < Spree::BaseJob+ def perform(template_promotion_id:, descendant_promotion_id:, promotion_batch_id:)+ template_promotion = find_promotion(template_promotion_id)+ descendant_promotion = find_promotion(descendant_promotion_id)++ handle_promotion(template_promotion, promotion_batch_id, descendant_promotion)+ end++ private++ def find_promotion(id)+ Spree::Promotion.find(id)+ end++ def handle_promotion(template_promotion, promotion_batch_id, descendant_promotion)+ Spree::PromotionHandler::PromotionBatchUpdateHandler.new(template_promotion, promotion_batch_id, descendant_promotion).duplicate+ end+ end+ end+enddiff --git a/core/app/models/spree/promotion.rb b/core/app/models/spree/promotion.rbindex 45c435177a..f578f26d10 100644--- a/core/app/models/spree/promotion.rb+++ b/core/app/models/spree/promotion.rb@@ -15,6 +15,7 @@ module Spreeattr_reader :eligibility_errors, :generate_codebelongs_to :promotion_category, optional: true+ belongs_to :promotion_batch, optional: truehas_many :promotion_rules, autosave: true, dependent: :destroyalias rules promotion_rules@@ -39,6 +40,8 @@ module Spreeauto_strip_attributes :code, :path, :name+ after_update :update_descendants+scope :coupons, -> { where.not(code: nil) }scope :advertised, -> { where(advertise: true) }scope :applied, lambda {@@ -47,6 +50,7 @@ module SpreeON spree_order_promotions.promotion_id = #{table_name}.idSQL}+ scope :non_batched, -> { where(promotion_batch_id: nil) }self.whitelisted_ransackable_attributes = ['path', 'promotion_category_id', 'code']@@ -236,5 +240,9 @@ module Spreeendcoupon_codeend++ def update_descendants+ Spree::PromotionHandler::UpdateDescendantsService.new(self).call+ endendenddiff --git a/core/app/models/spree/promotion_batch.rb b/core/app/models/spree/promotion_batch.rbnew file mode 100644index 0000000000..21421be9d5--- /dev/null+++ b/core/app/models/spree/promotion_batch.rb@@ -0,0 +1,16 @@+module Spree+ class PromotionBatch < Spree::Base+ validate :template_assignment, on: :update++ has_many :promotions+ belongs_to :template_promotion, class_name: "Promotion"++ private++ def template_assignment+ if template_promotion_id_changed? && template_promotion_id_was.present?+ errors.add(:template_promotion_id, :template_promotion_already_assigned, message: Spree.t(:template_promotion_already_assigned))+ end+ end+ end+enddiff --git a/core/app/models/spree/promotion_duplicator_core.rb b/core/app/models/spree/promotion_duplicator_core.rbnew file mode 100644index 0000000000..4248694d37--- /dev/null+++ b/core/app/models/spree/promotion_duplicator_core.rb@@ -0,0 +1,45 @@+module Spree+ class PromotionDuplicatorCore+ def initialize(promotion, random_string: generate_random_string(4))+ @promotion = promotion+ @random_string = random_string+ end++ def duplicate+ raise NotImplementedError+ end++ private++ def copy_rules(new_promotion)+ @promotion.promotion_rules.each do |rule|+ new_rule = rule.dup+ new_promotion.promotion_rules << new_rule++ new_rule.users = rule.users if rule.try(:users)+ new_rule.taxons = rule.taxons if rule.try(:taxons)+ new_rule.products = rule.products if rule.try(:products)+ end+ end++ def generate_random_string(number)+ charset = Array('A'..'Z') + Array('a'..'z')+ Array.new(number) { charset.sample }.join+ end++ def copy_actions(new_promotion)+ @promotion.promotion_actions.each do |action|+ new_action = action.dup+ new_action.calculator = action.calculator.dup if action.try(:calculator)++ new_promotion.promotion_actions << new_action++ next unless action.try(:promotion_action_line_items)++ action.promotion_action_line_items.each do |item|+ new_action.promotion_action_line_items << item.dup+ end+ end+ end+ end+enddiff --git a/core/app/models/spree/promotion_handler/promotion_batch_duplicator.rb b/core/app/models/spree/promotion_handler/promotion_batch_duplicator.rbnew file mode 100644index 0000000000..204dbb0851--- /dev/null+++ b/core/app/models/spree/promotion_handler/promotion_batch_duplicator.rb@@ -0,0 +1,39 @@+module Spree+ module PromotionHandler+ class PromotionBatchDuplicator < Spree::PromotionDuplicatorCore+ def initialize(promotion, promotion_batch_id, random_string: generate_random_string(4), code: nil)+ @promotion = promotion+ @promotion_batch_id = promotion_batch_id+ @random_string = random_string+ @code = code+ end++ def duplicate+ new_promotion = @promotion.dup+ new_promotion.usage_limit = 1+ new_promotion.promotion_batch_id = @promotion_batch_id+ new_promotion.path = "#{@promotion.path}_#{@random_string}"+ code_assignment(new_promotion)+ new_promotion.stores = @promotion.stores++ ActiveRecord::Base.transaction do+ new_promotion.save+ copy_rules(new_promotion)+ copy_actions(new_promotion)+ end++ new_promotion+ end++ private++ def code_assignment(new_promotion)+ if @code+ new_promotion.code = @code+ else+ new_promotion.generate_code=(true)+ end+ end+ end+ end+enddiff --git a/core/app/models/spree/promotion_handler/promotion_batch_update_handler.rb b/core/app/models/spree/promotion_handler/promotion_batch_update_handler.rbnew file mode 100644index 0000000000..514ff7d508--- /dev/null+++ b/core/app/models/spree/promotion_handler/promotion_batch_update_handler.rb@@ -0,0 +1,29 @@+module Spree+ module PromotionHandler+ class PromotionBatchUpdateHandler < Spree::PromotionDuplicatorCore+ def initialize(promotion, promotion_batch_id, descendant_promotion)+ @promotion = promotion+ @promotion_batch_id = promotion_batch_id+ @descendant_promotion = descendant_promotion+ end++ def duplicate+ new_promotion = @promotion.dup+ new_promotion.usage_limit = 1+ new_promotion.promotion_batch_id = @promotion_batch_id+ new_promotion.path = @descendant_promotion.path+ new_promotion.code = @descendant_promotion.code+ new_promotion.stores = @promotion.stores++ ActiveRecord::Base.transaction do+ @descendant_promotion.destroy!+ new_promotion.save+ copy_rules(new_promotion)+ copy_actions(new_promotion)+ end++ new_promotion+ end+ end+ end+enddiff --git a/core/app/models/spree/promotion_handler/promotion_duplicator.rb b/core/app/models/spree/promotion_handler/promotion_duplicator.rbindex e88c34bb96..711221d727 100644--- a/core/app/models/spree/promotion_handler/promotion_duplicator.rb+++ b/core/app/models/spree/promotion_handler/promotion_duplicator.rb@@ -1,58 +1,20 @@module Spreemodule PromotionHandler- class PromotionDuplicator- def initialize(promotion, random_string: nil)- @promotion = promotion- @random_string = random_string || generate_random_string(4)- end-+ class PromotionDuplicator < Spree::PromotionDuplicatorCoredef duplicate- @new_promotion = @promotion.dup- @new_promotion.path = "#{@promotion.path}_#{@random_string}"- @new_promotion.name = "New #{@promotion.name}"- @new_promotion.code = "#{@promotion.code}_#{@random_string}"- @new_promotion.stores = @promotion.stores+ new_promotion = @promotion.dup+ new_promotion.path = "#{@promotion.path}_#{@random_string}"+ new_promotion.name = "New #{@promotion.name}"+ new_promotion.code = "#{@promotion.code}_#{@random_string}"+ new_promotion.stores = @promotion.storesActiveRecord::Base.transaction do- @new_promotion.save- copy_rules- copy_actions+ new_promotion.save+ copy_rules(new_promotion)+ copy_actions(new_promotion)end- @new_promotion- end-- private-- def copy_rules- @promotion.promotion_rules.each do |rule|- new_rule = rule.dup- @new_promotion.promotion_rules << new_rule-- new_rule.users = rule.users if rule.try(:users)- new_rule.taxons = rule.taxons if rule.try(:taxons)- new_rule.products = rule.products if rule.try(:products)- end- end-- def generate_random_string(number)- charset = Array('A'..'Z') + Array('a'..'z')- Array.new(number) { charset.sample }.join- end-- def copy_actions- @promotion.promotion_actions.each do |action|- new_action = action.dup- new_action.calculator = action.calculator.dup if action.try(:calculator)-- @new_promotion.promotion_actions << new_action-- next unless action.try(:promotion_action_line_items)-- action.promotion_action_line_items.each do |item|- new_action.promotion_action_line_items << item.dup- end- end+ new_promotionendendenddiff --git a/core/app/models/spree/promotion_handler/update_descendants_service.rb b/core/app/models/spree/promotion_handler/update_descendants_service.rbnew file mode 100644index 0000000000..69dee79fe2--- /dev/null+++ b/core/app/models/spree/promotion_handler/update_descendants_service.rb@@ -0,0 +1,48 @@+module Spree+ module PromotionHandler+ class UpdateDescendantsService+ def initialize(template_promotion)+ @template_promotion = template_promotion+ end++ def call+ return unless promotion_batches?++ unused_promotions_ids_by_batch.each do |batch|+ batch.each do |batch_id, promotion_ids|+ promotion_ids.each do |promotion_id|+ Spree::Promotions::HandleDescendantPromotionJob.perform_later(+ template_promotion_id: @template_promotion.id,+ descendant_promotion_id: promotion_id,+ promotion_batch_id: batch_id+ )+ end+ end+ end+ end++ private++ def promotion_batches?+ promotion_batches.any?+ end++ def promotion_batches+ @promotion_batches = Spree::PromotionBatch.where(template_promotion_id: @template_promotion.id)+ end++ def unused_promotions_ids_by_batch+ @promotion_batches.map do |batch|+ {batch.id => unused_promotions_ids(batch)}+ end+ end++ def unused_promotions_ids(batch)+ batch.promotions+ .includes(:promotion_actions)+ .select {|promotion| promotion.credits_count < promotion.usage_limit}+ .pluck(:id)+ end+ end+ end+enddiff --git a/core/app/presenters/spree/promotion_batch_presenter.rb b/core/app/presenters/spree/promotion_batch_presenter.rbnew file mode 100644index 0000000000..f41bb5ac25--- /dev/null+++ b/core/app/presenters/spree/promotion_batch_presenter.rb@@ -0,0 +1,32 @@+module Spree+ class PromotionBatchPresenter+ def initialize(promotion_batch)+ @promotion_batch = promotion_batch+ end++ def call+ {+ template_promotion_name_id: template_promotion_name_id,+ model_name_id: model_name_id+ }+ end++ private++ attr_reader :promotion_batch++ def template_promotion_name_id+ return "" unless promotion_batch.template_promotion++ base = promotion_batch.template_promotion.name+ addon = promotion_batch.template_promotion_id.to_s+ base + ' # ' + addon+ end++ def model_name_id+ base = promotion_batch.class.name.demodulize+ addon = promotion_batch.id.to_s+ base + ' # ' + addon+ end+ end+enddiff --git a/core/app/services/spree/promotion_batches/batch_code_generator.rb b/core/app/services/spree/promotion_batches/batch_code_generator.rbnew file mode 100644index 0000000000..c1521c6723--- /dev/null+++ b/core/app/services/spree/promotion_batches/batch_code_generator.rb@@ -0,0 +1,41 @@+module Spree+ module PromotionBatches+ class BatchCodeGenerator+ class << self+ def build(batch_id, options)+ promotion_batch = Spree::PromotionBatch.find(batch_id)+ codes = codes(promotion_batch)+ code_generator = code_generator(options)++ loop do+ candidate = generate_code(code_generator)+ break candidate if candidate_valid?(candidate, codes)+ end+ end++ private++ def codes(promotion_batch)+ promotion_batch.promotions.pluck :code+ end++ def code_generator(options)+ Spree::Promotions::CodeGenerator.new(+ content: options[:content],+ affix: options[:affix],+ deny_list: options[:deny_list],+ random_part_bytes: options[:random_part_bytes]+ )+ end++ def generate_code(generator)+ generator.build+ end++ def candidate_valid?(candidate, codes)+ codes.exclude?(candidate)+ end+ end+ end+ end+enddiff --git a/core/app/services/spree/promotion_batches/destroy.rb b/core/app/services/spree/promotion_batches/destroy.rbnew file mode 100644index 0000000000..dbeac387f4--- /dev/null+++ b/core/app/services/spree/promotion_batches/destroy.rb@@ -0,0 +1,15 @@+module Spree+ module PromotionBatches+ class Destroy+ prepend Spree::ServiceModule::Base++ def call(promotion_batch:)+ ActiveRecord::Base.transaction do+ promotion_batch.promotions.destroy_all+ promotion_batch.update(template_promotion_id: nil)+ promotion_batch.destroy!+ end+ end+ end+ end+enddiff --git a/core/app/services/spree/promotion_batches/promotion_codes_exporter.rb b/core/app/services/spree/promotion_batches/promotion_codes_exporter.rbnew file mode 100644index 0000000000..dde798a9c7--- /dev/null+++ b/core/app/services/spree/promotion_batches/promotion_codes_exporter.rb@@ -0,0 +1,25 @@+module Spree+ module PromotionBatches+ class PromotionCodesExporter+ def initialize(params)+ @promotion_batch = find_promotion_batch(params[:id])+ end++ def call+ Spree::Core::Converters::CSV.to_csv(promo_codes)+ end++ private++ def find_promotion_batch(id)+ Spree::PromotionBatch.find(id)+ end++ def promo_codes+ @promotion_batch.promotions.map do |promotion|+ [promotion.code]+ end+ end+ end+ end+enddiff --git a/core/app/services/spree/promotion_batches/promotion_codes_importer.rb b/core/app/services/spree/promotion_batches/promotion_codes_importer.rbnew file mode 100644index 0000000000..513aba690c--- /dev/null+++ b/core/app/services/spree/promotion_batches/promotion_codes_importer.rb@@ -0,0 +1,63 @@+module Spree+ module PromotionBatches+ class PromotionCodesImporter+ Error = Class.new(StandardError)++ ALLOWED_FILE_TYPES = %w(text/csv).freeze++ def initialize(file:, promotion_batch_id:)+ @content_type = file&.content_type+ @content = file&.read.to_s+ @promotion_batch = find_promotion_batch(promotion_batch_id)+ end++ def call+ validate_file!+ validate_promotion_batch!++ parsed_rows.each do |parsed_row|+ Spree::Promotions::DuplicatePromotionJob+ .perform_later(template_promotion_id: @promotion_batch.template_promotion_id, batch_id: @promotion_batch.id, code: parsed_row)+ end+ end++ private++ def find_promotion_batch(id)+ Spree::PromotionBatch.find(id)+ end++ def validate_file!+ raise Error, Spree.t('invalid_file') unless file_valid+ end++ def file_valid+ file_type_correct? && file_not_empty?+ end++ def file_type_correct?+ @content_type.in?(ALLOWED_FILE_TYPES)+ end++ def file_not_empty?+ parsed_rows.present?+ end++ def validate_promotion_batch!+ raise Error, Spree.t('no_template_promotion') unless batch_validation_condition+ end++ def batch_validation_condition+ @promotion_batch.template_promotion_id+ end++ def parsed_rows+ CSV.new(rows, headers: false).read.map(&:first)+ end++ def rows+ @content.lines.join+ end+ end+ end+enddiff --git a/core/app/services/spree/promotions/code_generator.rb b/core/app/services/spree/promotions/code_generator.rbnew file mode 100644index 0000000000..6b464e6649--- /dev/null+++ b/core/app/services/spree/promotions/code_generator.rb@@ -0,0 +1,81 @@+module Spree+ module Promotions+ class CodeGenerator+ MutuallyExclusiveInputsError = Class.new(StandardError)+ RetriesDepleted = Class.new(StandardError)++ def initialize(content: nil, affix: nil, deny_list: [], random_part_bytes: 4)+ @content = content+ @affix = affix+ @deny_list = deny_list+ @random_part_bytes = random_part_bytes+ end++ def build+ validate_inputs unless deny_list.empty?+ success = false+ result = 100.times do+ candidate = compose+ if valid?(candidate)+ success = true+ break candidate+ end+ end+ success ? result : raise(RetriesDepleted)+ end++ private++ attr_reader :content, :affix, :deny_list, :random_part_bytes++ def validate_inputs+ raise_error if inputs_invalid?+ end++ def valid?(subject)+ return true if deny_list.empty?++ violation_checks = deny_list.map do |el|+ subject.include?(el)+ end++ violation_checks.none?+ end++ def compose+ case affix+ when :prefix+ prefix_alorithm+ when :suffix+ suffix_alorithm+ else+ default_algorithm+ end+ end++ def prefix_alorithm+ content + random_code+ end++ def suffix_alorithm+ random_code + content+ end++ def default_algorithm+ random_code+ end++ def random_code+ SecureRandom.hex(random_part_bytes)+ end++ def raise_error+ raise MutuallyExclusiveInputsError, Spree.t(:mutually_exclusive_inputs)+ end++ def inputs_invalid?+ deny_list.include?(content)+ end+ end+ end+enddiff --git a/core/app/services/spree/promotions/populate_promotion_batch.rb b/core/app/services/spree/promotions/populate_promotion_batch.rbnew file mode 100644index 0000000000..3ce16c8f6d--- /dev/null+++ b/core/app/services/spree/promotions/populate_promotion_batch.rb@@ -0,0 +1,37 @@+module Spree+ module Promotions+ class PopulatePromotionBatch+ TemplateNotFoundError = Class.new(StandardError)++ def initialize(batch_id, options = {})+ @batch_id = batch_id+ @options = options+ end++ def call+ validate_template_presence!++ size.times do+ DuplicatePromotionJob.perform_later(template_promotion_id: template_promotion_id, batch_id: batch_id, options: options.except(:batch_size))+ end+ end++ private++ attr_accessor :options+ attr_reader :batch_id++ def validate_template_presence!+ raise TemplateNotFoundError, Spree.t('template_not_found') unless template_promotion_id+ end++ def size+ options[:batch_size]+ end++ def template_promotion_id+ PromotionBatch.find(batch_id).template_promotion_id+ end+ end+ end+enddiff --git a/core/config/locales/en.yml b/core/config/locales/en.ymlindex 67890a1ac2..f1ff1ed252 100644--- a/core/config/locales/en.yml+++ b/core/config/locales/en.yml@@ -229,6 +229,9 @@ en:spree/promotion:one: Promotionother: Promotions+ spree/promotion_batch:+ one: Promotion Batch+ other: Promotion Batchesspree/promotion_category:one: Promotion Categoryother: Promotion Categories@@ -680,6 +683,7 @@ en:close: Closeclose_all_adjustments: Close All Adjustmentscode: Code+ code_upload: Promotion codes are being uploaded. It might take a while.company: Companycompare_at_price: Compare at pricecomplete: complete@@ -942,6 +946,7 @@ en:internationalization: Internationalizationinvalid_credit_card: Invalid credit card.invalid_exchange_variant: Invalid exchange variant.+ invalid_file: No file / Wrong file format / Empty fileinvalid_payment_provider: Invalid payment provider.invalid_promotion_action: Invalid promotion action.invalid_promotion_rule: Invalid promotion rule.@@ -1019,6 +1024,7 @@ en:meta_title: Meta Titlemetadata: Metadatamutable: Mutable+ mutually_exclusive_inputs: Invalid inputs. Forbidden phrases cannot contain the affix.must_have_one_store: The resource must belong to a store.min: 'Min'minimal_amount: Minimal Amount@@ -1059,6 +1065,7 @@ en:new_payment_method: New Payment Methodnew_product: New Productnew_promotion: New Promotion+ new_promotion_batch: New Promotion Batchnew_promotion_category: New Promotion Categorynew_property: New Propertynew_prototype: New Prototype@@ -1103,6 +1110,7 @@ en:no_returns_found: No returns foundno_shipping_method_selected: No shipping method selected.no_state_changes: No state changes yet.+ no_template_promotion: Promotion template must be set in order to import promotion codes.no_tracking_present: No tracking details provided.user_not_found: User not foundnone: None@@ -1311,8 +1319,20 @@ en:manual: Manually chooseproducts: Productspromotion: Promotion+ promotion_batch: Promotion Batch+ promotion_batches: Promotion Batches+ promotion_batch_form:+ affix: Affix+ affix_content: Affix content+ batch_size: Batch size+ forbidden_phrases: Forbidden phrases+ import_codes: Import codes from CSV+ populate: Populate+ prefix: Prefix+ random_part_bytes: Random part bytes+ sufix: Sufix+ promotion_batch_populated: Promotion Batch is being populated.promotionable: Promotable- promotion_cloned: Promotion has been clonedpromotion_not_cloned: "Promotion has not been cloned. Reason: %{error}"promotion_action: Promotion Actionpromotion_action_types:@@ -1723,6 +1743,8 @@ en:taxonomy_tree_error: The requested change has not been accepted and the tree has been returned to its previous state, please try again.taxonomy_tree_instruction: ! '* Right click (or double tap on iOS device) a child in the tree to access the menu for adding, deleting or sorting a child.'taxons: Taxons+ template_not_found: Template promotion - not found! Assign a template before populating a batch.+ template_promotion_already_assigned: Template promotion has already been assigned!test: Testtest_mailer:test_email:diff --git a/core/db/migrate/20231114071427_create_promotion_batches.rb b/core/db/migrate/20231114071427_create_promotion_batches.rbnew file mode 100644index 0000000000..dbcd3879d8--- /dev/null+++ b/core/db/migrate/20231114071427_create_promotion_batches.rb@@ -0,0 +1,9 @@+class CreatePromotionBatches < ActiveRecord::Migration[6.1]+ def change+ create_table :spree_promotion_batches do |t|+ t.string :status++ t.timestamps+ end+ end+enddiff --git a/core/db/migrate/20231114084551_add_template_promotion_id_to_promotion_batches.rb b/core/db/migrate/20231114084551_add_template_promotion_id_to_promotion_batches.rbnew file mode 100644index 0000000000..eee22fbb21--- /dev/null+++ b/core/db/migrate/20231114084551_add_template_promotion_id_to_promotion_batches.rb@@ -0,0 +1,5 @@+class AddTemplatePromotionIdToPromotionBatches < ActiveRecord::Migration[6.1]+ def change+ add_reference(:spree_promotion_batches, :template_promotion, foreign_key: { to_table: :spree_promotions })+ end+enddiff --git a/core/db/migrate/20231114182646_add_promotion_batch_reference_to_promotions.rb b/core/db/migrate/20231114182646_add_promotion_batch_reference_to_promotions.rbnew file mode 100644index 0000000000..f93f6db43c--- /dev/null+++ b/core/db/migrate/20231114182646_add_promotion_batch_reference_to_promotions.rb@@ -0,0 +1,5 @@+class AddPromotionBatchReferenceToPromotions < ActiveRecord::Migration[6.1]+ def change+ add_reference(:spree_promotions, :promotion_batch, foreign_key: { to_table: :spree_promotion_batches})+ end+enddiff --git a/core/db/migrate/20231211152651_add_unique_index_to_promotions_on_code_and_promotion_batch_id.rb b/core/db/migrate/20231211152651_add_unique_index_to_promotions_on_code_and_promotion_batch_id.rbnew file mode 100644index 0000000000..7e1bee4147--- /dev/null+++ b/core/db/migrate/20231211152651_add_unique_index_to_promotions_on_code_and_promotion_batch_id.rb@@ -0,0 +1,5 @@+class AddUniqueIndexToPromotionsOnCodeAndPromotionBatchId < ActiveRecord::Migration[6.1]+ def change+ add_index(:spree_promotions, [:code, :promotion_batch_id], unique: true)+ end+enddiff --git a/core/db/migrate/20231223085020_remove_status_from_pomotion_batches.rb b/core/db/migrate/20231223085020_remove_status_from_pomotion_batches.rbnew file mode 100644index 0000000000..32d15f4337--- /dev/null+++ b/core/db/migrate/20231223085020_remove_status_from_pomotion_batches.rb@@ -0,0 +1,5 @@+class RemoveStatusFromPomotionBatches < ActiveRecord::Migration[6.1]+ def change+ remove_column(:spree_promotion_batches, :status)+ end+enddiff --git a/core/lib/spree/core.rb b/core/lib/spree/core.rbindex 540ac5b44b..2d3e8a54b1 100644--- a/core/lib/spree/core.rb+++ b/core/lib/spree/core.rb@@ -128,6 +128,7 @@ require 'spree/service_module'require 'spree/database_type_utilities'require 'spree/core/importer'+require 'spree/core/converters'require 'spree/core/query_filters'require 'spree/core/product_duplicator'require 'spree/core/controller_helpers/auth'diff --git a/core/lib/spree/core/converters.rb b/core/lib/spree/core/converters.rbnew file mode 100644index 0000000000..df98b096f8--- /dev/null+++ b/core/lib/spree/core/converters.rb@@ -0,0 +1,8 @@+module Spree+ module Core+ module Converters+ end+ end+end++require 'spree/core/converters/csv'diff --git a/core/lib/spree/core/converters/csv.rb b/core/lib/spree/core/converters/csv.rbnew file mode 100644index 0000000000..46a461ae9a--- /dev/null+++ b/core/lib/spree/core/converters/csv.rb@@ -0,0 +1,17 @@+require "csv"++module Spree+ module Core+ module Converters+ class CSV+ def self.to_csv(rows)+ ::CSV.generate do |csv|+ rows.each do |row|+ csv << row+ end+ end+ end+ end+ end+ end+enddiff --git a/core/lib/spree/core/dependencies.rb b/core/lib/spree/core/dependencies.rbindex 5f92821756..4c3dbdbf2a 100644--- a/core/lib/spree/core/dependencies.rb+++ b/core/lib/spree/core/dependencies.rb@@ -97,7 +97,10 @@ module Spreecredit_card_finder: 'Spree::CreditCards::Find',products_finder: 'Spree::Products::Find',taxon_finder: 'Spree::Taxons::Find',- line_item_by_variant_finder: 'Spree::LineItems::FindByVariant'+ line_item_by_variant_finder: 'Spree::LineItems::FindByVariant',++ # promotion batches+ promotion_batch_destroy_service: 'Spree::PromotionBatches::Destroy'}.freezeinclude Spree::DependenciesHelperdiff --git a/core/lib/spree/testing_support/factories/promotion_batch_factory.rb b/core/lib/spree/testing_support/factories/promotion_batch_factory.rbnew file mode 100644index 0000000000..2b69c7cf7b--- /dev/null+++ b/core/lib/spree/testing_support/factories/promotion_batch_factory.rb@@ -0,0 +1,5 @@+FactoryBot.define do+ factory :promotion_batch, class: Spree::PromotionBatch do+ association :template_promotion, factory: :promotion+ end+enddiff --git a/core/lib/spree/testing_support/factories/promotion_factory.rb b/core/lib/spree/testing_support/factories/promotion_factory.rbindex 09b1f4c71b..16d022d1a3 100644--- a/core/lib/spree/testing_support/factories/promotion_factory.rb+++ b/core/lib/spree/testing_support/factories/promotion_factory.rb@@ -16,6 +16,14 @@ FactoryBot.define doendend+ trait :with_unique_code do+ code { SecureRandom.hex(4) }+ end++ trait :batched do+ promotion_batch+ end+factory :promotion, class: Spree::Promotion doname { 'Promo' }diff --git a/core/spec/jobs/spree/promotions/duplicate_promotion_job_spec.rb b/core/spec/jobs/spree/promotions/duplicate_promotion_job_spec.rbnew file mode 100644index 0000000000..e1cccd7f76--- /dev/null+++ b/core/spec/jobs/spree/promotions/duplicate_promotion_job_spec.rb@@ -0,0 +1,69 @@+require 'spec_helper'++module Spree+ describe Promotions::DuplicatePromotionJob do+ describe "#perform" do+ let(:promotion) { build(:promotion) }+ let(:promotion_batch) { build(:promotion_batch) }+ let(:new_code) { 'new_code' }+ let(:duplicator) { instance_double(Spree::PromotionHandler::PromotionDuplicator) }++ before do+ allow(Spree::Promotion)+ .to receive(:find)+ .and_return(promotion)+ end++ context 'when code is NOT provided' do+ let(:options) { {key: 'value'} }++ subject(:execute_job) do+ described_class.new.perform(template_promotion_id: promotion.id, batch_id: promotion_batch.id, options: options)+ end++ before do+ allow(Spree::PromotionBatches::BatchCodeGenerator)+ .to receive(:build)+ .with(promotion_batch.id, options)+ .and_return(new_code)+ allow(Spree::PromotionHandler::PromotionBatchDuplicator)+ .to receive(:new)+ .with(promotion, promotion_batch.id, code: new_code)+ .and_return(duplicator)+ allow(duplicator)+ .to receive(:duplicate)+ end++ it "sends #duplicate to the duplicator service" do+ expect(Spree::PromotionHandler::PromotionBatchDuplicator)+ .to receive(:new)+ .with(promotion, promotion_batch.id, code: new_code)+ .and_return(duplicator)+ expect(duplicator)+ .to receive(:duplicate)++ execute_job+ end+ end++ context 'when code IS provided' do+ subject(:execute_job) do+ described_class.new.perform(template_promotion_id: promotion.id, batch_id: promotion_batch.id, code: specified_code)+ end++ let(:specified_code) { 'specified_code' }++ it "sends #duplicate to the duplicator service" do+ expect(Spree::PromotionHandler::PromotionBatchDuplicator)+ .to receive(:new)+ .with(promotion, promotion_batch.id, code: specified_code)+ .and_return(duplicator)+ expect(duplicator)+ .to receive(:duplicate)++ execute_job+ end+ end+ end+ end+enddiff --git a/core/spec/jobs/spree/promotions/handle_descendant_promotion_job_spec.rb b/core/spec/jobs/spree/promotions/handle_descendant_promotion_job_spec.rbnew file mode 100644index 0000000000..53d844aebf--- /dev/null+++ b/core/spec/jobs/spree/promotions/handle_descendant_promotion_job_spec.rb@@ -0,0 +1,37 @@+require 'spec_helper'++module Spree+ describe Promotions::HandleDescendantPromotionJob do+ describe "#perform" do+ let(:template_promotion) { build(:promotion) }+ let(:descendant_promotion) { build(:promotion) }+ let(:batch) { instance_double(Spree::PromotionBatch, id: 123) }+ let(:duplicator) { instance_double(Spree::PromotionHandler::PromotionBatchUpdateHandler) }++ before do+ allow(Spree::Promotion)+ .to receive(:find)+ .and_return(template_promotion, descendant_promotion)+ end++ subject(:execute_job) do+ described_class.new.perform(+ template_promotion_id: template_promotion.id,+ descendant_promotion_id: descendant_promotion.id,+ promotion_batch_id: batch.id+ )+ end++ it "sends #duplicate to the duplicator service" do+ expect(Spree::PromotionHandler::PromotionBatchUpdateHandler)+ .to receive(:new)+ .with(template_promotion, batch.id, descendant_promotion)+ .and_return(duplicator)+ expect(duplicator)+ .to receive(:duplicate)++ execute_job+ end+ end+ end+enddiff --git a/core/spec/lib/spree/core/converters/csv_spec.rb b/core/spec/lib/spree/core/converters/csv_spec.rbnew file mode 100644index 0000000000..312fceeaed--- /dev/null+++ b/core/spec/lib/spree/core/converters/csv_spec.rb@@ -0,0 +1,31 @@+require 'spec_helper'++module Spree+ module Core+ describe Converters::CSV do+ subject(:csv_converter) { described_class }++ describe ".to_csv" do+ subject(:convert_to_csv) { csv_converter.to_csv(input) }++ let(:input) do+ [+ ["row1a", "row1b", 1, :symbol, "coma,case"],+ ["row2a", "row2b", 2, :symbol, "newline\ncase"],+ ]+ end++ let(:expected_csv_representation) do+ [+ "row1a,row1b,1,symbol,\"coma,case\"\n",+ "row2a,row2b,2,symbol,\"newline\ncase\"\n",+ ].join+ end++ it "returns a valid csv representation" do+ expect(convert_to_csv).to eql expected_csv_representation+ end+ end+ end+ end+enddiff --git a/core/spec/models/spree/promotion_batch_spec.rb b/core/spec/models/spree/promotion_batch_spec.rbnew file mode 100644index 0000000000..c4c5f068f2--- /dev/null+++ b/core/spec/models/spree/promotion_batch_spec.rb@@ -0,0 +1,21 @@+require 'spec_helper'++describe Spree::PromotionBatch, type: :model do+ describe 'validations' do+ describe 'template_assignment' do+ let(:promotion) { create(:promotion) }+ let(:other_promotion) { create(:promotion) }+ let(:promotion_batch) { create(:promotion_batch, template_promotion: promotion) }++ before do+ promotion+ other_promotion+ promotion_batch+ end++ it 'should validate template_assignment on update' do+ expect { promotion_batch.update!(template_promotion: other_promotion) }.to raise_error(ActiveRecord::RecordInvalid)+ end+ end+ end+enddiff --git a/core/spec/models/spree/promotion_handler/promotion_batch_duplicator_spec.rb b/core/spec/models/spree/promotion_handler/promotion_batch_duplicator_spec.rbnew file mode 100644index 0000000000..538aa15026--- /dev/null+++ b/core/spec/models/spree/promotion_handler/promotion_batch_duplicator_spec.rb@@ -0,0 +1,142 @@+require 'spec_helper'++describe Spree::PromotionHandler::PromotionBatchDuplicator do+ subject { described_class.new(promotion, promotion_batch.id) }++ let!(:promo_category) { create(:promotion_category) }+ let!(:calculator) { create(:calculator) }++ let(:store) { create(:store) }+ let(:store_2) { create(:store) }+ let!(:promotion) do+ create(:promotion_with_item_total_rule,+ description: 'Test description',+ expires_at: Date.current + 30,+ starts_at: Date.current,+ usage_limit: 100,+ match_policy: 'all',+ code: 'test1',+ advertise: true,+ path: 'test1',+ promotion_category: promo_category,+ stores: [store, store_2])+ end++ before do+ Spree::Promotion::Actions::CreateItemAdjustments.create!(calculator: calculator, promotion: promotion)+ end++ describe '#duplicate' do+ let(:new_promotion) { subject.duplicate }+ let(:promotion_batch) { create(:promotion_batch) }++ context 'model fields' do+ let(:excluded_fields) { ['code', 'path', 'id', 'created_at', 'updated_at', 'deleted_at', 'promotion_batch_id', 'usage_limit'] }++ context "when code is provided" do+ subject { described_class.new(promotion, promotion_batch.id, code: provided_code) }++ let(:provided_code) { 'provided_code' }++ it 'assigns a unique code to the duplicated promotion' do+ result = new_promotion+ expect(result.code).to match provided_code+ end+ end++ context "when code is NOT provided" do+ let(:new_code) { 'secure_random_code' }++ before do+ allow(SecureRandom).to receive(:hex).with(4).and_return(new_code)+ end++ it 'assigns a unique code to the duplicated promotion' do+ expect(SecureRandom).to receive(:hex).with(4).and_return(new_code)+ result = new_promotion+ expect(result.code).to match new_code+ end+ end++ it 'returns a duplicate of a promotion with the path field changed' do+ expect(new_promotion.path).to match /#{promotion.path}_[a-zA-Z]{4}/+ end++ it 'returns a duplicate of a promotion with all the fields (except the path, code and usage_limit fields) the same' do+ promotion.attributes.each_key do |key|+ expect(promotion.send(key)).to eq new_promotion.send(key) unless excluded_fields.include?(key)+ end+ end++ it 'associates the duplicated promotion with a batch' do+ expect(new_promotion.promotion_batch_id).to match promotion_batch.id+ end+ end++ context 'model associations - rules' do+ let(:excluded_fields) { ['promotion_id', 'id', 'created_at', 'updated_at', 'deleted_at'] }++ it 'copies all promotion rules' do+ expect(promotion.promotion_rules.size).to eq new_promotion.promotion_rules.size+ end++ it "promotion rule's fields (except promotion_id) are the same" do+ old_rule = promotion.promotion_rules.first+ new_rule = new_promotion.promotion_rules.first++ old_rule.attributes.each_key do |key|+ expect(old_rule.send(key)).to eq new_rule.send(key) unless excluded_fields.include?(key)+ end+ end++ it 'assigns a new promotion rule to new promotion' do+ expect(promotion.promotion_rules.first.promotion_id).not_to eq new_promotion.promotion_rules.first.promotion_id+ end+ end++ context 'model associations - actions' do+ let(:excluded_fields) { ['promotion_id', 'id', 'created_at', 'updated_at', 'deleted_at'] }++ it 'copies all promotion actions' do+ expect(promotion.promotion_actions.size).to eq new_promotion.promotion_actions.size+ end++ it 'copies promotion stores' do+ expect(promotion.store_ids).to eq new_promotion.store_ids+ end++ it "promotion action's fields (except promotion_id) are the same" do+ old_action = promotion.promotion_actions.first+ new_action = new_promotion.promotion_actions.first++ old_action.attributes.each_key do |key|+ expect(old_action.send(key)).to eq new_action.send(key) unless excluded_fields.include?(key)+ end+ end++ it 'assigns a new promotion action to new promotion' do+ expect(promotion.promotion_actions.first.promotion_id).not_to eq new_promotion.promotion_actions.first.promotion_id+ end+ end++ context "model associations - action's calculator" do+ let(:excluded_fields) { ['calculable_id', 'id', 'created_at', 'updated_at', 'deleted_at'] }++ it "copies promotion action's calculator" do+ new_calc = new_promotion.promotion_actions.first.calculator+ old_calc = promotion.promotion_actions.first.calculator++ new_calc.attributes.each_key do |key|+ expect(old_calc.send(key)).to eq new_calc.send(key) unless excluded_fields.include?(key)+ end+ end++ it 'assigns a new calculator to promotion action' do+ new_calc = new_promotion.promotion_actions.first.calculator+ old_calc = promotion.promotion_actions.first.calculator++ expect(old_calc.calculable_id).not_to eq new_calc.calculable_id+ end+ end+ end+enddiff --git a/core/spec/models/spree/promotion_handler/promotion_batch_update_handler_spec.rb b/core/spec/models/spree/promotion_handler/promotion_batch_update_handler_spec.rbnew file mode 100644index 0000000000..00d6bc7488--- /dev/null+++ b/core/spec/models/spree/promotion_handler/promotion_batch_update_handler_spec.rb@@ -0,0 +1,127 @@+require 'spec_helper'++describe Spree::PromotionHandler::PromotionBatchUpdateHandler do+ subject { described_class.new(promotion, promotion_batch.id, descendant_promotion) }++ let!(:promo_category) { create(:promotion_category) }+ let!(:calculator) { create(:calculator) }++ let(:store) { create(:store) }+ let(:store_2) { create(:store) }+ let!(:promotion) do+ create(:promotion_with_item_total_rule,+ description: 'Test description',+ expires_at: Date.current + 30,+ starts_at: Date.current,+ usage_limit: 100,+ match_policy: 'all',+ code: 'test1',+ advertise: true,+ path: 'test1',+ promotion_category: promo_category,+ stores: [store, store_2])+ end++ before do+ Spree::Promotion::Actions::CreateItemAdjustments.create!(calculator: calculator, promotion: promotion)+ end++ describe '#duplicate' do+ let(:new_promotion) { subject.duplicate }+ let(:promotion_batch) { create(:promotion_batch) }+ let(:descendant_promotion) { create(:promotion, code: descendant_code, path: descendant_path) }+ let(:descendant_code) { 'descendant_code' }+ let(:descendant_path) { 'descendant_path' }++ context 'model fields' do+ let(:excluded_fields) { ['code', 'path', 'id', 'created_at', 'updated_at', 'deleted_at', 'promotion_batch_id', 'usage_limit'] }++ it 'returns a duplicate of a promotion with all the fields (except the path, code and usage_limit fields) the same' do+ promotion.attributes.each_key do |key|+ expect(promotion.send(key)).to eq new_promotion.send(key) unless excluded_fields.include?(key)+ end+ end++ it 'assigns the descendant code and path to the new promotion' do+ expect(new_promotion.code).to match descendant_code+ expect(new_promotion.path).to match descendant_path+ end++ it 'destroys the descendant_promotion' do+ expect(descendant_promotion).to receive(:destroy!)++ new_promotion+ end++ it 'associates the new promotion with a batch' do+ expect(new_promotion.promotion_batch_id).to match promotion_batch.id+ end+ end++ context 'model associations - rules' do+ let(:excluded_fields) { ['promotion_id', 'id', 'created_at', 'updated_at', 'deleted_at'] }++ it 'copies all promotion rules' do+ expect(promotion.promotion_rules.size).to eq new_promotion.promotion_rules.size+ end++ it "promotion rule's fields (except promotion_id) are the same" do+ old_rule = promotion.promotion_rules.first+ new_rule = new_promotion.promotion_rules.first++ old_rule.attributes.each_key do |key|+ expect(old_rule.send(key)).to eq new_rule.send(key) unless excluded_fields.include?(key)+ end+ end++ it 'assigns a new promotion rule to new promotion' do+ expect(promotion.promotion_rules.first.promotion_id).not_to eq new_promotion.promotion_rules.first.promotion_id+ end+ end++ context 'model associations - actions' do+ let(:excluded_fields) { ['promotion_id', 'id', 'created_at', 'updated_at', 'deleted_at'] }++ it 'copies all promotion actions' do+ expect(promotion.promotion_actions.size).to eq new_promotion.promotion_actions.size+ end++ it 'copies promotion stores' do+ expect(promotion.store_ids).to eq new_promotion.store_ids+ end++ it "promotion action's fields (except promotion_id) are the same" do+ old_action = promotion.promotion_actions.first+ new_action = new_promotion.promotion_actions.first++ old_action.attributes.each_key do |key|+ expect(old_action.send(key)).to eq new_action.send(key) unless excluded_fields.include?(key)+ end+ end++ it 'assigns a new promotion action to new promotion' do+ expect(promotion.promotion_actions.first.promotion_id).not_to eq new_promotion.promotion_actions.first.promotion_id+ end+ end++ context "model associations - action's calculator" do+ let(:excluded_fields) { ['calculable_id', 'id', 'created_at', 'updated_at', 'deleted_at'] }++ it "copies promotion action's calculator" do+ new_calc = new_promotion.promotion_actions.first.calculator+ old_calc = promotion.promotion_actions.first.calculator++ new_calc.attributes.each_key do |key|+ expect(old_calc.send(key)).to eq new_calc.send(key) unless excluded_fields.include?(key)+ end+ end++ it 'assigns a new calculator to promotion action' do+ new_calc = new_promotion.promotion_actions.first.calculator+ old_calc = promotion.promotion_actions.first.calculator++ expect(old_calc.calculable_id).not_to eq new_calc.calculable_id+ end+ end+ end+enddiff --git a/core/spec/models/spree/promotion_handler/update_descendants_service_spec.rb b/core/spec/models/spree/promotion_handler/update_descendants_service_spec.rbnew file mode 100644index 0000000000..a95a527b3c--- /dev/null+++ b/core/spec/models/spree/promotion_handler/update_descendants_service_spec.rb@@ -0,0 +1,38 @@+require 'spec_helper'++describe Spree::PromotionHandler::UpdateDescendantsService do+ subject { described_class.new(template_promotion).call }++ let(:template_promotion) { create(:promotion) }+ let(:descendant_promotion) { create(:promotion, usage_limit: 1, promotion_batch_id: batch.id) }+ let(:batch) { create(:promotion_batch, template_promotion_id: template_promotion.id ) }++ context 'when the promotion is a template for a batch' do+ it 'enqueues a job' do+ expect(Spree::Promotions::HandleDescendantPromotionJob)+ .to receive(:perform_later)+ .with(+ template_promotion_id: template_promotion.id,+ descendant_promotion_id: descendant_promotion.id,+ promotion_batch_id: batch.id+ )++ subject+ end+ end++ context 'when the promotion is NOT a template for a batch' do+ before do+ allow(Spree::PromotionBatch)+ .to receive(:where)+ .with(template_promotion_id: template_promotion.id )+ .and_return([])+ end++ it 'does not enqueue a job' do+ expect(Spree::Promotions::HandleDescendantPromotionJob).not_to receive(:perform_later)++ subject+ end+ end+enddiff --git a/core/spec/models/spree/promotion_spec.rb b/core/spec/models/spree/promotion_spec.rbindex e41fba918d..e72785ff8d 100644--- a/core/spec/models/spree/promotion_spec.rb+++ b/core/spec/models/spree/promotion_spec.rb@@ -119,6 +119,22 @@ describe Spree::Promotion, type: :model doexpect(subject).to include(promotion_advertised)endend++ describe '.non_batched' do+ subject { described_class.non_batched }++ let!(:non_batched_promotion) { create :promotion, promotion_batch_id: nil }+ let!(:promotion_batch) { create :promotion_batch }+ let!(:batched_promotion) { create :promotion, promotion_batch_id: promotion_batch.id }++ it 'is expected to not include batched promotion' do+ expect(subject).not_to include(batched_promotion)+ end++ it 'is expected to include non_batched promotion' do+ expect(subject).to include(non_batched_promotion)+ end+ endenddescribe '#destroy' do@@ -727,4 +743,20 @@ describe Spree::Promotion, type: :model doendendend++ describe '#update_descendants' do+ let(:promotion) { create(:promotion) }+ let(:service) { instance_double(Spree::PromotionHandler::UpdateDescendantsService) }++ it 'calls the service' do+ expect(Spree::PromotionHandler::UpdateDescendantsService)+ .to receive(:new)+ .with(promotion)+ .and_return(service)+ expect(service)+ .to receive(:call)++ promotion.update(description: "anything")+ end+ endenddiff --git a/core/spec/services/spree/promotion_batches/batch_code_generator_spec.rb b/core/spec/services/spree/promotion_batches/batch_code_generator_spec.rbnew file mode 100644index 0000000000..f522bf6821--- /dev/null+++ b/core/spec/services/spree/promotion_batches/batch_code_generator_spec.rb@@ -0,0 +1,38 @@+require 'spec_helper'++module Spree+ describe PromotionBatches::BatchCodeGenerator do+ subject(:generate_batch_code) { described_class.build(batch_id, options) }++ let(:promotion) { build(:promotion, code: existing_code) }+ let(:promotion_batch) { build(:promotion_batch) }+ let(:code_generator) { instance_double(Promotions::CodeGenerator) }+ let(:existing_code) { "existing_code" }+ let(:new_code) { "new_code" }+ let(:options) { {key: 'value'} }+ let(:batch_id) { double }+++ before do+ allow(promotion_batch)+ .to receive(:id)+ .and_return(batch_id)+ allow(Spree::PromotionBatch)+ .to receive(:find)+ .and_return(promotion_batch)+ allow(promotion_batch)+ .to receive(:promotions)+ .and_return([promotion])+ allow(Promotions::CodeGenerator)+ .to receive(:new)+ .and_return(code_generator)+ allow(code_generator)+ .to receive(:build)+ .and_return(existing_code, new_code)+ end++ it 'returns new code' do+ expect(subject).to eq(new_code)+ end+ end+enddiff --git a/core/spec/services/spree/promotion_batches/destroy_spec.rb b/core/spec/services/spree/promotion_batches/destroy_spec.rbnew file mode 100644index 0000000000..d261f58a77--- /dev/null+++ b/core/spec/services/spree/promotion_batches/destroy_spec.rb@@ -0,0 +1,23 @@+require 'spec_helper'++module Spree+ describe PromotionBatches::Destroy do+ subject { described_class.call(promotion_batch: promotion_batch) }++ let(:promotion_batch) { create(:promotion_batch) }+ let(:promotion) { create(:promotion, promotion_batch_id: promotion_batch.id ) }+ let(:promotion2) { create(:promotion, promotion_batch_id: promotion_batch.id ) }++ before do+ promotion_batch+ promotion+ promotion2+ end++ it 'destroys the promotion batch with its promotions' do+ subject+ expect(Spree::Promotion.all).not_to include(promotion, promotion2)+ expect(Spree::PromotionBatch.all).not_to include(promotion_batch)+ end+ end+enddiff --git a/core/spec/services/spree/promotion_batches/promotion_codes_exporter_spec.rb b/core/spec/services/spree/promotion_batches/promotion_codes_exporter_spec.rbnew file mode 100644index 0000000000..28ae7b7cbb--- /dev/null+++ b/core/spec/services/spree/promotion_batches/promotion_codes_exporter_spec.rb@@ -0,0 +1,30 @@+require 'spec_helper'++module Spree+ describe PromotionBatches::PromotionCodesExporter do+ subject(:input) do+ described_class.new(params).call+ end++ let(:promotion_batch) { create(:promotion_batch) }+ let(:promotion) { create(:promotion, :with_unique_code, promotion_batch_id: promotion_batch.id ) }+ let(:promotion2) { create(:promotion, :with_unique_code, promotion_batch_id: promotion_batch.id ) }+ let(:params) { { id: promotion_batch.id } }++ let(:expected_codes_csv) do+ <<~CSV+ #{promotion.code}+ #{promotion2.code}+ CSV+ end++ before do+ promotion+ promotion2+ end++ it "generates correct csv file" do+ expect(input).to eq expected_codes_csv+ end+ end+enddiff --git a/core/spec/services/spree/promotion_batches/promotion_codes_importer_spec.rb b/core/spec/services/spree/promotion_batches/promotion_codes_importer_spec.rbnew file mode 100644index 0000000000..9494a7f8b3--- /dev/null+++ b/core/spec/services/spree/promotion_batches/promotion_codes_importer_spec.rb@@ -0,0 +1,78 @@+require 'spec_helper'++module Spree+ describe PromotionBatches::PromotionCodesImporter do+ subject(:import_promo_codes) do+ described_class.new(file: file, promotion_batch_id: promotion_batch.id).call+ end++ let(:promotion_batch) { build(:promotion_batch) }+ let(:code1) { 'cf14cec8' }+ let(:code2) { '4b2ff1a7' }+ let(:template_promotion_id) { double }+ let(:batch_id) { double }+ let(:content) do+ <<~CSV+ #{code1}+ #{code2}+ CSV+ end+ let(:file) { double }+ let(:content_type) { 'text/csv' }++ before do+ allow(file)+ .to receive(:content_type)+ .and_return(content_type)+ allow(file)+ .to receive(:read)+ .and_return(content)+ allow(Spree::PromotionBatch)+ .to receive(:find)+ .and_return(promotion_batch)+ allow(promotion_batch)+ .to receive(:template_promotion_id)+ .and_return(template_promotion_id)+ allow(promotion_batch)+ .to receive(:id)+ .and_return(batch_id)+ end++ context "when file is correct" do+ it "enqueues DuplicatePromotionJob jobs", sidekiq: :inline do+ expect(Spree::Promotions::DuplicatePromotionJob)+ .to receive(:perform_later)+ .with(template_promotion_id: template_promotion_id, batch_id: batch_id, code: code1)+ expect(Spree::Promotions::DuplicatePromotionJob)+ .to receive(:perform_later)+ .with(template_promotion_id: template_promotion_id, batch_id: batch_id, code: code2)++ import_promo_codes+ end+ end++ context "when file has wrong content type" do+ let(:content_type) { 'unallowable_type' }++ it "raises an error" do+ expect { import_promo_codes }.to raise_error Spree::PromotionBatches::PromotionCodesImporter::Error+ end+ end++ context "when file is empty" do+ let(:content) { "" }++ it "raises an error" do+ expect { import_promo_codes }.to raise_error Spree::PromotionBatches::PromotionCodesImporter::Error+ end+ end++ context "when there's no file" do+ let(:file) { nil }++ it "raises an error" do+ expect { import_promo_codes }.to raise_error Spree::PromotionBatches::PromotionCodesImporter::Error+ end+ end+ end+enddiff --git a/core/spec/services/spree/promotions/code_generator_spec.rb b/core/spec/services/spree/promotions/code_generator_spec.rbnew file mode 100644index 0000000000..3224792bad--- /dev/null+++ b/core/spec/services/spree/promotions/code_generator_spec.rb@@ -0,0 +1,85 @@+require 'spec_helper'++module Spree+ describe Promotions::CodeGenerator do+ describe "#build" do+ let(:random_code) { 'secure_random_code' }+ let(:content) { "black_week" }++ before do+ allow(SecureRandom).to receive(:hex).with(4).and_return(random_code)+ end++ context "prefix" do+ let(:affix) { :prefix }++ it "creates a code with a given prefix" do+ code = described_class.new(content: content, affix: affix).build+ expect(code).to eq content.concat(random_code)+ end+ end++ context "suffix" do+ let(:affix) { :suffix }++ it "creates a code with a given suffix" do+ code = described_class.new(content: content, affix: affix).build+ expect(code).to eq random_code.concat(content)+ end+ end++ context "deny-list" do+ let(:forbidden_phrases) { %w(forbidden phrase) }+ let(:deny_list) { forbidden_phrases }++ before do+ allow(SecureRandom)+ .to receive(:hex).with(4)+ .and_return("foo_#{forbidden_phrases.first}_bar", "foo_#{forbidden_phrases.last}_bar", random_code)+ end++ it "discards code containing forbidden phrases" do+ code = described_class.new(content: content, deny_list: deny_list).build+ expect(code).to eq random_code+ end+ end++ context "default" do+ it "creates a code" do+ code = described_class.new.build+ expect(code).to eq random_code+ end+ end++ context "forbidden phrases contain the affix" do+ let(:forbidden_phrases) { %w(black_week) }+ let(:deny_list) { forbidden_phrases }+ let(:affix) { :prefix }++ it "returns an error" do+ expect {+ described_class.new(content: content, affix: affix, deny_list: deny_list).build+ }.to raise_error Spree::Promotions::CodeGenerator::MutuallyExclusiveInputsError+ end+ end++ context "runs out of retries" do+ let(:forbidden_phrases) { (1..100).map(&:to_s) }+ let(:deny_list) { forbidden_phrases }+ let(:code_candidates) { forbidden_phrases }++ before do+ allow(SecureRandom)+ .to receive(:hex).with(4)+ .and_return(*code_candidates)+ end++ it "returns an error" do+ expect {+ described_class.new(deny_list: deny_list).build+ }.to raise_error Spree::Promotions::CodeGenerator::RetriesDepleted+ end+ end+ end+ end+enddiff --git a/core/spec/services/spree/promotions/populate_promotion_batch_spec.rb b/core/spec/services/spree/promotions/populate_promotion_batch_spec.rbnew file mode 100644index 0000000000..8dda6856ef--- /dev/null+++ b/core/spec/services/spree/promotions/populate_promotion_batch_spec.rb@@ -0,0 +1,49 @@+require 'spec_helper'++module Spree+ describe Promotions::PopulatePromotionBatch do+ describe "#call" do+ subject(:populate_promotion_batch) { described_class.new(batch_id, options).call }++ let(:batch_id) { double }+ let(:options) { {batch_size: 3} }+ let(:promotion_batch) { build(:promotion_batch) }+ let(:template_promotion_id) { double }++ before do+ allow(Spree::PromotionBatch)+ .to receive(:find)+ .and_return(promotion_batch)+ allow(promotion_batch)+ .to receive(:template_promotion_id)+ .and_return(template_promotion_id)+ allow(Spree::Promotions::DuplicatePromotionJob)+ .to receive(:perform_later)+ .with(options)+ end++ context "when PromotionBatch has a template assigned" do+ it "enqueues DuplicatePromotionJob jobs", sidekiq: :inline do+ expect(Spree::Promotions::DuplicatePromotionJob)+ .to receive(:perform_later)+ .at_least(options[:batch_size]).times+ .with(template_promotion_id: template_promotion_id, batch_id: batch_id, options: {})++ populate_promotion_batch+ end+ end++ context "when PromotionBatch hasn't a template assigned" do+ before do+ allow(promotion_batch)+ .to receive(:template_promotion_id)+ .and_return(nil)+ end++ it "raises an error" do+ expect { populate_promotion_batch }.to raise_error Spree::Promotions::PopulatePromotionBatch::TemplateNotFoundError+ end+ end+ end+ end+end