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

68 lines
2.3 KiB
JavaScript

const UserError = require('vn-loopback/util/user-error');
module.exports = Self => {
Self.remoteMethodCtx('updateTimeEntry', {
description: 'Updates a time entry for a worker if the user role is above the worker',
accessType: 'WRITE',
accepts: [{
arg: 'id',
type: 'number',
required: true,
description: 'The time entry id',
http: {source: 'path'}
},
{
arg: 'direction',
type: 'string',
required: true
}],
returns: {
type: 'boolean',
root: true
},
http: {
path: `/:id/updateTimeEntry`,
verb: 'POST'
}
});
Self.updateTimeEntry = async(ctx, timeEntryId, direction, options) => {
const currentUserId = ctx.req.accessToken.userId;
const models = Self.app.models;
const myOptions = {userId: currentUserId};
let tx;
if (typeof options == 'object')
Object.assign(myOptions, options);
if (!myOptions.transaction) {
tx = await Self.beginTransaction({});
myOptions.transaction = tx;
}
try {
const {id, userFk, timed, manual} = await Self.findById(timeEntryId, null, myOptions);
const isSubordinate = await models.Worker.isSubordinate(ctx, userFk, myOptions);
const isTeamBoss = await models.ACL.checkAccessAcl(ctx, 'Worker', 'isTeamBoss', 'WRITE');
const isHimself = currentUserId == userFk;
const notAllowed = isSubordinate === false || (isSubordinate && isHimself && !isTeamBoss);
if (notAllowed) throw new UserError(`You don't have enough privileges`);
await models.WorkerTimeControl.deleteById(id, myOptions);
const {id: newTimeEntryId} = await Self.clockIn(
userFk, timed, direction, null, myOptions
);
if (!manual) await Self.updateAll({id: newTimeEntryId}, {manual: false}, myOptions);
await models.WorkerTimeControl.resendWeeklyHourEmail(ctx, userFk, timed, myOptions);
if (tx) await tx.commit();
return newTimeEntryId;
} catch (e) {
if (tx) await tx.rollback();
throw e;
}
};
};