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

80 lines
2.5 KiB
JavaScript

const UserError = require('vn-loopback/util/user-error');
module.exports = Self => {
Self.remoteMethodCtx('restore', {
description: 'Restores a ticket within the first hour of deletion',
accessType: 'WRITE',
accepts: [{
arg: 'id',
type: 'number',
required: true,
description: 'The ticket id',
http: {source: 'path'}
}],
returns: {
type: 'string',
root: true
},
http: {
path: `/:id/restore`,
verb: 'post'
}
});
Self.restore = async(ctx, id, options) => {
const models = Self.app.models;
const $t = ctx.req.__; // $translate
const myOptions = {};
if (typeof options == 'object')
Object.assign(myOptions, options);
const ticketLog = await models.TicketLog.findOne({
fields: ['originFk', 'creationDate', 'newInstance'],
where: {
originFk: id,
newInstance: {like: '%"isDeleted":true%'}
},
order: 'creationDate DESC'
}, myOptions);
const ticket = await models.Ticket.findById(id, {
include: [{
relation: 'client',
scope: {
fields: ['id', 'salesPersonFk']
}
}]
}, myOptions);
const now = Date.vnNew();
const maxDate = new Date(ticketLog?.creationDate);
maxDate.setHours(maxDate.getHours() + 1);
if (!ticketLog || now > maxDate)
throw new UserError(`You can only restore a ticket within the first hour after deletion`);
// Send notification to salesPerson
const salesPersonId = ticket.client().salesPersonFk;
if (salesPersonId) {
const url = await Self.app.models.Url.getUrl();
const message = $t(`I have restored the ticket id`, {
id: id,
url: `${url}ticket/${id}/summary`
});
await models.Chat.sendCheckingPresence(ctx, salesPersonId, message);
}
const fullYear = Date.vnNew().getFullYear();
const newShipped = ticket.shipped;
const newLanded = ticket.landed;
newShipped.setFullYear(fullYear);
newLanded.setFullYear(fullYear);
return ticket.updateAttributes({
shipped: newShipped,
landed: newLanded,
isDeleted: false
}, myOptions);
};
};