class Manufacture < CommLogistics::Base::Model::SuperiorOrder
  include Comm::Module::Model::Logging
  #has_many :order_details, :dependent => :destroy
  has_many :child_details,
           :class_name => 'ManufactureDetail',
           :dependent => :destroy,
           :order => 'seq_number'
  has_many :purchases
  belongs_to :supplier
  
  #関連進捗率の100％となる本数を計算
  def self.set_stock_and_rels_total_quantity(table_params, details)
    super
    table_params['rels_total_quantity'] = table_params['stock_total_quantity'].to_i + table_params['manufacture_product_total_quantity']
  end
  
  def self.get_all_rels(id)
    ar = find_by_id(id)
    #受注/発注のtotal_quantityを求める。
    total_quantity = ar.total_quantity.to_i
    #非在庫品を除いた合計本数を求める。
    stock_total_quantity = ar.stock_total_quantity.to_i
    #mpdの合計本数
    manufacture_product_total_quantity = ar.manufacture_product_total_quantity.to_i
    #受注/発注
    table_name = self.name.tableize
    #受注区分／発注区分／加工区分
    parent_trans_type_code = ar[self.name.tableize.singularize + '_type_code']
    #関連処理
    rels = Rel.find_by_sql(["SELECT 
                              r.table_name, 
                              r.record_id, 
                              #{total_quantity} AS total_quantity, 
                              #{stock_total_quantity} AS stock_total_quantity, 
                              #{manufacture_product_total_quantity} AS manufacture_product_total_quantity, 
                              #{parent_trans_type_code} AS parent_trans_type_code
                             FROM rels AS r 
                             LEFT JOIN purchases AS p ON r.table_name='purchases' AND r.record_id=p.id
                             WHERE r.parent_table_name='#{table_name}' AND r.parent_record_id=#{id}
                             ORDER BY r.table_name, p.purchase_type_code, r.record_id "])
    return rels
  end
end
