Untitled

mail@pastecode.io avatar
unknown
plain_text
18 days ago
4.8 kB
2
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.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