diff --git a/app.js b/app.js index 6c375f7..b76b028 100644 --- a/app.js +++ b/app.js @@ -24,7 +24,7 @@ app.use( import user from "./resources/user/userRoute.js"; import ProductRouter from "./resources/Products/ProductRoute.js"; //Businesses -import BusinessRoute from "./resources/Businesses/BusinessRoute.js"; +// import BusinessRoute from "./resources/Businesses/BusinessRoute.js"; import orderRoute from "./resources/Orders/orderRoute.js"; import DepartureRouter from "./resources/Departure/DepartureRoute.js"; @@ -40,31 +40,31 @@ import PurposeRoute from "./resources/setting/Purpose/Purpose_routes.js"; // category Route import categoryRoute from "./resources/Category/categoryRoutes.js"; import ContentRoute from "./resources/Content/ContentRoutes.js"; +import UserAddressRoute from "./resources/userAddress/useAddressRoute.js"; //business_Type -import Business_TypeRoute from "./resources/setting/Business_Type/Business_routes.js"; +// import Business_TypeRoute from "./resources/setting/Business_Type/Business_routes.js"; import ConfigRouter from "./resources/setting/Configration/Config_routes.js"; import TaxRouter from "./resources/Tax/tax_routes.js"; //specialties import SpecialtiesRouter from "./resources/Specialties/SpecialtiesRoute.js"; -//specialist -import SpecialistRouter from "./resources/Specialist/SpecialistRoute.js"; -//appointments -import AppointmentRouter from "./resources/Appointments/AppointmentRoute.js"; + //short urls -import ShortUrlRouter from "./resources/Businesses/Short_Urls/ShortUrlRoute.js"; +// import ShortUrlRouter from "./resources/Businesses/Short_Urls/ShortUrlRoute.js"; app.use("/api/v1/", user); //Product app.use("/api", ProductRouter); //businesses -app.use("/api/businesses", BusinessRoute); +// app.use("/api/businesses", BusinessRoute); // Category app.use("/api/category", categoryRoute); // Content app.use("/api/content", ContentRoute); +// User Address +app.use("/api/user-address", UserAddressRoute); //Order app.use("/api", orderRoute); //Departure @@ -82,18 +82,18 @@ app.use("/api/language", LanguageRoute); //Purpose app.use("/api/purpose", PurposeRoute); //Business_Type -app.use("/api/business", Business_TypeRoute); +// app.use("/api/business", Business_TypeRoute); //Tax app.use("/api/tax", TaxRouter); //config app.use("/api/config", ConfigRouter); //config specialty -app.use("/api/config/specialty", SpecialtiesRouter); +// app.use("/api/config/specialty", SpecialtiesRouter); //specialties -app.use("/api/specialist", SpecialistRouter); +// app.use("/api/specialist", SpecialistRouter); //appointments -app.use("/api/appointment", AppointmentRouter); +// app.use("/api/appointment", AppointmentRouter); //short urls -app.use("/api/shorturl", ShortUrlRouter); +// app.use("/api/shorturl", ShortUrlRouter); export default app; diff --git a/middlewares/auth.js b/middlewares/auth.js index 392aa6a..20df498 100644 --- a/middlewares/auth.js +++ b/middlewares/auth.js @@ -2,7 +2,7 @@ import User from "../resources/user/userModel.js"; import jwt from "jsonwebtoken"; import ErrorHander from "../Utils/errorhander.js"; import { Franchisee } from "../resources/Temple/FranchiseeModel.js"; -import { Business } from "../resources/Businesses/BusinessModel.js"; +// import { Business } from "../resources/Businesses/BusinessModel.js"; export const isAuthenticatedUser = async (req, res, next) => { try { @@ -74,40 +74,40 @@ export const isFranchiAuthenticated = async (req, res, next) => { // isBusinessAuthenticated -export const isBusinessAuthenticated = async (req, res, next) => { - try { - if (!req.headers.authorization) { - return res.status(400).json({ - success: false, - message: "Login to Access this resource", - }); - } - const getToken = req.headers; - //remove Bearer from token +// export const isBusinessAuthenticated = async (req, res, next) => { +// try { +// if (!req.headers.authorization) { +// return res.status(400).json({ +// success: false, +// message: "Login to Access this resource", +// }); +// } +// const getToken = req.headers; +// //remove Bearer from token - const fronttoken = getToken.authorization.slice(7); +// const fronttoken = getToken.authorization.slice(7); - const frontdecoded = jwt.verify(fronttoken, process.env.JWT_SECRET); +// const frontdecoded = jwt.verify(fronttoken, process.env.JWT_SECRET); - if (!frontdecoded) { - return res.status(400).json({ - success: false, - message: "incorrect token", - }); - } - // console.log(frontdecoded) - const fuser = await Business.findById(frontdecoded.id); +// if (!frontdecoded) { +// return res.status(400).json({ +// success: false, +// message: "incorrect token", +// }); +// } +// // console.log(frontdecoded) +// const fuser = await Business.findById(frontdecoded.id); - req.business = fuser; +// req.business = fuser; - next(); - } catch (error) { - return res.status(400).json({ - success: false, - message: error.message, - }); - } -}; +// next(); +// } catch (error) { +// return res.status(400).json({ +// success: false, +// message: error.message, +// }); +// } +// }; export const authorizeRoles = (...roles) => { //pass admin diff --git a/resources/Appointments/AppointmentController.js b/resources/Appointments/AppointmentController.js deleted file mode 100644 index 14a22e3..0000000 --- a/resources/Appointments/AppointmentController.js +++ /dev/null @@ -1,132 +0,0 @@ -import { Appointment } from "./AppointmentModel.js"; -import pkg from "mongoose"; -const { Types } = pkg; - -// create a new appointment -// POST /api/appointment/new -export const createAppointment = async (req, res, next) => { - try { - const doctorId = Types.ObjectId(req.body.doctorId); - const { - doctorName, - date, - time, - patientName, - patientPhone, - HealthCareProviderID, - } = req.body; - const appointment = await Appointment.create({ - doctorId, - doctorName, - date, - time, - patientName, - patientPhone, - HealthCareProviderID, - }); - res.status(201).json({ - success: true, - appointment, - }); - } catch (error) { - res.status(400).json({ - success: false, - message: error.message, - }); - } -}; - -// update a single appointment -// PUT /api/appointment/update/:id -export const updateAppointment = async (req, res, next) => { - try { - const { id } = req.params; - - const doctorId = Types.ObjectId(req.body.doctorId); - - const { doctorName, date, time, patientName, patientPhone } = req.body; - const update = { - doctorId, - doctorName, - date, - time, - patientName, - patientPhone, - }; - const options = { new: true }; - - const updatedAppointment = await Appointment.findByIdAndUpdate( - id, - update, - options - ); - - res.status(200).json({ - success: true, - updatedAppointment, - }); - } catch (error) { - res.status(400).json({ - success: false, - message: error.message, - }); - } -}; - -// get all appointments -// GET /api/appointment/all -export const getAllAppointments = async (req, res, next) => { - try { - const appointments = await Appointment.find(); - res.status(200).json({ - success: true, - appointments, - }); - } catch (error) { - res.status(400).json({ - success: false, - message: error.message, - }); - } -}; - -// get a single appointment -// GET /api/appointment/:id -export const getSingleAppointment = async (req, res, next) => { - try { - const appointment = await Appointment.findById(req.params.id); - if (!appointment) { - return res.status(404).json({ - success: false, - message: "Appointment not found", - }); - } - res.status(200).json({ - success: true, - appointment, - }); - } catch (error) { - res.status(400).json({ - success: false, - message: error.message, - }); - } -}; - -// delete a single appointment -// DELETE /api/appointment/delete/:id -export const deleteAppointment = async (req, res, next) => { - try { - const { id } = req.params; - const appointment = await Appointment.findByIdAndDelete(id); - res.status(200).json({ - success: true, - appointment, - }); - } catch (error) { - res.status(400).json({ - success: false, - message: error.message, - }); - } -}; diff --git a/resources/Appointments/AppointmentModel.js b/resources/Appointments/AppointmentModel.js deleted file mode 100644 index 202fd49..0000000 --- a/resources/Appointments/AppointmentModel.js +++ /dev/null @@ -1,88 +0,0 @@ -import { mongoose } from "mongoose"; - -import { Specialist } from "./../Specialist/SpecialistModel.js"; - -// { -// "doctorId": "642ab7610ea12ad09d27060e", -// "doctorName": "Dr Subbarao", -// "date": "2023-09-17T18:30:00.000Z", date in ISO format -// "time": "10:30 AM", -// "patientName": "huksda", -// "patientPhone": "0937824827" -// } - -const appointmentSchema = new mongoose.Schema({ - HealthCareProviderID: { - type: mongoose.Schema.ObjectId, - ref: "Businesses", - required: true, - }, - - doctorId: { - type: mongoose.Schema.Types.ObjectId, - ref: Specialist, - required: true, - }, - doctorName: { - type: String, - required: true, - }, - date: { - type: Date, - required: true, - }, - time: { - type: String, - required: true, - }, - patientName: { - type: String, - required: true, - }, - patientPhone: { - type: String, - required: true, - }, - appointmentNumber: { - type: String, - }, - createdAt: { - type: Date, - default: Date.now, - }, -}); - -// Add a pre-save hook to generate the appointment number for each date for each doctor -appointmentSchema.pre("save", async function (next) { - const appointment = this; - const doctorId = appointment.doctorId; - const date = appointment.date; - //get only month and date without time and timezone info - const dateOnly = new Date(date).toLocaleDateString("en-IN", { - timeZone: "Asia/Kolkata", - }); - - const appointments = await Appointment.find({ - doctorId: doctorId, - date: date, - }); - - const appointmentNumber = appointments.length + 1; - // append the appointment number to the date - appointment.appointmentNumber = dateOnly + "-" + appointmentNumber; - //appointment.appointmentNumber = appointmentNumber; - next(); -}); - -// appointmentSchema.pre("save", async function (next) { -// const appointment = this; -// const date = appointment.date; -// const appointments = await Appointment.find({ date: date }) -// const appointmentNumber = appointments.length + 1; -// appointment.appointmentNumber = appointmentNumber; -// next(); -// }); - -const Appointment = mongoose.model("Appointment", appointmentSchema); - -export { Appointment }; diff --git a/resources/Appointments/AppointmentRoute.js b/resources/Appointments/AppointmentRoute.js deleted file mode 100644 index 4277a93..0000000 --- a/resources/Appointments/AppointmentRoute.js +++ /dev/null @@ -1,23 +0,0 @@ -import { Router } from "express"; -import { - isAuthenticatedUser, - authorizeRoles, - isBusinessAuthenticated, -} from "../../middlewares/auth.js"; -import { - createAppointment, - deleteAppointment, - getAllAppointments, - getSingleAppointment, - updateAppointment, -} from "./AppointmentController.js"; - -const router = Router(); - -router.route("/new").post(isBusinessAuthenticated, createAppointment); -router.route("/getall").get(getAllAppointments); -router.route("/get/:id").get(getSingleAppointment); -router.route("/update/:id").patch(isBusinessAuthenticated, updateAppointment); -router.route("/delete/:id").delete(isBusinessAuthenticated, deleteAppointment); - -export default router; diff --git a/resources/Businesses/BusinessController.js b/resources/Businesses/BusinessController.js deleted file mode 100644 index 8f6c339..0000000 --- a/resources/Businesses/BusinessController.js +++ /dev/null @@ -1,535 +0,0 @@ -import sendEmail from "../../Utils/sendEmail.js"; -import cloudinary from "../../Utils/cloudinary.js"; -import { Business } from "./BusinessModel.js"; -import { ShortUrl } from "./Short_Urls/ShortUrlModel.js"; -import password from "secure-random-password"; -import bcrypt from "bcryptjs"; - -import fs from "fs"; -import catchAsyncErrors from "../../middlewares/catchAsyncErrors.js"; -import sendToken from "../../Utils/jwtToken.js"; -import ErrorHander from "../../Utils/errorhander.js"; - - - - -export const createBusiness = async (req, res) => { - try { - if (!req?.user) return res.status(400).json({ message: "please login !" }); - - const { - userType, - specialization, - country, - language, - state, - city, - address_Line_1, - address_Line_2, - pincode, - userName, - email, - contact_Number, - contact_Person_Name, - url, - short_url, - } = req.body; - //validation - switch (true) { - case !userType: - return res.status(500).send({ error: "Business is Required" }); - // case !language: - // return res.status(500).send({ error: "Language is Required" }); - case !address_Line_1: - return res.status(500).send({ error: "address_Line_1 is Required" }); - case !address_Line_2: - return res.status(500).send({ error: "address_Line_2 is Required" }); - case !state: - return res.status(500).send({ error: "state is Required" }); - case !pincode: - return res.status(500).send({ error: "pincode is Required" }); - case !city: - return res.status(500).send({ error: "city is Required" }); - case !country: - return res.status(500).send({ error: "country is Required" }); - case !email: - return res.status(500).send({ error: "email is Required" }); - case !contact_Number: - return res.status(500).send({ error: "contact_Number is Required" }); - case !short_url: - return res.status(500).send({ error: "short_url is Required" }); - } - - // create unique url from short url and unique slug and add it to req.body - const slug = await Business.find({ short_url: req.body?.short_url }); - const uniqueSlug = - slug.length > 0 - ? `${req.body?.short_url}-${slug.length}` - : req.body?.short_url; - req.body.short_url = uniqueSlug; - req.body.url = `${url}${uniqueSlug}`; - - let businesse = await Business.findOne({ email }); - if (businesse) { - return res.status(400).json({ - success: false, - message: " THis Email already exists Please try another Email!", - }); - } - const businessWithURL = await Business.findOne({ - short_url: req.body?.short_url, - }); - - if (req?.files?.image?.tempFilePath) { - const result = await cloudinary.v2.uploader.upload( - image_file?.tempFilePath, - { - folder: "Bolo/business_Image", - } - ); - 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; - // req.user.role === 'admin' ? req.body.verify = true : req.body.verify = false - - req.body.added_by = req.user._id; - const businesses = await Business.create(req.body); - const shortUrls = await ShortUrl.create({ - shortUrl: req.body?.short_url, - HealthCareProviderID: businesses._id, - }); - await sendEmail({ - to: `${req.body.email}`, // Change to your recipient - - from: `${process.env.SEND_EMAIL_FROM}`, // Change to your verified sender - - subject: `Bolo.Ai business Created`, - html: `your Business Url is:${req.body.url}

your login email is: ${req.body.email}
and password is: ${passwords}

Thank You

`, - }); - - res.status(201).send({ - success: true, - - message: `business added successfully and Email sent to ${req.body.email} successfully`, - - businesses, - }); - } catch (error) { - console.log(error); - res.status(500).send({ - success: false, - error, - message: error.message ? error.message : "Unable to create.", - }); - } -}; - - - - - - - - - - - - - - - - - -export const getAllBusiness = async (req, res) => { - try { - if (!req?.user) return res.status(400).json({ message: "please login !" }); - - const businesses = await Business.find().sort({ createdAt: -1 }); - if (businesses) { - res.status(201).send({ - success: true, - message: "Business Fetched Successfully", - businesses, - }); - } - } catch (error) { - // console.log(error); - res.status(500).send({ - success: false, - error, - message: error.message ? error.message : "Unable to fetch.", - }); - } -}; - -//6.Get User Detail -export const getBusinessDetails = catchAsyncErrors(async (req, res, next) => { - const user = await Business.findById(req.business.id); - - res.status(200).json({ - success: true, - user, - }); -}); - -export const getSingleBusiness = async (req, res) => { - try { - if (!req?.params.id) - return res.status(400).json({ message: "please Provide Business ID !" }); - - const businesses = await Business.findById(req.params.id); - if (businesses) { - res.status(201).send({ - success: true, - message: "Business Fetched Successfully", - businesses, - }); - } - } catch (error) { - // console.log(error); - res.status(500).send({ - success: false, - error, - message: error.message ? error.message : "Unable to fetch.", - }); - } -}; - -// export getSelfBusiness -export const getSelfBusiness = async (req, res) => { - try { - if (!req?.business) - return res.status(400).json({ message: "please login !" }); - - const businesses = await Business.findById(req.business._id); - - if (businesses) { - res.status(201).send({ - success: true, - message: "Business Fetched Successfully", - businesses, - }); - } - } catch (error) { - // console.log(error); - res.status(500).send({ - success: false, - error, - message: error.message ? error.message : "Unable to fetch.", - }); - } -}; - -export const updateBusiness = async (req, res) => { - try { - if (!req?.user) return res.status(400).json({ message: "please login !" }); - if (!req?.params.id) - return res.status(400).json({ message: "please Provide Business ID !" }); - const BusinessWithURL = await Business.findOne({ - short_url: req.body?.short_url, - }); - if ( - BusinessWithURL?._id && - BusinessWithURL?._id?.toString() !== req.params.id - ) { - if (req?.files?.image?.tempFilePath) - fs.unlinkSync(image_file?.tempFilePath); - return res - .status(400) - .json({ message: "Business URL is not available!" }); - } - const getBusiness = await Business.findById(req.params.id); - - if (req?.files?.image?.tempFilePath) { - if (getBusiness?.banner) { - const imageId = getBusiness?.banner?.public_id; - - await cloudinary.uploader.destroy(imageId); - } - const result = await cloudinary.v2.uploader.upload( - image_file?.tempFilePath, - { - folder: "Bolo/business_Image", - } - ); - 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(getBusiness.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); - - req.body.added_by = req.user._id; - const business = await Business.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 Business Updated`, - html: `your business Url is:${req.body.url}

your login email is: ${req.body.email}
and password is: ${passwords}

Thank You

`, - }); - return res.status(200).json({ - success: true, - data: business, - message: `Business Updated successfully and Email sent to ${req.body.email} successfully`, - }); - } catch (error) { - console.log(error); - res.status(500).send({ - success: false, - error, - message: error.message ? error.message : "Unable to Update.", - }); - } -}; - -//delete -export const deleteBusinessById = async (req, res) => { - try { - if (!req?.user) return res.status(400).json({ message: "please login !" }); - if (!req?.params.id) - return res.status(400).json({ message: "please Provide Business ID !" }); - - const business = await Business.findById(req.params.id); - if (!business) { - return res.status(400).json({ message: "business Not Found" }); - } - await business.remove(); - - res.status(200).json({ status: "OK", msg: "Deleted successfully" }); - } catch (err) { - return res - .status(500) - .json({ message: err.message ? err.message : "Unable to delete." }); - } -}; - -// update password for business owner with old password -export const updatePassword = catchAsyncErrors(async (req, res, next) => { - try { - const business = await Business.findById(req.business._id).select( - "+password" - ); - - const isPasswordMatched = await business.comparePassword( - req.body.oldPassword - ); - - if (!isPasswordMatched) { - //return next(new ErrorHander("old password is incorrect", 400)); - return res.status(400).send("Please enter correct old password"); - } - - if (req.body.newPassword !== req.body.confirmPassword) { - //return next(new ErrorHander("password does not match", 400)); - return res.status(400).send("password does not match"); - } - - business.password = req.body.newPassword; - - await business.save(); - - sendToken(business, 200, res); - } catch (error) { - console.log(error); - res.status(500).send(error.message); - } -}); - -// login for business owner -export const loginBusiness = async (req, res, next) => { - const { email, password } = req.body; - // checking if user has given password and email both - - try { - if (!email || !password) { - return res.status(400).json({ message: "Please Enter Email & Password" }); - } - - const business = await Business.findOne({ email }).select("+password"); - - if (!business) { - return res.status(400).json({ message: "Invalid Email or Password" }); - } - - const isPasswordMatched = await business.comparePassword(password); - - if (!isPasswordMatched) { - return res.status(400).json({ message: "Invalid Email or Password" }); - } - - sendToken(business, 200, res); - } catch (error) { - return res - .status(500) - .json({ message: "Something went wrong!", error: error?.message || "" }); - } -}; - -// forgot password for business -export const forgotPassword = async (req, res, next) => { - const business = await Business.findOne({ email: req.body.email }); - - if (!business) { - return res.status(404).json({ message: "business not found" }); - } - // Get ResetPassword Token - //const resetToken = business.getResetPasswordToken(); //call function - - //save database reset token - await business.save({ validateBeforeSave: false }); - - const passwords = password.randomPassword({ - length: 12, - characters: [ - { characters: password.upper, exactly: 1 }, - { characters: password.symbols, exactly: 1 }, - password.lower, - password.digits, - ], - }); - - business.password = passwords; - await business.save(); - // const message = `Your password reset token are :- \n\n ${resetPasswordUrl} \n\nyour new password is:${password}\n\nIf you have not requested this email then, please ignore it.`; - try { - await sendEmail({ - to: `${business.email}`, // Change to your recipient - - from: `${process.env.SEND_EMAIL_FROM}`, // Change to your verified sender - - subject: `Bolo Ai Password Recovery`, - html: `your new password is:
${passwords}

If you have not requested this email then, please ignore it.`, - }); - - res.status(200).json({ - success: true, - message: `Email sent to ${business.email} successfully`, - }); - } catch (error) { - business.resetPasswordToken = undefined; - business.resetPasswordExpire = undefined; - - await business.save({ validateBeforeSave: false }); - - return res - .status(500) - .json({ message: "Something went wrong!", error: error?.message || "" }); - } -}; - -/****************************************** */ - -const addBusiness = async (req, res) => { - const image_file = req?.files?.image; - try { - const { email } = req.body; - let business = await Business.findOne({ email }); - if (business) { - return res - .status(400) - .json({ success: false, message: "business already exists" }); - } - const BusinessWithURL = await Business.findOne({ - short_url: req.body?.short_url, - }); - if (BusinessWithURL?._id) { - if (req?.files?.image?.tempFilePath) - fs.unlinkSync(image_file?.tempFilePath); - return res - .status(400) - .json({ message: "Business URL is not available!" }); - } - if (image_file?.tempFilePath) { - const result = await cloudinary.v2.uploader.upload( - image_file?.tempFilePath, - { - folder: "ATP/Business_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; - req.user.role === "admin" - ? (req.body.verify = true) - : (req.body.verify = false); - const entity = await Business.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 Business Created`, - html: `your business Url is:${req.body.url}

your login email is: ${req.body.email}
and password is: ${passwords}

Thank You

`, - }); - return res.status(200).json({ - success: true, - data: entity, - message: `Business 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 addProductToBusiness = async (req, res) => { - try { - const Business = await Business.findByIdAndUpdate( - req.params.id, - { - $push: { products: req.body.product_id }, - }, - { new: true } - ); - res.status(200).json({ - status: "ok", - message: "Product added to Business successfully", - }); - } catch (err) { - return res.status(500).json({ message: "Unable to get ID." }); - } -}; diff --git a/resources/Businesses/BusinessModel.js b/resources/Businesses/BusinessModel.js deleted file mode 100644 index d561210..0000000 --- a/resources/Businesses/BusinessModel.js +++ /dev/null @@ -1,99 +0,0 @@ -import mongoose from "mongoose"; -import validator from "validator"; -import bcrypt from "bcryptjs"; -import jwt from "jsonwebtoken"; -import crypto from "crypto"; -import { ShortUrl } from "./Short_Urls/ShortUrlModel.js"; -import { Appointment } from "../Appointments/AppointmentModel.js"; -import { Specialist } from "../Specialist/SpecialistModel.js"; -const { Schema, model } = mongoose; - -const BusinessSchema = new Schema( - { - userType: { type: String, required: true }, - - specialization: { - type: String, - }, - - language: [{ type: Array, default: [] }], - //contacts - userName: { - type: String, - required:true - }, - email: { - type: String, - }, - password: { - type: String, - required: [true, "Please Enter Your Password"], - minLength: [6, "Password should be greater than 6 characters"], - select: false, //find not got passpord - }, - - contact_Number: { type: Number, required: true }, - contact_Person_Name: { type: String}, - - url: { type: String, default: "" }, - short_url: { type: String, default: "" }, - banner: { type: Object, default: { url: "", public_id: "" } }, - /// - //address - address_Line_1: { type: String, required: true }, - address_Line_2: { type: String, required: true }, - country: { type: String, required: true, default: "" }, - state: { type: String, required: true, default: "" }, - city: { type: String, required: true }, - - pincode: { type: Number, required: true }, - - added_by: { - type: mongoose.Schema.ObjectId, - ref: "User", - - }, - }, - { timestamps: true } -); - -BusinessSchema.pre("remove", async function (next) { - try { - // Delete all the short urls associated with the healthcare provider - await ShortUrl.deleteMany({ HealthCareProviderID: this._id }); - - // Delete all the appointments associated with the healthcare provider - await Appointment.deleteMany({ - HealthCareProviderID: this._id, - }); - - // Delete all the specialist associated with the healthcare provider - await Specialist.deleteMany({ - HealthCareProviderID: this._id, - }); - next(); - } catch (error) { - next(error); - } -}); - -BusinessSchema.pre("save", async function (next) { - if (!this.isModified("password")) { - next(); - } - - this.password = await bcrypt.hash(this.password, 12); -}); - -// JWT TOKEN -BusinessSchema.methods.getJWTToken = function () { - return jwt.sign({ id: this._id }, process.env.JWT_SECRET); -}; - -// Compare Password - -BusinessSchema.methods.comparePassword = async function (password) { - return await bcrypt.compare(password, this.password); -}; - -export const Business = model("Business", BusinessSchema); diff --git a/resources/Businesses/BusinessRoute.js b/resources/Businesses/BusinessRoute.js deleted file mode 100644 index 6350f16..0000000 --- a/resources/Businesses/BusinessRoute.js +++ /dev/null @@ -1,45 +0,0 @@ -import { Router } from "express"; -import { - authorizeRoles, - isAuthenticatedUser, - isBusinessAuthenticated, -} from "../../middlewares/auth.js"; -import { - createBusiness, - getAllBusiness, - getSingleBusiness, - updateBusiness, - deleteBusinessById, - updatePassword, - getSelfBusiness, - loginBusiness, - forgotPassword, - getBusinessDetails, -} from "./BusinessController.js"; - -const router = Router(); - -router.route("/details").get(isBusinessAuthenticated, getBusinessDetails); -router - .route("/add") - .post(isAuthenticatedUser, authorizeRoles("admin"), createBusiness); -router - .route("/update/:id") - .patch(isAuthenticatedUser, authorizeRoles("admin"), updateBusiness); -router - .route("/delete/:id") - .delete(isAuthenticatedUser, authorizeRoles("admin"), deleteBusinessById); -router.route("/get/:id").get(isAuthenticatedUser, getSingleBusiness); -router.route("/getall").get(isAuthenticatedUser, getAllBusiness); - -router.route("/getselfbusiness").get(isBusinessAuthenticated, getSelfBusiness); - -//auth routes -router.route("/login").post(loginBusiness); -router.route("/password/update").patch(isBusinessAuthenticated, updatePassword); - -router.route("/password/forgot").post(forgotPassword); - -//outer.route("/password/reset/:token").put(resetPassword); - -export default router; diff --git a/resources/Businesses/Short_Urls/ShortUrlController.js b/resources/Businesses/Short_Urls/ShortUrlController.js deleted file mode 100644 index a370fea..0000000 --- a/resources/Businesses/Short_Urls/ShortUrlController.js +++ /dev/null @@ -1,39 +0,0 @@ -import { ShortUrl } from "./ShortUrlModel.js"; - -// get all short urls -export const getAllShortUrls = async (req, res) => { - try { - const shortUrls = await ShortUrl.find(); - res.status(200).json({ - success: true, - shortUrls, - }); - } catch (error) { - res.status(400).json({ - success: false, - message: error.message, - }); - } -}; - -// get a single short url -export const getSingleShortUrl = async (req, res) => { - try { - const shortUrl = await ShortUrl.findById(req.params.id); - if (!shortUrl) { - return res.status(404).json({ - success: false, - message: "Short url not found", - }); - } - res.status(200).json({ - success: true, - shortUrl, - }); - } catch (error) { - res.status(400).json({ - success: false, - message: error.message, - }); - } -}; diff --git a/resources/Businesses/Short_Urls/ShortUrlModel.js b/resources/Businesses/Short_Urls/ShortUrlModel.js deleted file mode 100644 index ecc55cd..0000000 --- a/resources/Businesses/Short_Urls/ShortUrlModel.js +++ /dev/null @@ -1,16 +0,0 @@ -import mongoose from "mongoose"; -const { Schema, model } = mongoose; - -const ShortUrlSchema = new Schema( - { - shortUrl: { type: String, required: true }, - HealthCareProviderID: { - type: mongoose.Schema.ObjectId, - ref: "Businesses", - required: true, - }, - }, - { timestamps: true } -); - -export const ShortUrl = model("ShortUrl", ShortUrlSchema); diff --git a/resources/Businesses/Short_Urls/ShortUrlRoute.js b/resources/Businesses/Short_Urls/ShortUrlRoute.js deleted file mode 100644 index c402dde..0000000 --- a/resources/Businesses/Short_Urls/ShortUrlRoute.js +++ /dev/null @@ -1,9 +0,0 @@ -import { Router } from "express"; -import { getAllShortUrls, getSingleShortUrl } from "./ShortUrlController.js"; - -const router = Router(); - -router.route("/getall").get(getAllShortUrls); -router.route("/get/:id").get(getSingleShortUrl); - -export default router; diff --git a/resources/Category/CategoryModel.js b/resources/Category/CategoryModel.js index 1f1aac9..c05dae5 100644 --- a/resources/Category/CategoryModel.js +++ b/resources/Category/CategoryModel.js @@ -6,6 +6,7 @@ const CategorySchema = new mongoose.Schema( type: String, required: [true, "Name of category required "], }, + categoryImage: {}, addedBy: { type: mongoose.Schema.ObjectId, ref: "User", diff --git a/resources/Category/categoryController.js b/resources/Category/categoryController.js index 82d991e..0d01c64 100644 --- a/resources/Category/categoryController.js +++ b/resources/Category/categoryController.js @@ -1,22 +1,36 @@ import mongoose from "mongoose"; import { CategoryModel } from "./CategoryModel.js"; +import cloudinary from "../../Utils/cloudinary.js"; // Add new Category export const addCategory = async (req, res) => { const { categoryName } = req.body; + const { categoryImage } = req.files; + // console.log(categoryName, categoryImage); + if (!req?.user) return res.status(400).json({ message: "please login !" }); try { if (!mongoose.Types.ObjectId.isValid(req.user._id)) { return res.status(400).json({ message: "please login again " }); } - const category = await CategoryModel.create({ - categoryName, - addedBy: req.user._id, - }); - if (category) { - res - .status(201) - .json({ success: true, category, message: "category Added" }); + const result = await cloudinary.v2.uploader.upload( + categoryImage.tempFilePath, + { + folder: "jatinMor/category", + } + ); + + if (result) { + const category = await CategoryModel.create({ + categoryName, + categoryImage: result, + addedBy: req.user._id, + }); + if (category) { + return res + .status(201) + .json({ success: true, category, message: "category Added" }); + } } } catch (error) { res.status(500).json({ @@ -52,26 +66,51 @@ export const updateCategory = async (req, res) => { try { if (!req?.user) return res.status(400).json({ message: "please login !" }); const { _id } = req.params; - const { categoryName } = req.body; + const olderImage = req.body?.olderImage; + const categoryImag = req.files?.categoryImage; + if (!mongoose.Types.ObjectId.isValid(_id)) { return res.status(404).json({ error: "Can not find the document " }); } - // Use findOneAndUpdate to update the document - const update = await CategoryModel.findOneAndUpdate( - { _id: _id }, - { categoryName: categoryName }, // Provide the updated categoryName - { new: true } // To return the updated document - ); + // find the document with the id to delete the image from cloudinary + if (JSON.parse(olderImage).length == 0) { + const deletefromCloudinary = await CategoryModel.findOne({ _id: _id }); - if (!update) { - return res - .status(404) - .json({ message: "Can not update document, something went wrong" }); + const deleteresponse = await cloudinary.v2.uploader.destroy( + deletefromCloudinary.categoryImage.public_id + ); + if (deleteresponse) { + const result = await cloudinary.v2.uploader.upload( + categoryImag.tempFilePath, + { + folder: "jatinMor/category", + } + ); + const update = await CategoryModel.findOneAndUpdate( + { _id: _id }, + { categoryName: categoryName, categoryImage: result }, // Provide the updated categoryName + { new: true } // To return the updated document + ); + if (!update) { + return res + .status(404) + .json({ message: "Can not update document, something went wrong" }); + } else { + return res.status(200).json({ success: true, update }); + } + } + } else { + const update = await CategoryModel.findOneAndUpdate( + { _id: _id }, + { categoryName: categoryName, categoryImage: JSON.parse(olderImage) }, // Provide the updated categoryName + { new: true } // To return the updated document + ); + if (update) { + return res.status(200).json({ success: true, update }); + } } - - res.status(200).json({ success: true, update }); } catch (error) { res.status(500).json({ success: false, @@ -88,13 +127,22 @@ export const deleteCategory = async (req, res) => { return res.status(404).json({ error: "Can not find the document " }); } - const deleteCategory = await CategoryModel.findOneAndDelete({ _id: _id }); - if (!deleteCategory) { - return res.status(404).json({ - error: "Can not find the document with the provided id to delete ", - }); + const deletefromCloudinary = await CategoryModel.findOne({ _id: _id }); + + const deleteresponse = await cloudinary.v2.uploader.destroy( + deletefromCloudinary.categoryImage.public_id + ); + if (deleteresponse) { + const deleteCategory = await CategoryModel.findOneAndDelete({ _id: _id }); + if (!deleteCategory) { + return res.status(404).json({ + error: "Can not find the document with the provided id to delete ", + }); + } + res.status(200).json({ success: true, deleteCategory }); + } else { + return res.status(404).json({ error: "can not delete the category " }); } - res.status(200).json({ success: true, deleteCategory }); } catch (error) { res.status(500).json({ success: false, diff --git a/resources/Specialist/SpecialistController.js b/resources/Specialist/SpecialistController.js deleted file mode 100644 index 3652209..0000000 --- a/resources/Specialist/SpecialistController.js +++ /dev/null @@ -1,101 +0,0 @@ -import catchAsyncErrors from "../../middlewares/catchAsyncErrors.js"; -import { Specialist } from "./SpecialistModel.js"; - -// create a new specialist -// POST /api/specialist -export const createSpecialist = async (req, res, next) => { - try { - const specialist = await Specialist.create(req.body); - res.status(201).json({ - success: true, - specialist, - }); - } catch (error) { - res.status(400).json({ - success: false, - message: error.message, - }); - } -}; - -// get all specialists -// GET /api/specialist -export const getAllSpecialist = catchAsyncErrors(async (req, res, next) => { - const specialist = await Specialist.find(); - - res.status(200).json({ - success: true, - specialist, - }); -}); - -// get a single specialist -// GET /api/specialist/:id -export const getSingleSpecialist = catchAsyncErrors(async (req, res, next) => { - const specialist = await Specialist.findById(req.params.id); - - if (!specialist) { - return res.status(404).json({ - success: false, - message: "Specialist not found", - }); - } - - res.status(200).json({ - success: true, - specialist, - }); -}); - -// update a single specialist -// PUT /api/specialist/:id -export const updateSpecialist = async (req, res, next) => { - try { - const { id } = req.params; - const update = req.body; - const options = { new: true }; - - const updatedSpecialist = await Specialist.findByIdAndUpdate( - id, - update, - options - ); - - if (!updatedSpecialist) { - return res.status(404).json({ - success: false, - message: "Specialist not found", - }); - } - - res.status(200).json({ - success: true, - updatedSpecialist, - }); - } catch (error) { - res.status(500).json({ - success: false, - message: error.message, - }); - } -}; - -// delete a single specialist -// DELETE /api/specialist/:id -export const deleteSpecialist = catchAsyncErrors(async (req, res, next) => { - const specialist = await Specialist.findById(req.params.id); - - if (!specialist) { - return res.status(404).json({ - success: false, - message: "Specialist not found", - }); - } - - await specialist.remove(); - - res.status(200).json({ - success: true, - message: "Specialist deleted successfully", - }); -}); diff --git a/resources/Specialist/SpecialistModel.js b/resources/Specialist/SpecialistModel.js deleted file mode 100644 index d8e0fd5..0000000 --- a/resources/Specialist/SpecialistModel.js +++ /dev/null @@ -1,70 +0,0 @@ -import { mongoose } from "mongoose"; - -// specialistName: "", -// specialty: "", -// location: "", -// daysAvailable: daysAvailable, -// phone: "", - -const daysAvailableSchema = new mongoose.Schema({ - label: { - type: String, - required: true, - enum: [ - "Monday", - "Tuesday", - "Wednesday", - "Thursday", - "Friday", - "Saturday", - "Sunday", - ], - }, - available: { - type: Boolean, - required: true, - default: false, - }, - timeSlots: [ - { - startTime: String, - endTime: String, - }, - ], -}); - -const specialistSchema = new mongoose.Schema({ - HealthCareProviderID: { - type: mongoose.Schema.ObjectId, - ref: "Businesses", - required: true, - }, - - specialistName: { - type: String, - required: [true, "Please enter specialist name"], - trim: true, - maxlength: [100, "Specialist name cannot exceed 100 characters"], - }, - specialty: { - type: String, - required: [true, "Please enter specialty name"], - trim: true, - maxlength: [100, "Specialty name cannot exceed 100 characters"], - }, - perPatientTime: { - type: String, - required: [true, "Please enter per Patient Time"], - }, - - daysAvailable: { - type: [daysAvailableSchema], - }, - - createdAt: { - type: Date, - default: Date.now, - }, -}); - -export const Specialist = mongoose.model("Specialist", specialistSchema); diff --git a/resources/Specialist/SpecialistRoute.js b/resources/Specialist/SpecialistRoute.js deleted file mode 100644 index 27a32d9..0000000 --- a/resources/Specialist/SpecialistRoute.js +++ /dev/null @@ -1,23 +0,0 @@ -import { Router } from "express"; -import { - isAuthenticatedUser, - authorizeRoles, - isBusinessAuthenticated, -} from "../../middlewares/auth.js"; -import { - createSpecialist, - deleteSpecialist, - getAllSpecialist, - getSingleSpecialist, - updateSpecialist, -} from "./SpecialistController.js"; - -const router = Router(); - -router.route("/add").post(createSpecialist); -router.route("/getall").get(getAllSpecialist); -router.route("/get/:id").get(getSingleSpecialist); -router.route("/delete/:id").delete(deleteSpecialist); -router.route("/update/:id").patch(updateSpecialist); - -export default router; diff --git a/resources/Specialties/SpecialtiesRoute.js b/resources/Specialties/SpecialtiesRoute.js index 8aefb26..8d5b080 100644 --- a/resources/Specialties/SpecialtiesRoute.js +++ b/resources/Specialties/SpecialtiesRoute.js @@ -1,9 +1,5 @@ import { Router } from "express"; -import { - isAuthenticatedUser, - authorizeRoles, - isBusinessAuthenticated, -} from "../../middlewares/auth.js"; +import { isAuthenticatedUser, authorizeRoles } from "../../middlewares/auth.js"; import { createSpecialty, deleteSpecialty, diff --git a/resources/userAddress/useAddressRoute.js b/resources/userAddress/useAddressRoute.js new file mode 100644 index 0000000..177579b --- /dev/null +++ b/resources/userAddress/useAddressRoute.js @@ -0,0 +1,29 @@ +import express from "express"; +import { isAuthenticatedUser, authorizeRoles } from "../../middlewares/auth.js"; +import { + addUserAddress, + deleteUserAddress, + getOneAddress, + getUserAddress, + updateAddress, +} from "./userAddressController.js"; + +const router = express.Router(); + +router + .route("/addAddress") + .post(isAuthenticatedUser, authorizeRoles("admin"), addUserAddress); +router + .route("/getAddressess") + .get(isAuthenticatedUser, authorizeRoles("admin"), getUserAddress); +router + .route("/getOneAddress/:_id") + .get(isAuthenticatedUser, authorizeRoles("admin"), getOneAddress); +router + .route("/updateAddress/:_id") + .patch(isAuthenticatedUser, authorizeRoles("admin"), updateAddress); +router + .route("/deleteAddress/:_id") + .delete(isAuthenticatedUser, authorizeRoles("admin"), deleteUserAddress); + +export default router; diff --git a/resources/userAddress/userAddressController.js b/resources/userAddress/userAddressController.js new file mode 100644 index 0000000..713b104 --- /dev/null +++ b/resources/userAddress/userAddressController.js @@ -0,0 +1,128 @@ +import mongoose from "mongoose"; + +import { UserAddressModel } from "./userAddressModel.js"; + +// Add new Category +export const addUserAddress = async (req, res) => { + if (!req?.user) return res.status(400).json({ message: "please login !" }); + try { + // Get the user address data from the request body + const { userType, name, email, phno, addressess } = req.body; + + // Create a new UserAddressModel instance with the data + const userAddress = new UserAddressModel({ + userType, + name, + email, + phno, + addressess, + addedBy: req.user._id, + }); + + // Save the user address data to the database + await userAddress.save(); + + res.status(201).json({ + success: true, + userAddress, + message: "User address data saved successfully", + }); + } catch (error) { + res.status(500).json({ + success: false, + message: error.message ? error.message : "Something went wrong", + }); + } +}; + +export const getUserAddress = async (req, res) => { + try { + if (!req?.user) return res.status(400).json({ message: "please login !" }); + const userAddress = await UserAddressModel.find({ + addedBy: req.user._id, + }).sort({ + createdAt: -1, + }); + + if (userAddress) { + return res.status(200).json({ success: true, userAddress }); + } + } catch (error) { + res.status(500).json({ + success: false, + message: error.message ? error.message : "Something went wrong", + }); + } +}; + +// Get single user addess +export const getOneAddress = async (req, res) => { + try { + const address = await UserAddressModel.findById(req.params._id); + + if (address) { + return res.status(200).json({ + success: true, + address, + }); + } + } catch (error) { + res.status(500).json({ + success: false, + msg: error.message ? error.message : "Something went wrong!", + }); + } +}; + +export const updateAddress = async (req, res) => { + try { + if (!req?.user) return res.status(400).json({ message: "please login !" }); + const { _id } = req.params; + + const { userType, name, email, phno, addressess } = req.body; + + if (!mongoose.Types.ObjectId.isValid(_id)) { + return res.status(404).json({ error: "Can not find the document " }); + } + + // Use findOneAndUpdate to update the document + const update = await UserAddressModel.findOneAndUpdate( + { _id: _id }, + { userType, name, email, phno, addressess }, // Provide the user address + { new: true } // To return the updated document + ); + + if (update) { + return res.status(200).json({ success: true, update }); + } + } catch (error) { + res.status(500).json({ + success: false, + message: error.message ? error.message : "Something went wrong", + }); + } +}; + +export const deleteUserAddress = async (req, res) => { + try { + if (!req?.user) return res.status(400).json({ message: "please login !" }); + const { _id } = req.params; + + if (!mongoose.Types.ObjectId.isValid(_id)) { + return res.status(404).json({ error: "Can not find the document " }); + } + + const deleteAddress = await UserAddressModel.findOneAndDelete({ _id: _id }); + if (!deleteAddress) { + return res.status(404).json({ + error: "Can not find the document with the provided id to delete ", + }); + } + res.status(200).json({ success: true, deleteAddress }); + } catch (error) { + res.status(500).json({ + success: false, + message: error.message ? error.message : "Something went wrong", + }); + } +}; diff --git a/resources/userAddress/userAddressModel.js b/resources/userAddress/userAddressModel.js new file mode 100644 index 0000000..d2472e4 --- /dev/null +++ b/resources/userAddress/userAddressModel.js @@ -0,0 +1,44 @@ +import mongoose from "mongoose"; + +const addressSchema = new mongoose.Schema({ + id: String, + addressLine1: String, + addressLine2: String, + country: String, + state: String, + city: String, + zipcode: String, +}); + +const userAddressSchema = new mongoose.Schema( + { + userType: { + type: String, + required: [true, "User type is required"], + }, + name: { + type: String, + required: [true, "Name is required"], + }, + email: { + type: String, + required: [true, "Email is required"], + }, + phno: { + type: String, + required: [true, "Phone number is required"], + }, + addressess: [addressSchema], // Define the schema for the array + addedBy: { + type: mongoose.Schema.Types.ObjectId, + ref: "User", + required: true, + }, + }, + { timestamps: true } +); + +export const UserAddressModel = mongoose.model( + "UserAddressModel", + userAddressSchema +);