update_cache_merchant.js 10.1 KB
const Subscription = require("egg").Subscription;

class UpdateCacheMerchant extends Subscription {
  constructor(ctx) {
    super(ctx);
    this.MerchantService = ctx.service.screen.merchant;
    this.helper = ctx.helper;
    this.CacheService = ctx.service.cache; //redis 缓存服务
  }
  /*  
  *    *    *    *    *    *
  ┬    ┬    ┬    ┬    ┬    ┬
  │    │    │    │    │    |
  │    │    │    │    │    └ 星期 (0 - 7) (0或7都是星期日)
  │    │    │    │    └───── 月份 (1 - 12)
  │    │    │    └────────── 日期 (1 - 31)
  │    │    └─────────────── 小时 (0 - 23)
  │    └──────────────────── 分钟 (0 - 59)
  └───────────────────────── 秒 (0 - 59, optional)
  */
  // 通过 schedule 属性来设置定时任务的执行间隔等配置
  static get schedule() {
    return {
      // interval: '1m', // 定时任务 1 分钟间隔
      cron: "0 30 6 * * *", // 定点任务 每天 凌晨 6点30 执行一次
      type: "worker", // 随机 worker 执行
      immediate: true //启动立即执行一次
      // disable:true // 不启动
    };
  }

  _group(merchants, f) {
    const data = {
    };
    var date= this.app.config.sys.init_date;
    function __init_or_plus__(target, obj) {
      target = target || {};
      if (obj) {
        const { total_merchant, total_device, total_amount, active_merchant, use_sys_merchant, total_order, today_order, 
          recent_7day_order, recent_7day_active, recent_7day_use,maintain_order,repair_order,insurance_order,device_order,
          type_4s,type_weixiu,type_yingai,type_jingpin,type_meibao,type_jingxiao,recent_merchant,
          today_device_order,today_insurance_order,today_repair_order,today_maintain_order } = obj;
        target["total_merchant"] += +total_merchant; //商户总数
        target["total_device"] += +total_device; //订购设备总数
        target["total_amount"] += parseFloat(total_amount); // 订购设备总额
        target["active_merchant"] += +active_merchant; // 活跃商户
        target["use_sys_merchant"] += +use_sys_merchant; // 使用的商户
        target["total_order"] += +total_order; // 累计订单数
        target["today_order"] += +today_order; // 当日订单数
        target["recent_7day_order"] += +recent_7day_order; // 近7日订单数
        target["recent_7day_active"] += +recent_7day_active; // 近7日活跃商户数
        target["recent_7day_use"] += +recent_7day_use; // 近7日使用商户数
        target["maintain_order"] += +maintain_order; // 保养订单数量
        target["repair_order"] += +repair_order; // 送修订单数量
        target["insurance_order"] += +insurance_order; // 保险订单数量
        target["device_order"] += +device_order; // 保险订单数量
        target["type_4s"] += +type_4s; // 商户类型:4S店
        target["type_weixiu"] += +type_weixiu; //商户类型:维修店
        target["type_yingai"] += +type_yingai; // 商户类型:音改店
        target["type_jingpin"] += +type_jingpin; //商户类型:精品店
        target["type_meibao"] += +type_meibao; // 商户类型:美保店
        target["type_jingxiao"] += +type_jingxiao; // 商户类型:经销商
        target["recent_merchant"] += +recent_merchant; // 近活跃商户
        target["today_device_order"] += +today_device_order; // 当日设备订单数量
        target["today_insurance_order"] += +today_insurance_order; // 当日保险订单数量
        target["today_repair_order"] += +today_repair_order; // 当日送修订单数量
        target["today_maintain_order"] += +today_maintain_order; // 当日保养订单数量
      } else {
        target["total_merchant"] = 0; //商户总数
        target["total_device"] = 0; //订购设备总数
        target["total_amount"] = 0.00; // 订购设备总额
        target["active_merchant"] = 0; // 活跃商户
        target["use_sys_merchant"] = 0; // 使用的商户
        target["total_order"] = 0; // 累计订单数
        target["today_order"] = 0; // 当日订单数
        target["recent_7day_order"] = 0; // 近7日订单数
        target["recent_7day_active"] = 0; // 近7日活跃商户数
        target["recent_7day_use"] = 0; // 近7日使用商户数
        target["maintain_order"] = 0; // 保养订单数量
        target["repair_order"] = 0; // 送修订单数量
        target["insurance_order"] = 0; // 保险订单数量
        target["device_order"] = 0; // 保险订单数量
        target["type_4s"] = 0; // 商户类型:4S店
        target["type_weixiu"] = 0; //商户类型:维修店
        target["type_yingai"] = 0; // 商户类型:音改店
        target["type_jingpin"] = 0; //商户类型:精品店
        target["type_meibao"] = 0; // 商户类型:美保店
        target["type_jingxiao"] = 0; // 商户类型:经销商
        target["recent_merchant"] = 0; //近活跃商户
        target["today_device_order"] = 0; //当日设备订单数量
        target["today_insurance_order"] = 0; //当日保险订单数量
        target["today_repair_order"] = 0; //当日送修订单数量
        target["today_maintain_order"] = 0; //当日保养订单数量
      }
      return target;
    }
    merchants.forEach(
      function(merchant) {
        const prov_code = f(merchant);
        let { total_merchant, total_device, total_amount, active_merchant, use_sys_merchant, total_order, today_order, 
          recent_7day_order, recent_7day_active, recent_7day_use,maintain_order,repair_order,insurance_order,device_order,
          type_4s,type_weixiu,type_yingai,type_jingpin,type_meibao,type_jingxiao,recent_merchant,
          today_device_order,today_insurance_order,today_repair_order,today_maintain_order,day} = merchant;
        date = this.helper.moment(day).isAfter(date) ? day : date;
        data[day] = data[day] || Object.assign(__init_or_plus__(null),{'p':{}}) //如果day 节点不存在 则 初始化一个
        data[day] = __init_or_plus__(data[day], { total_merchant, total_device, total_amount, active_merchant, use_sys_merchant, total_order, today_order, 
          recent_7day_order, recent_7day_active, recent_7day_use,maintain_order,repair_order,insurance_order,device_order,
          type_4s,type_weixiu,type_yingai,type_jingpin,type_meibao,type_jingxiao,recent_merchant,
          today_device_order,today_insurance_order,today_repair_order,today_maintain_order }); // 累加全国总数值
        data[day]["p"][prov_code] = { total_merchant, total_device, total_amount, active_merchant, use_sys_merchant, total_order, today_order, 
          recent_7day_order, recent_7day_active, recent_7day_use,maintain_order,repair_order,insurance_order,device_order,
          type_4s,type_weixiu,type_yingai,type_jingpin,type_meibao,type_jingxiao,recent_merchant,
          today_device_order,today_insurance_order,today_repair_order,today_maintain_order  };
      }.bind(this)
    );
    return { data, date };
  }

  // subscribe 是真正定时任务执行时被运行的函数
  async subscribe() {
    this.logger.info("===============执行日常任务-缓存每日统计数据(商户总30天) begin==================");
    const { moment, constant } = this.helper;
    const { DATES,MERCHANT_SUMMARY_30_DAY,MERCHANT_SUMMARY_STATS } = constant;
    const dates = await this.CacheService.get(DATES);
    var   { cache_update_time_merchant, cache_data_last_date_merchant } = dates
    const { user_cache_update_time_diff } = this.app.config.sys;
    if( moment().diff(moment(cache_update_time_merchant)) < user_cache_update_time_diff ) {
      this.logger.info( "=============== 距离上一次更新不到 %s 毫秒.不执行更新操作 ==================",user_cache_update_time_diff );
      return ;
    }
    const yesterday = this.helper.date(-1);
    const day30before = this.helper.date(-30);
    //  查询昨天 所有城市 分别 对应的 用户总数 列表
    const _merchants_daily = await this.MerchantService.merchant_summary_by_day({beginDate: day30before, endDate: yesterday})
    if (_merchants_daily.length) {
      var {data, date } = this._group(_merchants_daily, merchant => merchant.prov_code);
      if( moment(date).isAfter( cache_data_last_date_merchant) ){ //当前数据最新时间 大于 上一次缓存数据的最新时间 才写入缓存
        await this.CacheService.set(
          MERCHANT_SUMMARY_30_DAY,
          data
        );
        cache_data_last_date_merchant = date
        // STAT 
        const _last_month_ =moment().format('YYYY-MM')
        const _last_month_7 =moment().subtract(7, 'months').format('YYYY-MM')
        const _order_trend = await this.MerchantService.device_order({beginDate: _last_month_7, endDate: _last_month_})  //设备订购趋势
        const _active_trend = await this.MerchantService.active_trend({beginDate: _last_month_7, endDate: _last_month_})  //商户激活月度数据
        const _channel_stat = await this.MerchantService.channel_stat({limit: 6}) //商户渠道分布
        const _device_type = await this.MerchantService.device_type() //订购设备类型分布
        const _stats={
          'order_trend':_order_trend,  //设备订购趋势
          'active_trend':_active_trend,// 商户激活
          'channel':_channel_stat,//商户渠道分布
          'device_type':_device_type //订购设备类型分布
        }
        await this.CacheService.set(
          MERCHANT_SUMMARY_STATS,
          _stats
        );
        this.logger.info("merchant_summary_%s",date);
      }else{
        this.logger.info("cache_date:%s date:%s 不写缓存",cache_data_last_date_merchant,date);
      }
    }else {
      this.logger.warn("warnning=============merchant_summary_30_day===========is empty!");
    }
    dates.cache_data_last_date_merchant = cache_data_last_date_merchant
    dates.cache_update_time_merchant = moment()
    //缓存日期.方便业务使用
    await this.CacheService.set(DATES,dates);
    this.logger.info("===============执行日常任务-缓存每日商户统计数据(商户总30天) end==================");
  }
}

module.exports = UpdateCacheMerchant;