namespace :spree_tools do
desc "Generate random coupon codes in bulk."
task :generate_coupons => :environment do
puts "How many codes would you like to generate?"
number_of_codes = STDIN.gets.strip.to_i
puts "\nHow much would you like this discount to be for?"
amount = STDIN.gets.strip.to_f
puts "\nWhat product should this promotion apply for? (use product name)"
product_name = STDIN.gets.strip.to_s
puts "\nWhat would you like to name this sequence of promotion codes?"
puts 'Example: "Groupon" would produce "Groupon 1", "Groupon 2", etc.'
sequence = STDIN.gets.strip.to_s
n = 1
number_of_codes.times do
code = generate_unique_code
promo = Spree::Promotion.create(
name: "#{sequence} #{n}",
event_name: 'spree.checkout.coupon_code_added',
match_policy: 'all',
starts_at: DateTime.yesterday,
usage_limit: 1,
code: code
)
promo.promotion_actions << Spree::Promotion::Actions::CreateAdjustment.create(
calculator: Spree::Calculator::FlatRate.new(preferred_amount: amount)
)
promo.promotion_rules.create(type: 'Spree::Promotion::Rules::Product')
promo.promotion_rules.last.products << Spree::Product.find_by(name: product_name)
File.open('codes.csv', 'a') do |f|
f << "#{code}, "
end
n += 1
end
end
def generate_unique_code
begin
code = SecureRandom.hex(6)
end while Spree::Promotion.exists?(code: code)
code
end
end