All files / components/Courses InstructorAdminCoursesTable.jsx

100% Statements 91/91
100% Branches 35/35
100% Functions 28/28
100% Lines 90/90

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 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401                                                    110x   110x 301x 2x       299x 200x   99x       31x     68x     110x 110x 110x 110x 110x 110x   110x 5x 5x     110x 2x 2x     110x                 301x 301x                       301x 301x                                         301x 301x 232x       5x             69x                                 110x 4x                   110x 4x                       110x               110x 2x     110x 2x 1x     1x     110x 2x 2x     110x 2x 1x 1x     110x 3x 3x 3x     110x   2x 1x 1x     110x                 110x                 110x                 110x 11x 11x     110x 4x 4x     110x 4x 4x     110x 4x 4x 4x     110x           301x 301x 108x     11x               193x                     122x       122x             122x 82x                                       40x           8x 8x                       110x                                                           1x                                   2x           5x                      
import OurTable from "main/components/Common/OurTable";
import { hasRole } from "main/utils/currentUser";
import { Tooltip, OverlayTrigger, Button, Fade } from "react-bootstrap";
import { useState } from "react";
import { useBackendMutation } from "main/utils/useBackend";
import { toast } from "react-toastify";
import UpdateInstructorForm from "main/components/Courses/UpdateInstructorForm";
import CourseModal from "main/components/Courses/CourseModal";
import Modal from "react-bootstrap/Modal";
import { useLocation } from "react-router";
import LinkToScaffold from "main/components/Scaffold/LinkToScaffold";
import LinkToSettings from "main/components/Scaffold/LinkToSettings";
 
export default function InstructorAdminCoursesTable({
  courses,
  storybook = false,
  currentUser,
  testId = "InstructorAdminCoursesTable",
  enableInstructorUpdate = false,
  deleteCourseButton = false,
  canEditCourse,
  mutationQueryKeys = [
    "/api/courses/list/admins",
    "/api/courses/list/instructors",
  ],
}) {
  const location = useLocation();
 
  const canEdit = (row) => {
    if (canEditCourse !== undefined) {
      return typeof canEditCourse === "function"
        ? canEditCourse(row)
        : canEditCourse;
    }
    if (hasRole(currentUser, "ROLE_ADMIN")) {
      return true;
    }
    if (
      hasRole(currentUser, "ROLE_INSTRUCTOR") &&
      row.original.instructorEmail === currentUser.root.user.email
    ) {
      return true;
    }
 
    return false;
  };
 
  const [showModal, setShowModal] = useState(false);
  const [selectedCourse, setSelectedCourse] = useState(null);
  const [showCourseEditModal, setShowCourseEditModal] = useState(false);
  const [selectedCourseForEdit, setSelectedCourseForEdit] = useState(null);
  const [showDeleteModal, setShowDeleteModal] = useState(false);
  const [courseToDelete, setCourseToDelete] = useState(null);
 
  const handleShowCourseEditModal = (course) => {
    setSelectedCourseForEdit(course);
    setShowCourseEditModal(true);
  };
 
  const handleCloseCourseEditModal = () => {
    setShowCourseEditModal(false);
    setSelectedCourseForEdit(null);
  };
 
  const columns = [
    {
      header: "id",
      accessorKey: "id", // accessor is the "key" in the data
    },
    {
      header: "Course Name",
      id: "courseName",
      cell: ({ cell }) => {
        const course = cell.row.original;
        return (
          <LinkToScaffold
            course={course}
            testId={`InstructorAdminCoursesTable-cell-row-${cell.row.index}-col-${cell.column.id}-link`}
          />
        );
      },
    },
    {
      header: "Settings",
      id: "settings",
      cell: ({ cell }) => {
        const course = cell.row.original;
        return (
          <LinkToSettings
            course={course}
            testId={`InstructorAdminCoursesTable-cell-row-${cell.row.index}-col-${cell.column.id}-link`}
          />
        );
      },
    },
    {
      header: "Term",
      accessorKey: "term",
    },
    {
      header: "School",
      id: "school",
      accessorKey: "school.displayName",
    },
    {
      header: "Edit",
      id: "edit",
      cell: ({ cell }) => {
        const canEditCourse = canEdit(cell.row);
        if (canEditCourse) {
          return (
            <Button
              variant="outline-primary"
              size="sm"
              onClick={() => handleShowCourseEditModal(cell.row.original)}
              data-testid={`${testId}-cell-row-${cell.row.index}-col-edit-button`}
            >
              Edit
            </Button>
          );
        } else {
          return (
            <span
              data-testid={`${testId}-cell-row-${cell.row.index}-col-edit-no-permission`}
            ></span>
          );
        }
      },
    },
    {
      header: "Students",
      accessorKey: "numStudents",
    },
    {
      header: "Staff",
      accessorKey: "numStaff",
    },
  ];
  const cellToAxiosParamsEdit = (formData) => {
    return {
      url: `/api/courses/updateInstructor`,
      method: "PUT",
      params: {
        courseId: formData.courseId,
        instructorEmail: formData.instructorEmail,
      },
    };
  };
 
  const cellToAxiosParamsCourseEdit = (formData) => {
    return {
      url: `/api/courses`,
      method: "PUT",
      params: {
        courseId: formData.courseId,
        courseName: formData.courseName,
        term: formData.term,
        school: formData.school,
      },
    };
  };
 
  const cellToAxiosParamsDelete = (course) => ({
    url: "/api/courses",
    method: "DELETE",
    params: {
      courseId: course.id,
    },
  });
 
  const onInstructorUpdateSuccess = () => {
    handleCloseModal();
  };
 
  const onInstructorUpdateError = (error) => {
    if (error.response.data.message)
      toast(
        `Was not able to update instructor:\n${error.response.data.message}`,
      );
    else toast(`Was not able to update instructor:\n${error.message}`);
  };
 
  const onCourseUpdateSuccess = () => {
    handleCloseCourseEditModal();
    toast("Course updated successfully");
  };
 
  const onCourseUpdateError = (error) => {
    if (error.response.data.message)
      toast(`Was not able to update course:\n${error.response.data.message}`);
    else toast(`Was not able to update course:\n${error.message}`);
  };
 
  const onDeleteSuccess = () => {
    toast("Course deleted successfully");
    setShowDeleteModal(false);
    setCourseToDelete(null);
  };
 
  const onDeleteError = (error) => {
    // Stryker disable next-line OptionalChaining : defensive coding for error shape
    if (error.response?.data?.message)
      toast(`Could not delete course:\n${error.response.data.message}`);
    else toast(`Could not delete course:\n${error.message}`);
  };
 
  const editMutation = useBackendMutation(
    cellToAxiosParamsEdit,
    {
      onSuccess: onInstructorUpdateSuccess,
      onError: onInstructorUpdateError,
    },
    mutationQueryKeys,
  );
 
  const courseEditMutation = useBackendMutation(
    cellToAxiosParamsCourseEdit,
    {
      onSuccess: onCourseUpdateSuccess,
      onError: onCourseUpdateError,
    },
    mutationQueryKeys,
  );
 
  const deleteMutation = useBackendMutation(
    cellToAxiosParamsDelete,
    {
      onSuccess: onDeleteSuccess,
      onError: onDeleteError,
    },
    mutationQueryKeys,
  );
 
  const handleShowModal = (course) => {
    setSelectedCourse(course);
    setShowModal(true);
  };
 
  const handleCloseModal = () => {
    setShowModal(false);
    setSelectedCourse(null);
  };
 
  const handleUpdateInstructor = async (formData) => {
    formData.courseId = selectedCourse.id;
    editMutation.mutate(formData);
  };
 
  const handleUpdateCourse = async (formData) => {
    formData.courseId = selectedCourseForEdit.id;
    formData.school = formData.school.key;
    courseEditMutation.mutate(formData);
  };
 
  const columnsWithInstall = [
    ...columns,
    {
      header: "Instructor",
      accessorKey: "instructorEmail",
      cell: ({ cell }) => {
        const isAdmin = hasRole(currentUser, "ROLE_ADMIN");
        if (isAdmin && enableInstructorUpdate) {
          return (
            <Button
              variant="link"
              onClick={() => handleShowModal(cell.row.original)}
              data-testid={`${testId}-cell-row-${cell.row.index}-col-instructorEmail-button`}
              style={{ padding: 0, textDecoration: "underline" }}
            >
              {cell.row.original.instructorEmail}
            </Button>
          );
        } else {
          return cell.row.original.instructorEmail;
        }
      },
    },
    ...(deleteCourseButton
      ? [
          {
            header: "Delete",
            id: "delete",
            cell: ({ cell }) => {
              const canDelete =
                cell.row.original.numStudents === 0 &&
                cell.row.original.numStaff === 0;
 
              // Stryker disable ObjectLiteral,StringLiteral : cosmetic styling for disabled button
              const disabledButtonStyle = {
                background: "#A0A0A0",
                padding: "1px",
                borderRadius: "4px",
              };
              // Stryker restore ObjectLiteral,StringLiteral
 
              if (!canDelete) {
                return (
                  <OverlayTrigger
                    placement="right"
                    overlay={
                      <Tooltip>
                        Cannot delete a course with active students or staff
                      </Tooltip>
                    }
                  >
                    <span className="d-inline-block">
                      <div style={disabledButtonStyle}>
                        <Button variant="light" size="sm" disabled>
                          Delete
                        </Button>
                      </div>
                    </span>
                  </OverlayTrigger>
                );
              }
 
              return (
                <Button
                  variant="danger"
                  size="sm"
                  data-testid={`${testId}-cell-row-${cell.row.index}-col-delete-button`}
                  onClick={() => {
                    setCourseToDelete(cell.row.original);
                    setShowDeleteModal(true);
                  }}
                >
                  Delete
                </Button>
              );
            },
          },
        ]
      : []),
  ];
 
  return (
    <>
      <Modal
        data-testid={`${testId}-modal`}
        show={showModal}
        onHide={handleCloseModal}
        centered={true}
      >
        <Modal.Header closeButton>
          <Modal.Title>Update Instructor</Modal.Title>
        </Modal.Header>
        <Modal.Body>
          <UpdateInstructorForm
            handleUpdateInstructor={handleUpdateInstructor}
            initialContents={selectedCourse}
          />
        </Modal.Body>
      </Modal>
      <CourseModal
        showModal={showCourseEditModal}
        toggleShowModal={setShowCourseEditModal}
        onSubmitAction={handleUpdateCourse}
        initialContents={selectedCourseForEdit}
        buttonText="Update"
        modalTitle="Edit Course"
      />
 
      <Modal
        data-testid="InstructorAdminCoursesTable-delete-modal"
        show={showDeleteModal}
        onHide={() => setShowDeleteModal(false)}
        centered
      >
        <Modal.Header closeButton>
          <Modal.Title>Confirm Delete</Modal.Title>
        </Modal.Header>
 
        <Modal.Body>
          {courseToDelete && (
            <p>
              Please confirm that you really want to delete course{" "}
              <strong>{courseToDelete.courseName}</strong>. This action cannot
              be undone.
            </p>
          )}
        </Modal.Body>
 
        <Modal.Footer>
          <Button variant="secondary" onClick={() => setShowDeleteModal(false)}>
            Do not delete
          </Button>
 
          <Button
            variant="danger"
            onClick={() => deleteMutation.mutate(courseToDelete)}
          >
            Yes, Delete
          </Button>
        </Modal.Footer>
      </Modal>
 
      <OurTable data={courses} columns={columnsWithInstall} testid={testId} />
    </>
  );
}