All files / components/MenuItem MenuItemTable.js

100% Statements 25/25
100% Branches 12/12
100% Functions 8/8
100% Lines 23/23

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          27x 27x 27x 1x 1x     27x 3x 3x     27x 35x 8x 27x   68x   49x 27x 49x 25x     27x                     35x         27x 3x     3x     27x    
import OurTable, { ButtonColumn } from "../OurTable";
import { hasRole } from "../../utils/currentUser";
import { useNavigate } from "react-router-dom";
 
export default function MenuItemTable({ menuItems, currentUser }) {
  const testid = "MenuItemTable";
  const navigate = useNavigate();
  const reviewCallback = async (_cell) => {
    const itemId = _cell.row.original.id;
    navigate(`/reviews/post/${itemId}`);
  };
 
  const viewCallback = async (_cell) => {
    const itemId = _cell.row.original.id;
    navigate(`/reviews/${itemId}`);
  };
 
  const calculateAverageRating = (reviews) => {
    if (!reviews || !Array.isArray(reviews) || reviews.length === 0)
      return "No reviews";
    const validRatings = reviews
      .filter(
        (r) => r && typeof r === "object" && typeof r.itemsStars === "number",
      )
      .map((r) => r.itemsStars);
    if (validRatings.length === 0) return "No ratings";
    const avg = validRatings.reduce((a, b) => a + b, 0) / validRatings.length;
    return avg.toFixed(1);
  };
 
  const columns = [
    {
      Header: "Item Name",
      accessor: "name",
    },
    {
      Header: "Station",
      accessor: "station",
    },
    {
      Header: "Average Rating",
      accessor: (row) => calculateAverageRating(row.reviews),
      id: "averageRating",
    },
  ];
 
  if (hasRole(currentUser, "ROLE_USER")) {
    columns.push(
      ButtonColumn("Review Item", "warning", reviewCallback, testid),
    );
    columns.push(ButtonColumn("All Reviews", "warning", viewCallback, testid));
  }
 
  return <OurTable columns={columns} data={menuItems} testid={testid} />;
}