product_cache.js
3.02 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
91
92
93
94
95
96
97
98
99
100
101
102
/**
*
* @author: chenfeng<feng.chen@yoho.cn>
* @date: 16/10/19
*/
'use strict';
const Router = require('koa-router');
const xlsx = require('node-xlsx');
const fs = require('fs');
const _ = require('lodash');
const {
ProductCache,
TempProductImport
} = require('../../models');
const r = new Router();
const productCache = {
async query(ctx) {
if (await TempProductImport.count({}) > 0) {
await TempProductImport.remove({});
}
await ctx.render('action/product_cache');
},
async import(ctx) {
if (await TempProductImport.count({}) > 0) {
await TempProductImport.remove({});
}
let excelFile = ctx.request.body._files && ctx.request.body._files.excelFile;
if (excelFile) {
let sheets = xlsx.parse(fs.readFileSync(excelFile.path));
let data = ProductCache.rendExcel(sheets);
await TempProductImport.insert(data);
let count = await TempProductImport.count({});
ctx.body = {
code: 200,
count
}
return;
}
ctx.body = {
code: 400
}
},
async clear(ctx) {
let type = ctx.request.body.type;
if (await TempProductImport.count({}) > 0) {
let data = await TempProductImport.findAll();
if (type) {
if (type === '1') {
ProductCache.removePriceCache(data)
} else if (type === '2') {
ProductCache.removeProductCache(data)
}
ctx.body = {
code: 200
}
return;
}
} else {
ProductCache._broadcast('请导入商品');
}
ctx.body = {
code: 400
}
},
async downloadProductUrl(ctx) {
if (await TempProductImport.count({}) > 0) {
let data = await TempProductImport.findAll();
let productUrls = await ProductCache.generateProductUrl(data);
let domains = {'PC': 'http://www.yohobuy.com', 'WAP': 'https://m.yohobuy.com'};
let resultData = [];
_.forEach(domains, (value, key) => {
let rows = [['URL']];
_.forEach(productUrls, url => {
rows.push([value + url]);
});
resultData.push({name: key, data: rows});
});
var buffer = xlsx.build(resultData);
ctx.status = 200;
ctx.set('Content-disposition', 'attachment; filename=output.xlsx');
ctx.set('Content-type', 'application/vnd.ms-excel');
ctx.body = buffer;
return;
} else {
ProductCache._broadcast('请导入商品');
}
ctx.body = {
code: 400
}
}
}
r.get('/query', productCache.query);
r.post('/import', productCache.import);
r.post('/clear', productCache.clear);
r.get('/product_url', productCache.downloadProductUrl);
module.exports = r;