This commit is contained in:
pawan-dot 2023-01-25 23:21:26 +05:30
parent ef62f3a181
commit 103f22d3e7
5 changed files with 207 additions and 284 deletions

4
app.js
View File

@ -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);

View File

@ -1,7 +1,7 @@
{
"name": "atp-backend",
"version": "1.0.0",
"description": "",
"description": "atp",
"main": "server.js",
"type": "module",
"scripts": {

View File

@ -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 image_file = req.files.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");
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,
// console.log(error)
res.status(500).json({
success: false,
msg: error.message
});
variants_ids[i] = updatedVar._id;
} else {
delete v._id;
const addedVar = await Variant.create({
...v,
product: req.params.id,
}
};
//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,
});
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 },
res.status(500).json({
success: false,
msg: error.message ? error.message : "Something went wrong!"
});
res
.status(200)
.json({ status: "OK", message: "Variant deleted successfully!" });
}
};
//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({ message: "Something went wrong!" });
// 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);
})
);
await ProductImage.deleteMany({ _id: { $in: ids } });
}
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" });
}
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,
};
const removeProductFromSchool = async (req, res) => {
try {
const temple = await Temple.findByIdAndUpdate(
req.params.school_id,
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,
{
$pull: { products: req.params.product_id },
},
{ new: true }
);
res
.status(200)
.json({ status: "ok", message: "Product removed successfully" });
} catch (error) {
console.log(error);
res.status(500).json({ message: "Something went wrong!" });
folder: "ATP/Product_Image",
}
);
// console.log(myCloud)
newProductData.image = {
public_id: myCloud.public_id,
url: myCloud.secure_url,
};
}
// console.log(newCategoryData)
//req.user.id,
const ModifyProduct = await Product.findByIdAndUpdate(req.params.id, newProductData,
{ new: true }
// runValidators: true,
// useFindAndModify: false,
);
res.status(200).json({
success: true,
ModifyProduct
});
} catch (error) {
// 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!"
});
}
};

View File

@ -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,24 +13,25 @@ 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: [
image:
{
public_id: {
type: String,
@ -40,49 +42,11 @@ const productSchema = mongoose.Schema({
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,
},
}, { timestamps: true });
export const Product = mongoose.model("Product", productSchema);
export const Product = model("Product", productSchema);

View File

@ -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;