Class: EducodeSales::ContractsController

Inherits:
ApplicationController show all
Defined in:
app/controllers/educode_sales/contracts_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_follow_upsObject



386
387
388
389
390
391
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
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
# File 'app/controllers/educode_sales/contracts_controller.rb', line 386

def add_follow_ups
  @business = Business.find(params[:business_id])
  last_follow_up = @business.last_follow_up

  # 计划交货时间
  current_1_plan = nil
  # 计划验收时间
  current_2_plan = nil
  # 实际交货时间
  current_1_actual = nil
  # 实际验收时间
  current_2_actual = nil


  
  data = []
  6.times do |i|
    data[i] = []
    params["#{i+1}_promise_date"].each do |d, v|
      data[i] << [v]
    end
    params["#{i+1}_num"].each do |d, v|
      data[i][d.to_i] << v
    end
    params["#{i+1}_plan_date"].each do |d, v|
      data[i][d.to_i] << v
      if i == 0 && v.present?
        current_1_plan = v.to_date
      elsif i == 1 && v.present?
        current_2_plan = v
      end
    end
    params["#{i+1}_actual_date"].each do |d, v|
      data[i][d.to_i] << v
      if i == 0 && v.present?
        current_1_actual = v.to_date
      elsif i == 1 && v.present?
        current_2_actual = v
      end

      # if i == 1 && last_follow_up
      #   # 验收时间
      #   last_follow_up.reception_at = v
      # elsif i == 0 && last_follow_up
      #   # 合同部署时间
      #   last_follow_up.deploy_time = v
      #   @business.p_deploy_time = v
      # end
    end
   
  end
  data.each do  |row|
    # 全部为空的值去掉选项
    row.select! do |d|
      s = d.uniq
      s.size == 1 && s[0].blank? ? false : true
    end
  end
  if last_follow_up
    if data[0].present?
        # 合同部署时间
      last_follow_up.deploy_time = data[0][-1][-1]
      @business.p_deploy_time = data[0][-1][-1]
    end
    if data[1].present?
       # 验收时间
      last_follow_up.reception_at = data[1][-1][-1]
    end
  end

  current_week = Time.now.strftime('%W')
  staff_manage_ids = @business&.last_follow_up&.assign_follow_ups.present? ? @business.last_follow_up.assign_follow_ups.pluck(:staff_id) : [@business.staff_id]
  if current_1_plan && current_1_plan.to_date.strftime('%W') == current_week
    unless EducodeSales::SalePlan.where(weekly: current_week, content: "提醒:请补充交付计划内容!", business: @business, staff_id: staff_manage_ids, finish_rate: 0).exists?
      common_id = EducodeSales::Common.find_by(clazz: '计划类型', name: '交付计划')&.id
      staff_manage_ids.each do |staff_id|
        EducodeSales::SalePlan.create(month: Time.now.beginning_of_month, weekly: current_week, content: "提醒:请补充交付计划内容!", business: @business, staff_id: staff_id, finish_rate: '0', common_id: common_id )
        EducodeSales::SalePlan.create(month: Time.now.beginning_of_month, content: "提醒:请补充交付计划内容!", business: @business, staff_id: staff_id, finish_rate: '0', common_id: common_id )
      end
    end
  end

  if current_2_plan && current_2_plan.to_date.strftime('%W') == current_week
    unless EducodeSales::SalePlan.where(weekly: current_week, content: "提醒:请补充验收计划内容!", business: @business, staff_id: staff_manage_ids, finish_rate: 0).exists?
      common_id = EducodeSales::Common.find_by(clazz: '计划类型', name: '验收计划')&.id
      staff_manage_ids.each do |staff_id|
        EducodeSales::SalePlan.create(month: Time.now.beginning_of_month, weekly: current_week, content: "提醒:请补充验收计划内容!", business: @business, staff_id: staff_id, finish_rate: '0', common_id: common_id )
        EducodeSales::SalePlan.create(month: Time.now.beginning_of_month, content: "提醒:请补充验收计划内容!", business: @business, staff_id: staff_id, finish_rate: '0', common_id: common_id )
      end
    end
  end

  # 更新对应的计划完成度
  if current_2_plan.present? && current_2_plan.to_date.strftime('%W') == current_week
    common_id = EducodeSales::Common.find_by(clazz: '计划类型', name: '交付计划')&.id
    EducodeSales::SalePlan.where(month: Time.now.beginning_of_month, business: @business, staff_id: staff_manage_ids, finish_rate: 0, common_id: common_id).update_all(finish_rate: 100)
  end

  if current_2_actual.present? && current_2_actual.to_date.strftime('%W') == current_week
    common_id = EducodeSales::Common.find_by(clazz: '计划类型', name: '验收计划')&.id
    EducodeSales::SalePlan.where(month: Time.now.beginning_of_month, business: @business, staff_id: staff_manage_ids, finish_rate: 0, common_id: common_id).update_all(finish_rate: 100)
  end


  follow_up = last_follow_up.dup
 
  follow_up.assign_attributes(follow_up_params)
  follow_up.description = params[:content]
  if params[:service_time].present?
    date = params[:service_time].split(" - ")
    follow_up.service_start_time = date[0]
    follow_up.service_end_time = date[1]
    follow_up.service_time_long = (date[1].to_date - date[0].to_date).to_i
  end
  follow_up.staff = @current_admin

  last_follow_up.assign_follow_ups.each do |d|
    follow_up.assign_follow_ups.build(staff_id: d.staff_id)
  end

  if follow_up.save!
    if last_follow_up.present?
      last_follow_up.key_person.each do |d|
        key_person = d.dup
        key_person.follow_up_id = follow_up.id
        key_person.save
      end
      last_follow_up.money_plans.each do |d|
        money = d.dup
        money.staff = @current_admin
        money.follow_up_id = follow_up.id
        money.save
      end
    end

    contract_lists = EducodeSales::ContractDateList.clazzs.invert
    data.each_with_index do |s, i|
      if s.present?
        s.each do |d|
         follow_up.contract_date_lists.create!({promise_date: d[0], num: d[1], plan_date: d[2], actual_date: d[3], staff_id: @current_admin.id, clazz: contract_lists[i]})
        end
      end
    end
    follow_up.follow_up_trends.create(clazz: '跟进信息', content: params[:content], staff_id: @current_admin.id)
    @business.update(last_follow_up_id: follow_up.id)
    render_success
  else
    render_failure follow_up
  end
end

#adviseObject



537
538
539
540
541
# File 'app/controllers/educode_sales/contracts_controller.rb', line 537

def advise
  followup = FollowUp.find(params[:id])
  followup.follow_up_trends.create(clazz: '建议信息', content: params[:content], staff_id: @current_admin.id)
  render_success
end

#assignObject



543
544
545
546
547
548
549
550
# File 'app/controllers/educode_sales/contracts_controller.rb', line 543

def assign
  role = Role.find_by( name: '售后工程师')
  staffs = Staff.joins(:user).where(role_id: role.id)
  business = Business.find(params[:id])
  selected_staff_ids = business.assign_staffs.pluck(:staff_id)
  gon.sales_staffs = staffs.map { |d| {name: d.user.real_name, value: d.id, selected: selected_staff_ids.include?(d.id) } }
  render layout: false
end

#assign_staffObject



572
573
574
575
576
577
578
579
580
581
# File 'app/controllers/educode_sales/contracts_controller.rb', line 572

def assign_staff
  @business = Business.find(params[:id])
  assign_staffs = []
  params[:to_id].split(",").each do |i|
    assign_staffs << AssignStaff.find_or_initialize_by(sourcable_id: @business.id, staff_id: i, sourcable_type: "EducodeSales::Business")
  end
  @business.assign_staffs = assign_staffs
  @business.save
  render_success
end

#edit_productObject



605
606
607
608
# File 'app/controllers/educode_sales/contracts_controller.rb', line 605

def edit_product
  @product_catalog = ProductCatalog.find(params[:id])
  render layout: false
end

#follow_upsObject



323
324
325
326
327
328
329
330
331
332
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
# File 'app/controllers/educode_sales/contracts_controller.rb', line 323

def follow_ups
  authorize! :read_contract, Business
  contract_ids = Common.where(clazz: '商机阶段', name: ['已中标', '已签单', '已验收', '回款中', '服务中', '已结束']).pluck(:id)
  @follow_ups = FollowUp.joins("
    JOIN educode_sales_businesses ON educode_sales_follow_ups.business_id = educode_sales_businesses.id
  ").joins(:follow_up_trends).where("educode_sales_follow_ups.stage_id in (?)", contract_ids).select("educode_sales_follow_ups.*, educode_sales_follow_up_trends.clazz, educode_sales_follow_up_trends.content, educode_sales_follow_up_trends.id AS trend_id")

  if @current_admin.is_admin?
    @follow_ups = @follow_ups
  else
    level = @current_admin.role.role_areas.find_by(clazz: '合同管理').level
    case level
    when '自己'
      @follow_ups = @follow_ups.where("educode_sales_follow_ups.staff_id = ?", @current_admin.id)
    when '区域'
      school_ids = School.where(province: @current_admin.areas.pluck(:name)).pluck(:id) + StaffSchool.where(staff_id: @current_admin.id).pluck(:school_id)
      business_ids = Business.joins(last_follow_up: :assign_follow_ups).where("educode_sales_assign_follow_ups.staff_id = ?", @current_admin.id).pluck(:id)
      @businesses = Business.joins("JOIN departments ON educode_sales_businesses.department_id = departments.id").where("departments.school_id in (?) OR educode_sales_businesses.staff_id = #{@current_admin.id}  OR educode_sales_businesses.id in (?)", school_ids, business_ids)
      business_ids = @businesses.pluck(:id)
      @follow_ups = @follow_ups.where(business_id: business_ids)
    end
  end
  if params[:q].present? && params[:q][:name].present?
    @follow_ups = @follow_ups.joins(:business).where("educode_sales_businesses.name LIKE ?", "%#{params[:q][:name]}%")
  end
  if params[:q].present? && params[:q][:follows_date].present?
    date = params[:q][:follows_date].split(" - ")
    @follow_ups = @follow_ups.where("educode_sales_follow_ups.created_at > ? AND educode_sales_follow_ups.created_at < ?", date[0], date[1] + '23:59:59')
  end
  if params[:q].present? && params[:q][:staff_id].present?
    @follow_ups = @follow_ups.where(staff_id: params[:q][:staff_id])
  end
  if params[:q].present? && params[:q][:department].present?
    departments_ids = Department.joins(:school).where("schools.name like ?", "%#{params[:q][:department]}%").pluck(:id)
    @follow_ups = @follow_ups.joins(business: :department).where("departments.id in (?)", departments_ids)
  end
  if params[:q].present? && params[:q][:area].present?
    p = EducodeSales::Common.find(params[:q][:area]).name
    @follow_ups = @follow_ups.joins(business: :department).joins("
      JOIN schools ON departments.school_id = schools.id
    ").where("province = ?", p)
  end

  if params[:q].present? && params[:q][:description].present?
    @follow_ups = @follow_ups.joins(:business).joins("JOIN educode_sales_businesses ON educode_sales_businesses.id = educode_sales_follow_ups.business_id
            ").where("educode_sales_follow_ups.description LIKE ?" ,"%#{params[:q][:description]}%")

  end

  if params[:q].present? && params[:q][:info_clazz].present?
    @follow_ups = @follow_ups.where("educode_sales_follow_up_trends.clazz = ?", params[:q][:info_clazz])
  end

  @follow_ups = @follow_ups.includes(:staff, :clazz, :stage, key_person: :teacher, business: [department: :school])

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

#indexObject



5
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
63
64
65
66
67
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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
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
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
# File 'app/controllers/educode_sales/contracts_controller.rb', line 5

def index
  authorize! :read_contract, Business
  respond_to do |format|
    format.html do
      common = Common.find_by(clazz: 'staff_type', name: '销售')
      staffs = Staff.joins(:user).where(job_type: common.id).where.not(role_id: 11)
      @staffs = staffs.map { |d| [d.user.real_name, d.id]}
      gon.place = params[:place_id].present? ? [{ value: params[:place_id], name: EducodeSales::Place.find(params[:place_id]).name }] : []
      gon.staffs = staffs.map { |d| {name: d.user.real_name, value: d.id } }

      bussiness_type = []
      if params[:type]
        # 项目类型
        bussiness_type = EducodeSales::Business.include_types(params[:type]) || []
      end

      business_step = []
      if params[:step]
        # 项目阶段
        business_step = EducodeSales::Business.include_steps(params[:step]) || []
      end


      gon.business_type = Common.where(clazz: 'business_type').map do |d|
        {value: d.id, name: d.name, selected: bussiness_type.include?(d.extras)}
      end

      gon.business_step = Common.where(clazz: 'business_step', name: ['已中标', '已签单', '已验收', '回款中', '服务中', '已结束']).order("position").map do |d|
        {value: d.id, name: d.name, selected: business_step.include?(d.name)}
      end
      if params[:date_at].present? && params[:date_at] != '全部'
        gon.bidded_date = Time.new(params[:date_at]).beginning_of_year.strftime("%Y-%m-%d") + " - " + Time.new(params[:date_at]).end_of_year.strftime("%Y-%m-%d")
      end
    end
    format.json do
      @businesses = Business
      contract_ids = Common.where(clazz: '商机阶段', name: ['已中标', '已签单', '已验收', '回款中', '服务中', '已结束']).pluck(:id)
      @businesses = @businesses.joins("
        JOIN educode_sales_follow_ups ON educode_sales_businesses.last_follow_up_id = educode_sales_follow_ups.id
      ").where("educode_sales_follow_ups.stage_id in (?)", contract_ids)

      if @current_admin.is_admin?
        @businesses = @businesses
      else
        level = @current_admin.role.role_areas.find_by(clazz: '合同管理').level
        case level
        when '自己'
          assign_business_ids = EducodeSales::Business.joins(:assign_staffs).where("educode_sales_assign_staffs.staff_id = ?", @current_admin.id).pluck(:id)

          @businesses = @businesses.where("educode_sales_businesses.staff_id = ? OR educode_sales_businesses.id in (?)", @current_admin.id, assign_business_ids)
        when '区域'
          school_ids = School.where(province: @current_admin.areas.pluck(:name)).pluck(:id) + StaffSchool.where(staff_id: @current_admin.id).pluck(:school_id)
          business_ids = @businesses.joins(last_follow_up: :assign_follow_ups).where("educode_sales_assign_follow_ups.staff_id = ?", @current_admin.id).pluck(:id)
          assign_business_ids = EducodeSales::Business.joins(:assign_staffs).where("educode_sales_assign_staffs.staff_id = ?", @current_admin.id).pluck(: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
          @businesses = @businesses.joins("JOIN departments ON educode_sales_businesses.department_id = departments.id").where("departments.school_id in (?) OR educode_sales_businesses.staff_id = #{@current_admin.id}  OR educode_sales_businesses.id in (?)", school_ids.uniq, business_ids + assign_business_ids)
          
        end
      end


      if params[:q] && params[:q][:signed_date].present?
        date = params[:q][:signed_date].split(" - ")
        @businesses = @businesses.joins("
          JOIN educode_sales_follow_ups ON educode_sales_businesses.last_follow_up_id = educode_sales_follow_ups.id
        ").where("educode_sales_follow_ups.signed_date >= ? AND educode_sales_follow_ups.signed_date <= ?", date[0], date[1])
      end

      if params[:q]&& params[:q][:date_at].present?
        date = params[:q][:date_at].split(" - ")
        x_id = Common.find_by(extras: EducodeSales::Common::XTYPE)&.id
        @businesses = @businesses.joins(follow_ups: :money_plans).where("educode_sales_follow_ups.clazz_id != ?", x_id).where.not("educode_sales_money_plans.clazz!= 1").where("educode_sales_money_plans.date_at >= ?  AND educode_sales_money_plans.date_at <= ? ", date[0] + " 00:00:00", date[1] + " 23:59:59").distinct
      end

      if params[:q].present? && params[:q][:property].present?
        # 客户类型
        @businesses = @businesses.joins(department: [school: :school_tags]).where("school_tags.id = ?", params[:q][:property])
      end

      if params[:q] && params[:q][:reception_at].present?
        date = params[:q][:reception_at].split(" - ")
        @businesses = @businesses.joins("
          JOIN educode_sales_follow_ups ON educode_sales_businesses.last_follow_up_id = educode_sales_follow_ups.id
        ").where("educode_sales_follow_ups.reception_at >= ? AND educode_sales_follow_ups.reception_at <= ?", date[0], date[1])
      end

      if params[:q] && params[:q][:p_deploy_time].present?
        date = params[:q][:p_deploy_time].split(" - ")
        @businesses = @businesses.where("p_deploy_time >= ? AND p_deploy_time <= ?", date[0], date[1])
      end

      if params[:q] && params[:q][:bidded_date].present?
        date = params[:q][:bidded_date].split(" - ")
        @businesses = @businesses.joins("
          JOIN educode_sales_follow_ups ON educode_sales_businesses.last_follow_up_id = educode_sales_follow_ups.id
        ").where("educode_sales_follow_ups.bidded_date >= ? AND educode_sales_follow_ups.bidded_date <= ?", date[0], date[1])
      end


      if params[:q].present? && params[:q][:name].present?
        @businesses = @businesses.where("educode_sales_businesses.name like ?", "%#{params[:q][:name]}%")
      end
      if params[:q].present? && params[:q][:department].present?
        departments_ids = Department.joins(:school).where("schools.name like ?", "%#{params[:q][:department]}%").pluck(:id)
        @businesses = @businesses.joins(:department).where("departments.id in (?)", departments_ids)
      end
      if params[:q].present? && params[:q][:staff_id].present?
        part_a_ids = @businesses.where("educode_sales_businesses.last_follow_up_id is null AND educode_sales_businesses.staff_id = ?",params[:q][:staff_id]).ids
        part_b_ids = @businesses.where("educode_sales_businesses.last_follow_up_id is not null").joins("
          JOIN educode_sales_follow_ups ON educode_sales_businesses.last_follow_up_id = educode_sales_follow_ups.id
        ").where("educode_sales_follow_ups.staff_id = ?", params[:q][:staff_id]).ids
        business_ids = part_a_ids + part_b_ids
        @businesses = EducodeSales::Business.where(id:business_ids)
      end
      if params[:q].present? && params[:q][:business_type].present?
        @businesses = @businesses.where("educode_sales_businesses.clazz_id in (?)", params[:q][:business_type].split(",").map(&:to_i))
      end

      if params[:q].present? && params[:q][:business_step].present?
        @businesses = @businesses.joins("
          JOIN educode_sales_follow_ups ON educode_sales_businesses.last_follow_up_id = educode_sales_follow_ups.id
        ").where("educode_sales_follow_ups.stage_id in (?)", params[:q][:business_step].split(",").map(&:to_i))
      end
      if params[:q].present? && params[:q][:place_id].present?
        @businesses = @businesses.joins("
          JOIN educode_sales_follow_ups ON educode_sales_businesses.last_follow_up_id = educode_sales_follow_ups.id
        ").where("educode_sales_follow_ups.place_id = ?", params[:q][:place_id])
      end
      if params[:q].present? && params[:q][:business_year].present?
        @businesses = @businesses.joins("
          JOIN educode_sales_follow_ups ON educode_sales_businesses.last_follow_up_id = educode_sales_follow_ups.id
        ").where("educode_sales_follow_ups.year = ?", params[:q][:business_year])
      end

      if params[:q].present? && params[:q][:year].present?
        @businesses = @businesses.joins("
          JOIN educode_sales_follow_ups ON educode_sales_businesses.last_follow_up_id = educode_sales_follow_ups.id
        ").where("educode_sales_follow_ups.year <= ?", params[:q][:year])
      end

      if params[:q].present? && params[:q][:o_business_deployment].present?
        @businesses = @businesses.joins("
          JOIN educode_sales_follow_ups ON educode_sales_businesses.last_follow_up_id = educode_sales_follow_ups.id
        ").where("educode_sales_follow_ups.o_business_deployment = ?", params[:q][:o_business_deployment])
      end

      if params[:q].present? && params[:q][:area].present?
        area = EducodeSales::Common.find(params[:q][:area]).name
        if @current_admin.is_admin?
          @businesses = @businesses.joins("
            JOIN departments ON educode_sales_businesses.department_id = departments.id
            JOIN schools ON departments.school_id = schools.id
          ").where("province = ?", area)
        else
          level = @current_admin.role.role_areas.find_by(clazz: '商机管理').level
          if level == "区域"
              @businesses = @businesses.joins("
                JOIN schools ON departments.school_id = schools.id
              ").where("province = ?", area)
            else
              @businesses = @businesses.joins("
                JOIN departments ON educode_sales_businesses.department_id = departments.id
                JOIN schools ON departments.school_id = schools.id
              ").where("province = ?", area)
          end
        end
      end

      if params[:q].present? && params[:q][:date].present?
        date = params[:q][:date].split(" - ")
        @businesses = @businesses.where("educode_sales_businesses.created_at > ? AND educode_sales_businesses.created_at < ?", date[0], date[1] + '23:59:59')
      end

      if params[:q].present? && params[:q][:sales_staff_id].present?
        # 销售经理
        @businesses = @businesses.joins("LEFT JOIN educode_sales_assign_follow_ups ON educode_sales_assign_follow_ups.follow_up_id = educode_sales_businesses.last_follow_up_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[:q][:sales_staff_id], params[:q][:sales_staff_id])

      end

      if params[:q].present? && params[:q][:after_sales_staff_id].present?
        #  售后工程师
        @businesses = @businesses.joins("LEFT JOIN educode_sales_assign_staffs ON educode_sales_assign_staffs.sourcable_type = 'EducodeSales::Business' AND educode_sales_assign_staffs.sourcable_id = educode_sales_businesses.id").
                                  where("educode_sales_assign_staffs.staff_id = ?", params[:q][:after_sales_staff_id])

      end

      # 商机变化
      if params[:q][:clazz_changes].present?
        clazz_changes = EducodeSales::BusinessClazzChange.clazz_changes_value[params[:q][:clazz_changes].to_s]
        @businesses = @businesses.joins("JOIN educode_sales_business_clazz_changes ON educode_sales_business_clazz_changes.business_id = educode_sales_businesses.id").where("educode_sales_business_clazz_changes.clazz_changed in (?)", clazz_changes)
      end

      if params[:sort].present? && params[:sort][:field]
        if params[:sort][:field] == "service_end_time"
          @businesses = @businesses.order("service_time_long #{params[:sort][:order]}")
        else
          @businesses = @businesses.order("#{params[:sort][:field]} #{params[:sort][:order]}")
        end
      else
        @businesses = @businesses.order("educode_sales_businesses.created_at desc")
      end

      if params[:page].present?
        @businesses = @businesses.select("
        distinct
        educode_sales_businesses.*,
        last_follow.invitation_at,
        last_follow.budget_amount,
        last_follow.o_business_deployment,
        last_follow.service_time_long,
        last_follow.service_end_time,
        last_follow.service_start_time,
        last_follow.reception_at,
        last_follow.bidded_date,
        last_follow.signed_date,
        last_follow.year,
        last_follow.created_at as latest_time,
        last_follow.actual_amount,
        last_follow.divide_rate,
        last_follow.divide_amount,
        (last_follow.total_amount - last_follow.actual_amount) as divide_money,
        (last_follow.actual_amount - educode_sales_businesses.return_money) as wait_return_money,
        last_follow.total_amount,
        total_follow_ups.follow_ups_counts
        ").joins("
        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 (
          SELECT COUNT(*) AS follow_ups_counts, educode_sales_follow_ups.business_id
          FROM educode_sales_follow_ups
          WHERE educode_sales_follow_ups.deleted_at IS NULL
          GROUP BY educode_sales_follow_ups.business_id
        ) AS total_follow_ups ON educode_sales_businesses.id = total_follow_ups.business_id
      ").includes(:users, last_follow_up: [:clazz, :assign_follow_ups]).page(params[:page]).per(params[:limit])
      end

      @businesses = @businesses.select("
        distinct
        educode_sales_businesses.*,
        last_follow.invitation_at,
        last_follow.budget_amount,
        last_follow.o_business_deployment,
        last_follow.service_time_long,
        last_follow.service_end_time,
        last_follow.service_start_time,
        last_follow.reception_at,
        last_follow.bidded_date,
        last_follow.signed_date,
        last_follow.year,
        last_follow.created_at as latest_time,
        last_follow.actual_amount,
        last_follow.divide_rate,
        last_follow.divide_amount,
        (last_follow.total_amount - last_follow.actual_amount) as divide_money,
        (last_follow.actual_amount - educode_sales_businesses.return_money) as wait_return_money,
        last_follow.total_amount,
        total_follow_ups.follow_ups_counts
        ").joins("
        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 (
          SELECT COUNT(*) AS follow_ups_counts, educode_sales_follow_ups.business_id
          FROM educode_sales_follow_ups
          WHERE educode_sales_follow_ups.deleted_at IS NULL
          GROUP BY educode_sales_follow_ups.business_id
        ) AS total_follow_ups ON educode_sales_businesses.id = total_follow_ups.business_id
      ").includes(:users, last_follow_up: [:clazz, :assign_follow_ups])
    end
  end
end

#listObject



279
280
281
282
283
284
285
286
287
288
# File 'app/controllers/educode_sales/contracts_controller.rb', line 279

def list
  common = Common.find_by(clazz: 'staff_type', name: '销售')
  staffs = Staff.joins(:user).where(job_type: common.id).where.not(role_id: 11)
  @staffs = staffs.map { |d| [d.user.real_name, d.id]}
  role = Role.find_by(name: '售后工程师')
  @after_sales_staffs = Staff.joins(:user).where(role_id: role.id).map { |d| [d.user.real_name, d.id]}
  if params[:date_at].present? && params[:date_at] != '全部'
    gon.bidded_date = Time.new(params[:date_at]).beginning_of_year.strftime("%Y-%m-%d") + " - " + Time.new(params[:date_at]).end_of_year.strftime("%Y-%m-%d")
  end
end

#new_follow_upObject



290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
# File 'app/controllers/educode_sales/contracts_controller.rb', line 290

def new_follow_up
  @business = Business.find(params[:id])
  @last_follow_up = @business.last_follow_up
  @deployment_type = EducodeSales::FollowUp::BUSINESS_DEPLOYMENT
  @signed_clazz = EducodeSales::FollowUp.signed_clazzs.keys
  @stages =  Common.where(clazz: 'business_step', name: ['已中标', '已签单', '已验收', '回款中', '服务中', '已结束']).order("position").pluck(:name, :id)
  
  signed_department = @last_follow_up.signed_department
  if signed_department
    gon.department = [{value: signed_department.id, name: "#{signed_department&.school&.name}-#{signed_department&.name}"}]
    gon.value = signed_department.id
  else
    gon.department = []
    gon.value = ''
  end

  @list = {}
  EducodeSales::ContractDateList.clazzs.each do |d, i|
    @list[d] = [EducodeSales::ContractDateList.new]
  end

  @last_follow_up.contract_date_lists.each do |d|
    if @list[d.clazz][0].id ==  nil
      @list[d.clazz][0] = d
    else
      @list[d.clazz] << d
    end
  end
 
  render layout: false
end

#new_productObject



583
584
585
# File 'app/controllers/educode_sales/contracts_controller.rb', line 583

def new_product
  render layout: false
end

#new_sales_detailObject



628
629
630
# File 'app/controllers/educode_sales/contracts_controller.rb', line 628

def new_sales_detail
  render layout: false
end

#product_catalogObject



587
588
589
590
591
592
593
594
# File 'app/controllers/educode_sales/contracts_controller.rb', line 587

def product_catalog
  product_catalog = ProductCatalog.new(product_up_params)
  if product_catalog.save
    render_success
  else
    render_failure product_catalog
  end
end

#product_listObject



552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
# File 'app/controllers/educode_sales/contracts_controller.rb', line 552

def product_list
  respond_to do |format|
    format.html do
      common = Common.find_by(clazz: 'staff_type', name: '销售')
      staffs = Staff.joins(:user).where(job_type: common.id).where.not(role_id: 11)
      @staffs = staffs.map { |d| [d.user.real_name, d.id]}
      gon.staffs = staffs.map { |d| {name: d.user.real_name, value: d.id } }
      gon.business_step = Common.where(clazz: 'business_step', name: ['已中标', '已签单', '已验收', '回款中', '服务中', '已结束']).order("position").map do |d|
        {value: d.id, name: d.name, selected: false}
      end
    end
    format.json do
      @product_catalogs = ProductCatalog
      @product_catalogs = @product_catalogs.where("name like ?", "%#{params[:q][:name]}%") if params[:q] && params[:q][:name].present?
      @product_catalogs = @product_catalogs.where(item_clazz: params[:q][:item_clazz]) if params[:q] && params[:q][:item_clazz].present?
      @product_catalogs = @product_catalogs.page(params[:page]).per(params[:limit])
    end
  end
end

#sales_detailObject



636
637
638
639
640
641
642
643
644
# File 'app/controllers/educode_sales/contracts_controller.rb', line 636

def sales_detail
  sales_detail = SalesDetail.new(sales_detail_params)
  sales_detail.staff = @current_admin
  if sales_detail.save
    render_success
  else
    render_failure sales_detail
  end
end

#select_productObject



632
633
634
# File 'app/controllers/educode_sales/contracts_controller.rb', line 632

def select_product
  render layout: false
end

#show_follow_recordObject



610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
# File 'app/controllers/educode_sales/contracts_controller.rb', line 610

def show_follow_record
  @follow_up = FollowUp.find(params[:follow_up_id])
  @business = Business.find(@follow_up.business_id)
  @show_follow_recored_deployment = EducodeSales::FollowUp::BUSINESS_DEPLOYMENT.to_h.invert[@follow_up.o_business_deployment]

  @trend = FollowUpTrend.find(params[:trend_id])

  id = @follow_up.id
  @follow_ups = @business.follow_ups
  ids = @follow_ups.ids
  size = ids.size
  ids = ids.reverse
  index = ids.index(id)
  @next_id = (index != size - 1 && size > 1) ? ids[index + 1] : 0
  @pre_id = (index != 0 && size > 1) ? ids[index - 1] : 0
  render layout: false
end

#update_product_catalogObject



596
597
598
599
600
601
602
603
# File 'app/controllers/educode_sales/contracts_controller.rb', line 596

def update_product_catalog
  product_catalog = ProductCatalog.find(params[:id])
  if product_catalog.update(product_up_params)
    render_success
  else
    render_failure product_catalog
  end
end

#upload_productsObject



647
648
649
650
651
652
653
654
655
656
657
# File 'app/controllers/educode_sales/contracts_controller.rb', line 647

def upload_products
  xlsx = Roo::Spreadsheet.open(params[:file])
  ods = xlsx.sheet(0)
  rows = ods.last_row - 1
  rows.times do |r|  #行数
    next unless ods.row(r+2)[0]
    EducodeSales::ProductCatalog.create(name: ods.row(r+2)[0].to_s.strip, item_clazz: ods.row(r+2)[1].to_s.strip, brand: ods.row(r+2)[2].to_s.strip, specification: ods.row(r+2)[3].to_s.strip, unit: ods.row(r+2)[4].to_s.strip, param: ods.row(r+2)[5].to_s.strip, source_method: ods.row(r+2)[6].to_s.strip, supplier: ods.row(r+2)[7].to_s.strip)
  end
  
  render json: { succcess: true}
end