Skip to content

Commit

Permalink
Merge pull request solidusio#2578 from jhawthorn/promotion_batch_fix_…
Browse files Browse the repository at this point in the history
…2577

Generate correct number of codes in BatchBuilder
  • Loading branch information
jhawthorn authored Feb 16, 2018
2 parents 6970c32 + c905158 commit 5bebfdf
Showing 1 changed file with 12 additions and 17 deletions.
29 changes: 12 additions & 17 deletions core/app/models/spree/promotion_code/batch_builder.rb
Original file line number Diff line number Diff line change
Expand Up @@ -26,27 +26,22 @@ def build_promotion_codes
private

def generate_random_codes
total_batches = (number_of_codes.to_f / self.class.batch_size).ceil
created_codes = 0

total_batches.times do |i|
codes_for_current_batch = Set.new
codes_to_generate = [self.class.batch_size, number_of_codes - i * batch_size].min
while created_codes < number_of_codes
max_codes_to_generate = [self.class.batch_size, number_of_codes - created_codes].min

while codes_for_current_batch.size < codes_to_generate
new_codes = Array.new(codes_to_generate) { generate_random_code }.to_set
codes_for_current_batch += get_unique_codes(new_codes)
end
new_codes = Array.new(max_codes_to_generate) { generate_random_code }.uniq
codes_for_current_batch = get_unique_codes(new_codes)

codes_for_current_batch.map do |value|
promotion.codes.build(value: value, promotion_code_batch: promotion_code_batch)
codes_for_current_batch.each do |value|
Spree::PromotionCode.create!(
value: value,
promotion: promotion,
promotion_code_batch: promotion_code_batch
)
end

promotion.save!

# We have to reload the promotion because otherwise all promotion codes
# we are creating will remain in memory. Doing a reload will remove all
# codes from memory.
promotion.reload
created_codes += codes_for_current_batch.size
end
end

Expand Down

0 comments on commit 5bebfdf

Please sign in to comment.