salix/modules/item/back/models/item.js

73 lines
2.7 KiB
JavaScript

let UserError = require('vn-loopback/util/user-error');
module.exports = Self => {
require('../methods/item/filter')(Self);
require('../methods/item/clone')(Self);
require('../methods/item/updateTaxes')(Self);
require('../methods/item/getBalance')(Self);
require('../methods/item/lastEntriesFilter')(Self);
require('../methods/item/getSummary')(Self);
require('../methods/item/getCard')(Self);
require('../methods/item/regularize')(Self);
require('../methods/item/getVisibleAvailable')(Self);
require('../methods/item/new')(Self);
require('../methods/item/getWasteByWorker')(Self);
require('../methods/item/getWasteByItem')(Self);
require('../methods/item/createIntrastat')(Self);
require('../methods/item/activeBuyers')(Self);
require('../methods/item/buyerWasteEmail')(Self);
require('../methods/item/labelPdf')(Self);
Self.validatesPresenceOf('originFk', {message: 'Cannot be blank'});
Self.observe('before save', async function(ctx) {
let instance = ctx.currentInstance;
let oldInstance;
let newInstance;
ctx.hookState.oldInstance === undefined ? oldInstance = false : oldInstance = ctx.hookState.oldInstance;
ctx.hookState.newInstance === undefined ? newInstance = false : newInstance = ctx.hookState.newInstance;
if (oldInstance.image && newInstance.image) {
let image = newInstance.image.split('-')[0];
let user = newInstance.image.split('-')[1];
ctx.hookState.newInstance.image = image;
let query = `UPDATE vn.item SET doPhoto=0 WHERE id = ${instance.id}`;
await Self.rawSql(query);
let logQuery =
'INSERT INTO vn.itemLog(originFk, userFk, action, creationDate, description, oldInstance, newInstance) ' +
'VALUES (?, ?, ?, ?, ?, ?, ?)';
let logParams = [
instance.id,
user,
'update',
new Date(),
'Image',
JSON.stringify(oldInstance),
JSON.stringify(newInstance)
];
await Self.rawSql(logQuery, logParams);
}
await Self.availableId(ctx);
});
Self.availableId = async function(ctx) {
if (ctx.isNewInstance) {
try {
let query = `SELECT i1.id + 1 as id FROM vn.item i1
LEFT JOIN vn.item i2 ON i1.id + 1 = i2.id
WHERE i2.id IS NULL ORDER BY i1.id LIMIT 1`;
let newId = await Self.rawSql(query);
ctx.instance.id = newId[0].id;
return ctx.instance.id;
} catch (e) {
throw new UserError(e);
}
}
};
};