Criação completa do envio de mensagem programada para cliente ao finalizar o atendimento

pull/1/head
adriano 2022-03-01 00:27:17 -03:00
parent d8a00b6bce
commit 303098636a
8 changed files with 124 additions and 15 deletions

View File

@ -10,7 +10,7 @@ import "./database";
import uploadConfig from "./config/upload"; import uploadConfig from "./config/upload";
import AppError from "./errors/AppError"; import AppError from "./errors/AppError";
import routes from "./routes"; import routes from "./routes";
import { logger } from "./utils/logger"; import { logger } from "./utils/logger";
Sentry.init({ dsn: process.env.SENTRY_DSN }); Sentry.init({ dsn: process.env.SENTRY_DSN });

View File

@ -39,7 +39,7 @@ export const store = async (req: Request, res: Response): Promise<Response> => {
const { ticketId } = req.params; const { ticketId } = req.params;
const { body, quotedMsg }: MessageData = req.body; const { body, quotedMsg }: MessageData = req.body;
const medias = req.files as Express.Multer.File[]; const medias = req.files as Express.Multer.File[];
const ticket = await ShowTicketService(ticketId); const ticket = await ShowTicketService(ticketId);
SetTicketMessagesAsRead(ticket); SetTicketMessagesAsRead(ticket);
@ -51,6 +51,9 @@ export const store = async (req: Request, res: Response): Promise<Response> => {
}) })
); );
} else { } else {
console.log('------- quotedMsg: ', quotedMsg)
await SendWhatsAppMessage({ body, ticket, quotedMsg }); await SendWhatsAppMessage({ body, ticket, quotedMsg });
} }

View File

@ -70,6 +70,11 @@ export const index = async (req: Request, res: Response): Promise<Response> => {
export const store = async (req: Request, res: Response): Promise<Response> => { export const store = async (req: Request, res: Response): Promise<Response> => {
const { contactId, status, userId }: TicketData = req.body; const { contactId, status, userId }: TicketData = req.body;
// naty
// console.log(
// `contactId: ${contactId} \n| status: ${status} \n| userId: ${userId}`
// )
const ticket = await CreateTicketService({ contactId, status, userId }); const ticket = await CreateTicketService({ contactId, status, userId });
const io = getIO(); const io = getIO();

View File

@ -0,0 +1,76 @@
import SetTicketMessagesAsRead from "../helpers/SetTicketMessagesAsRead";
import ShowTicketService from "../services/TicketServices/ShowTicketService";
import SendWhatsAppMessage from "../services/WbotServices/SendWhatsAppMessage";
import ListSchedulingNotifyService from "../services/SchedulingNotifyServices/ListSchedulingNotifyService";
import DeleteSchedulingNotifyService from "../services/SchedulingNotifyServices/DeleteSchedulingNotifyService";
let countTest: number = 0
let scheduler_monitor:any;
// const test = async () => {
// const ticket = await ShowTicketService('336');
// SetTicketMessagesAsRead(ticket);
// await SendWhatsAppMessage({ body: 'Olá Sr Adriano, estamos entrando em contato para confirmar seu retorno hoje', ticket });
// }
const monitor = async () => {
countTest += 1
console.log(`${countTest}`)
let date = new Date()
let day = date.getDate().toString().padStart(2, '0');
let month = (date.getMonth()+1).toString().padStart(2, '0');
let year = date.getFullYear();
let hour = date.getHours()
let minute = date.getMinutes()
let fullDate = `${year}-${month}-${day}`;
let dateParm = `${fullDate} ${hour.toString().padStart(2, '0')}:${minute.toString().padStart(2, '0')}:00`
console.log(dateParm);
const { schedulingNotifies, count, hasMore } = await ListSchedulingNotifyService({ searchParam: dateParm, pageNumber: "1" });
if(schedulingNotifies.length){
const ticket = await ShowTicketService(schedulingNotifies[0].ticketId);
SetTicketMessagesAsRead(ticket);
await SendWhatsAppMessage({
body: schedulingNotifies[0].message, ticket
});
DeleteSchedulingNotifyService(schedulingNotifies[0].id)
}
};
export const startSchedulingMonitor =async (mileseconds: number) => {
scheduler_monitor = setInterval(monitor, mileseconds)
}
export const stopSchedulingMonitor =async ( ) => {
clearInterval(scheduler_monitor)
}

View File

@ -11,12 +11,7 @@ const upload = multer(uploadConfig);
messageRoutes.get("/messages/:ticketId", isAuth, MessageController.index); messageRoutes.get("/messages/:ticketId", isAuth, MessageController.index);
messageRoutes.post( messageRoutes.post("/messages/:ticketId", isAuth, upload.array("medias"), MessageController.store);
"/messages/:ticketId",
isAuth,
upload.array("medias"),
MessageController.store
);
messageRoutes.delete("/messages/:messageId", isAuth, MessageController.remove); messageRoutes.delete("/messages/:messageId", isAuth, MessageController.remove);

View File

@ -4,6 +4,8 @@ import { initIO } from "./libs/socket";
import { logger } from "./utils/logger"; import { logger } from "./utils/logger";
import { StartAllWhatsAppsSessions } from "./services/WbotServices/StartAllWhatsAppsSessions"; import { StartAllWhatsAppsSessions } from "./services/WbotServices/StartAllWhatsAppsSessions";
import { startSchedulingMonitor } from "./helpers/SchedulingNotifySendMessage"
const server = app.listen(process.env.PORT, () => { const server = app.listen(process.env.PORT, () => {
logger.info(`Server started on port: ${process.env.PORT}`); logger.info(`Server started on port: ${process.env.PORT}`);
}); });
@ -11,3 +13,5 @@ const server = app.listen(process.env.PORT, () => {
initIO(server); initIO(server);
StartAllWhatsAppsSessions(); StartAllWhatsAppsSessions();
gracefulShutdown(server); gracefulShutdown(server);
startSchedulingMonitor(5000)

View File

@ -1,4 +1,4 @@
import { Sequelize } from "sequelize"; import { Op, Sequelize } from "sequelize";
import SchedulingNotify from "../../models/SchedulingNotify"; import SchedulingNotify from "../../models/SchedulingNotify";
interface Request { interface Request {
@ -16,14 +16,39 @@ interface Request {
searchParam = "", searchParam = "",
pageNumber = "1" pageNumber = "1"
}: Request): Promise<Response> => { }: Request): Promise<Response> => {
const whereCondition = { // const whereCondition = {
message: Sequelize.where( // message: Sequelize.where(
Sequelize.fn("LOWER", Sequelize.col("cpf_cnpj")), "LIKE", `%${searchParam.toLowerCase().trim()}%`)
// Sequelize.fn("date", Sequelize.col("schedulingDate")), `${searchParam.toLowerCase().trim()}`,
// ),
// };
let date = searchParam.split(' ')[0]
let hour = searchParam.split(' ')[1].split(':')[0]
let minute = searchParam.split(' ')[1].split(':')[1]
const whereCondition = {
[Op.and]: [
{
"$schedulingDate$": Sequelize.where(Sequelize.fn("date", Sequelize.col("schedulingDate")), `${date.trim()}`)
},
{
"$schedulingDate$": Sequelize.where(Sequelize.fn("hour", Sequelize.col("schedulingDate")), `${hour.trim()}`)
},
{
"$schedulingDate$": Sequelize.where(Sequelize.fn("minute", Sequelize.col("schedulingDate")), `${minute.trim()}`)
}
]
}; };
const limit = 20;
const limit = 1;
const offset = limit * (+pageNumber - 1); const offset = limit * (+pageNumber - 1);
const { count, rows: schedulingNotifies } = await SchedulingNotify.findAndCountAll({ const { count, rows: schedulingNotifies } = await SchedulingNotify.findAndCountAll({
raw: true,
where: whereCondition, where: whereCondition,
limit, limit,
offset, offset,

View File

@ -61,7 +61,7 @@ const TicketActionButtons = ({ ticket, schedule }) => {
} }
const handleModal = (status, userId) => { const handleModal = (/*status, userId*/) => {
render(<Modal render(<Modal
modal_header={'Finalização de Atendimento'} modal_header={'Finalização de Atendimento'}
@ -154,7 +154,8 @@ const TicketActionButtons = ({ ticket, schedule }) => {
color="primary" color="primary"
onClick={e => { onClick={e => {
handleModal( "closed", user?.id)
handleModal()
// handleUpdateTicketStatus(e, "closed", user?.id) // handleUpdateTicketStatus(e, "closed", user?.id)
}} }}