const UserError = require('vn-loopback/util/user-error'); module.exports = Self => { Self.remoteMethodCtx('updateWorkerTimeControlMail', { description: 'Updates the state of WorkerTimeControlMail', accessType: 'WRITE', accepts: [{ arg: 'workerId', type: 'number', required: true }, { arg: 'year', type: 'number', required: true }, { arg: 'week', type: 'number', required: true }, { arg: 'state', type: 'string', required: true }, { arg: 'reason', type: 'string' }], returns: { type: 'boolean', root: true }, http: { path: `/updateWorkerTimeControlMail`, verb: 'POST' } }); Self.updateWorkerTimeControlMail = async(ctx, options) => { const models = Self.app.models; const args = ctx.args; const userId = ctx.req.accessToken.userId; const myOptions = {}; if (typeof options == 'object') Object.assign(myOptions, options); const workerTimeControlMail = await models.WorkerTimeControlMail.findOne({ where: { workerFk: args.workerId, year: args.year, week: args.week } }, myOptions); if (!workerTimeControlMail) throw new UserError(`There aren't records for this week`); const oldState = workerTimeControlMail.state; const oldReason = workerTimeControlMail.reason; await workerTimeControlMail.updateAttributes({ state: args.state, reason: args.reason || null }, myOptions); if (args.state == 'SENDED') { await workerTimeControlMail.updateAttributes({ sendedCounter: workerTimeControlMail.sendedCounter + 1 }, myOptions); } const logRecord = { originFk: args.workerId, userFk: userId, action: 'update', changedModel: 'WorkerTimeControlMail', oldInstance: { state: oldState, reason: oldReason }, newInstance: { state: args.state, reason: args.reason } }; return models.WorkerLog.create(logRecord, myOptions); }; };