salix/modules/worker/back/methods/worker-time-control/getWorkedWeek.js

79 lines
2.6 KiB
JavaScript
Raw Normal View History

2019-06-03 07:20:20 +00:00
/*
Author : Enrique Blasco BLanquer
Date: 29 de mayo de 2019
*/
module.exports = Self => {
Self.remoteMethodCtx('getWorkedWeek', {
description: 'get worked week info',
accessType: 'WRITE',
returns: [{
type: 'Object',
root: true
}],
http: {
path: `/getWorkedWeek`,
verb: 'GET'
}
});
Self.getWorkedWeek = async(ctx, data) => {
const myUserId = ctx.req.accessToken.userId; // user id
let lastDate = new Date('1986-09-24'); // reference date
let diff = 0; // difference of value between two dates
let total = 0; // total hours
// 1 Get days of week
let week = [];
// 2 Starting Monday not Sunday
let current = new Date();
current.setDate((current.getDate() - current.getDay() + 1));
for (let i = 0; i < 7; i++) {
week.push(
new Date(current)
);
current.setDate(current.getDate() + 1);
}
let fromDate = week[0].getFullYear() + '-' + (week[0].getMonth() + 1) + '-' + week[0].getDate();
let toDate = week[week.length - 1].getFullYear() + '-' + (week[week.length - 1].getMonth() + 1) + '-' + week[week.length - 1].getDate();
// 3 hours worked in a current week
let hoursWeek = await Self.rawSql(`SELECT wtc.timed ,wtc.order
FROM vn.workerTimeControl wtc
WHERE userFk = ?
AND DATE(timed) BETWEEN ? AND ? ORDER BY timed DESC;`, [myUserId, fromDate, toDate]);
// 4 treat data
let isFirst = true;
for (let i = hoursWeek.length - 1; i >= 0; i--) {
let d = new Date(hoursWeek[i].timed);
if (isFirst) {
lastDate = d;
isFirst = false;
} else {
if (lastDate.getDate() === d.getDate()) {
diff += Math.abs(d.getTime() - lastDate.getTime());
lastDate = d;
} else {
total += diff;
diff = 0;
lastDate = d;
}
}
}
total += diff;
// 5 calculate hours and minutes
let decimalTime = total / 1000 / 3600;
decimalTime = decimalTime * 60 * 60;
let hours = Math.floor((decimalTime / (60 * 60)));
decimalTime = decimalTime - (hours * 60 * 60);
let minutes = Math.floor((decimalTime / 60));
return {'timeds': hoursWeek, 'totalWorked': hours + ':' + minutes};
};
};