const LoopBackContext = require('loopback-context'); const dateUtil = require('vn-loopback/util/date'); module.exports = function(Self) { require('../methods/ticket-request/filter')(Self); require('../methods/ticket-request/deny')(Self); require('../methods/ticket-request/confirm')(Self); require('../methods/ticket-request/getItemTypeWorker')(Self); Self.observe('before save', async function(ctx) { const loopBackContext = LoopBackContext.getCurrentContext(); const filter = {where: {id: loopBackContext.active.accessToken.userId}}; const models = Self.app.models; const worker = await models.Worker.findOne(filter); const instance = ctx.instance; const attenderFk = instance?.attenderFk; if (ctx.isNewInstance) { instance.requesterFk = worker.id; const httpCtx = {req: loopBackContext.active}; const httpRequest = httpCtx.req.http.req; const $t = httpRequest.__; if (attenderFk) { const ticket = await models.Ticket.findById(instance.ticketFk); let messageText = 'New ticket request has been created'; if (instance.price) messageText = 'New ticket request has been created with price'; const shipped = dateUtil.toString(ticket.shipped); const message = $t(messageText, { description: instance.description, shipped: shipped, quantity: instance.quantity, price: instance.price }); await models.Chat.sendCheckingPresence(httpCtx, attenderFk, message); } else { const {defaultAttenderFk} = await models.TicketConfig.findOne(); Object.assign(instance, {attenderFk: defaultAttenderFk}); } } }); Self.observe('after save', async function(ctx) { const models = Self.app.models; const instance = ctx.instance; if (instance?.attenderFk === null && !ctx.isNewInstance) { const {defaultAttenderFk} = await models.TicketConfig.findOne(); await models.TicketRequest.updateAll({id: instance.id}, {attenderFk: defaultAttenderFk}); } }); };