Untitled
unknown
plain_text
a year ago
16 kB
3
Indexable
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 { isDecimal } = require('validator'); const Client = require('../Models/clientModel.js'); const Cart = require('../Models/cartModel.js'); const { createAndSendToken } = require('./authController.js'); const Order = require('../Models/orderModel.js'); const Retailer = require('../Models/retailerModel.js'); const Image = require('../Models/imageModel.js'); const RetailerRequest = require('../Models/retailerRequestModel.js'); const { isValidEmail, isValidName, isValidPhoneNumber } = require('./../utils/validationfunctions.js'); exports.RetaillerRequest = catchAsync(async(req,res,next) => { const { email, name, phone,company_name,province} = req.body; if(!isValidEmail(email)){ return next(new AppError('incorrect email', 400)); } if(!isValidName(name)){ return next(new AppError('incorrect full name', 400)); } if(!isValidPhoneNumber(phone)){ return next(new AppError('incorrect phone', 400)); } if(!company_name){ return next(new AppError('company is required', 400)); } if(!province){ return next(new AppError('province is required', 400)); } const newRetailer = await RetailerRequest.create({name:name,email:email,phone:phone, company_name:company_name,province:province}); console.log(newRetailer) res.status(200).json({ status: 'success', data: newRetailer }) }) exports.getRetaillerRequests = catchAsync(async(req,res,next) => { const list = await RetailerRequest.find({}) res.status(200).json({ status: 'success', data: list }); }) 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(); 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); } }) exports.updateRetailerProfile = catchAsync(async (req, res, next) => { const session = await mongoose.startSession(); try { session.startTransaction(); const user = await User.findById(req.user.id); // Assuming req.user.id contains the ObjectId of the user if (!user) { return next(new AppError('User not found', 404)); } console.log(req.body); const { firstName, lastName, email, phone, address, gender ,image} = req.body; const {company_name,province,ice,register_commerce,tax,cnss,rib,id_fiscal} = req.body console.log(req.body) if (firstName || lastName) { const fullName = [firstName, lastName].filter(Boolean).join(' '); user.name = fullName; } if (email) { user.email = email; } if (phone) { user.phone = phone; } // Update address if provided if (address) { user.fulladdress.address = address?.address; user.fulladdress.zipCode = address?.zipCode; user.fulladdress.city = address?.city; } if (gender) { user.gender = gender; } if(image){ const ImageProfile = await Image.create([{ image: new Buffer.from(image, 'base64') }],{ session }) user.photo = ImageProfile[0]._id } const retailer = await Retailer.findById(user.profile); if(company_name){ retailer.company_name = company_name; } if(province){ retailer.province = province } if(ice){ retailer.ice = ice } if(id_fiscal){ retailer.id_fiscal = id_fiscal } if(register_commerce){ retailer.register_commerce = register_commerce } if(tax){ retailer.taxe = tax; } if(cnss){ retailer.cnss = cnss; } if(rib){ retailer.rib = rib; } await retailer.save({ session }); await user.save({ session }); await session.commitTransaction(); session.endSession(); res.status(200).json({ status: ' the client profile is updated successfully', data: user }); }catch (error) { await session.abortTransaction(); session.endSession(); return next(error); } }); exports.getRetailer = catchAsync(async (req, res, next) => { const Id = toObjectId(req.params.id) const user = await User.findById(Id); if(!user){ return next(new AppError('User not found', 400)); } const data = await User.aggregate([ { $match : {_id :user._id}}, { $lookup: { from: 'retailers', localField: 'profile', foreignField: '_id', as: 'retailer' } }, ]) res.status(200).json({ status: ' the client profile is updated successfully', data: data }); }) exports.changeStatus = catchAsync(async (req, res, next) => { // ['client', 'admin', 'retailer', 'subadmin', 'manager', 'salesman'] let { id_retailer, status } = req.body; let obj = {}; if (id_retailer) { Id = toObjectId(id_retailer,next) } else { return next(new AppError('id retailer required', 400)); } if (id_retailer) { if (status == 'true') { obj.status = true; } else if (status == 'false') { obj.status = false; } else { return next(new AppError('status required', 400)); } } const retailer = await User.updateOne({ _id: Id }, obj); if (retailer) { res.status(200).json({ message: 'success', retailer, id_retailer }); } else { return next(new AppError('server error', 500)); } }); exports.bulkChangeStatus = catchAsync(async (req, res, next) => { let { ids, status } = req.body; let obj = {}; if (ids) { if (!Array.isArray(ids)) { return next(new AppError('ids of retailers is not an array', 400)); } }else { return next(new AppError('ids of retailers required', 400)); } if (status == 'true') { obj.status = true; } else if (status == 'false') { obj.status = false; } else { return next(new AppError('status required', 400)); } const retailers = await User.updateMany({ _id: {$in : ids} }, obj); if (retailers) { res.status(200).json({ message: 'success', retailers }); } else { return next(new AppError('server error', 500)); } }); exports.changePricingType = catchAsync(async (req, res, next) => { // ['client', 'admin', 'retailer', 'subadmin', 'manager', 'salesman'] let { id_retailer, pricingType } = req.body; let obj = {}; if (id_retailer) { Id = toObjectId(id_retailer,next) } else { return next(new AppError('id retailer required', 400)); } if (pricingType == 1 || pricingType == 2 || pricingType == 3) { obj.pricingType = parseInt(pricingType); }else { return next(new AppError('pricingType required', 400)); } const user = await User.find({ _id: Id,role : 'retailer' }); if(user.length < 1){ return next(new AppError('not user', 400)); } const retailer = await Retailer.updateOne({_id : user[0].profile},obj) if (retailer) { res.status(200).json({ message: 'success', retailer, id_retailer }); } else { return next(new AppError('server error', 500)); } }); exports.bulkChangePricingTypes = catchAsync(async (req, res, next) => { let { ids, pricingType } = req.body; let obj = {}; if (ids) { if (!Array.isArray(ids)) { return next(new AppError('ids of retailers is not an array', 400)); } }else { return next(new AppError('ids of retailers required', 400)); } if (pricingType == 1 || pricingType == 2 || pricingType == 3) { obj.pricingType = parseInt(pricingType); }else { return next(new AppError('pricingType required', 400)); } const users = await User.find({ _id: { $in : ids},role : 'retailer' }); if(users.length < 1){ return next(new AppError('not user', 400)); } let new_ids = users.map((user) => user.profile) console.log(new_ids) const retailers = await Retailer.updateMany({_id : {$in : new_ids}},obj) if (retailers) { res.status(200).json({ message: 'success', retailers }); } else { return next(new AppError('server error', 500)); } }); exports.getRetailersByFilter = catchAsync(async (req, res, next) => { const {email,pricingType,status} = req.query; const page = parseInt(req.query.page); const limit = parseInt(req.query.limit); let search = {role : "retailer"} let obj = {} if(email){ search.email = { $regex: email , $options: 'i' } } if (pricingType == 1 || pricingType == 2 || pricingType == 3) { obj.pricingType = parseInt(pricingType); } if (status == 'true') { search.status = true; } else if (status == 'false') { search.status = false; } const count = await User.find(search).count(); console.log(count); let retailers = null let countPages = count % limit == 0 ? parseInt(count / limit) : parseInt(count / limit) + 1; retailers = await User.aggregate([ {$match : search}, { $lookup: { from: 'retailers', localField: 'profile', foreignField: '_id', pipeline: [ {$match : obj}, {$project : {pricingType : 1}} ], as: 'Pricing' } }, {$match: { "Pricing": { $ne: [] } }} ]) //.map((resul) => resul.PricingType) console.log(retailers) const data = retailers.reduce((result, retailer) => { let obj = {}; obj._id = retailer._id; obj.name = retailer.name; obj.joiningDate = retailer.createdAt; obj.email = retailer.email; obj.phone = retailer.phone; obj.status = retailer.status; obj.profileImage = retailer.photo; obj.pricingType = retailer.Pricing[0].pricingType; console.log(retailer.Pricing) result.push(obj); return result; }, []); res.status(200).json({ status: "success", data: data, count : count }); }) exports.deleteRetailer = catchAsync(async (req, res, next) => { const retailerId = req.params.id; if (!retailerId) { return next(new AppError('Please provide the retailer ID', 400)); } // Start a Mongoose session const session = await mongoose.startSession(); try { // Use the session for transaction await session.withTransaction(async () => { // 1. Get the user document const user = await User.findById(retailerId).session(session); // 2. Check if the user exists if (!user) { return next(new AppError('retailer not found', 404)); } // 3. Determine the type of profile based on the user's role if (user.role !== 'retailer') { return next(new AppError('Invalid role', 400)); } // 4. Delete the client's profile document await Retailer.findByIdAndDelete(user.profile).session(session); // Additional Step: Delete the image document if it exists if (user.photo) { await Image.findByIdAndDelete(user.photo).session(session); } // 6. Delete the user document await User.findByIdAndDelete(retailerId).session(session); }); // Commit the session if everything went well await session.commitTransaction(); // Respond with a success message res.status(200).json({ status: 'success', message: 'retailer deleted successfully' }); } catch (err) { // If any error occurs, abort the session await session.abortTransaction(); // Pass the error to the error handling middleware next(err); } finally { // End the session session.endSession(); } }); exports.AddToWishlist = catchAsync(async (req, res, next) => { // Extract necessary information from the request body const { userID, productID } = req.body; // Find the user by ID and check if the client profile and wishlist exist const user = await User.findById(userID); if (!user) { return next(new AppError('User not found', 404)); } const retailer = await Retailer.findById(user.profile); if (!retailer) { return next(new AppError('retailer not found', 404)); } // Check if the product already exists in the client's wishlist const productExistsInWishlist = await Retailer.findOne({ _id: user.profile, wishlist: { $in: [productID] } }); if (productExistsInWishlist) { return res.status(400).json({ message: 'Product already exists in the wishlist' }); } // Add the product to the wishlist retailer.wishlist.push(product); await retailer.save(); res.status(200).json({ message: 'Product added to wishlist successfully', wishlist: retailer.wishlist }); }); const toObjectId = (id, next) => { try { return new mongoose.Types.ObjectId(id); }catch (e) { return next(new AppError('Invalid id.', 401)); } };
Editor is loading...
Leave a Comment