module.exports = Self => { Self.remoteMethod('summary', { description: 'Returns a client summary', accessType: 'READ', accepts: [{ arg: 'id', type: 'number', required: true, description: 'client id', http: {source: 'path'} }], returns: { type: [this.modelName], root: true }, http: { path: `/:id/summary`, verb: 'GET' } }); Self.summary = async clientFk => { let models = Self.app.models; let summaryObj = await getSummary(models.Client, clientFk); summaryObj.mana = await models.Client.getMana(clientFk); summaryObj.debt = await models.Client.getDebt(clientFk); summaryObj.averageInvoiced = await models.Client.getAverageInvoiced(clientFk); summaryObj.totalGreuge = await models.Greuge.sumAmount(clientFk); summaryObj.recovery = await getRecoveries(models.Recovery, clientFk); return summaryObj; }; async function getSummary(client, clientId) { let filter = { include: [ {relation: 'account', scope: {fields: ['name', 'active']}}, {relation: 'salesPerson', scope: {fields: ['firstName', 'name']}}, {relation: 'country', scope: {fields: ['country']}}, {relation: 'province', scope: {fields: ['name']}}, {relation: 'contactChannel', scope: {fields: ['name']}}, {relation: 'payMethod', scope: {fields: ['name']}}, { relation: 'addresses', scope: { where: {isDefaultAddress: true}, fields: ['nickname', 'street', 'city', 'postalCode'] } }, { relation: 'classifications', scope: { include: { relation: 'insurances', scope: { fields: ['id', 'grade', 'created'], order: 'created DESC' } }, where: {finished: null} } }, { relation: 'defaulters', scope: { fields: ['amount'], order: 'created DESC', limit: 1 } }, { relation: 'clientsRisk', scope: { where: {companyFk: 442}, fields: ['amount'], limit: 1 } }, { relation: 'claimsRatio', scope: { fields: ['claimingRate', 'priceIncreasing'], limit: 1 } } ], where: {id: clientId} }; return await client.findOne(filter); } async function getRecoveries(recovery, clientId) { let filter = { where: { and: [{clientFk: clientId}, {or: [{finished: null}, {finished: {gt: Date.now()}}]}] }, limit: 1 }; return await recovery.findOne(filter); } };