salix/modules/travel/back/methods/travel/getAverageDays.js

67 lines
2.0 KiB
JavaScript

const ParameterizedSQL = require('loopback-connector').ParameterizedSQL;
module.exports = Self => {
Self.remoteMethod('getAverageDays', {
description: 'Returns the average days duration and the two warehouses of the travel.',
accessType: 'READ',
accepts: [{
arg: 'agencyModeFk',
type: 'number',
required: true
}],
returns: {
type: 'object',
root: true
},
http: {
path: `/getAverageDays`,
verb: 'GET'
}
});
Self.getAverageDays = async agencyModeFk => {
const conn = Self.dataSource.connector;
let stmts = [];
stmts.push('DROP TEMPORARY TABLE IF EXISTS tmp.travel');
stmt = new ParameterizedSQL(`
CREATE TEMPORARY TABLE tmp.travel (
SELECT
t.id,
t.warehouseInFk,
t.warehouseOutFk,
t.landed,
t.shipped,
t.agencyModeFk
FROM travel t
WHERE t.agencyModeFk = ? LIMIT 50)`, [agencyModeFk]);
stmts.push(stmt);
stmt = new ParameterizedSQL(`
SELECT
t.id,
t.warehouseInFk,
t.warehouseOutFk,
(SELECT ROUND(AVG(DATEDIFF(t.landed, t.shipped )))
FROM tmp.travel t
WHERE t.agencyModeFk
ORDER BY id DESC LIMIT 50) AS dayDuration
FROM tmp.travel t
WHERE t.agencyModeFk
ORDER BY t.id DESC LIMIT 1`);
const avgDaysIndex = stmts.push(stmt) - 1;
stmts.push(
`DROP TEMPORARY TABLE
tmp.travel`);
const sql = ParameterizedSQL.join(stmts, ';');
const result = await conn.executeStmt(sql);
const [avgDays] = result[avgDaysIndex];
return avgDays;
};
};