LoanHistory

mail@pastecode.io avatar
unknown
plain_text
5 months ago
10 kB
2
Indexable
import React, { useState, useEffect } from 'react';
import Navbar from '../components/Navbar';
import Sidebar from '../components/Sidebar';
import Loader from '../components/Loader';
import { useNavigate } from 'react-router-dom';
import './LoanHistory.css';
import { BASE_URL } from '../pages/link';

const LoanHistory = () => {
    const [loans, setLoans] = useState([]);
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState(null);
    const [isAuthenticated, setIsAuthenticated] = useState(false);
    const [view, setView] = useState('borrowed'); // State variable to manage the current view
    const navigate = useNavigate();

    useEffect(() => {
        const token = localStorage.getItem('token');
        if (token) {
            setIsAuthenticated(true);
        } else {
            setIsAuthenticated(false);
        }
    }, []);

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

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

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

            try {
                const url = `${BASE_URL}/api/staff-member/loans/loanHistory/{MemberId}/{page}?MemberId=${userId}&page=0`;
                console.log('Fetching data from URL:', url);

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

                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();
                setLoans(data.content || []);
            } catch (error) {
                console.error('Error fetching data:', error.message);
                setError(error.message);
            } finally {
                setLoading(false);
            }
        };

        fetchLoanHistory();
    }, [isAuthenticated]);

    if (!isAuthenticated) {
        return (
            <div className="loan-history">
                <Navbar />
                <div className="content-long">
                    <Sidebar />
                    <div className="main">
                        <div className="main-content">
                            <h1>History of Borrowing and Returning Books</h1>
                            <p>Please login to view your book borrowing and returning history.</p>
</div>
                    </div>
                </div>
            </div>
        );
    }

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

    if (error) {
        return (
            <div className="loan-history">
                <Navbar />
                <div className="content-long">
                    <Sidebar />
                    <div className="main">
                        <div className="main-content">
                            <h1>History of Borrowing and Returning Books</h1>
                            <div className="error-message">{error}</div>
                        </div>
                    </div>
                </div>
            </div>
        );
    }

    const borrowedLoans = loans.filter(loan => !loan.returnDate);
    const returnedLoans = loans.filter(loan => loan.returnDate);

    return (
        <div className="loan-history">
            <Navbar />
            <div className="content-long">
                <Sidebar />
                <div className="main">
                    <div className="main-content">
                        <h1>History of Borrowing and Returning Books</h1>
                        <div className="button-group">
                            <button
                                onClick={() => setView('borrowed')}
                                className={view === 'borrowed' ? 'active' : ''}
                            >
                                Books on Borrow
                            </button>
                            <button
                                onClick={() => setView('returned')}
                                className={view === 'returned' ? 'active' : ''}
                            >
                                Returned Books
                            </button>
                        </div>

                        {view === 'borrowed' ? (
                            <>
                                <h2>Currently Borrowed Books</h2>
                                <table className="history-table">
                                    <thead>
                                        <tr>
                                            <th>Copy Book ID</th>
                                            <th>Image</th>
                                            <th>Title</th>
                                            <th>Loan Date</th>
                                            <th>Return Date</th>
                                            <th>Due Date</th>
                                            <th>Status</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        {borrowedLoans.length > 0 ? (
                                            borrowedLoans.map((loan) => (
                                                <tr key={loan.copyBookId}>
                                                    <td>{loan.copyBookId}</td>
<td>
                                                        {loan.copyBookCover ? (
                                                            <img src={loan.copyBookCover} alt={loan.copyBookTitle} className="history-image" />
                                                        ) : (
                                                            'No Image'
                                                        )}
                                                    </td>
                                                    <td className="Name">{loan.copyBookTitle}</td>
                                                    <td>{new Date(loan.loanDate).toLocaleDateString()}</td>
                                                    <td>{loan.returnDate ? new Date(loan.returnDate).toLocaleDateString() : 'Not Returned Yet'}</td>
                                                    <td>{new Date(loan.dueDate).toLocaleDateString()}</td>
                                                    <td className="borrowed">{loan.status}</td>
                                                </tr>
                                            ))
                                        ) : (
                                            <tr>
                                                <td colSpan="7">No borrowed books found.</td>
                                            </tr>
                                        )}
                                    </tbody>
                                </table>
                            </>
                        ) : (
                            <>
                                <h2>Returned Books</h2>
                                <table className="history-table">
                                    <thead>
                                        <tr>
                                            <th>Copy Book ID</th>
                                            <th>Image</th>
                                            <th>Title</th>
                                            <th>Loan Date</th>
                                            <th>Return Date</th>
                                            <th>Due Date</th>
                                            <th>Status</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        {returnedLoans.length > 0 ? (
                                            returnedLoans.map((loan) => (
                                                <tr key={loan.copyBookId}>
                                                    <td>{loan.copyBookId}</td>
                                                    <td>
                                                        {loan.copyBookCover ? (
                                                            <img src={loan.copyBookCover} alt={loan.copyBookTitle} className="history-image" />
) : (
                                                            'No Image'
                                                        )}
                                                    </td>
                                                    <td className="Name">{loan.copyBookTitle}</td>
                                                    <td>{new Date(loan.loanDate).toLocaleDateString()}</td>
                                                    <td>{new Date(loan.returnDate).toLocaleDateString()}</td>
                                                    <td>{new Date(loan.dueDate).toLocaleDateString()}</td>
                                                    <td className="returned">{loan.status}</td>
                                                </tr>
                                            ))
                                        ) : (
                                            <tr>
                                                <td colSpan="7">No returned books found.</td>
                                            </tr>
                                        )}
                                    </tbody>
                                </table>
                            </>
                        )}
                    </div>
                </div>
            </div>
        </div>
    );
};

export default LoanHistory;
Leave a Comment