mirror of
https://github.com/cheveguerra/whaticket-community.git
synced 2026-04-18 19:59:20 +00:00
finished user store in typscript
This commit is contained in:
@@ -1,170 +0,0 @@
|
||||
const Sequelize = require("sequelize");
|
||||
const { Op } = require("sequelize");
|
||||
|
||||
const Contact = require("../models/Contact");
|
||||
const Whatsapp = require("../models/Whatsapp");
|
||||
const ContactCustomField = require("../models/ContactCustomField");
|
||||
|
||||
const { getIO } = require("../libs/socket");
|
||||
const { getWbot } = require("../libs/wbot");
|
||||
|
||||
exports.index = async (req, res) => {
|
||||
const { searchParam = "", pageNumber = 1 } = req.query;
|
||||
|
||||
const whereCondition = {
|
||||
[Op.or]: [
|
||||
{
|
||||
name: Sequelize.where(
|
||||
Sequelize.fn("LOWER", Sequelize.col("name")),
|
||||
"LIKE",
|
||||
"%" + searchParam.toLowerCase() + "%"
|
||||
),
|
||||
},
|
||||
{ number: { [Op.like]: `%${searchParam}%` } },
|
||||
],
|
||||
};
|
||||
|
||||
let limit = 20;
|
||||
let offset = limit * (pageNumber - 1);
|
||||
|
||||
const { count, rows: contacts } = await Contact.findAndCountAll({
|
||||
where: whereCondition,
|
||||
limit,
|
||||
offset,
|
||||
order: [["createdAt", "DESC"]],
|
||||
});
|
||||
|
||||
const hasMore = count > offset + contacts.length;
|
||||
|
||||
return res.json({ contacts, count, hasMore });
|
||||
};
|
||||
|
||||
exports.store = async (req, res) => {
|
||||
const defaultWhatsapp = await Whatsapp.findOne({
|
||||
where: { default: true },
|
||||
});
|
||||
|
||||
if (!defaultWhatsapp) {
|
||||
return res
|
||||
.status(404)
|
||||
.json({ error: "No default WhatsApp found. Check Connection page." });
|
||||
}
|
||||
|
||||
const wbot = getWbot(defaultWhatsapp);
|
||||
const io = getIO();
|
||||
const newContact = req.body;
|
||||
|
||||
try {
|
||||
const isValidNumber = await wbot.isRegisteredUser(
|
||||
`${newContact.number}@c.us`
|
||||
);
|
||||
if (!isValidNumber) {
|
||||
return res
|
||||
.status(400)
|
||||
.json({ error: "The suplied number is not a valid Whatsapp number" });
|
||||
}
|
||||
} catch (err) {
|
||||
console.log(err);
|
||||
return res.status(500).json({
|
||||
error: "Could not check whatsapp contact. Check connection page.",
|
||||
});
|
||||
}
|
||||
|
||||
const profilePicUrl = await wbot.getProfilePicUrl(
|
||||
`${newContact.number}@c.us`
|
||||
);
|
||||
|
||||
const contact = await Contact.create(
|
||||
{ ...newContact, profilePicUrl },
|
||||
{
|
||||
include: "extraInfo",
|
||||
}
|
||||
);
|
||||
|
||||
io.emit("contact", {
|
||||
action: "create",
|
||||
contact: contact,
|
||||
});
|
||||
|
||||
return res.status(200).json(contact);
|
||||
};
|
||||
|
||||
exports.show = async (req, res) => {
|
||||
const { contactId } = req.params;
|
||||
|
||||
const contact = await Contact.findByPk(contactId, {
|
||||
include: "extraInfo",
|
||||
attributes: ["id", "name", "number", "email"],
|
||||
});
|
||||
|
||||
if (!contact) {
|
||||
return res.status(404).json({ error: "No contact found with this id." });
|
||||
}
|
||||
|
||||
return res.status(200).json(contact);
|
||||
};
|
||||
|
||||
exports.update = async (req, res) => {
|
||||
const io = getIO();
|
||||
|
||||
const updatedContact = req.body;
|
||||
|
||||
const { contactId } = req.params;
|
||||
|
||||
const contact = await Contact.findByPk(contactId, {
|
||||
include: "extraInfo",
|
||||
});
|
||||
|
||||
if (!contact) {
|
||||
return res.status(404).json({ error: "No contact found with this ID" });
|
||||
}
|
||||
|
||||
if (updatedContact.extraInfo) {
|
||||
await Promise.all(
|
||||
updatedContact.extraInfo.map(async info => {
|
||||
await ContactCustomField.upsert({ ...info, contactId: contact.id });
|
||||
})
|
||||
);
|
||||
|
||||
await Promise.all(
|
||||
contact.extraInfo.map(async oldInfo => {
|
||||
let stillExists = updatedContact.extraInfo.findIndex(
|
||||
info => info.id === oldInfo.id
|
||||
);
|
||||
|
||||
if (stillExists === -1) {
|
||||
await ContactCustomField.destroy({ where: { id: oldInfo.id } });
|
||||
}
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
await contact.update(updatedContact);
|
||||
|
||||
io.emit("contact", {
|
||||
action: "update",
|
||||
contact: contact,
|
||||
});
|
||||
|
||||
return res.status(200).json(contact);
|
||||
};
|
||||
|
||||
exports.delete = async (req, res) => {
|
||||
const io = getIO();
|
||||
const { contactId } = req.params;
|
||||
|
||||
const contact = await Contact.findByPk(contactId);
|
||||
|
||||
if (!contact) {
|
||||
return res.status(404).json({ error: "No contact found with this ID" });
|
||||
}
|
||||
|
||||
await contact.destroy();
|
||||
|
||||
io.emit("contact", {
|
||||
action: "delete",
|
||||
contactId: contactId,
|
||||
});
|
||||
|
||||
return res.status(200).json({ message: "Contact deleted" });
|
||||
};
|
||||
@@ -1,38 +0,0 @@
|
||||
const Contact = require("../models/Contact");
|
||||
const Whatsapp = require("../models/Whatsapp");
|
||||
const { getIO } = require("../libs/socket");
|
||||
const { getWbot, initWbot } = require("../libs/wbot");
|
||||
|
||||
exports.store = async (req, res, next) => {
|
||||
const defaultWhatsapp = await Whatsapp.findOne({
|
||||
where: { default: true },
|
||||
});
|
||||
|
||||
if (!defaultWhatsapp) {
|
||||
return res
|
||||
.status(404)
|
||||
.json({ error: "No default WhatsApp found. Check Connection page." });
|
||||
}
|
||||
|
||||
const io = getIO();
|
||||
const wbot = getWbot(defaultWhatsapp);
|
||||
|
||||
let phoneContacts;
|
||||
|
||||
try {
|
||||
phoneContacts = await wbot.getContacts();
|
||||
} catch (err) {
|
||||
console.log(err);
|
||||
return res.status(500).json({
|
||||
error: "Could not check whatsapp contact. Check connection page.",
|
||||
});
|
||||
}
|
||||
|
||||
await Promise.all(
|
||||
phoneContacts.map(async ({ number, name }) => {
|
||||
await Contact.create({ number, name });
|
||||
})
|
||||
);
|
||||
|
||||
return res.status(200).json({ message: "contacts imported" });
|
||||
};
|
||||
@@ -1,203 +0,0 @@
|
||||
const Message = require("../models/Message");
|
||||
const Contact = require("../models/Contact");
|
||||
const User = require("../models/User");
|
||||
const Whatsapp = require("../models/Whatsapp");
|
||||
|
||||
const Ticket = require("../models/Ticket");
|
||||
const { getIO } = require("../libs/socket");
|
||||
const { getWbot } = require("../libs/wbot");
|
||||
const Sequelize = require("sequelize");
|
||||
|
||||
const { MessageMedia } = require("whatsapp-web.js");
|
||||
|
||||
const setMessagesAsRead = async ticket => {
|
||||
const io = getIO();
|
||||
const wbot = getWbot(ticket.whatsappId);
|
||||
|
||||
await Message.update(
|
||||
{ read: true },
|
||||
{
|
||||
where: {
|
||||
ticketId: ticket.id,
|
||||
read: false,
|
||||
},
|
||||
}
|
||||
);
|
||||
|
||||
try {
|
||||
await wbot.sendSeen(`${ticket.contact.number}@c.us`);
|
||||
} catch (err) {
|
||||
console.log(
|
||||
"Could not mark messages as read. Maybe whatsapp session disconnected?"
|
||||
);
|
||||
}
|
||||
|
||||
io.to("notification").emit("ticket", {
|
||||
action: "updateUnread",
|
||||
ticketId: ticket.id,
|
||||
});
|
||||
};
|
||||
|
||||
exports.index = async (req, res, next) => {
|
||||
const { ticketId } = req.params;
|
||||
const { searchParam = "", pageNumber = 1 } = req.query;
|
||||
|
||||
const whereCondition = {
|
||||
body: Sequelize.where(
|
||||
Sequelize.fn("LOWER", Sequelize.col("body")),
|
||||
"LIKE",
|
||||
"%" + searchParam.toLowerCase() + "%"
|
||||
),
|
||||
};
|
||||
|
||||
const limit = 20;
|
||||
const offset = limit * (pageNumber - 1);
|
||||
|
||||
const ticket = await Ticket.findByPk(ticketId, {
|
||||
include: [
|
||||
{
|
||||
model: Contact,
|
||||
as: "contact",
|
||||
include: "extraInfo",
|
||||
attributes: ["id", "name", "number", "profilePicUrl"],
|
||||
},
|
||||
{
|
||||
model: User,
|
||||
as: "user",
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
if (!ticket) {
|
||||
return res.status(404).json({ error: "No ticket found with this ID" });
|
||||
}
|
||||
|
||||
await setMessagesAsRead(ticket);
|
||||
|
||||
const ticketMessages = await ticket.getMessages({
|
||||
where: whereCondition,
|
||||
limit,
|
||||
offset,
|
||||
order: [["createdAt", "DESC"]],
|
||||
});
|
||||
|
||||
const count = await ticket.countMessages();
|
||||
|
||||
const serializedMessages = ticketMessages.map(message => {
|
||||
return {
|
||||
...message.dataValues,
|
||||
mediaUrl: `${
|
||||
message.mediaUrl
|
||||
? `${process.env.BACKEND_URL}:${process.env.PROXY_PORT}/public/${message.mediaUrl}`
|
||||
: ""
|
||||
}`,
|
||||
};
|
||||
});
|
||||
|
||||
const hasMore = count > offset + ticketMessages.length;
|
||||
|
||||
return res.json({
|
||||
messages: serializedMessages.reverse(),
|
||||
ticket,
|
||||
count,
|
||||
hasMore,
|
||||
});
|
||||
};
|
||||
|
||||
exports.store = async (req, res, next) => {
|
||||
const io = getIO();
|
||||
|
||||
const { ticketId } = req.params;
|
||||
const message = req.body;
|
||||
const media = req.file;
|
||||
let sentMessage;
|
||||
|
||||
const ticket = await Ticket.findByPk(ticketId, {
|
||||
include: [
|
||||
{
|
||||
model: Contact,
|
||||
as: "contact",
|
||||
attributes: ["number", "name", "profilePicUrl"],
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
if (!ticket) {
|
||||
return res.status(404).json({ error: "No ticket found with this ID" });
|
||||
}
|
||||
|
||||
if (!ticket.whatsappId) {
|
||||
const defaultWhatsapp = await Whatsapp.findOne({
|
||||
where: { default: true },
|
||||
});
|
||||
|
||||
if (!defaultWhatsapp) {
|
||||
return res
|
||||
.status(404)
|
||||
.json({ error: "No default WhatsApp found. Check Connection page." });
|
||||
}
|
||||
|
||||
await ticket.setWhatsapp(defaultWhatsapp);
|
||||
}
|
||||
|
||||
const wbot = getWbot(ticket.whatsappId);
|
||||
|
||||
try {
|
||||
if (media) {
|
||||
const newMedia = MessageMedia.fromFilePath(req.file.path);
|
||||
|
||||
message.mediaUrl = req.file.filename;
|
||||
if (newMedia.mimetype) {
|
||||
message.mediaType = newMedia.mimetype.split("/")[0];
|
||||
} else {
|
||||
message.mediaType = "other";
|
||||
}
|
||||
|
||||
sentMessage = await wbot.sendMessage(
|
||||
`${ticket.contact.number}@c.us`,
|
||||
newMedia
|
||||
);
|
||||
|
||||
await ticket.update({ lastMessage: message.mediaUrl });
|
||||
} else {
|
||||
sentMessage = await wbot.sendMessage(
|
||||
`${ticket.contact.number}@c.us`,
|
||||
message.body
|
||||
);
|
||||
await ticket.update({ lastMessage: message.body });
|
||||
}
|
||||
} catch (err) {
|
||||
console.log(
|
||||
"Could not create whatsapp message. Is session details valid? "
|
||||
);
|
||||
}
|
||||
|
||||
if (sentMessage) {
|
||||
message.id = sentMessage.id.id;
|
||||
const newMessage = await ticket.createMessage(message);
|
||||
|
||||
const serialziedMessage = {
|
||||
...newMessage.dataValues,
|
||||
mediaUrl: `${
|
||||
message.mediaUrl
|
||||
? `${process.env.BACKEND_URL}:${process.env.PROXY_PORT}/public/${message.mediaUrl}`
|
||||
: ""
|
||||
}`,
|
||||
};
|
||||
|
||||
io.to(ticketId).to("notification").emit("appMessage", {
|
||||
action: "create",
|
||||
message: serialziedMessage,
|
||||
ticket: ticket,
|
||||
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." });
|
||||
};
|
||||
@@ -1,181 +0,0 @@
|
||||
// const Sequelize = require("sequelize");
|
||||
// const Yup = require("yup");
|
||||
// const { Op } = require("sequelize");
|
||||
|
||||
// const User = require("../models/User");
|
||||
// const Setting = require("../models/Setting");
|
||||
|
||||
// const { getIO } = require("../libs/socket");
|
||||
|
||||
// exports.index = async (req, res) => {
|
||||
// if (req.user.profile !== "admin") {
|
||||
// return res
|
||||
// .status(403)
|
||||
// .json({ error: "Only administrators can access this route." });
|
||||
// }
|
||||
|
||||
// const { searchParam = "", pageNumber = 1 } = req.query;
|
||||
|
||||
// const whereCondition = {
|
||||
// [Op.or]: [
|
||||
// {
|
||||
// name: Sequelize.where(
|
||||
// Sequelize.fn("LOWER", Sequelize.col("name")),
|
||||
// "LIKE",
|
||||
// "%" + searchParam.toLowerCase() + "%"
|
||||
// ),
|
||||
// },
|
||||
// { email: { [Op.like]: `%${searchParam.toLowerCase()}%` } },
|
||||
// ],
|
||||
// };
|
||||
|
||||
// let limit = 20;
|
||||
// let offset = limit * (pageNumber - 1);
|
||||
|
||||
// const { count, rows: users } = await User.findAndCountAll({
|
||||
// attributes: ["name", "id", "email", "profile"],
|
||||
// where: whereCondition,
|
||||
// limit,
|
||||
// offset,
|
||||
// order: [["createdAt", "DESC"]],
|
||||
// });
|
||||
|
||||
// const hasMore = count > offset + users.length;
|
||||
|
||||
// return res.status(200).json({ users, count, hasMore });
|
||||
// };
|
||||
|
||||
export default async (req, res, next) => {
|
||||
console.log(req.url);
|
||||
const schema = Yup.object().shape({
|
||||
name: Yup.string().required().min(2),
|
||||
email: Yup.string()
|
||||
.email()
|
||||
.required()
|
||||
.test(
|
||||
"Check-email",
|
||||
"An user with this email already exists",
|
||||
async value => {
|
||||
const userFound = await User.findOne({ where: { email: value } });
|
||||
return !Boolean(userFound);
|
||||
}
|
||||
),
|
||||
password: Yup.string().required().min(5)
|
||||
});
|
||||
|
||||
if (req.url === "/signup") {
|
||||
const { value: userCreation } = await Setting.findByPk("userCreation");
|
||||
|
||||
if (userCreation === "disabled") {
|
||||
return res
|
||||
.status(403)
|
||||
.json({ error: "User creation is disabled by administrator." });
|
||||
}
|
||||
} else if (req.user.profile !== "admin") {
|
||||
return res
|
||||
.status(403)
|
||||
.json({ error: "Only administrators can create users." });
|
||||
}
|
||||
|
||||
try {
|
||||
await schema.validate(req.body);
|
||||
} catch (err) {
|
||||
return res.status(400).json({ error: err.message });
|
||||
}
|
||||
|
||||
const io = getIO();
|
||||
|
||||
const { name, id, email, profile } = await User.create(req.body);
|
||||
|
||||
io.emit("user", {
|
||||
action: "create",
|
||||
user: { name, id, email, profile }
|
||||
});
|
||||
|
||||
return res.status(201).json({ message: "User created!", userId: id });
|
||||
};
|
||||
|
||||
// exports.show = async (req, res) => {
|
||||
// const { userId } = req.params;
|
||||
|
||||
// const user = await User.findByPk(userId, {
|
||||
// attributes: ["id", "name", "email", "profile"],
|
||||
// });
|
||||
|
||||
// if (!user) {
|
||||
// res.status(400).json({ error: "No user found with this id." });
|
||||
// }
|
||||
|
||||
// return res.status(200).json(user);
|
||||
// };
|
||||
|
||||
// exports.update = async (req, res) => {
|
||||
// const schema = Yup.object().shape({
|
||||
// name: Yup.string().min(2),
|
||||
// email: Yup.string().email(),
|
||||
// password: Yup.string(),
|
||||
// });
|
||||
|
||||
// if (req.user.profile !== "admin") {
|
||||
// return res
|
||||
// .status(403)
|
||||
// .json({ error: "Only administrators can edit users." });
|
||||
// }
|
||||
|
||||
// await schema.validate(req.body);
|
||||
|
||||
// const io = getIO();
|
||||
// const { userId } = req.params;
|
||||
|
||||
// const user = await User.findByPk(userId, {
|
||||
// attributes: ["name", "id", "email", "profile"],
|
||||
// });
|
||||
|
||||
// if (!user) {
|
||||
// res.status(404).json({ error: "No user found with this id." });
|
||||
// }
|
||||
|
||||
// if (user.profile === "admin" && req.body.profile === "user") {
|
||||
// const adminUsers = await User.count({ where: { profile: "admin" } });
|
||||
// if (adminUsers <= 1) {
|
||||
// return res
|
||||
// .status(403)
|
||||
// .json({ error: "There must be at leat one admin user." });
|
||||
// }
|
||||
// }
|
||||
|
||||
// await user.update(req.body);
|
||||
|
||||
// io.emit("user", {
|
||||
// action: "update",
|
||||
// user: user,
|
||||
// });
|
||||
|
||||
// return res.status(200).json(user);
|
||||
// };
|
||||
|
||||
// exports.delete = async (req, res) => {
|
||||
// const io = getIO();
|
||||
// const { userId } = req.params;
|
||||
|
||||
// const user = await User.findByPk(userId);
|
||||
|
||||
// if (!user) {
|
||||
// res.status(400).json({ error: "No user found with this id." });
|
||||
// }
|
||||
|
||||
// if (req.user.profile !== "admin") {
|
||||
// return res
|
||||
// .status(403)
|
||||
// .json({ error: "Only administrators can edit users." });
|
||||
// }
|
||||
|
||||
// await user.destroy();
|
||||
|
||||
// io.emit("user", {
|
||||
// action: "delete",
|
||||
// userId: userId,
|
||||
// });
|
||||
|
||||
// return res.status(200).json({ message: "User deleted" });
|
||||
// };
|
||||
@@ -1,32 +0,0 @@
|
||||
const jwt = require("jsonwebtoken");
|
||||
const authConfig = require("../config/auth");
|
||||
|
||||
const User = require("../models/User");
|
||||
|
||||
exports.store = async (req, res, next) => {
|
||||
const { email, password } = req.body;
|
||||
|
||||
const user = await User.findOne({ where: { email: email } });
|
||||
if (!user) {
|
||||
return res.status(404).json({ error: "No user found with this email" });
|
||||
}
|
||||
|
||||
if (!(await user.checkPassword(password))) {
|
||||
return res.status(401).json({ error: "Password does not match" });
|
||||
}
|
||||
|
||||
const token = jwt.sign(
|
||||
{ email: user.email, userId: user.id },
|
||||
authConfig.secret,
|
||||
{
|
||||
expiresIn: authConfig.expiresIn,
|
||||
}
|
||||
);
|
||||
|
||||
return res.status(200).json({
|
||||
token: token,
|
||||
username: user.name,
|
||||
profile: user.profile,
|
||||
userId: user.id,
|
||||
});
|
||||
};
|
||||
16
backend/src/controllers/SessionController.ts
Normal file
16
backend/src/controllers/SessionController.ts
Normal file
@@ -0,0 +1,16 @@
|
||||
import { Request, Response } from "express";
|
||||
|
||||
import AuthUserService from "../services/AuthUserSerice";
|
||||
|
||||
const store = async (req: Request, res: Response): Promise<Response> => {
|
||||
const { email, password } = req.body;
|
||||
|
||||
const { user, token } = await AuthUserService({ email, password });
|
||||
|
||||
return res.status(200).json({
|
||||
user,
|
||||
token
|
||||
});
|
||||
};
|
||||
|
||||
export default store;
|
||||
@@ -1,39 +0,0 @@
|
||||
const Setting = require("../models/Setting");
|
||||
const { getIO } = require("../libs/socket");
|
||||
|
||||
exports.index = async (req, res) => {
|
||||
if (req.user.profile !== "admin") {
|
||||
return res
|
||||
.status(403)
|
||||
.json({ error: "Only administrators can access this route." });
|
||||
}
|
||||
|
||||
const settings = await Setting.findAll();
|
||||
|
||||
return res.status(200).json(settings);
|
||||
};
|
||||
|
||||
exports.update = async (req, res) => {
|
||||
if (req.user.profile !== "admin") {
|
||||
return res
|
||||
.status(403)
|
||||
.json({ error: "Only administrators can access this route." });
|
||||
}
|
||||
|
||||
const io = getIO();
|
||||
const { settingKey } = req.params;
|
||||
const setting = await Setting.findByPk(settingKey);
|
||||
|
||||
if (!setting) {
|
||||
return res.status(404).json({ error: "No setting found with this ID" });
|
||||
}
|
||||
|
||||
await setting.update(req.body);
|
||||
|
||||
io.emit("settings", {
|
||||
action: "update",
|
||||
setting,
|
||||
});
|
||||
|
||||
return res.status(200).json(setting);
|
||||
};
|
||||
@@ -1,185 +0,0 @@
|
||||
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");
|
||||
|
||||
exports.index = async (req, res) => {
|
||||
const {
|
||||
pageNumber = 1,
|
||||
status = "",
|
||||
date = "",
|
||||
searchParam = "",
|
||||
showAll,
|
||||
} = req.query;
|
||||
|
||||
const userId = req.user.id;
|
||||
|
||||
const limit = 20;
|
||||
const offset = limit * (pageNumber - 1);
|
||||
|
||||
let includeCondition = [
|
||||
{
|
||||
model: Contact,
|
||||
as: "contact",
|
||||
attributes: ["name", "number", "profilePicUrl"],
|
||||
},
|
||||
];
|
||||
|
||||
let whereCondition = { userId: userId };
|
||||
|
||||
if (showAll === "true") {
|
||||
whereCondition = {};
|
||||
}
|
||||
|
||||
if (status) {
|
||||
whereCondition = {
|
||||
...whereCondition,
|
||||
status: status,
|
||||
};
|
||||
}
|
||||
|
||||
if (searchParam) {
|
||||
includeCondition = [
|
||||
...includeCondition,
|
||||
{
|
||||
model: Message,
|
||||
as: "messages",
|
||||
attributes: ["id", "body"],
|
||||
where: {
|
||||
body: Sequelize.where(
|
||||
Sequelize.fn("LOWER", Sequelize.col("body")),
|
||||
"LIKE",
|
||||
"%" + searchParam.toLowerCase() + "%"
|
||||
),
|
||||
},
|
||||
required: false,
|
||||
duplicating: false,
|
||||
},
|
||||
];
|
||||
|
||||
whereCondition = {
|
||||
[Sequelize.Op.or]: [
|
||||
{
|
||||
"$contact.name$": Sequelize.where(
|
||||
Sequelize.fn("LOWER", Sequelize.col("name")),
|
||||
"LIKE",
|
||||
"%" + searchParam.toLowerCase() + "%"
|
||||
),
|
||||
},
|
||||
{ "$contact.number$": { [Sequelize.Op.like]: `%${searchParam}%` } },
|
||||
{
|
||||
"$message.body$": Sequelize.where(
|
||||
Sequelize.fn("LOWER", Sequelize.col("body")),
|
||||
"LIKE",
|
||||
"%" + searchParam.toLowerCase() + "%"
|
||||
),
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
if (date) {
|
||||
whereCondition = {
|
||||
...whereCondition,
|
||||
createdAt: {
|
||||
[Sequelize.Op.between]: [
|
||||
startOfDay(parseISO(date)),
|
||||
endOfDay(parseISO(date)),
|
||||
],
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
const { count, rows: tickets } = await Ticket.findAndCountAll({
|
||||
where: whereCondition,
|
||||
distinct: true,
|
||||
include: includeCondition,
|
||||
limit,
|
||||
offset,
|
||||
order: [["updatedAt", "DESC"]],
|
||||
});
|
||||
|
||||
const hasMore = count > offset + tickets.length;
|
||||
|
||||
return res.status(200).json({ count, tickets, hasMore });
|
||||
};
|
||||
|
||||
exports.store = async (req, res) => {
|
||||
const io = getIO();
|
||||
|
||||
const defaultWhatsapp = await Whatsapp.findOne({
|
||||
where: { default: true },
|
||||
});
|
||||
|
||||
if (!defaultWhatsapp) {
|
||||
return res
|
||||
.status(404)
|
||||
.json({ error: "No default WhatsApp found. Check Connection page." });
|
||||
}
|
||||
|
||||
const ticket = await defaultWhatsapp.createTicket(req.body);
|
||||
|
||||
const contact = await ticket.getContact();
|
||||
|
||||
const serializaedTicket = { ...ticket.dataValues, contact: contact };
|
||||
|
||||
io.to("notification").emit("ticket", {
|
||||
action: "create",
|
||||
ticket: serializaedTicket,
|
||||
});
|
||||
|
||||
return res.status(200).json(ticket);
|
||||
};
|
||||
|
||||
exports.update = async (req, res) => {
|
||||
const io = getIO();
|
||||
const { ticketId } = req.params;
|
||||
|
||||
const ticket = await Ticket.findByPk(ticketId, {
|
||||
include: [
|
||||
{
|
||||
model: Contact,
|
||||
as: "contact",
|
||||
attributes: ["name", "number", "profilePicUrl"],
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
if (!ticket) {
|
||||
return res.status(404).json({ error: "No ticket found with this ID" });
|
||||
}
|
||||
|
||||
await ticket.update(req.body);
|
||||
|
||||
io.to("notification").emit("ticket", {
|
||||
action: "updateStatus",
|
||||
ticket: ticket,
|
||||
});
|
||||
|
||||
return res.status(200).json(ticket);
|
||||
};
|
||||
|
||||
exports.delete = async (req, res) => {
|
||||
const io = getIO();
|
||||
const { ticketId } = req.params;
|
||||
|
||||
const ticket = await Ticket.findByPk(ticketId);
|
||||
|
||||
if (!ticket) {
|
||||
return res.status(400).json({ error: "No ticket found with this ID" });
|
||||
}
|
||||
|
||||
await ticket.destroy();
|
||||
|
||||
io.to("notification").emit("ticket", {
|
||||
action: "delete",
|
||||
ticketId: ticket.id,
|
||||
});
|
||||
|
||||
return res.status(200).json({ message: "ticket deleted" });
|
||||
};
|
||||
@@ -1,6 +1,6 @@
|
||||
import { Request, Response } from "express";
|
||||
|
||||
// import CheckSettingsHelper from "../helpers/CheckSettingsHelper";
|
||||
import CheckSettingsHelper from "../helpers/CheckSettingsHelper";
|
||||
import AppError from "../errors/AppError";
|
||||
|
||||
import CreateUserService from "../services/CreateUserService";
|
||||
@@ -9,30 +9,31 @@ import CreateUserService from "../services/CreateUserService";
|
||||
// import FindUserService from "../services/FindUserService";
|
||||
|
||||
export const index = async (req: Request, res: Response): Promise<Response> => {
|
||||
if (req.user.profile !== "admin") {
|
||||
throw new AppError("Only administrators can access this route.", 403); // should be handled better.
|
||||
}
|
||||
const { searchParam, pageNumber } = req.query as any;
|
||||
// if (req.user.profile !== "admin") {
|
||||
// throw new AppError("Only administrators can access this route.", 403); // should be handled better.
|
||||
// }
|
||||
// const { searchParam, pageNumber } = req.query as any;
|
||||
|
||||
const { users, count, hasMore } = await ListUsersService({
|
||||
searchParam,
|
||||
pageNumber
|
||||
});
|
||||
// const { users, count, hasMore } = await ListUsersService({
|
||||
// searchParam,
|
||||
// pageNumber
|
||||
// });
|
||||
|
||||
return res.json({ users, count, hasMore });
|
||||
// return res.json({ users, count, hasMore });
|
||||
return res.json({ ok: "ok" });
|
||||
};
|
||||
|
||||
export const store = async (req: Request, res: Response): Promise<Response> => {
|
||||
const { email, password, name, profile } = req.body;
|
||||
|
||||
// if (
|
||||
// req.url === "/signup" &&
|
||||
// (await CheckSettingsHelper("userCreation")) === "disabled"
|
||||
// ) {
|
||||
// throw new AppError("User creation is disabled by administrator.", 403);
|
||||
// } else if (req.user.profile !== "admin") {
|
||||
// throw new AppError("Only administrators can create users.", 403);
|
||||
// }
|
||||
if (
|
||||
req.url === "/signup" &&
|
||||
(await CheckSettingsHelper("userCreation")) === "disabled"
|
||||
) {
|
||||
throw new AppError("User creation is disabled by administrator.", 403);
|
||||
} else if (req.url !== "/signup" && req.user.profile !== "admin") {
|
||||
throw new AppError("Only administrators can create users.", 403);
|
||||
}
|
||||
|
||||
const user = await CreateUserService({
|
||||
email,
|
||||
@@ -44,26 +45,26 @@ export const store = async (req: Request, res: Response): Promise<Response> => {
|
||||
return res.status(200).json(user);
|
||||
};
|
||||
|
||||
export const show = async (req: Request, res: Response): Promise<Response> => {
|
||||
const { userId } = req.params;
|
||||
// export const show = async (req: Request, res: Response): Promise<Response> => {
|
||||
// const { userId } = req.params;
|
||||
|
||||
const user = await FindUserService(userId);
|
||||
// const user = await FindUserService(userId);
|
||||
|
||||
return res.status(200).json(user);
|
||||
};
|
||||
// return res.status(200).json(user);
|
||||
// };
|
||||
|
||||
export const update = async (
|
||||
req: Request,
|
||||
res: Response
|
||||
): Promise<Response> => {
|
||||
if (req.user.profile !== "admin") {
|
||||
throw new AppError("Only administrators can edit users.", 403);
|
||||
}
|
||||
// export const update = async (
|
||||
// req: Request,
|
||||
// res: Response
|
||||
// ): Promise<Response> => {
|
||||
// if (req.user.profile !== "admin") {
|
||||
// throw new AppError("Only administrators can edit users.", 403);
|
||||
// }
|
||||
|
||||
const { userId } = req.params;
|
||||
const userData = req.body;
|
||||
// const { userId } = req.params;
|
||||
// const userData = req.body;
|
||||
|
||||
const user = await UpdateUserService({ userData, userId });
|
||||
// const user = await UpdateUserService({ userData, userId });
|
||||
|
||||
return res.status(200).json(user);
|
||||
};
|
||||
// return res.status(200).json(user);
|
||||
// };
|
||||
|
||||
@@ -1,141 +0,0 @@
|
||||
const Yup = require("yup");
|
||||
const Whatsapp = require("../models/Whatsapp");
|
||||
const { getIO } = require("../libs/socket");
|
||||
const { getWbot, initWbot, removeWbot } = require("../libs/wbot");
|
||||
const wbotMessageListener = require("../services/wbotMessageListener");
|
||||
const wbotMonitor = require("../services/wbotMonitor");
|
||||
|
||||
exports.index = async (req, res) => {
|
||||
const whatsapps = await Whatsapp.findAll();
|
||||
|
||||
return res.status(200).json(whatsapps);
|
||||
};
|
||||
|
||||
exports.store = async (req, res) => {
|
||||
const schema = Yup.object().shape({
|
||||
name: Yup.string().required().min(2),
|
||||
default: Yup.boolean()
|
||||
.required()
|
||||
.test(
|
||||
"Check-default",
|
||||
"Only one default whatsapp is permited",
|
||||
async value => {
|
||||
if (value === true) {
|
||||
const whatsappFound = await Whatsapp.findOne({
|
||||
where: { default: true },
|
||||
});
|
||||
return !Boolean(whatsappFound);
|
||||
} else return true;
|
||||
}
|
||||
),
|
||||
});
|
||||
|
||||
try {
|
||||
await schema.validate(req.body);
|
||||
} catch (err) {
|
||||
return res.status(400).json({ error: err.message });
|
||||
}
|
||||
|
||||
const io = getIO();
|
||||
|
||||
const whatsapp = await Whatsapp.create(req.body);
|
||||
|
||||
if (!whatsapp) {
|
||||
return res.status(400).json({ error: "Cannot create whatsapp session." });
|
||||
}
|
||||
|
||||
initWbot(whatsapp)
|
||||
.then(() => {
|
||||
wbotMessageListener(whatsapp);
|
||||
wbotMonitor(whatsapp);
|
||||
})
|
||||
.catch(err => console.log(err));
|
||||
|
||||
io.emit("whatsapp", {
|
||||
action: "update",
|
||||
whatsapp: whatsapp,
|
||||
});
|
||||
|
||||
return res.status(200).json(whatsapp);
|
||||
};
|
||||
|
||||
exports.show = async (req, res) => {
|
||||
const { whatsappId } = req.params;
|
||||
const whatsapp = await Whatsapp.findByPk(whatsappId);
|
||||
|
||||
if (!whatsapp) {
|
||||
return res.status(200).json({ message: "Session not found" });
|
||||
}
|
||||
|
||||
return res.status(200).json(whatsapp);
|
||||
};
|
||||
|
||||
exports.update = async (req, res) => {
|
||||
const { whatsappId } = req.params;
|
||||
|
||||
const schema = Yup.object().shape({
|
||||
name: Yup.string().required().min(2),
|
||||
default: Yup.boolean()
|
||||
.required()
|
||||
.test(
|
||||
"Check-default",
|
||||
"Only one default whatsapp is permited",
|
||||
async value => {
|
||||
if (value === true) {
|
||||
const whatsappFound = await Whatsapp.findOne({
|
||||
where: { default: true },
|
||||
});
|
||||
if (whatsappFound) {
|
||||
return !(whatsappFound.id !== +whatsappId);
|
||||
} else {
|
||||
return true;
|
||||
}
|
||||
} else return true;
|
||||
}
|
||||
),
|
||||
});
|
||||
|
||||
try {
|
||||
await schema.validate(req.body);
|
||||
} catch (err) {
|
||||
return res.status(400).json({ error: err.message });
|
||||
}
|
||||
|
||||
const io = getIO();
|
||||
|
||||
const whatsapp = await Whatsapp.findByPk(whatsappId);
|
||||
|
||||
if (!whatsapp) {
|
||||
return res.status(404).json({ message: "Whatsapp not found" });
|
||||
}
|
||||
|
||||
await whatsapp.update(req.body);
|
||||
|
||||
io.emit("whatsapp", {
|
||||
action: "update",
|
||||
whatsapp: whatsapp,
|
||||
});
|
||||
|
||||
return res.status(200).json({ message: "Whatsapp updated" });
|
||||
};
|
||||
|
||||
exports.delete = async (req, res) => {
|
||||
const io = getIO();
|
||||
const { whatsappId } = req.params;
|
||||
|
||||
const whatsapp = await Whatsapp.findByPk(whatsappId);
|
||||
|
||||
if (!whatsapp) {
|
||||
return res.status(404).json({ message: "Whatsapp not found" });
|
||||
}
|
||||
|
||||
await whatsapp.destroy();
|
||||
removeWbot(whatsapp.id);
|
||||
|
||||
io.emit("whatsapp", {
|
||||
action: "delete",
|
||||
whatsappId: whatsapp.id,
|
||||
});
|
||||
|
||||
return res.status(200).json({ message: "Whatsapp deleted." });
|
||||
};
|
||||
@@ -1,32 +0,0 @@
|
||||
// const Whatsapp = require("../models/Whatsapp");
|
||||
// const { getIO } = require("../libs/socket");
|
||||
// const { getWbot, initWbot, removeWbot } = require("../libs/wbot");
|
||||
// const wbotMessageListener = require("../services/wbotMessageListener");
|
||||
// const wbotMonitor = require("../services/wbotMonitor");
|
||||
|
||||
// exports.show = async (req, res) => {
|
||||
// const { whatsappId } = req.params;
|
||||
// const dbSession = await Whatsapp.findByPk(whatsappId);
|
||||
|
||||
// if (!dbSession) {
|
||||
// return res.status(200).json({ message: "Session not found" });
|
||||
// }
|
||||
|
||||
// return res.status(200).json(dbSession);
|
||||
// };
|
||||
|
||||
// exports.delete = async (req, res) => {
|
||||
// const { whatsappId } = req.params;
|
||||
|
||||
// const dbSession = await Whatsapp.findByPk(whatsappId);
|
||||
|
||||
// if (!dbSession) {
|
||||
// return res.status(404).json({ message: "Session not found" });
|
||||
// }
|
||||
|
||||
// const wbot = getWbot(dbSession.id);
|
||||
|
||||
// wbot.logout();
|
||||
|
||||
// return res.status(200).json({ message: "Session disconnected." });
|
||||
// };
|
||||
Reference in New Issue
Block a user