Untitled

mail@pastecode.io avatar
unknown
plain_text
a month ago
7.3 kB
1
Indexable
Never
const mongoose = require('mongoose');
const User = require('../Models/userModel.js');
const SubCategory = require('../Models/subcategoryModel.js');
const Group = require('../Models/groupModel.js');
const Brand = require('../Models/brandModel.js');
const Category = require('../Models/categoryModel.js');
const Product = require('../Models/productModel.js');
const AppError = require('../utils/appError.js');
const catchAsync = require('../utils/catchAsync.js');
const Client = require('../Models/clientModel.js');
const SalesMan = require('../Models/salesmanModel.js');
const Cart = require('../Models/cartModel.js');
const Order = require('../Models/orderModel.js');
const Retailer = require('../Models/retailerModel.js');
const Chat = require('../Models/chatModel.js');
const Message = require('../Models/messageModel.js');
const Offer = require('../Models/offerModel.js');
const { exist } = require('joi');



exports.addNewOffer = catchAsync(async(req,res,next) => {
    const {name,discount,listproducts} = req.body
   if(!name){
    return next(new AppError('name is require', 400));
   }
   if(!discount){
    return next(new AppError('discount is require', 400));
   }
   if(discount <0 || discount > 100){
    return next(new AppError('discount is not valid', 400));
   }
   if ( !Array.isArray(listproducts) || !listproducts.length) {
    return next(new AppError('products array cannot be empty', 400));
   }
   const {validIds , invalidIds} = await verifyIds(listproducts,next)
   const newvalidIds = validIds.map( id => toObjectId(id,next))
   if(invalidIds.length){
    return next(new AppError('invalid products ids '+invalidIds, 400)); 
   }

   for(let i=0 ; i<validIds.length ; i++){
    const prod = await Product.findById(validIds[i])
    if(prod.offer){
        return next(new AppError('this product '+prod.name.fr +' has offer', 400));
    }
   }
   const session = await mongoose.startSession();

   try {
   session.startTransaction();   
    const offer = await Offer.create([{name : name,discount: discount}],{ session })
    const Products = await Product.updateMany({_id: {$in : validIds}},{offer : offer[0]._id},{ session })

    await session.commitTransaction();
    session.endSession();
    res.status(200).json({
        message: 'offer added successfully', 
        data: Products
    });
  } catch (error) {
    await session.abortTransaction();
    session.endSession();
    return next(error);
  } 

})

exports.getoffersList = catchAsync(async(req,res,next) => {
  const requestedPage = parseInt(req.query.page) || 1; // Requested page number
  const productsPerPage = parseInt(req.query.limit) || 10; // Requested page number
  const obj = {}
  const {name} = req.query
  if(name){
    obj.name = { $regex: name , $options: 'i' } 
  }
  // Count total number of products
  const count = await Offer.countDocuments();
   console.log(name)
  // Get products for the requested page
  const offers = await Offer.aggregate([
    {
      $match : obj
    },
    {
      $lookup: {
      from: 'products',
      localField: '_id',
      foreignField: 'offer',
      pipeline: [
        { $group: {
            _id:"" , 
            totalProduct: { $sum: 1 } 
          }
        }
      ],
      as: 'products'
      }
   },
  ])
    .skip((requestedPage - 1) * productsPerPage)
    .limit(productsPerPage)
    
    const data = offers.reduce((result, offer) => {
      let obj = {};
      obj._id = offer._id;
      obj.name = offer.name;
      obj.discount = offer.discount;
      obj.status = offer.status;
      obj.totalProduct = offer.products[0]?.totalProduct ?? 0;
      result.push(obj);
  
    return result;
    }, []);  
  res.status(200).json({
    count,
    currentPage: requestedPage,
    productsPerPage,
    offers : data
  });
});

exports.getofferbyId = catchAsync(async(req,res,next) => {
  const {id} = req.params
  const offer = await Offer.findById(toObjectId(id,next))
  if(!offer) {
    return next(new AppError('no offer existe', 400));
  }
  
  const results = await Offer.aggregate([
    {
      $match : {_id : toObjectId(id,next)}
    },
    {
      $lookup: {
      from: 'products',
      localField: '_id',
      foreignField: 'offer',
      pipeline: [
        { $project: { name: 1} },
      ],
      as: 'products'
      }
   },
  ])

  res.status(200).json({
    offer : results[0]
  });

})

exports.changeStatus = catchAsync(async(req,res,next) =>{
  const {status,id_offer} = req.body
  const offer = await Offer.findById(toObjectId(id_offer,next))
  if(!offer) {
    return next(new AppError('this offer no existe', 400));
  }
  if(status == 'true'){
     offer.status = true
  }else if(status == 'false'){
    offer.status = false
  }else{
    return next(new AppError('status invalid', 400));
  }
  offer.save()
  res.status(200).json({
    message: 'offer updated successfully', 
});
})

exports.updateOffer = catchAsync(async(req,res,next) => {
  const {name,discount,id_offer} = req.body
   if(!id_offer){
    return next(new AppError('id_offer is require', 400));
   }
  try{
   const offer = await Offer.findById(toObjectId(id_offer,next))
    if(!offer){
     return next(new AppError('this offer not valid', 400));
    }
   if(name){
    offer.name = name
   }
   if(discount){
    if(discount <0 || discount > 100){
        return next(new AppError('discount is not valid', 400));
    }
    offer.discount = discount
   } 
   offer.save()
    res.status(200).json({
        message: 'offer updated successfully', 
    });
  } catch (error) {
    return next(error);
  } 
  
})


exports.deleteOffer = catchAsync(async(req,res,next) => {
    const {id} = req.params
    console.log(id)
     if(!id){
      return next(new AppError('id offer is require', 400));
     }
     const offer = await Offer.findById(toObjectId(id,next))
      if(!offer){
       return next(new AppError('this offer not valid', 400));
      }
      
   const session = await mongoose.startSession();
   try {
   session.startTransaction();  
   await Product.updateMany({offer : toObjectId(id)},{$unset : {offer : ""}})
   await Offer.deleteOne({_id : id})

   await session.commitTransaction();
   session.endSession();
   res.status(200).json({
       message: 'offer deleted successfully', 
   });
    } catch (error) {
    await session.abortTransaction();
    session.endSession();
    return next(error);
    } 
    
  })


async function verifyIds(ids,next) {
    const objectIds = ids.map(id => toObjectId(id,next));
    try {
      const results = await Product.find({ _id: { $in: objectIds } }).lean().select('_id');

      const foundIds = results.map(doc => doc._id.toString());
 
      const invalidIds = ids.filter(id => !foundIds.includes(id));
      
      return {
        validIds: foundIds,
        invalidIds: invalidIds
      };
    } catch (error) {
      console.error("Error verifying IDs:", error);
      throw error;
    }
  }

const toObjectId = (id, next) => {
    try {
      return new mongoose.Types.ObjectId(id);
    } catch (e) {
      return next(new AppError('Invalid id.', 401));
    }
  };
Leave a Comment