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

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(`计算平均价格错误, key: ${key}, avgPrice: ${avgPrice}, size: ${list.length}, beginTime: ${beginTime}, endTime: ${endTime}`);
      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(`更新平均价格失败, key: ${key}, avgPrice: ${avgPrice}, beginTime: ${beginTime}, endTime: ${endTime}`);
      } else {
        logger.info(`更新计算平均价成功, key: ${key}, price: ${avgPrice}`);
      }
    } catch (error) {
      logger.error(`更新平均价格错误, error: ${error.stack}`);
    }
  });

};