Skip to content

Commit

Permalink
fixes buy medicines backend issue
Browse files Browse the repository at this point in the history
  • Loading branch information
imohit1o1 committed May 19, 2024
1 parent 8e0388f commit 613e16d
Show file tree
Hide file tree
Showing 9 changed files with 93 additions and 92 deletions.
8 changes: 4 additions & 4 deletions backend/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -29,17 +29,17 @@ app.use(express.urlencoded({ extended: true }));
import userRouter from "./src/routes/user.routes.js";
import contactUsRouter from "./src/routes/contactus.routes.js";
import appointmentRouter from "./src/routes/appointment.routes.js";
import buymeidcineRouter from "./src/routes/medicine.routes.js";
import medicineRouter from "./src/routes/medicine.routes.js";
import CartRouter from "./src/routes/UserCart.routes.js"
import PaymentRouter from "./src/routes/payment.routes.js"

// routes declaration
app.use("/api/v1/user", userRouter);
app.use("/api/v1/message", contactUsRouter);
app.use("/api/v1/appointment", appointmentRouter);
app.use("/api/v1/BuyMedicines", buymeidcineRouter);
app.use("/api/v1/medicines-cart",CartRouter)
app.use("/api/v1/payment",PaymentRouter)
app.use("/api/v1/medicines", medicineRouter);
app.use("/api/v1/medicines-cart", CartRouter)
app.use("/api/v1/payment", PaymentRouter)


// error middleware
Expand Down
10 changes: 4 additions & 6 deletions backend/src/controllers/UserCart.controller.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@ import { ApiError } from "../utilis/ApiError.js";
import asyncHandler from "../utilis/asyncHandler.js";
import { UserCart } from "../models/UserCart.model.js";

const AddToCart = asyncHandler(async (req, res) => {

export const addToCart = asyncHandler(async (req, res) => {
const { userId, medicineId, quantity, totalPrice, status } = req.body;

if (!userId || !medicineId || !quantity || !totalPrice) {
Expand All @@ -29,20 +29,18 @@ const AddToCart = asyncHandler(async (req, res) => {
json(new ApiResponse(201, cart, "Medicine Added to Cart Successfully!"));
});

const deleteFromCart = asyncHandler(async (req, res) => {
export const deleteFromCart = asyncHandler(async (req, res) => {
const cart = await UserCart.findByIdAndDelete(req.params.id);
if (!cart) {
throw new ApiError(404, "Medicine not found");
}
return res.json(new ApiResponse(200, {}, "Medicine Deleted from Cart Successfully!"));
});

const getUserCart = asyncHandler(async (req, res) => {
export const getUserCart = asyncHandler(async (req, res) => {
const cart = await UserCart.find({ userId: req.params.userId });
if (!cart) {
throw new ApiError(404, "Cart not found");
}
return res.json(new ApiResponse(200, cart, "Cart Fetched Successfully!"));
});

export { AddToCart, deleteFromCart, getUserCart };
4 changes: 2 additions & 2 deletions backend/src/controllers/doctor.controller.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,8 @@ export const addNewDoctor = asyncHandler(async (req, res, next) => {
if (!firstName || !lastName || !email || !phone || !password || !address || !gender || !department || !specializations || !qualifications || !experience || !availabelSlots || !languagesKnown || !appointmentCharges) {
throw new ApiError(400, "Please Fill Full Form!");
}

// check if the admin already exists
console.log(req.body);
// check if the doctor already exists
let existedDoctor = await Doctor.findOne({ email });
if (existedDoctor) {
throw new ApiError(400, `${existedDoctor.role} with this Email already Registered`);
Expand Down
103 changes: 53 additions & 50 deletions backend/src/controllers/medicine.controller.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,70 +5,78 @@ import { ApiResponse } from "../utilis/ApiResponse.js";
import asyncHandler from "../utilis/asyncHandler.js";
import { uploadOnCloudinary } from "../utilis/cloudinary.js";

// Adding new medicine by admin only
const AddNewMedicine = asyncHandler(async (req, res) => {
const { name, price, description, category, expiryDate, manufacturer, stock, image, discount } = req.body;
//! Adding new medicine by admin only
export const addNewMedicine = asyncHandler(async (req, res) => {
const { name, price, description, category, manufacturer, expiryDate, stock, discount } = req.body;

console.log(req.body);

if (!name || !price || !description || !category || !expiryDate || !manufacturer || !stock || !discount|| !image) {
throw new ApiError(400, "Please Fill Full Form!");
if (!name || !price || !description || !category || !manufacturer || !expiryDate || !stock || !discount) {
throw new ApiError(400, "Please Fill All Medicine Details!");
}

let existedMedicine = await Medicine.findOne({ name });
if (existedMedicine) {
throw new ApiError(400, `Medicine with this Name already exists`);
}
const medicineImage = req.file?.path;
if (!medicineImage) {

// Medicine Image
const medicineImageLocalPath = req.file?.path;
if (!medicineImageLocalPath) {
throw new ApiError(400, "Medicine Image Path Not Found!");
}
const medicineImageCloudinary = await uploadOnCloudinary(medicineImage);
if (!medicineImageCloudinary) {
const medicineImage = await uploadOnCloudinary(medicineImageLocalPath);
if (!medicineImage) {
throw new ApiError(400, "Medicine Image is required")
}
const medicine = await Medicine.create({
const createdMedicine = await Medicine.create({
name,
price,
description,
category,
expiryDate,
manufacturer,
stock,
discount: (price - discount) / price * 100,
image: medicineImageCloudinary?.url|| "https://t4.ftcdn.net/jpg/02/81/42/77/360_F_281427785_gfahY8bX4VYCGo6jlfO8St38wS9cJQop.jpg",
discount,
image: medicineImage.url,
});

return res.
status(201).
json(new ApiResponse(201, medicine, "Medicine Added Successfully!"));
json(new ApiResponse(201, createdMedicine, "Medicine Added Successfully!"));
});

// delete medicine by admin only
const deleteMedicine = asyncHandler(async (req, res) => {

//! delete medicine by admin only
export const deleteMedicine = asyncHandler(async (req, res) => {
const medicine = await Medicine.findByIdAndDelete(req.params.id);
if (!medicine) {
throw new ApiError(404, "Medicine not found");
}
return res.json(new ApiResponse(200, {}, "Medicine Deleted Successfully!"));
});

// update medicine by admin only
const updateMedicine = asyncHandler(async (req, res) => {

//! update medicine by admin only
export const updateMedicine = asyncHandler(async (req, res) => {
// only 3 parameters can be updated by admin else create a new medicine
const { price, stock, discount } = req.body;
if (!price || !stock || !discount) {
throw new ApiError(400, "Please Fill Full Form!");

// Ensure at least one field is provided
if (price === undefined && stock === undefined && discount === undefined) {
throw new ApiError(400, "Please provide at least one field to update (price, stock, or discount)!");
}
const medicine = await Medicine.findByIdAndUpdate(req.params.id
, {
price,
stock,
discount: (price - discount) / price * 100,
},

// Build the update object dynamically
const updateFields = {};
if (price !== undefined) updateFields.price = price;
if (stock !== undefined) updateFields.stock = stock;
if (discount !== undefined) updateFields.discount = discount;

const medicine = await Medicine.findByIdAndUpdate(
req.params.id,
updateFields,
{
new: true,
// runValidators: true,
runValidators: true,
}
);
if (!medicine) {
Expand All @@ -77,8 +85,9 @@ const updateMedicine = asyncHandler(async (req, res) => {
return res.json(new ApiResponse(200, {}, "Medicine Updated Successfully!"));
});

// get all high discount medicines by admin
const getHighDiscountMedicines = asyncHandler(async (req, res) => {

//! get all high discount medicines by user
export const getHighDiscountMedicines = asyncHandler(async (req, res) => {
const page = parseInt(req.query.page, 10) || 1;
const limit = parseInt(req.query.limit, 10) || 12;
const skip = (page - 1) * limit;
Expand All @@ -87,11 +96,12 @@ const getHighDiscountMedicines = asyncHandler(async (req, res) => {
if (!medicines) {
throw new ApiError(404, "No medicines found");
}
return res.json(new ApiResponse(200, medicines , "Medicines fetched successfully!"));
return res.json(new ApiResponse(200, medicines, "Medicines fetched successfully!"));
});

// get category medicines by admin
const getCategoryMedicines = asyncHandler(async (req, res) => {

//! get category medicines by user
export const getCategoryMedicines = asyncHandler(async (req, res) => {
const page = parseInt(req.query.page, 10) || 1;
const limit = parseInt(req.query.limit, 10) || 10;
const skip = (page - 1) * limit;
Expand All @@ -106,20 +116,22 @@ const getCategoryMedicines = asyncHandler(async (req, res) => {
throw new ApiError(404, "No medicines found");
}

return res.json(new ApiResponse(200, medicines , "Medicines fetched successfully!"));
return res.json(new ApiResponse(200, medicines, "Medicines fetched successfully!"));
});

// get single medicine by user
const getSingleMedicine = asyncHandler(async (req, res) => {
console.log(req.params.id);

//! get single medicine by user
export const getSingleMedicine = asyncHandler(async (req, res) => {
const medicine = await Medicine.findById(req.params.id);
if (!medicine) {
throw new ApiError(404, "Medicine not found");
}
return res.json(new ApiResponse(200, medicine , "Medicine fetched successfully!"));
return res.json(new ApiResponse(200, medicine, "Medicine fetched successfully!"));
});
// Search medicine on the basis of name and category
const searchMedicine = asyncHandler(async (req, res) => {


//! Search medicine on the basis of name and category
export const searchMedicine = asyncHandler(async (req, res) => {
const search = validator.escape(req.query.search);
const medicines = await Medicine.find({
$or: [
Expand All @@ -130,14 +142,5 @@ const searchMedicine = asyncHandler(async (req, res) => {
if (!medicines) {
throw new ApiError(404, "No medicines found");
}
return res.json(new ApiResponse(200, medicines , "Medicines fetched successfully!"));
return res.json(new ApiResponse(200, medicines, "Medicines fetched successfully!"));
});
export {
AddNewMedicine,
deleteMedicine,
updateMedicine,
searchMedicine,
getCategoryMedicines,
getSingleMedicine,
getHighDiscountMedicines
};
4 changes: 2 additions & 2 deletions backend/src/controllers/payment.controller.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { instance } from "../../index.js";
// import { instance } from "../../index.js";
import crypto from "crypto";
import { Payment } from "../models/payment.model.js";

Expand Down Expand Up @@ -40,7 +40,7 @@ export const paymentVerification = async (req, res) => {
});

res.redirect(
`http://localhost:3000/paymentsuccess?reference=${razorpay_payment_id}`
`${process.env.FRONTEND_URL}/paymentsuccess?reference=${razorpay_payment_id}`
);
} else {
res.status(400).json({
Expand Down
11 changes: 3 additions & 8 deletions backend/src/models/medicine.model.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import mongoose ,{Schema, model }from "mongoose";
import mongoose, { Schema, model } from "mongoose";

const medicineSchema = new Schema({
name: {
Expand All @@ -18,17 +18,12 @@ const medicineSchema = new Schema({
category: {
type: String,
required: [true, "Category is required"],
enum: ["Tablet","Syrup", "Injection", "Drops","Cream", "Powder", "Lotion", "Inhaler"],
enum: ["Tablet", "Syrup", "Injection", "Drops", "Cream", "Powder", "Lotion", "Inhaler"],
},
manufacturer: {
type: String,
required: [true, "Manufacturer is required"],
},
prescriptionRequired: {
type: Boolean,
required: [true, "Prescription is required"],
default: true,
},
expiryDate: {
type: Date,
required: [true, "Expiry Date is required"],
Expand All @@ -38,7 +33,7 @@ const medicineSchema = new Schema({
required: [true, "Stock is required"],
},
image: {
type: String,
type: String, // cloudinary url
required: [true, "Image is required"],
},
discount: {
Expand Down
13 changes: 7 additions & 6 deletions backend/src/routes/UserCart.routes.js
Original file line number Diff line number Diff line change
@@ -1,14 +1,15 @@
import express from 'express';
import{
AddToCart,
import {
addToCart,
deleteFromCart,
getUserCart,
} from '../controllers/UserCart.controller.js';
} from '../controllers/userCart.controller.js';
import { isPatientAuthenticated } from "../middlewares/auth.middleware.js";

const router = express.Router();

router.route("/add-to-cart").post(AddToCart);
router.route("/delete-from-cart/:id").delete(deleteFromCart);
router.route("/user-cart/:userId").get(getUserCart);
router.post("/add-to-cart", addToCart);
router.delete("/delete-from-cart/:id", deleteFromCart);
router.get("/user-cart/:userId", isPatientAuthenticated, getUserCart);

export default router
27 changes: 16 additions & 11 deletions backend/src/routes/medicine.routes.js
Original file line number Diff line number Diff line change
@@ -1,26 +1,31 @@
import express from 'express';
import {
AddNewMedicine,
addNewMedicine,
updateMedicine,
deleteMedicine,
getHighDiscountMedicines,
getCategoryMedicines,
getSingleMedicine,
searchMedicine
} from '../controllers/medicine.controller.js';
import { isAdminAuthenticated } from "../middlewares/auth.middleware.js";
import { upload } from "../middlewares/multer.middleware.js";



const router = express.Router();

// routes of admin
router.route("test").get((req, res) => {
res.send("Medicine routes working");
});
router.route("/add-medicine").post(AddNewMedicine);
router.route("/update-medicine/:id").put(updateMedicine);
router.route("/delete-medicine/:id").delete(deleteMedicine);
router.route("/search-medicine").get(searchMedicine);
router.post("/addmedicine", isAdminAuthenticated, upload.single("image"), addNewMedicine);
router.delete("/delete-medicine/:id", isAdminAuthenticated, deleteMedicine);
router.put("/update-medicine/:id", isAdminAuthenticated, updateMedicine);

// routes of user
router.route("/get/:id").get(getSingleMedicine);
router.route("/shope-by-category/:category").get(getCategoryMedicines);
router.route("/discount").get(getHighDiscountMedicines)
router.get("/get/:id", getSingleMedicine);
router.get("/shop-by-category/:category", getCategoryMedicines);
router.get("/discount", getHighDiscountMedicines)

router.get("/search-medicine", searchMedicine);


export default router;
5 changes: 2 additions & 3 deletions backend/src/routes/payment.routes.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,7 @@ import {

const router = express.Router();

router.route("/checkout").post(checkout);

router.route("/paymentverification").post(paymentVerification);
router.post("/checkout", checkout);
router.post("/paymentverification", paymentVerification);

export default router;

1 comment on commit 613e16d

@vercel
Copy link

@vercel vercel bot commented on 613e16d May 19, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please sign in to comment.