#
#= customer_groupsコントローラー
# Authors:: Sumiyo Yamamoto
# Copyright:: Copyright (C) OrbusNeich Medical K.K.  2010.
#--
# date        name                   note
# 2010.11.5   Sumiyo Yamamoto        新規作成
#-------------------------------------------------------------------------------
#++
class CustomerGroupsController < Comm::BaseController::PermanentMaster
  include Comm::Module::Controller::UnifiedIF
  #== コンストラクタ
  #-----------------------------------------------------------------#++
  def initialize
    @mcls = CustomerGroup
    @search_cls = CustomerGroupSearch
  end
  
  def find_all
    ss = CustomerGroupSearch.new
    ss.table_alias = {'customer_groups' => 'a',
                      'customer_group_payments' => 'a'}
    return ss.search(FLAG_ON, CustomerGroup, [], params)
  end
  
  class CustomerGroupSearch < Comm::Tool::SqlSearch
    def get_columns_and_tables(tab, join_lists, params, str_vals)
      invalid_vals = (!params || params[:with_invalid]==STR_TRUE) ? '0,1' : '0'
      str_cols = ' * '
      str_tab =  " FROM ( SELECT cg.*, 
                                 cgp.payment_type_code, 
                                 cgp.payment_month_code, 
                                 cgp.payment_date_code, 
                                 cgp.encach_month_code, 
                                 cgp.encach_date_code,
                                 IFNULL(cgp.payment_cnt,0) AS payment_conditions_cnt
                          FROM master_app_production.customer_groups AS cg 
                          LEFT JOIN (SELECT *, COUNT(*) AS payment_cnt 
                                     FROM ( SELECT * FROM master_app_production.customer_group_payments 
                                            ORDER BY payment_condition_code) AS tmp 
                                            GROUP BY customer_group_id) AS cgp ON cgp.customer_group_id=cg.id
                          WHERE cg.invalid_flag_code in (#{invalid_vals})) AS a"
      return str_cols, str_tab, str_vals
    end
  end
  
  # show 関連
  def add_to_extra_table_columns(merge_h, result)
    arrange_result(merge_h, result, CustomerGroupPayment)
    merge_h['payment_conditions_cnt'] = result['payment_conditions_cnt']
  end
  
  def get_show_where_clause
    int_id = params[:id].to_i
    case int_id
    when -1
      condition = " (SELECT min(id) FROM customer_groups) "
    when -2
      condition = " (SELECT max(id) FROM customer_groups) "
    else
      condition = int_id.to_s
    end
    return "WHERE a.id = "+condition
  end
end