module.exports = Self => { Self.remoteMethodCtx('refund', { description: 'Create refund tickets with sales and services if provided', accessType: 'WRITE', accepts: [ { arg: 'ref', type: 'string', description: 'The invoice reference', required: true }, { arg: 'withWarehouse', type: 'boolean', required: true } ], returns: { type: ['number'], root: true }, http: { path: '/refund', verb: 'post' } }); Self.refund = async(ctx, ref, withWarehouse, 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 filter = {where: {refFk: ref}}; const tickets = await models.Ticket.find(filter, myOptions); const ticketsIds = tickets.map(ticket => ticket.id); const refundedTickets = await models.Ticket.refund(ctx, ticketsIds, withWarehouse, myOptions); if (tx) await tx.commit(); return refundedTickets; } catch (e) { if (tx) await tx.rollback(); throw e; } }; };