Untitled

mail@pastecode.io avatar
unknown
plain_text
5 days ago
7.0 kB
1
Indexable
Never


//   change status


exports.changeOrderStatus = catchAsync(async (req, res, next) => {
  const { id, status } = req.body;
  const order_id = toObjectId(id, next);
  const session = await mongoose.startSession();

  try {
    session.startTransaction();
  const order = await Order.updateOne({ _id: order_id }, { status: status }, { runValidators: true },{session});
  if (order.matchedCount > 0) {
    const users = await Order.aggregate([
      {$match : {_id: order_id}},
      {
        $lookup: {
          from: 'users',
          localField: 'ordered_by',
          foreignField: '_id',
          pipeline: [{ $project: { name: 1 } }],
          as: 'user'
        }
      },
    ]);
    console.log('data :',users)
    const usersIds = []
    for(let i=0;i<users[0].user.length;i++){
     const notification = await Notification.create([{content:'Your order status has been '+status+'', type:'order'}],{ session })

     await User.updateOne({_id : users[0].user[i]._id},{ $push: { notifications: notification[0]._id } })
     usersIds.push({id :users[0].user[i]._id.toString(),data: notification})
    }
    Socket.SocketConnectedList(usersIds)
    res.status(200).json({ status: 'success', order: order });
  } else {
    res.status(400).json({ status: 'error', message: 'order id invalid' });
  }
  } catch (error) {
  await session.abortTransaction();
  session.endSession();
  return next(error);
}
});














//  add retailer   ---> retailer controller

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
            }
          ],
          { 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));
      }
      console.log('hiii')
      if(request_retailer_id){
      
       await RetailerRequest.deleteOne({_id:request_retailer_id},{session})
      // console.log("retailer req : ",request_retailer_id)
       }
      if (newUser) {
        
        await session.commitTransaction();
        session.endSession();
        const users = await User.find({ $or :[{role:'manager'},{role:'admin'},{role:'salesman',province:req.body.province}]});
        const usersIds = []
        for(let i=0;i<users.length;i++){
         const notification = await Notification.create([{content:'new order', type:'order'}],{ 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)
        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);
    }
})











// user controller


exports.signupUser = catchAsync(async (req, res, next) => {
  const { email, password, name, role, phone, passwordConfirm } = req.body;
  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 = null;
    // Création du profil
    if (role == 'client') {
      profile = await Client.create([{}], { session });
    } else if (role == 'retailer') {
      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
          }
        ],
        { session }
      );
    } else {
      res.status(400);
      throw new Error('Invalid role specified');
    }

    // Création de l'utilisateur
    const newUser = await User.create({
      name,
      email,
      phone,
      role,
      password,
      profile: profile[0],
      creationDate: new Date(),
      active: false
    });
    if (newUser) {
      await session.commitTransaction();
      session.endSession();
      const users = await User.find({ $or :[{role:'manager'},{role:'admin'}]});
    const usersIds = []
    for(let i=0;i<users.length;i++){
     const notification = await Notification.create([{content:'A new client has been added to the system', type:'order'}],{ 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)
      // Envoi de la réponse avec les détails de l'utilisateur et le jeton d'authentification
      this.createAndSendToken(newUser, 200, req, res);
    } 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