#!/usr/bin/env ruby require 'date' require "rawbotz" require 'optparse' options = {config: RawgentoModels::CONF_FILE} optparse = OptionParser.new do |opts| opts.banner = "Usage: #{$PROGRAM_NAME} [OPTIONS]" opts.separator "" opts.separator "RawgentoDB configuration file (MySQL options)" opts.on("-c", "--config FILE", 'file path to rawgento-db YAML config file.') do |c| if !File.exist? c STDERR.puts "Cannot load conf file #{c}" exit 2 end options[:config] = c end opts.on("-f", "--fake VALUE", 'Fake value. If quantity is higher than 0.9*VALUE, subtract VALUE.') do |f| options[:fake_value] = f end opts.separator "" opts.separator "Output options" opts.on("-v", "--verbose", 'print debug output (WARNING: including PASSWORD)') do |v| $stdout.sync = true options[:verbose] = true end opts.separator "" opts.separator "General" opts.on_tail('--version', 'Show version.') do puts "#{$PROGRAM_NAME} #{Rawbotz::VERSION}" exit 0 end opts.on('-h', '--help', 'Show this help.') do puts opts exit 0 end end optparse.parse! include RawgentoModels def main options logger = Logger.new(STDOUT) logger.level = options[:verbose] ? Logger::DEBUG : Logger::INFO logger.debug "#{$PROGRAM_NAME} #{Rawbotz::VERSION}" if !File.exist? options[:config] logger.warn "Cannot load conf file #{options[:config]}" exit 2 end RawgentoModels.establish_connection options[:config] begin result = RawgentoDB::Query.stock(RawgentoDB.settings(options[:config])) rescue Mysql2::Error => e logger.error "Problems accessing MySQL database #{e.inspect}" exit 2 end now = DateTime.now logger.info("Starting stock update") result.each do |s| product = RawgentoModels::LocalProduct.find_by(product_id: s.product_id) if product.nil? logger.info("No such product #{s.product_id}") else qty = s.qty if options[:fake_value].to_i > 0 && options[:fake_value].to_i * 0.9 < s.qty.to_i qty = qty - options[:fake_value].to_i logger.info("Fake value (#{options[:fake_value]}) applies for product_id #{product.product_id}: #{s.qty}") end product.stock_items.create(qty: qty, date: now) logger.info("Updated stock for #{s.product_id}") end end logger.info("Finished with stock update") end main options