sale-task.js 2.61 KB
const _ = require('lodash');
const {ProductRelationModel} = require('../models');
const {mysqlPool} = require('../libs/mysql');
const spider = require('../libs/spider');
const nodeLockup = require('node-lockup');
const {logger} = require('../libs/logger');

async function report({productId, soldNum}) {
  const updateTime = parseInt(Date.now() / 1000, 10);

  try {
    soldNum = parseInt(soldNum * 0.4, 10);

    const saleData = await mysqlPool.query('SELECT * FROM `product_sales` WHERE `product_id` = :productId AND `company_id` = 1', {
      productId
    });

    if (saleData.length === 0) {
      const insertRow = await mysqlPool.insert('INSERT `product_sales` (`amount`, `product_id`, `company_id`, `update_time`) VALUES (:soldNum, :productId, 1, :updateTime)', {
        productId,
        soldNum,
        updateTime
      });

      if (!insertRow) {
        logger.error(`[sale-task]插入product_sales表失败 ${JSON.stringify({productId, soldNum, updateTime})}`);
      }
    } else {
      const row = _.first(saleData);

      if (+row.amount < +soldNum) {
        const updateRows = await mysqlPool.update('UPDATE `product_sales` SET `amount` = :soldNum, `update_time` = :updateTime WHERE `product_id` = :productId AND `company_id` = 1', {
          productId,
          soldNum,
          updateTime
        });

        if (!updateRows) {
          logger.error(`[sale-task]更新product_sales表失败 ${JSON.stringify({productId, soldNum, updateTime})}`);
        }
      }
    }
  } catch (error) {
    logger.error(`[sale-task],${error}`);
  }
  logger.info(`[sale-task]更新成功, ${JSON.stringify({productId, soldNum, updateTime})}`);
  return Promise.resolve();
}
const lockReportTask = nodeLockup(report);

function spiderData(products) {
  const ids = products.map(p => p.duId);

  return spider(ids, '', {}, 1).forEach(promise => promise.then(result => {
    if (result && result.status === 200) {
      const {detail} = result.data;
      const find = _.find(products, p => p.duId === detail.productId);

      if (find) {
        lockReportTask({
          productId: find.productId,
          soldNum: detail.soldNum
        });
      }
    } else {
      console.log('[sale-task]', result);
    }
  }));
}


module.exports = async() => {
  const alls = await ProductRelationModel.findAll();
  const list = alls.filter(item => _.get(item, 'third.du.productId'));

  const chunks = _.chunk(list, 2000);

  chunks.forEach(chunk => {
    const products = chunk.map(item => {
      return {
        duId: item.third.du.productId,
        productId: item.productId
      };
    });

    spiderData(products);
  });
};

module.exports();