added employee section conflict resolved

This commit is contained in:
roshangarg 2024-05-03 10:36:46 +05:30
commit 3735e7167a
5 changed files with 362 additions and 250 deletions

View File

@ -58,7 +58,7 @@
"react": "18.0.0",
"react-bootstrap": "^2.7.0",
"react-chartjs-2": "^5.2.0",
"react-datepicker": "^4.8.0",
"react-datepicker": "^4.25.0",
"react-dom": "^18.0.0",
"react-draft-wysiwyg": "^1.15.0",
"react-hot-toast": "^2.4.0",

View File

@ -125,6 +125,8 @@ const Pos = () => {
const [cartItem, setCartItem] = useState([]);
const [individualSubtotals, setIndividualSubtotals] = useState([]);
const [total, setTotal] = useState(0);
// varient
const [selectedVariants, setSelectedVariants] = useState({});
const getAllProducts = async () => {
try {
@ -216,95 +218,91 @@ const Pos = () => {
},
};
const addToCart = (item) => {
// Check if the item is already in the cart with the same product ID and variant
const existingCartItemIndex = cartItem.findIndex(
(cartItem) =>
cartItem.product._id === item._id &&
cartItem.variant._id === selectedVariants[item._id]?._id
);
if (existingCartItemIndex !== -1) {
// Item with the same product ID and variant already exists in the cart, update its quantity
const newCart = [...cartItem];
const existingCartItem = newCart[existingCartItemIndex];
const addToCart = async (item) => {
try {
const selectedVariant = selectedVariants[item._id];
const price = selectedVariant ? selectedVariant.price : item.price;
if (selectedVariant) {
// Fetch tax details using the gstdetails function
const taxRate = selectedVariant?.gst_Id?.tax / 100;
const taxAmount = selectedVariant.price * taxRate;
const subtotal =
parseFloat(selectedVariant.price) + parseFloat(taxAmount);
existingCartItem.quantity += 1;
existingCartItem.subtotal +=
parseFloat(price) + parseFloat(item.gst_amount);
const existingCartItemIndex = cartItem.findIndex(
(cartItem) =>
cartItem.product._id === item._id &&
cartItem.variant._id === selectedVariant._id
);
setCartItem(newCart);
// Show a success message
swal("Item quantity updated in cart", "", "success");
} else {
// Item is not in the cart, add it
const selectedVariant = selectedVariants[item._id];
const price = selectedVariant ? selectedVariant.price : item.price;
const totalAmount = parseFloat(price) + parseFloat(item.gst_amount);
if (existingCartItemIndex !== -1) {
const newCart = [...cartItem];
const existingCartItem = newCart[existingCartItemIndex];
setCartItem([
...cartItem,
{
product: item,
quantity: 1,
variant: {
_id: selectedVariant?._id,
gst_Id: selectedVariant?.gst_Id,
price: selectedVariant?.price,
volume: selectedVariant?.volume,
weight: selectedVariant?.weight,
variant_Name: selectedVariant?.variant_Name,
},
subtotal: totalAmount,
},
]);
// Show a success message
swal("Item added to cart", "", "success");
existingCartItem.quantity += 1;
existingCartItem.subtotal =
parseFloat(existingCartItem.quantity) *
parseFloat(existingCartItem.subtotal);
setCartItem(newCart);
swal("Item quantity updated in cart", "", "success");
} else {
setCartItem([
...cartItem,
{
product: item,
quantity: 1,
variant: {
_id: selectedVariant._id,
gst_Id: selectedVariant.gst_Id,
price: selectedVariant.price,
volume: selectedVariant.volume,
weight: selectedVariant.weight,
variant_Name: selectedVariant.variant_Name,
},
subtotal: subtotal.toFixed(2), // Format the subtotal to two decimal places
},
]);
swal("Item added to cart", "", "success");
}
}
} catch (error) {
console.error("Error adding item to cart:", error);
swal("Error", "Failed to add item to cart", "error");
}
};
const handleIncrease = (index) => {
const newCart = [...cartItem];
const item = newCart[index];
const selectedVariant = selectedVariants[item.product._id];
const price = selectedVariant ? selectedVariant.price : item.product.price;
const taxRate = item.variant?.gst_Id?.tax / 100;
const taxAmount = item.variant?.price * taxRate;
const price = item.variant ? item.variant?.price : item.product.price;
const totalAmount =
(item.quantity + 1) * parseFloat(price) +
parseFloat(item.product.gst_amount);
(item.quantity + 1) * (parseFloat(price) + parseFloat(taxAmount));
newCart[index].quantity += 1;
newCart[index].subtotal = totalAmount;
setCartItem(newCart);
};
const handleDecrease = (index) => {
const newCart = [...cartItem];
const item = newCart[index];
const taxRate = item.variant?.gst_Id?.tax / 100;
const taxAmount = item.variant?.price * taxRate;
const price = item.variant ? item.variant?.price : item.product.price;
const totalAmount =
(item.quantity - 1) * (parseFloat(price) + parseFloat(taxAmount));
if (item.quantity > 1) {
const selectedVariant = selectedVariants[item.product._id];
const price = selectedVariant
? selectedVariant.price
: item.product.price;
const totalAmount =
(item.quantity - 1) * parseFloat(price) +
parseFloat(item.product.gst_amount);
newCart[index].quantity -= 1;
newCart[index].subtotal = totalAmount;
newCart[index].quantity -= 1;
newCart[index].subtotal = totalAmount;
setCartItem(newCart);
}
setCartItem(newCart);
};
// console.log(cartItem)
const removeCartItemHandler = (id, variant) => {
const newCart = cartItem.filter(
(item) => item?.product._id !== id || item.variant._id !== variant
(item) => item.product._id !== id || item.variant._id !== variant
);
setCartItem(newCart);
};
@ -313,14 +311,17 @@ const Pos = () => {
const calculateTotal = () => {
let subtotal = 0;
cartItem.forEach((item) => {
subtotal += item.subtotal;
subtotal += parseFloat(item.subtotal);
});
setTotal(subtotal);
// Round the subtotal to two decimal places
const roundedSubtotal = parseFloat(subtotal.toFixed(2));
setTotal(roundedSubtotal);
};
useEffect(() => {
calculateTotal();
}, [cartItem]);
// console.log(usersWithAddresses);
const [showChangeAddress, setShowChangeAddress] = useState(false);
const [selectedAddress, setSelectedAddress] = useState(
@ -338,71 +339,6 @@ const Pos = () => {
setShowChangeAddress(false);
};
// const checkoutCash = async () => {
// // console.log("Checkout button clicked");
// try {
// const config = {
// headers: {
// Authorization: `Bearer ${token}`,
// },
// };
// const cartData = cartItem.map((item) => ({
// product: item.product, // Entire product object
// quantity: item.quantity,
// variant: item.variant, // Entire variant object
// subtotal: item.subtotal,
// }));
// const order = {
// userr: currentUser._id,
// address: selectedAddress._id,
// cart: cartData,
// subtotal: total,
// orderType: "PointOfSale",
// };
// // Send POST request to backend API endpoint
// const response = await axios.post(
// "/api/order/pos-checkout/",
// order,
// config
// );
// toast.success("Order Placed! Your order has been successfully placed.");
// swal({
// title: "Order Placed!",
// text: `Order ID: ${
// response.data.order.orderID
// }\nDate and Time: ${new Date(
// response.data.order.createdAt
// ).toLocaleString("en-IN", {
// month: "short",
// day: "numeric",
// year: "numeric",
// hour: "2-digit",
// minute: "numeric",
// hour12: true,
// })}`,
// icon: "success",
// button: "OK",
// });
// // Clear cart items, reset current user and address, and reset radio button states
// setCartItem([]);
// setCurrentUser(null);
// setSelectedAddress(null);
// setSalesType("");
// setStoreDelivery("");
// setTotal(0);
// setCategoryValue("All");
// } catch (error) {
// // Handle errors
// console.error("Error placing order:", error);
// toast.error(
// "Error! There was an error placing your order. Please try again later."
// );
// }
// };
const checkoutCash = async () => {
const config = {
headers: {
@ -518,8 +454,8 @@ const Pos = () => {
order_id: order.id,
// callback_url:
// "http://localhost:5000/api/order/pos-paymentverification/",
callback_url:
"https://api.smellika.com/api/order/pos-paymentverification/",
callback_url:
"https://api.smellika.com/api/order/pos-paymentverification/",
prefill: {
name: currentUser.name,
@ -555,8 +491,6 @@ const Pos = () => {
}
}
};
// varient
const [selectedVariants, setSelectedVariants] = useState({});
// Function to set default variant for each product
const setDefaultVariants = () => {
@ -1162,7 +1096,12 @@ const Pos = () => {
color: "#121212",
}}
>
{row?.product.gst_amount}
{Number(
(row.variant?.price *
row.variant?.gst_Id?.tax) /
100
)?.toFixed(2)}
</TableCell>
<TableCell
@ -1173,7 +1112,7 @@ const Pos = () => {
color: "#121212",
}}
>
{row.subtotal}
{Number(row?.subtotal)?.toFixed(2)}
</TableCell>
</TableRow>
))
@ -1200,82 +1139,65 @@ const Pos = () => {
style={{ display: "flex", justifyContent: "space-between" }}
>
<div>
{/* {salesType === "" ? null : salesType ===
"inStoreDelivery" ? ( */}
<div style={{ display: "flex", flexDirection: "row" }}>
<Typography
style={{
fontWeight: "bold",
marginRight: "0.5rem",
}}
>
In-Store delivery:
</Typography>
<div style={{ marginRight: "0.5rem" }}>
<input
type="radio"
id="QRCode"
name="storedelivery"
value="QRCode"
checked={storedelivery === "QRCode"}
onChange={handlestoredeliveryChange}
className="mr-2"
/>
<label htmlFor="QRCode">QR Code</label>
</div>
<div style={{ marginRight: "5rem" }}>
<input
type="radio"
id="Cash"
name="storedelivery"
value="Cash"
checked={storedelivery === "Cash"}
onChange={handlestoredeliveryChange}
className="mr-2"
/>
<label htmlFor="Cash">Cash</label>
</div>
{storedelivery && (
<Button
variant="contained"
color="primary"
{currentUser ? (
<div style={{ display: "flex", flexDirection: "row" }}>
<Typography
style={{
fontWeight: "bold",
textTransform: "capitalize",
marginRight: "0.5rem",
}}
onClick={
storedelivery === "QRCode"
? checkoutQRCode
: checkoutCash
}
>
Checkout
</Button>
)}
</div>
{/* ) : (
<div>
{salesType === "shipToCustomer" && (
<Button variant="contained" color="primary">
Send Payment Link to Customer
</Button>
)}
{salesType !== "shipToCustomer" && (
In-Store delivery:
</Typography>
<div style={{ marginRight: "0.5rem" }}>
<input
type="radio"
id="QRCode"
name="storedelivery"
value="QRCode"
checked={storedelivery === "QRCode"}
onChange={handlestoredeliveryChange}
className="mr-2"
/>
<label htmlFor="QRCode">QR Code</label>
</div>
<div style={{ marginRight: "5rem" }}>
<input
type="radio"
id="Cash"
name="storedelivery"
value="Cash"
checked={storedelivery === "Cash"}
onChange={handlestoredeliveryChange}
className="mr-2"
/>
<label htmlFor="Cash">Cash</label>
</div>
{storedelivery && (
<Button
variant="contained"
color="primary"
style={{
fontWeight: "bold",
marginLeft: "5rem",
textTransform: "capitalize",
}}
onClick={checkout}
onClick={
storedelivery === "QRCode"
? checkoutQRCode
: checkoutCash
}
>
Checkout
</Button>
)}
</div>
)} */}
) : (
<div>
<h3>
Please Add user and their address to place the order
</h3>
</div>
)}
</div>
{/* Total Section */}

View File

@ -33,7 +33,7 @@ const Dashboard = () => {
//3rd
const [product, setProduct] = useState([]);
const getAllProduct = async () => {
let res = await axios.get(`/api/product/getAll/admin`, {
let res = await axios.get(`/api/product/getAll/user/`, {
headers: {
Authorization: `Bearer ${token}`,
},

View File

@ -4,13 +4,19 @@ import axios from "axios";
import { isAutheticated } from "src/auth";
import Button from "@material-ui/core/Button";
import { cilSearch } from "@coreui/icons";
import CIcon from "@coreui/icons-react";
import { TextField, FormControl, Select, MenuItem } from "@material-ui/core";
import { Typography } from "@material-ui/core";
import DatePicker from "react-datepicker";
import "react-datepicker/dist/react-datepicker.css";
function NewOrders() {
const token = isAutheticated();
const [loading, setLoading] = useState(true);
const [success, setSuccess] = useState(true);
const [newOrdersData, setNewOrdersData] = useState([]);
console.log(newOrdersData);
// console.log(newOrdersData);
const [currentPage, setCurrentPage] = useState(1);
const [itemPerPage, setItemPerPage] = useState(10);
@ -21,40 +27,31 @@ function NewOrders() {
setItemPerPage(e.target.value);
};
useEffect(() => {
function getNewOrder() {
axios
.get(`/api/order/getAll/new`, {
headers: {
"Access-Control-Allow-Origin": "*",
Authorization: `Bearer ${token}`,
},
})
.then((res) => {
const filteredOrders = res.data.order.filter(
(order) => order.orderType === "WebSite"
);
function getNewOrder() {
axios
.get(`/api/order/getAll/new`, {
headers: {
"Access-Control-Allow-Origin": "*",
Authorization: `Bearer ${token}`,
},
})
.then((res) => {
const filteredOrders = res.data.order.filter(
(order) => order.orderType === "WebSite"
);
setNewOrdersData(filteredOrders);
setLoading(false);
})
.catch((err) => {
console.log(err);
setLoading(false);
});
}
setNewOrdersData(filteredOrders);
setLoading(false);
})
.catch((err) => {
console.log(err);
setLoading(false);
});
}
useEffect(() => {
setLoading(true);
getNewOrder();
}, [success]);
useEffect(() => {
const loadData = () => {
const indexOfLastPost = currentPage * itemPerPage;
const indexOfFirstPost = indexOfLastPost - itemPerPage;
setShowData(newOrdersData.slice(indexOfFirstPost, indexOfLastPost));
};
loadData();
}, [currentPage, itemPerPage, newOrdersData]);
}, [token]);
const handleDelete = (id) => {
console.log(id);
@ -91,7 +88,94 @@ function NewOrders() {
}
});
};
const [searchTerm, setSearchTerm] = useState("");
const [searchValue, setsearchValue] = useState("orderId");
const handleChange = (event) => {
const { name, value } = event.target;
if (name === "Search") {
setsearchValue(value);
}
};
const formatDate = (dateString) => {
const dateArray = dateString.split(" ");
const day = dateArray[0];
const month = dateArray[1];
const year = dateArray[2];
const monthNumber = new Date(Date.parse(`${month} 1, 2022`)).getMonth() + 1;
return `${year}-${
monthNumber < 10 ? "0" + monthNumber : monthNumber
}-${day}`;
};
// const formatDate = (date) => {
// const day = ("0" + date.getDate()).slice(-2);
// const month = ("0" + (date.getMonth() + 1)).slice(-2);
// const year = date.getFullYear();
// return `${year}-${month}-${day}`;
// };
console.log(searchTerm);
useEffect(() => {
setTimeout(() => {
if (searchTerm !== "") {
let searchedResult = [];
if (searchValue === "orderId") {
searchedResult = newOrdersData.filter((item) =>
item.orderID.toString().includes(searchTerm)
);
} else if (searchValue === "Name") {
searchedResult = newOrdersData.filter((item) =>
item.user?.name
.toString()
.toLowerCase()
.includes(searchTerm.toLowerCase())
);
} else if (searchValue === "City") {
searchedResult = newOrdersData.filter((item) =>
item.shippingInfo.city
.toString()
.toLowerCase()
.includes(searchTerm.toLowerCase())
);
} else if (searchValue === "Amount") {
searchedResult = newOrdersData.filter((item) =>
item.total_amount.toString().includes(searchTerm)
);
} else if (searchValue === "OrderDate") {
// Format input date
const formattedDate = formatDate(searchTerm);
searchedResult = newOrdersData.filter((item) =>
item.createdAt.includes(formattedDate)
);
} else if (searchValue === "ProductName") {
searchedResult = newOrdersData.filter((order) =>
order.orderItems.some((item) =>
item.name
.toString()
.toLowerCase()
.includes(searchTerm.toLowerCase())
)
);
} else if (searchValue === "MobileNumber") {
searchedResult = newOrdersData.filter((item) =>
item.shippingInfo.phone_Number.toString().includes(searchTerm)
);
}
setShowData(searchedResult);
} else {
getNewOrder();
}
}, 100);
}, [searchTerm, searchValue, newOrdersData]);
useEffect(() => {
const loadData = () => {
const indexOfLastPost = currentPage * itemPerPage;
const indexOfFirstPost = indexOfLastPost - itemPerPage;
setShowData(newOrdersData.slice(indexOfFirstPost, indexOfLastPost));
};
loadData();
}, [currentPage, itemPerPage, newOrdersData]);
return (
<div className="main-content">
<div className="page-content">
@ -132,28 +216,135 @@ function NewOrders() {
<div className="col-lg-12">
<div className="card">
<div className="card-body">
<div className="row ml-0 mr-0 mb-10">
<div className="col-sm-12 col-md-12">
<div className="dataTables_length">
<label className="w-100">
Show
<select
style={{ width: "10%" }}
name=""
onChange={(e) => handleShowEntries(e)}
className="
<div className="d-flex align-items-center">
<div className="row ml-0 mr-0 mb-10">
<div className="col-sm-12 col-md-12">
<div className="dataTables_length">
<label className="w-100">
Show
<select
style={{ width: "50px" }}
name=""
onChange={(e) => handleShowEntries(e)}
className="
select-w
custom-select custom-select-sm
form-control form-control-sm
"
>
<option value="10">10</option>
<option value="25">25</option>
<option value="50">50</option>
<option value="100">100</option>
</select>
entries
</label>
</div>
</div>
</div>
<div className="ml-5 mt-2" style={{ display: "flex" }}>
<div
style={{
display: "flex",
alignItems: "center",
marginLeft: "1rem",
}}
>
<Typography
style={{
display: "flex",
justifyContent: "center",
alignItems: "center",
fontWeight: "bold",
marginRight: "1rem",
}}
>
Search by :
</Typography>
<FormControl>
<Select
name="Search"
value={searchValue}
onChange={handleChange}
style={{
display: "flex",
marginBottom: "1rem",
width: "120px",
height: "2rem",
}}
>
<option value="10">10</option>
<option value="25">25</option>
<option value="50">50</option>
<option value="100">100</option>
</select>
entries
</label>
<MenuItem
value="orderId"
style={{ display: "block", marginLeft: "0.5rem" }}
>
orderId
</MenuItem>
<MenuItem
value="Name"
style={{ display: "block", marginLeft: "0.5rem" }}
>
Name
</MenuItem>
<MenuItem
value="City"
style={{ display: "block", marginLeft: "0.5rem" }}
>
City
</MenuItem>
<MenuItem
value="Amount"
style={{ display: "block", marginLeft: "0.5rem" }}
>
Amount
</MenuItem>
<MenuItem
value="OrderDate"
style={{ display: "block", marginLeft: "0.5rem" }}
>
OrderDate
</MenuItem>
<MenuItem
value="ProductName"
style={{ display: "block", marginLeft: "0.5rem" }}
>
ProductName
</MenuItem>
<MenuItem
value="MobileNumber"
style={{ display: "block", marginLeft: "0.5rem" }}
>
MobileNumber
</MenuItem>
</Select>
</FormControl>
</div>
{/* <div>
{searchValue === "OrderDate" && (
<DatePicker
selected={searchTerm}
onChange={(date) => setSearchTerm(date)}
dateFormat="dd/MM/yyyy"
placeholderText="Select a date"
/>
)}
{searchValue !== "OrderDate" && (
<TextField
type="text"
placeholder="Search Here"
value={searchTerm}
onChange={(e) => setSearchTerm(e.target.value)}
/>
)}
<CIcon icon={cilSearch} size="xl" />
</div> */}
<div>
<TextField
type="text"
placeholder="Search Here"
value={searchTerm}
onChange={(e) => setSearchTerm(e.target.value)}
/>
<CIcon icon={cilSearch} size="xl" />
</div>
</div>
</div>

View File

@ -529,8 +529,7 @@ function POSViewOrders() {
<p className="m-0 mt-3 ms-3">
<stong> Subtotal:</stong>
{productDetails?.quantity *
productDetails?.price}
{productDetails?.product_Subtotal}
</p>
<p className="m-0 mt-3 ms-3">
<stong> Variant:</stong>{" "}