const UserError = require('vn-loopback/util/user-error'); module.exports = Self => { Self.remoteMethodCtx('addToOrder', { description: 'Creates rows (lines) for a order', accessType: 'WRITE', accepts: [{ arg: 'params', type: 'object', required: true, description: 'order id, [items]', http: {source: 'body'} }], returns: { type: 'object', root: true }, http: { path: `/addToOrder`, verb: 'POST' } }); Self.addToOrder = async(ctx, params, options) => { 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; } try { const isEditable = await Self.app.models.Order.isEditable(params.orderFk, myOptions); if (!isEditable) throw new UserError('This order is not editable'); const promises = []; for (const item of params.items) { promises.push( Self.rawSql( `CALL hedera.order_addItem(?, ?, ?, ?)`, [params.orderFk, item.warehouseFk, item.itemFk, item.quantity], myOptions ) ); } await Promise.all(promises); if (tx) await tx.commit(); return true; } catch (e) { if (tx) await tx.rollback(); throw e; } }; };