salix/modules/item/back/methods/item/new.js

74 lines
2.2 KiB
JavaScript

let UserError = require('vn-loopback/util/user-error');
module.exports = Self => {
Self.remoteMethod('new', {
description: 'Create a new item and returns the new ID',
accessType: 'WRITE',
accepts: [{
arg: 'params',
type: 'object',
http: {source: 'body'}
}],
returns: {
type: 'number',
root: true
},
http: {
path: `/new`,
verb: 'post'
}
});
Self.new = async params => {
let validUpdateParams = [
'provisionalName',
'typeFk',
'intrastatFk',
'originFk',
'relevancy'
];
for (const key in params) {
if (validUpdateParams.indexOf(key) === -1)
throw new UserError(`You don't have enough privileges to do that`);
}
let tx = await Self.beginTransaction({});
try {
let options = {transaction: tx};
let provisionalName = params.provisionalName;
delete params.provisionalName;
let item = await Self.app.models.Item.create(params, options);
let typeTags = await Self.app.models.ItemTypeTag.find({where: {itemTypeFk: item.typeFk}});
let query = `SET @isTriggerDisabled = TRUE`;
await Self.rawSql(query, null, options);
let nameTag = await Self.app.models.Tag.findOne({where: {name: 'Nombre temporal'}});
let newTags = [];
newTags.push({itemFk: item.id, tagFk: nameTag.id, value: provisionalName, priority: '2'});
typeTags.forEach(typeTag => {
newTags.push({itemFk: item.id, tagFk: typeTag.tagFk, value: '', priority: typeTag.priority});
});
await Self.app.models.ItemTag.create(newTags, options);
query = `SET @isTriggerDisabled = FALSE`;
await Self.rawSql(query, null, options);
query = `CALL vn.itemRefreshTags(?)`;
await Self.rawSql(query, [item.id], options);
await tx.commit();
return item;
} catch (e) {
await tx.rollback();
throw e;
}
};
};