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

97 lines
3.3 KiB
JavaScript

const UserError = require('vn-loopback/util/user-error');
module.exports = Self => {
Self.remoteMethodCtx('deleteAbsence', {
description: 'Deletes a worker absence',
accepts: [{
arg: 'id',
type: 'number',
description: 'The worker id',
http: {source: 'path'}
},
{
arg: 'absenceId',
type: 'number',
required: true
}],
returns: 'Object',
http: {
path: `/:id/deleteAbsence`,
verb: 'DELETE'
}
});
Self.deleteAbsence = async(ctx, id, options) => {
const models = Self.app.models;
const $t = ctx.req.__; // $translate
const args = ctx.args;
const userId = ctx.req.accessToken.userId;
let tx;
const myOptions = {};
if (typeof options == 'object')
Object.assign(myOptions, options);
if (!myOptions.transaction) {
tx = await Self.beginTransaction({});
myOptions.transaction = tx;
}
try {
const isSubordinate = await models.Worker.isSubordinate(ctx, id, myOptions);
const isTeamBoss = await models.Account.hasRole(userId, 'teamBoss', myOptions);
if (!isSubordinate || (isSubordinate && userId == id && !isTeamBoss))
throw new UserError(`You don't have enough privileges`);
const absence = await models.Calendar.findById(args.absenceId, {
include: {
relation: 'labour',
scope: {
include: {relation: 'department'}
}
}
}, myOptions);
const result = await absence.destroy(myOptions);
const labour = absence.labour();
const department = labour && labour.department();
if (department && department.notificationEmail) {
const absenceType = await models.AbsenceType.findById(absence.dayOffTypeFk, null, myOptions);
const account = await models.Account.findById(userId, null, myOptions);
const subordinated = await models.Account.findById(labour.workerFk, null, myOptions);
const origin = ctx.req.headers.origin;
const body = $t('Deleted absence', {
author: account.nickname,
employee: subordinated.nickname,
absenceType: absenceType.name,
dated: formatDate(absence.dated),
workerUrl: `${origin}/#!/worker/${id}/calendar`
});
await models.Mail.create({
subject: $t('Absence change notification on the labour calendar'),
body: body,
receiver: department.notificationEmail
}, myOptions);
}
if (tx) await tx.commit();
return result;
} catch (e) {
if (tx) await tx.rollback();
throw e;
}
};
function formatDate(date) {
let day = date.getDate();
if (day < 10) day = `0${day}`;
let month = date.getMonth() + 1;
if (month < 10) month = `0${month}`;
let year = date.getFullYear();
return `${day}-${month}-${year}`;
}
};