Skip to content

Commit

Permalink
Whatsapp padrão do usuário e vários tickets por contato
Browse files Browse the repository at this point in the history
  • Loading branch information
rtenorioh authored Jun 28, 2022
1 parent b19c9c2 commit 930db47
Show file tree
Hide file tree
Showing 23 changed files with 209 additions and 69 deletions.
5 changes: 3 additions & 2 deletions backend/src/controllers/ImportPhoneContactsController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@ import { Request, Response } from "express";
import ImportContactsService from "../services/WbotServices/ImportContactsService";

export const store = async (req: Request, res: Response): Promise<Response> => {
await ImportContactsService();
const userId:number = parseInt(req.user.id);
await ImportContactsService(userId);

return res.status(200).json({ message: "contacts imported" });
};
};
6 changes: 3 additions & 3 deletions backend/src/controllers/UserController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ export const store = async (req: Request, res: Response): Promise<Response> => {
throw new AppError("ERR_USER_CREATION_COUNT", 403);
}

const { email, password, name, profile, queueIds } = req.body;
const { email, password, name, profile, queueIds, whatsappId } = req.body;

if (
req.url === "/signup" &&
Expand All @@ -50,7 +50,8 @@ export const store = async (req: Request, res: Response): Promise<Response> => {
password,
name,
profile,
queueIds
queueIds,
whatsappId
});

const io = getIO();
Expand Down Expand Up @@ -83,7 +84,6 @@ export const update = async (
throw new AppError("ERR_NO_PERMISSION", 403);
}

//const { userId } = req.params;
const userData = req.body;

const user = await UpdateUserService({ userData, userId });
Expand Down
15 changes: 12 additions & 3 deletions backend/src/helpers/CheckContactOpenTickets.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,23 @@ import { Op } from "sequelize";
import AppError from "../errors/AppError";
import Ticket from "../models/Ticket";

const CheckContactOpenTickets = async (contactId: number): Promise<void> => {
const CheckContactOpenTickets = async (
contactId: number,
whatsappId: number
): Promise<void> => {
const ticket = await Ticket.findOne({
where: { contactId, status: { [Op.or]: ["open", "pending"] } }
where: {
contactId,
whatsappId,
status: {
[Op.or]: ["open", "pending"]
}
}
});

if (ticket) {
throw new AppError("ERR_OTHER_OPEN_TICKET");
}
};

export default CheckContactOpenTickets;
export default CheckContactOpenTickets;
14 changes: 12 additions & 2 deletions backend/src/helpers/GetDefaultWhatsApp.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,17 @@
import AppError from "../errors/AppError";
import Whatsapp from "../models/Whatsapp";
import GetDefaultWhatsAppByUser from "./GetDefaultWhatsAppByUser";

const GetDefaultWhatsApp = async (
userId?: number
): Promise<Whatsapp> => {
if(userId) {
const whatsappByUser = await GetDefaultWhatsAppByUser(userId);
if(whatsappByUser !== null) {
return whatsappByUser;
}
}

const GetDefaultWhatsApp = async (): Promise<Whatsapp> => {
const defaultWhatsapp = await Whatsapp.findOne({
where: { isDefault: true }
});
Expand All @@ -13,4 +23,4 @@ const GetDefaultWhatsApp = async (): Promise<Whatsapp> => {
return defaultWhatsapp;
};

export default GetDefaultWhatsApp;
export default GetDefaultWhatsApp;
20 changes: 20 additions & 0 deletions backend/src/helpers/GetDefaultWhatsAppByUser.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import User from "../models/User";
import Whatsapp from "../models/Whatsapp";
import { logger } from "../utils/logger";

const GetDefaultWhatsAppByUser = async (
userId: number
): Promise<Whatsapp | null> => {
const user = await User.findByPk(userId, {include: ["whatsapp"]});
if( user === null ) {
return null;
}

if(user.whatsapp !== null) {
logger.info(`Found whatsapp linked to user '${user.name}' is '${user.whatsapp.name}'.`);
}

return user.whatsapp;
};

export default GetDefaultWhatsAppByUser;
4 changes: 2 additions & 2 deletions backend/src/helpers/GetTicketWbot.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import Ticket from "../models/Ticket";

const GetTicketWbot = async (ticket: Ticket): Promise<Session> => {
if (!ticket.whatsappId) {
const defaultWhatsapp = await GetDefaultWhatsApp();
const defaultWhatsapp = await GetDefaultWhatsApp(ticket.user.id);

await ticket.$set("whatsapp", defaultWhatsapp);
}
Expand All @@ -15,4 +15,4 @@ const GetTicketWbot = async (ticket: Ticket): Promise<Session> => {
return wbot;
};

export default GetTicketWbot;
export default GetTicketWbot;
7 changes: 5 additions & 2 deletions backend/src/helpers/SerializeUser.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
import Queue from "../models/Queue";
import User from "../models/User";
import Whatsapp from "../models/Whatsapp";

interface SerializedUser {
id: number;
name: string;
email: string;
profile: string;
queues: Queue[];
whatsapp: Whatsapp;
}

export const SerializeUser = (user: User): SerializedUser => {
Expand All @@ -15,6 +17,7 @@ export const SerializeUser = (user: User): SerializedUser => {
name: user.name,
email: user.email,
profile: user.profile,
queues: user.queues
queues: user.queues,
whatsapp: user.whatsapp
};
};
};
14 changes: 12 additions & 2 deletions backend/src/models/User.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,15 @@ import {
AutoIncrement,
Default,
HasMany,
BelongsToMany
BelongsToMany,
ForeignKey,
BelongsTo
} from "sequelize-typescript";
import { hash, compare } from "bcryptjs";
import Ticket from "./Ticket";
import Queue from "./Queue";
import UserQueue from "./UserQueue";
import Whatsapp from "./Whatsapp";

@Table
class User extends Model<User> {
Expand Down Expand Up @@ -45,6 +48,13 @@ class User extends Model<User> {
@Column
profile: string;

@ForeignKey(() => Whatsapp)
@Column
whatsappId: number;

@BelongsTo(() => Whatsapp)
whatsapp: Whatsapp;

@CreatedAt
createdAt: Date;

Expand All @@ -70,4 +80,4 @@ class User extends Model<User> {
};
}

export default User;
export default User;
19 changes: 14 additions & 5 deletions backend/src/services/TicketServices/CreateTicketService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,30 +2,39 @@ import AppError from "../../errors/AppError";
import CheckContactOpenTickets from "../../helpers/CheckContactOpenTickets";
import GetDefaultWhatsApp from "../../helpers/GetDefaultWhatsApp";
import Ticket from "../../models/Ticket";
import User from "../../models/User";
import ShowContactService from "../ContactServices/ShowContactService";

interface Request {
contactId: number;
status: string;
userId: number;
queueId ?: number;
}

const CreateTicketService = async ({
contactId,
status,
userId
userId,
queueId
}: Request): Promise<Ticket> => {
const defaultWhatsapp = await GetDefaultWhatsApp();
const defaultWhatsapp = await GetDefaultWhatsApp(userId);

await CheckContactOpenTickets(contactId);
await CheckContactOpenTickets(contactId, defaultWhatsapp.id);

const { isGroup } = await ShowContactService(contactId);

if(queueId === undefined) {
const user = await User.findByPk(userId, { include: ["queues"]});
queueId = user?.queues.length === 1 ? user.queues[0].id : undefined;
}

const { id }: Ticket = await defaultWhatsapp.$create("ticket", {
contactId,
status,
isGroup,
userId
userId,
queueId
});

const ticket = await Ticket.findByPk(id, { include: ["contact"] });
Expand All @@ -37,4 +46,4 @@ const CreateTicketService = async ({
return ticket;
};

export default CreateTicketService;
export default CreateTicketService;
11 changes: 7 additions & 4 deletions backend/src/services/TicketServices/FindOrCreateTicketService.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
// import { subHours } from "date-fns";
const add = require('date-fns/add')
const add = require('date-fns/add');
import { Op } from "sequelize";
import Contact from "../../models/Contact";
import Ticket from "../../models/Ticket";
Expand All @@ -17,7 +17,8 @@ const FindOrCreateTicketService = async (
status: {
[Op.or]: ["open", "pending"]
},
contactId: groupContact ? groupContact.id : contact.id
contactId: groupContact ? groupContact.id : contact.id,
whatsappId: whatsappId
}
});

Expand All @@ -28,7 +29,8 @@ const FindOrCreateTicketService = async (
if (!ticket && groupContact) {
ticket = await Ticket.findOne({
where: {
contactId: groupContact.id
contactId: groupContact.id,
whatsappId: whatsappId
},
order: [["updatedAt", "DESC"]]
});
Expand All @@ -52,7 +54,8 @@ const FindOrCreateTicketService = async (
updatedAt: {
[Op.between]: [+add(new Date(), {seconds: timeCreateNewTicket}), +new Date()]
},
contactId: contact.id
contactId: contact.id,
whatsappId: whatsappId
},
order: [["updatedAt", "DESC"]]
});
Expand Down
19 changes: 13 additions & 6 deletions backend/src/services/TicketServices/UpdateTicketService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ interface TicketData {
status?: string;
userId?: number;
queueId?: number;
whatsappId?: number;
}

interface Request {
Expand All @@ -27,16 +28,20 @@ const UpdateTicketService = async ({
ticketData,
ticketId
}: Request): Promise<Response> => {
const { status, userId, queueId } = ticketData;
const { status, userId, queueId, whatsappId } = ticketData;

const ticket = await ShowTicketService(ticketId);
await SetTicketMessagesAsRead(ticket);

if(whatsappId && ticket.whatsappId !== whatsappId) {
await CheckContactOpenTickets(ticket.contactId, whatsappId);
}

const oldStatus = ticket.status;
const oldUserId = ticket.user?.id;

if (oldStatus === "closed") {
await CheckContactOpenTickets(ticket.contact.id);
await CheckContactOpenTickets(ticket.contact.id, ticket.whatsappId);
}

await ticket.update({
Expand All @@ -45,7 +50,11 @@ const UpdateTicketService = async ({
userId
});


if(whatsappId) {
await ticket.update({
whatsappId
});
}

await ticket.reload();

Expand All @@ -58,8 +67,6 @@ const UpdateTicketService = async ({
});
}



io.to(ticket.status)
.to("notification")
.to(ticketId.toString())
Expand All @@ -71,4 +78,4 @@ const UpdateTicketService = async ({
return { ticket, oldStatus, oldUserId };
};

export default UpdateTicketService;
export default UpdateTicketService;
15 changes: 8 additions & 7 deletions backend/src/services/UserServices/CreateUserService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ interface Request {
name: string;
queueIds?: number[];
profile?: string;
whatsappId?: number;
}

interface Response {
Expand All @@ -24,7 +25,8 @@ const CreateUserService = async ({
password,
name,
queueIds = [],
profile = "admin"
profile = "admin",
whatsappId
}: Request): Promise<Response> => {
const schema = Yup.object().shape({
name: Yup.string().required().min(2),
Expand Down Expand Up @@ -56,18 +58,17 @@ const CreateUserService = async ({
email,
password,
name,
profile
profile,
whatsappId: whatsappId ? whatsappId : null
},
{ include: ["queues"] }
{ include: ["queues", "whatsapp"] }
);

await user.$set("queues", queueIds);

await user.reload();

const serializedUser = SerializeUser(user);

return serializedUser;
return SerializeUser(user);
};

export default CreateUserService;
export default CreateUserService;
Loading

0 comments on commit 930db47

Please sign in to comment.