const UserError = require('vn-loopback/util/user-error'); module.exports = Self => { Self.remoteMethodCtx('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(ctx, params, options) => { const models = Self.app.models; const myOptions = {userId: ctx.req.accessToken.userId}; 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', 'priority', 'tag' ]; for (const key in params) { if (validUpdateParams.indexOf(key) === -1) throw new UserError(`You don't have enough privileges to do that`); } try { const itemConfig = await models.ItemConfig.findOne({fields: ['validPriorities']}, myOptions); if (!itemConfig.validPriorities.includes(params.priority)) throw new UserError('Valid priorities', 'VALID_PRIORITIES', [...itemConfig.validPriorities]); const provisionalName = params.provisionalName; delete params.provisionalName; const itemType = await models.ItemType.findById(params.typeFk, {fields: ['isLaid']}, myOptions); params.isLaid = itemType.isLaid; params.isPhotoRequested = true; 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); const nameTag = await models.Tag.findById(params.tag, {fields: ['id']}, myOptions); let newTags = []; newTags.push({itemFk: item.id, tagFk: nameTag.id, value: provisionalName, priority: item.priority}); typeTags.forEach(typeTag => { if (nameTag.id != typeTag.tagFk) 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; } }; };