Skip to content

Instantly share code, notes, and snippets.

@pepsin
Last active March 17, 2017 08:57
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pepsin/e26bce1e8820483bf6e0b384a20a00a8 to your computer and use it in GitHub Desktop.
Save pepsin/e26bce1e8820483bf6e0b384a20a00a8 to your computer and use it in GitHub Desktop.
Simple CMB CSV Merger and Organizer script
#If you don't have colorize gem, do install it via 'gem install colorize'
#Update
#Add cache categories function
require 'csv'
require 'readline'
require 'colorize'
require 'json'
CACHED_CATEGORIES_FILE = "cache_categories.json"
cache_categories = JSON.parse(File.open(CACHED_CATEGORIES_FILE).read) rescue {}
CATEGORIES = {
'H' => "Hobby",
"E" => "Eat",
"O" => "Outing",
"G" => "Game & App",
"S" => "Service",
"L" => "Life",
"T" => "Transportation",
"B" => "Book",
"C" => "Clothes",
"X" => "Electronics",
"W" => "Workout",
"R" => "Return"
}
def beatiful_print_categories
str = ""
index = 0
CATEGORIES.each_pair do |k, v|
index += 1
str += "#{k.to_s.underline}:#{v} "
if index % 5 == 0
str += "\n"
end
end
str.strip.yellow
end
def ask_input(prompt="", newline=true)
prompt += "\n" if newline
input = Readline.readline(prompt, true).squeeze(" ").strip.upcase
if CATEGORIES[input].nil?
input = ask_input prompt, newline
end
input
end
NAME_INDEX = 3
COST_INDEX = 5
input_file = ARGV[0]
file = File.open(input_file).read
rows = CSV.parse(file)
dict = {}
rows[1..-1].each do |row|
name = row[NAME_INDEX].strip
cost = row[COST_INDEX].gsub(/[^\d\-\.]/, "").to_f
if dict[name]
dict[name][0] += cost
else
puts "#{name}: #{cost}".green
category_key = cache_categories.keys.select do |ca|
name.include?(ca)
end
category = cache_categories[category_key.first]
category = nil if (category == 0)
if category.nil?
category = ask_input(beatiful_print_categories)
cache_categories[name] = category
end
dict[name] = [0, 0]
dict[name][0] = cost
dict[name][1] = category
end
end
File.open(CACHED_CATEGORIES_FILE, "w+").write(JSON.pretty_generate(cache_categories))
output_file = "merged_" + input_file.split(".").first
CSV.open("#{output_file}.csv", "wb") do |csv|
csv << ["Name", "Cost", "Category"]
total = 0
outcome = 0
categories_outcome = {}
CATEGORIES.invert.keys.each {|k| categories_outcome[k] = 0}
dict.keys.each do |key|
number = dict[key][0].ceil
category = CATEGORIES[dict[key][1]]
total += number
if number > 0
outcome += number
end
if categories_outcome[category].nil?
categories_outcome[category] = 0
end
categories_outcome[category] += number
csv << [key, number, category]
end
categories_outcome.keys.each do |key|
csv << [key, categories_outcome[key], ""]
end
csv << ["Outcome", outcome.floor, ""]
csv << ["Total", total.floor, ""]
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment