#
#= 製品単価
#== DB
#* product_id  製品ID
#* target_date 対象日付
#* price       単価
#
class ProductsPrice < CommLogistics::Base::Model::LogisticsModel
  require 'bigdecimal'
  #== 単価レコード取得
  #[product_id] 製品ID
  #[target_date] 対象日付
  def self.one(product_id, target_date)
    result = find_by_sql(["SELECT * FROM products_prices 
                           WHERE target_date = ? AND product_id = ? LIMIT 1",
                           target_date, product_id])
    logger.debug(["products_price one", result.first.inspect].join("\n\t"))
    return result.first
  end
  
  #== 最新単価レコード取得
  #[product_id] 製品ID
  #[target_date] 対象日付
  def self.last_one(product_id, target_date, include_target_date=false)
    compare = include_target_date ? " <= " : " < "
    result = find_by_sql(["SELECT price FROM products_prices
                           WHERE (target_date #{compare} ? OR target_date IS NULL) AND product_id = ?
                           ORDER BY target_date DESC
                           LIMIT 1",
                           target_date, product_id])
    logger.debug(["products_price last_one", result.first.inspect].join("\n\t"))
    return result.first
  end
  
  #== 記録が必要かどうか
  # purchaseでも単価レコードを記録しない場合は
  # falseを返すと他の取引のような扱い(記録なしの更新のみ)になる
  def self.need_recording?(opts)
    true
  end
  
  def get_last_date(target_date)
    return convert_to_date(target_date, true)
  end
  
  def convert_to_date(target_date, need_last_date=false)
    if target_date.is_a?(Date)
      td = target_date
    else
      td = Date.parse(target_date)
    end
    if need_last_date
      td = td - 1
    end
    return td
  end
end