Untitled

 avatar
unknown
plain_text
a month ago
6.3 kB
4
Indexable
exports.sendMessage = catchAsync(async (req, res, next) => {
  const { content, receiver_id, receiver_role } = req.body;
  if (!content) {
    return next(new AppError('message is require', 400));
  }

  if (req.user.role != 'retailer' && req.user.role != 'distributeur' && req.user.role != 'manager') {
    return next(new AppError('this role no have a chat', 400));
  }
  const session = await mongoose.startSession();
  let manager_chat = null;
  let client_chat = null;
  let role_client = null;
  try {
    session.startTransaction();
    if (req.user.role == 'manager') {
      if (!receiver_id) {
        return next(new AppError('receiver id is require', 400));
      }
      const manager = await Manager.findById(req.user.profile);
      if (!manager) {
        return next(new AppError('manager not found', 400));
      }
      if (!receiver_role) {
        return next(new AppError('receiver_role required', 400));
      }
      if (receiver_role == 'retailer') {
        //  return next(new AppError('receiver_role is not correct', 400));
        const retailer = await Retailer.findById(toObjectId(receiver_id, next));
        if (!retailer) {
          return next(new AppError('retailer not found', 400));
        }
        // check manager
        if (!retailer.manager) {
          return next(new AppError("this retailer doesn't have a  manager", 400));
        }
        if (String(retailer.manager) != String(manager._id)) {
          return next(new AppError("manager can't chat with this retailer", 400));
        }

        client_chat = retailer._id;
        role_client = 'retailer';
      } else if (receiver_role == 'distributeur') {
        const distributeur = await Distributeur.findById(toObjectId(receiver_id, next));
        if (!distributeur) {
          return next(new AppError('distributeur not found', 400));
        }
        // check manager
        if (!distributeur.manager) {
          return next(new AppError("this distributeur doesn't have a  manager", 400));
        }
        if (String(distributeur.manager) != String(manager._id)) {
          return next(new AppError("manager can't chat with this distributeur", 400));
        }

        client_chat = distributeur._id;
        role_client = 'distributeur';
      } else {
        return next(new AppError('invalid role', 400));
      }

      manager_chat = manager._id;
    } else {
      if (req.user.role == 'retailer') {
        const retailer = await Retailer.findById(req.user.profile);
        if (!retailer) {
          return next(new AppError('retailer not found', 400));
        }

        // check this retailer have a manager
        if (!retailer.manager) {
          return next(new AppError("this retailer doesn't have a  salesman", 400));
        }
        const manager = await Manager.findById(retailer.manager);
        if (!manager) {
          return next(new AppError('manager not found', 400));
        }

        manager_chat = manager._id;
        client_chat = retailer._id;
        role_client = 'retailer';
      } else if (req.user.role == 'distributeur') {
        const distributeur = await Distributeur.findById(req.user.profile);
        if (!distributeur) {
          return next(new AppError('distributeur not found', 400));
        }

        // check this retailer have a manager
        if (!distributeur.manager) {
          return next(new AppError("this retailer doesn't have a  salesman", 400));
        }
        const manager = await Manager.findById(distributeur.manager);
        if (!manager) {
          return next(new AppError('manager not found', 400));
        }

        manager_chat = manager._id;
        client_chat = distributeur._id;
        role_client = 'distributeur';
      } else {
        return next(new AppError('Logic error', 500));
      }
    }

    // check chat data
    if (!manager_chat || !client_chat || !role_client) {
      return next(new AppError('chat data not complete', 500));
    }

    const user = await User.findOne({ profile: client_chat });
    if (user.length < 1) {
      return next(new AppError('user not found', 400));
    }

    const chat = await Chat.find({ client: client_chat, manager: manager_chat });
    let message;
    if (req.user.role == 'manager') {
      message = await Message.create([{ message: content, sender: manager_chat, receiver: client_chat }], { session });
    } else {
      message = await Message.create([{ message: content, sender: client_chat, receiver: manager_chat }], { session });
    }
    if (chat.length < 1) {
      const newChat = await Chat.create([{ manager: manager_chat, client: client_chat, role: role_client }], {
        session
      });
      await Chat.updateOne({ _id: newChat[0]._id }, { $push: { messages: message[0]._id } }, { session });
      
    } else {
      await Chat.updateOne({ _id: chat[0]._id }, { $push: { messages: message[0]._id } }, { session });
    }

    // send notification

      let users = []
      if(req.user.role == "manager"){
        users = await User.find({ profile: client_chat });
      }else{
        users = await User.find({ profile: manager_chat });
      }
      
      const usersIds = [];
      for (let i = 0; i < users.length; i++) {
        const notification = await Notification.create(
          [{ content: 'new message from ' + req.user.name, type: 'chat' }],
          { session }
        );
        // send to mobile
        if(req.user.role == "manager"){
          mobileNotification.sendNotificationToUser(
                    user.token_notification,
                    notification.content,
                    notification.type
                  )
        }
        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);

    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