const UserError = require('vn-loopback/util/user-error'); module.exports = Self => { Self.remoteMethodCtx('updateInTime', { description: 'Updates the corresponding registry if the worker has been registered in the last few hours', accessType: 'WRITE', accepts: [ { arg: 'plate', type: 'string', } ], http: { path: `/updateInTime`, verb: 'POST' } }); Self.updateInTime = async(ctx, plate, options) => { const models = Self.app.models; 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 machine = await models.Machine.findOne({ fields: ['id', 'plate'], where: {plate} }, myOptions); if (!machine) throw new Error(`plate ${plate} does not exist`); const {maxHours} = await models.MachineWorkerConfig.findOne({fields: ['maxHours']}, myOptions); const machineWorker = await Self.findOne({ where: { machineFk: machine.id, outTime: null, } }, myOptions); if (machineWorker) { const hoursDifference = (Date.vnNew() - machineWorker.inTime) / (60 * 60 * 1000); const isHimSelf = userId == machineWorker.workerFk; if (maxHours > hoursDifference && !isHimSelf) throw new UserError('Esta máquina ya está en uso.'); await machineWorker.updateAttributes({ outTime: Date.vnNew() }, myOptions); if (!isHimSelf) await models.MachineWorker.create({machineFk: machine.id, workerFk: userId}, myOptions); } else await models.MachineWorker.create({machineFk: machine.id, workerFk: userId}, myOptions); if (tx) await tx.commit(); } catch (e) { if (tx) await tx.rollback(); throw e; } }; };