product manual completed

This commit is contained in:
Sibunnayak 2024-08-27 21:54:20 +05:30
parent c6cee73fdc
commit 4775d20253
56 changed files with 145213 additions and 91 deletions

View File

@ -0,0 +1,56 @@
import jwt from "jsonwebtoken";
import SalesCoOrdinator from "../resources/SalesCoOrdinators/SalesCoOrdinatorModel.js";
import TerritoryManager from "../resources/TerritoryManagers/TerritoryManagerModel.js";
export const isAuthenticated_SC_TM = async (req, res, next) => {
try {
if (!req.headers.authorization) {
return res.status(401).json({
success: false,
message: "Please login to access this resource",
});
}
const getToken = req.headers.authorization;
const token = getToken.slice(7);
const decoded = jwt.verify(token, process.env.JWT_SECRET);
if (!decoded) {
return res.status(400).json({
success: false,
message: "Incorrect token",
});
}
let user = await SalesCoOrdinator.findById(decoded.id);
if (user) {
req.user = user;
req.userType = "SalesCoOrdinator";
} else {
user = await TerritoryManager.findById(decoded.id);
if (user) {
req.user = user;
req.userType = "TerritoryManager";
}
}
if (!user) {
return res.status(401).json({
success: false,
message: "Unauthorized",
});
}
return next();
} catch (error) {
if (error.name === "TokenExpiredError") {
return res.status(401).json({ message: "Token has expired." });
} else if (error.name === "JsonWebTokenError") {
return res.status(401).json({ message: "Invalid token." });
} else {
return res.status(500).json({
message: "An internal error occurred while verifying the token.",
});
}
}
};

Binary file not shown.

Binary file not shown.

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

Binary file not shown.

File diff suppressed because it is too large Load Diff

Binary file not shown.

File diff suppressed because it is too large Load Diff

Binary file not shown.

File diff suppressed because it is too large Load Diff

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

Binary file not shown.

File diff suppressed because it is too large Load Diff

Binary file not shown.

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

Binary file not shown.

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

Binary file not shown.

Binary file not shown.

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

Binary file not shown.

View File

@ -1,31 +1,53 @@
import ProductManual from "./ProductManualModel.js"; import ProductManual from "./ProductManualModel.js";
import cloudinary from "../../Utils/cloudinary.js"; import cloudinary from "../../Utils/cloudinary.js";
import path from "path";
// Create a new product manual // Create a new product manual
export const createProductManual = async (req, res) => { export const createProductManual = async (req, res) => {
const { title } = req.body; const { title } = req.body;
const pdfFile = req.files ? req.files.pdfFile : null;
// Check if title is provided
if (!title) {
return res.status(400).json({
success: false,
message: "Title is required",
});
}
// Check if a file is provided
if (!pdfFile) {
return res.status(400).json({
success: false,
message: "File is required",
});
}
try { try {
let productManualDetails; let productManualDetails = null;
let filename = "";
// Upload the file to Cloudinary
if (pdfFile) {
filename = pdfFile.name;
// console.log(pdfFile);
const originalFilename = path.basename(pdfFile.name, path.extname(pdfFile.name));
// Check if a file is provided
if (req.files && req.files.product_manual) {
const pdfFile = req.files.product_manual;
const result = await cloudinary.v2.uploader.upload(pdfFile.tempFilePath, { const result = await cloudinary.v2.uploader.upload(pdfFile.tempFilePath, {
folder: "chemiNova/ProductManuals", folder: "chemiNova/ProductManuals",
resource_type: "raw", // For PDF or other non-image files public_id: originalFilename,
}); });
// console.log(result);
productManualDetails = { productManualDetails = {
public_id: result.public_id, public_id: result.public_id,
url: result.secure_url, url: result.secure_url,
filename: filename,
}; };
} }
// Create the product manual // Create the product manual
const productManual = await ProductManual.create({ const productManual = await ProductManual.create({
title, title,
product_manual: productManualDetails, product_manual: productManualDetails || {}, // Ensure product_manual is an empty object if no file is provided
}); });
res.status(201).json({ res.status(201).json({
@ -41,14 +63,34 @@ export const createProductManual = async (req, res) => {
}); });
} }
}; };
// Get all product manuals // Get all product manuals
export const getAllProductManuals = async (req, res) => { export const getAllProductManuals = async (req, res) => {
try { try {
const productManuals = await ProductManual.find(); const PAGE_SIZE = parseInt(req.query.show) || 10;
const page = parseInt(req.query.page) || 1;
const skip = (page - 1) * PAGE_SIZE;
let filter = {};
if (req.query.title) {
filter.title = {
$regex: new RegExp(req.query.title, "i"),
};
}
// Fetch total count of documents
const total = await ProductManual.countDocuments(filter);
// Fetch paginated data
const productManuals = await ProductManual.find(filter)
.limit(PAGE_SIZE)
.skip(skip)
.sort({ createdAt: -1 })
.exec();
// Send response
res.status(200).json({ res.status(200).json({
success: true, success: true,
productManuals, productManuals,
total,
}); });
} catch (error) { } catch (error) {
console.error("Error fetching product manuals:", error); console.error("Error fetching product manuals:", error);
@ -90,7 +132,6 @@ export const getSingleProductManual = async (req, res) => {
export const updateProductManual = async (req, res) => { export const updateProductManual = async (req, res) => {
const { id } = req.params; const { id } = req.params;
const { title } = req.body; const { title } = req.body;
try { try {
const productManual = await ProductManual.findById(id); const productManual = await ProductManual.findById(id);
@ -100,33 +141,41 @@ export const updateProductManual = async (req, res) => {
message: "Product manual not found", message: "Product manual not found",
}); });
} }
let filename = "";
// Check if a new file is provided // Check if a new file is provided
if (req.files && req.files.product_manual) { if (req.files && req.files.pdfFile) {
// Delete the old file from Cloudinary // Delete the old file from Cloudinary
if (productManual.product_manual.public_id) { if (productManual.product_manual.public_id) {
await cloudinary.v2.uploader.destroy(productManual.product_manual.public_id, { await cloudinary.v2.uploader.destroy(
resource_type: "raw", productManual.product_manual.public_id,
}); {
folder: "chemiNova/ProductManuals",
}
);
} }
// Upload the new file to Cloudinary // Upload the new file to Cloudinary
const pdfFile = req.files.product_manual; const pdfFile = req.files.pdfFile;
// console.log(pdfFile);
filename = pdfFile.name;
const originalFilename = path.basename(pdfFile.name, path.extname(pdfFile.name));
const result = await cloudinary.v2.uploader.upload(pdfFile.tempFilePath, { const result = await cloudinary.v2.uploader.upload(pdfFile.tempFilePath, {
folder: "chemiNova/ProductManuals", folder: "chemiNova/ProductManuals",
resource_type: "raw", public_id: originalFilename,
}); });
// console.log(result);
// Update the product manual details // Update the product manual details
productManual.product_manual = { productManual.product_manual = {
public_id: result.public_id, public_id: result.public_id,
url: result.secure_url, url: result.secure_url,
filename: filename,
}; };
} }
// Update the title // Update the title
productManual.title = title || productManual.title; productManual.title = title || productManual.title;
// console.log(productManual);
await productManual.save(); await productManual.save();
res.status(200).json({ res.status(200).json({
@ -159,9 +208,11 @@ export const deleteProductManual = async (req, res) => {
// Delete the file from Cloudinary // Delete the file from Cloudinary
if (productManual.product_manual.public_id) { if (productManual.product_manual.public_id) {
await cloudinary.v2.uploader.destroy(productManual.product_manual.public_id, { await cloudinary.v2.uploader.destroy(
resource_type: "raw", productManual.product_manual.public_id,
}); {
folder: "chemiNova/ProductManuals",
});
} }
// Delete the product manual from the database // Delete the product manual from the database
@ -178,4 +229,4 @@ export const deleteProductManual = async (req, res) => {
message: error.message || "Internal server error", message: error.message || "Internal server error",
}); });
} }
}; };

View File

@ -1,4 +1,4 @@
import mongoose from "mongoose"; import mongoose from 'mongoose';
const ProductManualSchema = new mongoose.Schema( const ProductManualSchema = new mongoose.Schema(
{ {
@ -9,17 +9,18 @@ const ProductManualSchema = new mongoose.Schema(
product_manual: { product_manual: {
public_id: { public_id: {
type: String, type: String,
required: true,
}, },
url: { url: {
type: String, type: String,
required: true, },
filename: {
type: String,
}, },
}, },
}, },
{ timestamps: true } { timestamps: true }
); );
const ProductManual = mongoose.model("ProductManual", ProductManualSchema); const ProductManual = mongoose.model('ProductManual', ProductManualSchema);
export default ProductManual; export default ProductManual;

View File

@ -6,12 +6,8 @@ import {
updateProductManual, updateProductManual,
deleteProductManual, deleteProductManual,
} from "./ProductManualController.js"; } from "./ProductManualController.js";
import { import { isAuthenticatedUser, authorizeRoles } from "../../middlewares/auth.js";
isAuthenticatedUser, import { isAuthenticated_SC_TM } from "../../middlewares/generalAuth.js";
authorizeRoles,
} from "../../middlewares/auth.js";
import { isAuthenticatedSalesCoOrdinator } from "../../middlewares/SalesCoOrdinatorAuth.js";
import { isAuthenticatedTerritoryManager } from "../../middlewares/TerritoryManagerAuth.js";
const router = express.Router(); const router = express.Router();
@ -19,64 +15,17 @@ const router = express.Router();
router router
.route("/create") .route("/create")
.post(isAuthenticatedUser, authorizeRoles("admin"), createProductManual); .post(isAuthenticatedUser, authorizeRoles("admin"), createProductManual);
router
.route("/")
.get(isAuthenticatedUser, authorizeRoles("admin"), getAllProductManuals);
// Route for getting all product manuals (accessible to Sales Coordinator, Territory Manager, and Admin) router.route("/getall").get(isAuthenticatedUser, getAllProductManuals);
router.route("/").get(
(req, res, next) => {
// Allow access if the user is a sales coordinator, territory manager, or admin
isAuthenticatedSalesCoOrdinator(req, res, (err) => {
if (err) {
isAuthenticatedTerritoryManager(req, res, (err) => {
if (err) {
isAuthenticatedUser(req, res, (err) => {
if (err || !["admin"].includes(req.user.role)) {
return res.status(403).json({
success: false,
message: "Access denied. Unauthorized role.",
});
}
next();
});
} else {
next();
}
});
} else {
next();
}
});
},
getAllProductManuals
);
// Route for getting a single product manual by ID (accessible to Sales Coordinator, Territory Manager, and Admin) router
router.route("/:id").get( .route("/:id")
(req, res, next) => { .get(isAuthenticatedUser, authorizeRoles("admin"), getSingleProductManual);
// Allow access if the user is a sales coordinator, territory manager, or admin
isAuthenticatedSalesCoOrdinator(req, res, (err) => { router.route("/getone/:id").get(isAuthenticatedUser, getSingleProductManual);
if (err) {
isAuthenticatedTerritoryManager(req, res, (err) => {
if (err) {
isAuthenticatedUser(req, res, (err) => {
if (err || !["admin"].includes(req.user.role)) {
return res.status(403).json({
success: false,
message: "Access denied. Unauthorized role.",
});
}
next();
});
} else {
next();
}
});
} else {
next();
}
});
},
getSingleProductManual
);
// Route to update a product manual by ID // Route to update a product manual by ID
router router
.route("/update/:id") .route("/update/:id")
@ -87,4 +36,4 @@ router
.route("/delete/:id") .route("/delete/:id")
.delete(isAuthenticatedUser, authorizeRoles("admin"), deleteProductManual); .delete(isAuthenticatedUser, authorizeRoles("admin"), deleteProductManual);
export default router; export default router;
// /api/productmanual // /api/productmanual/update