paymen

mail@pastecode.io avatar
unknown
plain_text
a month ago
4.9 kB
0
Indexable
Never
import React, { useState, useEffect } from 'react';
import Navbar from '../components/Navbar';
import Sidebar from '../components/Sidebar';
import Loader from '../components/Loader';
import './PaymentHistory.css';
import { BASE_URL } from './apiConfig';

const PaymentHistory = () => {
    const [payments, setPayments] = useState([]);
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState(null);
    const [isAuthenticated, setIsAuthenticated] = useState(false);

    useEffect(() => {
        const token = localStorage.getItem('token');
        setIsAuthenticated(!!token);
    }, []);

    useEffect(() => {
        if (!isAuthenticated) return;

        const fetchPaymentHistory = async () => {
            const token = localStorage.getItem('token');
            const userId = localStorage.getItem('userId');

            if (!token || !userId) {
                setError('Please login to view your payment history.');
                setLoading(false);
                return;
            }

            try {
                const url = `${BASE_URL}/api/staff-member/getPaymentHistory/${userId}`;
                console.log('Fetching data from URL:', url);

                const response = await fetch(url, {
                    method: 'GET',
                    headers: {
                        'Content-Type': 'application/json',
                        'Authorization': `Bearer ${token}`,
                    },
                });

                if (response.status === 401) {
                    setError('Unauthorized access. Please login again.');
                    return;
                }

                if (!response.ok) {
                    const errorText = await response.text();
                    console.error('Error response:', errorText);
                    throw new Error(`HTTP error! Status: ${response.status}, Message: ${errorText}`);
                }

                const data = await response.json();
                console.log('Data received:', data);

                // Assume data is a direct array of payments
                if (Array.isArray(data)) {
                    setPayments(data);
                } else {
                    setError('Unexpected data format received.');
                }
            } catch (error) {
                console.error('Error fetching data:', error.message);
                setError(error.message);
            } finally {
                setLoading(false);
            }
        };

        fetchPaymentHistory();
    }, [isAuthenticated]);

    const renderTable = (payments) => (
        <table className="history-tablee">
            <thead>
                <tr>
                    <th>#</th>
                    <th>Order Type</th>
                    <th>Order Date</th>
                    <th>Amount</th>
                </tr>
            </thead>
            <tbody>
                {payments.length > 0 ? (
                    payments.map((payment, index) => (
                        <tr key={index}>
                            <td>{index + 1}</td>
                            <td>{payment.orderType}</td>
                            <td>{new Date(payment.orderDate).toLocaleDateString()}</td>
                            <td>{payment.amount.toLocaleString()}</td>
                        </tr>
                    ))
                ) : (
                    <tr>
                        <td colSpan="4">No payments found.</td>
                    </tr>
                )}
            </tbody>
        </table>
    );

    

    if (loading) {
        return <Loader />;
    }

    if (error) {
        return (
            <div className="payment-history">
                <Navbar />
                <div className="content-long">
                    <Sidebar />
                    <div className="main">
                        <div className="main-content">
                            <h1>Payment History</h1>
                            <div className="error-message">{error}</div>
                        </div>
                    </div>
                </div>
            </div>
        );
    }

    return (
        <div className="payment-history">
            <Navbar />
            <div className="content-long">
                <Sidebar />
                <div className="main">
                    <div className="main-content">
                        <div className="History-title">
                        <h1>Payment History</h1>
                        </div>
                        {renderTable(payments)}
                    </div>
                </div>
            </div>
        </div>
    );
};

export default PaymentHistory;
Leave a Comment