module.exports = Self => { Self.remoteMethod('moveToNewTicket', { description: 'Change the state of a ticket', accessType: '', accepts: [{ arg: 'ticketParams', type: 'object', required: true, description: '[sales IDs], newTicketFk, actualTicketFk', http: {source: 'body'} }, { arg: 'sales', type: 'object', required: true, description: '[sales IDs]', http: {source: 'body'} }], returns: { type: 'string', root: true }, http: { path: `/moveToNewTicket`, verb: 'post' } }); Self.moveToNewTicket = async params => { let model = Self.app.models; let thisTicketIsEditable = await model.Ticket.isEditable(params.ticket.oldTicketFk); if (!thisTicketIsEditable) throw new Error(`The sales of this ticket can't be modified`); let travelDates = await model.Agency.getFirstShipped(params.ticket); let newTicketParams = { clientFk: params.ticket.clientFk, addressFk: params.ticket.addressFk, agencyModeFk: params.ticket.agencyModeFk, warehouseFk: params.ticket.warehouseFk, shipped: travelDates.vShipped, landed: travelDates.vLanded }; let newTicket = await model.Ticket.create(newTicketParams); for (let i = 0; i < params.sales.length; i++) { await model.Sale.update({id: params.sales[i].id}, {ticketFk: newTicket.id}); } return newTicket; }; };