All files / src/pages/analytics/blocks LowStockTable.tsx

0% Statements 0/238
0% Branches 0/1
0% Functions 0/1
0% Lines 0/238

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 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             
/**
 * @file LowStockTable.tsx
 * @module pages/analytics/blocks/LowStockTable
 * @category Analytics
 *
 * @summary
 * Renders a low-stock table for a selected supplier. The table shows
 * item name, current quantity, minimum threshold, a computed “deficit”,
 * and a status chip (OK / Warning / Critical).
 *
 * @remarks
 * - Data source: `GET /api/analytics/low-stock-items?supplierId=...&start=...&end=...`
 * - Query is disabled when no supplierId is provided (via React Query `enabled`).
 * - DTOs are normalized in the API layer; this component assumes:
 *   `{ itemName: string, quantity: number, minimumQuantity: number }`.
 * - Uses plain MUI Table for portability.
 */

import { useCallback, type JSX } from 'react';
import {
  Box,
  Typography,
  Skeleton,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  Paper,
  Chip,
} from '@mui/material';
import { useTheme as useMuiTheme } from '@mui/material/styles';
import { useQuery } from '@tanstack/react-query';
import { useTranslation } from 'react-i18next';
import { getLowStockItems, type LowStockRow, type AnalyticsParams } from '../../../api/analytics';
import { useSettings } from '../../../hooks/useSettings';
import { formatNumber } from '../../../utils/formatters';

/**
 * Props accepted by {@link LowStockTable}.
 * @public
 */
export type LowStockTableProps = {
  /** Required supplier id whose items should be evaluated for low stock. */
  supplierId: string;
  /** Optional ISO date (YYYY-MM-DD) for lower bound. */
  from?: string;
  /** Optional ISO date (YYYY-MM-DD) for upper bound. */
  to?: string;
  /** Show at most N most severe rows (by deficit). `0` = show all. @defaultValue 12 */
  limit?: number;
};

/** Narrow filter params to only allowed keys for the low-stock endpoint. @internal */
function narrowParams(p: Pick<AnalyticsParams, 'from' | 'to'>): AnalyticsParams {
  const out: AnalyticsParams = {};
  if (p.from) out.from = p.from;
  if (p.to) out.to = p.to;
  return out;
}

/**
 * LowStockTable
 *
 * @description
 * Displays items at or below minimum quantity for a given supplier. The query
 * is **always declared** (top-level Hook) and **conditionally enabled** using
 * React Query’s `enabled` flag, thereby complying with the Rules of Hooks.
 *
 * @example
 * ```tsx
 * <LowStockTable supplierId="sup-123" from="2025-06-01" to="2025-09-15" limit={12} />
 * ```
 */
export default function LowStockTable(props: LowStockTableProps): JSX.Element {
  const { supplierId, from, to, limit = 12 } = props;
  const { t } = useTranslation(['analytics', 'common']);
  const muiTheme = useMuiTheme();
  const { userPreferences } = useSettings();
  const formatQty = useCallback(
    (value: number | undefined | null): string => {
      if (typeof value !== 'number' || Number.isNaN(value)) return formatNumber(0, userPreferences.numberFormat, 0);
      return formatNumber(value, userPreferences.numberFormat, 0);
    },
    [userPreferences.numberFormat]
  );

  // Data fetching (Hooks MUST be unconditioned; gate with `enabled`)
  const enabled = Boolean(supplierId);

  /**
   * React Query:
   * - Keyed by endpoint + supplierId + date window so caching is correct.
   * - `enabled` prevents calls when supplierId is empty.
   */
  const q = useQuery<LowStockRow[], Error>({
    queryKey: ['analytics', 'lowStock', supplierId, from ?? null, to ?? null],
    queryFn: () => getLowStockItems(supplierId, narrowParams({ from, to })),
    enabled,
    staleTime: 60_000,
  });

  // Conditional UI states

  if (!enabled) {
    return (
      <Box sx={{ height: 220, display: 'grid', placeItems: 'center', color: 'text.secondary' }}>
        {t('analytics:selectSupplier', 'Select a supplier to see low stock')}
      </Box>
    );
  }

  if (q.isLoading) {
    return <Skeleton variant="rounded" height={220} />;
  }

  if (q.isError) {
    return (
      <Box sx={{ height: 220, display: 'grid', placeItems: 'center', color: 'text.secondary' }}>
        {t('common:error', 'Error')}
      </Box>
    );
  }

  // Compute deficits and order by most severe first.
  const rows: Array<LowStockRow & { deficit: number }> = (q.data ?? [])
    .map((r) => ({
      ...r,
      deficit: Math.max(0, (r.minimumQuantity ?? 0) - (r.quantity ?? 0)),
    }))
    // Keep only items truly under/at threshold (deficit > 0).
    .filter((r) => r.deficit > 0 || (r.quantity ?? 0) <= (r.minimumQuantity ?? 0))
    .sort((a, b) => b.deficit - a.deficit);

  const visible = limit > 0 ? rows.slice(0, limit) : rows;

  if (visible.length === 0) {
    return (
      <Box sx={{ height: 220, display: 'grid', placeItems: 'center', color: 'text.secondary' }}>
        {t('analytics:lowStock.noneForSupplier', 'No items below minimum for this supplier')}
      </Box>
    );
  }

  return (
    <TableContainer 
      component={Paper} 
      variant="outlined" 
      sx={{ 
          maxHeight: 360,
          overflowX: 'auto', // Allow Horizontal scroll instead of clipping
          pr: 1,            // tiny right gutter so chips and tooltips do not get cut off
        }}
    >
      <Table 
        size="small" 
        stickyHeader
        sx={{
        minWidth: 640,     // avoids cramped columns on small breakpoints
        tableLayout: 'fixed', // predictable column widths; text can ellipsis
        }}
      >
        <TableHead>
          <TableRow>
            <TableCell sx={{ width: '40%' }}>
              {t('analytics:lowStock.columns.item', 'Item')}
            </TableCell>
            <TableCell align="right" sx={{ width: '15%' }}>
              {t('analytics:lowStock.columns.quantity', 'Quantity')}
            </TableCell>
            <TableCell align="right" sx={{ width: '15%' }}>
              {t('analytics:lowStock.columns.minimum', 'Minimum')}
            </TableCell>
            <TableCell align="right" sx={{ width: '15%' }}>
              {t('analytics:lowStock.columns.deficit', 'Deficit')}
            </TableCell>
            <TableCell align="left" sx={{ width: '15%', whiteSpace: 'nowrap' }}>
              {t('analytics:lowStock.columns.status', 'Status')}
            </TableCell>
          </TableRow>
        </TableHead>
        <TableBody>
          {visible.map((r) => {
            const critical = r.deficit >= 5; // tweak policy if needed
            const warning = r.deficit > 0 && r.deficit < 5;

            return (
              <TableRow key={r.itemName}>
                <TableCell 
                  component="th" 
                  scope="row"
                  sx={{ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}
                >
                  {r.itemName}
                </TableCell>
                <TableCell align="right">{formatQty(r.quantity)}</TableCell>
                <TableCell align="right">{formatQty(r.minimumQuantity)}</TableCell>
                <TableCell
                  align="right"
                  sx={{
                    fontWeight: 600,
                    color: critical
                      ? muiTheme.palette.error.main
                      : warning
                        ? muiTheme.palette.warning.main
                        : muiTheme.palette.text.primary,
                  }}
                >
                  {formatQty(r.deficit)}
                </TableCell>
                <TableCell align="left" sx={{ whiteSpace: 'nowrap' }}>
                  {critical ? (
                    <Chip size="small" color="error" label={t('analytics:lowStock.status.critical', 'Critical')} />
                  ) : warning ? (
                    <Chip size="small" color="warning" label={t('analytics:lowStock.status.warning', 'Warning')} />
                  ) : (
                    <Chip size="small" color="success" label={t('analytics:lowStock.status.ok', 'OK')} />
                  )}
                </TableCell>
              </TableRow>
            );
          })}
        </TableBody>
      </Table>
      {limit > 0 && rows.length > limit && (
        <Box sx={{ p: 1.5, color: 'text.secondary' }}>
          <Typography variant="caption">
            {t('analytics:lowStock.shownNOfM', 'Showing {{n}} of {{m}} items', {
              n: visible.length,
              m: rows.length,
            })}
          </Typography>
        </Box>
      )}
    </TableContainer>
  );
}