franchisee edit

This commit is contained in:
pawan-dot 2023-02-09 18:04:15 +05:30
parent c9326a2151
commit 55fd1c72f7
7 changed files with 383 additions and 281 deletions

7
app.js
View File

@ -29,9 +29,10 @@ app.use("/api", ProductRouter);
//Order //Order
import orderRoute from './resources/Orders/orderRoute.js' import orderRoute from './resources/Orders/orderRoute.js'
app.use("/api", orderRoute); app.use("/api", orderRoute);
//Temple
import TempleRouter from "./resources/Temple/TempleRoute.js"; //Franchisee
app.use("/api/temple", TempleRouter); import FranchiseeRouter from "./resources/Franchisee/FranchiseeRoute.js";
app.use("/api/franchisee", FranchiseeRouter);
//state //state
import StateRouter from "./resources/setting/state/state_routes.js"; import StateRouter from "./resources/setting/state/state_routes.js";
app.use("/api/state", StateRouter); app.use("/api/state", StateRouter);

View File

@ -0,0 +1,69 @@
import mongoose from "mongoose";
import validator from "validator"
import bcrypt from "bcryptjs"
import jwt from "jsonwebtoken"
import crypto from "crypto"
const { Schema, model } = mongoose;
const FranchiseeSchema = new Schema(
{
name: {
type: String,
required: [true, "Please Enter Your Name"],
maxLength: [30, "Name cannot exceed 30 characters"],
minLength: [3, "Name should have more than 3 characters"],
}, email: {
type: String,
required: [true, "Please Enter Your Email"],
unique: true,
validate: [validator.isEmail, "Please Enter a valid Email"],
},
password: {
type: String,
required: [true, "Please Enter Your Password"],
minLength: [6, "Password should be greater than 6 characters"],
select: false,//find not got passpord
},
address_line_1: { type: String, required: true },
address_line_2: { type: String, required: true },
contact_Number: { type: Number, required: true },
contact_Person_Name: { type: String, required: true },
city: { type: mongoose.Schema.ObjectId, ref: "City" },
products: [
{
type: mongoose.Schema.ObjectId,
ref: "Product",
},
],
price_Lable: { type: String, default: "" },
url: { type: String, default: "" },
pin_Code: { type: Number, required: true },
short_url: { type: String, default: "" },
banner: { type: Object, default: { url: "", public_id: "" } },
},
{ timestamps: true }
);
FranchiseeSchema.pre("save", async function (next) {
if (!this.isModified("password")) {
next();
}
this.password = await bcrypt.hash(this.password, 12);
});
// JWT TOKEN
FranchiseeSchema.methods.getJWTToken = function () {
return jwt.sign({ id: this._id }, process.env.JWT_SECRET);
};
// Compare Password
FranchiseeSchema.methods.comparePassword = async function (password) {
return await bcrypt.compare(password, this.password);
};
export const Franchisee = model("Franchisee", FranchiseeSchema);

View File

@ -0,0 +1,30 @@
import { Router } from "express";
const router = Router();
import {
addFranchisee,
getAllFranchisees,
getFranchiseeById,
updateFranchisee,
deleteFranchiseeById,
getFranchiseeByIdWithoutPopulate,
getAllFranchiseesPopulated,
// getAllFranchiseesPopulatedWithOption,
addProductToFranchisee,
// addGradeToFranchisee,
getFranchiseeByIdPopulated,
} from "./Franchisee_controller.js";
import { authorizeRoles, isAuthenticatedUser } from "../../middlewares/auth.js";
router.get("/", getAllFranchisees);
router.get("/withpopulate", isAuthenticatedUser, getAllFranchiseesPopulated);
// router.get("/withpopulate/:option", getAllFranchiseesPopulatedWithOption);
router.get("/withoutpopulate/:id", isAuthenticatedUser, getFranchiseeByIdWithoutPopulate);
router.get("/:id", isAuthenticatedUser, getFranchiseeById);
router.get("/arrayspopulate/:id", getFranchiseeByIdPopulated);
router.post("/", isAuthenticatedUser, authorizeRoles("admin"), addFranchisee);
router.patch("/product/:id", isAuthenticatedUser, addProductToFranchisee);
// router.patch("/grade/:id", addGradeToFranchisee);
router.patch("/:id", isAuthenticatedUser, authorizeRoles("admin"), updateFranchisee);
router.delete("/:id", isAuthenticatedUser, authorizeRoles("admin"), deleteFranchiseeById);
export default router;

View File

@ -0,0 +1,280 @@
import { Franchisee } from "./FranchiseeModel.js";
import sendEmail from "../../Utils/sendEmail.js"
import cloudinary from "../../Utils/cloudinary.js";
import fs from "fs";
import bcrypt from "bcryptjs"
import password from 'secure-random-password'
import mongoose from "mongoose";
const addFranchisee = async (req, res) => {
const image_file = req?.files?.image;
try {
const { email } = req.body
let franchisee = await Franchisee.findOne({ email });
if (franchisee) {
return res
.status(400)
.json({ success: false, message: "franchisee already exists" });
}
const FranchiseeWithURL = await Franchisee.findOne({
short_url: req.body?.short_url,
});
if (FranchiseeWithURL?._id) {
if (req?.files?.image?.tempFilePath)
fs.unlinkSync(image_file?.tempFilePath);
return res.status(400).json({ message: "Franchisee URL is not available!" });
}
if (image_file?.tempFilePath) {
const result = await cloudinary.v2.uploader.upload(
image_file?.tempFilePath,
{
folder: "ATP/Franchisee_banners",
}
);
const image = { url: result?.secure_url, public_id: result?.public_id };
req.body.banner = image;
fs.unlinkSync(image_file?.tempFilePath);
}
//generate password
const passwords = password.randomPassword({
length: 10,
characters: [
{ characters: password.upper, exactly: 1 },
{ characters: password.symbols, exactly: 1 },
password.lower,
password.digits]
})
req.body.password = passwords;
const entity = await Franchisee.create(req.body);
await sendEmail({
to: `${req.body.email}`, // Change to your recipient
from: `${process.env.SEND_EMAIL_FROM}`, // Change to your verified sender
subject: `ATP Franchisee Created`,
html: `your franchisee Url is:${req.body.url}<br/><br/>your login email is: <strong> ${req.body.email}</strong><br/>and password is: <strong> ${passwords}</strong><br/><br/><h3>Thank You</h3>`
});
return res.status(200).json({
success: true,
data: entity,
message: `Franchisee added successfully and Email sent to ${req.body.email} successfully`,
});
} catch (err) {
// console.log(err)
fs.unlinkSync(image_file?.tempFilePath);
return res.status(500).json({ message: err.message ? err.message : "Unable to create." });
}
};
const addProductToFranchisee = async (req, res) => {
try {
const Franchisee = await Franchisee.findByIdAndUpdate(
req.params.id,
{
$push: { products: req.body.product_id },
},
{ new: true }
);
res
.status(200)
.json({ status: "ok", message: "Product added to Franchisee successfully" });
} catch (err) {
return res.status(500).json({ message: "Unable to get ID." });
}
};
const getFranchiseeById = async (req, res) => {
try {
const entity = await Franchisee.findById(req.params.id)
.populate("city")
.populate("products");
return res.status(200).json({ status: "OK", data: entity });
} catch (err) {
console.log(err);
return res.status(500).json({ message: "Unable to get menu items." });
}
};
const getFranchiseeByIdPopulated = async (req, res) => {
try {
const entity = await Franchisee.findById(req.params.id).populate({
path: "city",
select: "city_name state -_id",
populate: {
path: "state",
select: "state_name state_code -_id",
},
});
return res.status(200).json({ status: "OK", data: entity });
} catch (err) {
return res.status(500).json({ message: "Unable to get franchiee ." });
}
};
const getFranchiseeByIdWithoutPopulate = async (req, res) => {
try {
const entity = await Franchisee.findById(req.params.id);
return res.status(200).json({ status: "OK", data: entity });
} catch (err) {
console.log(err);
return res.status(500).json({ message: "Unable to get menu items." });
}
};
const getAllFranchisees = async (req, res) => {
try {
const entity = await Franchisee.find({}).populate("city");
return res.status(200).json({ status: "OK", data: entity });
} catch (err) {
return res.status(500).json({ message: "Unable to get menu items." });
}
};
const getAllFranchiseesPopulated = async (req, res) => {
try {
const entity = await Franchisee.find({})
.populate("city");
return res.status(200).json({ status: "OK", data: entity });
} catch (err) {
return res.status(500).json({ message: "Unable to get menu items." });
}
};
const updateFranchisee = async (req, res) => {
const image_file = req?.files?.image;
try {
const FranchiseeWithURL = await Franchisee.findOne({
short_url: req.body?.short_url,
});
if (
FranchiseeWithURL?._id &&
FranchiseeWithURL?._id?.toString() !== req.params.id
) {
if (req?.files?.image?.tempFilePath)
fs.unlinkSync(image_file?.tempFilePath);
return res.status(400).json({ message: "Franchisee URL is not available!" });
}
const getFranchisee = await Franchisee.findById(req.params.id);
if (image_file?.tempFilePath) {
if (getFranchisee?.banner) {
const imageId = getFranchisee?.banner?.public_id;
await cloudinary.uploader.destroy(imageId)
}
const result = await cloudinary.v2.uploader.upload(
image_file?.tempFilePath,
{
folder: "ATP/Franchisee_banners",
}
);
const image = { url: result?.secure_url, public_id: result?.public_id };
req.body.banner = image;
fs.unlinkSync(image_file?.tempFilePath);
await cloudinary.v2.uploader.destroy(getFranchisee.banner.public_id);
}
//generate password
const passwords = password.randomPassword({
length: 10,
characters: [
{ characters: password.upper, exactly: 1 },
{ characters: password.symbols, exactly: 1 },
password.lower,
password.digits]
})
req.body.password = await bcrypt.hash(passwords, 12)
const entity = await Franchisee.findByIdAndUpdate(req.params.id, req.body);
await sendEmail({
to: `${req.body.email}`, // Change to your recipient
from: `${process.env.SEND_EMAIL_FROM}`, // Change to your verified sender
subject: `ATP Franchisee Updated`,
html: `your franchisee Url is:${req.body.url}<br/><br/>your login email is: <strong> ${req.body.email}</strong><br/>and password is: <strong> ${passwords}</strong><br/><br/><h3>Thank You</h3>`
});
return res.status(200).json({
success: true,
data: entity,
message: `Franchisee Updated successfully and Email sent to ${req.body.email} successfully`,
});
} catch (err) {
console.log(err);
if (req?.files?.image?.tempFilePath)
fs.unlinkSync(image_file?.tempFilePath);
return res.status(500).json({ message: "Unable to create." });
}
};
const deleteFranchiseeById = async (req, res) => {
try {
const findFranchisee = await Franchisee.findById(req.params.id);
if (findFranchisee?.banner?.public_id)
await cloudinary.v2.uploader.destroy(findFranchisee?.banner?.public_id);
const franchisee = await Franchisee.findByIdAndDelete(req.params.id)
if (!franchisee) {
return res.status(400).json({ message: 'franchisee Not Found' });
}
await franchisee.remove();
res.status(200).json({ status: "OK", msg: 'Deteted successfully' });
} catch (err) {
return res.status(500).json({ message: err.message ? err.message : "Unable to delete." });
}
};
//website requests
const findFranchiseeByURL = async (req, res) => {
try {
const entity = await Franchisee.findOne({ short_url: req.params.url })
.populate({
path: "city",
select: "city_name state -_id",
populate: {
path: "state",
select: "state_name state_code -_id",
},
})
.select(
" -products -url -short_url -state_name -createdAt -updatedAt"
);
if (entity?._id) {
return res.status(200).json({ status: "OK", data: entity });
} else {
return res.status(404).json({ message: "Franchisee not found" });
}
} catch (err) {
console.log(err);
return res.status(500).json({ message: "Franchisee not found" });
}
};
export {
addFranchisee,
getAllFranchisees,
getAllFranchiseesPopulated,
getFranchiseeById,
getFranchiseeByIdPopulated,
updateFranchisee,
deleteFranchiseeById,
getFranchiseeByIdWithoutPopulate,
// getAllFranchiseesPopulatedWithOption,
findFranchiseeByURL,
// getFranchiseeProductsForChild,
addProductToFranchisee,
// addGradeToFranchisee,
// getFranchiseeGradesAndHousesByParent,
};

View File

@ -1,29 +0,0 @@
import mongoose from "mongoose";
const { Schema, model } = mongoose;
const TempleSchema = new Schema(
{
name: { type: String, required: true },
address_line_1: { type: String, required: true },
address_line_2: { type: String, required: true },
contact_Number: { type: Number, required: true },
contact_Person_Name: { type: String, required: true },
city: { type: mongoose.Schema.ObjectId, ref: "City" },
products: [
{
type: mongoose.Schema.ObjectId,
ref: "Product",
},
],
price_Lable: { type: String, default: "" },
url: { type: String, default: "" },
short_url: { type: String, default: "" },
banner: { type: Object, default: { url: "", public_id: "" } },
},
{ timestamps: true }
);
export const Temple = model("Temple", TempleSchema);

View File

@ -1,30 +0,0 @@
import { Router } from "express";
const router = Router();
import {
addTemple,
getAllTemples,
getTempleById,
updateTemple,
deleteTempleById,
getTempleByIdWithoutPopulate,
getAllTemplesPopulated,
// getAllTemplesPopulatedWithOption,
addProductToTemple,
// addGradeToTemple,
getTempleByIdPopulated,
} from "./Temple_controller.js";
import { authorizeRoles, isAuthenticatedUser } from "../../middlewares/auth.js";
router.get("/", getAllTemples);
router.get("/withpopulate", isAuthenticatedUser, getAllTemplesPopulated);
// router.get("/withpopulate/:option", getAllTemplesPopulatedWithOption);
router.get("/withoutpopulate/:id", isAuthenticatedUser, getTempleByIdWithoutPopulate);
router.get("/:id", isAuthenticatedUser, getTempleById);
router.get("/arrayspopulate/:id", getTempleByIdPopulated);
router.post("/", isAuthenticatedUser, authorizeRoles("admin"), addTemple);
router.patch("/product/:id", isAuthenticatedUser, addProductToTemple);
// router.patch("/grade/:id", addGradeToTemple);
router.patch("/:id", isAuthenticatedUser, authorizeRoles("admin"), updateTemple);
router.delete("/:id", isAuthenticatedUser, authorizeRoles("admin"), deleteTempleById);
export default router;

View File

@ -1,219 +0,0 @@
import { Temple } from "./TempleModel.js";
import cloudinary from "../../Utils/cloudinary.js";
import fs from "fs";
import mongoose from "mongoose";
const addTemple = async (req, res) => {
const image_file = req?.files?.image;
try {
const TempleWithURL = await Temple.findOne({
short_url: req.body?.short_url,
});
if (TempleWithURL?._id) {
if (req?.files?.image?.tempFilePath)
fs.unlinkSync(image_file?.tempFilePath);
return res.status(400).json({ message: "Temple URL is not available!" });
}
if (image_file?.tempFilePath) {
const result = await cloudinary.v2.uploader.upload(
image_file?.tempFilePath,
{
folder: "ATP/Temple_banners",
}
);
const image = { url: result?.secure_url, public_id: result?.public_id };
req.body.banner = image;
fs.unlinkSync(image_file?.tempFilePath);
}
const entity = await Temple.create(req.body);
res.status(200).json({ status: "OK", data: entity });
} catch (err) {
fs.unlinkSync(image_file?.tempFilePath);
return res.status(500).json({ message: "Unable to create." });
}
};
const addProductToTemple = async (req, res) => {
try {
const Temple = await Temple.findByIdAndUpdate(
req.params.id,
{
$push: { products: req.body.product_id },
},
{ new: true }
);
res
.status(200)
.json({ status: "ok", message: "Product added to Temple successfully" });
} catch (err) {
return res.status(500).json({ message: "Unable to get ID." });
}
};
const getTempleById = async (req, res) => {
try {
const entity = await Temple.findById(req.params.id)
.populate("city")
.populate("products");
return res.status(200).json({ status: "OK", data: entity });
} catch (err) {
console.log(err);
return res.status(500).json({ message: "Unable to get menu items." });
}
};
const getTempleByIdPopulated = async (req, res) => {
try {
const entity = await Temple.findById(req.params.id).populate({
path: "city",
select: "city_name state -_id",
populate: {
path: "state",
select: "state_name state_code -_id",
},
});
return res.status(200).json({ status: "OK", data: entity });
} catch (err) {
return res.status(500).json({ message: "Unable to get franchiee ." });
}
};
const getTempleByIdWithoutPopulate = async (req, res) => {
try {
const entity = await Temple.findById(req.params.id);
return res.status(200).json({ status: "OK", data: entity });
} catch (err) {
console.log(err);
return res.status(500).json({ message: "Unable to get menu items." });
}
};
const getAllTemples = async (req, res) => {
try {
const entity = await Temple.find({}).populate("city");
return res.status(200).json({ status: "OK", data: entity });
} catch (err) {
return res.status(500).json({ message: "Unable to get menu items." });
}
};
const getAllTemplesPopulated = async (req, res) => {
try {
const entity = await Temple.find({})
.populate("city");
return res.status(200).json({ status: "OK", data: entity });
} catch (err) {
return res.status(500).json({ message: "Unable to get menu items." });
}
};
const updateTemple = async (req, res) => {
const image_file = req?.files?.image;
try {
const TempleWithURL = await Temple.findOne({
short_url: req.body?.short_url,
});
if (
TempleWithURL?._id &&
TempleWithURL?._id?.toString() !== req.params.id
) {
if (req?.files?.image?.tempFilePath)
fs.unlinkSync(image_file?.tempFilePath);
return res.status(400).json({ message: "Temple URL is not available!" });
}
const getTemple = await Temple.findById(req.params.id);
if (image_file?.tempFilePath) {
if (getTemple?.banner) {
const imageId = getTemple?.banner?.public_id;
await cloudinary.uploader.destroy(imageId)
}
const result = await cloudinary.v2.uploader.upload(
image_file?.tempFilePath,
{
folder: "ATP/Temple_banners",
}
);
const image = { url: result?.secure_url, public_id: result?.public_id };
req.body.banner = image;
fs.unlinkSync(image_file?.tempFilePath);
await cloudinary.v2.uploader.destroy(getTemple.banner.public_id);
}
const entity = await Temple.findByIdAndUpdate(req.params.id, req.body);
res.status(200).json({ status: "OK", data: entity });
} catch (err) {
console.log(err);
if (req?.files?.image?.tempFilePath)
fs.unlinkSync(image_file?.tempFilePath);
return res.status(500).json({ message: "Unable to create." });
}
};
const deleteTempleById = async (req, res) => {
try {
const findTemple = await Temple.findById(req.params.id);
if (findTemple?.banner?.public_id)
await cloudinary.v2.uploader.destroy(findTemple?.banner?.public_id);
const temple = await Temple.findByIdAndDelete(req.params.id)
if (!temple) {
return res.status(400).json({ message: 'temple Not Found' });
}
await temple.remove();
res.status(200).json({ status: "OK", msg: 'Deteted successfully' });
} catch (err) {
return res.status(500).json({ message: err.message ? err.message : "Unable to delete." });
}
};
//website requests
const findTempleByURL = async (req, res) => {
try {
const entity = await Temple.findOne({ short_url: req.params.url })
.populate({
path: "city",
select: "city_name state -_id",
populate: {
path: "state",
select: "state_name state_code -_id",
},
})
.select(
" -products -url -short_url -state_name -createdAt -updatedAt"
);
if (entity?._id) {
return res.status(200).json({ status: "OK", data: entity });
} else {
return res.status(404).json({ message: "Temple not found" });
}
} catch (err) {
console.log(err);
return res.status(500).json({ message: "Temple not found" });
}
};
export {
addTemple,
getAllTemples,
getAllTemplesPopulated,
getTempleById,
getTempleByIdPopulated,
updateTemple,
deleteTempleById,
getTempleByIdWithoutPopulate,
// getAllTemplesPopulatedWithOption,
findTempleByURL,
// getTempleProductsForChild,
addProductToTemple,
// addGradeToTemple,
// getTempleGradesAndHousesByParent,
};