All files / react-app/src/features/sign-up cmsSignup.tsx

78.57% Statements 33/42
65.51% Branches 19/29
75% Functions 9/12
82.05% Lines 32/39

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                                                  2x 113x 106x     7x 7x     2x 18x 18x 18x 18x   18x   18x 18x   18x 2x 2x                   1x 1x   1x             1x   1x                     18x 6x 6x               6x               11x                                                                         2x 16x   2x                                           2x 14x   2x                                                                          
import { useEffect, useState } from "react";
import { Navigate, useNavigate } from "react-router";
 
import {
  useGetUserDetails,
  // useSubmitGroupDivision,
  useSubmitRoleRequests,
} from "@/api";
import {
  banner,
  Button,
  ConfirmationDialog,
  LoadingSpinner,
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
  SimplePageContainer,
  SubNavHeader,
} from "@/components";
 
import { divisionsType, groupDivision, groupDivisionType } from "./groupDivision";
 
// sorting helper function
const groupSortFn = (groupA, groupB) => {
  if (groupA.abbr) {
    Eif (groupB.abbr) return groupA.abbr.localeCompare(groupB.abbr);
    return -1;
  }
  Iif (groupA.abbr) return 1;
  return 0;
};
 
export const CMSSignup = () => {
  const [showModal, setShowModal] = useState<boolean>(false);
  const [group, setGroup] = useState<groupDivisionType | null>(null);
  const [division, setDivision] = useState<divisionsType | null>(null);
  const { mutateAsync: submitRequest } = useSubmitRoleRequests();
 
  const navigate = useNavigate();
 
  const { data: userDetails, isLoading: isUserDetailsLoading } = useGetUserDetails();
  const currentRole = userDetails?.role;
 
  const onSubmit = async () => {
    try {
      await submitRequest({
        email: userDetails.email,
        state: "N/A",
        role: isCMSRoleApprover ? "defaultcmsuser" : "cmsroleapprover",
        eventType: "user-role",
        requestRoleChange: true,
        group: !isCMSRoleApprover ? group?.abbr : null,
        division: !isCMSRoleApprover ? division?.abbr : null,
      });
 
      Iif (isCMSRoleApprover) navigate("/usermanagement");
      else navigate("/dashboard");
 
      banner({
        header: "Submission Completed",
        body: "Your submission has been received.",
        variant: "success",
        pathnameToDisplayOn: isCMSRoleApprover ? "/usermanagement" : "/dashboard",
      });
    } catch (error) {
      console.error(`Error updating group and division: ${error?.message || error}`);
 
      banner({
        header: "An unexpected error has occurred:",
        body: error instanceof Error ? error.message : String(error),
        variant: "destructive",
        pathnameToDisplayOn: window.location.pathname,
      });
    }
  };
 
  // should leave this page if the user is requesting to be read-on
  // this work could be done in sign-up but we want to keep the submit fnc in one place & have a loading screen
  useEffect(() => {
    const autoSubmit = async () => {
      Iif (currentRole === "cmsroleapprover") {
        try {
          await onSubmit();
        } catch (e) {
          console.error("CMS Read-only access submission failed", e);
        }
      }
    };
    autoSubmit();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);
 
  if (isUserDetailsLoading) return <LoadingSpinner />;
 
  if (!userDetails?.role) return <Navigate to="/" />;
 
  const isCMSRoleApprover = currentRole === "cmsroleapprover";
 
  // TODO: refactor to use isCmsUser
  if (!["defaultcmsuser", "cmsroleapprover", "cmsreviewer"].includes(currentRole))
    return <Navigate to="/profile" />;
 
  return (
    <div>
      <SubNavHeader>
        <h1 className="text-xl font-medium">
          {isCMSRoleApprover
            ? "Registration: CMS Read-only Access"
            : "Registration: CMS Role Approver Access"}
        </h1>
      </SubNavHeader>
      {!isCMSRoleApprover && (
        <SimplePageContainer>
          <ConfirmationDialog
            open={showModal}
            title="Cancel role request?"
            body="Changes you made will not be saved."
            onAccept={() => navigate("/signup")}
            onCancel={() => setShowModal(false)}
            cancelButtonText="Stay on Page"
            acceptButtonText="Confirm"
          />
 
          <div className="flex justify-center p-5">
            <div className="w-1/2">
              <div className="py-2">
                <h2 className="text-xl font-bold mb-2">Select a Group and Division</h2>
              </div>
 
              <div className="py-4">
                <h2 className="text-xl font-bold mb-2">Group</h2>
                <Select
                  onValueChange={(value) => {
                    const matchingGroup: groupDivisionType[] = groupDivision.filter(
                      (group) => group.abbr === value,
                    );
                    setGroup(matchingGroup[0]);
                  }}
                >
                  <SelectTrigger aria-label="Select group">
                    <SelectValue placeholder="Select..." />
                  </SelectTrigger>
                  <SelectContent>
                    {groupDivision.sort(groupSortFn).map((group) => (
                      <SelectItem value={group.abbr} key={`${group.id}-${group.abbr}`}>
                        <span className="font-bold min-w-[4rem]">{group.abbr}</span>
                        <span>{group.name}</span>
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
 
              {group && (
                <div className="py-4">
                  <h2 className="text-xl font-bold mb-2">Division</h2>
                  <Select
                    onValueChange={(value) => {
                      const matchingDivision: divisionsType[] = group.divisions.filter(
                        (division) => division.id === parseInt(value),
                      );
                      setDivision(matchingDivision[0]);
                    }}
                  >
                    <SelectTrigger aria-label="Select division">
                      <SelectValue placeholder="Select..." />
                    </SelectTrigger>
                    <SelectContent>
                      {group &&
                        group.divisions.sort(groupSortFn).map((divisions) => (
                          <SelectItem
                            value={divisions.id.toString()}
                            key={`${divisions.id}-${divisions.abbr}`}
                          >
                            <span className="font-bold min-w-[4rem]">{divisions.abbr ?? "--"}</span>
                            <span>{divisions.name}</span>
                          </SelectItem>
                        ))}
                    </SelectContent>
                  </Select>
                </div>
              )}
 
              <div className="py-4">
                <Button className="mr-3" disabled={division == null} onClick={onSubmit}>
                  Submit
                </Button>
                <Button variant="outline" onClick={() => setShowModal(true)}>
                  Cancel
                </Button>
              </div>
            </div>
          </div>
        </SimplePageContainer>
      )}
    </div>
  );
};