Skip to content

Instantly share code, notes, and snippets.

@ROFISH
Created June 13, 2012 21:38
Show Gist options
  • Save ROFISH/2926625 to your computer and use it in GitHub Desktop.
Save ROFISH/2926625 to your computer and use it in GitHub Desktop.
Coupons limiting to Collection ID
# http://forums.shopify.com/categories/6/posts/42926
# This is a fairly simple mechanize script to create a few hundred or so shopify discounts from a CSV of groupon codes.
# You'll want to change all of the "changeme" values to your own.
# The script expects there to be a groupon_codes.csv in the same directory.
#
# The groupons_code.csv should look like this:
# 8m7677
# 8m6749
# 8m5398
# 8m7699
# 8m8885
# 8m788
# etc.
require 'rubygems'
require 'mechanize'
require 'csv'
BASE_URL = 'https://XXXXXXX.myshopify.com/admin'
LOGIN_PATH = '/auth/login'
USER = 'XXXXXXXXXXX'
PASSWORD = 'XXXXXXXXXXXX'
DISCOUNT = "20"
@agent = Mechanize.new
@groupon_codes = []
def login
page = @agent.get(BASE_URL + LOGIN_PATH)
form = page.forms.first
form.login = USER
form.password = PASSWORD
@agent.submit(page.forms.first)
end
def load_codes
#@groupon_codes = CSV.read("groupon_codes.csv").flatten
@groupon_codes = []
allowed_chars = %w(A C D E H J K L M N P T V W X Y 3 4 6 7 9)
5000.times do
unique_chars = allowed_chars.dup
s = "RCR-ISUPPORTINDIEGAMES-"
10.times do
char = unique_chars[rand(unique_chars.length)]
s << unique_chars.delete(char)
end
@groupon_codes << s
raise "duplicated code generated" if @groupon_codes != @groupon_codes.uniq
end
end
def create_discount(page, code)
puts "Create discount for code: #{code}..."
# You may want to have some error handling in case you have connection issues. Worked fine for me with 500+ codes though.
begin
page.form_with(:action => "#{BASE_URL}/discounts") do |f|
f['discount[code]'] = code
f["discount[usage_limit]"] = '1'
#f[""] = 'Collection'
f["type"] = "percentage"
#f["discount[applies_to_id]"] = "7051722"
#f["applies_to_product"] = "76668552"
#f["applies_to_collection"] = "504322"
#f["applies_to_customer_group"] = "1122452"
#p f.fields_with(:name => 'discount_[value]').length
# Set both the visible and hidden textfield to ensure the value gets sent
discount_value_fields = f.fields_with(:id => 'discount_value')
discount_value_fields.each do |textfield|
textfield.value = DISCOUNT
end
f.fields_with(:name=>'discount[applies_to_id]').each do |textfield|
textfield.value = "7051722"
end
f.fields_with(:name=>'discount[applies_to_type]').each do |textfield|
textfield.value = "Collection"
end
end.click_button
$file.write "#{code}\n"
rescue
STDERR.print "Failed to save code: #{code}"
end
end
load_codes
login
#p @groupon_codes
$file = File.open("rcr_codes.txt","w")
begin
@agent.get(BASE_URL + '/marketing') do |page|
@groupon_codes.each do |code|
create_discount(page, code)
end
end
ensure
$file.close
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment