From cf993bf06a93f3bc19a8a5cb3ac6cd30530f2c3c Mon Sep 17 00:00:00 2001 From: Sibunnayak Date: Fri, 26 Jul 2024 08:39:02 +0530 Subject: [PATCH] update --- resources/Products/ProductController.js | 203 ++++++++++++++---------- resources/Products/ProductModel.js | 17 +- resources/Products/ProductRoute.js | 29 +--- 3 files changed, 123 insertions(+), 126 deletions(-) diff --git a/resources/Products/ProductController.js b/resources/Products/ProductController.js index 1e9737a..03f4267 100644 --- a/resources/Products/ProductController.js +++ b/resources/Products/ProductController.js @@ -46,68 +46,73 @@ export const createProduct = async (req, res) => { /////////////////////////////////////////////////////////////////////////////////////// export const updateProduct = async (req, res) => { try { - if (req.body?.variants) { - const vars = req.body.variants || []; // Default to an empty array if req.body.variants is undefined or null - const product = await Product.findByIdAndUpdate( - req.params.id, - { variants: vars }, - { new: true } // Return the updated document - ); + // console.log("Product ID:", req.params.id); + // console.log("Files:", req.files); + // console.log("Body:", req.body); - // Send a JSON response back to the client - return res.status(201).json({ - message: "Product variant saved successfully", - variants: product?.variants || [], // Return the updated variants or an empty array if product is undefined - }); + const { removedImages } = req.body; + const files = req.files?.images || []; + + // Parse removedImages + const removedImageIds = removedImages ? JSON.parse(removedImages) : []; + + // Find the product + const product = await Product.findById(req.params.id); + if (!product) { + return res.status(404).json({ message: "Product not found!" }); } - if (req.files) { - const getProduct = await Product.findById(req.params.id); + // Existing images + let existingImages = product.image || []; + let newImagesLinks = []; - if (getProduct.image?.length > 0) { - // Deleting Images From Cloudinary - for (let i = 0; i < getProduct.image.length; i++) { - await cloudinary.v2.uploader.destroy(getProduct.image[i].public_id); + // Ensure files is always an array + const filesArray = Array.isArray(files) ? files : [files]; + + // Process new images + for (const file of filesArray) { + if (file && file.tempFilePath) { // Check if file has tempFilePath + try { + const result = await cloudinary.v2.uploader.upload(file.tempFilePath, { + folder: "chemiNova/product", + }); + newImagesLinks.push({ + public_id: result.public_id, + url: result.secure_url, + }); + // console.log("Uploaded image:", result.secure_url); + } catch (uploadError) { + console.error("Error uploading image:", uploadError); + return res.status(500).json({ message: "Failed to upload image", error: uploadError.message }); } } - let images = []; - let Allfiles = req.files.image; - if (typeof Allfiles.tempFilePath === "string") { - let filepath = Allfiles.tempFilePath; - - images.push(filepath); - } else { - Allfiles.map((item) => { - images.push(item.tempFilePath); - }); - } - - const imagesLinks = []; - for (let i = 0; i < images.length; i++) { - const result = await cloudinary.v2.uploader.upload(images[i], { - folder: "chemiNova/product", - }); - - imagesLinks.push({ - public_id: result.public_id, - url: result.secure_url, - }); - } - let product = await Product.findByIdAndUpdate( - req.params.id, - { image: imagesLinks }, - { new: true } // Return the updated document - ); - return res.status(201).json({ - message: "Product image saved successfully", - images: product?.image || [], // Return the updated variants or an empty array if product is undefined - }); } + + // Remove images from Cloudinary and database + // for (const public_id of removedImageIds) { + // try { + // await cloudinary.v2.uploader.destroy(public_id); + // // console.log("Deleted image from Cloudinary:", public_id); + // } catch (deleteError) { + // console.error("Error deleting image from Cloudinary:", deleteError); + // return res.status(500).json({ message: "Failed to delete image", error: deleteError.message }); + // } + // } + + // Filter out removed images + const updatedImages = existingImages.filter( + (img) => !removedImageIds.includes(img.public_id) + ); + const allImages = [...updatedImages, ...newImagesLinks]; + + // Update product + product.image = allImages; + await product.save(); + + res.status(200).json({ message: "Product updated successfully!", images: allImages }); } catch (error) { - console.log(error); - res.status(500).json({ - message: error.message ? error.message : "Something went wrong!", - }); + console.error(error); // Log error for debugging + res.status(500).json({ message: "Server error!", error: error.message }); } }; @@ -117,38 +122,45 @@ export const getAllProductAdmin = async (req, res) => { try { const PAGE_SIZE = parseInt(req.query?.show || "10"); const page = parseInt(req.query?.page - 1 || "0"); - let obj = {}; - if (req.query?.name) - obj.name = { - $regex: new RegExp(req.query.name), - $options: "i", + + // Create filter object based on query parameters + let filter = {}; + + if (req.query?.name) { + filter.name = { + $regex: new RegExp(req.query.name, "i"), // Case-insensitive search }; - if (req.query?.category) obj.category = req.query.category; - if (req.query?.FeatureProduct) - obj.featured_Product = req.query.FeatureProduct; - const total = await Product.countDocuments(obj); - const product = await Product.find(obj) + } + if (req.query?.category) { + filter.category = mongoose.Types.ObjectId(req.query.category); // Ensure category is an ObjectId + } + if (req.query?.FeatureProduct) { + filter.featured_Product = req.query.FeatureProduct === "true"; // Convert string to boolean + } + + // Count total products matching the filter + const total = await Product.countDocuments(filter); + + // Fetch products with pagination and sorting + const products = await Product.find(filter) .populate({ - path: "category addedBy master_GST variants.gst_Id", - select: "name categoryName tax", + path: "category addedBy GST", + select: "categoryName name tax", }) .limit(PAGE_SIZE) .skip(PAGE_SIZE * page) - // .sort("name") .sort({ featured_Product: -1, createdAt: -1, }) .exec(); - if (product) { - return res.status(200).json({ - success: true, - total_data: total, - total_pages: Math.ceil(total / PAGE_SIZE), - product, - }); - } + return res.status(200).json({ + success: true, + total_data: total, + total_pages: Math.ceil(total / PAGE_SIZE), + products, // Changed from `product` to `products` to match the response variable + }); } catch (error) { res.status(500).json({ success: false, @@ -175,7 +187,7 @@ export const getAllProductUser = async (req, res) => { const total = await Product.countDocuments(obj); const product = await Product.find(obj) .populate({ - path: "category addedBy master_GST variants.gst_Id", + path: "category addedBy GST", select: "name categoryName tax", }) .limit(PAGE_SIZE) @@ -283,7 +295,7 @@ export const ChangeFeatueProductStatus = async (req, res) => { export const getOneProduct = async (req, res) => { try { const data = await Product.findById(req.params.id).populate({ - path: "category addedBy master_GST variants.gst_Id", + path: "category addedBy GST", select: "name categoryName tax", }); if (data) { @@ -522,30 +534,45 @@ export const getAllProductsDevicesFirst = async (req, res) => { // } // }; + export const deleteImageFromCloudinary = async (req, res) => { const { public_id } = req.params; + // console.log("Received public_id:", public_id); // Debugging log + + // Ensure public_id is not empty + if (!public_id) { + return res.status(400).json({ + success: false, + msg: "Public ID is required!", + }); + } + + const decodedPublicId = decodeURIComponent(public_id); + try { - if (!public_id) { + const response = await cloudinary.v2.uploader.destroy(decodedPublicId); + + if (response.result === "ok") { + return res.status(200).json({ + success: true, + msg: "Image Deleted Successfully!", + }); + } else { return res.status(400).json({ success: false, - msg: "Please Provide Product ID!", - }); - } - const response = await cloudinary.v2.uploader.destroy(public_id); - if (response) { - res.status(200).json({ - success: true, - msg: "Product Deleted Successfully!!", + msg: "Image deletion failed!", }); } } catch (error) { - res.status(500).json({ + console.error("Error deleting image:", error); // Log error for debugging + return res.status(500).json({ success: false, - msg: error.message ? error.message : "Something went wrong!", + msg: error.message || "Something went wrong!", }); } }; + //delete one Product export const deleteProduct = async (req, res) => { try { diff --git a/resources/Products/ProductModel.js b/resources/Products/ProductModel.js index 987d436..4c9c593 100644 --- a/resources/Products/ProductModel.js +++ b/resources/Products/ProductModel.js @@ -15,11 +15,11 @@ const productSchema = new Schema( ref: "CategoryModel", }, - master_price: { + price: { type: Number, required: true, }, - master_GST: { + GST: { type: mongoose.Schema.ObjectId, ref: "Tax", }, @@ -36,19 +36,6 @@ const productSchema = new Schema( type: Boolean, default: false, // Initially, products are not featured }, - variants: [ - { - variant_Name: { type: String, default: "" }, - weight: { type: Number, default: 0 }, - volume: { type: Number, default: 0 }, - price: { type: String, default: "" }, - - gst_Id: { - type: mongoose.Schema.ObjectId, - ref: "Tax", - }, - }, - ], image: [ { public_id: { diff --git a/resources/Products/ProductRoute.js b/resources/Products/ProductRoute.js index 736d1f0..ea0908d 100644 --- a/resources/Products/ProductRoute.js +++ b/resources/Products/ProductRoute.js @@ -16,18 +16,10 @@ const router = express.Router(); import { isAuthenticatedUser, authorizeRoles } from "../../middlewares/auth.js"; router .route("/product/create/") - .post( - isAuthenticatedUser, - authorizeRoles("admin", "Employee"), - createProduct - ); + .post(isAuthenticatedUser, authorizeRoles("admin"), createProduct); router .route("/product/getAll/admin/") - .get( - isAuthenticatedUser, - authorizeRoles("admin", "Employee"), - getAllProductAdmin - ); + .get(isAuthenticatedUser, authorizeRoles("admin"), getAllProductAdmin); //change Product status router.route("/product/admin/status/:id").patch(ChangeProductStatus); @@ -43,23 +35,14 @@ router router.route("/product/getOne/:id").get(getOneProduct); router .route("/product/update/:id") - .patch( - isAuthenticatedUser, - authorizeRoles("admin", "Employee"), - updateProduct - ); + .patch(isAuthenticatedUser, authorizeRoles("admin"), updateProduct); router .route("/product/delete/:id") - .delete( - isAuthenticatedUser, - authorizeRoles("admin", "Employee"), - deleteProduct - ); + .delete(isAuthenticatedUser, authorizeRoles("admin"), deleteProduct); router - .route("/product/deleteImage/jatinMor/product/:public_id") + .route("/product/deleteImage/:public_id") .delete( - isAuthenticatedUser, - authorizeRoles("admin", "Employee"), + isAuthenticatedUser, authorizeRoles("admin"), deleteImageFromCloudinary ); router.route("/products/category/:categoryName").get(getProductsByCategory);