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

72 lines
2.1 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 ticket = await models.Ticket.findById(id, {
include: [{
relation: 'client',
scope: {
fields: ['id', 'salesPersonFk']
}
}]
}, myOptions);
const now = Date.vnNew();
const maxDate = new Date(ticket.updated);
maxDate.setHours(maxDate.getHours() + 1);
if (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);
};
};