From 103f22d3e724cf554ca39a3aeb4660c1d1ae35d9 Mon Sep 17 00:00:00 2001 From: pawan-dot <71133473+pawan-dot@users.noreply.github.com> Date: Wed, 25 Jan 2023 23:21:26 +0530 Subject: [PATCH] temple --- app.js | 4 +- package.json | 2 +- resources/Products/ProductController.js | 380 ++++++++++-------------- resources/Products/ProductModel.js | 84 ++---- resources/Products/ProductRoute.js | 21 ++ 5 files changed, 207 insertions(+), 284 deletions(-) create mode 100644 resources/Products/ProductRoute.js diff --git a/app.js b/app.js index d232522..0111e9b 100644 --- a/app.js +++ b/app.js @@ -23,7 +23,9 @@ app.use(fileUpload({ //auth import user from "./resources/user/userRoute.js" app.use("/api/v1/", user); - +//Product +import ProductRouter from "./resources/Products/ProductRoute.js"; +app.use("/api", ProductRouter); //Temple import TempleRouter from "./resources/Temple/TempleRoute.js"; app.use("/api/temple", TempleRouter); diff --git a/package.json b/package.json index 9ba6e41..3b4157d 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "atp-backend", "version": "1.0.0", - "description": "", + "description": "atp", "main": "server.js", "type": "module", "scripts": { diff --git a/resources/Products/ProductController.js b/resources/Products/ProductController.js index 2c908be..2695ab2 100644 --- a/resources/Products/ProductController.js +++ b/resources/Products/ProductController.js @@ -1,255 +1,191 @@ -import { Product } from "./product_model.js"; -import { Temple } from "../Schools/school_model.js"; -import cloudinary from "../../util/cloudinary.js"; +import { Product } from "./ProductModel.js"; +import cloudinary from "../../Utils/cloudinary.js"; + + + + +export const createProduct = async (req, res) => { -const getProductById = async (req, res) => { try { - const product = await Product.findById(req.params.id) - .populate("variants") - .populate("category") - .populate("images"); + // console.log(req.body) + if (!req.files) { + return res.status(400).json({ - res.json({ status: "OK", data: product }); - } catch (e) { - console.log(e); - res.status(500).json({ message: "Something went wrong!" }); - } -}; + msg: " PLease Provide Product image", -const getProductByIdWithAllPopulated = async (req, res) => { - try { - const product = await Product.findById(req.params.id) - .populate({ - path: "variants", - populate: { - path: "tax", - }, - }) - .populate("category") - .populate("images"); + }); + } + const image_file = req.files.image; - res.json({ status: "OK", data: product }); - } catch (e) { - console.log(e); - res.status(500).json({ message: "Something went wrong!" }); - } -}; -const getAllProducts = async (req, res) => { - try { - const product = await Product.find() - .populate("category") - .populate("images"); - res.status(200).json({ data: product }); - } catch (error) { - res.status(500).json({ message: "Something went wrong!" }); - } -}; -const getAllProductsOfSchool = async (req, res) => { - try { - const temple = await Temple.findOne({ _id: req.params.school_id }).populate( + const myCloud = await cloudinary.v2.uploader.upload( + image_file?.tempFilePath, { - path: "products", - populate: { - path: "category images variants", - select: "name url size weight price tax", - }, + folder: "ATP/Product_Image", } ); - const products = await Product.find(); - res.status(200).json({ - status: "ok", - school_products: temple?.products || [], - products: products || [], - school_name: temple.name, - }); - } catch (error) { - res.status(500).json({ message: "Something went wrong!" }); - } -}; + // const { name, base, description, date, time } = req.body; -const getProductsAllVariants = async (req, res) => { - try { - const product = await Product.findById(req.params.id).populate({ - path: "variants", - populate: { - path: "tax", + const data = await Product.create({ + ...req.body, + image: { + public_id: myCloud.public_id, + url: myCloud.secure_url, }, - }); - res.json({ - status: "OK", - data: product?.variants || [], - product_name: product.name, - }); - } catch (error) { - console.log(error); - res.status(500).json({ message: "Something went wrong!" }); - } -}; -const getVariantById = async (req, res) => { - try { - const variant = await Variant.findById(req.params.id); - res.status(200).json({ status: "OK", data: variant }); - } catch (error) { - console.log(error); - res.status(500).json({ message: "Something went wrong!" }); - } -}; -const addProduct = async (req, res) => { - try { - let findProduct = ""; - let product = { _id: "" }; - if (req.body?.product_id) { - findProduct = await Product.findById(req.body.product_id); - } - if (findProduct === "") { - product = await Product.create(req.body); - } else { - product = await Product.findByIdAndUpdate(req.body.product_id, req.body); - } - if (req.body?.school_id) { - const temple = await Temple.findByIdAndUpdate( - req.body?.school_id, - { - $push: { products: product._id }, - }, - { new: true } - ); - } + }); res.status(201).json({ - message: "Product details added successfully!", - product_id: product._id, + success: true, + msg: " create Product Successfully!!", + }); } catch (error) { - res.status(500).json({ message: "Something went wrong" }); - } -}; - -const updateProduct = async (req, res) => { - try { - if (req.body?.variants) { - const vars = req.body.variants || []; - let variants_ids = []; - await Promise.all( - vars.map(async (v, i) => { - if (v._id !== "") { - const updatedVar = await Variant.findByIdAndUpdate(v._id, { - ...v, - product: req.params.id, - }); - variants_ids[i] = updatedVar._id; - } else { - delete v._id; - const addedVar = await Variant.create({ - ...v, - product: req.params.id, - }); - variants_ids[i] = addedVar._id; - } - }) - ); - variants_ids = variants_ids.filter((e) => e !== undefined); - req.body.variants = variants_ids; - } - - if (req.body?.delete_variants && req.body?.delete_variants[0]) { - await Variant.deleteMany({ _id: { $in: req.body?.delete_variants } }); - } - - const product = await Product.findByIdAndUpdate(req.params.id, req.body); - res.status(201).json({ message: "Product updated successfully" }); - } catch (error) { - console.log(error); - res.status(500).json({ message: "Something went wrong!" }); - } -}; - -const updateVariantById = async (req, res) => { - try { - const variant = await Variant.findByIdAndUpdate(req.params.id, req.body); - res - .status(200) - .json({ status: "OK", message: "Variant updated successfully!" }); - } catch (error) { - console.log(error); - res.status(500).json({ message: "Something went wrong!" }); - } -}; - -const deleteVariantById = async (req, res) => { - try { - const variant = await Variant.findByIdAndDelete(req.params.id); - const product = await Product.findByIdAndUpdate(req.params.product_id, { - $pull: { variants: variant._id }, + // console.log(error) + res.status(500).json({ + success: false, + msg: error.message }); - res - .status(200) - .json({ status: "OK", message: "Variant deleted successfully!" }); + } + +}; +//get All Product +export const getAllProduct = async (req, res) => { + + try { + const product = await Product.find().sort({ createdAt: -1 }); + if (product) { + return res.status(200).json({ + success: true, + product, + }); + } + + } catch (error) { - console.log(error); - res.status(500).json({ message: "Something went wrong!" }); + res.status(500).json({ + success: false, + msg: error.message ? error.message : "Something went wrong!" + }); } + +}; +//get One Product +export const getOneProduct = async (req, res) => { + + try { + const product = await Product.findById(req.params.id); + if (product) { + return res.status(200).json({ + success: true, + product, + }); + } + } catch (error) { + // console.log(error) + res.status(500).json({ + success: false, + msg: error.message ? error.message : "Something went wrong!" + }); + } + }; -const deleteProduct = async (req, res) => { +// 3.update Product +export const updateProduct = async (req, res) => { try { - const product = await Product.findById(req.params.id).populate("images"); - if (product?.images && product?.images.length !== 0) { - let ids = []; - await Promise.all( - product.images.map(async (e) => { - try { - await cloudinary.uploader.destroy(e.public_id); - } catch (error) { } - ids.push(e._id); - }) + const newProductData = { + name: req.body.name, + description: req.body.description, + base_Price: req.body.base_Price, + price_Level_2: req.body.price_Level_2, + price_Level_3: req.body.price_Level_3, + }; + + + if (req.files) { + const image_file = req.files.image; + const getProduct = await Product.findById(req.params.id); + if (getProduct) { + const imageId = getProduct.image.public_id; + //delete image from claudinary + await cloudinary.uploader.destroy(imageId) + } + + + const myCloud = await cloudinary.v2.uploader.upload( + image_file?.tempFilePath, + { + folder: "ATP/Product_Image", + } ); - await ProductImage.deleteMany({ _id: { $in: ids } }); + // console.log(myCloud) + newProductData.image = { + public_id: myCloud.public_id, + url: myCloud.secure_url, + }; } - if (product?.variants && product?.variants.length !== 0) { - await Variant.deleteMany({ _id: { $in: product.variants } }); - } - await Variant.deleteMany({ product: req.params.id }); - await Product.findByIdAndDelete(req.params.id); - res.status(200).json({ message: "Product deleted successfully!" }); - } catch (e) { - console.log(e); - res.status(500).json({ message: "Error deleting product" }); - } -}; + // console.log(newCategoryData) + //req.user.id, + const ModifyProduct = await Product.findByIdAndUpdate(req.params.id, newProductData, -const removeProductFromSchool = async (req, res) => { - try { - const temple = await Temple.findByIdAndUpdate( - req.params.school_id, - { - $pull: { products: req.params.product_id }, - }, { new: true } + // runValidators: true, + // useFindAndModify: false, ); - res - .status(200) - .json({ status: "ok", message: "Product removed successfully" }); + + res.status(200).json({ + success: true, + ModifyProduct + }); + } catch (error) { - console.log(error); - res.status(500).json({ message: "Something went wrong!" }); + // console.log(error) + res.status(500).json({ + success: false, + msg: error.message ? error.message : "Something went wrong!" + }); + } + }; -export { - getProductById, - getAllProducts, - getProductsAllVariants, - addProduct, - getVariantById, - updateProduct, - deleteProduct, - getProductByIdWithAllPopulated, - getAllProductsOfSchool, - removeProductFromSchool, - updateVariantById, - deleteVariantById, +//delete one Product +export const deleteProduct = async (req, res) => { + + try { + //delete image from cloudinary + const getProduct = await Product.findById(req.params.id); + // console.log(categ) + if (!getProduct) { + return res.status(404).json({ + success: false, + msg: "Product not Found!" + }); + + } + const imageId = getProduct.image.public_id; + await cloudinary.uploader.destroy(imageId) + + //-------------------------// + const product = await Product.findByIdAndDelete(req.params.id) + if (!product) { + return res.status(404).json({ message: 'Product Not Found' }); + } + await product.remove(); + res.status(200).json({ + success: true, + msg: "Product Deleted Successfully!!", + + }); + } catch (error) { + res.status(500).json({ + success: false, + msg: error.message ? error.message : "Something went wrong!" + }); + } + }; + + diff --git a/resources/Products/ProductModel.js b/resources/Products/ProductModel.js index 767b3e7..a5edeb8 100644 --- a/resources/Products/ProductModel.js +++ b/resources/Products/ProductModel.js @@ -1,6 +1,7 @@ import mongoose from "mongoose"; +const { Schema, model } = mongoose; -const productSchema = mongoose.Schema({ +const productSchema = new Schema({ name: { type: String, maxLength: [25, "name cannot exceed 25 characters"], @@ -12,77 +13,40 @@ const productSchema = mongoose.Schema({ maxLength: [100, "description cannot exceed 100 characters"], required: [true, "Please Enter product Description"], }, - price: { + base_Price: { type: Number, required: [true, "Please Enter product Price"], maxLength: [8, "Price cannot exceed 8 characters"], }, - price_leval_2: { + price_Level_2: { type: Number, + required: true, + maxLength: [8, "price leval2 cannot exceed 8 characters"], }, - price_leval_3: { + price_Level_3: { type: Number, + required: true, + maxLength: [8, "price leval3 cannot exceed 8 characters"], }, - ratings: { - type: Number, - default: 0, - }, - images: [ - { - public_id: { - type: String, - required: true, - }, - url: { - type: String, - required: true, - }, - }, - ], - category: { - type: mongoose.Schema.ObjectId, - ref: "Category", - }, - Stock: { - type: Number, - required: [true, "Please Enter product Stock"], - maxLength: [100, "Stock cannot exceed 4 characters"], - default: 1, - }, - numOfReviews: { - type: Number, - default: 0, - }, - reviews: [ - { - user: { - type: mongoose.Schema.ObjectId, - ref: "User", - required: true, - }, - name: { - type: String, - required: true, - }, - rating: { - type: Number, - required: true, - }, - comment: { - type: String, - required: true, - }, - }, - ], - user: { - type: mongoose.Schema.ObjectId, - ref: "User", - required: true, + image: + { + public_id: { + type: String, + required: true, + }, + url: { + type: String, + required: true, + }, }, + + + + }, { timestamps: true }); -export const Product = mongoose.model("Product", productSchema); +export const Product = model("Product", productSchema); diff --git a/resources/Products/ProductRoute.js b/resources/Products/ProductRoute.js new file mode 100644 index 0000000..6ec1aea --- /dev/null +++ b/resources/Products/ProductRoute.js @@ -0,0 +1,21 @@ +import express from "express"; +import { + createProduct, + getAllProduct, + updateProduct, + deleteProduct, + getOneProduct, + + +} from "./ProductController.js" +const router = express.Router(); +import { isAuthenticatedUser, authorizeRoles } from "../../middlewares/auth.js" +router.route("/product/create/").post(isAuthenticatedUser, authorizeRoles("admin"), createProduct) +router.route("/product/getAll/").get(getAllProduct) +router.route("/product/getOne/:id").get(getOneProduct) +router.route("/product/update/:id").put(isAuthenticatedUser, authorizeRoles("admin"), updateProduct); +router.route("/product/delete/:id").delete(isAuthenticatedUser, authorizeRoles("admin"), deleteProduct); + +export default router; + +