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

92 lines
2.6 KiB
JavaScript

let UserError = require('vn-loopback/util/user-error');
module.exports = Self => {
Self.remoteMethod('new', {
description: 'returns the created item',
accessType: 'WRITE',
accepts: [{
arg: 'params',
type: 'object',
http: {source: 'body'}
}],
returns: {
type: 'number',
root: true
},
http: {
path: `/new`,
verb: 'post'
}
});
Self.new = async(params, options) => {
const models = Self.app.models;
const myOptions = {};
let tx;
if (typeof options == 'object')
Object.assign(myOptions, options);
if (!myOptions.transaction) {
tx = await Self.beginTransaction({});
myOptions.transaction = tx;
}
const 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`);
}
try {
const provisionalName = params.provisionalName;
delete params.provisionalName;
const itemType = await models.ItemType.findById(params.typeFk, myOptions);
params.isLaid = itemType.isLaid;
const item = await models.Item.create(params, myOptions);
const typeTags = await models.ItemTypeTag.find({
where: {itemTypeFk: item.typeFk}
}, myOptions);
let query = `SET @isTriggerDisabled = TRUE`;
await Self.rawSql(query, null, myOptions);
let nameTag = await 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 models.ItemTag.create(newTags, myOptions);
query = `SET @isTriggerDisabled = FALSE`;
await Self.rawSql(query, null, myOptions);
query = `CALL vn.itemRefreshTags(?)`;
await Self.rawSql(query, [item.id], myOptions);
if (tx) await tx.commit();
return item;
} catch (e) {
if (tx) await tx.rollback();
throw e;
}
};
};