Skip to content

Commit

Permalink
you can add and delete data form orderdetails page
Browse files Browse the repository at this point in the history
  • Loading branch information
bbiruly committed Aug 6, 2024
1 parent 5f46520 commit cc616e1
Show file tree
Hide file tree
Showing 10 changed files with 418 additions and 78 deletions.
30 changes: 15 additions & 15 deletions backend/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,10 @@ import express from "express";
import dotenv from "dotenv";
import cookieParser from "cookie-parser";
import cors from "cors";
import http from "http"
import {Server} from "socket.io"
import http from "http";
import { Server } from "socket.io";
import { Vehicle } from "./model/location.model.js";


// /import all the routes
import authRoutes from "./routes/AuthRoutes.js";
import leadRoutes from "./routes/LeadRoutes.js";
Expand All @@ -24,7 +23,6 @@ import vehicleRoute from "./routes/VehicleLocationRoute.js";
//export express
export const app = express();


//configure dot env file
dotenv.config({
path: "./config/.env",
Expand All @@ -35,7 +33,7 @@ app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());

export const server = http.createServer(app)
export const server = http.createServer(app);

// Create Socket.IO server
// Create Socket.IO server
Expand All @@ -46,25 +44,27 @@ const io = new Server(server, {
},
});

io.on('connection', (socket) => {
console.log('New client connected');
io.on("connection", (socket) => {
console.log("New client connected");

socket.on('updateLocation', async (data) => {
socket.on("updateLocation", async (data) => {
const { id, latitude, longitude } = data;
console.log(data)
const vehicle = await Vehicle.findOneAndUpdate(
{ id },
{ latitude, longitude, updatedAt: new Date() },
{ $set: { latitude, longitude, updatedAt: new Date() } },
{ upsert: true, new: true }
);
io.emit('locationUpdate', vehicle);

io.emit("locationUpdate", vehicle);
});

socket.on("send-location", function (data){
io.emit("recieve-location",{id:socket.id, ...data} )
})
socket.on("send-location", function (data) {
io.emit("recieve-location", { id: socket.id, ...data });
});

socket.on('disconnect', () => {
console.log('Client disconnected');
socket.on("disconnect", () => {
console.log("Client disconnected");
});
});

Expand Down
96 changes: 88 additions & 8 deletions backend/controller/CustomerOrderController.js
Original file line number Diff line number Diff line change
Expand Up @@ -213,20 +213,35 @@ export const addItems = async (req, res) => {

// if flag id bedding then
if (flag === "beding") {
console.log(findOrder.bistarOrder);
// then push bistar order
findOrder.bistarOrder.push({
itemNameBistar: item.itemName,
itemCountForOrderBistar: item.quantity,
});
// Check if the item already exists
const itemIndex = findOrder.bistarOrder.findIndex(
(orderItem) => orderItem.itemNameBistar === item.itemName
);

if (itemIndex > -1) {
// Item exists, update the quantity
findOrder.bistarOrder[itemIndex].itemCountForOrderBistar =
item.quantity;
var message = "item updated";
} else {
// Item does not exist, push new item
findOrder.bistarOrder.push({
itemNameBistar: item.itemName,
itemCountForOrderBistar: item.quantity,
});
var message = "new item added";
}

const addedNew = await findOrder.save();

//retrun the response
// Return the response
res.status(200).json({
success: true,
message: "new item added",
message: message,
item: addedNew,
});
}

// if flag id bedding then
if (flag === "light") {
console.log(findOrder.lightOrder);
Expand Down Expand Up @@ -268,3 +283,68 @@ export const addItems = async (req, res) => {
}
} catch (error) {}
};

// delete controller for remove the item
export const removeItem = async (req, res) => {
const { id } = req.params;
console.log(id);
console.log(req.body);

const { flag, item } = req.body;

try {
// Find the order first
const findOrder = await CustomerOrder.findById(id);

// Validation
if (!findOrder) {
return res.status(404).json({
success: false,
message: "Order not found",
});
}

// If flag is "beding"
if (flag === "beding") {
// Check if the item exists
const itemIndex = findOrder.bistarOrder.findIndex(
(orderItem) => orderItem.itemNameBistar === item.itemNameBistar
);

console.log("working");
console.log(itemIndex);

if (itemIndex === -1) {
// Item not found
return res.status(404).json({
success: false,
message: "Item not found",
});
}

// Remove the item
findOrder.bistarOrder.splice(itemIndex, 1);

// Save the updated order
const updatedOrder = await findOrder.save();

// Return the response
res.status(200).json({
success: true,
message: "Item removed successfully",
item: updatedOrder.bistarOrder,
});
} else {
res.status(400).json({
success: false,
message: "Invalid flag value",
});
}
} catch (error) {
console.error(error);
res.status(500).json({
success: false,
message: "An error occurred",
});
}
};
5 changes: 4 additions & 1 deletion backend/routes/CustomerOrderRoutes.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import express from "express"
import { addItems, createOrder, deleteOrder, getAllOrderOfACustomer, getAllOrders, getOrderById, updateOrder, updateOrderStatus } from "../controller/CustomerOrderController.js"
import { addItems, createOrder, deleteOrder, getAllOrderOfACustomer, getAllOrders, getOrderById, removeItem, updateOrder, updateOrderStatus } from "../controller/CustomerOrderController.js"

const router = express.Router()

Expand Down Expand Up @@ -27,5 +27,8 @@ router.put("/update/status/:id", updateOrderStatus)
//to add items in order details page
router.post("/add-item/:id", addItems)

// remove the item
router.post("/remove-item/:id", removeItem)


export default router
42 changes: 37 additions & 5 deletions client/src/components/BedingDetails.jsx
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
import { Edit, Trash } from "lucide-react";
import React, { memo, useEffect, useState } from "react";
import React, { memo, useState } from "react";
import AddItems from "./common/AddItems";
import axios from "axios";
import config from "../config/config";
import toast, { Toaster } from "react-hot-toast";

const BedingDetails = ({ bedingDetails, isAddItemClicked, id, flag }) => {
const [itemToEdit, setItemToEdit] = useState(null);
const [isUpdateCliked, setIsUpdateCliked] = useState(isAddItemClicked);

// Handle on addItem
const handleAddItem = async (item) => {
Expand All @@ -15,6 +17,13 @@ const BedingDetails = ({ bedingDetails, isAddItemClicked, id, flag }) => {
{ item, flag }
);
console.log("Item added:", response);
const { success, message } = response.data;
if (success) {
toast.success(message);
setIsUpdateCliked(false);
// reload the screen
window.location.reload();
}
// Optionally update the local state or refresh the data from the backend
} catch (error) {
console.error("Error adding item:", error);
Expand All @@ -25,19 +34,42 @@ const BedingDetails = ({ bedingDetails, isAddItemClicked, id, flag }) => {
// Handle the edit button click
const handleEditClick = (item) => {
setItemToEdit(item);
setIsUpdateCliked((prev) => !prev);
};

// Handle the delete button click
const handleDeleteClick = (item) => {
console.log(item._id);
const handleDeleteClick = async(item) => {
try {
const response = await axios.post(
`${config.apiUrl}/order/remove-item/${id}`,
{ item, flag }
);
const { success, message } = response.data;
if (success) {
toast.success(message);
setIsUpdateCliked(false);
// reload the screen
window.location.reload();
}
// Optionally update the local state or refresh the data from the backend
} catch (error) {
console.error("Error removing item:", error);
// Handle error accordingly
}
};

return (
<div className="overflow-x-auto">
<Toaster />
{bedingDetails?.length > 0 ? (
<>
{isAddItemClicked && (
<AddItems onAddItem={handleAddItem} itemToEdit={itemToEdit} isAddItemClicked={isAddItemClicked} flag={flag} />
{(isAddItemClicked || isUpdateCliked) && (
<AddItems
onAddItem={handleAddItem}
itemToEdit={itemToEdit}
isAddItemClicked={isUpdateCliked}
flag={flag}
/>
)}

<table className="min-w-full divide-y divide-gray-200">
Expand Down
115 changes: 96 additions & 19 deletions client/src/components/LightDetails.jsx
Original file line number Diff line number Diff line change
@@ -1,28 +1,105 @@
import React, { memo } from "react";
import React, { memo, useState } from "react";
import AddItems from "./common/AddItems";
import toast, { Toaster } from "react-hot-toast";
import config from "../config/config";
import axios from "axios";
import { Edit, Trash } from "lucide-react";

const LightDetails = ({ lightDetails, id, flag, isAddItemClicked }) => {
const [itemToEdit, setItemToEdit] = useState(null);
const [isUpdateCliked, setIsUpdateCliked] = useState(isAddItemClicked);

const LightDetails = ({ lightDetails }) => {
// Handle on addItem
const handleAddItem = async (item) => {
try {
const response = await axios.post(
`${config.apiUrl}/order/add-item/${id}`,
{ item, flag }
);
console.log("Item added:", response);
const { success, message } = response.data;
if (success) {
toast.success(message);
setIsUpdateCliked(false);
// reload the screen
window.location.reload();
}
// Optionally update the local state or refresh the data from the backend
} catch (error) {
console.error("Error adding item:", error);
// Handle error accordingly
}
};

// Handle the edit button click
const handleEditClick = (item) => {
setItemToEdit(item);
setIsUpdateCliked((prev) => !prev);
};

// Handle the delete button click
const handleDeleteClick = async (item) => {
try {
const response = await axios.post(
`${config.apiUrl}/order/remove-item/${id}`,
{ item, flag }
);
const { success, message } = response.data;
if (success) {
toast.success(message);
setIsUpdateCliked(false);
// reload the screen
window.location.reload();
}
// Optionally update the local state or refresh the data from the backend
} catch (error) {
console.error("Error removing item:", error);
// Handle error accordingly
}
};
return (
<div className="overflow-x-auto">
<Toaster/>
{lightDetails?.length > 0 ? (
<table className="min-w-full divide-y divide-gray-200">
<thead className="bg-gray-50 text-gray-800">
<tr className="text-center">
<th className="py-2 px-4">S.No.</th>
<th className="py-2 px-4">Item Name</th>
<th className="py-2 px-4">Item Quantity</th>
</tr>
</thead>
<tbody className="bg-white divide-y divide-gray-200">
{lightDetails.map((item, index) => (
<tr key={index} className="text-center">
<td className="py-2 px-4">{index + 1}</td>
<td className="py-2 px-4 capitalize">{item.itemNameLight}</td>
<td className="py-2 px-4">{item.itemCountForOrderLight}</td>
<>
{(isAddItemClicked || isUpdateCliked) && (
<AddItems
onAddItem={handleAddItem}
itemToEdit={itemToEdit}
isAddItemClicked={isUpdateCliked}
flag={flag}
/>
)}
<table className="min-w-full divide-y divide-gray-200">
<thead className="bg-gray-50 text-gray-800">
<tr className="text-center">
<th className="py-2 px-4">S.No.</th>
<th className="py-2 px-4">Item Name</th>
<th className="py-2 px-4">Item Quantity</th>
</tr>
))}
</tbody>
</table>
</thead>
<tbody className="bg-white divide-y divide-gray-200">
{lightDetails.map((item, index) => (
<tr key={index} className="text-center">
<td className="py-2 px-4">{index + 1}</td>
<td className="py-2 px-4 capitalize">{item.itemNameLight}</td>

<td className="py-2 px-4">{item.itemCountForOrderLight}</td>
<td className="py-2 px-4 flex gap-4 justify-center">
<Edit
className="cursor-pointer"
onClick={() => handleEditClick(item)}
/>
<Trash
className="cursor-pointer"
onClick={() => handleDeleteClick(item)}
/>
</td>
</tr>
))}
</tbody>
</table>
</>
) : (
<div className="bg-gray-200 border border-gray-300 rounded-md p-4 text-center text-gray-600 font-bold">
There are no light details available.
Expand Down
Loading

0 comments on commit cc616e1

Please sign in to comment.