calc-task.js 2.02 KB
const dayjs = require('dayjs');
const _ = require('lodash');
const {logger} = require('../libs/logger');
const {mysqlPool} = require('../libs/mysql');
const {sendMessage} = require('../libs/influx-report');

module.exports = async() => {
  const beginTime = dayjs().subtract(24, 'hour').unix();
  const endTime = dayjs().unix();

  const records = await mysqlPool.query('SELECT CONCAT(`product_id`, \'_\', `size_id`) AS `key`, `product_id`, `size_id`, `channel_price` FROM `channel_sku_compare_record` WHERE `create_time` BETWEEN :beginTime AND :endTime', {
    beginTime,
    endTime
  });

  const skuGroups = _.groupBy(records, 'key');

  _.each(skuGroups, async(list, key) => {
    if (list.length < 3) {
      return;
    }
    const sortList = _.sortBy(list, 'channel_price');
    const prices = sortList.map(p => p.channel_price);
    const avgPrice = _.mean(_.dropRight(_.drop(prices)));

    if (!avgPrice) {
      logger.error(`[calc-task]计算平均价格错误, key: ${key}, avgPrice: ${avgPrice}, size: ${list.length}, beginTime: ${beginTime}, endTime: ${endTime}`);
      sendMessage(1, new Date().getTime() * 1000000, 'ufo-calc-error');
      return;
    }
    try {
      const productId = key.split('_')[0];
      const sizeId = key.split('_')[1];

      const changeRows = await mysqlPool.update('UPDATE `channel_sku_compare` SET `channel_average_price` = :avgPrice  WHERE `product_id` = :productId AND `size_id` = :sizeId', {
        avgPrice,
        productId,
        sizeId
      });

      if (changeRows <= 0) {
        logger.error(`[calc-task]更新平均价格失败, key: ${key}, avgPrice: ${avgPrice}, beginTime: ${beginTime}, endTime: ${endTime}`);
        sendMessage(1, new Date().getTime() * 1000000, 'ufo-calc-error');
      } else {
        logger.info(`[calc-task]更新计算平均价成功, key: ${key}, price: ${avgPrice}`);
      }
    } catch (error) {
      sendMessage(1, new Date().getTime() * 1000000, 'ufo-calc-error');
      logger.error(`[calc-task]更新平均价格错误, error: ${error.stack}`);
    }
  });

};