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; const $t = ctx.req.__; 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($t('the plate does not exist', {plate})); const machineWorker = await Self.findOne({ where: { or: [{machineFk: machine.id}, {workerFk: userId}], outTime: null, } }, myOptions); const {maxHours} = await models.MachineWorkerConfig.findOne({fields: ['maxHours']}, myOptions); const hoursDifference = (Date.vnNow() - machineWorker.inTime.getTime()) / (60 * 60 * 1000); if (machineWorker) { const isHimself = userId == machineWorker.workerFk; const isSameMachine = machine.id == machineWorker.machineFk; if (hoursDifference < maxHours && !isHimself) throw new UserError($t('This machine is already in use.')); if (hoursDifference < maxHours && isHimself && !isSameMachine) throw new UserError($t('You are already using a machine')); await machineWorker.updateAttributes({ outTime: Date.vnNew() }, myOptions); } if (!machineWorker || hoursDifference >= maxHours) await models.MachineWorker.create({machineFk: machine.id, workerFk: userId}, myOptions); if (tx) await tx.commit(); } catch (e) { if (tx) await tx.rollback(); throw e; } }; };