sale-task.js
2.61 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
83
84
85
86
87
88
89
90
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();