Untitled

mail@pastecode.io avatar
unknown
plain_text
5 months ago
3.2 kB
2
Indexable
exports.addRetailler = catchAsync(async (req, res, next) => {
  const { email, password, name, phone, address, image, request_retailer_id } = req.body;
  let fulladdress = {};
  let ImageProfile = [null];
  const session = await mongoose.startSession();

  try {
    session.startTransaction();
    // Vérification si l'utilisateur existe déjà
    const existingUser = await User.findOne({ email });
    if (existingUser) {
      res.status(400);
      throw new Error('User already exists');
    }

    let profile = await Retailer.create(
      [
        {
          company_name: req.body.company_name,
          province: req.body.province,
          ice: req.body.ice,
          id_fiscal: req.body.id_fiscal,
          register_commerce: req.body.register_commerce,
          taxe: req.body.taxe,
          cnss: req.body.cnss,
          rib: req.body.rib,
          pricingType: req.body.pricingType,
          payment_method: req.body.payment_method
        }
      ],
      { session }
    );
    if (image) {
      ImageProfile = await Image.create([{ image: new Buffer.from(image, 'base64') }], { session });
    }
    if (address) {
      fulladdress.address = address?.address;
      fulladdress.zipCode = address?.zipCode;
      fulladdress.city = address?.city;
    }
    const newUser = await User.create(
      [
        {
          name,
          email,
          phone,
          role: 'retailer',
          password,
          profile: profile[0],
          fulladdress: fulladdress,
          photo: ImageProfile[0],
          creationDate: new Date(),
          active: false
        }
      ],
      { session }
    );

    const req_ret_id = toObjectId(request_retailer_id, next);
    if (!req_ret_id) {
      return next(new AppError('Invalid id.', 401));
    }
    if (request_retailer_id) {
      await RetailerRequest.deleteOne({ _id: request_retailer_id }, { session });
      // console.log("retailer req : ",request_retailer_id)
    }
    if (newUser) {
      const users = await User.find({
        $or: [
          { role: 'manager' },
          { role: 'admin' },
          { role: 'subadmin' },
          { role: 'salesman', province: req.body.province }
        ]
      });
      const usersIds = [];
      for (let i = 0; i < users.length; i++) {
        const notification = await Notification.create(
          [{ content: 'new Retailer added to the system : ' + ' ' + name, type: 'user' }],
          { 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);
      await session.commitTransaction();
      session.endSession();
      res.status(200).json({
        status: 'success',
        data: newUser[0]
      });
    } else {
      await session.abortTransaction();
      session.endSession();
      res.status(400);

      throw new Error('cant create User');
    }
  } catch (error) {
    await session.abortTransaction();
    session.endSession();
    return next(error);
  }
});
Leave a Comment