Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Generate Gift Card Based on CSV

Purpose

This script generates gift card vouchers for users from a CSV source file. It outputs two files:

  • valid.csv: successfully created vouchers
  • invalid.csv: rows that failed validation or user lookup

Prerequisites

  • Rails environment loaded
  • CSV stdlib available
  • Input file exists at /tmp/compensation.csv

Expected CSV columns

  • Comp Method (for example GF100)
  • email

Execution

rails c --production
# paste and run script

Script

require 'csv'

user_not_founds = []
valid = []
invalid = []

expiry_date = Date.today + 1.year
today = Date.today
payment_types = PaymentType.all

ActiveRecord::Base.transaction do
  CSV.foreach('/tmp/compensation.csv', headers: true) do |row|
    name = row['Comp Method'].to_s
    next unless name.include?('GF')

    email = row['email']
    user = User.find_by(email: email)

    if user.blank?
      user_not_founds << email
      invalid << row
      next
    end

    amount = name.gsub('GF', '').to_i

    voucher = Voucher.new(
      user_id: user.id,
      voucher_type: 'specific_customer',
      name: name,
      amount_cents: amount * 100,
      amount_currency: 'THB',
      max_usage: 1,
      expiry_date: expiry_date,
      quota: 1,
      expiry_type: 'range',
      expiry_range_by: 'created_at',
      start_date: today,
      end_date: expiry_date,
      subsidized_by: 'hungryhub',
      apply_for: 'package',
      usage_type: 'one_time',
      discount_type: 'amount',
      active: true,
      sun_active: true,
      mon_active: true,
      tue_active: true,
      wed_active: true,
      thu_active: true,
      fri_active: true,
      sat_active: true,
      for_web: true,
      for_ios: true,
      for_android: true,
      non_refundable: true,
      require_full_prepayment: true,
      amount_cap_cents: 0,
      amount_cap_currency: 'THB',
      voucher_code: Voucher.generate_voucher_code
    )

    if voucher.valid?
      voucher.save!
      payment_types.each { |pt| voucher.payment_types << pt }
      valid << voucher
    else
      invalid << row
    end
  end
end

File.open('/tmp/valid.csv', 'w') do |f|
  headers = %w[id user_id email voucher_code name amount_cents amount_currency start_date end_date]
  f.puts(headers.to_csv)

  valid.each do |v|
    f.puts([
      v.id,
      v.user_id,
      v.user&.email,
      v.voucher_code,
      v.name,
      v.amount_cents,
      v.amount_currency,
      v.start_date,
      v.end_date
    ].to_csv)
  end
end

File.open('/tmp/invalid.csv', 'w') do |f|
  f.puts('Comp Method,email')
  invalid.each do |row|
    f.puts([row['Comp Method'], row['email']].to_csv)
  end
end

puts "User not found: #{user_not_founds.join(', ')}"