2024-03-14 07:36:19 +00:00
|
|
|
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);
|
2024-03-21 09:18:54 +00:00
|
|
|
const hoursDifference = (Date.vnNow() - machineWorker?.inTimed?.getTime() ?? 0) / (60 * 60 * 1000);
|
2024-03-14 07:36:19 +00:00
|
|
|
|
|
|
|
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;
|
|
|
|
}
|
|
|
|
};
|
|
|
|
};
|