All files / components/Teams TeamsTable.jsx

100% Statements 76/76
100% Branches 29/29
100% Functions 29/29
100% Lines 68/68

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                                            456x 456x 456x 456x   456x             456x   456x 456x   456x                     456x 456x               456x 1x 1x     456x 1x     456x 2x     456x 2x     456x 1x     456x 1x     456x                   456x           456x           456x           456x                   456x                     456x                 456x                 456x           456x           456x           456x       1x 1x 4x   1x             2x 2x 1x       1x                       456x 3x     456x 2x 2x     456x 1x 1x 1x           456x                                                               456x                                             456x         1x   1x                             2x                           1x                   1x                             241x                                         6x 6x 6x                     2x 2x                                                     1x                                
import React from "react";
import { Accordion, Button } from "react-bootstrap";
 
import { useBackendMutation } from "main/utils/useBackend";
import { hasRole } from "main/utils/currentUser";
import OurTable, { ButtonColumn } from "main/components/OurTable";
import { toast } from "react-toastify";
import { useState } from "react";
import { useBackend } from "main/utils/useBackend";
 
import Modal from "react-bootstrap/Modal";
import { ModalBody, ModalHeader } from "react-bootstrap";
import TeamMemberForm from "main/components/Teams/TeamMemberForm";
 
export default function TeamsTable({
  teams,
  currentUser,
  courseId,
  testIdPrefix = "TeamsTable",
  instructorView = true,
  canManageTeams,
}) {
  const [postMemberModal, setPostMemberModal] = useState(false);
  const [selectedTeam, setSelectedTeam] = useState(null);
  const [errorPostMemberModal, setErrorPostMemberModal] = useState(false);
  const [selectedTeamKeys, setSelectedTeamKeys] = useState();
  const canManage =
    canManageTeams ??
    (instructorView && hasRole(currentUser, "ROLE_INSTRUCTOR"));
  // Each team's accordion item is keyed by its id, so the same teams stay open
  // when the list of teams shown changes (e.g. when it is searched). Which
  // teams are open is a single piece of state, so Expand All and Collapse All
  // each cause a single re-render. Instructors start with every team closed;
  // students, who usually have one or two teams, start with them all open.
  const teamKey = (team) => `${team.id}`;
  // Stryker disable next-line ArrayDeclaration : a key that matches no team opens no team, just like no key
  const defaultOpenTeamKeys = instructorView ? [] : teams.map(teamKey);
  const openTeamKeys = selectedTeamKeys ?? defaultOpenTeamKeys;
 
  const { data: rosterStudents } = useBackend(
    [`/api/rosterstudents/course/${courseId}`],
    // Stryker disable next-line all : GET and empty string are equivalent
    { method: "GET", url: `/api/rosterstudents/course/${courseId}` },
    [],
    true,
    { enabled: instructorView },
  );
 
  // The members of a staff team are the course staff, so they are only needed
  // when there is a staff team to show.
  const hasStaffTeam = teams.some((team) => team.isStaffTeam);
  const { data: courseStaff } = useBackend(
    [`/api/coursestaff/course?courseId=${courseId}`],
    // Stryker disable next-line all : GET and empty string are equivalent
    { method: "GET", url: `/api/coursestaff/course?courseId=${courseId}` },
    [],
    true,
    { enabled: instructorView && hasStaffTeam },
  );
  const onSuccessMember = (modalFn) => {
    toast("Member added successfully");
    modalFn(false);
  };
 
  const onDeleteMember = () => {
    toast("Member removed successfully");
  };
 
  const onDeleteTeam = () => {
    toast("Team removed successfully");
  };
 
  const onDeleteGithubTeam = () => {
    toast("Delete GitHub team job launched successfully");
  };
 
  const onDeleteGithubMember = () => {
    toast("Delete GitHub team member job launched successfully");
  };
 
  const onAddGithubMember = () => {
    toast("Add GitHub team member job launched successfully");
  };
 
  const cellToAxiosParamsPost = (data) => ({
    url: `/api/teams/addMember`,
    method: "POST",
    params: {
      courseId: courseId,
      teamId: selectedTeam.id,
      rosterStudentId: data.rosterStudentId,
    },
  });
 
  const cellToAxiosParamDeleteTeam = (team) => ({
    method: "DELETE",
    url: `/api/teams`,
    params: { id: team.id, courseId: courseId },
  });
 
  const cellToAxiosParamDeleteMember = (member) => ({
    method: "DELETE",
    url: `/api/teams/removeMember`,
    params: { teamMemberId: member.id, courseId: courseId },
  });
 
  const cellToAxiosParamDeleteGithubTeam = (team) => ({
    method: "POST",
    url: `/api/jobs/launch/deleteTeamFromGithub`,
    params: { githubTeamId: team.githubTeamId, courseId: courseId },
  });
 
  const cellToAxiosParamDeleteGithubMember = (data) => ({
    method: "POST",
    url: `/api/jobs/launch/deleteTeamMemberFromGithub`,
    params: {
      memberGithubLogin: data.memberGithubLogin,
      githubTeamId: data.githubTeamId,
      courseId: courseId,
    },
  });
 
  const cellToAxiosParamAddGithubMember = (data) => ({
    method: "POST",
    url: `/api/jobs/launch/addTeamMemberToGithub`,
    params: {
      memberGithubLogin: data.memberGithubLogin,
      githubTeamId: data.githubTeamId,
      teamMemberId: data.teamMemberId,
      courseId: courseId,
    },
  });
 
  const deleteTeamMutation = useBackendMutation(
    cellToAxiosParamDeleteTeam,
    { onSuccess: onDeleteTeam },
    [
      `/api/teams/all?courseId=${courseId}`,
      `/api/rosterstudents/course/${courseId}`,
    ],
  );
 
  const deleteMemberMutation = useBackendMutation(
    cellToAxiosParamDeleteMember,
    { onSuccess: onDeleteMember },
    [
      `/api/teams/all?courseId=${courseId}`,
      `/api/rosterstudents/course/${courseId}`,
    ],
  );
 
  const deleteGithubTeamMutation = useBackendMutation(
    cellToAxiosParamDeleteGithubTeam,
    { onSuccess: onDeleteGithubTeam },
    [`/api/jobs/launch/deleteTeamFromGithub`],
  );
 
  const deleteGithubMemberMutation = useBackendMutation(
    cellToAxiosParamDeleteGithubMember,
    { onSuccess: onDeleteGithubMember },
    [`/api/jobs/launch/deleteTeamMemberFromGithub`],
  );
 
  const addGithubMemberMutation = useBackendMutation(
    cellToAxiosParamAddGithubMember,
    { onSuccess: onAddGithubMember },
    [`/api/jobs/launch/addTeamMemberToGithub`],
  );
 
  const memberPostMutation = useBackendMutation(
    cellToAxiosParamsPost,
    {
      onSuccess: (createdTeamMember) => {
        onSuccessMember(setPostMemberModal);
        const rosterStudent = rosterStudents.find(
          (rs) => rs.id === createdTeamMember.rosterStudent.id,
        );
        addGithubMemberMutation.mutate({
          memberGithubLogin: rosterStudent.githubLogin,
          githubTeamId: selectedTeam.githubTeamId,
          teamMemberId: createdTeamMember.id,
        });
      },
      onError: (error) => {
        setPostMemberModal(false);
        if (error.response.status === 409) {
          setErrorPostMemberModal({
            message: `This member is already in this team.`,
          });
        } else {
          setErrorPostMemberModal({
            message: `${JSON.stringify(error.status)} error occurred while adding member to the team.`,
          });
        }
      },
    },
    [
      `/api/teams/all?courseId=${courseId}`,
      `/api/rosterstudents/course/${courseId}`,
    ],
  );
 
  const handlePostSubmit = (data) => {
    memberPostMutation.mutate(data);
  };
 
  const deleteTeamCallback = async (team) => {
    deleteTeamMutation.mutate(team);
    deleteGithubTeamMutation.mutate(team);
  };
 
  const deleteMemberCallback = async (cell, team) => {
    const member = cell.row.original;
    deleteMemberMutation.mutate(member);
    deleteGithubMemberMutation.mutate({
      memberGithubLogin: member.rosterStudent.githubLogin,
      githubTeamId: team.githubTeamId,
    });
  };
 
  const memberColumns = [
    ...(instructorView
      ? [
          {
            Header: "Roster Student ID",
            accessor: "rosterStudent.id",
          },
        ]
      : []),
    {
      Header: "First Name",
      accessor: "rosterStudent.firstName",
    },
    {
      Header: "Last Name",
      accessor: "rosterStudent.lastName",
    },
    {
      Header: "Email",
      accessor: "rosterStudent.email",
    },
    instructorView
      ? {
          Header: "GitHub Login",
          accessor: "rosterStudent.githubLogin",
        }
      : {
          Header: "GitHub ID",
          accessor: "rosterStudent.githubId",
        },
  ];
 
  const staffColumns = [
    {
      Header: "Id",
      accessor: "id",
    },
    {
      Header: "First Name",
      accessor: "firstName",
    },
    {
      Header: "Last Name",
      accessor: "lastName",
    },
    {
      Header: "Email",
      accessor: "email",
    },
    {
      Header: "GitHub Login",
      accessor: "githubLogin",
    },
  ];
 
  return (
    <>
      <Modal
        show={postMemberModal}
        onHide={() => {
          setPostMemberModal(false);
          // Stryker disable next-line all : selectedTeam is only read while the modal is open
          setSelectedTeam(null);
        }}
        centered={true}
        data-testid={`${testIdPrefix}-post-modal`}
      >
        <ModalHeader closeButton>Add Team Member</ModalHeader>
        <ModalBody>
          <TeamMemberForm
            submitAction={handlePostSubmit}
            rosterStudents={rosterStudents}
          />
        </ModalBody>
      </Modal>
      <Modal
        show={errorPostMemberModal}
        onHide={() => setErrorPostMemberModal(false)}
        centered={true}
        data-testid={`${testIdPrefix}-error-post-member-modal`}
      >
        <ModalHeader closeButton>
          <h4 className="text-danger"> Error Creating Member </h4>
        </ModalHeader>
        <ModalBody>{errorPostMemberModal.message}</ModalBody>
      </Modal>
      {instructorView && (
        <div className="d-flex justify-content-end gap-2 mb-2">
          <Button
            variant="outline-secondary"
            size="sm"
            onClick={() => setSelectedTeamKeys(teams.map(teamKey))}
            data-testid={`${testIdPrefix}-expand-all`}
          >
            Expand All
          </Button>
          <Button
            variant="outline-secondary"
            size="sm"
            onClick={() => {
              // Stryker disable next-line ArrayDeclaration : a key that matches no team opens no team, just like no key
              setSelectedTeamKeys([]);
            }}
            data-testid={`${testIdPrefix}-collapse-all`}
          >
            Collapse All
          </Button>
        </div>
      )}
      <Accordion
        alwaysOpen
        activeKey={openTeamKeys}
        onSelect={setSelectedTeamKeys}
        data-testid={`${testIdPrefix}-accordion`}
      >
        {teams.map((team) => (
          <Accordion.Item eventKey={teamKey(team)} key={team.id}>
            <Accordion.Header>
              <span className="d-flex align-items-center justify-content-between w-100">
                <h3 data-testid={`${testIdPrefix}-${team.id}-name`}>
                  {team.name}
                  {team.isStaffTeam ? " (Staff Team)" : ""}
                </h3>
 
                {canManage && (
                  <span className="ms-auto me-3">
                    {team.isStaffTeam ? (
                      <Button
                        disabled
                        data-testid={`${testIdPrefix}-${team.id}-staff-team-button`}
                        className="me-3"
                      >
                        Staff Team
                      </Button>
                    ) : (
                      <Button
                        onClick={(e) => {
                          e.stopPropagation();
                          setPostMemberModal(true);
                          setSelectedTeam(team);
                        }}
                        data-testid={`${testIdPrefix}-${team.id}-add-member-button`}
                        className="me-3"
                      >
                        Add Team Member
                      </Button>
                    )}
                    <Button
                      variant="danger"
                      onClick={(e) => {
                        e.stopPropagation();
                        deleteTeamCallback(team);
                      }}
                      data-testid={`${testIdPrefix}-${team.id}-delete-button`}
                    >
                      Delete
                    </Button>
                  </span>
                )}
              </span>
            </Accordion.Header>
            <Accordion.Body>
              {team.isStaffTeam ? (
                <OurTable
                  data={courseStaff}
                  columns={staffColumns}
                  testid={`${testIdPrefix}-${team.id}-members-table`}
                />
              ) : (
                <OurTable
                  data={team.teamMembers}
                  columns={[
                    ...memberColumns,
                    ...(canManage
                      ? [
                          ButtonColumn(
                            "Remove",
                            "danger",
                            (cell) => deleteMemberCallback(cell, team),
                            `${testIdPrefix}-${team.id}`,
                          ),
                        ]
                      : []),
                  ]}
                  testid={`${testIdPrefix}-${team.id}-members-table`}
                />
              )}
            </Accordion.Body>
          </Accordion.Item>
        ))}
      </Accordion>
    </>
  );
}