Untitled

mail@pastecode.io avatar
unknown
plain_text
13 days ago
2.9 kB
3
Indexable
Never
exports.sendMessage = catchAsync(async (req, res, next) => {
  const { content, salesMan_id, retailer_id, sender } = req.body;
  if (!content) {
    return next(new AppError('message is require', 400));
  }
  if (!retailer_id) {
    return next(new AppError('retailer id is require', 400));
  }
  if (!salesMan_id) {
    return next(new AppError('salesMan id is require', 400));
  }
  if (sender != 'retailer' && sender != 'salesman') {
    return next(new AppError('sender is require', 400));
  }
  const session = await mongoose.startSession();

  try {
    session.startTransaction();
    const retailer = await Retailer.findById(toObjectId(retailer_id, next));
    if (!retailer) {
      return next(new AppError('retailer not found', 400));
    }
    if (!retailer.sales_man) {
      return next(new AppError("this retailer doesn't have a  salesman", 400));
    }
    const salesman = await SalesMan.findById(retailer.sales_man);
    if (!salesman) {
      return next(new AppError('salesman not found', 400));
    }
    if (String(retailer.sales_man) != String(salesMan_id)) {
      return next(new AppError("salesman can't chat with this retailer", 400));
    }

    const chat = await Chat.find({ retailer: toObjectId(retailer_id, next), sales_man: toObjectId(salesMan_id, next) });
    let message;
    if (sender == 'retailer') {
      message = await Message.create([{ message: content, sender: retailer_id, receiver: salesMan_id }], { session });
    } else {
      message = await Message.create([{ message: content, sender: salesMan_id, receiver: retailer_id }], { session });
    }
    if (chat.length < 1) {
      const newChat = await Chat.create([{ retailer: retailer._id, sales_man: retailer.sales_man }], { 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) {}
    } else {
      await Chat.updateOne({ _id: chat[0]._id }, { $push: { messages: message[0]._id } }, { session });
    }
    await session.commitTransaction();
    session.endSession();
    res.status(200).json({
      message: 'message successfully'
    });
  } catch (error) {
    await session.abortTransaction();
    session.endSession();
    return next(error);
  }
});
Leave a Comment