All files / components/Courses InstructorCoursesTable.jsx

100% Statements 398/398
100% Branches 67/67
100% Functions 32/32
100% Lines 398/398

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 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 5131x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x   1x 84x 84x 84x 84x 84x 84x 84x 84x   84x 318x 178x 178x 140x 140x 140x 318x 70x 70x   70x 70x   84x 66x 66x 58x 15x 66x 14x 14x   52x 52x   84x 84x 84x 84x 84x 84x   84x 5x 5x 5x   84x 2x 2x 2x   84x 3x 3x 3x   84x 3x 3x 3x   84x 84x 84x 84x 84x 84x 84x 84x 84x 318x 318x 318x 318x 318x         318x 318x 318x   318x       318x 84x 84x 84x 84x 84x 84x 84x 84x 84x 84x 84x 84x 84x 318x 318x 248x 248x 248x 248x 248x 248x 248x       310x 70x 70x 70x     70x 318x 84x 84x 84x 84x 84x 84x 84x 84x 84x 84x 84x 21x 21x 21x 21x 66x 66x 14x 14x 14x 14x 14x 14x 14x       66x 52x 52x 52x 52x 52x         52x 52x 52x 52x 52x 52x 52x 52x           52x 66x 21x 21x 84x 4x 4x 4x 4x 4x 4x 4x 4x 4x   84x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x   84x 2x 2x 2x 2x 2x 2x 2x 2x   84x 2x 2x   84x 2x 1x 1x   1x 2x   84x 2x 2x 2x   84x 2x 1x 1x 2x   84x 2x 2x 2x   84x 84x 84x 84x 84x 84x 84x     84x 84x 84x 84x 84x 84x 84x     84x 84x 84x 84x 84x 84x     84x 11x 11x 11x   84x 4x 4x 4x   84x 4x 4x 4x   84x 4x 4x 4x   84x 2x 2x 2x   84x 4x   4x 4x 2x 2x 2x 2x 2x   84x 601x 320x 320x 585x 176x 176x 105x 105x 105x 601x 70x 70x   35x 35x   84x 283x 283x 283x 123x 275x 160x 160x 283x 283x   283x   84x 84x 84x 84x 84x 84x 318x 318x 123x 123x 123x 123x 123x 123x 123x 123x           310x 35x 35x 35x     195x 160x 160x 160x 160x 160x 160x 160x 160x   160x 160x 160x 160x 160x 160x 160x   160x       160x 160x 160x 160x           160x 160x 160x 160x 160x 160x   160x 160x 160x             160x 318x 84x 84x 84x 84x 84x 318x 318x 132x 132x 132x 132x 132x 132x   132x     318x 186x 186x 318x 84x 84x   84x 84x 84x 84x 84x 84x 84x   84x 84x   84x 84x 84x 84x       84x 84x 84x 84x 84x 84x 84x   84x 84x 84x 84x 84x   84x 84x     84x 84x 84x   84x           84x 84x 84x 84x 84x 84x       84x 84x 84x 84x 84x         84x     84x  
import OurTable from "main/components/OurTable";
import { hasRole } from "main/utils/currentUser";
import { Tooltip, OverlayTrigger, Button } from "react-bootstrap";
import { Link } from "react-router";
import { useState } from "react";
import GithubSettingIcon from "main/components/Common/GithubSettingIcon";
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";
 
export default function InstructorCoursesTable({
  courses,
  storybook = false,
  currentUser,
  testId = "InstructorCoursesTable",
  enableInstructorUpdate = false,
  deleteCourseButton = false,
}) {
  const location = useLocation();
 
  const canEdit = (row) => {
    if (hasRole(currentUser, "ROLE_ADMIN")) {
      return true;
    }
    if (
      hasRole(currentUser, "ROLE_INSTRUCTOR") &&
      row.original.instructorEmail === currentUser.root.user.email
    ) {
      return true;
    }
 
    return false;
  };
 
  const canDelete = (row) => {
    if (
      hasRole(currentUser, "ROLE_ADMIN") &&
      row.original.numStudents === 0 &&
      row.original.numStaff === 0
    ) {
      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 [showCourseDeleteModal, setShowCourseDeleteModal] = useState(false);
  const [selectedCourseForDelete, setSelectedCourseForDelete] = useState(null);
 
  const handleShowCourseEditModal = (course) => {
    setSelectedCourseForEdit(course);
    setShowCourseEditModal(true);
  };
 
  const handleCloseCourseEditModal = () => {
    setShowCourseEditModal(false);
    setSelectedCourseForEdit(null);
  };
 
  const handleShowCourseDeleteModal = (course) => {
    setSelectedCourseForDelete(course);
    setShowCourseDeleteModal(true);
  };
 
  const handleCloseCourseDeleteModal = () => {
    setShowCourseDeleteModal(false);
    setSelectedCourseForDelete(null);
  };
 
  const columns = [
    {
      header: "id",
      accessorKey: "id", // accessor is the "key" in the data
    },
    {
      header: "Course Name",
      id: "courseName",
      cell: ({ cell }) => {
        return (
          <OverlayTrigger
            placement="right"
            overlay={
              <Tooltip id={`tooltip-coursename-${cell.row.index}`}>
                View course details
              </Tooltip>
            }
          >
            <Link
              to={`/instructor/courses/${cell.row.original.id}`}
              data-testid={`CoursesTable-cell-row-${cell.row.index}-col-${cell.column.id}-link`}
            >
              {cell.row.original.courseName}
            </Link>
          </OverlayTrigger>
        );
      },
    },
    {
      header: "Term",
      accessorKey: "term",
    },
    {
      header: "School",
      accessorKey: "school",
    },
    {
      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",
    },
  ];
  if (deleteCourseButton) {
    columns.push({
      header: "Delete",
      id: "delete",
      cell: ({ cell }) => {
        const canDeleteCourse = canDelete(cell.row);
        if (canDeleteCourse) {
          return (
            <Button
              variant="danger"
              size="sm"
              onClick={() => handleShowCourseDeleteModal(cell.row.original)}
              data-testid={`${testId}-cell-row-${cell.row.index}-col-delete-button`}
            >
              Delete
            </Button>
          );
        } else {
          return (
            <OverlayTrigger
              placement="top"
              overlay={
                <Tooltip id="tooltip-disabled">
                  Cannot delete a course with active students or staff
                </Tooltip>
              }
            >
              <span className="d-inline-block">
                <Button
                  variant="light"
                  size="sm"
                  disabled
                  style={{ pointerEvents: "none" }}
                  data-testid={`${testId}-cell-row-${cell.row.index}-col-delete-no-permission`}
                >
                  Delete
                </Button>
              </span>
            </OverlayTrigger>
          );
        }
      },
    });
  }
  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 cellToAxiosParamsCourseDelete = (formData) => {
    return {
      url: `/api/courses`,
      method: "DELETE",
      params: {
        courseId: formData.courseId,
      },
    };
  };
 
  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 onCourseDeleteSuccess = () => {
    handleCloseCourseDeleteModal();
    toast("Course deleted successfully");
  };
 
  const editMutation = useBackendMutation(
    cellToAxiosParamsEdit,
    {
      onSuccess: onInstructorUpdateSuccess,
      onError: onInstructorUpdateError,
    },
    ["/api/courses/allForAdmins", "/api/courses/allForInstructors"],
  );
 
  const courseEditMutation = useBackendMutation(
    cellToAxiosParamsCourseEdit,
    {
      onSuccess: onCourseUpdateSuccess,
      onError: onCourseUpdateError,
    },
    ["/api/courses/allForAdmins", "/api/courses/allForInstructors"],
  );
 
  const courseDeleteMutation = useBackendMutation(
    cellToAxiosParamsCourseDelete,
    {
      onSuccess: onCourseDeleteSuccess,
    },
    ["/api/courses/allForAdmins", "/api/courses/allForInstructors"],
  );
 
  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;
    courseEditMutation.mutate(formData);
  };
 
  const handleDeleteCourse = async (formData) => {
    formData.courseId = selectedCourseForDelete.id;
    courseDeleteMutation.mutate(formData);
  };
 
  const installCallback = (cell) => {
    sessionStorage.setItem("redirect", location.pathname);
 
    const url = `/api/courses/redirect?courseId=${cell.row.original.id}`;
    if (storybook) {
      window.alert(`would have navigated to: ${url}`);
      return;
    }
    window.location.href = url;
  };
 
  const canInstall = (row) => {
    if (row.original.orgName) {
      return false;
    }
    if (hasRole(currentUser, "ROLE_ADMIN")) {
      return true;
    }
    if (
      hasRole(currentUser, "ROLE_INSTRUCTOR") &&
      row.original.instructorEmail === currentUser.root.user.email
    ) {
      return true;
    }
 
    return false;
  };
 
  const renderTooltip = (cell) => {
    let set_message;
    const result = canInstall(cell.row);
    if (result) {
      set_message = `Click to install the GitHub app for ${cell.row.original.courseName}`;
    } else {
      set_message = `View organization associated with ${cell.row.original.courseName}.`;
    }
    return (
      <Tooltip id={`tooltip-orgname-${cell.row.index}`}>{set_message}</Tooltip>
    );
  };
 
  const columnsWithInstall = [
    ...columns,
    {
      header: "GitHub Org",
      id: "orgName",
      cell: ({ cell }) => {
        const result = canInstall(cell.row);
        if (result) {
          return (
            <OverlayTrigger placement="right" overlay={renderTooltip(cell)}>
              <span>
                <Button
                  variant={"primary"}
                  onClick={() => installCallback(cell)}
                  data-testid={`${testId}-cell-row-${cell.row.index}-col-${cell.column.id}-button`}
                >
                  Install GitHub App
                </Button>
              </span>
            </OverlayTrigger>
          );
        } else if (!cell.row.original.orgName) {
          return (
            <span
              data-testid={`${testId}-cell-row-${cell.row.index}-col-${cell.column.id}-no-org`}
            ></span>
          );
        } else {
          return (
            <div
              style={{
                display: "flex",
                justifyContent: "space-between",
                width: "100%",
              }}
              data-testid={`${testId}-cell-row-${cell.row.index}-col-${cell.column.id}-div`}
            >
              <OverlayTrigger placement="right" overlay={renderTooltip(cell)}>
                <span>
                  <a
                    href={`https://github.com/${cell.row.original.orgName}`}
                    target="_blank"
                    rel="noopener noreferrer"
                    data-testid={`${testId}-cell-row-${cell.row.index}-col-${cell.column.id}-github-link`}
                  >
                    {cell.row.original.orgName}
                  </a>
                </span>
              </OverlayTrigger>
              <OverlayTrigger
                placement="right"
                overlay={
                  <Tooltip id={`tooltip-geargithubicon-${cell.row.index}`}>
                    Manage settings for association between your GitHub
                    organization and this web application.
                  </Tooltip>
                }
              >
                <span>
                  <a
                    href={`https://github.com/organizations/${cell.row.original.orgName}/settings/installations/${cell.row.original.installationId}`}
                    target="_blank"
                    rel="noopener noreferrer"
                    data-testid={`CoursesTable-cell-row-${cell.row.index}-col-${cell.column.id}-github-settings-link`}
                  >
                    <GithubSettingIcon
                      size={24}
                      data-testid={`CoursesTable-cell-row-${cell.row.index}-col-${cell.column.id}-gear-github-icon`}
                    />
                  </a>
                </span>
              </OverlayTrigger>
            </div>
          );
        }
      },
    },
    {
      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;
        }
      },
    },
  ];
 
  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
        show={showCourseDeleteModal}
        onHide={handleCloseCourseDeleteModal}
        centered
        data-testid="CourseModal-delete"
      >
        <Modal.Header closeButton>
          <Modal.Title>Delete Course</Modal.Title>
        </Modal.Header>
 
        <Modal.Body>
          {selectedCourseForDelete && (
            <p>
              Please confirm that you really want to delete course&nbsp;
              <strong>{selectedCourseForDelete.courseName}</strong>. This action
              cannot be undone.
            </p>
          )}
        </Modal.Body>
 
        <Modal.Footer>
          <Button
            variant="secondary"
            onClick={handleCloseCourseDeleteModal}
            data-testId="CourseModal-closeButton"
          >
            Do not delete
          </Button>
 
          <Button
            variant="danger"
            onClick={handleDeleteCourse}
            data-testid="CourseModal-confirm"
          >
            Yes, Delete
          </Button>
        </Modal.Footer>
      </Modal>
      <OurTable data={courses} columns={columnsWithInstall} testid={testId} />
    </>
  );
}