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 = new Date(); 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 origin = ctx.req.headers.origin; const message = $t(`I have restored the ticket id`, { id: id, url: `${origin}/#!/ticket/${id}/summary` }); await models.Chat.sendCheckingPresence(ctx, salesPersonId, message); } const fullYear = new Date().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); }; };