diff --git a/package.json b/package.json index 18a472f..2333507 100644 --- a/package.json +++ b/package.json @@ -57,7 +57,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", diff --git a/src/views/PointOfSale/Pos.js b/src/views/PointOfSale/Pos.js index 3ed84b2..630b030 100644 --- a/src/views/PointOfSale/Pos.js +++ b/src/views/PointOfSale/Pos.js @@ -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)} { color: "#121212", }} > - ₹{row.subtotal} + ₹{Number(row?.subtotal)?.toFixed(2)} )) @@ -1200,82 +1139,65 @@ const Pos = () => { style={{ display: "flex", justifyContent: "space-between" }} >
- {/* {salesType === "" ? null : salesType === - "inStoreDelivery" ? ( */} -
- - In-Store delivery: - -
- - -
-
- - -
- {storedelivery && ( - - )} -
- {/* ) : ( -
- {salesType === "shipToCustomer" && ( - - )} - {salesType !== "shipToCustomer" && ( + In-Store delivery: + +
+ + +
+
+ + +
+ {storedelivery && ( )}
- )} */} + ) : ( +
+

+ Please Add user and their address to place the order +

+
+ )}
{/* Total Section */} diff --git a/src/views/dashboard/Dashboard.js b/src/views/dashboard/Dashboard.js index 805fa64..930b58a 100644 --- a/src/views/dashboard/Dashboard.js +++ b/src/views/dashboard/Dashboard.js @@ -33,7 +33,7 @@ const Dashboard = () => { //3rd const [product, setProduct] = useState([]); const getAllProduct = async () => { - let res = await axios.get(`/api/product/getAll/`, { + let res = await axios.get(`/api/product/getAll/user/`, { headers: { Authorization: `Bearer ${token}`, }, diff --git a/src/views/orders/NewOrders.js b/src/views/orders/NewOrders.js index f6acb81..5b3aec5 100644 --- a/src/views/orders/NewOrders.js +++ b/src/views/orders/NewOrders.js @@ -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" - ); - - setNewOrdersData(filteredOrders); - setLoading(false); - }) - .catch((err) => { - console.log(err); - setLoading(false); - }); - } - getNewOrder(); - }, [success]); - + 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); + }); + } useEffect(() => { - const loadData = () => { - const indexOfLastPost = currentPage * itemPerPage; - const indexOfFirstPost = indexOfLastPost - itemPerPage; - setShowData(newOrdersData.slice(indexOfFirstPost, indexOfLastPost)); - }; - loadData(); - }, [currentPage, itemPerPage, newOrdersData]); + setLoading(true); + getNewOrder(); + }, [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 (
@@ -132,28 +216,135 @@ function NewOrders() {
-
-
-
- +
+
+
+
+
+ + Search by : + + + - entries - + + orderId + + + Name + + + City + + + Amount + + + OrderDate + + + ProductName + + + MobileNumber + + + +
+ {/*
+ {searchValue === "OrderDate" && ( + setSearchTerm(date)} + dateFormat="dd/MM/yyyy" + placeholderText="Select a date" + /> + )} + {searchValue !== "OrderDate" && ( + setSearchTerm(e.target.value)} + /> + )} + +
*/} +
+ setSearchTerm(e.target.value)} + /> +
diff --git a/src/views/orders/POSViewOrders.js b/src/views/orders/POSViewOrders.js index 7af4c55..0c3c263 100644 --- a/src/views/orders/POSViewOrders.js +++ b/src/views/orders/POSViewOrders.js @@ -529,8 +529,7 @@ function POSViewOrders() {

Subtotal: ₹ - {productDetails?.quantity * - productDetails?.price} + {productDetails?.product_Subtotal}

Variant:{" "}