module.exports = Self => { Self.remoteMethodCtx('book', { description: 'Book an invoiceOut', accessType: 'WRITE', accepts: { arg: 'ref', type: 'string', required: true, description: 'The invoiceOut ref', http: {source: 'path'} }, returns: { type: 'object', root: true }, http: { path: '/:ref/book', verb: 'POST' } }); Self.book = async(ctx, ref, options) => { const models = Self.app.models; let tx; const myOptions = {userId: ctx.req.accessToken.userId}; if (typeof options == 'object') Object.assign(myOptions, options); if (!myOptions.transaction) { tx = await Self.beginTransaction({}); myOptions.transaction = tx; } try { const ticketAddress = await models.Ticket.findOne({ where: {invoiceOut: ref} }, myOptions); const invoiceCompany = await models.InvoiceOut.findOne({ where: {ref: ref} }, myOptions); let query = 'SELECT vn.addressTaxArea(?, ?) AS code'; const [taxArea] = await Self.rawSql(query, [ ticketAddress.address, invoiceCompany.company ], myOptions); query = 'CALL vn.invoiceOutAgain(?, ?)'; const result = Self.rawSql(query, [ref, taxArea.code], myOptions); if (tx) await tx.commit(); return result; } catch (e) { if (tx) await tx.rollback(); throw e; } }; };