From 6580f5d85409dc942bf1b38a1ca11f4b74002c5d Mon Sep 17 00:00:00 2001 From: ROSHAN GARG Date: Fri, 23 Aug 2024 10:49:28 +0530 Subject: [PATCH] order process completed --- src/_nav.js | 14 ++ src/components/AppHeader.js | 4 +- src/routes.js | 4 +- src/views/orders/Order.js | 144 ++++++++++++++- src/views/orders/OrderDetails.js | 206 ++++++++++++++++++++++ src/views/pages/cart/cart.js | 17 +- src/views/pages/cart/orderConfirmation.js | 6 +- src/views/pages/cart/reviewOrder.js | 66 ++++++- src/views/pages/cart/shopingCart.js | 6 +- src/views/pages/login/Login.js | 4 + 10 files changed, 446 insertions(+), 25 deletions(-) create mode 100644 src/views/orders/OrderDetails.js diff --git a/src/_nav.js b/src/_nav.js index 72cc65f..bcd0619 100644 --- a/src/_nav.js +++ b/src/_nav.js @@ -9,6 +9,7 @@ import { cilDescription, cilDrop, cilNotes, + cilPaperPlane, cilPencil, cilPuzzle, cilShare, @@ -30,6 +31,19 @@ const _nav = [ to: '/shop', icon: , }, + { + component: CNavItem, + name: 'Cart', + to: '/cart', + icon: , + }, + { + component: CNavItem, + name: 'Orders Placed', + to: '/orders-placed', + icon: , + }, + // { // component: CNavItem, // name: 'Orders', diff --git a/src/components/AppHeader.js b/src/components/AppHeader.js index 60e1b30..d2a24e4 100644 --- a/src/components/AppHeader.js +++ b/src/components/AppHeader.js @@ -134,11 +134,11 @@ const AppHeader = () => { */} - + {/* - + */} diff --git a/src/routes.js b/src/routes.js index 534addf..9ed04ac 100644 --- a/src/routes.js +++ b/src/routes.js @@ -2,6 +2,7 @@ import { element } from 'prop-types' import React from 'react' import Cart from './views/pages/cart/cart' +import OrderDetails from './views/orders/OrderDetails' const Dashboard = React.lazy(() => import('./views/dashboard/Dashboard')) const Shop = React.lazy(() => import('./views/shops/Shop')) @@ -15,7 +16,8 @@ const routes = [ { path: '/', exact: true, name: 'Home' }, { path: '/dashboard', name: 'Dashboard', element: Dashboard }, { path: '/shop', name: 'Shop', element: Shop }, - { path: '/order', name: 'Order', element: Order }, + { path: '/orders-placed', name: 'Order', element: Order }, + { path: '/orders-placed/:id', name: 'Order', element: OrderDetails }, // KYC { path: '/kyc', name: 'KYC', element: Kyc }, { path: '/kyc/details/:id', name: 'Kyc details', element: KycDetails }, diff --git a/src/views/orders/Order.js b/src/views/orders/Order.js index f95e1cc..612160c 100644 --- a/src/views/orders/Order.js +++ b/src/views/orders/Order.js @@ -1,7 +1,147 @@ -import React from 'react' +import React, { useEffect, useState } from 'react' +import { + Table, + TableBody, + TableCell, + TableContainer, + TableHead, + TableRow, + Paper, + Typography, + Skeleton, + Box, + Button, + TablePagination, +} from '@mui/material' +import Axios from '../../axios' +import { isAutheticated } from '../../auth' +import { useNavigate } from 'react-router-dom' const Order = () => { - return
Order
+ const [orders, setOrders] = useState([]) + const [loading, setLoading] = useState(true) + const [page, setPage] = useState(0) + const [rowsPerPage, setRowsPerPage] = useState(5) + const [totalOrders, setTotalOrders] = useState(0) + const token = isAutheticated() + const navigate = useNavigate() + + const formatAMPM = (date) => { + var hours = new Date(date).getHours() + var minutes = new Date(date).getMinutes() + var ampm = hours >= 12 ? 'PM' : 'AM' + hours = hours % 12 + hours = hours ? hours : 12 // the hour '0' should be '12' + minutes = minutes < 10 ? '0' + minutes : minutes + var strTime = hours + ':' + minutes + ' ' + ampm + return strTime + } + + useEffect(() => { + // Fetch orders from the API with pagination + const fetchOrders = async () => { + try { + const response = await Axios.get('/api/get-placed-order-pd', { + headers: { + 'Access-Control-Allow-Origin': '*', + Authorization: `Bearer ${token}`, + 'Content-Type': 'application/json', + }, + params: { + page: page + 1, // page number for API (usually starts from 1) + limit: rowsPerPage, // number of rows per page + }, + }) + setOrders(response.data.plcaedOrders) + setTotalOrders(response.data.totalOrders) // Ensure the API returns the total count of orders + } catch (error) { + console.error('Error fetching orders:', error) + } finally { + setLoading(false) + } + } + + fetchOrders() + }, [page, rowsPerPage]) + + const handleChangePage = (event, newPage) => { + setPage(newPage) + } + + const handleChangeRowsPerPage = (event) => { + setRowsPerPage(parseInt(event.target.value, 10)) + setPage(0) // Reset page to 0 when rows per page changes + } + + return ( + + + Order placed list + + + + + + Order ID + Order Date + Items + Order Value + Status + Action + + + + {loading ? ( + Array.from(new Array(rowsPerPage)).map((_, index) => ( + + + + + + )) + ) : orders.length > 0 ? ( + orders.map((order) => ( + + {order.uniqueId} + + {new Date(`${order?.createdAt}`).toDateString()} + , {`${formatAMPM(order?.createdAt)}`} + + {order.orderItem.length} + {order.grandTotal.toFixed(2)} + {order.status} + + + + + )) + ) : ( + + + Data not found + + + )} + +
+ +
+
+ ) } export default Order diff --git a/src/views/orders/OrderDetails.js b/src/views/orders/OrderDetails.js new file mode 100644 index 0000000..f01c948 --- /dev/null +++ b/src/views/orders/OrderDetails.js @@ -0,0 +1,206 @@ +import React, { useEffect, useState } from 'react' +import { + Box, + Button, + Grid, + Paper, + Table, + TableBody, + TableCell, + TableContainer, + TableHead, + TableRow, + Typography, +} from '@mui/material' +import axios from 'axios' // Make sure you have axios installed +import { useNavigate, useParams } from 'react-router-dom' +import Axios from '../../axios' + +const OrderDetails = () => { + const [order, setOrder] = useState(null) + const [loading, setLoading] = useState(true) + const [error, setError] = useState(null) + const navigate = useNavigate() + const { id } = useParams() // Assuming order ID is passed as a route parameter + + useEffect(() => { + const fetchOrderDetails = async () => { + try { + const response = await Axios.get(`/api/get-single-placed-order-pd/${id}`) // Adjust API endpoint as needed + setOrder(response.data.singleOrder) + console.log(response) + setLoading(false) + } catch (err) { + setError(err.return_msg) + setLoading(false) + } + } + + fetchOrderDetails() + }, [id]) + + if (loading) { + return Loading... + } + + if (error) { + return Error: {error} + } + + if (!order) { + return No data found + } + + const { + uniqueId, + billTo, + shipTo, + paymentMode, + orderItem, + subtotal, + gstTotal, + grandTotal, + statusHistory, // Assume this is an array of status objects + } = order + console.log(statusHistory) + + return ( + + {/* Order Details Section */} + + + + + Order ID: {uniqueId} + + + + + + + + Bill Address + + {billTo} + + + + Ship Address + + {shipTo} + + + + Payment Mode: {paymentMode} + + + + + + {/* Order Items Table */} + + + + + + + + + Product + SKU + Quantity + Price + GST + Subtotal + + + + {order.orderItem.map((row, index) => { + const gstAmount = (row.productId.price * row.productId.GST) / 100 + return ( + + + + + {row.productId.name} + + + + {row.productId.SKU} + {row.quantity} + ₹{row.productId.price} + ₹{gstAmount} + ₹{row.productId.price * row.quantity} + + ) + })} + + + + Subtotal: ₹ {subtotal} + + + + + + Total GST: ₹ {gstTotal} + + + + + + Grand Total: ₹ {grandTotal} + + + +
+
+
+
+
+
+ + {/* Status History Table */} + {statusHistory.length > 0 && ( + + + Status History + + + + + + Status + Timestamp + + + + {statusHistory.map((status, index) => ( + + {status.status} + {new Date(status.timestamp).toLocaleString()} + + ))} + +
+
+
+ )} +
+ ) +} + +export default OrderDetails diff --git a/src/views/pages/cart/cart.js b/src/views/pages/cart/cart.js index 451697f..5c01ce5 100644 --- a/src/views/pages/cart/cart.js +++ b/src/views/pages/cart/cart.js @@ -14,6 +14,7 @@ import ReviewOrder from './reviewOrder' import OrderConfirmation from './orderConfirmation' import { useDispatch, useSelector } from 'react-redux' import { + clearCart, loadCart, selectCartItemCount, selectCartItems, @@ -103,6 +104,7 @@ const styles = { const Cart = () => { const [shipTo, setShipTo] = useState('') const [billTo, setBillTo] = useState('') + const dispatch = useDispatch() const [paymentMode, setPaymentMode] = useState('') const cartItems = useSelector(selectCartItems) const totalItemCount = useSelector(selectCartItemCount) @@ -110,6 +112,12 @@ const Cart = () => { const [value, setValue] = useState(0) const handleTabChange = (event, newValue) => { console.log(newValue) + if (value === 3 && newValue !== 3) { + setPaymentMode('') + setBillTo('') + setShipTo('') + dispatch(clearCart()) + } if (newValue === 1 && cartItems.length === 0) { Swal.fire('Cart is emplty ,can not move to next screen pls add items to cart ') return @@ -133,7 +141,7 @@ const Cart = () => { // } // setValue(1) // } - const orderId = '#F5SD67G' + const [orderId, setOrderId] = useState(null) // const [cartItem, setCartItem] = useState([ // { // product: { @@ -166,12 +174,6 @@ const Cart = () => { // subtotal: 150, // }, // ]) - const dispatch = useDispatch() - - // Load the cart items from local storage when the component mounts - useEffect(() => { - dispatch(loadCart()) - }, []) return ( @@ -225,6 +227,7 @@ const Cart = () => { shipTo={shipTo} paymentMode={paymentMode} orderId={orderId} + setOrderId={setOrderId} cartItem={cartItems} handleTabChange={handleTabChange} /> diff --git a/src/views/pages/cart/orderConfirmation.js b/src/views/pages/cart/orderConfirmation.js index a43728f..bcda06f 100644 --- a/src/views/pages/cart/orderConfirmation.js +++ b/src/views/pages/cart/orderConfirmation.js @@ -21,7 +21,7 @@ const OrderConfirmation = ({ orderId, billTo, shipTo, paymentMode, cartItem }) = // Calculate total GST for the entire cart const totalGST = cartItem.reduce((acc, item) => { // console.log(item) - const gstAmount = (item.price * item.GST.tax) / 100 + const gstAmount = (item.price * item.GST) / 100 return acc + gstAmount * item.count }, 0) return ( @@ -65,7 +65,7 @@ const OrderConfirmation = ({ orderId, billTo, shipTo, paymentMode, cartItem }) = Product - HSN + SKU Quantity Price GST @@ -74,7 +74,7 @@ const OrderConfirmation = ({ orderId, billTo, shipTo, paymentMode, cartItem }) = {cartItem.map((row, index) => { - const gstAmount = (row.price * row.GST.tax) / 100 + const gstAmount = (row.price * row.GST) / 100 return ( { +const ReviewOrder = ({ + orderId, + billTo, + shipTo, + paymentMode, + cartItem, + + handleTabChange, + setOrderId, +}) => { const subtotal = useSelector(selectCartSubtotal) + const token = isAutheticated() + const dispatch = useDispatch() // Calculate total GST for the entire cart const totalGST = cartItem.reduce((acc, item) => { // console.log(item) - const gstAmount = (item.price * item.GST.tax) / 100 + const gstAmount = (item.price * item.GST) / 100 return acc + gstAmount * item.count }, 0) + + const handleConfirmOrder = async (e) => { + e.preventDefault() + if (!billTo || !shipTo || !paymentMode || !cartItem || !subtotal || !totalGST) { + Swal.fire('All fields are required ') + } + try { + const res = await Axios.post( + '/api/order-place', + { + billTo, + shipTo, + paymentMode, + grandTotal: subtotal + totalGST, + gstTotal: totalGST, + subtotal: subtotal, + orderItems: cartItem, + }, + { + headers: { + 'Access-Control-Allow-Origin': '*', + Authorization: `Bearer ${token}`, + 'Content-Type': 'application/json', + }, + }, + ) + console.log(res) + if (res.status === 201) { + setOrderId(res?.data?.placedOrder?.uniqueId) + + console.log(res) + Swal.fire('Success!', 'Your order has been placed successfully.', 'success') + handleTabChange(e, 3) + } + } catch (error) { + Swal.fire('Something went wrong', error.message, 'error') + } + } return ( @@ -62,7 +114,7 @@ const ReviewOrder = ({ orderId, billTo, shipTo, paymentMode, cartItem, handleTab Product - HSN + SKU Quantity Price GST @@ -71,7 +123,7 @@ const ReviewOrder = ({ orderId, billTo, shipTo, paymentMode, cartItem, handleTab {cartItem.map((row, index) => { - const gstAmount = (row.price * row.GST.tax) / 100 + const gstAmount = (row.price * row.GST) / 100 return ( handleTabChange(e, 0)}> Update Order - diff --git a/src/views/pages/cart/shopingCart.js b/src/views/pages/cart/shopingCart.js index b88ea37..14647d4 100644 --- a/src/views/pages/cart/shopingCart.js +++ b/src/views/pages/cart/shopingCart.js @@ -36,7 +36,7 @@ const ShoppingCart = ({ handleTabChange }) => { // Calculate total GST for the entire cart const totalGST = cartItems.reduce((acc, item) => { // console.log(item) - const gstAmount = (item.price * item.GST.tax) / 100 + const gstAmount = (item.price * item.GST) / 100 return acc + gstAmount * item.count }, 0) @@ -68,7 +68,7 @@ const ShoppingCart = ({ handleTabChange }) => { Product - HSN + SKU Quantity Price GST @@ -77,7 +77,7 @@ const ShoppingCart = ({ handleTabChange }) => { {cartItems.map((row, index) => { - const gstAmount = (row.price * row.GST.tax) / 100 + const gstAmount = (row.price * row.GST) / 100 return ( { const [loading, setLoading] = useState(false) const [validForm, setValidForm] = useState(false) + const dispatch = useDispatch() const navigate = useNavigate() const [auth, setAuth] = useState({ email: '', @@ -101,6 +104,7 @@ const Login = () => { console.log(res) if (res.data.success === true && res.data.user.role === 'principal-Distributor') { localStorage.setItem('authToken', res.data.token) + dispatch(clearCart()) navigate('/dashboard') setLoading(false) Swal.fire('success', 'logged in successfully ', 'success')