Untitled

mail@pastecode.io avatar
unknown
plain_text
a month ago
4.9 kB
1
Indexable
Never
import React, { useState, useEffect } from 'react';
import axios from 'axios';
import { Button } from '@mui/material';
import Navbar from '../Navbar/Navbar';
import { useNavigate } from 'react-router-dom';
import { ToastContainer, toast } from 'react-toastify';
import 'react-toastify/dist/ReactToastify.css';
import { useParams } from 'react-router-dom';
import { GetCartProductsByGmail, deletefromcart, postorder } from '../API_FILE/apis';
import './OrderSelection.css'; // Import CSS file for OrderSelection component styling

export default function OrderSelection() {
    const navigate = useNavigate();
    const { addressId } = useParams();

    const [products, setProducts] = useState([]);
    const storedEmail = sessionStorage.getItem('email');
    const [totalAmount, setTotalAmount] = useState(0);

    console.log(addressId);

    const fetchProducts = async () => {
        try {
            const response = await axios.get(GetCartProductsByGmail(storedEmail));
            setProducts(response.data);
            calculateTotal(response.data);
        } catch (error) {
            console.error('Error fetching products:', error);
        }
    };

    const calculateTotal = (products) => {
        let total = 0;
        products.forEach(product => {
            total += product.price * product.cartquantity;
        });
        setTotalAmount(total);
    };

    function generateUniqueKey(length) {
        var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
            var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
            return v.toString(16);
        });
        var uniqueKey = "";
        for (var i = 0; i < length; i++) {
            uniqueKey += uuid.substring(i % 32, 1);
        }
        return uniqueKey;
    }

    const handlePlaceOrder = async () => {
        var unique_code = generateUniqueKey(5);

        for (let i = 0; i < products.length; i++) {
            const product = products[i];
            console.log(unique_code);

            try {
                const response = await axios.post(postorder(storedEmail, product.productid, unique_code, addressId));

                if (response.status === 200) {
                    console.log(`Order placed successfully for product ID: ${product.productid}`);
                }

                axios.delete(deletefromcart(product.productid, storedEmail));
            } catch (error) {
                console.error(`Error placing order for product ID: ${product.productid}`, error);
            }
        }

        navigate('/OrderSuccess');
    };

    useEffect(() => {
        fetchProducts();
    }, [storedEmail]);

    return (
        <>
            <Navbar />

            <div className="order-selection-container">
                <div className="order-summary">
                    <h2>Order Summary</h2>
                    <div className="receipt">
                        {products.map(product => (
                            <div key={product.productid} className="receipt-item">
                                <img src={product.productimage} alt={product.Name} />
                                <div className="receipt-details">
                                    <h3>{product.name}</h3>
                                    <p>Price: INR {product.price}</p>
                                </div>
                            </div>
                        ))}
                    </div>
                    <div className="total-amount">Total Amount: INR {totalAmount}</div>
                    <Button variant="contained" onClick={handlePlaceOrder}>Place Order</Button>
                </div>
            </div>
        </>
    );
}

/* OrderSelection.css */

.order-selection-container {
    max-width: 800px;
    margin: 0 auto;
    padding: 20px;
}

.order-summary {
    background-color: #f9f9f9;
    padding: 20px;
    border-radius: 8px;
    box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}

.order-summary h2 {
    margin-top: 0;
    margin-bottom: 20px;
    font-size: 24px;
    color: #333;
}

.receipt {
    display: flex;
    flex-direction: column;
}

.receipt-item {
    display: flex;
    align-items: center;
    margin-bottom: 20px;
}

.receipt-item img {
    width: 100px;
    height: 100px;
    margin-right: 20px;
    border-radius: 4px;
}

.receipt-details h3 {
    margin-top: 0;
    margin-bottom: 5px;
    font-size: 18px;
    color: #333;
}

.receipt-details p {
    margin: 0;
    font-size: 16px;
    color: #666;
}

.total-amount {
    margin-top: 20px;
    font-size: 20px;
    font-weight: bold;
    color: #333;
}

button {
    margin-top: 20px;
    padding: 10px 20px;
    font-size: 18px;
    color: #fff;
    background-color: #007bff;
    border: none;
    border-radius: 4px;
    cursor: pointer;
    transition: background-color 0.3s ease;
}

button:hover {
    background-color: #0056b3;
}


Leave a Comment