Compare commits

..

22 Commits

Author SHA1 Message Date
adriano e80ed8d092 Merge branch 'master' of github.com:AdrianoRobson/projeto-hit 2024-03-18 15:21:42 -03:00
adriano 5572ca1223 Merge branch 'feat-iam-integration' into feat_lojas 2024-03-18 15:19:53 -03:00
adriano db4bf2bf84 feat: Add routes and controllers to integrate with E-Trust Horacius for user and application management 2024-03-18 15:18:18 -03:00
gustavo-gsp 64d2cf8323
Merge pull request #22 from gustavo-gsp/feat_lojas
Feat lojas
2024-03-18 15:09:42 -03:00
gustavo-gsp 7533a382cc
Update server.js 2024-03-18 15:07:47 -03:00
Adriano d7019ffb1a feat: add notification and sound alert for new tickets in user's service queue
Details:
- Implemented functionality to notify users with a sound alert when new tickets arrive in their service queues.

fix: include responsible person's name when generating ticket already opened error in all languages

Details:
- Fixed the error generation process to include the name of the responsible person for the ticket when the system detects an attempt to create an already opened ticket.
2024-03-18 14:51:13 -03:00
Adriano e864e0b97f Merge branch 'master' of github.com:AdrianoRobson/projeto-hit 2024-03-15 16:36:41 -03:00
Henrriky 37c384a712 chore: update md files 2024-03-12 17:19:16 -03:00
Henrriky 895ce83b5b feat: add reset password service 2024-03-12 17:18:41 -03:00
Henrriky d608538c9e feat: Add API routes for integrating Horacius users with Omnihit 2024-03-12 17:18:22 -03:00
Henrriky 2f56673962 refactor: update name of functions link and unlink user right 2024-03-12 17:16:46 -03:00
Henrriky fca4dd7036 feat: add unlink user right to change profile property of user to default 2024-03-12 17:16:07 -03:00
Henrriky 2d22a4b9f0 feat: add link user right to modify profile property of user 2024-03-12 17:15:24 -03:00
Henrriky 097737a3b8 feat: add check user right service 2024-03-12 17:11:26 -03:00
Henrriky 26e90c6ea9 feat: add middleware to verify token (API KEY) send by horacius system 2024-03-12 17:09:56 -03:00
Henrriky 3478b7c5b2 feat: add iam controllers (createUser, checkUser, deleteUser, updateUser, resetPassword, linkUserAndUserRight, unlinkUserAndUserRight, checkUserRight) 2024-03-12 17:06:39 -03:00
Henrriky 4c7e49fb9a feat: add base structure to EL-IAM integration 2024-03-12 12:46:12 -03:00
Adriano e5dff2a6d5 Merge branch 'master' of github.com:AdrianoRobson/projeto-hit 2024-03-04 16:46:25 -03:00
Adriano 60b69db0c5 Merge branch 'master' of github.com:AdrianoRobson/projeto-hit 2024-02-21 17:52:31 -03:00
Adriano 939a91e573 Merge branch 'master' of github.com:AdrianoRobson/projeto-hit 2024-02-21 11:25:32 -03:00
Adriano 9e62f5d5e8 Merge branch 'master' of github.com:AdrianoRobson/projeto-hit 2024-02-21 09:21:15 -03:00
Adriano 7f52466c50 chore: change frontend port 2024-02-21 09:21:02 -03:00
17 changed files with 757 additions and 86 deletions

3
.gitignore vendored
View File

@ -40,7 +40,10 @@ WWebJS
.env.development.local .env.development.local
.env.test.local .env.test.local
.env.production.local .env.production.local
.env.save
nano.save
npm-debug.log* npm-debug.log*
yarn-debug.log* yarn-debug.log*
yarn-error.log* yarn-error.log*

View File

@ -0,0 +1,494 @@
import { Request, Response } from "express";
import { getIO } from "../libs/socket";
import { Op } from "sequelize";
import CreateUserService from "../services/UserServices/CreateUserService";
import UpdateUserService from "../services/UserServices/UpdateUserService";
import DeleteUserService from "../services/UserServices/DeleteUserService";
import { del, get, set } from "../helpers/RedisClient";
import {
startWhoIsOnlineMonitor,
stopWhoIsOnlineMonitor
} from "../helpers/WhoIsOnlineMonitor";
import User from "../models/User";
export const createUser = async (
req: Request,
res: Response
): Promise<Response> => {
const { user_id, user_first_name, user_tax_id, user_email, user_title }: any =
req.body;
const invalid = invalidProperties(req.body, [
"user_id",
"user_tax_id",
"user_first_name"
]);
if (invalid) {
return res.status(400).json(response("1", `${invalid}`, "0", "createUser"));
}
const auxUser = await User.findOne({ where: { secondaryId: user_id } });
if (auxUser) {
return res
.status(400)
.json(
response("1", `The user ${user_id} already exist`, "0", "createUser")
);
}
const user = await CreateUserService({
email: user_tax_id || user_email,
password: "12345",
name: user_first_name,
positionCompany: user_title,
profile: "user",
ignoreThrow: true
});
if (user?.error) {
return res
.status(user?.status)
.json(response("0", `${user?.msg}`, "0", "createUser"));
}
if (!user?.error) {
const _user = await User.findByPk(user.id);
_user?.update({ secondaryId: user_id });
const { id, name } = user;
await set(`user:${id}`, { id, name });
const io = getIO();
io.emit("user", {
action: "create",
user
});
await startWhoIsOnlineMonitor();
}
return res
.status(200)
.json(response("1", `User ${user_id} created`, "1", "createUser"));
};
export const deleteUser = async (
req: Request,
res: Response
): Promise<Response> => {
const { user_id }: any = req.body;
const invalid = invalidProperties(req.body, ["user_id"]);
if (invalid) {
return res.status(400).json(response("1", `${invalid}`, "0", "deleteUser"));
}
const _user = await User.findOne({ where: { secondaryId: user_id } });
if (_user) {
const user = await DeleteUserService(_user.id, true);
if (user?.error) {
return res
.status(user?.status)
.json(response("0", `${user?.msg}`, "0", "deleteUser"));
}
if (!user?.error) {
del(`user:${_user.id}`);
const io = getIO();
io.emit("user", {
action: "delete",
userId: _user.id
});
await stopWhoIsOnlineMonitor();
io.emit("onlineStatus", {
action: "delete",
userOnlineTime: _user.id
});
await startWhoIsOnlineMonitor();
return res
.status(200)
.json(response("1", `User ${user_id} deleted`, "1", "deleteUser"));
}
}
return res
.status(500)
.json(response("0", "Internal server error", "0", "deleteUser"));
};
export const listAllUsers = async (
req: Request,
res: Response
): Promise<Response> => {
const _users: any = await User.findAll({
where: {
secondaryId: {
[Op.ne]: ""
}
},
attributes: ["secondaryId", "name"]
});
if (_users) {
const user_list = _users.map((user: any) => {
const { secondaryId, name } = user;
return { user_id: secondaryId, full_name: name };
});
return res
.status(200)
.json(response("1", "Success", user_list, "listAllUsers"));
}
return res
.status(500)
.json(response("0", "Internal server error", [], "listAllUsers"));
};
export const checkUser = async (
req: Request,
res: Response
): Promise<Response> => {
const { user_id }: any = req.body;
const invalid = invalidProperties(req.body, ["user_id"]);
if (invalid) {
return res.status(400).json(response("1", `${invalid}`, "0", "checkUser"));
}
const _user = await User.findOne({ where: { secondaryId: user_id } });
if (_user) {
return res
.status(200)
.json(response("1", `User ${user_id} exist`, "1", "checkUser"));
}
return res
.status(404)
.json(response("1", `User ${user_id} not exist`, "0", "checkUser"));
};
export const updateUser = async (
req: Request,
res: Response
): Promise<Response> => {
const { user_id, user_first_name, user_tax_id, user_email, user_title }: any =
req.body;
const invalid = invalidProperties(req.body, ["user_id"]);
if (invalid) {
return res.status(400).json(response("1", `${invalid}`, "0", "checkUser"));
}
const _user: any = await User.findOne({ where: { secondaryId: user_id } });
if (!_user)
return res
.status(404)
.json(response("1", `User ${user_id} not exist`, "0", "updateUser"));
const userData = {
email: user_tax_id || user_email,
name: user_first_name,
positionCompany: user_title
};
let user: any = await UpdateUserService({
userData,
userId: _user.id,
ignoreThrow: true
});
if (user?.error) {
return res
.status(user?.status)
.json(response("0", `${user?.msg}`, "0", "updateUser"));
}
if (user) {
const { id, name } = user;
await set(`user:${id}`, { id, name });
}
const io = getIO();
io.emit("user", {
action: "update",
user
});
return res
.status(200)
.json(response("1", `User ${user_id} updated`, "1", "updateUser"));
};
export const resetPassword = async (
req: Request,
res: Response
): Promise<Response> => {
const { user_id, user_password }: any = req.body;
const invalid = invalidProperties(req.body, ["user_id", "user_password"]);
if (invalid) {
return res
.status(400)
.json(response("1", `${invalid}`, "0", "resetPassword"));
}
const _user = await User.findOne({ where: { secondaryId: user_id } });
if (!_user) {
return res
.status(404)
.json(response("1", `User ${user_id} not exist`, "0", "resetPassword"));
}
const userData = {
password: user_password,
email: _user.email
};
let user: any = await UpdateUserService({
userData,
userId: _user.id,
ignoreThrow: true
});
if (user?.error) {
return res
.status(user?.status)
.json(response("0", `${user?.msg}`, "0", "resetPassword"));
}
await logoutUser(_user.id);
return res
.status(200)
.json(
response("1", `User ${user_id} password updated`, "1", "resetPassword")
);
};
export const linkUserAndUserRight = async (
req: Request,
res: Response
): Promise<Response> => {
const { user_id, user_right_id, user_right_title }: any = req.body;
const invalid = invalidProperties(req.body, ["user_id", "user_right_id"]);
if (invalid) {
return res
.status(400)
.json(response("1", `${invalid}`, "0", "linkUserAndUserRight"));
}
if (
(user_right_id &&
!["admin", "user", "supervisor"].includes(
user_right_id?.trim().toLocaleLowerCase()
)) ||
(user_right_title &&
!["admin", "user", "supervisor"].includes(
user_right_title?.trim().toLocaleLowerCase()
))
) {
return res
.status(400)
.json(
response(
"1",
`The user profile ${
user_right_title || user_right_id
} provided by the property user_right_title or user_right_id does not match the following profiles: admin, user, supervisor`,
"0",
"linkUserAndUserRight"
)
);
}
const _user: any = await User.findOne({ where: { secondaryId: user_id } });
if (!_user)
return res
.status(404)
.json(
response("1", `User ${user_id} not exist`, "0", "linkUserAndUserRight")
);
const userData = {
profile: user_right_title || user_right_id,
email: _user.email
};
let user: any = await UpdateUserService({
userData,
userId: _user.id,
ignoreThrow: true
});
if (user?.error) {
return res
.status(user?.status)
.json(response("0", `${user?.msg}`, "0", "linkUserAndUserRight"));
}
await logoutUser(_user.id);
return res
.status(200)
.json(
response(
"1",
`User ${user_id} associated with ${
user_right_title || user_right_id
} profile`,
"1",
"linkUserAndUserRight"
)
);
};
export const checkUserRight = async (
req: Request,
res: Response
): Promise<Response> => {
const { user_id, user_right_id, user_right_title }: any = req.body;
const invalid = invalidProperties(req.body, ["user_id", "user_right_id"]);
if (invalid) {
return res
.status(400)
.json(response("1", `${invalid}`, "0", "checkUserRight"));
}
if (
(user_right_id &&
!["admin", "user", "supervisor"].includes(
user_right_id?.trim().toLocaleLowerCase()
)) ||
(user_right_title &&
!["admin", "user", "supervisor"].includes(
user_right_title?.trim().toLocaleLowerCase()
))
) {
return res
.status(400)
.json(
response(
"1",
`The user profile ${
user_right_title || user_right_id
} provided by the property user_right_title or user_right_id does not match the following profiles: admin, user, supervisor`,
"0",
"checkUserRight"
)
);
}
const _user: any = await User.findOne({
where: {
secondaryId: user_id
}
});
if (!_user)
return res
.status(404)
.json(response("1", `User ${user_id} not exist`, "0", "checkUserRight"));
if (
(user_right_id && _user.profile != user_right_id) ||
(user_right_title && _user.profile != user_right_title)
) {
return res
.status(403)
.json(
response(
"1",
`User ${user_id} does not have this profile`,
"0",
"checkUserRight"
)
);
}
return res
.status(200)
.json(
response(
"1",
`User ${user_id} has ${user_right_title || user_right_id} profile`,
"1",
"checkUserRight"
)
);
};
async function logoutUser(userId: any) {
await stopWhoIsOnlineMonitor();
let onlineTime = {
userId: `${userId}`,
status: "logout..."
};
const io = getIO();
io.emit("onlineStatus", {
action: "logout",
userOnlineTime: onlineTime
});
await startWhoIsOnlineMonitor();
}
function response(code: string, msg: string, obj: any, type: string) {
let payload = { return_code: code, return_msg: msg };
switch (type) {
case "createUser":
return { ...payload, user_created: obj };
case "deleteUser":
return { ...payload, user_removed: obj };
case "listAllUsers":
return { ...payload, user_list: obj };
case "checkUser":
return { ...payload, user_exists: obj };
case "updateUser":
return { ...payload, user_updated: obj };
case "resetPassword":
return { ...payload, password_set: obj };
case "linkUserAndUserRight":
return { ...payload, user_right_linked: obj };
case "checkUserRight":
return { ...payload, user_right_exists: obj };
default:
return payload;
}
}
function invalidProperties(body: any, pros: any[]) {
for (const field of pros) {
console.log("body[field]: ", body[field], " field: ", field);
if (!body[field]) {
return `${field} is required`;
}
}
return false;
}

View File

@ -0,0 +1,14 @@
import { QueryInterface, DataTypes } from "sequelize";
module.exports = {
up: (queryInterface: QueryInterface) => {
return queryInterface.addColumn("Users", "secondaryId", {
type: DataTypes.STRING,
allowNull: true
});
},
down: (queryInterface: QueryInterface) => {
return queryInterface.removeColumn("Users", "secondaryId");
}
};

View File

@ -1,5 +1,5 @@
class AppError { class AppError {
public readonly message: string; public message: string;
public readonly statusCode: number; public readonly statusCode: number;

View File

@ -1,6 +1,7 @@
import { Op } from "sequelize"; import { Op } from "sequelize";
import AppError from "../errors/AppError"; import AppError from "../errors/AppError";
import Ticket from "../models/Ticket"; import Ticket from "../models/Ticket";
import User from "../models/User";
import ListWhatsAppsNumber from "../services/WhatsappService/ListWhatsAppsNumber"; import ListWhatsAppsNumber from "../services/WhatsappService/ListWhatsAppsNumber";
import { getSettingValue } from "./WhaticketSettings"; import { getSettingValue } from "./WhaticketSettings";
import ListWhatsAppsForQueueService from "../services/WhatsappService/ListWhatsAppsForQueueService"; import ListWhatsAppsForQueueService from "../services/WhatsappService/ListWhatsAppsForQueueService";
@ -38,8 +39,13 @@ const CheckContactOpenTickets = async (
if (ticket) { if (ticket) {
if (handle) return true; if (handle) return true;
const userName = await User.findOne({
where:{ id: ticket.userId }
});
const error = new AppError("ERR_OTHER_OPEN_TICKET");
error.message = `Erro: já existe um ticket criado com esse contato. Responsável: ${userName? userName.name.toUpperCase() : 'Aguardando'}`;
throw new AppError("ERR_OTHER_OPEN_TICKET"); throw error;
} }

View File

@ -0,0 +1,23 @@
import { Request, Response, NextFunction } from "express";
import AppError from "../errors/AppError";
const verifyAPIKey = (req: Request, res: Response, next: NextFunction): void => {
const authHeader = req.headers.authorization;
if (!authHeader) {
throw new AppError("ERR_SESSION_EXPIRED", 401);
}
const [, token] = authHeader.split(" ");
const apiKeyIsValid = token === process.env.TOKEN_IAM_HORACIUS_EL
if (!apiKeyIsValid) {
throw new AppError(
"Invalid token",
401
);
}
return next();
};
export default verifyAPIKey;

View File

@ -45,6 +45,9 @@ class User extends Model<User> {
@Column @Column
positionCompany: string; positionCompany: string;
@Column
secondaryId: string;
@Default("admin") @Default("admin")
@Column @Column
profile: string; profile: string;

View File

@ -0,0 +1,56 @@
import { Router } from "express";
import * as IAMControllerEL from "../controllers/IAMControllerEL";
import verifyAPIKey from "../middleware/verifyAPIKey";
const iamRoutesEL = Router();
iamRoutesEL.post(
"/iam/horacius/createUser",
verifyAPIKey,
IAMControllerEL.createUser
);
iamRoutesEL.put(
"/iam/horacius/updateUser",
verifyAPIKey,
IAMControllerEL.updateUser
);
iamRoutesEL.delete(
"/iam/horacius/deleteUser",
verifyAPIKey,
IAMControllerEL.deleteUser
);
iamRoutesEL.get(
"/iam/horacius/listAllUsers",
verifyAPIKey,
IAMControllerEL.listAllUsers
);
iamRoutesEL.get(
"/iam/horacius/checkUser",
verifyAPIKey,
IAMControllerEL.checkUser
);
iamRoutesEL.patch(
"/iam/horacius/linkUserAndUserRight",
verifyAPIKey,
IAMControllerEL.linkUserAndUserRight
);
iamRoutesEL.post(
"/iam/horacius/linkUserAndUserRight",
verifyAPIKey,
IAMControllerEL.checkUserRight
);
iamRoutesEL.patch(
"/iam/horacius/resetPassword",
verifyAPIKey,
IAMControllerEL.resetPassword
);
export default iamRoutesEL;

View File

@ -14,10 +14,12 @@ import reportRoutes from "./reportRoutes";
import schedulingNotifiyRoutes from "./SchedulingNotifyRoutes"; import schedulingNotifiyRoutes from "./SchedulingNotifyRoutes";
import statusChatEndRoutes from "./statusChatEndRoutes"; import statusChatEndRoutes from "./statusChatEndRoutes";
import wbotMonitorRoutes from "./wbotMonitorRoutes"; import wbotMonitorRoutes from "./wbotMonitorRoutes";
import iamRoutesEL from "./iamRoutesEL";
const routes = Router(); const routes = Router();
routes.use(iamRoutesEL);
routes.use(userRoutes); routes.use(userRoutes);
routes.use("/auth", authRoutes); routes.use("/auth", authRoutes);
routes.use(settingRoutes); routes.use(settingRoutes);

View File

@ -11,6 +11,7 @@ interface Request {
positionCompany?: string; positionCompany?: string;
queueIds?: number[]; queueIds?: number[];
profile?: string; profile?: string;
ignoreThrow?: boolean;
} }
interface Response { interface Response {
@ -27,15 +28,17 @@ const CreateUserService = async ({
name, name,
positionCompany, positionCompany,
queueIds = [], queueIds = [],
profile = "master" profile = "master",
}: Request): Promise<Response> => { ignoreThrow = false
}: Request): Promise<Response | any> => {
try { try {
const schema = Yup.object().shape({ const schema = Yup.object().shape({
name: Yup.string().required().min(2), name: Yup.string().required().min(2),
email: Yup.string().required().trim().test( email: Yup.string()
.required()
.trim()
.test(
"Check-email", "Check-email",
"An user with this email already exists.", "An user with this email already exists.",
async value => { async value => {
@ -65,6 +68,8 @@ const CreateUserService = async ({
try { try {
await schema.validate({ email, password, name }); await schema.validate({ email, password, name });
} catch (err: any) { } catch (err: any) {
if (ignoreThrow) return { error: true, msg: err.message, status: 400 };
throw new AppError(err.message); throw new AppError(err.message);
} }
@ -86,12 +91,14 @@ const CreateUserService = async ({
const serializedUser = SerializeUser(user); const serializedUser = SerializeUser(user);
return serializedUser; return serializedUser;
} catch (error: any) { } catch (error: any) {
console.error('===> Error on CreateUserService.ts file: \n', error) console.error("===> Error on CreateUserService.ts file: \n", error);
if (ignoreThrow)
return { error: true, msg: "Create user error", status: 500 };
throw new AppError(error.message); throw new AppError(error.message);
} }
}; };
export default CreateUserService; export default CreateUserService;

View File

@ -2,14 +2,24 @@ import User from "../../models/User";
import AppError from "../../errors/AppError"; import AppError from "../../errors/AppError";
import Ticket from "../../models/Ticket"; import Ticket from "../../models/Ticket";
import UpdateDeletedUserOpenTicketsStatus from "../../helpers/UpdateDeletedUserOpenTicketsStatus"; import UpdateDeletedUserOpenTicketsStatus from "../../helpers/UpdateDeletedUserOpenTicketsStatus";
import { set } from "../../helpers/RedisClient" import { set } from "../../helpers/RedisClient";
const DeleteUserService = async (id: string | number): Promise<void> => { const DeleteUserService = async (
id: string | number,
ignoreThrow = false
): Promise<void | any> => {
const user = await User.findOne({ const user = await User.findOne({
where: { id } where: { id }
}); });
if (!user) { if (!user) {
if (ignoreThrow)
return {
error: true,
msg: `No user found with this id ${id}`,
status: 404
};
throw new AppError("ERR_NO_USER_FOUND", 404); throw new AppError("ERR_NO_USER_FOUND", 404);
} }

View File

@ -16,6 +16,7 @@ interface UserData {
interface Request { interface Request {
userData: UserData; userData: UserData;
userId: string | number; userId: string | number;
ignoreThrow?: boolean;
} }
interface Response { interface Response {
@ -27,11 +28,10 @@ interface Response {
const UpdateUserService = async ({ const UpdateUserService = async ({
userData, userData,
userId userId,
}: Request): Promise<Response | undefined> => { ignoreThrow = false
}: Request): Promise<Response | undefined | any> => {
try { try {
const user = await ShowUserService(userId); const user = await ShowUserService(userId);
const schema = Yup.object().shape({ const schema = Yup.object().shape({
@ -40,28 +40,41 @@ const UpdateUserService = async ({
profile: Yup.string(), profile: Yup.string(),
password: Yup.string(), password: Yup.string(),
email: Yup.string().trim().required().test( email: Yup.string()
.trim()
.required()
.test(
"Check-email", "Check-email",
"An user with this email already exists.", "An user with this email already exists.",
async value => { async value => {
if (!value) return false; if (!value) return false;
const emailExists = await User.findOne({ where: { email: value }, raw: true, attributes: ['email', 'id'] }); const emailExists = await User.findOne({
where: { email: value },
raw: true,
attributes: ["email", "id"]
});
if (emailExists && user.id != emailExists?.id) { if (emailExists && user.id != emailExists?.id) {
console.error(
console.error('The email already exists in another user profile!') "The email already exists in another user profile!"
);
return !emailExists; return !emailExists;
} }
return true return true;
} }
), )
}); });
const { email, password, profile, name, positionCompany, queueIds = [] } = userData; const {
email,
password,
profile,
name,
positionCompany,
queueIds = []
} = userData;
try { try {
await schema.validate({ email, password, profile, name }); await schema.validate({ email, password, profile, name });
@ -69,7 +82,6 @@ const UpdateUserService = async ({
throw new AppError(err.message); throw new AppError(err.message);
} }
await user.update({ await user.update({
email, email,
password, password,
@ -91,13 +103,18 @@ const UpdateUserService = async ({
}; };
return serializedUser; return serializedUser;
} catch (err: any) {
console.error("===> Error on UpdateUserService.ts file: \n", err);
} catch (error: any) { if (ignoreThrow)
console.error('===> Error on UpdateUserService.ts file: \n', error) return {
throw new AppError(error.message); error: true,
msg: err.message,
status: 500
};
throw new AppError(err.message);
} }
}; };
export default UpdateUserService; export default UpdateUserService;

View File

@ -409,7 +409,7 @@ const verifyQueue = async (
//test del transfere o atendimento se entrar na ura infinita //test del transfere o atendimento se entrar na ura infinita
const repet: any = await mostRepeatedPhrase(ticket.id); const repet: any = await mostRepeatedPhrase(ticket.id);
if (repet.occurrences > 4) { if (repet.occurrences > 10) {
await UpdateTicketService({ await UpdateTicketService({
ticketData: { status: "pending", queueId: queues[0].id }, ticketData: { status: "pending", queueId: queues[0].id },
ticketId: ticket.id ticketId: ticket.id
@ -884,7 +884,7 @@ const handleMessage = async (
console.log("repet.occurrences: ", repet.occurrences); console.log("repet.occurrences: ", repet.occurrences);
if (repet.occurrences > 4) { if (repet.occurrences > 10) {
await transferTicket(0, wbot, ticket); await transferTicket(0, wbot, ticket);
await SendWhatsAppMessage({ await SendWhatsAppMessage({

View File

@ -217,12 +217,18 @@ const NotificationsPopOver = () => {
} }
}) })
socket.on('notifyPeding', data =>{
handleNotifications("", data);
});
return () => { return () => {
socket.disconnect() socket.disconnect()
} }
}, [user]) }, [user])
const handleNotifications = data => { const handleNotifications = (data, notify) => {
let isQueue = false;
if(!notify){
const { message, contact, ticket } = data const { message, contact, ticket } = data
const options = { const options = {
@ -253,7 +259,34 @@ const NotificationsPopOver = () => {
} }
return [notification, ...prevState] return [notification, ...prevState]
}) })
}else{
user.queues.forEach(queue =>{
if(queue.id === notify.data.queue?.id){
isQueue = true;
}
})
}
if(!isQueue && notify){
return;
}else{
const notification = new Notification(`${i18n.t("tickets.notification.messagePeding")} ${notify.data.queue?.name}`);
notification.onclick = e => {
e.preventDefault()
window.focus()
historyRef.current.push(`/tickets`)
}
setDesktopNotifications(prevState => {
const notfiticationIndex = prevState.findIndex(
n => n.tag === notification.tag
)
if (notfiticationIndex !== -1) {
prevState[notfiticationIndex] = notification
return [...prevState]
}
return [notification, ...prevState]
})
}
soundAlertRef.current() soundAlertRef.current()
} }

View File

@ -241,6 +241,7 @@ const messages = {
}, },
notification: { notification: {
message: "Message from", message: "Message from",
messagePeding: "new ticket in queue",
}, },
tabs: { tabs: {
open: { title: "Inbox" }, open: { title: "Inbox" },

View File

@ -245,6 +245,7 @@ const messages = {
}, },
notification: { notification: {
message: "Mensaje de", message: "Mensaje de",
messagePeding: "Nuevo billete en cola",
}, },
tabs: { tabs: {
open: { title: "Bandeja" }, open: { title: "Bandeja" },

View File

@ -244,6 +244,7 @@ const messages = {
}, },
notification: { notification: {
message: "Mensagem de", message: "Mensagem de",
messagePeding: "Novo ticket na fila",
}, },
tabs: { tabs: {
open: { title: "Inbox" }, open: { title: "Inbox" },