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

96.87% Statements 31/32
84% Branches 21/25
87.5% Functions 7/8
96.87% Lines 31/32

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                                      2x 24x   24x 24x 24x 24x 24x 24x 24x   24x 24x     24x         24x 24x             14x               13x 3x     13x 2x 2x 2x               1x 1x 1x             1x 1x                                       1x                                       3x                         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,
  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>
              <FilterableSelect
                ariaLabel="Select state here"
                value={stateSelected}
                options={statesToRequest}
                onChange={(values: StateCode[]) => onChange(values)}
                placeholder="Select state here"
                selectedDisplay={isNewUserRoleDisplay ? "value" : "label"}
              />
              {!stateSelected.length && (
                <p className="text-red-600 mt-3">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>
  );
};