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

Rails: Pull Vouchers into CSV

Purpose

This script reads a compensation CSV, finds users by email, and appends matched voucher IDs to a new CSV. It also exports rows where users are not found.

Prerequisites

  • Rails environment loaded
  • Input CSV at /tmp/compensation.csv
  • Expected columns: Comp Method, email

Output files

  • /tmp/new_comp.csv: original rows + voucher ids column
  • /tmp/not_found.csv: rows where users were not found

Notes

  • Voucher filter uses id >= 484000. Adjust this threshold if needed.

Script

require 'csv'

user_not_founds = []
new_csv = []

CSV.foreach('/tmp/compensation.csv', headers: true) do |row|
  name = row['Comp Method'].to_s

  if new_csv.blank?
    headers = row.headers
    headers.push('voucher ids')
    new_csv << headers.to_csv
  end

  next unless name.include?('GF')

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

  if user.blank?
    user_not_founds << row
    next
  end

  body = row.to_h.values

  vouchers = Voucher.where('id >= ?', 484000).where(user_id: user.id).where('name LIKE ?', 'GF%')
  body << vouchers.pluck(:id).map(&:to_s).join(', ') if vouchers.present?
  new_csv << body.to_csv
end

File.open('/tmp/new_comp.csv', 'w') { |f| f.write(new_csv.join('')) }

File.open('/tmp/not_found.csv', 'w') do |f|
  data = user_not_founds.map { |row| row.to_h.values.to_csv }.join('')
  f.write(data)
end

puts "Not found count: #{user_not_founds.size}"