Untitled
unknown
plain_text
a year ago
2.3 kB
8
Indexable
const sendEmailToSalesman = catchAsync(async (user,name) => {
await new Email(user).sendNotificationToSalesMan(name);
});
exports.createNewChat = catchAsync(async (req, res, next) => {
const { content, id } = req.body;
if (!content) {
return next(new AppError('message is require', 400));
}
if (!id) {
return next(new AppError('user is require', 400));
}
const session = await mongoose.startSession();
try {
session.startTransaction();
const user = await User.findOne({ _id: id });
const retailer = await Retailer.findOne({ _id: user.profile });
const salesMan = await getRandomSalesMan(retailer.province, retailer._id, next);
const chat = await Chat.find({ retailer: retailer._id, sales_man: salesMan._id });
if (chat.length > 0) {
const message = await Message.create([{ message: content, sender: retailer._id, receiver: salesMan._id }], {
session
});
await Chat.updateOne({ _id: chat[0]._id }, { $push: { messages: message[0]._id } }, { session });
} else {
const newChat = await Chat.create([{ retailer: retailer._id, sales_man: salesMan._id }], { session });
const message = await Message.create([{ message: content, sender: retailer._id, receiver: salesMan._id }], {
session
});
await Chat.updateOne({ _id: newChat[0]._id }, { $push: { messages: message[0]._id } }, { session });
}
const users = await User.find({ profile:salesMan._id });
const usersIds = [];
for (let i = 0; i < users.length; i++) {
const notification = await Notification.create([{ content: 'new conversation with '+user.name, type: 'chat' }], { session });
await User.updateOne({ _id: users[i]._id }, { $push: { notifications: notification[0]._id } }, { session });
usersIds.push({ id: users[i]._id.toString(), data: notification });
}
Socket.SocketConnectedList(usersIds);
try{
sendEmailToSalesman(users[0],user.name)
}catch(error){
}
await session.commitTransaction();
session.endSession();
res.status(200).json({
message: 'message successfully'
});
} catch (error) {
await session.abortTransaction();
session.endSession();
return next(error);
}
});Editor is loading...
Leave a Comment