atualização para guardar em banco de dados o numero do chamdado

pull/20/head
adriano 2023-07-18 13:01:56 -03:00
parent 2497f3711a
commit d993b20637
8 changed files with 326 additions and 18 deletions

View File

@ -21,6 +21,9 @@ import GetProfilePicUrl from "../services/WbotServices/GetProfilePicUrl";
import CreateContactService from "../services/ContactServices/CreateContactService"; import CreateContactService from "../services/ContactServices/CreateContactService";
import { resourceUsage } from "process"; import { resourceUsage } from "process";
import FindOrCreateTicketServiceBot from "../services/TicketServices/FindOrCreateTicketServiceBot"; import FindOrCreateTicketServiceBot from "../services/TicketServices/FindOrCreateTicketServiceBot";
import ShowQuickAnswerService from "../services/QuickAnswerService/ShowQuickAnswerService";
import ShowQueryItemService from "../services/SLM/ShowQueryItemService";
import QueryItem from "../models/QueryItem";
@ -132,7 +135,7 @@ export const hit = async (req: Request, res: Response): Promise<Response> => {
await sendMessageHitMonitoring(response, ticket); 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) { else if (ticket.id && ticket.userId == botInfo.userIdBot) {
@ -149,7 +152,7 @@ export const hit = async (req: Request, res: Response): Promise<Response> => {
await sendMessageHitMonitoring(response, ticket); await sendMessageHitMonitoring(response, ticket);
await sendMessageInsertInfoSLM(req, ticket, ['atdabriu', 'atdatualizou']); await sendMessageInsertInfoSLM(req, ticket, ['atdabriu', 'atdatualizou'], contact.id);
} }
} }
@ -162,15 +165,62 @@ export const hit = async (req: Request, res: Response): Promise<Response> => {
}; };
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'])) { if (params.includes(req.body['action'])) {
if (insert_protocol_info &&
insert_protocol_info?.status &&
n_chamado_web?.queryItem) {
await sendMessageHitMonitoring(`🔄 Houve uma atualização no chamado acima`, ticket);
await new Promise(f => setTimeout(f, 1000)); 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); 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);
}
}
}
} }
async function sendMessageHitMonitoring(msg: any, ticket: Ticket) { async function sendMessageHitMonitoring(msg: any, ticket: Ticket) {

View File

@ -16,6 +16,7 @@ import StatusChatEnd from "../models/StatusChatEnd";
import UserOnlineTime from "../models/UserOnlineTime"; import UserOnlineTime from "../models/UserOnlineTime";
import Dialogflow from "../models/Dialogflow"; import Dialogflow from "../models/Dialogflow";
import QueryItem from "../models/QueryItem";
// eslint-disable-next-line // eslint-disable-next-line
const dbConfig = require("../config/database"); const dbConfig = require("../config/database");
// import dbConfig from "../config/database"; // import dbConfig from "../config/database";
@ -39,6 +40,7 @@ const models = [
StatusChatEnd, StatusChatEnd,
UserOnlineTime, UserOnlineTime,
Dialogflow, Dialogflow,
QueryItem
]; ];
sequelize.addModels(models); sequelize.addModels(models);

View File

@ -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");
}
};

View File

@ -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
});
}
};

View File

@ -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<QueryItem> {
@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;

View File

@ -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<QueryItem> => {
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;

View File

@ -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<any> => {
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;

View File

@ -75,6 +75,9 @@ import { tr } from "date-fns/locale";
import mostRepeatedPhrase from "../../helpers/MostRepeatedPhrase"; import mostRepeatedPhrase from "../../helpers/MostRepeatedPhrase";
import FindOrCreateTicketServiceBot from "../TicketServices/FindOrCreateTicketServiceBot"; import FindOrCreateTicketServiceBot from "../TicketServices/FindOrCreateTicketServiceBot";
import { setMessageAsRead } from "../../helpers/SetMessageAsRead"; 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') { if (params[0] === 'validate_n_chamado_web') {
await FindOrCreateQueryItemService({
contactId: contact.id,
queryItem: params[1].trim(),
name: 'n_chamado_web'
})
let valid = await endPointQuery( let valid = await endPointQuery(
'http://177.107.192.247:8095/labs/monitoramentohit/api/api.php', 'http://177.107.192.247:8095/labs/monitoramentohit/api/api.php',
'post', '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.`) 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') { else if (valid && valid.data.result == 'notfound') {
@ -1105,31 +1120,41 @@ const handleMessage = async (
} }
else { 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 }) 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( let response = await endPointQuery(
'http://177.107.192.247:8095/labs/monitoramentohit/api/api.php', 'http://177.107.192.247:8095/labs/monitoramentohit/api/api.php',
'post', 'post',
{ {
'params[n_chamado_web]': matches.join(''), 'params[n_chamado_web]': item?.queryItem,
'method': 'omnihit.chamadoaddobs', 'method': 'omnihit.chamadoaddobs',
'params[obs]': msg.body 'params[obs]': msg.body
}) })