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 //auth
import user from "./resources/user/userRoute.js" import user from "./resources/user/userRoute.js"
app.use("/api/v1/", user); app.use("/api/v1/", user);
//Product
import ProductRouter from "./resources/Products/ProductRoute.js";
app.use("/api", ProductRouter);
//Temple //Temple
import TempleRouter from "./resources/Temple/TempleRoute.js"; import TempleRouter from "./resources/Temple/TempleRoute.js";
app.use("/api/temple", TempleRouter); app.use("/api/temple", TempleRouter);

View File

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

View File

@ -1,255 +1,191 @@
import { Product } from "./product_model.js"; import { Product } from "./ProductModel.js";
import { Temple } from "../Schools/school_model.js"; import cloudinary from "../../Utils/cloudinary.js";
import cloudinary from "../../util/cloudinary.js";
export const createProduct = async (req, res) => {
const getProductById = async (req, res) => {
try { try {
const product = await Product.findById(req.params.id) // console.log(req.body)
.populate("variants") if (!req.files) {
.populate("category") return res.status(400).json({
.populate("images");
res.json({ status: "OK", data: product }); msg: " PLease Provide Product image",
} catch (e) {
console.log(e);
res.status(500).json({ message: "Something went wrong!" });
}
};
const getProductByIdWithAllPopulated = async (req, res) => { });
try { }
const product = await Product.findById(req.params.id) const image_file = req.files.image;
.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) => { const myCloud = await cloudinary.v2.uploader.upload(
try { image_file?.tempFilePath,
const temple = await Temple.findOne({ _id: req.params.school_id }).populate(
{ {
path: "products", folder: "ATP/Product_Image",
populate: {
path: "category images variants",
select: "name url size weight price tax",
},
} }
); );
const products = await Product.find(); // const { name, base, description, date, time } = req.body;
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 getProductsAllVariants = async (req, res) => { const data = await Product.create({
try { ...req.body,
const product = await Product.findById(req.params.id).populate({ image: {
path: "variants", public_id: myCloud.public_id,
populate: { url: myCloud.secure_url,
path: "tax",
}, },
});
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({ res.status(201).json({
message: "Product details added successfully!", success: true,
product_id: product._id, msg: " create Product Successfully!!",
}); });
} catch (error) { } catch (error) {
res.status(500).json({ message: "Something went wrong" }); // console.log(error)
} res.status(500).json({
}; success: false,
msg: error.message
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 },
}); });
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) { } catch (error) {
console.log(error); res.status(500).json({
res.status(500).json({ message: "Something went wrong!" }); 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 { try {
const product = await Product.findById(req.params.id).populate("images"); const newProductData = {
if (product?.images && product?.images.length !== 0) { name: req.body.name,
let ids = []; description: req.body.description,
await Promise.all( base_Price: req.body.base_Price,
product.images.map(async (e) => { price_Level_2: req.body.price_Level_2,
try { price_Level_3: req.body.price_Level_3,
await cloudinary.uploader.destroy(e.public_id); };
} catch (error) { }
ids.push(e._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,
{
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) { // console.log(newCategoryData)
await Variant.deleteMany({ _id: { $in: product.variants } }); //req.user.id,
} const ModifyProduct = await Product.findByIdAndUpdate(req.params.id, newProductData,
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 removeProductFromSchool = async (req, res) => {
try {
const temple = await Temple.findByIdAndUpdate(
req.params.school_id,
{
$pull: { products: req.params.product_id },
},
{ new: true } { new: true }
// runValidators: true,
// useFindAndModify: false,
); );
res
.status(200) res.status(200).json({
.json({ status: "ok", message: "Product removed successfully" }); success: true,
ModifyProduct
});
} catch (error) { } catch (error) {
console.log(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!"
});
} }
}; };
export { //delete one Product
getProductById, export const deleteProduct = async (req, res) => {
getAllProducts,
getProductsAllVariants, try {
addProduct, //delete image from cloudinary
getVariantById, const getProduct = await Product.findById(req.params.id);
updateProduct, // console.log(categ)
deleteProduct, if (!getProduct) {
getProductByIdWithAllPopulated, return res.status(404).json({
getAllProductsOfSchool, success: false,
removeProductFromSchool, msg: "Product not Found!"
updateVariantById, });
deleteVariantById,
}
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"; import mongoose from "mongoose";
const { Schema, model } = mongoose;
const productSchema = mongoose.Schema({ const productSchema = new Schema({
name: { name: {
type: String, type: String,
maxLength: [25, "name cannot exceed 25 characters"], maxLength: [25, "name cannot exceed 25 characters"],
@ -12,77 +13,40 @@ const productSchema = mongoose.Schema({
maxLength: [100, "description cannot exceed 100 characters"], maxLength: [100, "description cannot exceed 100 characters"],
required: [true, "Please Enter product Description"], required: [true, "Please Enter product Description"],
}, },
price: { base_Price: {
type: Number, type: Number,
required: [true, "Please Enter product Price"], required: [true, "Please Enter product Price"],
maxLength: [8, "Price cannot exceed 8 characters"], maxLength: [8, "Price cannot exceed 8 characters"],
}, },
price_leval_2: { price_Level_2: {
type: Number, type: Number,
required: true,
maxLength: [8, "price leval2 cannot exceed 8 characters"], maxLength: [8, "price leval2 cannot exceed 8 characters"],
}, },
price_leval_3: { price_Level_3: {
type: Number, type: Number,
required: true,
maxLength: [8, "price leval3 cannot exceed 8 characters"], 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: { image:
type: mongoose.Schema.ObjectId, {
ref: "User", public_id: {
required: true, type: String,
required: true,
},
url: {
type: String,
required: true,
},
}, },
}, { timestamps: 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;