salix/modules/worker/back/methods/worker/createAbsence.js

93 lines
2.9 KiB
JavaScript

const UserError = require('vn-loopback/util/user-error');
module.exports = Self => {
Self.remoteMethodCtx('createAbsence', {
description: 'Creates a new worker absence',
accepts: [{
arg: 'id',
type: 'Number',
description: 'The worker id',
http: {source: 'path'}
},
{
arg: 'absenceTypeId',
type: 'Number',
required: true
},
{
arg: 'dated',
type: 'Date',
required: false
}],
returns: {
type: 'Object',
root: true
},
http: {
path: `/:id/createAbsence`,
verb: 'POST'
}
});
Self.createAbsence = async(ctx, id, absenceTypeId, dated) => {
const models = Self.app.models;
const $t = ctx.req.__; // $translate
const userId = ctx.req.accessToken.userId;
const isSubordinate = await models.Worker.isSubordinate(ctx, id);
const isTeamBoss = await models.Account.hasRole(userId, 'teamBoss');
if (!isSubordinate || (isSubordinate && userId == id && !isTeamBoss))
throw new UserError(`You don't have enough privileges`);
const labour = await models.WorkerLabour.findOne({
include: {relation: 'department'},
where: {
and: [
{workerFk: id},
{or: [{
ended: {gte: [dated]}
}, {ended: null}]}
]
}
});
const absence = await models.Calendar.create({
businessFk: labour.businessFk,
dayOffTypeFk: absenceTypeId,
dated: dated
});
const department = labour.department();
if (department && department.notificationEmail) {
const absenceType = await models.AbsenceType.findById(absenceTypeId);
const account = await models.Account.findById(userId);
const subordinated = await models.Account.findById(id);
const origin = ctx.req.headers.origin;
const body = $t('Created absence', {
author: account.nickname,
employee: subordinated.nickname,
absenceType: absenceType.name,
dated: formatDate(dated),
workerUrl: `${origin}/#!/worker/${id}/calendar`
});
await models.Mail.create({
subject: $t('Absence change notification on the labour calendar'),
body: body,
sender: department.notificationEmail
});
}
return absence;
};
function formatDate(date) {
let day = date.getDate();
if (day < 10) day = `0${day}`;
let month = date.getMonth();
if (month < 10) month = `0${month}`;
let year = date.getFullYear();
return `${day}-${month}-${year}`;
}
};