salix/modules/zone/back/methods/zone/deleteZone.js

83 lines
2.4 KiB
JavaScript

module.exports = Self => {
Self.remoteMethodCtx('deleteZone', {
description: 'Delete a zone',
accessType: 'WRITE',
accepts: {
arg: 'id',
type: 'number',
description: 'The zone id',
http: {source: 'path'}
},
returns: {
type: 'object',
root: true
},
http: {
path: `/:id/deleteZone`,
verb: 'POST'
}
});
Self.deleteZone = async(ctx, id, options) => {
const models = Self.app.models;
const token = ctx.req.accessToken;
const userId = token.userId;
const today = new Date();
today.setHours(0, 0, 0, 0);
let tx;
const myOptions = {};
if (typeof options == 'object')
Object.assign(myOptions, options);
if (!myOptions.transaction) {
tx = await Self.beginTransaction({});
myOptions.transaction = tx;
}
try {
const filter = {
where: {
zoneFk: id,
shipped: {gte: today}
},
include: {
relation: 'ticketState',
scope: {
fields: ['id', 'alertLevel', 'code']
}
}
};
const promises = [];
const ticketList = await models.Ticket.find(filter, myOptions);
const fixingState = await models.State.findOne({where: {code: 'FIXING'}}, myOptions);
const worker = await models.Worker.findOne({
where: {userFk: userId}
}, myOptions);
await models.Ticket.rawSql('UPDATE ticket SET zoneFk = NULL WHERE zoneFk = ?', [id], myOptions);
for (ticket of ticketList) {
if (ticket.ticketState().alertLevel == 0) {
promises.push(models.TicketTracking.create({
ticketFk: ticket.id,
stateFk: fixingState.id,
workerFk: worker.id
}, myOptions));
}
}
await Promise.all(promises);
await models.Zone.destroyById(id, myOptions);
if (tx) await tx.commit();
return id;
} catch (err) {
if (tx) await tx.rollback();
throw err;
}
};
};