Merge branch 'whats_session_out' into dialogflow_sessions_out

pull/20/head
adriano 2023-04-24 14:30:42 -03:00
commit b08fbbf56f
20 changed files with 957 additions and 847 deletions

View File

@ -561,7 +561,7 @@ app.post('/api/DeleteWhatsAppMessage', async (req, res) => {
} catch (error) {
console.log('There was an error on try disconnect the whatsapp: ', error)
console.log('There was an error on try delete the massage: ', error)
res.status(500).json({ message: "There was an error on trying delete the message" });
return

View File

@ -28,6 +28,8 @@ const CreateContactService = async ({
extraInfo = []
}: Request): Promise<Contact> => {
try {
const numberExists = await Contact.findOne({
where: { number }
});
@ -57,6 +59,13 @@ const CreateContactService = async ({
//
return contact;
} catch (error: any) {
console.error('===> Error on CreateContactService.ts file: \n', error)
throw new AppError(error.message);
}
};
export default CreateContactService;

View File

@ -2,6 +2,8 @@ import { getIO } from "../../libs/socket";
import Contact from "../../models/Contact";
import { createOrUpdateContactCache } from '../../helpers/ContactsCache'
import { tr } from "date-fns/locale";
import AppError from "../../errors/AppError";
interface ExtraInfo {
name: string;
@ -25,6 +27,9 @@ const CreateOrUpdateContactService = async ({
email = "",
extraInfo = []
}: Request): Promise<Contact> => {
try {
const number = isGroup ? rawNumber : rawNumber.replace(/[^0-9]/g, "");
const io = getIO();
@ -66,6 +71,12 @@ const CreateOrUpdateContactService = async ({
}
return contact;
} catch (error: any) {
console.error('===> Error on CreateOrUpdateContactService.ts file: \n', error)
throw new AppError(error.message);
}
};
export default CreateOrUpdateContactService;

View File

@ -4,6 +4,7 @@ import ContactCustomField from "../../models/ContactCustomField";
import { updateTicketsByContactsCache } from '../../helpers/TicketCache'
import { updateContactCacheById } from '../../helpers/ContactsCache'
import { tr } from "date-fns/locale";
interface ExtraInfo {
id?: number;
@ -27,6 +28,9 @@ const UpdateContactService = async ({
contactData,
contactId
}: Request): Promise<Contact> => {
try {
const { email, name, number, extraInfo } = contactData;
// console.log('email, name, number, extraInfo: ', email, name, number, extraInfo)
@ -63,19 +67,17 @@ const UpdateContactService = async ({
//Solução para o erro tcp_wrap.cc
// console.log('----------> oldNumber: ', oldNumber)
console.log('----------> oldNumber: ', oldNumber)
if (number) {
const numberExists = await Contact.findOne({
where: { number }
});
if (numberExists && numberExists.id != +contactId) {
if (numberExists && numberExists.id != +contactId && numberExists.id != +contactId) {
throw new AppError("ERR_DUPLICATED_CONTACT");
}
}
//
await contact.update({
name,
@ -83,6 +85,8 @@ const UpdateContactService = async ({
email
});
//TEST DEL
await updateTicketsByContactsCache(oldNumber, contact.name, contact.number)
//
@ -99,6 +103,12 @@ const UpdateContactService = async ({
await updateContactCacheById(contact.id, JSON.parse(JSON.stringify(contact)))
return contact;
} catch (error: any) {
console.error('===> Error on UpdateContactService.ts file: \n', error)
throw new AppError(error.message);
}
};
export default UpdateContactService;

View File

@ -1,3 +1,4 @@
import AppError from "../../errors/AppError";
import { updateTicketCacheByTicketId } from "../../helpers/TicketCache";
import { getIO } from "../../libs/socket";
import Message from "../../models/Message";
@ -21,6 +22,8 @@ const CreateMessageService = async ({ messageData }: Request): Promise<Message>
// console.log('UPSERT MESSAGE messageData: ', messageData)
try {
await Message.upsert(messageData);
const message = await Message.findByPk(messageData.id, {
@ -75,6 +78,13 @@ const CreateMessageService = async ({ messageData }: Request): Promise<Message>
return message;
} catch (error: any) {
console.error('===> Error on CreateMessageService.ts file: \n', error)
throw new AppError(error.message);
}
};
export default CreateMessageService;

View File

@ -10,6 +10,9 @@ interface QueueData {
}
const CreateQueueService = async (queueData: QueueData): Promise<Queue> => {
try {
const { color, name } = queueData;
const queueSchema = Yup.object().shape({
@ -56,7 +59,7 @@ const CreateQueueService = async (queueData: QueueData): Promise<Queue> => {
try {
await queueSchema.validate({ color, name });
} catch (err) {
} catch (err: any) {
throw new AppError(err.message);
}
@ -65,6 +68,12 @@ const CreateQueueService = async (queueData: QueueData): Promise<Queue> => {
deleteFileFromTMP(`botInfo.json`)
return queue;
} catch (error: any) {
console.error('===> Error on CreateQueueService.ts file: \n', error)
throw new AppError(error.message);
}
};
export default CreateQueueService;

View File

@ -15,6 +15,9 @@ const UpdateQueueService = async (
queueId: number | string,
queueData: QueueData
): Promise<Queue> => {
try {
const { color, name } = queueData;
const queueSchema = Yup.object().shape({
@ -60,7 +63,7 @@ const UpdateQueueService = async (
try {
await queueSchema.validate({ color, name });
} catch (err) {
} catch (err: any) {
throw new AppError(err.message);
}
@ -71,6 +74,12 @@ const UpdateQueueService = async (
deleteFileFromTMP(`botInfo.json`)
return queue;
} catch (error: any) {
console.error('===> Error on UpdateQueueService.ts file: \n', error)
throw new AppError(error.message);
}
};
export default UpdateQueueService;

View File

@ -22,6 +22,8 @@ const CreateSchedulingNotifyService = async ({
message
}: Request): Promise<SchedulingNotify> => {
try {
let schedulingNotify = null;
if (schedulingNotifyId) {
@ -63,6 +65,12 @@ const CreateSchedulingNotifyService = async ({
return schedulingNotify
} catch (error: any) {
console.error('===> Error on CreateSchedulingNotifyService.ts file: \n', error)
throw new AppError(error.message);
}
}

View File

@ -16,6 +16,9 @@ const UpdateSchedulingNotify = async ({
schedulingDataId
}: Request): Promise<SchedulingNotify> => {
try {
const { name } = schedulingData;
const updateScheduling = await SchedulingNotify.findOne({
@ -34,6 +37,12 @@ const UpdateSchedulingNotify = async ({
});
return updateScheduling;
} catch (error: any) {
console.error('===> Error on CreateSchedulingNotifyService.ts file: \n', error)
throw new AppError(error.message);
}
};
export default UpdateSchedulingNotify;

View File

@ -10,6 +10,8 @@ const UpdateSettingService = async ({
key,
value
}: Request): Promise<Setting | undefined> => {
try {
const setting = await Setting.findOne({
where: { key }
});
@ -21,6 +23,11 @@ const UpdateSettingService = async ({
await setting.update({ value });
return setting;
} catch (error: any) {
console.error('===> Error on UpdateSettingService.ts file: \n', error)
throw new AppError(error.message);
}
};
export default UpdateSettingService;

View File

@ -29,6 +29,9 @@ const CreateTicketService = async ({
status,
userId
}: Request): Promise<Ticket> => {
try {
const defaultWhatsapp = await GetDefaultWhatsApp(userId);
await CheckContactOpenTickets(contactId);
@ -80,6 +83,12 @@ const CreateTicketService = async ({
return ticket;
} catch (error: any) {
console.error('===> Error on CreateTicketService.ts file: \n', error)
throw new AppError(error.message);
}
};
export default CreateTicketService;

View File

@ -5,6 +5,7 @@ import Contact from "../../models/Contact";
import Ticket from "../../models/Ticket";
import ShowWhatsAppService from "../WhatsappService/ShowWhatsAppService";
import ShowTicketService from "./ShowTicketService";
import AppError from "../../errors/AppError";
const FindOrCreateTicketService = async (
@ -13,6 +14,9 @@ const FindOrCreateTicketService = async (
unreadMessages: number,
groupContact?: Contact
): Promise<Ticket> => {
try {
let ticket = await Ticket.findOne({
where: {
status: {
@ -109,8 +113,12 @@ const FindOrCreateTicketService = async (
ticket = await ShowTicketService(ticket.id);
return ticket;
} catch (error: any) {
console.error('===> Error on FindOrCreateTicketService.ts file: \n', error)
throw new AppError(error.message);
}
};
export default FindOrCreateTicketService;

View File

@ -7,6 +7,7 @@ import ShowWhatsAppService from "../WhatsappService/ShowWhatsAppService";
import ShowTicketService from "./ShowTicketService";
import { createOrUpdateTicketCache } from '../../helpers/TicketCache'
import AppError from "../../errors/AppError";
var flatten = require('flat')
@ -33,6 +34,9 @@ const UpdateTicketService = async ({
ticketData,
ticketId
}: Request): Promise<Response> => {
try {
const { status, userId, queueId, statusChatEnd } = ticketData;
const ticket = await ShowTicketService(ticketId);
@ -99,6 +103,12 @@ const UpdateTicketService = async ({
return { ticket, oldStatus, oldUserId };
} catch (error: any) {
console.error('===> Error on UpdateTicketService.ts file: \n', error)
throw new AppError(error.message);
}
};
export default UpdateTicketService;

View File

@ -34,7 +34,7 @@ const CreateOrUpdateUserOnlineTime = async ({
status,
}: Request): Promise<UserOnlineTime> => {
try {
const io = getIO();
let userOnlineTime: any = null;
@ -174,6 +174,12 @@ const CreateOrUpdateUserOnlineTime = async ({
return userOnlineTime
} catch (error: any) {
console.error('===> Error on CreateOrUpdateUserOnlineTime.ts file: \n', error)
throw new AppError(error.message);
}
}

View File

@ -28,6 +28,9 @@ const CreateUserService = async ({
queueIds = [],
profile = "master"
}: Request): Promise<Response> => {
try {
const schema = Yup.object().shape({
name: Yup.string().required().min(2),
@ -83,6 +86,12 @@ const CreateUserService = async ({
deleteFileFromTMP(`botInfo.json`)
return serializedUser;
} catch (error: any) {
console.error('===> Error on CreateUserService.ts file: \n', error)
throw new AppError(error.message);
}
};
export default CreateUserService;

View File

@ -30,6 +30,9 @@ const UpdateUserService = async ({
userData,
userId
}: Request): Promise<Response | undefined> => {
try {
const user = await ShowUserService(userId);
const schema = Yup.object().shape({
@ -90,6 +93,13 @@ const UpdateUserService = async ({
deleteFileFromTMP(`botInfo.json`)
return serializedUser;
} catch (error: any) {
console.error('===> Error on UpdateUserService.ts file: \n', error)
throw new AppError(error.message);
}
};
export default UpdateUserService;

View File

@ -43,6 +43,8 @@ const SendWhatsAppMessage = async ({
number
}: Request): Promise<WbotMessage | any> => {
try {
let timestamp = Math.floor(Date.now() / 1000)
var timetaken = `########################################${timestamp}| TicketId: ${ticket.id} => Time taken to send the message`;
@ -75,7 +77,7 @@ const SendWhatsAppMessage = async ({
if (listWhatsapp.whatsapp && listWhatsapp.whatsapp.status != 'CONNECTED' && listWhatsapp.whatsapps.length > 0) {
console.log('kkkkkkkkkkkkkkkkkkkkkkkkkkkk: ', listWhatsapp.whatsapps[0].id)
// console.log('kkkkkkkkkkkkkkkkkkkkkkkkkkkk: ', listWhatsapp.whatsapps[0].id)
await ticket.update({ whatsappId: + listWhatsapp.whatsapps[0].id });
@ -84,22 +86,14 @@ const SendWhatsAppMessage = async ({
}
if (listWhatsapp.whatsapps.length > 1) {
const _whatsapp = listWhatsapp.whatsapps[Math.floor(Math.random() * listWhatsapp.whatsapps.length)];
await ticket.update({ whatsappId: +_whatsapp.id });
// await ticket.reload();
}
// console.log('listWhatsapp.whatsapps.length: ', listWhatsapp.whatsapps.length)
// console.log('listWhatsapp.whatsapp.status: ', listWhatsapp.whatsapp.status)
if (listWhatsapp.whatsapps.length == 0 && listWhatsapp.whatsapp.status != 'CONNECTED') {
console.log('listWhatsapp.whatsapps == 0')
@ -125,43 +119,7 @@ const SendWhatsAppMessage = async ({
}
console.log('1 --------> ticket.whatsappId: ', ticket.whatsappId)
// const wbot = await GetTicketWbot(ticket);
/*const whatsapp = await Whatsapp.findByPk(ticket.whatsappId);
if (whatsapp && whatsapp.status != 'CONNECTED') {
let whatsapps = await wbotByUserQueue(ticket.userId)
if (whatsapps.length > 0) {
if (whatsapps.length > 1) {
await ticket.update({ whatsappId: whatsapps[+WhatsIndex(whatsapps)].id });
}
else {
await ticket.update({ whatsappId: whatsapps[0].id });
}
}
}
const wbot = await GetTicketWbot(ticket);
*/
console.log('2 --------> send from whatsapp ticket.whatsappId: ', ticket.whatsappId)
console.log('1 --------> send from whatsapp ticket.whatsappId: ', ticket.whatsappId)
try {
@ -171,24 +129,20 @@ const SendWhatsAppMessage = async ({
await updateTicketCacheByTicketId(ticket.id, { lastMessage: body, updatedAt: new Date(ticket.updatedAt).toISOString() })
// const sentMessage = await wbot.sendMessage(`${ticket.contact.number}@${ticket.isGroup ? "g" : "c"}.us`, body, { quotedMessageId: quotedMsgSerializedId, linkPreview: false });
// await ticket.update({ lastMessage: body });
// await updateTicketCacheByTicketId(ticket.id, { lastMessage: body, updatedAt: new Date(ticket.updatedAt).toISOString() })
// return sentMessage;
console.timeEnd(timetaken)
} catch (err) {
// const whatsapp = await ShowWhatsAppService(ticket.whatsappId);
} catch (err: any) {
console.error('0 ===> Error on SendWhatsAppMessage.ts file: \n', err)
throw new AppError("ERR_SENDING_WAPP_MSG");
}
} catch (error: any) {
console.error('===> Error on SendWhatsAppMessage.ts file: \n', error)
throw new AppError(error.message);
}
};
export default SendWhatsAppMessage;

View File

@ -70,6 +70,7 @@ import { _restore } from "../../helpers/RestoreControll";
import sendWhatsAppMessageSocket from "../../helpers/SendWhatsappMessageSocket";
import { getWhatsappIds, setWhatsappId } from "../../helpers/WhatsappIdMultiSessionControl";
import SendWhatsAppMedia from "./SendWhatsAppMedia";
import AppError from "../../errors/AppError";
@ -964,11 +965,6 @@ const handleMessage = async (
}
if (!isValidMsg(msg)) {
return;
}
@ -1072,7 +1068,14 @@ const handleMessage = async (
// console.log('PARA RESPONDER PELO MEMOS WHATSAPP wbot.id: ', wbot.id, ' | wbot.status: ', wbot.status)
// console.log('WHATSAPP STATUS ticket.whatsappId: ', ticket.whatsappId)
try {
await ticket.update({ whatsappId: wbot.id });
} catch (error: any) {
console.error('===> Error on wbotMessageListener.ts into handleMessage fuction file: \n', error)
throw new AppError(error.message);
}
}
//

View File

@ -30,6 +30,9 @@ const CreateWhatsAppService = async ({
farewellMessage,
isDefault = false,
}: Request): Promise<Response> => {
try {
const schema = Yup.object().shape({
name: Yup.string()
.required()
@ -91,6 +94,13 @@ const CreateWhatsAppService = async ({
await AssociateWhatsappQueue(whatsapp, queueIds);
return { whatsapp, oldDefaultWhatsapp };
} catch (error: any) {
console.error('===> Error on CreateWhatsAppService.ts file: \n', error)
throw new AppError(error.message);
}
};
export default CreateWhatsAppService;

View File

@ -37,6 +37,9 @@ const UpdateWhatsAppService = async ({
whatsappData,
whatsappId
}: Request): Promise<Response> => {
try {
const schema = Yup.object().shape({
name: Yup.string().min(2),
status: Yup.string(),
@ -111,6 +114,12 @@ const UpdateWhatsAppService = async ({
await AssociateWhatsappQueue(whatsapp, queueIds);
return { whatsapp, oldDefaultWhatsapp };
} catch (error: any) {
console.error('===> Error on UpdateWhatsAppService.ts file: \n', error)
throw new AppError(error.message);
}
};
export default UpdateWhatsAppService;