Class: EducodeSales::SaleTrendsController

Inherits:
ApplicationController show all
Includes:
SaleTrendsCountHelper, SaleTrendsHelper
Defined in:
app/controllers/educode_sales/sale_trends_controller.rb

Constant Summary

Constants included from SaleTrendsCountHelper

EducodeSales::SaleTrendsCountHelper::NAMES

Constants included from SaleTrendsHelper

EducodeSales::SaleTrendsHelper::NAMES, EducodeSales::SaleTrendsHelper::RETURN_NAMES

Instance Method Summary collapse

Methods included from SaleTrendsCountHelper

#goal_forecast_month_count, #goal_forecast_quarter_count, #goal_forecast_week_count, #goal_forecast_year_count

Methods included from SaleTrendsHelper

#goal_forecast_month, #goal_forecast_quarter, #goal_forecast_week, #goal_forecast_year, #return_money_forecast_month, #return_money_forecast_quarter, #return_money_forecast_week, #return_money_forecast_year, #visit_analysis_charts

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

#business_areaObject

商机区域分布



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
278
279
280
281
282
283
284
285
286
287
288
289
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
321
322
323
324
# File 'app/controllers/educode_sales/sale_trends_controller.rb', line 241

def business_area
  respond_to do |format|
    format.html do
    end
    format.js do
      @business_types = EducodeSales::Common.where(clazz: 'business_type').where.not(extras: "x_class").map { |d| {name: d.name, value: d.id } }
      @select_business_type = params[:business_type].present? ?  params[:business_type].split(",") : []
      x = EducodeSales::Common.find_by(extras: EducodeSales::Common::XTYPE)&.id
      o = Common.find_by(extras: EducodeSales::Common::OTYPE)&.id
      provinces = EducodeSales::Common.where(clazz: 'area').pluck(:name)
      if params[:business_count_type] == 'money' || params[:business_count_type].blank?
        data = provinces.map { |province|
          if params[:business_type].blank?
            Business.joins(:last_follow_up).where("educode_sales_businesses.department_id in (?)", School.joins(:departments).where(province: province).pluck("departments.id")).where("educode_sales_follow_ups.clazz_id != ? AND educode_sales_follow_ups.clazz_id != ?", x, o).sum(:budget_amount).round(2)
          else
            Business.joins(:last_follow_up).where("educode_sales_businesses.department_id in (?)", School.joins(:departments).where(province: province).pluck("departments.id")).where("educode_sales_follow_ups.clazz_id in (?)", params[:business_type].split(",")).sum(:budget_amount).round(2)
          end
        }
        if params[:sort_by].present?
          data_hash = []
          data.each_with_index do |d, i|
            data_hash << {id: i, num: d}
          end

          data_hash.sort! { |a, b| params[:sort_by] == 'asc' ?  a[:num] <=> b[:num]  : b[:num] <=> a[:num] }
          data = []
          provinces_sort = []
          data_hash.each_with_index do |d|
            data << d[:num]
            provinces_sort << provinces[d[:id]]
          end
          provinces = provinces_sort
        end
        @business_data = {
          labels: provinces,
          datasets: [
            {
              label: "商机总额",
              data: data,
              backgroundColor: SaleTrend::COLORS[0],
              borderColor: SaleTrend::COLORS[0],
              borderWidth: 1
            }
          ]
        }
      else
        data = provinces.map { |province|
          if params[:business_type].blank?
            Business.joins(:last_follow_up).where("educode_sales_businesses.department_id in (?)", School.joins(:departments).where(province: province).pluck("departments.id")).where("educode_sales_follow_ups.clazz_id != ? AND educode_sales_follow_ups.clazz_id != ?", x, o).count
          else
            Business.joins(:last_follow_up).where("educode_sales_businesses.department_id in (?)", School.joins(:departments).where(province: province).pluck("departments.id")).where("educode_sales_follow_ups.clazz_id in (?)", params[:business_type].split(",")).count
          end
        }
        if params[:sort_by].present?
          data_hash = []
          data.each_Wit_index do |d, i|
            data_hash << {id: i, num: d}
          end

          data_hash.sort! { |a, b| params[:sort_by] == 'asc' ?  a[:num] <=> b[:num]  : b[:num] <=> a[:num] }
          data = []
          provinces_sort = []
          data_hash.each_with_index do |d|
            data << d[:num]
            provinces_sort << provinces[d[:id]]
          end
          provinces = provinces_sort
        end
        @business_data = {
          labels: provinces,
          datasets: [
            {
              label: "商机数量",
              data: data,
              backgroundColor: SaleTrend::COLORS[0],
              borderColor: SaleTrend::COLORS[0],
              borderWidth: 1
            }
          ]
        }
      end
    end
  end
end

#business_followup_analysisObject

商机跟进数



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
# File 'app/controllers/educode_sales/sale_trends_controller.rb', line 101

def business_followup_analysis
  common = EducodeSales::Common.find_by(clazz: 'staff_type', name: '销售')
  names = EducodeSales::Staff.includes(:user).where(job_type: common.id).map { |d| [d.user.real_name, d.id, d.role_id] }
  x = EducodeSales::Common.find_by(extras: EducodeSales::Common::XTYPE)&.id
  x_business_ids = EducodeSales::Business.joins(last_follow_up: :clazz).where("educode_sales_commons.id = ?",x).pluck :id

  @follow_count_range = params[:follow_count_range] || "week"
  # 商机跟进数图表
  respond_to do |format|
    format.html do

    end
    format.js do
      default_dates = (30.day.ago.to_date..Date.today).map { |d| d.strftime("%Y-%W") }.uniq #默认时间范围
      @follow_count_data =  business_followup_charts(default_dates, names, x_business_ids, SaleTrend::COLORS, [30.day.ago.to_date.beginning_of_week, Date.today], "%Y%u") do |default_dates|
        default_dates.map { |date|
          d = date.split("-")
          year = d[0].to_i
          week = d[1].to_i
          if week == 0
            0
          else
            month = Date.commercial(year, week).strftime("%m月%d日")
            day = Date.commercial(year, week, 7).strftime("%m月%d日")
            date.to_s + "(#{month}-#{day})"
          end
        } - [0]
      end
    end
    format.json do
      if params[:follow_count_range].present?
        case params[:follow_count_range]
        when "week" #按周
          if params[:date_week].present?
            date = params[:date_week].split(" - ")
            # 年初第一天周数是0会导致周数重复计算
            dates = (date[0].to_date..date[1].to_date).map { |d|  d.strftime("%Y-%W") }.uniq.select { |d| d.split("-")[1] != '00' }
            @follow_count_data =  business_followup_charts(dates, names, x_business_ids, SaleTrend::COLORS, date, "%Y%u") do |dates|
              dates.map { |date|
                d = date.split("-")
                year = d[0].to_i
                week = d[1].to_i
                if week == 0
                  0
                else
                  month = Date.commercial(year, week).strftime("%m月%d日")
                  day = Date.commercial(year, week, 7).strftime("%m月%d日")
                  date.to_s + "(#{month}-#{day})"
                end
              } - [0]
            end
          else
            return render json: {msg: '请选择时间范围', success: false }
          end
        when "month" #按月
          if params[:date_month].present?
            date = params[:date_month].split(" - ")
            dates = ((date[0] + "-01").to_date..(date[1] + "-01").to_date).map { |d| d.strftime("%Y-%m") }.uniq
            @follow_count_data = business_followup_charts(dates, names, x_business_ids, SaleTrend::COLORS, [(date[0] + "-01").to_date, (date[1] + "-01").to_date.end_of_month], '%Y%m')
          else
            return render json: {msg: '请选择时间范围', success: false }
          end
        when "year" #按年
          if params[:date_year].present?
            date = params[:date_year].split(" - ")
            dates = (date[0]..date[1]).to_a.map { |d| d.to_s}
            @follow_count_data = business_followup_charts(dates, names, x_business_ids, SaleTrend::COLORS, ["#{date[0]}-01-01".to_date.beginning_of_year, "#{date[1]}-01-01".to_date.end_of_year], '%Y')
          else
            return render json: {msg: '请选择时间范围', success: false }
          end
        else
          #按天
          if params[:date].present?
            date = params[:date].split(" - ")
            dates = (date[0].to_date..date[1].to_date).to_a.map { |d| d.to_s}
            @follow_count_data = business_followup_charts(dates, names, x_business_ids, SaleTrend::COLORS, [date[0].to_date, date[1].to_date], '%Y%m%d')
          else
            return render json: {msg: '请选择时间范围', success: false }
          end
        end
      end
      render json: {data: @follow_count_data }
    end
  end

end

#goal_forecastObject



405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
# File 'app/controllers/educode_sales/sale_trends_controller.rb', line 405

def goal_forecast
  respond_to do |format|
    format.html do
    end
    format.js do
      if params[:forecast_type].blank? || params[:forecast_type] == "money"
        p "按金额"
        goal_forecast_money
      else
        p "按数量"
        goal_forecast_count
      end
    end
  end
end

#operationsObject



96
97
98
# File 'app/controllers/educode_sales/sale_trends_controller.rb', line 96

def operations

end

#return_money_forecastObject

回款预测图



422
423
424
425
426
427
428
# File 'app/controllers/educode_sales/sale_trends_controller.rb', line 422

def return_money_forecast
  respond_to do |format|
    format.js do
      return_forecast_by_money
    end
  end
end


87
88
89
90
91
92
93
94
# File 'app/controllers/educode_sales/sale_trends_controller.rb', line 87

def sale_trends
  sale_trend = SaleTrend.find_by(year: params[:year])
  if sale_trend.update(sale_trend_params)
    render_success
  else
    render_failure sale_trend
  end
end

#sales_analysisObject

销售额分析



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
# File 'app/controllers/educode_sales/sale_trends_controller.rb', line 189

def sales_analysis
  respond_to do |format|
    format.html do

    end
    format.js do
      x = EducodeSales::Common.find_by(extras: EducodeSales::Common::XTYPE)&.id
      count_type = params[:count_type] || "actual_amount"
      stage_ids = Common.where(clazz: '商机阶段', name: ['已中标', '已签单', '已验收', '回款中', '服务中', '已结束']).pluck(:id)
      s_stage_ids = Common.where(clazz: '商机阶段', name: ['已签单', '已验收', '回款中', '服务中', '已结束']).pluck(:id)
      @goal_count_range = params[:goal_count_range] || "month"

      goal_default_dates = ("#{Time.now.year}-01-01".to_date.."#{Time.now.year}-#{Time.now.month}-01".to_date).map { |d| d.strftime("%Y-%m") }.uniq
      sale_names = ['已中标', '已签单', '已回款']

      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]}

      if params[:goal_count_range].present?
        case params[:goal_count_range]
        when "week"
        when "month" #按月
          if params[:goal_date_month].present?
            date = params[:goal_date_month].split(" - ")
            date[0] = (date[0] + "-01").to_date.to_s
            date[1] = (date[1] + "-01").to_date.end_of_month.to_s

            dates = ((date[0] + "-01").to_date..(date[1] + "-01").to_date).map { |d| d.strftime("%Y-%m") }.uniq
            @goal_count_data = month_sale_chart(dates, sale_names, SaleTrend::COLORS, x, stage_ids, s_stage_ids, count_type, date)
          else
            @goal_count_data = month_sale_chart(goal_default_dates, sale_names, SaleTrend::COLORS, x, stage_ids, s_stage_ids, count_type, ["#{Time.now.year}-01", "#{Time.now.year}-#{Time.now.month}"])
          end
        else
          #按年
          if params[:goal_date_year].present?
            date = params[:goal_date_year].split(" - ")
            dates = (date[0]..date[1]).to_a
            @goal_count_data = year_sale_chart(dates, sale_names, SaleTrend::COLORS, x, stage_ids, s_stage_ids, count_type, date)
          else
            goal_default_dates = ("#{Time.now.year}-01-01".to_date.."#{Time.now.year}-#{Time.now.month}-01".to_date).map { |d| d.strftime("%Y") }.uniq
            @goal_count_data = year_sale_chart(goal_default_dates, sale_names, SaleTrend::COLORS, x, stage_ids, s_stage_ids, count_type, ["#{Time.now.year}", "#{Time.now.year}"])
          end
        end
      else
        @goal_count_data = month_sale_chart(goal_default_dates, sale_names, SaleTrend::COLORS, x, stage_ids, s_stage_ids, count_type, ["#{Time.now.year}-01", "#{Time.now.year}-#{Time.now.month}"])
      end
    end
  end
end

#sales_followup_analysisObject

销售人员跟进分析



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
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
# File 'app/controllers/educode_sales/sale_trends_controller.rb', line 327

def sales_followup_analysis
  respond_to do |format|
    format.html do

    end
    format.js do
      #  销售人员跟进分析
      @goal_count_range = params[:goal_count_range] || "month"
      begin_time = Time.now.at_beginning_of_year.to_s
      end_time = Time.now.at_end_of_year.to_s
      customer_time_range = params[:customer_time_range]
      case customer_time_range
      when 'last_week'
        begin_time = (Time.now - 1.week).at_beginning_of_week.to_s
        end_time = (Time.now - 1.week).at_end_of_week.to_s
      when 'this_week'
        begin_time = Time.now.at_beginning_of_week.to_s
        end_time = Time.now.at_end_of_week.to_s
      when 'last_month'
        begin_time = (Time.now - 1.month).at_beginning_of_month.to_s
        end_time = (Time.now - 1.month).at_end_of_month.to_s
      when 'this_month'
        begin_time = Time.now.at_beginning_of_month.to_s
        end_time = Time.now.at_end_of_month.to_s
      when 'last_year'
        begin_time = (Time.now - 1.year).at_beginning_of_year.to_s
        end_time = (Time.now - 1.year).at_end_of_year.to_s
      when 'this_year'
        begin_time = Time.now.at_beginning_of_year.to_s
        end_time = Time.now.at_end_of_year.to_s
      when 'all'
        begin_time = (Time.now - 5.year).at_beginning_of_year.to_s
        end_time = (Time.now + 5.year).at_end_of_year.to_s
      when 'diy'
        if params[:customer_date].present?
          date = params[:customer_date].split(" - ")
          begin_time = date[0] + " 00:00:00"
          end_time = date[1] + " 23:59:59"
        end
      end
      common = Common.find_by(clazz: 'staff_type', name: '销售')
      staff_names = Staff.joins(:user).where(job_type: common.id).map { |d| d.user.real_name }
      staff_ids = Staff.joins(:user).where(job_type: common.id).pluck(:id)
      if params[:customer_count_type] == 'money' || params[:customer_count_type].blank?
        @customer_data = {
          labels: staff_names,
          datasets: [
            {
              label: "跟进客户数",
              data: staff_ids.map { |staff_id|
                (EducodeSales::CustomerFollow.where(staff_id: staff_id).where("created_at >= ? AND created_at <= ?", begin_time, end_time).pluck(:school_id) + EducodeSales::Business.where(id: EducodeSales::FollowUp.where(staff_id: staff_id).where("created_at >= ? AND created_at <= ?", begin_time, end_time).pluck(:business_id).uniq).pluck(:school_id)).uniq.size
              },
              backgroundColor: SaleTrend::COLORS[0],
              borderColor: SaleTrend::COLORS[0],
              borderWidth: 1
            }
          ]
        }
      else
        @customer_data = {
          labels: staff_names,
          datasets: [
            {
              label: "跟进客户次数",
              data: staff_ids.map { |staff_id|
                EducodeSales::CustomerFollow.where(staff_id: staff_id).where("created_at >= ? AND created_at <= ?", begin_time, end_time).size + EducodeSales::FollowUp.where(staff_id: staff_id).where("created_at >= ? AND created_at <= ?", begin_time, end_time).size
              },
              backgroundColor: SaleTrend::COLORS[0],
              borderColor: SaleTrend::COLORS[0],
              borderWidth: 1
            }
          ]
        }
      end
    end
  end
end


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
# File 'app/controllers/educode_sales/sale_trends_controller.rb', line 8

def trends
  # authorize! :trends,  EducodeSales::SaleTrend
  @year = params[:year] ? params[:year] : Time.now.year
  @years = ['全部'] + (1..(Time.now.year - 2014)).reverse_each.map { |d| 2014 + d }
  x = Common.find_by(extras: EducodeSales::Common::XTYPE)&.id
  o = Common.find_by(extras: EducodeSales::Common::OTYPE)&.id
  if (@year == '全部')
    @business_amount = Business.joins(:last_follow_up).where("educode_sales_follow_ups.clazz_id != ? AND educode_sales_follow_ups.clazz_id != ?", x, o).sum(:budget_amount).round(2)
    stage_ids = Common.where(clazz: '商机阶段', name: ['已中标', '已签单', '已验收', '回款中', '服务中', '已结束']).pluck(:id)
    # 中标总金额, 已回款总金额
    total_return = Business.joins(:last_follow_up).where("educode_sales_follow_ups.clazz_id != ?", x).where("educode_sales_follow_ups.stage_id IN (?)", stage_ids).select("sum(total_amount) AS total, sum(educode_sales_businesses.return_money) AS return_money")
    @goal_amount = total_return[0]['total']&.round(2) || 0

    @actual_goal_amount = Business.joins(:last_follow_up).where("educode_sales_follow_ups.clazz_id != ?", x).where("educode_sales_follow_ups.stage_id IN (?)", stage_ids).sum(:actual_amount).round(2)
    s_stage_ids = Common.where(clazz: '商机阶段', name: ['已签单', '已验收', '回款中', '服务中', '已结束']).pluck(:id)
    @service_amount = Business.joins(:last_follow_up).where("educode_sales_follow_ups.clazz_id != ?", x).where("educode_sales_follow_ups.stage_id IN (?)", s_stage_ids).sum(:total_amount).round(2)
    @actual_service_amount = Business.joins(:last_follow_up).where("educode_sales_follow_ups.clazz_id != ?", x).where("educode_sales_follow_ups.stage_id IN (?)", s_stage_ids).sum(:actual_amount).round(2)


    @return_amount = EducodeSales::MoneyPlanRecord.from("(
      SELECT distinct(educode_sales_money_plan_records.id), educode_sales_money_plan_records.amount
      FROM educode_sales_money_plan_records
      JOIN educode_sales_money_plan_claims ON educode_sales_money_plan_claims.money_plan_record_id = educode_sales_money_plan_records.id
      GROUP BY educode_sales_money_plan_records.id
      ) AS educode_sales_money_plan_records
    ").sum("amount").round(2)
    # @return_amount = Business.joins(last_follow_up: :money_plans).where("educode_sales_follow_ups.clazz_id != ?", x).where.not("educode_sales_money_plans.clazz!= ?", 1).sum(:amount).round(2)
    # # @return_amount = total_return[0]['return_money']&.round(2) || 0
    # @receivable_amount = @goal_amount - @return_amount

    @receivable_amount = Business.joins(:last_follow_up).where("educode_sales_follow_ups.clazz_id != ?", x).where("educode_sales_follow_ups.stage_id IN (?)", stage_ids).select("(SUM(educode_sales_follow_ups.actual_amount) - SUM(educode_sales_businesses.return_money)) AS num")
    @receivable_amount = @receivable_amount.present? && @receivable_amount[0]['num'] ? @receivable_amount[0]['num'].round(2) : 0

    a = Common.where(clazz: '商机类型', name: Common.find_by(extras: EducodeSales::Common::ATYPE)&.name).pluck(:id)
    @a_amount = Business.joins(:last_follow_up).where("educode_sales_follow_ups.clazz_id IN (?)", a).sum(:budget_amount).round(2)
    b = Common.where(clazz: '商机类型', name: Common.find_by(extras: EducodeSales::Common::BTYPE)&.name).pluck(:id)
    @b_amount = Business.joins(:last_follow_up).where("educode_sales_follow_ups.clazz_id IN (?)", b).sum(:budget_amount).round(2)
  else
    year_time = "#{@year}-01-01 00:00:00"
    year_over_time = "#{@year}-12-31 23:59:59"

    @sale_trend = SaleTrend.find_or_create_by(year: @year)
    @business_amount = Business.joins(:last_follow_up).where("educode_sales_follow_ups.clazz_id != ? AND educode_sales_follow_ups.clazz_id != ?", x, o).where("educode_sales_follow_ups.year <= ?", @year).sum(:budget_amount).round(2)
    stage_ids = Common.where(clazz: '商机阶段', name: ['已中标', '已签单', '已验收', '回款中', '服务中', '已结束']).pluck(:id)

    # 中标总金额, 已回款总金额
    total_return = Business.joins(:last_follow_up).where("educode_sales_follow_ups.clazz_id != ?", x).where("educode_sales_follow_ups.bidded_date >= ? AND educode_sales_follow_ups.bidded_date <= ? AND educode_sales_follow_ups.stage_id IN (?)", "#{@year}-01-01", "#{@year}-12-31", stage_ids).select("sum(total_amount) AS total, sum(educode_sales_businesses.return_money) AS return_money")
    @goal_amount = total_return[0]['total']&.round(2) || 0

    @actual_goal_amount = Business.joins(:last_follow_up).where("educode_sales_follow_ups.clazz_id != ?", x).where("educode_sales_follow_ups.bidded_date >= ? AND educode_sales_follow_ups.bidded_date <= ? AND educode_sales_follow_ups.stage_id IN (?)", "#{@year}-01-01", "#{@year}-12-31", stage_ids).sum(:actual_amount).round(2)
    s_stage_ids = Common.where(clazz: '商机阶段', name: ['已签单', '已验收', '回款中', '服务中', '已结束']).pluck(:id)
    @service_amount = Business.joins(:last_follow_up).where("educode_sales_follow_ups.clazz_id != ?", x).where("educode_sales_follow_ups.signed_date >= ? AND educode_sales_follow_ups.signed_date <= ?  AND educode_sales_follow_ups.stage_id IN (?)", "#{@year}-01-01", "#{@year}-12-31", s_stage_ids).sum(:total_amount).round(2)
    @actual_service_amount = Business.joins(:last_follow_up).where("educode_sales_follow_ups.clazz_id != ?", x).where("educode_sales_follow_ups.signed_date >= ? AND educode_sales_follow_ups.signed_date <= ?  AND educode_sales_follow_ups.stage_id IN (?)", "#{@year}-01-01", "#{@year}-12-31", s_stage_ids).sum(:actual_amount).round(2)
    # @return_amount = Business.joins(last_follow_up: :money_plans).where("educode_sales_follow_ups.clazz_id != ?", x).where.not("educode_sales_money_plans.clazz!= ?", 1).where("educode_sales_money_plans.date_at >= ?  AND educode_sales_money_plans.date_at <= ? ", year_time, year_over_time).sum(:amount).round(2)

    @return_amount = EducodeSales::MoneyPlanRecord.from("(
      SELECT distinct(educode_sales_money_plan_records.id), educode_sales_money_plan_records.amount, date_at
      FROM educode_sales_money_plan_records
      JOIN educode_sales_money_plan_claims ON educode_sales_money_plan_claims.money_plan_record_id = educode_sales_money_plan_records.id
      GROUP BY educode_sales_money_plan_records.id
      ) AS educode_sales_money_plan_records
    ").where("educode_sales_money_plan_records.date_at >= ?  AND educode_sales_money_plan_records.date_at <= ? ", year_time, year_over_time).sum(:amount).round(2)
    # 往年累计已中标合同
    # @former_goal_amount = Business.joins(:last_follow_up).where("educode_sales_follow_ups.clazz_id != ?", x).where("educode_sales_follow_ups.bidded_date <= ? AND educode_sales_follow_ups.stage_id IN (?)", "#{@year}-12-31", stage_ids).sum(:actual_amount).round(2)
    # # 往年累计已回款
    # @former_return_amount = Business.joins(last_follow_up: :money_plans).where("educode_sales_follow_ups.clazz_id != ?", x).where.not("educode_sales_money_plans.clazz!= ?", 1).where("educode_sales_money_plans.date_at <= ? ", year_over_time).sum(:amount).round(2)
    # @receivable_amount = @former_goal_amount - @former_return_amount

    @receivable_amount = Business.joins(:last_follow_up).where("educode_sales_follow_ups.clazz_id != ?", x).where("educode_sales_follow_ups.bidded_date <= ? AND educode_sales_follow_ups.stage_id IN (?)", "#{@year}-12-31", stage_ids).select("(SUM(educode_sales_follow_ups.actual_amount) - SUM(educode_sales_businesses.return_money)) AS num")
    @receivable_amount = @receivable_amount.present? && @receivable_amount[0]['num'] ? @receivable_amount[0]['num'].round(2) : 0

    a = Common.where(clazz: '商机类型', name: Common.find_by(extras: EducodeSales::Common::ATYPE)&.name).pluck(:id)
    @a_amount = Business.joins(:last_follow_up).where("educode_sales_follow_ups.clazz_id IN (?)", a).where("educode_sales_follow_ups.year <= ?", @year).sum(:budget_amount).round(2)
    b = Common.where(clazz: '商机类型', name: Common.find_by(extras: EducodeSales::Common::BTYPE)&.name).pluck(:id)
    @b_amount = Business.joins(:last_follow_up).where("educode_sales_follow_ups.clazz_id IN (?)", b).where("educode_sales_follow_ups.year <= ?", @year).sum(:budget_amount).round(2)
  end

end

#user_statObject



430
431
432
433
434
435
436
437
438
439
440
441
442
# File 'app/controllers/educode_sales/sale_trends_controller.rb', line 430

def user_stat
  respond_to do |format|
    format.html do

    end
    format.js do
      user_stat = EducodeSales::UserStatService.new
      gon.table_1 = user_stat.table_1
      gon.table_2 = user_stat.table_2(1)
      gon.table_3 = user_stat.table_3
    end
  end
end

#visit_analysisObject

拜访分析



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
# File 'app/controllers/educode_sales/sale_trends_controller.rb', line 445

def visit_analysis
  sort_by = params[:sort_by].present? ? params[:sort_by] : "desc"
  user_name = params[:user_name]
  visit_type = params[:visit_type].present? ? params[:visit_type].split(",") : ""
  title_names = %w[本年拜访数 本季拜访数 本月拜访数 本周拜访数]
  respond_to do |format|
    format.js do
      @user_names = EducodeSales::Attendance.pluck(:name).uniq.map{|d| {name: d, value: d}}
      @visit_types  = SaleTrend::VISIT_TYPE.map {|d| {name: d[0], value: d[1]}}
      sql = "SELECT name, count(*) as name_count FROM `educode_sales_attendances` WHERE (attendance_date >= '#{Time.now.beginning_of_year}' and attendance_date <= '#{Time.now.end_of_year}') group by name order by name_count desc limit 30"
      visit_count = EducodeSales::Attendance.find_by_sql(sql).map{|d| [d.name, d.name_count]}
      #年拜访量前30的用户名
      top_thirty_username = visit_count.map{ |d| d[0]}
      @visit_count_data = visit_user_type_name(top_thirty_username, sort_by, visit_type, title_names)
    end
    format.json do
      if params[:user_type].present? && params[:user_type] == "name"
        if user_name.present?
          sql_by_name = "SELECT name, count(*) as name_count FROM `educode_sales_attendances` WHERE (attendance_date >= '#{Time.now.beginning_of_year}' and attendance_date <= '#{Time.now.end_of_year}') and name like '%#{user_name}%' group by name"
        else
          sql_by_name = "SELECT name, count(*) as name_count FROM `educode_sales_attendances` WHERE (attendance_date >= '#{Time.now.beginning_of_year}' and attendance_date <= '#{Time.now.end_of_year}') group by name order by name_count desc limit 30"
        end
        visit_count = EducodeSales::Attendance.find_by_sql(sql_by_name).map{|d| [d.name, d.name_count]}
        #年拜访量前30的用户名
        top_thirty_username = visit_count.map{ |d| d[0]}
        @visit_count_data = visit_user_type_name(top_thirty_username, sort_by, visit_type, title_names)
      else
        if user_name.present?
          sql_by_customer = "SELECT name, customer, count(*) as customer_count FROM `educode_sales_attendances` WHERE (attendance_date >= '#{Time.now.beginning_of_year}' and attendance_date <= '#{Time.now.end_of_year}') and name like '%#{user_name}%' group by customer order by customer_count desc limit 30"
        else
          sql_by_customer = "SELECT name, customer, count(*) as customer_count FROM `educode_sales_attendances` WHERE (attendance_date >= '#{Time.now.beginning_of_year}' and attendance_date <= '#{Time.now.end_of_year}') group by customer order by customer_count desc limit 30"
        end
        visit_count = EducodeSales::Attendance.find_by_sql(sql_by_customer).map{|d| [d.customer, d.customer_count]}
        #年拜访量前30的用户名
        top_thirty_customer = visit_count.map{ |d| d[0]}
        @visit_count_data = visit_user_type_customer(top_thirty_customer, sort_by, visit_type, title_names)
      end
      render json: {data: @visit_count_data }
    end
  end
end