All files / components/TabComponent StaffTabComponent.jsx

100% Statements 44/44
100% Branches 10/10
100% Functions 18/18
100% Lines 43/43

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                                                          276x 276x 276x             276x   276x                     276x 2x 2x 2x                   276x 3x   3x 3x     276x   2x             276x     1x   1x     1x                 276x 2x     276x 2x     276x 2x       276x 1x     276x       1x                           1x                           4x                                   3x                                                                               5x                   349x 349x 349x 329x 20x     1x 19x 1x   18x                                                 436x                                            
import { toast } from "react-toastify";
import { useBackend, useBackendMutation } from "main/utils/useBackend";
import React, { useState } from "react";
import {
  Button,
  Col,
  Form,
  ModalBody,
  ModalHeader,
  Row,
  OverlayTrigger,
  Tooltip,
} from "react-bootstrap";
import { BsInfoCircle } from "react-icons/bs";
import CourseStaffForm from "main/components/CourseStaff/CourseStaffForm";
import CourseStaffCSVUploadForm from "main/components/CourseStaff/CourseStaffCSVUploadForm";
import CourseStaffTable from "main/components/CourseStaff/CourseStaffTable";
import Modal from "react-bootstrap/Modal";
import CourseEmailsCard from "main/components/Emails/CourseEmailsCard";
import { courseEmailsQueryKey } from "main/utils/courseEmailsUtils";
 
export default function StaffTabComponent({
  courseId,
  testIdPrefix,
  currentUser,
  isInstructor = true,
  instructorEmail,
  courseLoaded = false,
}) {
  const [postModal, showPostModal] = useState(false);
  const [csvModal, setCsvModal] = useState(false);
  const { data: courseStaff } = useBackend(
    [`/api/coursestaff/course?courseId=${courseId}`],
    // Stryker disable next-line StringLiteral : GET and empty string are equivalent
    { method: "GET", url: `/api/coursestaff/course?courseId=${courseId}` },
    [],
    true,
  );
  const [searchTerm, setSearchTerm] = useState("");
 
  const objectToAxiosParamsPost = (staff) => ({
    url: `/api/coursestaff/post`,
    method: "POST",
    params: {
      courseId: courseId,
      firstName: staff.firstName,
      lastName: staff.lastName,
      email: staff.email,
    },
  });
 
  const objectToAxiosParamsCSV = (formData) => {
    const file = new FormData();
    file.append("file", formData.upload[0]);
    return {
      url: `/api/coursestaff/upload/csv`,
      data: file,
      params: {
        courseId: courseId,
      },
      method: "POST",
    };
  };
 
  const onSuccessStaff = (modalFn) => {
    toast("Staff roster successfully updated.");
    // Clear the search filter to show the updated roster
    setSearchTerm("");
    modalFn(false);
  };
 
  const staffPostMutation = useBackendMutation(
    objectToAxiosParamsPost,
    { onSuccess: () => onSuccessStaff(showPostModal) },
    [
      `/api/coursestaff/course?courseId=${courseId}`,
      courseEmailsQueryKey(courseId),
    ],
  );
 
  const staffCsvMutation = useBackendMutation(
    objectToAxiosParamsCSV,
    {
      onSuccess: () => onSuccessStaff(setCsvModal),
      onError: (error) => {
        toast.error(
          `Error uploading CSV: ${JSON.stringify(error.response.data, null, 2)}`,
        );
        setCsvModal(false);
      },
    },
    [
      `/api/coursestaff/course?courseId=${courseId}`,
      courseEmailsQueryKey(courseId),
    ],
  );
 
  const handlePostSubmit = (staff) => {
    staffPostMutation.mutate(staff);
  };
 
  const handleCsvSubmit = (formData) => {
    staffCsvMutation.mutate(formData);
  };
 
  const openCsvHelp = () => {
    window.open("/help/csv#staff-information", "_blank");
  };
 
  // The download uses the same format as Upload Staff CSV
  const downloadCsv = () => {
    window.open(`/api/csv/staff?courseId=${courseId}`, "_blank");
  };
 
  return (
    <div data-testid={`${testIdPrefix}-StaffTabComponent`}>
      <Modal
        show={postModal}
        onHide={() => showPostModal(false)}
        centered={true}
        data-testid={`${testIdPrefix}-post-modal`}
      >
        <ModalHeader closeButton>Add Staff Member</ModalHeader>
        <ModalBody>
          <CourseStaffForm
            submitAction={handlePostSubmit}
            cancelDisabled={true}
          />
        </ModalBody>
      </Modal>
      <Modal
        show={csvModal}
        onHide={() => setCsvModal(false)}
        centered={true}
        data-testid={`${testIdPrefix}-csv-modal`}
      >
        <ModalHeader closeButton>Upload Staff CSV</ModalHeader>
        <ModalBody>
          <CourseStaffCSVUploadForm submitAction={handleCsvSubmit} />
        </ModalBody>
      </Modal>
      {isInstructor && (
        <Row sm={3} className="p-2">
          <Col>
            <div className="d-flex align-items-center position-relative">
              <Button
                onClick={() => setCsvModal(true)}
                data-testid={`${testIdPrefix}-csv-button`}
                className="w-100 pe-5"
              >
                Upload Staff CSV
              </Button>
              <CsvHelpIcon
                tooltipId="csv-help-tooltip"
                placement="right"
                onClick={openCsvHelp}
                testId={`${testIdPrefix}-csv-info-icon`}
              >
                Staff CSV Upload Format Help
              </CsvHelpIcon>
            </div>
          </Col>
          <Col>
            <Button
              onClick={() => showPostModal(true)}
              data-testid={`${testIdPrefix}-post-button`}
              className="w-100"
            >
              Add Staff Member
            </Button>
          </Col>
          <Col>
            <div className="d-flex align-items-center position-relative">
              <Button
                onClick={downloadCsv}
                data-testid={`${testIdPrefix}-download-csv-button`}
                className="w-100 pe-5"
              >
                Download Staff CSV
              </Button>
              {/* the button is at the right edge of the page, so the tooltip opens to the left */}
              <CsvHelpIcon
                tooltipId="csv-download-help-tooltip"
                placement="left"
                onClick={openCsvHelp}
                testId={`${testIdPrefix}-download-csv-info-icon`}
              >
                Staff CSV Download Format Help (same format as upload)
              </CsvHelpIcon>
            </div>
          </Col>
        </Row>
      )}
      <Row className="mb-1">
        <Form>
          <Form.Group as={Row} controlId="searchFilter">
            <Form.Label column sm={2}>
              Search Staff:
            </Form.Label>
            <Col sm={10}>
              <Form.Control
                type="text"
                placeholder="Search by name, email, or Github Login"
                value={searchTerm}
                onChange={(e) => setSearchTerm(e.target.value)}
                data-testid={`${testIdPrefix}-search`}
              />
            </Col>
          </Form.Group>
        </Form>
      </Row>
      <Row>
        <CourseStaffTable
          staff={courseStaff.filter((staffMember) => {
            const searchTermLower = searchTerm.toLowerCase();
            const fullName = `${staffMember.firstName} ${staffMember.lastName}`;
            if (staffMember.email.toLowerCase().includes(searchTermLower)) {
              return true;
            } else if (
              staffMember.githubLogin?.toLowerCase().includes(searchTermLower)
            ) {
              return true;
            } else if (fullName.toLowerCase().includes(searchTermLower)) {
              return true;
            }
            return false;
          })}
          currentUser={currentUser}
          courseId={courseId}
          testIdPrefix={`${testIdPrefix}-CourseStaffTable`}
          isInstructor={isInstructor}
          instructorEmail={instructorEmail}
          courseLoaded={courseLoaded}
        />
      </Row>
      <CourseEmailsCard
        courseId={courseId}
        type="STAFF"
        testIdPrefix={`${testIdPrefix}-StaffEmailsCard`}
      />
    </div>
  );
}
 
/**
 * An info icon placed over the right end of a CSV button; hovering shows the
 * tooltip given as children on the given side of the icon, and clicking calls
 * onClick (which opens the CSV help page).
 */
function CsvHelpIcon({ tooltipId, placement, onClick, testId, children }) {
  return (
    <OverlayTrigger
      placement={placement}
      overlay={<Tooltip id={tooltipId}>{children}</Tooltip>}
    >
      <BsInfoCircle
        onClick={onClick}
        style={{
          position: "absolute",
          top: "50%",
          right: "0.75rem",
          transform: "translateY(-50%)",
          color: "#fff",
          cursor: "pointer",
          fontSize: "0.9rem",
          userSelect: "none",
        }}
        data-testid={testId}
      />
    </OverlayTrigger>
  );
}