shenjian.js
2.51 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
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}`);
}
};