salix/modules/client/back/methods/client/summary.js

137 lines
4.2 KiB
JavaScript

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, options) => {
const models = Self.app.models;
const myOptions = {};
if (typeof options == 'object')
Object.assign(myOptions, options);
const summaryObj = await getSummary(models.Client, clientFk, myOptions);
summaryObj.mana = await models.Client.getMana(clientFk, myOptions);
summaryObj.debt = await models.Client.getDebt(clientFk, myOptions);
summaryObj.averageInvoiced = await models.Client.getAverageInvoiced(clientFk, myOptions);
summaryObj.totalGreuge = await models.Greuge.sumAmount(clientFk, myOptions);
summaryObj.recovery = await getRecoveries(models.Recovery, clientFk, myOptions);
return summaryObj;
};
async function getSummary(clientModel, clientId, options) {
const filter = {
include: [
{
relation: 'account',
scope: {
fields: ['name', 'active']
}
},
{
relation: 'salesPersonUser',
scope: {
fields: ['id', 'name']
}
},
{
relation: 'country',
scope: {
fields: ['country']
}
},
{
relation: 'province',
scope: {
fields: ['name']
}
},
{
relation: 'contactChannel',
scope: {
fields: ['name']
}
},
{
relation: 'payMethod',
scope: {
fields: ['name']
}
},
{
relation: 'defaultAddress',
scope: {
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: 'clientRisks',
scope: {
fields: ['amount', 'companyFk']
}
},
{
relation: 'claimsRatio',
scope: {
fields: ['claimingRate', 'priceIncreasing'],
limit: 1
}
}
],
where: {id: clientId}
};
return clientModel.findOne(filter, options);
}
async function getRecoveries(recoveryModel, clientId, options) {
const filter = {
where: {
and: [{clientFk: clientId}, {or: [{finished: null}, {finished: {gt: Date.now()}}]}]
},
limit: 1
};
return recoveryModel.findOne(filter, options);
}
};