let UserError = require('vn-loopback/util/user-error'); module.exports = Self => { Self.remoteMethodCtx('updateQuantity', { description: 'Changes the quantity of a sale', accessType: 'WRITE', accepts: [{ arg: 'id', type: 'number', required: true, description: 'sale ID', http: {source: 'path'} }, { arg: 'quantity', type: 'number', required: true, description: 'newQuantity' }], returns: { type: 'string', root: true }, http: { path: `/:id/updateQuantity`, verb: 'post' } }); Self.updateQuantity = async(ctx, id, newQuantity) => { const $t = ctx.req.__; // $translate const models = Self.app.models; const canEditSale = await models.Sale.canEdit(ctx, [id]); if (!canEditSale) throw new UserError(`Sale(s) blocked, please contact production`); if (isNaN(newQuantity)) throw new UserError(`The value should be a number`); const filter = { include: { relation: 'ticket', scope: { include: { relation: 'client', scope: { include: { relation: 'salesPersonUser', scope: { fields: ['id', 'name'] } } } } } } }; const sale = await models.Sale.findById(id, filter); if (newQuantity > sale.quantity) throw new UserError('The new quantity should be smaller than the old one'); const oldQuantity = sale.quantity; const result = await sale.updateAttributes({quantity: newQuantity}); const salesPerson = sale.ticket().client().salesPersonUser(); if (salesPerson) { const origin = ctx.req.headers.origin; const message = $t('Changed sale quantity', { ticketId: sale.ticket().id, itemId: sale.itemFk, concept: sale.concept, oldQuantity: oldQuantity, newQuantity: newQuantity, ticketUrl: `${origin}/#!/ticket/${sale.ticket().id}/sale`, itemUrl: `${origin}/#!/item/${sale.itemFk}/summary` }); await models.Chat.sendCheckingPresence(ctx, salesPerson.id, message); } return result; }; };