calc-task.js
1.79 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
const dayjs = require('dayjs');
const _ = require('lodash');
const {logger} = require('../libs/logger');
const {mysqlPool} = require('../libs/mysql');
module.exports = async() => {
mysqlPool.delete('update `channel_sku_compare` set `channel_average_price` = 0');
const beginTime = dayjs().subtract(24, 'hour').unix();
const endTime = dayjs().unix();
const records = await mysqlPool.query('SELECT CONCAT(`product_id`, \'_\', `size_id`) AS `key`, `product_id`, `size_id`, `channel_price` FROM `channel_sku_compare_record` WHERE `create_time` BETWEEN :beginTime AND :endTime', {
beginTime,
endTime
});
const skuGroups = _.groupBy(records, 'key');
_.each(skuGroups, async(list, key) => {
if (list.length < 3) {
return;
}
const sortList = _.sortBy(list, 'channel_price');
const prices = sortList.map(p => p.channel_price);
const avgPrice = _.mean(_.dropRight(_.drop(prices)));
if (!avgPrice) {
logger.error(`计算平均价格错误, key: ${key}, avgPrice: ${avgPrice}, size: ${list.length}, beginTime: ${beginTime}, endTime: ${endTime}`);
return;
}
try {
const productId = key.split('_')[0];
const sizeId = key.split('_')[1];
const changeRows = await mysqlPool.update('UPDATE `channel_sku_compare` SET `channel_average_price` = :avgPrice WHERE `product_id` = :productId AND `size_id` = :sizeId', {
avgPrice,
productId,
sizeId
});
if (changeRows <= 0) {
logger.error(`更新平均价格失败, key: ${key}, avgPrice: ${avgPrice}, beginTime: ${beginTime}, endTime: ${endTime}`);
} else {
logger.info(`更新计算平均价成功, key: ${key}, price: ${avgPrice}`);
}
} catch (error) {
logger.error(`更新平均价格错误, error: ${error.stack}`);
}
});
};