Class: EducodeSales::PlansController

Inherits:
ApplicationController show all
Defined in:
app/controllers/educode_sales/plans_controller.rb

Instance Method Summary collapse

Methods inherited from ApplicationController

#authenticate_admin, #authenticate_request, #current_user, #filter, #is_commissioner_above?, #paginate, #render_failure, #render_success, #subject_members, #subject_staffs, #subject_url

Methods included from ApplicationHelper

#add_businesses_score, #base_url, #collection_amount_score, #completion_rate, #current?, #disk_filename, #get_businesses_chart, #handled_data, #handled_time_data, #handled_time_data_accurate, #relative_path, #signed_amount_score, #storage_path, #url_to_avatar, #visits_score

Instance Method Details

#add_year_targetObject



673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
# File 'app/controllers/educode_sales/plans_controller.rb', line 673

def add_year_target
  history = EducodeSales::SalesTargetHistory.find_by(staff_id: params[:staff_id], year: params[:year], school_tag_id: params[:school_tag_id], target_clazz: params[:target_clazz])
  # history.update_attributes(params.permit(:m_target_1, :m_target_2, :m_target_3, :m_target_4, :m_target_5, :m_target_6, :m_target_7, :m_target_8, :m_target_9, :m_target_10, :m_target_11, :m_target_12)) if history
  # 不能重复添加
  #if EducodeSales::SalesTargetHistory.exists?(staff_id: params[:staff_id], year: params[:year], school_tag_id: params[:school_tag_id], target_clazz: params[:target_clazz])
  #  return render_failure "不能重复添加"
  #end
  target = EducodeSales::SalesTargetHistory.new(year_target_param)
  if history
    use_old_attributes = %w[m_target_1 m_target_2 m_target_3 m_target_4 m_target_5 m_target_6 m_target_7 m_target_8 m_target_9 m_target_10 m_target_11 m_target_12] - params.keys
    use_old_attributes.each do |attr|
      target[attr] = history[attr]
    end
  end
  if history
    target.num = history.num
  else
    target.num = EducodeSales::SalesTargetHistory.maximum(:id).to_i + 1
  end

  target.creator_id = @current_admin.id
  target.state = '待审核'
  if target.save
    render json: { id: target.id, state: target.state, updated_at: target.updated_at.to_s(:date) }
  else
    render_failure target
  end
end

#audit_staff_year_targetObject



771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
# File 'app/controllers/educode_sales/plans_controller.rb', line 771

def audit_staff_year_target
  target = EducodeSales::SalesTarget.find(params[:id])
  if target.state == '待审核'
    target.state = params[:state]
    target.comment = params[:comment]
    target.reviewer_id = @current_admin.id
    if target.save
      create_target_operation_log(target.attributes.dup)
      p
      render json: {id: target.id, comment: target.comment, reviewer: @current_admin.user&.real_name, state: target.state, updated_at: target.updated_at.to_s(:date)}
    else
      render_failure target
    end
  else
    render json: {success: false, msg: '该状态不能编辑'}
  end
end

#business_infosObject



450
451
452
453
454
455
456
457
458
459
# File 'app/controllers/educode_sales/plans_controller.rb', line 450

def business_infos
  @data = @current_admin.business_infos.where(sale_plan_id: nil, year: params[:year])

  if params[:sort].present? && params[:sort][:field]
    @data = @data.order("#{params[:sort][:field]} #{params[:sort][:order]}")
  else
    @data = @data.order("created_at desc")
  end
  @data = @data.page(params[:page]).per(params[:limit])
end

#cal_finish_amountObject



629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
# File 'app/controllers/educode_sales/plans_controller.rb', line 629

def cal_finish_amount
  start_at = params[:year] + "-01-01"
  end_at = params[:year] + "-12-31"
  amount = 0
  case  params[:target_clazz]
  when "回款"
    # 对应销售经理下回款时间的回款金额
    amount = EducodeSales::MoneyPlanRecord.joins("
        LEFT JOIN educode_sales_follow_ups AS last_follow_up ON educode_sales_businesses.last_follow_up_id = last_follow_up.id AND last_follow_up.deleted_at IS NULL
        LEFT JOIN educode_sales_assign_follow_ups ON educode_sales_assign_follow_ups.follow_up_id = last_follow_up.id").
      joins(business: [department: [school: :school_tags]]).where("school_tags.id = ?", params[:school_tag_id]).
      where("(educode_sales_assign_follow_ups.id IS NOT NULL AND educode_sales_assign_follow_ups.staff_id = ?) OR (educode_sales_assign_follow_ups.id IS NULL AND educode_sales_businesses.staff_id = ?)", params[:staff_id], params[:staff_id]).
      where("date_at >= ? AND date_at <= ?", start_at, end_at).sum("amount")

  when '商机'
    a_clazz = EducodeSales::Common.find_by(extras: 'a_class')
    start_at = "#{params[:year]}-01-01 00:00:01"
    end_at = "#{params[:year]}-12-31 23:59:59"
    staff_id =  params[:staff_id]
    # 对应销售经理下A类商机预算金额
    amount = EducodeSales::Business.from("(
      SELECT distinct educode_sales_businesses.id, last_follow_up.budget_amount, educode_sales_businesses.deleted_at, educode_sales_businesses.department_id
      FROM educode_sales_businesses
      JOIN educode_sales_follow_ups ON educode_sales_follow_ups.business_id = educode_sales_businesses.id AND educode_sales_businesses.clazz_id = #{a_clazz.id}
           AND educode_sales_follow_ups.created_at > '#{start_at}' AND educode_sales_follow_ups.created_at < '#{end_at}'
      JOIN educode_sales_follow_ups AS last_follow_up ON educode_sales_businesses.last_follow_up_id = last_follow_up.id AND last_follow_up.deleted_at IS NULL AND last_follow_up.clazz_id = #{a_clazz.id}
      LEFT JOIN educode_sales_assign_follow_ups ON educode_sales_assign_follow_ups.follow_up_id = last_follow_up.id
      WHERE (educode_sales_assign_follow_ups.id IS NOT NULL AND educode_sales_assign_follow_ups.staff_id = '#{staff_id}') OR (educode_sales_assign_follow_ups.id IS NULL AND educode_sales_businesses.staff_id = '#{staff_id}')
      ) AS educode_sales_businesses
    ").joins(department: [school: :school_tags]).where("school_tags.id = ?", params[:school_tag_id]).sum(:budget_amount)
  when '中标'
    # 对应销售经理下合同列表的中标时间下合同金额
    contract_ids = EducodeSales::Common.where(clazz: '商机阶段', name: ['已中标', '已签单', '已验收', '回款中', '服务中', '已结束']).pluck(:id)
    businesses = EducodeSales::Business.joins("
      JOIN educode_sales_follow_ups ON educode_sales_businesses.last_follow_up_id = educode_sales_follow_ups.id
    ").joins("LEFT JOIN educode_sales_assign_follow_ups ON educode_sales_assign_follow_ups.follow_up_id = educode_sales_businesses.last_follow_up_id").
      joins(department: [school: :school_tags]).where("school_tags.id = ?", params[:school_tag_id]).
      where("(educode_sales_assign_follow_ups.id IS NOT NULL AND educode_sales_assign_follow_ups.staff_id = ?) OR (educode_sales_assign_follow_ups.id IS NULL AND educode_sales_businesses.staff_id = ?)", params[:staff_id], params[:staff_id]).
      where("educode_sales_follow_ups.stage_id in (?)", contract_ids).
      where("educode_sales_follow_ups.bidded_date >= ? AND educode_sales_follow_ups.bidded_date <= ?", start_at, end_at).sum(:actual_amount)
  end
  render json: {amount: amount}
end

#createObject



68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
# File 'app/controllers/educode_sales/plans_controller.rb', line 68

def create
  if params["year"].present?
    business = Business.find_by(id: params[:business_id])
    plan = @current_admin.sale_plans.build(year: params[:year], business_id: business.id, clazz: params[:clazz], common_id: params[:common_id] )
    if params[:assign_id].present?
      plan.staff_id = params[:assign_id]
      plan.assign_id = @current_admin.id
    end
    if plan.save
      render_success
    else
      render_failure plan
    end
  else
    plan = @current_admin.sale_plans.build(plan_params)
    plan.month = params["month"] + "-1"
    plan.business = Business.find_by(id: params[:business_id])

    if params[:assign_id].present?
      plan.staff_id = params[:assign_id]
      plan.assign_id = @current_admin.id
    end
    if plan.save
      render_success
    else
      render_failure plan
    end
  end

end

#create_business_infoObject



99
100
101
102
103
104
105
106
107
# File 'app/controllers/educode_sales/plans_controller.rb', line 99

def create_business_info
  business = Business.find_by(id: params[:business_id])
  info = @current_admin.business_infos.find_or_initialize_by(year: params[:year], business_id: business.id, clazz: params[:clazz])
  if info.save
    render_success
  else
    render_failure info
  end
end

#create_sales_planObject



514
515
516
517
518
519
520
# File 'app/controllers/educode_sales/plans_controller.rb', line 514

def create_sales_plan
  @current_admin.business_infos.where(sale_plan_id: nil).each do |d|
    plan = @current_admin.sale_plans.create(year: d.year, business_id: d.business_id, clazz: d.clazz)
    d.update(sale_plan_id: plan.id)
  end
  render_success
end

#delete_business_infoObject



522
523
524
525
# File 'app/controllers/educode_sales/plans_controller.rb', line 522

def delete_business_info
  @current_admin.business_infos.where(id: params[:id]).destroy_all
  render_success
end

#destroyObject



274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
# File 'app/controllers/educode_sales/plans_controller.rb', line 274

def destroy
  if params[:year].present?
    # 删除年度计划
    sale_plans = SalePlan.where(year: params[:year], clazz: EducodeSales::SalePlan::CLAZZ_NAME[params[:clazz]])
    sale_plans.each do |d|
      EducodeSales::Recycle.create(source: d, deleter_id: @current_admin.id)
    end
    sale_plans.update_all(deleted_at: Time.now)
    sale_plans.business_infos.delete_all
    render_success
  else
    sale_plan = SalePlan.find(params[:id])
    if sale_plan.soft_destroy(@current_admin.id)
      render_success
    else
      render_failure sale_plan
    end
  end
end

#edit_bussiness_infoObject



461
462
463
464
# File 'app/controllers/educode_sales/plans_controller.rb', line 461

def edit_bussiness_info
  @business_info = @current_admin.business_infos.find(params[:id])
  render layout: false
end

#edit_bussiness_info_extraObject



466
467
468
469
# File 'app/controllers/educode_sales/plans_controller.rb', line 466

def edit_bussiness_info_extra
  @business_info = EducodeSales::BusinessInfo.find(params[:id])
  render layout: false
end

#edit_monthObject



298
299
300
301
302
303
304
305
306
307
# File 'app/controllers/educode_sales/plans_controller.rb', line 298

def edit_month
  @commons = Common.where(clazz: '计划类型').pluck(:name, :id)
  business_ids = EducodeSales::AssignFollowUp.joins(:follow_up).where(staff_id: @current_admin.id).pluck :business_id
  @businesses = Business.includes(:department, :last_follow_up).where("educode_sales_businesses.id in (?) or educode_sales_businesses.staff_id = ?", business_ids, @current_admin.id).order(created_at: :desc)
  @businesses = @businesses.map { |b| [b.name + "(" + b.department&.school&.name.to_s + ")" + "---" + "最新跟进:" + (b.last_follow_up.present? ? b.last_follow_up.created_at.to_s : b.created_at.to_s), b.id] }
  @sale_plan = SalePlan.find(params[:id])
  @finish_rates = []
  11.times { |d| @finish_rates << ["#{d*10}%", d * 10]}
  render layout: false
end

#edit_monthlyObject



309
310
311
# File 'app/controllers/educode_sales/plans_controller.rb', line 309

def edit_monthly
  render layout: false
end

#edit_weekObject



228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
# File 'app/controllers/educode_sales/plans_controller.rb', line 228

def edit_week
  @commons = Common.where(clazz: '计划类型').pluck(:name, :id)
  business_ids = EducodeSales::AssignFollowUp.joins(:follow_up).where(staff_id: @current_admin.id).pluck :business_id
  @sale_plan = SalePlan.find(params[:id])
  # 加入指派的商机id
  business_ids << @sale_plan.business_id
  @businesses = Business.includes(:department, :last_follow_up).where("educode_sales_businesses.id in (?) or educode_sales_businesses.staff_id = ?", business_ids, @current_admin.id).order(created_at: :desc)
  @businesses = @businesses.map { |b| [b.name + "(" + b.department&.school&.name.to_s + ")" + "---" + "最新跟进:" + (b.last_follow_up.present? ? b.last_follow_up.created_at.to_s : b.created_at.to_s), b.id] }

  if @sale_plan.weekly.present?
    week = Time.now.strftime('%W').to_i
    if week > 3
      @weeks = [week+2, week+1, week, week - 1, week - 2]
    elsif week == 2
      @weeks = [week, week - 1]
    else
      @weeks = [week]
    end
    @weeks << @sale_plan.weekly
    @weeks = @weeks.uniq.sort
    @weeks = @weeks.map do |d|
      if d == week
        ["#{d}  本周", d]
      else
        [d, d]
      end
    end
  end
  @months = [Time.now.strftime("%Y-%m"), Time.now.months_ago(1).strftime("%Y-%m")]
  @months << @sale_plan.month.strftime("%Y-%m")
  @months = @months.uniq.sort
  @finish_rates = []
  11.times { |d| @finish_rates << ["#{d * 10}%", d * 10] }
  render layout: false
end

#edit_weeklyObject



294
295
296
# File 'app/controllers/educode_sales/plans_controller.rb', line 294

def edit_weekly
  render layout: false
end

#edit_year_planObject



527
528
529
530
# File 'app/controllers/educode_sales/plans_controller.rb', line 527

def edit_year_plan
  @clazz = EducodeSales::SalePlan::CLAZZ_NAME
  render layout: false
end

#indexObject



6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# File 'app/controllers/educode_sales/plans_controller.rb', line 6

def index
  # authorize! :read, SalePlan
  respond_to do |format|
    format.html do
      common = Common.find_by(clazz: 'staff_type', name: '销售')
      @staffs = Staff.includes(:user).where(job_type: common.id).map { |d| [d.user.real_name, d.id] }
      @years = (1..(Time.now.year - 2020)).map { |d| 2020 + d }
      @months = (1..12).map { |d| d }
    end
    format.json do
      if @current_admin.is_admin?
        @sale_plans = SalePlan
      else
        level = @current_admin.role.role_areas.find_by(clazz: '销售计划').level
        case level
        when '自己'
          @sale_plans = SalePlan.where(staff_id: @current_admin.id)
        when '区域'
          staff_ids = Staff.joins(user: [user_extension: [department: :school]]).where("schools.province in (?)", @current_admin.areas.pluck(:name)).pluck(:id)

          school_ids = StaffSchool.where(staff_id: @current_admin.id).pluck(:school_id)
          if @current_admin.staff_school_tags.present?
            # 如果设置专项客户类型,则视为专项经理,根据专项客户查看对应商机
            school_ids += School.joins(:school_tags).where("school_tags.id in (?)", @current_admin.staff_school_tags.pluck(:school_tag_id)).pluck(:id)
          end

          business_ids = Business.where(school_id: school_ids.uniq).pluck(:id)
          @sale_plans = SalePlan.where("staff_id in (?) OR educode_sales_sale_plans.staff_id = ? OR educode_sales_sale_plans.business_id in (?)", staff_ids, @current_admin.id,business_ids)
        else
          @sale_plans = SalePlan
        end
      end
      if params[:clazz] == 'week'
        @sale_plans = @sale_plans.where.not(weekly: nil).where.not(month: nil)
      elsif params[:clazz] == 'month'
        @sale_plans = @sale_plans.where(weekly: nil).where.not(month: nil)
      end
      if params[:q].present? && params[:q][:staff_id].present?
        @sale_plans = @sale_plans.where(staff_id: params[:q][:staff_id])
      end
      # p "#{params[:q][:year]}-01-01 00:00:00".to_date, "#{params[:q][:year]}-12-31 23:59:00".to_date
      if params[:q].present? && params[:q][:year].present?
        @sale_plans = @sale_plans.where("month >= ? and month <= ?", "#{params[:q][:year]}-01-01 00:00:00".to_date, "#{params[:q][:year]}-12-31 23:59:00".to_date)
      end
      if params[:q].present? && params[:q][:month].present?
        @sale_plans = @sale_plans.where("month = ?", "#{params[:q][:month]}-01 00:00:00".to_date)
      end
      if params[:sort].present? && params[:sort][:field]
        @sale_plans = @sale_plans.order("#{params[:sort][:field]} #{params[:sort][:order]}")
      else
        @sale_plans = @sale_plans.order("created_at desc")
      end

      @sale_plans = @sale_plans.page(params[:page]).per(params[:limit])
    end
  end
end

#month_planObject



553
554
555
556
557
558
# File 'app/controllers/educode_sales/plans_controller.rb', line 553

def month_plan
  common = Common.find_by(clazz: 'staff_type', name: '销售')
  @staffs = Staff.includes(:user).where(job_type: common.id).map { |d| [d.user.real_name, d.id] }
  @years = (1..(Time.now.year - 2020)).map { |d| 2020 + d }
  @months = (1..12).map { |d| d }
end

#monthlyObject



546
547
548
549
550
551
# File 'app/controllers/educode_sales/plans_controller.rb', line 546

def monthly
  common = Common.find_by(clazz: 'staff_type', name: '销售')
  @staffs = Staff.includes(:user).where(job_type: common.id).map { |d| [d.user.real_name, d.id] }
  @years = (1..(Time.now.year - 2020)).map { |d| 2020 + d }
  @months = (1..12).map { |d| d }
end

#my_monthObject



323
324
325
326
327
328
329
330
331
# File 'app/controllers/educode_sales/plans_controller.rb', line 323

def my_month
  @sale_plans = SalePlan.where(staff_id: @current_admin.id, month: Time.now.strftime("%Y-%m") + "-01 00:00:00", weekly: nil)
  if  params[:sort].present? && params[:sort][:field]
    @sale_plans = @sale_plans.order("#{params[:sort][:field]} #{params[:sort][:order]}")
  else
    @sale_plans = @sale_plans.order("updated_at desc")
  end
  @sale_plans =  @sale_plans.page(params[:page]).per(params[:limit])
end

#my_weekObject



313
314
315
316
317
318
319
320
321
# File 'app/controllers/educode_sales/plans_controller.rb', line 313

def my_week
  @sale_plans = SalePlan.where(staff_id: @current_admin.id, month: Time.now.strftime("%Y-%m") + "-01 00:00:00", weekly: Time.now.strftime('%W').to_i)
  if  params[:sort].present? && params[:sort][:field]
    @sale_plans = @sale_plans.order("#{params[:sort][:field]} #{params[:sort][:order]}")
  else
    @sale_plans = @sale_plans.order("updated_at desc")
  end
  @sale_plans =  @sale_plans.page(params[:page]).per(params[:limit])
end

#my_years_planObject



446
447
448
# File 'app/controllers/educode_sales/plans_controller.rb', line 446

def my_years_plan
  @sale_plans = SalePlan.where(staff_id: @current_admin.id)
end

#newObject



64
65
66
# File 'app/controllers/educode_sales/plans_controller.rb', line 64

def new
  render layout: false
end

#new_monthObject



152
153
154
155
156
157
158
159
160
161
162
# File 'app/controllers/educode_sales/plans_controller.rb', line 152

def new_month
  @commons = Common.where(clazz: '计划类型').pluck(:name, :id)
  common = Common.find_by(clazz: 'staff_type', name: '销售')
  @staffs = Staff.includes(:user).where(job_type: common.id).map { |d| [d.user.real_name, d.id] }

  @business = Business.find_by(id: params[:business_id])
  business_ids = EducodeSales::AssignFollowUp.joins(:follow_up).where(staff_id: @current_admin.id).pluck :business_id
  @businesses =Business.includes(:department, :last_follow_up).where("educode_sales_businesses.id in (?) or educode_sales_businesses.staff_id = ?", business_ids, @current_admin.id).order(created_at: :desc)
  @businesses = @businesses.map { |b| [b.name + "(#{b.department&.school&.name} #{b.department&.name})" + "---" + "最新跟进:" + (b.last_follow_up.present? ? b.last_follow_up.created_at.to_s : b.created_at.to_s), b.id] }
  render layout: false
end

#new_monthlyObject



190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
# File 'app/controllers/educode_sales/plans_controller.rb', line 190

def new_monthly
  d = @current_admin
  area_ids = EducodeSales::Common.where(clazz: 'area').ids.sort.to_s
  if d.areas.present?
    if d.areas.ids.sort.to_s == area_ids
      @area = '全国'
    else
      @area =  d.areas.pluck(:name).join("")
    end
  else
    @area =  ''
  end
  @name = @current_admin.user.real_name
  sale_plans = SalePlan.where(month: Time.now.strftime("%Y-%m") + "-01 00:00:00", staff_id: @current_admin.id, weekly: nil)
  @rate = sale_plans.present? ? (sale_plans.sum("finish_rate") / sale_plans.size) : 0
  @departments_count = sale_plans.joins(:business).count("distinct(department_id)")
  @total_amount = sale_plans.joins(business: :last_follow_up).distinct.sum("total_amount")
  render layout: false
end

#new_weekObject



110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
# File 'app/controllers/educode_sales/plans_controller.rb', line 110

def new_week
  @business = Business.find_by(id: params[:business_id])
  common = Common.find_by(clazz: 'staff_type', name: '销售')
  @staffs = Staff.includes(:user).where(job_type: common.id).map { |d| [d.user.real_name, d.id] }


  @week = Time.now.strftime('%W').to_i
  week = Time.now.strftime('%W').to_i
  if week > 3
    @weeks = [[week+2,week+2], [week+1,week+1], [week.to_s + '  本周',week], [week - 1,week - 1], [week - 2,week - 2]]
  elsif week == 2
    @weeks = [[week.to_s + '  本周',week], [week - 1,week - 1]]
  else
    @weeks = [[week.to_s + '  本周',week]]
  end
  @commons = Common.where(clazz: '计划类型').pluck(:name, :id)
  business_ids = EducodeSales::AssignFollowUp.joins(:follow_up).where(staff_id: @current_admin.id).pluck :business_id
  @businesses = Business.includes(:department, :last_follow_up).where("educode_sales_businesses.id in (?) or educode_sales_businesses.staff_id = ?", business_ids, @current_admin.id).order(created_at: :desc)
  @businesses = @businesses.map { |b| [b.name + "(#{b.department&.school&.name} #{b.department&.name})" + "---" + "最新跟进:" + (b.last_follow_up.present? ? b.last_follow_up.created_at.to_s : b.created_at.to_s), b.id] }
  render layout: false
end

#new_weeklyObject



132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
# File 'app/controllers/educode_sales/plans_controller.rb', line 132

def new_weekly
  d = @current_admin
  area_ids = EducodeSales::Common.where(clazz: 'area').ids.sort.to_s
  if d.areas.present?
    if d.areas.ids.sort.to_s == area_ids
      @area = '全国'
    else
      @area =  d.areas.pluck(:name).join("")
    end
  else
    @area =  ''
  end
  @name = @current_admin.user.real_name
  sale_plans = SalePlan.where(month: Time.now.strftime("%Y-%m") + "-01 00:00:00", weekly: Time.now.strftime('%W').to_i, staff_id: @current_admin.id)
  @rate = sale_plans.present? ? (sale_plans.sum("finish_rate") / sale_plans.size) : 0
  @departments_count = sale_plans.joins(:business).count("distinct(department_id)")
  @total_amount = sale_plans.joins(business: :last_follow_up).distinct.sum("total_amount")
  render layout: false
end

#new_yearObject



164
165
166
167
168
169
170
171
# File 'app/controllers/educode_sales/plans_controller.rb', line 164

def new_year
  @business = Business.find_by(id: params[:business_id])
  business_ids = EducodeSales::AssignFollowUp.joins(:follow_up).where(staff_id: @current_admin.id).pluck :business_id
  @businesses =Business.includes(:department, :last_follow_up).where("educode_sales_businesses.id in (?) or educode_sales_businesses.staff_id = ?", business_ids, @current_admin.id).order(created_at: :desc)
  @businesses = @businesses.map { |b| [ b.name + "(#{b.department&.school&.name} #{b.department&.name})" + "---" + "最新跟进:" + (b.last_follow_up.present? ? b.last_follow_up.created_at.to_s : b.created_at.to_s), b.id] }
  @clazz = EducodeSales::SalePlan::CLAZZ_NAME
  render layout: false
end

#plan_business_infosObject



471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
# File 'app/controllers/educode_sales/plans_controller.rb', line 471

def plan_business_infos
  if params[:q] && params[:q][:year_search].present?
    @data = EducodeSales::BusinessInfo.where(year: params[:q][:year_search], staff_id: params[:staff_id])
  else
    @data = EducodeSales::BusinessInfo.where(year: params[:year], staff_id: params[:staff_id])
  end

  @data = @data.where.not(sale_plan_id: nil)

  if params[:q] && params[:q][:clazz].present?
    @data = @data.where(clazz: params[:q][:clazz])
  end

  if params[:q] && params[:q][:department].present?
    @data = @data.joins(business: [department: :school]).where("schools.name like ?", "%#{params[:q][:department]}%")
  end

  if params[:sort].present? && params[:sort][:field]
    @data = @data.order("#{params[:sort][:field]} #{params[:sort][:order]}")
  else
    @data = @data.order("created_at desc")
  end
  @data = @data.page(params[:page]).per(params[:limit])
end

#save_staff_year_targetObject



745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
# File 'app/controllers/educode_sales/plans_controller.rb', line 745

def save_staff_year_target
  unless params[:id].present?
    history = EducodeSales::SalesTarget.find_by(staff_id: params[:staff_id], year: params[:year], school_tag_id: params[:school_tag_id], target_clazz: params[:target_clazz])
    # 不能重复添加
    unless history.nil?
      return render_failure "同类型数据已存在,无法添加"
    end
    target = EducodeSales::SalesTarget.new(year_target_param)
  else
    target = EducodeSales::SalesTarget.find(params[:id])
    if target.nil?
      return render_failure "数据不存在,无法编辑"
    end
    target.update_attributes(year_target_param)
  end

  target.creator_id = @current_admin.id
  target.state = '待审核'
  if target.save
    create_target_operation_log(target.attributes.dup)
    render json: { id: target.id, state: target.state, updated_at: target.updated_at.to_s(:date) }
  else
    render_failure target
  end
end

#show_monthObject



219
220
221
222
# File 'app/controllers/educode_sales/plans_controller.rb', line 219

def show_month
  @sale_plan = SalePlan.find(params[:id])
  render layout: false
end

#show_monthlyObject



224
225
226
# File 'app/controllers/educode_sales/plans_controller.rb', line 224

def show_monthly
  render layout: false
end

#show_weekObject



210
211
212
213
# File 'app/controllers/educode_sales/plans_controller.rb', line 210

def show_week
  @sale_plan = SalePlan.find(params[:id])
  render layout: false
end

#show_weeklyObject



215
216
217
# File 'app/controllers/educode_sales/plans_controller.rb', line 215

def show_weekly
  render layout: false
end

#staff_businessesObject

暂时不用



174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
# File 'app/controllers/educode_sales/plans_controller.rb', line 174

def staff_businesses
  if params[:q].present?
    business_ids = EducodeSales::AssignFollowUp.joins(:follow_up).where(staff_id: @current_admin.id).pluck :business_id
    @businesses = Business.includes(:department, :last_follow_up).where("educode_sales_businesses.id in (?) or educode_sales_businesses.staff_id = ?", business_ids, @current_admin.id)
    if params[:q].present?
      @businesses =  @businesses.where("educode_sales_businesses.name like ?", "%#{params[:q]}%")
    else
      @businesses =  @businesses.limit(10)
    end
    @businesses =  @businesses.order(created_at: :desc)

    @businesses = @businesses.map { |b| {name: b.name + "(#{b.department&.school&.name} #{b.department&.name})" + "---" + "最新跟进:" + (b.last_follow_up.present? ? b.last_follow_up.created_at.to_s : b.created_at.to_s), value: b.id} }
    render json: { data: @businesses, code: 0, msg: "success" }
  end
end

#staff_year_businessObject



800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
# File 'app/controllers/educode_sales/plans_controller.rb', line 800

def staff_year_business
  respond_to do |format|
    format.html do
      @staff_id = (params[:staff_id].blank? || params[:staff_id] == 'null') ? nil : params[:staff_id]
      @year = params[:year].present? ? params[:year].to_i : Date.today.year.to_i
      @target_clazz = params[:target_clazz].present? ? params[:target_clazz] : '中标'
      @type = params[:type]
      @school_tag_id = params[:school_tag_id]
      render layout: false
    end
    format.json do
      staff_id = (params[:staff_id].blank? || params[:staff_id] == 'null') ? nil : params[:staff_id]
      staffs = get_sales_staffs_by_id(staff_id)
      if staffs.nil?
        return render json: {success: false, msg: '无此数据或权限不足'}
      end
      @year = params[:year].present? ? params[:year].to_i : Date.today.year.to_i
      month = params[:month].present? ? params[:month].to_i : nil
      @target_clazz = params[:target_clazz].present? ? params[:target_clazz] : '中标'
      school_tag_id = params[:school_tag_id].present? && params[:school_tag_id]!='0' ? params[:school_tag_id] : nil
      type = params[:type].present? ? params[:type] : 'plan'

      if month.present? && month != 0
        first_day = Date.new(@year, month, 1)
        last_day = Date.new(@year, month, -1)
      else
        first_day = Date.new(@year, 1, 1)
        last_day = Date.new(@year, 12, -1)
      end
      
      #staffs = get_sales_staffs_by_id(staff_id)
      staff_ids = staffs.pluck(:id).compact.join(',')
      follow_up_ids = get_follow_up_id(staff_ids)
      if follow_up_ids.empty?
        return
      end
      school_where = ''
      unless follow_up_ids.empty?
        ##查出哪些学校既属于本科又属于军事院校
        school_ids = EducodeSales::MoneyPlanRecord.from(
          "(SELECT TM1.school_id
      FROM school_tag_middles AS TM1
      LEFT JOIN school_tag_middles AS TM2
      ON TM1.school_id = TM2.school_id AND TM1.school_tag_id=1 AND TM2.school_tag_id=10
      WHERE TM1.school_tag_id IS NOT NULL AND TM2.school_tag_id IS NOT NULL AND TM1.school_id IN (
        SELECT school_id FROM educode_sales_businesses WHERE last_follow_up_id in (#{follow_up_ids})
      )) AS school"
        ).pluck(:school_id).join(',')
        unless school_ids.empty?
          school_where = " AND (TM.school_id in (#{school_ids}) AND TM.school_tag_id = 10 OR TM.school_id not in (#{school_ids}))"
        end
      end
      follow_up_ids_where = follow_up_ids.present? ? " AND B.last_follow_up_id in (#{follow_up_ids})" : " AND B.id in(0)"
      if type == 'plan'
        case @target_clazz
        when '中标'
          @data = get_staff_bidden_plan(follow_up_ids_where, school_where, first_day, last_day, school_tag_id)
        when '回款'
          @data = get_staff_money_plan(follow_up_ids_where, school_where, first_day, last_day, school_tag_id)
        when '商机'
          @data = get_staff_business_plan(follow_up_ids_where, school_where, first_day, last_day, school_tag_id)
        else
          # type code here
        end
      else
        case @target_clazz
        when '中标'
          @data = get_staff_bidden_finish(follow_up_ids_where, school_where, first_day, last_day, school_tag_id)
        when '回款'
          @data = get_staff_money_finish(follow_up_ids_where, school_where, first_day, last_day, school_tag_id)
        when '商机'
          @data = get_staff_business_finish(follow_up_ids_where, school_where, first_day, last_day, school_tag_id)
        else
        end
      end
      @data = @data.page(params[:page]).per(params[:limit])
    end
  end
end

#staff_year_targetObject



702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
# File 'app/controllers/educode_sales/plans_controller.rb', line 702

def staff_year_target
  respond_to do |format|
    format.html do
    end
    format.js do
      @staffs = get_sales_staffs_by_id().map { |d| [d.user.real_name, d.id] }
      gon.school_tags = SchoolTag.where(for_missions: true).map { |d| {value: d.id, name: d.name } }
      gon.month = Time.now.month
    end
    format.json do
      if @current_admin.is_admin?
        @data = EducodeSales::SalesTarget.all
      else
        level = @current_admin.role.role_areas.find_by(clazz: '销售计划').level
        case level
        when '自己'
          @data = EducodeSales::SalesTarget.where(staff_id: @current_admin.id)
        when '区域'
          @data = EducodeSales::SalesTarget.all
          staff_ids = Staff.joins(user: [user_extension: [department: :school]]).where("schools.province in (?)", @current_admin.areas.pluck(:name)).pluck(:id)
          @data = @data.where(staff_id: staff_ids)
        else
          @data = EducodeSales::SalesTarget.all
        end
      end
      @data = @data.order("staff_id asc,field(state, 1,2,0), id desc")
      if params[:year].present?
        @data = @data.where(year: params[:year])
      end
      if params[:school_tag_id].present?
        @data = @data.where(school_tag_id: params[:school_tag_id])
      end
      if params[:staff_id].present?
        @data = @data.where(staff_id: params[:staff_id])
      end
      if params[:target_clazz].present?
        @data = @data.where(target_clazz: params[:target_clazz])
      end
      @data = @data.page(params[:page]).per(params[:limit])
    end
  end
end

#staff_year_target_logObject



789
790
791
792
793
794
795
796
797
798
# File 'app/controllers/educode_sales/plans_controller.rb', line 789

def staff_year_target_log
  @data = EducodeSales::SalesTargetLog.where(target_id: params[:target_id]).order('id desc').page(params[:page]).per(params[:limit])
  respond_to do |format|
    format.html do
      render layout: false
    end
    format.json do
    end
  end
end

#updateObject



264
265
266
267
268
269
270
271
272
# File 'app/controllers/educode_sales/plans_controller.rb', line 264

def update
  sale_plan = SalePlan.find(params[:id])
  params["month"] = params["month"] + "-1"
  if sale_plan.update(plan_params)
    render_success
  else
    render_failure sale_plan
  end
end

#update_business_infoObject



496
497
498
499
500
501
502
503
# File 'app/controllers/educode_sales/plans_controller.rb', line 496

def update_business_info
  business_info = @current_admin.business_infos.find(params[:id])
  if business_info.update(business_info_params)
    render_success
  else
    render_failure business_info
  end
end

#update_business_info_extraObject



505
506
507
508
509
510
511
512
# File 'app/controllers/educode_sales/plans_controller.rb', line 505

def update_business_info_extra
  business_info = EducodeSales::BusinessInfo.find(params[:id])
  if business_info.update(update_business_info_extra_params)
    render_success
  else
    render_failure business_info
  end
end

#week_planObject



532
533
534
535
536
537
# File 'app/controllers/educode_sales/plans_controller.rb', line 532

def week_plan
  common = Common.find_by(clazz: 'staff_type', name: '销售')
  @staffs = Staff.includes(:user).where(job_type: common.id).map { |d| [d.user.real_name, d.id] }
  @years = (1..(Time.now.year - 2020)).map { |d| 2020 + d }
  @months = (1..12).map { |d| d }
end

#weeklyObject



539
540
541
542
543
544
# File 'app/controllers/educode_sales/plans_controller.rb', line 539

def weekly
  common = Common.find_by(clazz: 'staff_type', name: '销售')
  @staffs = Staff.includes(:user).where(job_type: common.id).map { |d| [d.user.real_name, d.id] }
  @years = (1..(Time.now.year - 2020)).map { |d| 2020 + d }
  @months = (1..12).map { |d| d }
end

#year_executeObject



568
569
570
571
572
573
574
575
576
577
578
579
580
# File 'app/controllers/educode_sales/plans_controller.rb', line 568

def year_execute
  respond_to do |format|
    format.html do
      @staffs = get_sales_staffs_by_id().map { |d| [d.user.real_name, d.id] }
      gon.school_tags = SchoolTag.where(for_missions: true).map { |d| {value: d.id, name: d.name } }
    end
    format.js do
      @staffs = get_sales_staffs_by_id().map { |d| [d.user.real_name, d.id] }
      gon.school_tags = SchoolTag.where(for_missions: true).map { |d| {value: d.id, name: d.name } }
      gon.school_tags.unshift({value: 0, name: '全部类型'})
    end
  end
end

#year_planObject



560
561
562
563
564
565
# File 'app/controllers/educode_sales/plans_controller.rb', line 560

def year_plan
  common = Common.find_by(clazz: 'staff_type', name: '销售')
  @staffs = Staff.includes(:user).where(job_type: common.id).map { |d| [d.user.real_name, d.id] }
  @years = (1..(Time.now.year - 2020)).map { |d| 2020 + d }
  @months = (1..12).map { |d| d }
end

#year_targetObject



582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
# File 'app/controllers/educode_sales/plans_controller.rb', line 582

def year_target
  respond_to do |format|
    format.html do
    end
    format.js do
      @staffs = get_sales_staffs_by_id().map { |d| [d.user.real_name, d.id] }
      gon.school_tags = SchoolTag.where(for_missions: true).map { |d| {value: d.id, name: d.name } }
      gon.school_tags.unshift({value: 0, name: '全部类型'})
      gon.month = Time.now.month
    end
    format.json do
      if @current_admin.is_admin?
        @data = EducodeSales::SalesTargetHistory.all
      else
        level = @current_admin.role.role_areas.find_by(clazz: '销售计划').level
        case level
        when '自己'
          @data = EducodeSales::SalesTargetHistory.where(staff_id: @current_admin.id)
        when '区域'
          @data = EducodeSales::SalesTargetHistory.all
          staff_ids = Staff.joins(user: [user_extension: [department: :school]]).where("schools.province in (?)", @current_admin.areas.pluck(:name)).pluck(:id)
          @data = @data.where(staff_id: staff_ids)
        else
          @data = EducodeSales::SalesTargetHistory.all
        end
      end
      @data = @data.order("staff_id asc,num desc, is_use desc,field(state, 1,0,2), id desc")
      if params[:year].present?
        @data = @data.where(year: params[:year])
      end
      if params[:school_tag_id].present?
        @data = @data.where(school_tag_id: params[:school_tag_id])
      end
      if params[:staff_id].present?
        @data = @data.where(staff_id: params[:staff_id])
      end
      if params[:year_target].present?
        @data = @data.where(year_target: params[:year_target])
      end
      if params[:target_clazz].present?
        @data = @data.where(target_clazz: params[:target_clazz])
      end
      @data = @data.page(params[:page]).per(params[:limit])
    end
  end
end

#years_all_targetObject



392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
# File 'app/controllers/educode_sales/plans_controller.rb', line 392

def years_all_target
  #目标类别
  target_clazz = params[:target_clazz]
  #年份
  year = params[:year].present? ? params[:year].to_i : Date.today.year.to_i
  type = params[:type] || 'staff'
  #员工id
  staff_id = params[:staff_id].present? ? params[:staff_id] : nil
  #客户类型
  school_tag_id = params[:school_tag_id]

  staffs = get_sales_staffs_by_id(staff_id, params[:page], params[:limit])
  if staffs.nil?
    return render json: {success: false, msg: '无此数据或权限不足'}
  end
  if type == 'all'
    @data = get_sales_all_plan(staffs, type, year, school_tag_id)
    unless @data.empty?
      @data[0]['id'] = 0
    end
    @total_count = 1
  else
    @total_count = staffs.count
    @data = []
    staffs.each do |staff|
      @data += get_sales_all_plan([staff], type, year, school_tag_id)
    end
  end
  unless @data.empty?
    @data = @data.reject { |item| item['target_clazz'].nil? || (target_clazz.present? && !target_clazz.include?(item['target_clazz']))}
    current_months = Time.now.month
    @data.each do |item|
      item['year_plan'] = 0
      (13 - current_months).times do |i|
        column = 'plan_' + (i + current_months).to_s
        item['year_plan'] += item[column].present? ? item[column] : 0
      end
    end

    if type != 'all'
      tmp_id = 1
      last_id = 0
      @data.each do |item|
        if last_id > 0 && item['id'] != last_id
          tmp_id += 1
        end
        last_id = item['id']
        item['staff_id'] = last_id
        item['id'] = tmp_id + (params[:page].to_i-1)*params[:limit].to_i
      end
    end
  end
end

#years_planObject



333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
# File 'app/controllers/educode_sales/plans_controller.rb', line 333

def years_plan
  @sale_plans = SalePlan.from("(
                                SELECT SUM(last_follow.budget_amount) AS budget_amounts, educode_sales_sale_plans.*, ss.annual,
                                       SUM(IF(educode_sales_sale_plans.clazz = 1 AND educode_sales_business_infos.plan_sign_on IS NOT NULL, last_follow.budget_amount, 0)) AS clazz_1,
                                       SUM(IF(educode_sales_sale_plans.clazz = 18 and plan_bid_on IS NOT NULL, last_follow.budget_amount, 0)) AS clazz_18,

                                       (SUM(IF(educode_sales_sale_plans.clazz = 2 AND prepayment_plan_on IS NOT NULL AND check_fee_plan_on IS NOT NULL AND qa_plan_on IS NOT NULL, prepayment_amount, 0)) +
                                       SUM(IF(educode_sales_sale_plans.clazz = 2 AND prepayment_plan_on IS NOT NULL AND check_fee_plan_on IS NOT NULL AND qa_plan_on IS NOT NULL, check_fee, 0)) +
                                       SUM(IF(educode_sales_sale_plans.clazz = 2 AND prepayment_plan_on IS NOT NULL AND check_fee_plan_on IS NOT NULL AND qa_plan_on IS NOT NULL, qa_amount, 0)) ) AS clazz_2,
                                       SUM(IF(educode_sales_sale_plans.clazz = 7, last_follow.budget_amount, 0)) AS clazz_7,

                                       SUM(IF(last_follow.bidded_date IS NOT NULL, last_follow.actual_amount, 0)) AS finish_bid,
                                       SUM(IF(last_follow.signed_date IS NOT NULL, last_follow.actual_amount, 0)) AS finish_sign,
                                       SUM(educode_sales_businesses.return_money) AS finish_return_money

                                FROM educode_sales_sale_plans
                                JOIN educode_sales_businesses ON educode_sales_businesses.id = educode_sales_sale_plans.business_id
                                LEFT JOIN educode_sales_business_infos ON educode_sales_business_infos.sale_plan_id = educode_sales_sale_plans.id
                                LEFT JOIN educode_sales_follow_ups AS last_follow ON educode_sales_businesses.last_follow_up_id = last_follow.id AND last_follow.deleted_at IS NULL
                                LEFT JOIN educode_sales_assessments_settings AS ss ON ss.staff_id = educode_sales_sale_plans.staff_id
                                     AND YEAR(ss.assessment_year) = educode_sales_sale_plans.year AND ss.assessment = educode_sales_sale_plans.clazz
                                WHERE educode_sales_sale_plans.deleted_at IS NULL
                                GROUP BY educode_sales_sale_plans.staff_id, educode_sales_sale_plans.clazz, educode_sales_sale_plans.year
                              ) AS educode_sales_sale_plans
  ")
  if @current_admin.is_admin?
    # @sale_plans = SalePlan
  else
    level = @current_admin.role.role_areas.find_by(clazz: '销售计划').level
    case level
    when '自己'
      @sale_plans = @sale_plans.where(staff_id: @current_admin.id)
    when '区域'
      staff_ids = Staff.joins(user: [user_extension: [department: :school]]).where("schools.province in (?)", @current_admin.areas.pluck(:name)).pluck(:id)
      business_ids = Business.where(school_id: StaffSchool.where(staff_id: @current_admin.id).pluck(:school_id)).pluck(:id)
      @sale_plans = @sale_plans.where("educode_sales_sale_plans.staff_id in (?) OR educode_sales_sale_plans.staff_id = ? OR educode_sales_sale_plans.business_id in (?)", staff_ids, @current_admin.id,business_ids)
    else
      # @sale_plans = SalePlan
    end
  end
  @sale_plans = @sale_plans.where.not(year: nil)

  @sale_plans = @sale_plans.where(deleted_at: nil)

  if params[:q].present? && params[:q][:year].present?
    @sale_plans = @sale_plans.where(year: params[:q][:year])
  end
  if params[:q].present? && params[:q][:staff_id].present?
    @sale_plans = @sale_plans.where(staff_id: params[:q][:staff_id])
  end
  if params[:sort].present? && params[:sort][:field]
    @sale_plans = @sale_plans.order("#{params[:sort][:field]} #{params[:sort][:order]}")
  else
    @sale_plans = @sale_plans.order("created_at desc")
  end

  @sale_plans = @sale_plans.page(params[:page]).per(params[:limit])
end