From d993b20637def17a48a2340912baf2a12acf5817 Mon Sep 17 00:00:00 2001 From: adriano Date: Tue, 18 Jul 2023 13:01:56 -0300 Subject: [PATCH] =?UTF-8?q?atualiza=C3=A7=C3=A3o=20para=20guardar=20em=20b?= =?UTF-8?q?anco=20de=20dados=20o=20numero=20do=20chamdado?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- backend/src/controllers/HitController.ts | 62 ++++++++++++++++-- backend/src/database/index.ts | 2 + .../20230718123604-create-query-items.ts | 44 +++++++++++++ ...query-items-queryItem-column-allow-null.ts | 17 +++++ backend/src/models/QueryItem.ts | 50 +++++++++++++++ .../SLM/FindOrCreateQueryItemService.ts | 63 +++++++++++++++++++ .../src/services/SLM/ShowQueryItemService.ts | 57 +++++++++++++++++ .../WbotServices/wbotMessageListener.ts | 49 +++++++++++---- 8 files changed, 326 insertions(+), 18 deletions(-) create mode 100644 backend/src/database/migrations/20230718123604-create-query-items.ts create mode 100644 backend/src/database/migrations/20230718132435-change-query-items-queryItem-column-allow-null.ts create mode 100644 backend/src/models/QueryItem.ts create mode 100644 backend/src/services/SLM/FindOrCreateQueryItemService.ts create mode 100644 backend/src/services/SLM/ShowQueryItemService.ts diff --git a/backend/src/controllers/HitController.ts b/backend/src/controllers/HitController.ts index f2df0a5..02789b1 100644 --- a/backend/src/controllers/HitController.ts +++ b/backend/src/controllers/HitController.ts @@ -21,6 +21,9 @@ import GetProfilePicUrl from "../services/WbotServices/GetProfilePicUrl"; import CreateContactService from "../services/ContactServices/CreateContactService"; import { resourceUsage } from "process"; import FindOrCreateTicketServiceBot from "../services/TicketServices/FindOrCreateTicketServiceBot"; +import ShowQuickAnswerService from "../services/QuickAnswerService/ShowQuickAnswerService"; +import ShowQueryItemService from "../services/SLM/ShowQueryItemService"; +import QueryItem from "../models/QueryItem"; @@ -102,7 +105,7 @@ export const hit = async (req: Request, res: Response): Promise => { response = req.body['mensagem'] } - + if (!response || response.length == 0 || !contact) { @@ -132,7 +135,7 @@ export const hit = async (req: Request, res: Response): Promise => { await sendMessageHitMonitoring(response, ticket); - await sendMessageInsertInfoSLM(req, ticket, ['atdabriu', 'atdatualizou']); + await sendMessageInsertInfoSLM(req, ticket, ['atdabriu', 'atdatualizou'], contact.id); } else if (ticket.id && ticket.userId == botInfo.userIdBot) { @@ -149,7 +152,7 @@ export const hit = async (req: Request, res: Response): Promise => { await sendMessageHitMonitoring(response, ticket); - await sendMessageInsertInfoSLM(req, ticket, ['atdabriu', 'atdatualizou']); + await sendMessageInsertInfoSLM(req, ticket, ['atdabriu', 'atdatualizou'], contact.id); } } @@ -162,14 +165,61 @@ export const hit = async (req: Request, res: Response): Promise => { }; -async function sendMessageInsertInfoSLM(req: Request, ticket: any, params: any[]) { +async function sendMessageInsertInfoSLM(req: Request, ticket: any, params: any[], contactId: number) { + + const insert_protocol_info: QueryItem = await ShowQueryItemService({ + contactId, + name: 'insert_protocol_info' + }) + + const n_chamado_web: QueryItem = await ShowQueryItemService({ + contactId, + name: 'n_chamado_web' + }) + + await new Promise(f => setTimeout(f, 2000)); if (params.includes(req.body['action'])) { - await new Promise(f => setTimeout(f, 1000)); + if (insert_protocol_info && + insert_protocol_info?.status && + n_chamado_web?.queryItem) { - await sendMessageHitMonitoring(`Se deseja adicionar alguma informação ao protocolo acima, digite 2.`, ticket); + await sendMessageHitMonitoring(`🔄 Houve uma atualização no chamado acima`, ticket); + await new Promise(f => setTimeout(f, 1000)); + + await sendMessageHitMonitoring(`✅ Protocolo *${n_chamado_web?.queryItem}* validado, digite a informação que deseja adicionar.`, ticket); + + } + else { + + // await new Promise(f => setTimeout(f, 1000)); + + await sendMessageHitMonitoring(`Se deseja adicionar alguma informação ao protocolo acima, digite 2.`, ticket); + + } + + + } + else if (req.body['action'] == 'atdfechou') { + + if (insert_protocol_info && + insert_protocol_info?.status && + n_chamado_web?.queryItem) { + + if (req.body['n_chamado_web'] && + req.body['n_chamado_web'].trim() == n_chamado_web?.queryItem) { + + insert_protocol_info.update({ status: false }) + + await new Promise(f => setTimeout(f, 1000)); + + await sendMessageHitMonitoring(`O Protocolo *${n_chamado_web?.queryItem}* foi encerrado. Não é mais possível adicionar informação. Se desejar consultar o historico digite 1`, ticket); + + } + + } } } diff --git a/backend/src/database/index.ts b/backend/src/database/index.ts index b06b14c..d3fcf0b 100644 --- a/backend/src/database/index.ts +++ b/backend/src/database/index.ts @@ -16,6 +16,7 @@ import StatusChatEnd from "../models/StatusChatEnd"; import UserOnlineTime from "../models/UserOnlineTime"; import Dialogflow from "../models/Dialogflow"; +import QueryItem from "../models/QueryItem"; // eslint-disable-next-line const dbConfig = require("../config/database"); // import dbConfig from "../config/database"; @@ -39,6 +40,7 @@ const models = [ StatusChatEnd, UserOnlineTime, Dialogflow, + QueryItem ]; sequelize.addModels(models); diff --git a/backend/src/database/migrations/20230718123604-create-query-items.ts b/backend/src/database/migrations/20230718123604-create-query-items.ts new file mode 100644 index 0000000..ec78c45 --- /dev/null +++ b/backend/src/database/migrations/20230718123604-create-query-items.ts @@ -0,0 +1,44 @@ +import { QueryInterface, DataTypes } from "sequelize"; + +module.exports = { + up: (queryInterface: QueryInterface) => { + return queryInterface.createTable("QueryItems", { + id: { + type: DataTypes.INTEGER, + autoIncrement: true, + primaryKey: true, + allowNull: false + }, + status: { + type: DataTypes.BOOLEAN, + defaultValue: false, + }, + contactId: { + type: DataTypes.INTEGER, + references: { model: "Contacts", key: "id" }, + onUpdate: "CASCADE", + onDelete: "CASCADE" + }, + queryItem: { + type: DataTypes.STRING, + allowNull: false + }, + name: { + type: DataTypes.STRING, + allowNull: false + }, + createdAt: { + type: DataTypes.DATE(6), + allowNull: false + }, + updatedAt: { + type: DataTypes.DATE(6), + allowNull: false + } + }); + }, + + down: (queryInterface: QueryInterface) => { + return queryInterface.dropTable("QueryItems"); + } +}; diff --git a/backend/src/database/migrations/20230718132435-change-query-items-queryItem-column-allow-null.ts b/backend/src/database/migrations/20230718132435-change-query-items-queryItem-column-allow-null.ts new file mode 100644 index 0000000..cb05483 --- /dev/null +++ b/backend/src/database/migrations/20230718132435-change-query-items-queryItem-column-allow-null.ts @@ -0,0 +1,17 @@ +import { QueryInterface, DataTypes } from "sequelize"; + +module.exports = { + up: (queryInterface: QueryInterface) => { + return queryInterface.changeColumn("QueryItems", "queryItem", { + type: DataTypes.STRING, + allowNull: true + }); + }, + + down: (queryInterface: QueryInterface) => { + return queryInterface.changeColumn("QueryItems", "queryItem", { + type: DataTypes.STRING, + allowNull: false + }); + } +}; diff --git a/backend/src/models/QueryItem.ts b/backend/src/models/QueryItem.ts new file mode 100644 index 0000000..d7ddf67 --- /dev/null +++ b/backend/src/models/QueryItem.ts @@ -0,0 +1,50 @@ +import { + Table, + Column, + CreatedAt, + UpdatedAt, + Model, + PrimaryKey, + ForeignKey, + BelongsTo, + HasMany, + HasOne, + AutoIncrement, + Default, + DataType +} from "sequelize-typescript"; + +import Contact from "./Contact"; + +@Table +class QueryItem extends Model { + @PrimaryKey + @AutoIncrement + @Column + id: number; + + @ForeignKey(() => Contact) + @Column + contactId: number; + + @BelongsTo(() => Contact) + contact: Contact; + + @Column + queryItem: string; + + @Column + name: string; + + @Default(false) + @Column + status: boolean; + + @CreatedAt + createdAt: Date; + + @UpdatedAt + updatedAt: Date; +} + +export default QueryItem; diff --git a/backend/src/services/SLM/FindOrCreateQueryItemService.ts b/backend/src/services/SLM/FindOrCreateQueryItemService.ts new file mode 100644 index 0000000..e22c0f0 --- /dev/null +++ b/backend/src/services/SLM/FindOrCreateQueryItemService.ts @@ -0,0 +1,63 @@ +import AppError from "../../errors/AppError"; +import CheckContactOpenTickets from "../../helpers/CheckContactOpenTickets"; +import GetDefaultWhatsApp from "../../helpers/GetDefaultWhatsApp"; +import Ticket from "../../models/Ticket"; +import ShowContactService from "../ContactServices/ShowContactService"; + + +import { getIO } from "../../libs/socket"; +import ShowUserServiceReport from "../UserServices/ShowUserServiceReport"; + +import format from 'date-fns/format'; +import ptBR from 'date-fns/locale/pt-BR'; +import { splitDateTime } from "../../helpers/SplitDateTime"; +import TicketEmiterSumOpenClosedByUser from "../../helpers/OnlineReporEmiterInfoByUser"; + +import { createOrUpdateTicketCache } from '../../helpers/TicketCache' +import User from "../../models/User"; +import whatsappQueueMatchingUserQueue from "../../helpers/whatsappQueueMatchingUserQueue"; +import QueryItem from "../../models/QueryItem"; +let flatten = require('flat') + + +interface Request { + contactId: number | string; + name: string; + queryItem?: string; + status?: boolean; +} + +const FindOrCreateQueryItemService = async ({ + contactId, + name, + queryItem, + status, +}: Request): Promise => { + + try { + + let _queryitem = await QueryItem.findOne({ where: { contactId, name } }) + + if (!_queryitem) { + + _queryitem = await QueryItem.create({ + contactId, + name, + queryItem, + status + }); + } + else { + await _queryitem.update({ queryItem, status, name }); + } + + return _queryitem; + + } catch (error: any) { + console.error('===> Error on FindOrCreateQueryItem.ts file: \n', error) + throw new AppError(error.message); + } + +}; + +export default FindOrCreateQueryItemService; diff --git a/backend/src/services/SLM/ShowQueryItemService.ts b/backend/src/services/SLM/ShowQueryItemService.ts new file mode 100644 index 0000000..adc416e --- /dev/null +++ b/backend/src/services/SLM/ShowQueryItemService.ts @@ -0,0 +1,57 @@ +import Ticket from "../../models/Ticket"; +import AppError from "../../errors/AppError"; +import Contact from "../../models/Contact"; +import User from "../../models/User"; +import Queue from "../../models/Queue"; + +import Message from "../../models/Message"; +import { userInfo } from "os"; + +import { Op, where } from "sequelize"; + +import { Sequelize } from "sequelize"; +import moment from 'moment'; + +import { startOfDay, endOfDay, parseISO, getDate, subHours, isBefore, subMinutes } from "date-fns"; +import { string } from "yup/lib/locale"; +import Whatsapp from "../../models/Whatsapp"; + +import UserOnlineTime from "../../models/UserOnlineTime"; +import QueryItem from "../../models/QueryItem"; + + +interface Request { + contactId: number | string; + name: string; +} + +//Report by user, startDate, endDate +const ShowQueryItemService = async ({ + contactId, + name +}: Request): Promise => { + + let _queryItem = await QueryItem.findOne({ + where: { contactId, name } + }) + + if (_queryItem) { + + const currentTime = new Date(); + + // Subtract 2 hours from the current time + // const twoHoursAgo = subHours(currentTime, 2); + + const fortyFiveMinutesAgo = subMinutes(currentTime, 45); + + if (isBefore(_queryItem.updatedAt, fortyFiveMinutesAgo)) { + console.log('The updatedAt value is older than 45 minutes from the current time.'); + _queryItem.update({ status: false }) + } + + } + + return _queryItem; +}; + +export default ShowQueryItemService; diff --git a/backend/src/services/WbotServices/wbotMessageListener.ts b/backend/src/services/WbotServices/wbotMessageListener.ts index 5b33ddf..dbb3ffa 100644 --- a/backend/src/services/WbotServices/wbotMessageListener.ts +++ b/backend/src/services/WbotServices/wbotMessageListener.ts @@ -75,6 +75,9 @@ import { tr } from "date-fns/locale"; import mostRepeatedPhrase from "../../helpers/MostRepeatedPhrase"; import FindOrCreateTicketServiceBot from "../TicketServices/FindOrCreateTicketServiceBot"; import { setMessageAsRead } from "../../helpers/SetMessageAsRead"; +import FindOrCreateQueryItemService from "../SLM/FindOrCreateQueryItemService"; +import ShowQueryItemService from "../SLM/ShowQueryItemService"; +import QueryItem from "../../models/QueryItem"; @@ -390,6 +393,12 @@ async function sendDelayedMessages(wbot: any, ticket: Ticket, contact: Contact, if (params[0] === 'validate_n_chamado_web') { + await FindOrCreateQueryItemService({ + contactId: contact.id, + queryItem: params[1].trim(), + name: 'n_chamado_web' + }) + let valid = await endPointQuery( 'http://177.107.192.247:8095/labs/monitoramentohit/api/api.php', 'post', @@ -403,6 +412,12 @@ async function sendDelayedMessages(wbot: any, ticket: Ticket, contact: Contact, botSendMessage(ticket, `✅ Protocolo validado, agora digite a informação que deseja adicionar.`) + FindOrCreateQueryItemService({ + contactId: contact.id, + name: 'insert_protocol_info', + status: true, + }) + } else if (valid && valid.data.result == 'notfound') { @@ -1105,31 +1120,41 @@ const handleMessage = async ( } else { - let last_messages = await ShowTicketMessage(ticket.id, 2, true) + const _item = await ShowQueryItemService({ + contactId: contact.id, + name: 'insert_protocol_info' + }) + - if (last_messages.length > 0 && last_messages[0].body.includes('validado') && msg.body.trim() != '0') { + // let last_messages = await ShowTicketMessage(ticket.id, 2, true) + + // if (last_messages.length > 0 && last_messages[0].body.includes('validado') && msg.body.trim() != '0') { + + + if (_item && _item?.status && msg.body.trim() != '0') { + + _item.update({ status: false }) await SendWhatsAppMessage({ body: `Aguarde inserindo informação, em breve te atualizaremos`, ticket }) - let aux_msg = last_messages[0].body + const item: QueryItem = await ShowQueryItemService({ + contactId: contact.id, + name: 'n_chamado_web' + }) - aux_msg = aux_msg.split('\n')[0] - let index = aux_msg.indexOf('do protocolo ') + if (!item?.queryItem) { - aux_msg = aux_msg.substring(index, aux_msg.length) + botSendMessage(ticket, `Ops! Houve um erro, tente novamente.`) + return + } - let regex = /[0-9-]+/g; - - let matches: any = aux_msg.match(regex); - - console.log("~~~~~~~~~~~~~~~~~~~~~~> matches.join(''): ", matches.join('')); let response = await endPointQuery( 'http://177.107.192.247:8095/labs/monitoramentohit/api/api.php', 'post', { - 'params[n_chamado_web]': matches.join(''), + 'params[n_chamado_web]': item?.queryItem, 'method': 'omnihit.chamadoaddobs', 'params[obs]': msg.body })