const UserError = require('vn-loopback/util/user-error'); module.exports = Self => { Self.remoteMethod('updateFromSale', { description: 'Update the visible items', accessType: 'WRITE', accepts: [{ arg: 'saleFk', type: 'number', required: true, }], http: { path: `/updateFromSale`, verb: 'POST' } }); Self.updateFromSale = async(saleFk, 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; } try { const itemShelvingSale = await models.ItemShelvingSale.findOne({ where: {saleFk}, include: {relation: 'itemShelving'} }, myOptions); if (!itemShelvingSale?.itemShelving()) throw new UserError('The sale not exists in the item shelving'); const itemShelving = itemShelvingSale.itemShelving(); const quantity = itemShelving.visible + itemShelvingSale.quantity; const available = itemShelving.available + itemShelvingSale.quantity; await itemShelving.updateAttributes( { visible: quantity, available: available }, myOptions ); if (tx) await tx.commit(); } catch (e) { if (tx) await tx.rollback(); throw e; } }; };