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

module.exports = async() => {
  const now = dayjs();
  let insertTime;

  if (now.hour() > 12) {
    insertTime = now.startOf('day').add(12, 'hour');
  } else {
    insertTime = now.startOf('day');
  }
  const resultExists = await mysqlPool.query('SELECT 1 AS Num FROM `price_trend_month` WHERE `create_time` = :createTime limit 1', {
    createTime: insertTime.unix()
  });

  if (resultExists.length > 0) {
    logger.info(`[price-30day-task] exists createtime price: ${insertTime.unix()}`);
    return;
  }
  const leastDay = await mysqlPool.query('SELECT MAX(`create_time`) AS create_time FROM `price_trend_day`');

  if (leastDay.length) {
    const dayTime = _.first(leastDay).create_time;

    if (dayTime) {
      const {affectedRows} = await mysqlPool.execute('INSERT INTO `price_trend_month` (`product_id`, `size_id`, `skn_price`, `sku_price`, `create_time`) SELECT `product_id`, `size_id`, `skn_price`, `sku_price`, :insertTime FROM `price_trend_day` WHERE `create_time` = :createTime', {
        createTime: dayTime,
        insertTime: insertTime.unix()
      });

      logger.info(`[price-30day-task] insert ${affectedRows}`);
      sendMessage(affectedRows, new Date().getTime() * 1000000, 'price-30day-task-inserted');
    }
  }
};