All files / src/pages ListStockPage.tsx

43.47% Statements 30/69
18.18% Branches 4/22
29.41% Functions 5/17
43.75% Lines 28/64

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211                                                            2x             2x 12x 12x 12x 12x 12x 12x 12x 12x         12x               12x 6x 6x 6x   6x 6x                               6x       12x 6x       6x 6x 6x             12x                   12x                                           12x 6x   6x                                                                                                                                                          
/**
 * @file ListStockPage.tsx
 * @description
 * Stock inventory display with pagination and CSV export.
 *
 * **Features:**
 * - Paginated product listing (10 per page)
 * - Product cards showing name, quantity, and total value
 * - CSV export of current page
 * - Pagination controls (previous/next)
 * - Role-based dashboard navigation
 * - Help modal support
 *
 * **CSV Export:**
 * Downloads products from current page as CSV file
 * Filename: products_page_N.csv
 *
 * @component
 */
 
import React, { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import ProductService from '../api/ProductService';
import { Product } from '../types/Product';
import { useTranslation } from 'react-i18next';
import HelpModal from '../components/HelpModal';
import '../styles/tailwindCustom.css';
import Header from '../components/Header';
import Footer from '../components/Footer';
 
const PRODUCTS_PER_PAGE = 10;
 
/**
 * Stock list page component
 * @component
 * @returns {JSX.Element} Paginated product inventory
 */
const ListStockPage: React.FC = () => {
  const { t, i18n } = useTranslation(['translation', 'help']);
  const [products, setProducts] = useState<Product[]>([]);
  const [totalPages, setTotalPages] = useState(0);
  const [currentPage, setCurrentPage] = useState(0);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [isHelpOpen, setIsHelpOpen] = useState(false);
  const navigate = useNavigate();
 
  /**
   * Navigate to role-appropriate dashboard
   */
  const navigateToDashboard = () => {
    const role = localStorage.getItem('role');
    if (role === 'ROLE_ADMIN') navigate('/admin');
    else if (role === 'ROLE_USER') navigate('/user');
    else navigate('/login');
  };
 
  // Fetch products for current page
  useEffect(() => {
    const fetchProducts = async () => {
      setLoading(true);
      setError(null);
 
      try {
        const response = await ProductService.fetchPagedProducts(currentPage, PRODUCTS_PER_PAGE);
        if (response && response.content) {
          setProducts(response.content);
          setTotalPages(response.totalPages || 0);
        } else {
          setProducts([]);
          setTotalPages(0);
        }
      } catch (err) {
        console.error(t('listStock.error.fetch'), err);
        setError(t('listStock.error.general'));
      } finally {
        setLoading(false);
      }
    };
 
    fetchProducts();
  }, [currentPage, t]);
 
  // Re-render help button on language changes
  useEffect(() => {
    const handleLanguageChange = () => {
      setIsHelpOpen((prev) => prev);
    };
 
    i18n.on('languageChanged', handleLanguageChange);
    return () => {
      i18n.off('languageChanged', handleLanguageChange);
    };
  }, [i18n]);
 
  /**
   * Update current page if valid
   */
  const handlePageChange = (newPage: number) => {
    if (newPage >= 0 && newPage < totalPages) {
      setCurrentPage(newPage);
    }
  };
 
  /**
   * Export current page products as CSV
   * Format: name,quantity,price,totalValue
   */
  const downloadCSV = () => {
    if (products.length === 0) {
      alert(t('listStock.alert.noProducts'));
      return;
    }
 
    const csvHeader = `${t('listStock.csvHeader.name')},${t('listStock.csvHeader.quantity')},${t('listStock.csvHeader.price')},${t('listStock.csvHeader.totalValue')}\n`;
    const csvRows = products
      .map((product) => `${product.name},${product.quantity},${product.price},${product.totalValue}`)
      .join('\n');
 
    const csvContent = csvHeader + csvRows;
    const blob = new Blob([csvContent], { type: 'text/csv' });
    const url = URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    link.download = `products_page_${currentPage + 1}.csv`;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  };
 
  if (loading) return <div>{t('loading')}</div>;
  Iif (error) return <div className="text-red-500">{error}</div>;
 
  return (
    <div className="flex flex-col min-h-screen bg-gray-50">
      <Header isLoggedIn={true} onLogout={() => navigate('/login')} />
 
      <div className="absolute top-4 left-1/2 transform -translate-x-1/2">
        <button
          onClick={() => setIsHelpOpen(true)}
          className="button-secondary"
          key={i18n.language}
        >
          {t('button', { ns: 'help' })}
        </button>
      </div>
 
      <HelpModal isOpen={isHelpOpen} onClose={() => setIsHelpOpen(false)} pageKey="listStock" />
 
      <main className="w-full max-w-4xl p-6 bg-white shadow-lg rounded mx-auto mt-6">
        <div className="flex justify-between items-center mb-4">
          <h2 className="text-xl font-semibold">{t('listStock.totalStock')}</h2>
          <button className="button-primary px-3 py-2 h-10 min-w-[120px] max-w-[180px] text-sm" onClick={downloadCSV}>
            {t('listStock.downloadCSV')}
          </button>
        </div>
 
        {products.length > 0 ? (
          <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 gap-4">
            {products.map((product) => (
              <div key={product.id} className="product-card">
                <p>
                  <strong>{t('listStock.labels.name')}:</strong> {product.name}
                </p>
                <p>
                  <strong>{t('listStock.labels.quantity')}:</strong> {product.quantity}
                </p>
                <p>
                  <strong>{t('listStock.labels.totalValue')}:</strong> ${product.totalValue?.toFixed(2)}
                </p>
              </div>
            ))}
          </div>
        ) : (
          <p className="text-center text-gray-500">{t('listStock.noProducts')}</p>
        )}
 
        <div className="mt-6 flex justify-center gap-4">
          <button
            className="button-secondary"
            disabled={currentPage === 0}
            onClick={() => handlePageChange(currentPage - 1)}
          >
            {t('listStock.pagination.previous')}
          </button>
          <span>
            {t('listStock.pagination.page')} {currentPage + 1} {t('listStock.pagination.of')} {totalPages}
          </span>
          <button
            className="button-secondary"
            disabled={currentPage === totalPages - 1}
            onClick={() => handlePageChange(currentPage + 1)}
          >
            {t('listStock.pagination.next')}
          </button>
        </div>
      </main>
 
      <div className="mt-6 flex justify-center">
        <button className="logout-button" onClick={navigateToDashboard}>
          {t('listStock.backToDashboard')}
        </button>
      </div>
 
      <Footer />
    </div>
  );
};
 
export default ListStockPage;