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

93.93% Statements 31/33
85.71% Branches 24/28
80% Functions 8/10
93.93% Lines 31/33

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                                                2x 25x   25x 24x 24x 24x 24x 24x 24x   24x 24x     24x         24x 24x                           13x 3x     13x 2x 2x 2x               1x 1x 1x             1x 1x                                       1x                                       1x             2x                                                                   1x 1x                         1x                        
import { useState } from "react";
import { Navigate, useNavigate, useSearchParams } from "react-router";
import { StateCode } from "shared-types";
import { UserRole } from "shared-types/events/legacy-user";
import { userRoleMap } from "shared-utils";
 
import { useGetUserDetails, useGetUserProfile, useSubmitRoleRequests } from "@/api";
import {
  banner,
  Button,
  ConfirmationDialog,
  LoadingSpinner,
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
  SimplePageContainer,
  SubNavHeader,
} from "@/components";
import { FilterableSelect, Option } from "@/components/Opensearch/main/Filtering/Drawer/Filterable";
import { useAvailableStates } from "@/hooks/useAvailableStates";
import { useFeatureFlag } from "@/hooks/useFeatureFlag";
 
export const StateSignup = () => {
  const isNewUserRoleDisplay = useFeatureFlag("SHOW_USER_ROLE_UPDATE");
 
  const [stateSelected, setStateSelected] = useState<StateCode[]>([]);
  const [showModal, setShowModal] = useState<boolean>(false);
  const navigate = useNavigate();
  const { mutateAsync: submitRequest, isLoading } = useSubmitRoleRequests();
  const { data: userDetails, isLoading: isUserDetailsLoading } = useGetUserDetails();
  const { data: userProfile, isLoading: isUserProfileLoading } = useGetUserProfile();
  const currentRole = userDetails?.role;
 
  const [searchParams] = useSearchParams();
  const roleKey = searchParams.get("role") as UserRole;
 
  // Determine which role the user is allowed to request based on their current role
  const roleToRequestMap: Partial<Record<UserRole, UserRole>> = {
    norole: roleKey,
    statesubmitter: "statesystemadmin",
    statesystemadmin: "statesubmitter",
  };
  const roleToRequest = roleToRequestMap[currentRole];
  const statesToRequest: Option[] = useAvailableStates(roleToRequest, userProfile?.stateAccess);
 
  if (isUserDetailsLoading || isUserProfileLoading) return <LoadingSpinner />;
 
  if (!userDetails?.role) return <Navigate to="/" />;
 
  // Only state users can access this page
  if (
    currentRole !== "statesubmitter" &&
    currentRole !== "statesystemadmin" &&
    currentRole !== "norole"
  )
    return <Navigate to="/profile" />;
 
  const onChange = (values: StateCode[]) => {
    setStateSelected(values);
  };
 
  const onSubmit = async () => {
    try {
      for (const state of stateSelected) {
        await submitRequest({
          email: userDetails.email,
          state,
          role: roleToRequest,
          eventType: "user-role",
          requestRoleChange: true,
        });
      }
      const redirectRoute = currentRole === "norole" ? "/profile" : "/dashboard";
      navigate(redirectRoute);
      banner({
        header: "Submission Completed",
        body: "Your submission has been received.",
        variant: "success",
        pathnameToDisplayOn: redirectRoute,
      });
    } catch (error) {
      console.error(error);
      banner({
        header: "An unexpected error has occurred:",
        body: error instanceof Error ? error.message : String(error),
        variant: "destructive",
        pathnameToDisplayOn: window.location.pathname,
      });
    }
  };
 
  return (
    <div>
      <SubNavHeader>
        <h1 className="text-xl font-medium">
          {isNewUserRoleDisplay ? "Choose States For Access" : "Registration: State Access"}
        </h1>
      </SubNavHeader>
      <ConfirmationDialog
        open={showModal}
        title="Cancel role request?"
        body="Changes you made will not be saved."
        onAccept={() => navigate(isNewUserRoleDisplay ? "/profile" : "/signup")}
        onCancel={() => setShowModal(false)}
        cancelButtonText="Stay on Page"
        acceptButtonText="Confirm"
      />
      <SimplePageContainer>
        <div className="flex justify-center p-5">
          <div className="w-1/3">
            {!isNewUserRoleDisplay && (
              <div className="py-2">
                <h2 className="text-xl font-bold mb-2">User Role:</h2>
                <p className="text-xl italic">{userRoleMap[roleToRequest] ?? "Not Found"}</p>
              </div>
            )}
            <div className="py-2">
              <h2 className="text-xl font-bold mb-2">Select your State Access</h2>
              {isNewUserRoleDisplay && (
                <FilterableSelect
                  value={stateSelected}
                  options={statesToRequest}
                  onChange={(values: StateCode[]) => onChange(values)}
                  placeholder="Select state here"
                  selectedDisplay="value"
                />
              )}
              {!isNewUserRoleDisplay &&
                (roleToRequest === "statesystemadmin" ? (
                  <Select onValueChange={(value: StateCode) => onChange([value])}>
                    <SelectTrigger aria-label="Select state">
                      <SelectValue placeholder="Select state here" />
                    </SelectTrigger>
                    <SelectContent isScrollable>
                      {statesToRequest.map((state) => (
                        <SelectItem value={state.value} key={state.value}>
                          {state.label}
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                ) : (
                  <FilterableSelect
                    value={stateSelected}
                    options={statesToRequest}
                    onChange={(values: StateCode[]) => onChange(values)}
                    placeholder="Select state here"
                    selectedDisplay="label"
                  />
                ))}
              {!stateSelected.length && (
                <p className="text-red-600 mt-3">
                  {roleToRequest === "statesystemadmin"
                    ? "Please select a state."
                    : "Please select at least one state."}
                </p>
              )}
              <div className="py-4">
                {isNewUserRoleDisplay ? (
                  <Button
                    className="mr-3"
                    disabled={!stateSelected.length}
                    onClick={() => {
                      const stateParam = encodeURIComponent(stateSelected.join(","));
                      navigate(`/signup/state/role?states=${stateParam}`);
                    }}
                  >
                    Continue
                  </Button>
                ) : (
                  <Button className="mr-3" disabled={!stateSelected.length} onClick={onSubmit}>
                    Submit
                  </Button>
                )}
                {isLoading && <LoadingSpinner />}
                <Button
                  variant={isNewUserRoleDisplay ? "link" : "outline"}
                  onClick={() => setShowModal(true)}
                >
                  Cancel
                </Button>
              </div>
            </div>
          </div>
        </div>
      </SimplePageContainer>
    </div>
  );
};