const UserError = require('vn-loopback/util/user-error'); module.exports = Self => { Self.remoteMethodCtx('transferInvoice', { description: 'Transfer an issued invoice to another client', accessType: 'WRITE', accepts: [ { arg: 'id', type: 'number', required: true, description: 'Issued invoice id' }, { arg: 'ref', type: 'string', required: true }, { arg: 'newClientFk', type: 'number', required: true }, { arg: 'cplusRectificationId', type: 'number', required: true }, { arg: 'siiTypeInvoiceOutId', type: 'number', required: true }, { arg: 'invoiceCorrectionTypeId', type: 'number', required: true }, ], returns: { type: 'boolean', root: true }, http: { path: '/transferInvoice', verb: 'post' } }); Self.transferInvoice = async(ctx, options) => { const models = Self.app.models; const myOptions = {userId: ctx.req.accessToken.userId}; const args = ctx.args; let tx; if (typeof options == 'object') Object.assign(myOptions, options); const {clientFk} = await models.InvoiceOut.findById(args.id); if (clientFk == args.newClientFk) throw new UserError(`Select a different client`); if (!myOptions.transaction) { tx = await Self.beginTransaction({}); myOptions.transaction = tx; } try { const filterRef = {where: {refFk: args.ref}}; const tickets = await models.Ticket.find(filterRef, myOptions); const ticketsIds = tickets.map(ticket => ticket.id); await models.Ticket.refund(ctx, ticketsIds, null, myOptions); const filterTicket = {where: {ticketFk: {inq: ticketsIds}}}; const services = await models.TicketService.find(filterTicket, myOptions); const servicesIds = services.map(service => service.id); const sales = await models.Sale.find(filterTicket, myOptions); const salesIds = sales.map(sale => sale.id); const clonedTickets = await models.Sale.clone(ctx, salesIds, servicesIds, null, false, false, myOptions); const clonedTicketIds = []; for (const clonedTicket of clonedTickets) { await clonedTicket.updateAttribute('clientFk', args.newClientFk, myOptions); clonedTicketIds.push(clonedTicket.id); } const invoiceIds = await models.Ticket.invoiceTickets(ctx, clonedTicketIds, myOptions); const [invoiceId] = invoiceIds; await models.InvoiceCorrection.create({ correctingFk: invoiceId, correctedFk: args.id, cplusRectificationTypeFk: args.cplusRectificationId, siiTypeInvoiceOutFk: args.siiTypeInvoiceOutId, invoiceCorrectionTypeFk: args.invoiceCorrectionTypeId }, myOptions); if (tx) { await tx.commit(); await models.InvoiceOut.makePdfAndNotify(ctx, invoiceId, null); } return invoiceId; } catch (e) { if (tx) await tx.rollback(); throw e; } }; };