salix/modules/worker/back/methods/calendar/absences.js

131 lines
3.5 KiB
JavaScript

const UserError = require('vn-loopback/util/user-error');
module.exports = Self => {
Self.remoteMethodCtx('absences', {
description: 'Returns an array of absences from an specified contract',
accepts: [{
arg: 'workerFk',
type: 'number',
required: true,
},
{
arg: 'businessFk',
type: 'number',
required: false,
},
{
arg: 'year',
type: 'date',
required: true,
}],
returns: [{
arg: 'absences',
type: 'number'
},
{
arg: 'holidays',
type: 'number'
}],
http: {
path: `/absences`,
verb: 'GET'
}
});
Self.absences = async(ctx, workerFk, businessFk, year, options) => {
const models = Self.app.models;
const started = new Date();
started.setFullYear(year);
started.setMonth(0);
started.setDate(1);
const ended = new Date();
ended.setFullYear(year);
ended.setMonth(12);
ended.setDate(0);
const myOptions = {};
if (typeof options == 'object')
Object.assign(myOptions, options);
let condition = {
and: [
{workerFk: workerFk},
{businessFk: businessFk}
]
};
if (businessFk)
condition.and.push({workerFk: workerFk});
const contracts = await models.WorkerLabour.find({
include: [{
relation: 'holidays',
scope: {
where: {year}
}
},
{
relation: 'absences',
scope: {
include: {
relation: 'absenceType',
},
where: {
dated: {between: [started, ended]}
}
}
},
{
relation: 'workCenter',
scope: {
include: {
relation: 'holidays',
scope: {
include: [{
relation: 'detail'
},
{
relation: 'type'
}],
where: {
dated: {between: [started, ended]}
}
}
}
}
}],
where: condition
}, myOptions);
if (!contracts) return;
const isSubordinate = await models.Worker.isSubordinate(ctx, workerFk, myOptions);
if (!isSubordinate)
throw new UserError(`You don't have enough privileges`);
const absences = [];
const holidays = [];
for (let contract of contracts) {
for (let absence of contract.absences()) {
absence.dated = new Date(absence.dated);
absence.dated.setHours(0, 0, 0, 0);
absences.push(absence);
}
for (let day of contract.workCenter().holidays()) {
day.dated = new Date(day.dated);
day.dated.setHours(0, 0, 0, 0);
holidays.push(day);
}
}
return [absences, holidays];
};
};