const ParameterizedSQL = require('loopback-connector').ParameterizedSQL; module.exports = Self => { Self.remoteMethod('summary', { description: 'The invoiceOut summary', accessType: 'READ', accepts: [{ arg: 'id', type: 'number', required: true, description: 'The invoiceOut id', http: {source: 'path'} }], returns: { type: 'object', root: true }, http: { path: `/:id/summary`, verb: 'GET' } }); Self.summary = async id => { const conn = Self.dataSource.connector; let summary = {}; const filter = { fields: [ 'id', 'ref', 'issued', 'dued', 'amount', 'created', 'booked', 'clientFk', 'companyFk', 'hasPdf' ], where: {id: id}, include: [ { relation: 'company', scope: { fields: ['id', 'code'] } }, { relation: 'supplier', scope: { fields: ['id', 'countryFk'] } }, { relation: 'client', scope: { fields: ['id', 'socialName'] } }, { relation: 'tickets' } ] }; summary.invoiceOut = await Self.app.models.InvoiceOut.findOne(filter); let stmts = []; stmts.push('DROP TEMPORARY TABLE IF EXISTS tmp.ticket'); stmt = new ParameterizedSQL(` CREATE TEMPORARY TABLE tmp.ticket (INDEX (ticketFk)) ENGINE = MEMORY SELECT id ticketFk FROM vn.ticket WHERE refFk=?`, [summary.invoiceOut.ref]); stmts.push(stmt); stmts.push('CALL ticketGetTotal()'); let ticketTotalsIndex = stmts.push('SELECT * FROM tmp.ticketTotal') - 1; stmt = new ParameterizedSQL(` SELECT iot.* , pgc.*, IF(pe.equFk IS NULL, taxableBase, 0) AS Base, pgc.rate / 100 as vatPercent FROM vn.invoiceOutTax iot JOIN vn.pgc ON pgc.code = iot.pgcFk LEFT JOIN vn.pgcEqu pe ON pe.equFk = pgc.code WHERE invoiceOutFk = ?`, [summary.invoiceOut.id]); let invoiceOutTaxesIndex = stmts.push(stmt) - 1; stmts.push( `DROP TEMPORARY TABLE tmp.ticket, tmp.ticketTotal`); let sql = ParameterizedSQL.join(stmts, ';'); let result = await conn.executeStmt(sql); totalMap = {}; for (ticketTotal of result[ticketTotalsIndex]) totalMap[ticketTotal.ticketFk] = ticketTotal.total; summary.invoiceOut.tickets().forEach(ticket => { ticket.total = totalMap[ticket.id]; }); summary.invoiceOut.taxesBreakdown = result[invoiceOutTaxesIndex]; return summary; }; };