shenjian.js 2.51 KB
const _ = require('lodash');
const {logger} = require('../../../libs/logger');
const sjApi = require('../../../libs/sj-api');

const processSkus = (data, productCode, sizeRelation) => {
  const skuDetail = _.get(data, 'product_sku_detail', []);
  const colorAttr = _.get(data, 'sku', []).find(s => s.label === '颜色分类');
  const sizeAttr = _.get(data, 'sku', []).find(s => s.label === '鞋码');

  if (!colorAttr || !sizeAttr ||
    _.get(colorAttr, 'values', []).length === 0 ||
    _.get(sizeAttr, 'values', []).length === 0) {
    logger.error(`[price-line-task] ${data.__id} colorAttr or sizeAttr no data, ${JSON.stringify(colorAttr)}, ${JSON.stringify(sizeAttr)}`);
    return [];
  }
  let colorNumber;

  if (colorAttr.values.length > 1) {
    colorNumber = (colorAttr.values.find(v => v.desc === productCode) || {}).number;
  } else {
    colorNumber = _.first(colorAttr.values).number;
  }

  if (!colorNumber) {
    logger.error(`[price-line-task] ${data.__id} no colorNumber`);
    return [];
  }
  return _.map(sizeRelation, (val, size) => {
    const findSize = _.find(sizeAttr.values, v => v.desc === size || v.desc === `${size}码`);

    if (findSize) {
      const findSku = _.find(skuDetail, sku => sku.sku_number === `;${findSize.number};${colorNumber};`);

      if (findSku && +findSku.sku_price > 0 && +findSku.sku_stock > 0) {
        return {
          size,
          price: +findSku.sku_price
        };
      }
    }
  }).filter(s => s);
};

const mergeSkus = skuGroups => {
  const allSkus = [].concat(...skuGroups);
  const sizeSet = new Set(allSkus.map(sku => sku.size));

  return _.map(Array.from(sizeSet), size => {
    const filterSkus = _.filter(allSkus, sku => sku.size === size);
    const sumPrice = _.sumBy(filterSkus, 'price');

    if (sumPrice > 0) {
      return {
        size,
        price: _.parseInt(sumPrice / filterSkus.length)
      };
    }
  }).filter(s => s);
};

module.exports = async(third, productCode, sizeRelation) => {
  try {
    if (!third || third.length === 0) {
      return void 0;
    }
    const res = await sjApi(`source(__id:{in: ${JSON.stringify(third)}}){data{}}`);

    if (res.code !== 0) {
      logger.error(`[price-line-task]sjApi failed, ${JSON.stringify(third)}, ${JSON.stringify(res)}`);
      return void 0;
    }

    const skuGroups = _.map(_.get(res, 'result.data', []), data =>
      processSkus(data, productCode, sizeRelation));

    return {
      skus: mergeSkus(skuGroups)
    };
  } catch (error) {
    logger.error(`[price-line-task] shenjian spider, ${error}`);
  }
};