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

67 lines
2.0 KiB
JavaScript
Raw Normal View History

2021-02-17 10:01:50 +00:00
const ParameterizedSQL = require('loopback-connector').ParameterizedSQL;
module.exports = Self => {
2021-02-12 10:27:24 +00:00
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: {
2021-02-24 10:32:31 +00:00
type: 'object',
root: true
},
http: {
2021-02-12 10:27:24 +00:00
path: `/getAverageDays`,
verb: 'GET'
}
});
2021-02-12 10:27:24 +00:00
Self.getAverageDays = async agencyModeFk => {
2021-02-17 10:01:50 +00:00
const conn = Self.dataSource.connector;
let stmts = [];
2021-02-17 10:01:50 +00:00
stmts.push('DROP TEMPORARY TABLE IF EXISTS tmp.travel');
stmt = new ParameterizedSQL(`
2021-02-24 10:32:31 +00:00
CREATE TEMPORARY TABLE tmp.travel (
SELECT
t.id,
t.warehouseInFk,
t.warehouseOutFk,
t.landed,
t.shipped,
2022-07-13 12:36:03 +00:00
t.agencyModeFk
2021-02-24 10:32:31 +00:00
FROM travel t
2022-07-13 12:36:03 +00:00
WHERE t.agencyModeFk = ? LIMIT 50)`, [agencyModeFk]);
2021-02-24 10:32:31 +00:00
stmts.push(stmt);
stmt = new ParameterizedSQL(`
SELECT
t.id,
2021-02-17 10:01:50 +00:00
t.warehouseInFk,
t.warehouseOutFk,
2021-02-24 10:32:31 +00:00
(SELECT ROUND(AVG(DATEDIFF(t.landed, t.shipped )))
FROM tmp.travel t
2022-07-13 12:36:03 +00:00
WHERE t.agencyModeFk
2021-02-24 10:32:31 +00:00
ORDER BY id DESC LIMIT 50) AS dayDuration
FROM tmp.travel t
2022-07-13 12:36:03 +00:00
WHERE t.agencyModeFk
2021-02-24 10:32:31 +00:00
ORDER BY t.id DESC LIMIT 1`);
2021-02-17 10:01:50 +00:00
2021-02-24 10:32:31 +00:00
const avgDaysIndex = stmts.push(stmt) - 1;
2021-02-22 08:53:03 +00:00
2021-02-17 10:01:50 +00:00
stmts.push(
`DROP TEMPORARY TABLE
tmp.travel`);
2021-02-24 10:32:31 +00:00
const sql = ParameterizedSQL.join(stmts, ';');
const result = await conn.executeStmt(sql);
2021-02-17 10:01:50 +00:00
2021-02-24 10:32:31 +00:00
const [avgDays] = result[avgDaysIndex];
2021-02-22 08:53:03 +00:00
2021-02-12 10:27:24 +00:00
return avgDays;
};
};