#
# 仕切り価格 コントローラー
#-------------------------------------------------------------------------------
#
class WholesaleApprovalsController < Comm::BaseController::PermanentMaster
  include Comm::Module::Controller::Table
  #== コンストラクタ
  #-----------------------------------------------------------------#++
  def initialize
    @mcls = WholesaleApproval
  end
  
  #== テーブル表示
  def table
    #製品ID
    product_ids = ProductSet.find(:all, :conditions => "invalid_flag_code = #{MCODE_FLAG_OFF}").map{|ar| ar.id}
    #役職ID
    rank_ids = Rank.find(:all, :conditions => "invalid_flag_code = #{MCODE_FLAG_OFF}").map{|ar| ar.id}
    #テーブル作成
    result_hash = create_table(rank_ids, product_ids, 'rank_id', 'product_set_id', '製品クラス')
    
    respond_to do |format|
      format.ext_json{
        render :json => result_hash.to_json 
      }
      format.xls{
        resp = output_xls(result_hash[@table_name], params)
        resp[:file_name] = @table_name + resp[:file_name]
        render :json => resp.to_json
      }
    end
  end
  
  #関連配列の判断(_override)
  def is_concern(cid, rid)
    @user_rank ||= User.find(session[:user_id]).rank_id
    return (is_user_sales() and cid == @user_rank) ? true : false
  end
  #取得カラムの判定(_override)
  def get_data_column(ar)
    return ar ? ar.amount : nil
  end
  
  #== テーブル更新
  def in_transaction()
    res_array = JSON.parse(params[:rules])
    res_array.each do |r|
      cond = r.dup
      amount = cond.delete('amount')
      ar = @mcls.find(:first, :conditions => cond)
      if ar
        #更新
        ar.amount = amount
        ar.save!
      else
        #新規
        ar = @mcls.new({'invalid_flag_code' => 0}.merge(r))
        ar.save!
      end
    end
  end
  
end
