module CommLogistics::Tools
  #
  #= 在庫数取得
  #
  class StockCounter
    include CommLogistics::Const::Code
    
    #== 在庫数取得
    #* 引数
    #  [target_date] 対象日付
    #  [product_id] 製品ID
    #  [supplier_id] 在庫主ID（省略時は自社）
    #* 返り値
    #  [Hash] supplierオーナー総在庫数
    #
    def self.get_quantity(target_date, product_id, supplier_id=OWN_SUPPLIER_ID )
      params = {:target_date => target_date, :product_ids => product_id, :supplier_ids => supplier_id, :show_all => true }
      ars = self.stock_search(params)
      if ars.blank? || ars.length > 1
        return 0
      else
        return ars[0].quantity.to_i
      end
    end
    #== 複数在庫数取得
    #* 引数
    #  [target_date] 対象日付
    #  [product_ids] 製品ID配列
    #  supplier_id 在庫主ID
    #* 返り値
    #  [Hash] {製品ID=>supplierオーナーの総在庫数}
    #
    def self.get_quantities(target_date, product_ids, supplier_id=OWN_SUPPLIER_ID)
      params = {:target_date => target_date, :product_ids => product_ids.join(','), :supplier_ids => supplier_id, :show_all => true }
      ars = self.stock_search(params) || []
      results = Hash.new
      product_ids.each do |value|
        results.store(value, 0)
      end
      ars.each do |record|
        results.store(record.product_id.to_i, record.quantity.to_i)
      end
      return results
    end
    
    #== 在庫数計算
    def self.stock_search(params)
      ss = CommLogistics::Tools::ProductsStocksSearch.new
      ars = ss.search(params)
      return ars;
    end
  end
end