#
#= user_positions モデル
# Authors:: Sumiyo Yamamoto
# Copyright:: Copyright (C) OrbusNeich Medical K.K.  2010.
#--
# date        name                   note
# 2010.2.26   Sumiyo Yamamoto        新規登録
#-------------------------------------------------------------------------------
#++
class UserPosition < Comm::BaseModel::PermanentMaster
  belongs_to :section

  #== named_scope
  #-----------------------------------------------------------------#++
  named_scope :possort, :order => 'position_number'
  
  named_scope :sales, lambda{
    sale_sections = Section.sales.set(MFIND_V).select_id.all.extract('id')
    if sale_sections.empty?
      {:conditions => '1 = 0'}
    else
      {:conditions => "section_id IN (#{sale_sections.join(',')})"}
    end
  }
  
  named_scope :user_is, lambda{ |id| {
    :conditions => ["user_id = ?", id.to_i]
  }}
  named_scope :position_number_is, lambda{ |id| {
    :conditions => ["position_number = ?", id.to_i]
  }}
  
  def validate
    ars = UserPosition.disp_name_is(self.disp_name).valid.id_is_not(self.id)
    record_num = ars.length
    if record_num > 0
       ids = ars.collect{|ar| ar.id}
       emsg = ''
       emsg << EMJ0005
       emsg << "指定の表示名のユーザポジションは既に登録されています。"
       emsg << "ID:"+ids.inspect
       raise UserOperationError, emsg
    end
#    ars = UserPosition.user_is(self.user_id).position_number_is(self.position_number).valid.id_is_not(self.id)
#    record_num = ars.length
#    if record_num > 0
#       ids = ars.collect{|ar| ar.id}
#       emsg = ''
#       emsg << EMJ0005
#       emsg << "該当ユーザに指定のポジション番号は既に登録されています。"
#       emsg << "ID:"+ids.inspect
#       raise UserOperationError, emsg
#    end
  end
  
  def validate_on_create
    require 'config/site_config'
    #ユーザ数の制限
    $POSITION_NUM_PER_USER ||= 0 #0だったら無制限
    if $POSITION_NUM_PER_USER > 0
      ars = UserPosition.valid.user_is(self.user_id)
      record_num = ars.length
      if record_num >= $POSITION_NUM_PER_USER
        emsg = ''
        emsg << EMJ0005
        emsg << ["1ユーザ当たりのユーザーポジション数（",$POSITION_NUM_PER_USER.to_s,"）を超えて登録はできません。"].join
        emsg << "新規ユーザポジション登録の前に登録済みユーザポジションを消してください。"
        raise UserOperationError, emsg
      end
    end
  end
  
  #== ユーザーポジションが所属するグルーピング部署取得
  # 引数で指定されたユーザーポジションが所属する、グルーピングレベルの部署を取得する。
  #_upid_:: ユーザーポジションID
  #
  # 戻り値:: 部署(ActiveRecord)
  #-----------------------------------------------------------------#++
  def group_section
    result = nil
    
    # 部署検索
    section = Section.find(self.section_id)
    
    # グルーピングレベルの部署を取得
    result = section.group
    
    return result
  end

  #== 営業部判定処理
  # 戻り値:: true/false
  #-----------------------------------------------------------------#++
  def sales_section?
    section = Section.find(section_id)
    return section.sales_flag_code == Comm::Const::MasterCode::MCODE_FLAG_ON ? true : false
  end
end
