This commit is contained in:
Sibunnayak 2024-07-26 08:39:02 +05:30
parent dd96bb3aff
commit cf993bf06a
3 changed files with 123 additions and 126 deletions

View File

@ -46,68 +46,73 @@ export const createProduct = async (req, res) => {
/////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////
export const updateProduct = async (req, res) => { export const updateProduct = async (req, res) => {
try { try {
if (req.body?.variants) { // console.log("Product ID:", req.params.id);
const vars = req.body.variants || []; // Default to an empty array if req.body.variants is undefined or null // console.log("Files:", req.files);
const product = await Product.findByIdAndUpdate( // console.log("Body:", req.body);
req.params.id,
{ variants: vars },
{ new: true } // Return the updated document
);
// Send a JSON response back to the client const { removedImages } = req.body;
return res.status(201).json({ const files = req.files?.images || [];
message: "Product variant saved successfully",
variants: product?.variants || [], // Return the updated variants or an empty array if product is undefined // 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) { // Existing images
const getProduct = await Product.findById(req.params.id); let existingImages = product.image || [];
let newImagesLinks = [];
if (getProduct.image?.length > 0) { // Ensure files is always an array
// Deleting Images From Cloudinary const filesArray = Array.isArray(files) ? files : [files];
for (let i = 0; i < getProduct.image.length; i++) {
await cloudinary.v2.uploader.destroy(getProduct.image[i].public_id); // 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) { } catch (error) {
console.log(error); console.error(error); // Log error for debugging
res.status(500).json({ res.status(500).json({ message: "Server error!", error: error.message });
message: error.message ? error.message : "Something went wrong!",
});
} }
}; };
@ -117,38 +122,45 @@ export const getAllProductAdmin = async (req, res) => {
try { try {
const PAGE_SIZE = parseInt(req.query?.show || "10"); const PAGE_SIZE = parseInt(req.query?.show || "10");
const page = parseInt(req.query?.page - 1 || "0"); const page = parseInt(req.query?.page - 1 || "0");
let obj = {};
if (req.query?.name) // Create filter object based on query parameters
obj.name = { let filter = {};
$regex: new RegExp(req.query.name),
$options: "i", 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) if (req.query?.category) {
obj.featured_Product = req.query.FeatureProduct; filter.category = mongoose.Types.ObjectId(req.query.category); // Ensure category is an ObjectId
const total = await Product.countDocuments(obj); }
const product = await Product.find(obj) 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({ .populate({
path: "category addedBy master_GST variants.gst_Id", path: "category addedBy GST",
select: "name categoryName tax", select: "categoryName name tax",
}) })
.limit(PAGE_SIZE) .limit(PAGE_SIZE)
.skip(PAGE_SIZE * page) .skip(PAGE_SIZE * page)
// .sort("name")
.sort({ .sort({
featured_Product: -1, featured_Product: -1,
createdAt: -1, createdAt: -1,
}) })
.exec(); .exec();
if (product) { return res.status(200).json({
return res.status(200).json({ success: true,
success: true, total_data: total,
total_data: total, total_pages: Math.ceil(total / PAGE_SIZE),
total_pages: Math.ceil(total / PAGE_SIZE), products, // Changed from `product` to `products` to match the response variable
product, });
});
}
} catch (error) { } catch (error) {
res.status(500).json({ res.status(500).json({
success: false, success: false,
@ -175,7 +187,7 @@ export const getAllProductUser = async (req, res) => {
const total = await Product.countDocuments(obj); const total = await Product.countDocuments(obj);
const product = await Product.find(obj) const product = await Product.find(obj)
.populate({ .populate({
path: "category addedBy master_GST variants.gst_Id", path: "category addedBy GST",
select: "name categoryName tax", select: "name categoryName tax",
}) })
.limit(PAGE_SIZE) .limit(PAGE_SIZE)
@ -283,7 +295,7 @@ export const ChangeFeatueProductStatus = async (req, res) => {
export const getOneProduct = async (req, res) => { export const getOneProduct = async (req, res) => {
try { try {
const data = await Product.findById(req.params.id).populate({ 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", select: "name categoryName tax",
}); });
if (data) { if (data) {
@ -522,30 +534,45 @@ export const getAllProductsDevicesFirst = async (req, res) => {
// } // }
// }; // };
export const deleteImageFromCloudinary = async (req, res) => { export const deleteImageFromCloudinary = async (req, res) => {
const { public_id } = req.params; 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 { 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({ return res.status(400).json({
success: false, success: false,
msg: "Please Provide Product ID!", msg: "Image deletion failed!",
});
}
const response = await cloudinary.v2.uploader.destroy(public_id);
if (response) {
res.status(200).json({
success: true,
msg: "Product Deleted Successfully!!",
}); });
} }
} catch (error) { } catch (error) {
res.status(500).json({ console.error("Error deleting image:", error); // Log error for debugging
return res.status(500).json({
success: false, success: false,
msg: error.message ? error.message : "Something went wrong!", msg: error.message || "Something went wrong!",
}); });
} }
}; };
//delete one Product //delete one Product
export const deleteProduct = async (req, res) => { export const deleteProduct = async (req, res) => {
try { try {

View File

@ -15,11 +15,11 @@ const productSchema = new Schema(
ref: "CategoryModel", ref: "CategoryModel",
}, },
master_price: { price: {
type: Number, type: Number,
required: true, required: true,
}, },
master_GST: { GST: {
type: mongoose.Schema.ObjectId, type: mongoose.Schema.ObjectId,
ref: "Tax", ref: "Tax",
}, },
@ -36,19 +36,6 @@ const productSchema = new Schema(
type: Boolean, type: Boolean,
default: false, // Initially, products are not featured 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: [ image: [
{ {
public_id: { public_id: {

View File

@ -16,18 +16,10 @@ const router = express.Router();
import { isAuthenticatedUser, authorizeRoles } from "../../middlewares/auth.js"; import { isAuthenticatedUser, authorizeRoles } from "../../middlewares/auth.js";
router router
.route("/product/create/") .route("/product/create/")
.post( .post(isAuthenticatedUser, authorizeRoles("admin"), createProduct);
isAuthenticatedUser,
authorizeRoles("admin", "Employee"),
createProduct
);
router router
.route("/product/getAll/admin/") .route("/product/getAll/admin/")
.get( .get(isAuthenticatedUser, authorizeRoles("admin"), getAllProductAdmin);
isAuthenticatedUser,
authorizeRoles("admin", "Employee"),
getAllProductAdmin
);
//change Product status //change Product status
router.route("/product/admin/status/:id").patch(ChangeProductStatus); router.route("/product/admin/status/:id").patch(ChangeProductStatus);
@ -43,23 +35,14 @@ router
router.route("/product/getOne/:id").get(getOneProduct); router.route("/product/getOne/:id").get(getOneProduct);
router router
.route("/product/update/:id") .route("/product/update/:id")
.patch( .patch(isAuthenticatedUser, authorizeRoles("admin"), updateProduct);
isAuthenticatedUser,
authorizeRoles("admin", "Employee"),
updateProduct
);
router router
.route("/product/delete/:id") .route("/product/delete/:id")
.delete( .delete(isAuthenticatedUser, authorizeRoles("admin"), deleteProduct);
isAuthenticatedUser,
authorizeRoles("admin", "Employee"),
deleteProduct
);
router router
.route("/product/deleteImage/jatinMor/product/:public_id") .route("/product/deleteImage/:public_id")
.delete( .delete(
isAuthenticatedUser, isAuthenticatedUser, authorizeRoles("admin"),
authorizeRoles("admin", "Employee"),
deleteImageFromCloudinary deleteImageFromCloudinary
); );
router.route("/products/category/:categoryName").get(getProductsByCategory); router.route("/products/category/:categoryName").get(getProductsByCategory);