All files / components/Sections SectionsTable.jsx

100% Statements 49/49
100% Branches 32/32
100% Functions 22/22
100% Lines 49/49

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                                              5x 1x                   5x 2x 1x       1x           5x 2x   2x   2x     5x   554x 554x   554x 400x     154x   308x   308x                     74x 4x     68x 4x         64x 64x           64x 1x       1x     64x   64x     75x                     2330x                                         2330x           2330x                       554x             2330x         2330x         2330x         2330x         2330x         2330x         2330x         2330x           2330x 597x 1733x 936x   797x           1x                   74x            
import SectionsTableBase from "main/components/SectionsTableBase";
 
import { useBackendMutation } from "main/utils/useBackend";
import { toast } from "react-toastify";
import { useCurrentUser } from "main/utils/currentUser.jsx";
 
import {
  formatDays,
  formatInstructors,
  formatLocation,
  formatTime,
  formatStatus,
  enrollmentFraction,
  getSection,
  getSectionField,
  renderInfoLink,
  renderDetailPageLink,
  shouldShowAddToScheduleLink,
  getQuarter,
} from "main/utils/sectionUtils.jsx";
import { yyyyqToQyy } from "main/utils/quarterUtilities";
import AddToScheduleModal from "main/components/PersonalSchedules/AddToScheduleModal";
 
const objectToAxiosParams = (data) => {
  return {
    url: "/api/courses/post",
    method: "POST",
    params: {
      enrollCd: data.enrollCd.toString(),
      psId: data.psId.toString(),
    },
  };
};
 
const onSuccess = (response) => {
  if (response.length < 3) {
    toast(
      `New course Created - id: ${response[0].id} enrollCd: ${response[0].enrollCd}`,
    );
  } else {
    toast(
      `Course ${response[0].enrollCd} replaced old section ${response[2].enrollCd} with new section ${response[1].enrollCd}`,
    );
  }
};
 
const onError = (error) => {
  console.error("onError: error=", error);
  const message =
    error.response.data?.message ||
    `An unexpected error occurred adding the schedule: ${JSON.stringify(error)}`;
  toast.error(message);
};
 
const formatGeneralEducation = (row) => {
  const primaryRow =
    row.depth === 0 ? row.original : row.getParentRow()?.original;
  const geList = primaryRow?.generalEducation;
 
  if (!Array.isArray(geList) || geList.length === 0) {
    return "";
  }
 
  return geList
    .map((ge) => {
      const college = ge?.geCollege?.trim?.();
 
      return college;
    })
    .filter(Boolean)
    .join(", ");
};
 
export default function SectionsTable({
  sections,
  schedules = [],
  includeGeneralEducation = false,
}) {
  if (!(schedules instanceof Array)) {
    throw new Error("schedules prop must be an array");
  }
 
  if (schedules.length > 0 && !Object.hasOwn(schedules[0], "id")) {
    throw new Error(
      "schedules prop must be an array of objects with an 'id' property",
    );
  }
 
  const { data: currentUser } = useCurrentUser();
  const mutation = useBackendMutation(
    objectToAxiosParams,
    { onSuccess, onError },
    [],
  );
 
  const addToScheduleCallback = (section, schedule, mutation) => {
    const dataFinal = {
      enrollCd: section.enrollCode,
      psId: schedule,
    };
    mutation.mutate(dataFinal);
  };
 
  const testid = "SectionsTable";
 
  const columns = [
    {
      id: "expander", // Unique ID for the expander column
      header: ({ table }) => (
        <button
          data-testid={`${testid}-expand-all-rows`}
          {...{
            onClick: table.getToggleAllRowsExpandedHandler(),
          }}
        >
          {table.getIsAllRowsExpanded() ? "➖" : "➕"}
        </button>
      ),
      cell: ({ row }) =>
        row.getCanExpand() ? (
          <button
            data-testid={`${testid}-row-${row.index}-expand-button`}
            {...{
              onClick: row.getToggleExpandedHandler(),
              style: { cursor: "pointer" },
            }}
          >
            {row.getIsExpanded() ? "➖" : "➕"}
          </button>
        ) : (
          <span data-testid={`${testid}-row-${row.index}-cannot-expand`} />
        ),
      // This is important for indenting sub-rows
      // We'll apply this style in the render, but you can define it here too
      // For sub-rows, you might want to adjust cell content for clarity
    },
    {
      header: "Quarter",
      accessorKey: "quarter",
      cell: ({ row }) =>
        row.original.quarter ? yyyyqToQyy(row.original.quarter) : "",
    },
    {
      accessorKey: "courseId",
      header: "Course ID",
      cell: ({ row }) => {
        return renderDetailPageLink(row, testid);
      },
    },
    {
      accessorKey: "title",
      header: "Title",
    },
    ...(includeGeneralEducation
      ? [
          {
            id: "generalEducation",
            header: "GE Areas",
            cell: ({ row }) => formatGeneralEducation(row),
          },
        ]
      : []),
    {
      header: "Status",
      accessorKey: "status",
      cell: ({ row }) => formatStatus(getSection(row)),
    },
    {
      header: "Enrolled",
      accessorKey: "enrolled",
      cell: ({ row }) => enrollmentFraction(row),
    },
    {
      id: "location",
      header: "Location",
      cell: ({ row }) => formatLocation(getSection(row).timeLocations),
    },
    {
      id: "days",
      header: "Days",
      cell: ({ row }) => formatDays(getSection(row).timeLocations),
    },
    {
      id: "time",
      header: "Time",
      cell: ({ row }) => formatTime(getSection(row).timeLocations),
    },
    {
      id: "instructor",
      header: "Instructor",
      cell: ({ row }) => formatInstructors(getSection(row).instructors),
    },
    {
      accessorKey: "enrollCode",
      header: "Enroll Code",
      cell: ({ row }) => getSectionField(row, "enrollCode"),
    },
    {
      header: "Info",
      id: "info",
      cell: ({ row }) => renderInfoLink(row, testid),
    },
    {
      header: "Action",
      id: "action",
      cell: ({ row }) => {
        if (!currentUser.loggedIn) {
          return <span data-testid={`${testid}-row-${row.id}-not-logged-in`} />;
        } else if (!shouldShowAddToScheduleLink(row)) {
          return <span data-testid={`${testid}-row-${row.id}-no-action`} />;
        }
        return (
          <div className="d-flex align-items-center gap-2">
            <AddToScheduleModal
              section={getSection(row)}
              quarter={getQuarter(row)}
              onAdd={(section, schedule) =>
                addToScheduleCallback(section, schedule, mutation)
              }
              schedules={schedules}
              testid={`${testid}-cell-row-${row.id}-col-action`}
            />
          </div>
        );
      },
    },
  ];
  return (
    <>
      <SectionsTableBase columns={columns} data={sections} testid={testid} />
    </>
  );
}