salix/modules/claim/back/methods/claim/logs.js

135 lines
4.0 KiB
JavaScript

const ParameterizedSQL = require('loopback-connector').ParameterizedSQL;
const buildFilter = require('vn-loopback/util/filter').buildFilter;
const {mergeFilters, mergeWhere} = require('vn-loopback/util/filter');
module.exports = Self => {
Self.remoteMethodCtx('logs', {
description: 'Find all claim logs of the claim entity matched by a filter',
accessType: 'READ',
accepts: [
{
arg: 'id',
type: 'Number',
description: 'The claim id',
http: {source: 'path'}
},
{
arg: 'filter',
type: 'object',
http: {source: 'query'}
},
{
arg: 'search',
type: 'string',
http: {source: 'query'}
},
{
arg: 'userFk',
type: 'number',
http: {source: 'query'}
},
{
arg: 'created',
type: 'date',
http: {source: 'query'}
},
],
returns: {
type: ['object'],
root: true
},
http: {
path: `/:id/logs`,
verb: 'GET'
}
});
Self.logs = async(ctx, id, filter, options) => {
const conn = Self.dataSource.connector;
const args = ctx.args;
const myOptions = {};
let to;
if (typeof options == 'object')
Object.assign(myOptions, options);
let where = buildFilter(args, (param, value) => {
switch (param) {
case 'search':
return {
or: [
{changedModel: {like: `%${value}%`}},
{oldInstance: {like: `%${value}%`}}
]
};
case 'userFk':
return {'cl.userFk': value};
case 'created':
value.setHours(0, 0, 0, 0);
to = new Date(value);
to.setHours(23, 59, 59, 999);
return {creationDate: {between: [value, to]}};
}
});
where = mergeWhere(where, {['cl.originFk']: id});
filter = mergeFilters(args.filter, {where});
const stmts = [];
const stmt = new ParameterizedSQL(
`SELECT
cl.id,
cl.userFk,
u.name AS userName,
cl.oldInstance,
cl.newInstance,
cl.changedModel,
cl.action,
cl.creationDate AS created
FROM claimLog cl
JOIN account.user u ON u.id = cl.userFk
`
);
stmt.merge(conn.makeSuffix(filter));
stmts.push(stmt);
const sql = ParameterizedSQL.join(stmts, ';');
const result = await conn.executeStmt(sql, myOptions);
const logs = [];
for (const row of result) {
const changes = [];
const oldInstance = JSON.parse(row.oldInstance) || {};
const newInstance = JSON.parse(row.newInstance) || {};
const mergedProperties = [...Object.keys(oldInstance), ...Object.keys(newInstance)];
const properties = new Set(mergedProperties);
for (const property of properties) {
let oldValue = oldInstance[property];
let newValue = newInstance[property];
const change = {
property: property,
before: oldValue,
after: newValue,
};
changes.push(change);
}
logs.push({
model: row.changedModel,
action: row.action,
created: row.created,
userFk: row.userFk,
userName: row.userName,
changes: changes,
});
}
return logs;
};
};