merchant.js 9.96 KB
/*
 * @Author: limin
 * @Date: 2019-11-21 11:20:01
 * @Last Modified by: limin
 * @Last Modified time: 2020-01-08 13:44:11
 */

"use strict";

const Controller = require("egg").Controller;
/**
 * @Controller screen/merchant
 * @Description 数据大屏-商户
 */
class MerchantController extends Controller {
  constructor(ctx) {
    super(ctx);
    this.validate = ctx.app.validator.validate;
    this.request = ctx.request;
    this.helper = ctx.helper;
    this.redis = ctx.app.redis;
    this.MerchantService = ctx.service.screen.merchant;
    this.CacheService = ctx.service.cache; //redis 缓存服务
    this.ServerResponseCode = ctx.response.ServerResponseCode;
    this.ServerResponse = ctx.response.ServerResponse;
    this.queue = ctx.app.merchant_queue;
  }


   /**
   * 从内存获取日期(昨天,今天)
   */
  async _fetch_date_in_cache_(){
    const { DATES } = this.helper.constant;
    return await this.CacheService.get(DATES);
  }


  /**
   * 对比和获取内存中的数据(总共30天,每天通过定时任务更新)
   * 如果获取的时候数据还是最新则手动触发定时任务更新一次
   */
  async _compare_get_(isRunTask,type = this.helper.constant.MERCHANT_SUMMARY_30_DAY){
    var { yesterday, cache_data_last_date_merchant } = await this._fetch_date_in_cache_();
    if(!this.helper.moment(cache_data_last_date_merchant).isSame(yesterday) && isRunTask){ //如果 内存中的数据的日期不是昨天的 则手动启动定时器 更新缓存数据
      await this.app.runSchedule('update_cache_merchant');
    }
    const summary = await this.CacheService.get(type) || [];
    return summary
  }

   /**
   * 内部方法 从内存获取 昨天的统计数据 
   * 比较数据时间 如果不是昨天的数据 则启动定时任务 更新一遍数据 再次获取数据并返回
   */
  async _fetch_summary_( { beginDate,endDate,isGetLast }, fn ){ 
    var summary_30_day= await this._compare_get_(isGetLast);
    const { moment } =this.helper
    var result=[];
    if(isGetLast){
      const { cache_data_last_date_merchant } = await this._fetch_date_in_cache_();
      result = [summary_30_day[cache_data_last_date_merchant]];
      fn && fn(cache_data_last_date_merchant,summary_30_day[cache_data_last_date_merchant])
    }else if(beginDate){
      endDate = endDate || beginDate;
      if(moment(beginDate).isSame(endDate) ){
        result.push(summary_30_day[beginDate])
        fn && fn(beginDate,summary_30_day[beginDate])
      }else{
        for(const day in summary_30_day){
          if(moment(day).isBetween(beginDate,endDate) 
            || moment(day).isSame(beginDate)
            || moment(day).isSame(endDate)){
            result.push(summary_30_day[day])
            fn && fn(day,summary_30_day[day])
          }
        }
      }
    }else{
      if(fn){
        for(const day in summary_30_day){
          await fn(day,summary_30_day[day])
        }
      }
      result = Object.values(summary_30_day)
    }
    return result ||[]
  }
  async _fetch_total_({ field,isGetLast } ){
    const _summary =  await this._fetch_summary_({isGetLast});
    // return this._set_(field,async (f)=>_summary[f]||0);
     const result = await this._set_(field,(f)=>_summary.reduce((pre,next)=>pre + +next[f],0));
     return result
  }

   /**
   * 内部方法 从内存获取 范围时间内的数据
   */
  async _fetch_detail_by_range_({ pid,field, beginDate,endDate } ){
    var res = []
    var _set = this._set_
    var data = null
    await this._fetch_summary_({ beginDate, endDate },async (day,value)=>{
      var fn = null;
      if (pid) {
        fn = async f=>value && value['p'][pid] ? value['p'][pid][f]:0
      }else{
        fn = async f=>value ? value[f]:0
      }
      data = await _set(field,fn);
      res.push({ day, data }) 
    });
    return res;
  }

   /**
   * 内部帮助方法
   * @param {*} field 
   * @param {*} fn 
   */
  async _set_(field,fn){
    var total;
    if(typeof field ==='string'){
      total = await fn(field)
    }else{
      total = {}
      for (const f of field) {
        total[f] = await fn(f)
      }
    }
    return total;
  }

  /**
   * 内部帮助方法
   * @param {*} field 
   * @param {*} fn 
   */
  async _get_stats(field){
    const result = await this._compare_get_(true,this.helper.constant.MERCHANT_SUMMARY_STATS);
    return await this._set_(field,f=>result[f])
  }

  /**
   * @Router GET /screen/merchant/total
   * @Description 数据大屏-商户总数统计.---- 广联商户总数(merchant_total)  商户累计订单数(order_total)  当日订单数(realtime_new_order) 当日活跃商户(active_merchant) 
   */
  async total() {
    let {  total_merchant:merchant_total, total_order:order_total } = await this._fetch_total_({ field:['total_merchant','total_order'],isGetLast:true})
    // var merchant_total = await this._fetch_total_({ field:'total_merchant',isGetLast:true})
    // var order_total = await this._fetch_total_({ field:'total_order',isGetLast:true})
    const realtime = await this.MerchantService.merchant_realtime();
    const realtime_new_order = realtime.reduce((pre,next)=>pre + +next['new_order'],0);
    const realtime_new_merchant = realtime.reduce((pre,next)=>pre + +next['new_merchant'],0);
    const active_merchant = realtime.reduce((pre,next)=>pre + +next['active_merchant'],0);
    merchant_total += ~~realtime_new_merchant;
    order_total += ~~realtime_new_order;
    const data = { merchant_total, order_total, realtime_new_order, active_merchant };
    this.ctx.body = this.ServerResponse.Success(data);
  }
  /**
   * @Router GET /screen/merchant/statistics
   * @Description 数据大屏-数据统计 1.近七天订单数(recent_7day_order)2.商户订购设备数(total_device)3.商户订购设备总额(total_amount)4.商户活跃度(active_percent)
   * @Request query integer pid 省份id
   */
  async statistics() {
    const {recent_7day_order,total_device,total_amount,recent_merchant,active_merchant} 
    = 
    await this._fetch_total_({ field:['recent_7day_order','total_device','total_amount','recent_merchant','active_merchant'],isGetLast:true})
    const active_percent = this.helper.percent(active_merchant,recent_merchant)
    const data = { recent_7day_order,total_device , total_amount,active_percent}
    this.ctx.body = this.ServerResponse.Success(data);
  }
   /**
   * @Router GET /screen/merchant/trend
   * @Description 数据大屏-1 商户订单趋势(merchant_data today_device_order:当日设备订单数量,today_insurance_order:当日保险订单数量,today_repair_order:当日送修订单数量,today_maintain_order:当日保养订单数量) 2.设备订购趋势(order_trend), 3.商户活跃度(active_merchant/recent_merchant) 4:(活跃商户数 active_merchant)
   */
  async trend() {
    const { active_trend:active, order_trend}  = await this._get_stats(['order_trend','active_trend'])  //月度数据
    const merchant_data  =  await this._fetch_detail_by_range_({ field:['today_device_order','today_insurance_order','today_repair_order','today_maintain_order' ]});
    const active_merchant  =  await this._fetch_detail_by_range_({ field:['active_merchant']});
    const data = { order_trend,merchant_data,active,active_merchant }
    this.ctx.body = this.ServerResponse.Success(data);
  }

  /**
   * @Router GET /screen/merchant/device_order_stat
   * @Description 数据大屏-设备订单统计 1.商户订单类型分布(order_type) 2.订购设备类型分布(device_type) 3商户类型分布(merchant_type) 4订单数量区域排名(order_sort) 5:商户渠道分布(channel) 6:每个省对应的商户数(merchants)
   * @Request query integer n 近N天数据 默认 30天 
   * @Request query string beginDate 查询开始时间 (2019-12-12)
   * @Request query string endDate 查询结束时间 (2019-12-12)
   */
  async device_order_stat() {
    const { type_4s , type_weixiu , type_yingai , type_jingpin ,type_meibao,type_jingxiao ,maintain_order ,repair_order ,insurance_order ,device_order  } 
    =  
    await this._fetch_total_({field:[ 'type_4s', 'type_weixiu', 'type_yingai', 'type_jingpin','type_meibao','type_jingxiao', 'maintain_order','repair_order','insurance_order','device_order' ],isGetLast:true})
    //订单数量区域排名
    const last = await this._fetch_summary_({isGetLast:true});
    const order_sort = []
    const merchants = []
    const province = last[0].p

    for (const key in province) {
      if(key ==='0') continue
      order_sort.push({prov_code:key,value:province[key].total_order})
      merchants.push({prov_code:key,value:province[key].total_merchant})
    }
    order_sort.sort((a,b)=>b.value-a.value).length = 10
    // const channel = await this.MerchantService.channel_stat({limit:6})
    // const device_type = await this.MerchantService.device_type()
    const { channel,device_type }  = await this._get_stats(['channel','device_type'])
    const data = {
      merchant_type : { type_4s, type_weixiu, type_yingai, type_jingpin,type_meibao,type_jingxiao }, // 商户类型
      order_type: { maintain_order,repair_order,insurance_order,device_order }, // 商户订单类型分布 
      order_sort,  //订单数量区域排名
      channel,  // 商户渠道分布
      device_type, //订购设备类型分布
      merchants // 每个省对应的商户数
    }
    this.ctx.body = this.ServerResponse.Success(data);
  }

  /**
   * @Router GET /screen/merchant/activation
   * @Description 实时激活数据播报 订单类型(order_type):0:设备激活 1:订购设备 2:保险下单 3:维修订单 4:保养
   * @Request query integer pid 省份id
   */
  async activation({ query: { pid } }) {
    const data = this.queue.peek();
    // const { MERCHANT_ACTIVE_DATA_LASI_ID } = this.helper.constant;
    // const _last_id = await this.CacheService.get(MERCHANT_ACTIVE_DATA_LASI_ID);
    // this.queue.fill(async ()=>await this.MerchantService.activation({ pid, limit: this.queue.size(), last_id:_last_id }))
    // .then(last_id=>last_id && this.CacheService.set(MERCHANT_ACTIVE_DATA_LASI_ID,last_id))
    this.ctx.body = this.ServerResponse.Success(data);
  }
}

module.exports = MerchantController;