articulos.js
2.23 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
var bookshelf = require('bookshelf')(knex);
const ArticuloImagen = bookshelf.Model.extend({
tableName: 'ARTICULOS_IMAGEN'
});
const Articulo = bookshelf.Model.extend({
tableName: 'ARTICULOS',
imagenes: function() {
return this.hasMany(ArticuloImagen, 'id_articulo', 'id');
}
});
router.get('/articulos', (req , res) => {
let cantidadesVendidas = knex.schema
.raw(`select stock.SEC, stock.ART, SUM(stock.can) as cantidadVendida
from AMOVSTOC stock
join ARTICULOS art on art.CodSec = stock.SEC and art.CodArt = stock.ART and
art.categoria_selfservice > 0 and art.PreVen > 0
where stock.FEC >= dateadd(month, -2, getdate()) and stock.CYV = 'V' and TCO = 'FT'
group by stock.sec, stock.art`)
var articulos = Articulo
.where((query) => {
query.where('NHA', 0);
query.where('PreVen', '>', 0);
query.where('categoria_selfservice', '>', 0);
})
.fetchAll({withRelated: ['imagenes']})
Promise.all([articulos, cantidadesVendidas])
.then(values => {
let articulos = values[0];
let cantidadesVendidas = values[1];
var promisesCodBar = [];
articulos.forEach(articulo => {
let cantidadVendida = cantidadesVendidas.filter(art => {
return articulo.get('CodArt') == art.ART && articulo.get('CodSec') == art.SEC;
});
articulo.set('cantidadVendida', cantidadVendida[0] ? cantidadVendida[0].cantidadVendida : 0);
promisesCodBar.push(
knex('CODBAR').where({
CodSec: articulo.get('CodSec'),
CodArt: articulo.get('CodArt')
})
);
});
Promise.all(promisesCodBar).then((codigoBarra) => {
codigoBarra.forEach(codigo => {
codigo = codigo[0];
let articulo = articulos.filter(art => {
return art.get('CodArt') == codigo.CodArt;
});
articulo[0].set('codigoBarra', codigo.CodBar);
});
res.status(200).send(articulos);
});
});
});
router.get('/articulos/:id', (req, res) => {
Articulo
.where({id: req.params.id})
.fetch({withRelated: 'imagenes'})
.then(articulo => res.status(200).send(articulo))
.catch(err => { res.status(500).send(err)})
});
module.exports = router;