salix/back/methods/machine-worker/add.js

69 lines
2.0 KiB
JavaScript

module.exports = Self => {
Self.remoteMethodCtx('add', {
description: 'Insert log if the worker has not logged anything in the last 12 hours',
accessType: 'READ',
accepts: [
{
arg: 'plate',
type: 'string',
}
],
http: {
path: `/add`,
verb: 'POST'
}
});
Self.add = 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 twelveHoursAgo = Date.vnNew();
twelveHoursAgo.setHours(twelveHoursAgo.getHours() - 12);
const isRegistered = await models.MachineWorker.findOne({
where: {
and: [
{machineFk: machine.id},
{workerFk: userId},
{outTime: {gte: twelveHoursAgo}}
]
}
}, myOptions);
if (!isRegistered) await models.MachineWorker.create({machineFk: machine.id, workerFk: userId}, myOptions);
else {
await models.MachineWorker.updateAll(
{or: [{workerFk: userId}, {machineFk: machine.id}]},
{outTime: Date.vnNew()},
myOptions
);
}
if (tx) await tx.commit();
} catch (e) {
if (tx) await tx.rollback();
throw e;
}
};
};