started messages migration to ts

This commit is contained in:
canove
2020-09-19 22:49:27 -03:00
parent 70c391e8ef
commit 9368ef2512
10 changed files with 295 additions and 230 deletions

View File

@@ -1,203 +1,188 @@
// const Message = require("../models/Message"); import { Request, Response } from "express";
// const Contact = require("../models/Contact"); import CreateMessageService from "../services/MessageServices/CreateMessageService";
// const User = require("../models/User"); import ListMessagesService from "../services/MessageServices/ListMessagesService";
// const Whatsapp = require("../models/Whatsapp"); // import Sequelize from "sequelize";
// import { MessageMedia } from "whatsapp-web.js";
// import Message from "../models/Message";
// import Contact from "../models/Contact";
// import User from "../models/User";
// import Whatsapp from "../models/Whatsapp";
// const Ticket = require("../models/Ticket"); // import Ticket from "../models/Ticket";
// const { getIO } = require("../libs/socket"); // import { getIO } from "../libs/socket";
// const { getWbot } = require("../libs/wbot"); // import { getWbot } from "../libs/wbot";
// const Sequelize = require("sequelize");
// const { MessageMedia } = require("whatsapp-web.js");
// const setMessagesAsRead = async ticket => { // const setMessagesAsRead = async ticket => {
// const io = getIO(); // const io = getIO();
// const wbot = getWbot(ticket.whatsappId); // const wbot = getWbot(ticket.whatsappId);
// await Message.update( // await Message.update(
// { read: true }, // { read: true },
// { // {
// where: { // where: {
// ticketId: ticket.id, // ticketId: ticket.id,
// read: false, // read: false
// }, // }
// } // }
// ); // );
// try { // try {
// await wbot.sendSeen(`${ticket.contact.number}@c.us`); // await wbot.sendSeen(`${ticket.contact.number}@c.us`);
// } catch (err) { // } catch (err) {
// console.log( // console.log(
// "Could not mark messages as read. Maybe whatsapp session disconnected?" // "Could not mark messages as read. Maybe whatsapp session disconnected?"
// ); // );
// } // }
// io.to("notification").emit("ticket", { // io.to("notification").emit("ticket", {
// action: "updateUnread", // action: "updateUnread",
// ticketId: ticket.id, // ticketId: ticket.id
// }); // });
// }; // };
// exports.index = async (req, res, next) => { type IndexQuery = {
// const { ticketId } = req.params; searchParam: string;
// const { searchParam = "", pageNumber = 1 } = req.query; pageNumber: string;
};
// const whereCondition = { export const index = async (req: Request, res: Response): Promise<Response> => {
// body: Sequelize.where( const { ticketId } = req.params;
// Sequelize.fn("LOWER", Sequelize.col("body")), const { searchParam, pageNumber } = req.query as IndexQuery;
// "LIKE",
// "%" + searchParam.toLowerCase() + "%"
// ),
// };
// const limit = 20; const { count, messages, ticket, hasMore } = await ListMessagesService({
// const offset = limit * (pageNumber - 1); searchParam,
pageNumber,
ticketId
});
// const ticket = await Ticket.findByPk(ticketId, { // const ticketMessages = await ticket.getMessages({
// include: [ // where: whereCondition,
// { // limit,
// model: Contact, // offset,
// as: "contact", // order: [["createdAt", "DESC"]]
// include: "extraInfo", // });
// attributes: ["id", "name", "number", "profilePicUrl"],
// },
// {
// model: User,
// as: "user",
// },
// ],
// });
// if (!ticket) { // const count = await ticket.countMessages();
// return res.status(404).json({ error: "No ticket found with this ID" });
// }
// await setMessagesAsRead(ticket); // const serializedMessages = ticketMessages.map(message => {
// return {
// ...message.dataValues,
// mediaUrl: `${
// message.mediaUrl
// ? `${process.env.BACKEND_URL}:${process.env.PROXY_PORT}/public/${message.mediaUrl}`
// : ""
// }`
// };
// });
// const ticketMessages = await ticket.getMessages({ // const hasMore = count > offset + ticketMessages.length;
// where: whereCondition,
// limit,
// offset,
// order: [["createdAt", "DESC"]],
// });
// const count = await ticket.countMessages(); // return res.json({
// messages: serializedMessages.reverse(),
// ticket,
// count,
// hasMore
// });
return res.json({ count, messages, ticket, hasMore });
};
// const serializedMessages = ticketMessages.map(message => { export const store = async (req: Request, res: Response): Promise<Response> => {
// return { // const io = getIO();
// ...message.dataValues,
// mediaUrl: `${
// message.mediaUrl
// ? `${process.env.BACKEND_URL}:${process.env.PROXY_PORT}/public/${message.mediaUrl}`
// : ""
// }`,
// };
// });
// const hasMore = count > offset + ticketMessages.length; const { ticketId } = req.params;
const messageData = req.body;
// return res.json({ const message = await CreateMessageService({ messageData, ticketId });
// messages: serializedMessages.reverse(),
// ticket, // const media = req.file;
// count, // let sentMessage;
// hasMore,
// }); // const ticket = await Ticket.findByPk(ticketId, {
// }; // include: [
// {
// exports.store = async (req, res, next) => { // model: Contact,
// const io = getIO(); // as: "contact",
// attributes: ["number", "name", "profilePicUrl"]
// const { ticketId } = req.params; // }
// const message = req.body; // ]
// const media = req.file; // });
// let sentMessage;
// if (!ticket) {
// const ticket = await Ticket.findByPk(ticketId, { // return res.status(404).json({ error: "No ticket found with this ID" });
// include: [ // }
// {
// model: Contact, // if (!ticket.whatsappId) {
// as: "contact", // const defaultWhatsapp = await Whatsapp.findOne({
// attributes: ["number", "name", "profilePicUrl"], // where: { default: true }
// }, // });
// ],
// }); // if (!defaultWhatsapp) {
// return res
// if (!ticket) { // .status(404)
// return res.status(404).json({ error: "No ticket found with this ID" }); // .json({ error: "No default WhatsApp found. Check Connection page." });
// } // }
// if (!ticket.whatsappId) { // await ticket.setWhatsapp(defaultWhatsapp);
// const defaultWhatsapp = await Whatsapp.findOne({ // }
// where: { default: true },
// }); // const wbot = getWbot(ticket.whatsappId);
// if (!defaultWhatsapp) { // try {
// return res // if (media) {
// .status(404) // const newMedia = MessageMedia.fromFilePath(req.file.path);
// .json({ error: "No default WhatsApp found. Check Connection page." });
// } // message.mediaUrl = req.file.filename;
// if (newMedia.mimetype) {
// await ticket.setWhatsapp(defaultWhatsapp); // message.mediaType = newMedia.mimetype.split("/")[0];
// } // } else {
// message.mediaType = "other";
// const wbot = getWbot(ticket.whatsappId); // }
// try { // sentMessage = await wbot.sendMessage(
// if (media) { // `${ticket.contact.number}@c.us`,
// const newMedia = MessageMedia.fromFilePath(req.file.path); // newMedia
// );
// message.mediaUrl = req.file.filename;
// if (newMedia.mimetype) { // await ticket.update({ lastMessage: message.mediaUrl });
// message.mediaType = newMedia.mimetype.split("/")[0]; // } else {
// } else { // sentMessage = await wbot.sendMessage(
// message.mediaType = "other"; // `${ticket.contact.number}@c.us`,
// } // message.body
// );
// sentMessage = await wbot.sendMessage( // await ticket.update({ lastMessage: message.body });
// `${ticket.contact.number}@c.us`, // }
// newMedia // } catch (err) {
// ); // console.log(
// "Could not create whatsapp message. Is session details valid? "
// await ticket.update({ lastMessage: message.mediaUrl }); // );
// } else { // }
// sentMessage = await wbot.sendMessage(
// `${ticket.contact.number}@c.us`, // if (sentMessage) {
// message.body // message.id = sentMessage.id.id;
// ); // const newMessage = await ticket.createMessage(message);
// await ticket.update({ lastMessage: message.body });
// } // const serialziedMessage = {
// } catch (err) { // ...newMessage.dataValues,
// console.log( // mediaUrl: `${
// "Could not create whatsapp message. Is session details valid? " // message.mediaUrl
// ); // ? `${process.env.BACKEND_URL}:${process.env.PROXY_PORT}/public/${message.mediaUrl}`
// } // : ""
// }`
// if (sentMessage) { // };
// message.id = sentMessage.id.id;
// const newMessage = await ticket.createMessage(message); // io.to(ticketId).to("notification").emit("appMessage", {
// action: "create",
// const serialziedMessage = { // message: serialziedMessage,
// ...newMessage.dataValues, // ticket,
// mediaUrl: `${ // contact: ticket.contact
// message.mediaUrl // });
// ? `${process.env.BACKEND_URL}:${process.env.PROXY_PORT}/public/${message.mediaUrl}`
// : "" // await setMessagesAsRead(ticket);
// }`,
// }; return res.status(200).json(message);
};
// io.to(ticketId).to("notification").emit("appMessage", {
// action: "create", // return res
// message: serialziedMessage, // .status(500)
// ticket: ticket, // .json({ error: "Cannot sent whatsapp message. Check connection page." });
// contact: ticket.contact,
// });
// await setMessagesAsRead(ticket);
// return res.status(200).json({ newMessage, ticket });
// }
// return res
// .status(500)
// .json({ error: "Cannot sent whatsapp message. Check connection page." });
// }; // };

View File

@@ -1,23 +1,12 @@
import { Request, Response } from "express"; import { Request, Response } from "express";
import GetDefaultWhatsapp from "../helpers/GetDefaultWhatsapp";
import Ticket from "../models/Ticket";
import CreateTicketService from "../services/TicketServices/CreateTicketService"; import CreateTicketService from "../services/TicketServices/CreateTicketService";
import DeleteTicketService from "../services/TicketServices/DeleteTicketService"; import DeleteTicketService from "../services/TicketServices/DeleteTicketService";
import ListTicketsService from "../services/TicketServices/ListTicketsService"; import ListTicketsService from "../services/TicketServices/ListTicketsService";
import UpdateTicketService from "../services/TicketServices/UpdateTicketService"; import UpdateTicketService from "../services/TicketServices/UpdateTicketService";
// const Sequelize = require("sequelize");
// const { startOfDay, endOfDay, parseISO } = require("date-fns");
// const Ticket = require("../models/Ticket");
// const Contact = require("../models/Contact");
// const Message = require("../models/Message");
// const Whatsapp = require("../models/Whatsapp");
// const { getIO } = require("../libs/socket"); // const { getIO } = require("../libs/socket");
// import FindWhatsAppService from "../services/WhatsappService/FindWhatsAppService"; type IndexQuery = {
type RequestQuery = {
searchParam: string; searchParam: string;
pageNumber: string; pageNumber: string;
status: string; status: string;
@@ -25,6 +14,11 @@ type RequestQuery = {
showAll: string; showAll: string;
}; };
interface TicketData {
contactId: number;
status: string;
}
export const index = async (req: Request, res: Response): Promise<Response> => { export const index = async (req: Request, res: Response): Promise<Response> => {
const { const {
pageNumber, pageNumber,
@@ -32,7 +26,7 @@ export const index = async (req: Request, res: Response): Promise<Response> => {
date, date,
searchParam, searchParam,
showAll showAll
} = req.query as RequestQuery; } = req.query as IndexQuery;
const userId = req.user.id; const userId = req.user.id;
@@ -96,11 +90,6 @@ export const index = async (req: Request, res: Response): Promise<Response> => {
return res.status(200).json({ tickets, count, hasMore }); return res.status(200).json({ tickets, count, hasMore });
}; };
interface TicketData {
contactId: number;
status: string;
}
export const store = async (req: Request, res: Response): Promise<Response> => { export const store = async (req: Request, res: Response): Promise<Response> => {
const { contactId, status }: TicketData = req.body; const { contactId, status }: TicketData = req.body;

View File

@@ -9,7 +9,7 @@ import UpdateUserService from "../services/UserServices/UpdateUserService";
import FindUserService from "../services/UserServices/FindUserService"; import FindUserService from "../services/UserServices/FindUserService";
import DeleteUserService from "../services/UserServices/DeleteUserService"; import DeleteUserService from "../services/UserServices/DeleteUserService";
type RequestQuery = { type IndexQuery = {
searchParam: string; searchParam: string;
pageNumber: string; pageNumber: string;
}; };
@@ -18,7 +18,7 @@ export const index = async (req: Request, res: Response): Promise<Response> => {
if (req.user.profile !== "admin") { if (req.user.profile !== "admin") {
throw new AppError("Only administrators can access this route.", 403); // should be handled better. throw new AppError("Only administrators can access this route.", 403); // should be handled better.
} }
const { searchParam, pageNumber } = req.query as RequestQuery; const { searchParam, pageNumber } = req.query as IndexQuery;
const { users, count, hasMore } = await ListUsersService({ const { users, count, hasMore } = await ListUsersService({
searchParam, searchParam,

View File

@@ -53,7 +53,7 @@ export const store = async (req: Request, res: Response): Promise<Response> => {
export const show = async (req: Request, res: Response): Promise<Response> => { export const show = async (req: Request, res: Response): Promise<Response> => {
const { whatsappId } = req.params; const { whatsappId } = req.params;
const whatsapp = await FindWhatsAppService(whatsappId); const whatsapp = await FindWhatsAppService({ where: { id: +whatsappId } });
return res.status(200).json(whatsapp); return res.status(200).json(whatsapp);
}; };

View File

@@ -1,12 +1,12 @@
import { Router } from "express"; import { Router } from "express";
// import isAuth from "../middleware/isAuth"; import isAuth from "../middleware/isAuth";
// import { index, store } from "../controllers/MessageController"; import * as MessageController from "../controllers/MessageController";
const messageRoutes = Router(); const messageRoutes = Router();
// messageRoutes.get("/messages/:ticketId", isAuth, index); messageRoutes.get("/messages/:ticketId", isAuth, MessageController.index);
// messageRoutes.post("/messages/:ticketId", isAuth, store); messageRoutes.post("/messages/:ticketId", isAuth, MessageController.store);
export default messageRoutes; export default messageRoutes;

View File

@@ -16,16 +16,6 @@ const ListContactsService = async ({
searchParam = "", searchParam = "",
pageNumber = "1" pageNumber = "1"
}: Request): Promise<Response> => { }: Request): Promise<Response> => {
let includeCondition = [
{
model: Contact,
as: "contact",
attributes: ["name", "number", "profilePicUrl"]
}
];
// let whereCondition = {};
const whereCondition = { const whereCondition = {
[Op.or]: [ [Op.or]: [
{ {
@@ -43,7 +33,6 @@ const ListContactsService = async ({
const { count, rows: contacts } = await Contact.findAndCountAll({ const { count, rows: contacts } = await Contact.findAndCountAll({
where: whereCondition, where: whereCondition,
include: includeCondition,
limit, limit,
offset, offset,
order: [["createdAt", "DESC"]] order: [["createdAt", "DESC"]]

View File

@@ -0,0 +1,24 @@
import Message from "../../models/Message";
import FindTicketService from "../TicketServices/FindTicketService";
interface Request {
ticketId: string;
messageData: Message;
}
const CreateMessageService = async ({
messageData,
ticketId
}: Request): Promise<Message> => {
const ticket = await FindTicketService({ where: { id: +ticketId } });
if (!ticket) {
throw new Error("No ticket found with this ID");
}
const message = Message.create({ ...messageData, ticketId });
return message;
};
export default CreateMessageService;

View File

@@ -0,0 +1,60 @@
import { where, fn, col } from "sequelize";
import Message from "../../models/Message";
import Ticket from "../../models/Ticket";
import FindTicketService from "../TicketServices/FindTicketService";
interface Request {
ticketId: string;
searchParam?: string;
pageNumber?: string;
}
interface Response {
messages: Message[];
ticket: Ticket;
count: number;
hasMore: boolean;
}
const ListMessagesService = async ({
searchParam = "",
pageNumber = "1",
ticketId
}: Request): Promise<Response> => {
const whereCondition = {
body: where(
fn("LOWER", col("body")),
"LIKE",
`%${searchParam.toLowerCase()}%`
),
ticketId
};
const ticket = await FindTicketService({ where: { id: +ticketId } });
if (!ticket) {
throw new Error("No ticket found with this ID");
}
// await setMessagesAsRead(ticket);
const limit = 20;
const offset = limit * (+pageNumber - 1);
const { count, rows: messages } = await Message.findAndCountAll({
where: whereCondition,
limit,
offset,
order: [["createdAt", "DESC"]]
});
const hasMore = count > offset + messages.length;
return {
messages: messages.reverse(),
ticket,
count,
hasMore
};
};
export default ListMessagesService;

View File

@@ -1,28 +1,45 @@
import Whatsapp from "../../models/Whatsapp"; import Ticket from "../../models/Ticket";
import AppError from "../../errors/AppError"; import AppError from "../../errors/AppError";
import Contact from "../../models/Contact";
import User from "../../models/User";
interface WhereParams { interface WhereParams {
id?: number; id?: number;
name?: string; status?: string;
isDefault?: boolean; userId?: number;
contactId?: number;
whatsappId?: number;
} }
interface Request { interface Request {
where?: WhereParams; where?: WhereParams;
} }
const FindTicketService = async ({ where }: Request): Promise<Whatsapp> => { const FindTicketService = async ({ where }: Request): Promise<Ticket> => {
const whereCondition = { ...where }; const whereCondition = { ...where };
const whatsapp = await Whatsapp.findOne({ const ticket = await Ticket.findOne({
where: whereCondition where: whereCondition,
include: [
{
model: Contact,
as: "contact",
attributes: ["id", "name", "number", "profilePicUrl"],
include: ["extraInfo"]
},
{
model: User,
as: "user",
attributes: ["id", "name"]
}
]
}); });
if (!whatsapp) { if (!ticket) {
throw new AppError("No whatsapp found with this conditions.", 404); throw new AppError("No ticket found with this conditions.", 404);
} }
return whatsapp; return ticket;
}; };
export default FindTicketService; export default FindTicketService;

View File

@@ -35,7 +35,8 @@ const ListTicketsService = async ({
{ {
model: Contact, model: Contact,
as: "contact", as: "contact",
attributes: ["name", "number", "profilePicUrl"] attributes: ["id", "name", "number", "profilePicUrl"],
include: ["extraInfo"]
} }
]; ];