salix/modules/ticket/back/methods/ticket/setDeleted.js

103 lines
3.4 KiB
JavaScript
Raw Normal View History

2018-12-27 11:54:16 +00:00
const UserError = require('vn-loopback/util/user-error');
module.exports = Self => {
Self.remoteMethodCtx('setDeleted', {
description: 'Sets true the isDeleted value of a ticket',
2019-05-22 10:35:24 +00:00
accessType: 'WRITE',
accepts: [{
arg: 'id',
type: 'Number',
required: true,
description: 'The ticket id',
http: {source: 'path'}
}],
returns: {
type: 'string',
root: true
},
http: {
path: `/:id/setDeleted`,
verb: 'post'
}
});
Self.setDeleted = async(ctx, id) => {
const models = Self.app.models;
const isEditable = await Self.isEditable(ctx, id);
const $t = ctx.req.__; // $translate
if (!isEditable)
throw new UserError(`The sales of this ticket can't be modified`);
// Check if has sales with shelving
const sales = await models.Sale.find({
include: {relation: 'itemShelving'},
where: {ticketFk: id}
});
const hasItemShelvingSales = sales.some(sale => {
return sale.itemShelving();
});
if (hasItemShelvingSales)
2019-11-13 06:04:47 +00:00
throw new UserError(`You cannot delete a ticket that part of it is being prepared`);
// Check for existing claim
2019-11-12 14:07:37 +00:00
const claimOfATicket = await models.Claim.findOne({where: {ticketFk: id}});
if (claimOfATicket)
throw new UserError('You must delete the claim id %d first', 'DELETE_CLAIM_FIRST', claimOfATicket.id);
// Check for existing purchase requests
const hasPurchaseRequests = await models.TicketRequest.count({
ticketFk: id,
isOk: true
});
if (hasPurchaseRequests)
throw new UserError('You must delete all the buy requests first');
// Remove ticket greuges
const ticketGreuges = await models.Greuge.find({where: {ticketFk: id}});
const ownGreuges = ticketGreuges.every(greuge => {
return greuge.ticketFk = id;
});
if (ownGreuges) {
for (const greuge of ticketGreuges) {
const instance = await models.Greuge.findById(greuge.id);
await instance.destroy();
}
2019-08-13 10:44:34 +00:00
}
const ticket = await models.Ticket.findById(id, {
include: {
relation: 'client',
scope: {
fields: ['id', 'salesPersonFk'],
include: {
relation: 'salesPerson',
scope: {
fields: ['id', 'userFk'],
include: {
relation: 'user'
}
}
}
}
}
});
// Send notification to salesPerson
const salesPerson = ticket.client().salesPerson();
if (salesPerson) {
const salesPersonUser = salesPerson.user().name;
const origin = ctx.req.headers.origin;
const message = $t(`Has deleted the ticket id`, {
id: id,
url: `${origin}/#!/ticket/${id}/summary`
});
2020-01-20 10:59:15 +00:00
await models.Chat.send(ctx, `@${salesPersonUser}`, message);
}
return ticket.updateAttribute('isDeleted', true);
};
};