module.exports = Self => { Self.remoteMethod('summary', { description: 'The invoiceIn summary', accessType: 'READ', accepts: [{ arg: 'id', type: 'number', required: true, description: 'The invoiceIn id', http: {source: 'path'} }], returns: { type: 'object', root: true }, http: { path: `/:id/summary`, verb: 'GET' } }); Self.summary = async id => { const filter = { include: [ { relation: 'company', scope: { fields: ['id', 'code'] } }, { relation: 'supplier', scope: { fields: ['id', 'name'] } }, { relation: 'sageWithholding', scope: { fields: ['withholding'] } }, { relation: 'invoiceInTax', scope: { fields: ['id', 'invoiceInFk', 'taxableBase', 'expenseFk', 'taxTypeSageFk', 'transactionTypeSageFk', 'foreignValue'], include: [{ relation: 'transactionTypeSage', scope: { fields: ['transaction'] } }, { relation: 'taxTypeSage', scope: { fields: ['vat'] } }] } }, { relation: 'expenseDeductible', scope: { fields: ['id', 'name', 'taxTypeFk'] } }, { relation: 'currency', scope: { fields: ['id', 'code'] } } ] }; let summaryObj = await Self.app.models.InvoiceIn.findById(id, filter); summaryObj.totals = await getTotals(id); return summaryObj; }; async function getTotals(invoiceInFk) { return (await Self.rawSql(` SELECT SUM(iit.taxableBase) totalTaxableBase, SUM(iit.taxableBase * (1 + (ti.PorcentajeIva / 100))) totalVat, SUM(iidd.amount) totalDueDay FROM vn.invoiceIn ii LEFT JOIN vn.invoiceInTax iit ON iit.invoiceInFk = ii.id LEFT JOIN sage.TiposIva ti ON ti.CodigoIva = iit.taxTypeSageFk LEFT JOIN vn.invoiceInDueDay iidd ON iidd.invoiceInFk = ii.id WHERE ii.id = ?`, [invoiceInFk]))[0]; } };