All files / react-app/src/api useSubmitRoleRequests.ts

95.65% Statements 22/23
57.14% Branches 8/14
83.33% Functions 5/6
95.23% Lines 20/21

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                                      105x 11x 11x     4x   7x 7x       105x 54x   54x                 4x   4x   4x   2x 2x 2x   46x                                               2x         2x       2x 1x          
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { API } from "aws-amplify";
import { StateCode } from "shared-types";
import { UserRole } from "shared-types/events/legacy-user";
 
import { OneMacUserProfile } from "./useGetUserProfile";
 
export type RoleStatus = "active" | "denied" | "pending" | "revoked";
export type RoleRequest = {
  email: string;
  state: StateCode | "N/A";
  role: UserRole;
  eventType: string;
  requestRoleChange: boolean; // is this a role change request? (used in state signup and profile page)
  grantAccess?: RoleStatus; // active, denied, revoked, or pending if undefined (used in user management page)
  group?: string; // used for systemadmins upgrading defaultcmsuser to cmsroleapprover
  division?: string; // used for systemadmins upgrading defaultcmsuser to cmsroleapprover
};
 
export const submitRoleRequests = async (request: RoleRequest): Promise<{ message: string }> => {
  try {
    const roleRequest = await API.post("os", "/submitRoleRequests", {
      body: request,
    });
    return roleRequest;
  } catch (error) {
    console.error(error);
    throw new Error("Failed to submit role request");
  }
};
 
export const useSubmitRoleRequests = () => {
  const queryClient = useQueryClient();
 
  return useMutation<
    { message: string },
    Error,
    RoleRequest,
    { previousProfile?: OneMacUserProfile }
  >({
    mutationFn: submitRoleRequests,
 
    onMutate: async (newRequest) => {
      await queryClient.cancelQueries({ queryKey: ["profile"] });
 
      const previousProfile = queryClient.getQueryData<OneMacUserProfile>(["profile"]);
 
      if (!previousProfile) return;
 
      const { email, state, role, grantAccess, eventType } = newRequest;
      const id = `${email}_${state}_${role}`;
      const oldStateAccess = previousProfile.stateAccess ?? [];
 
      const updatedStateAccess = oldStateAccess.some((stateAccess) => stateAccess.id === id)
        ? oldStateAccess.map((stateAccess) =>
            stateAccess.id === id
              ? {
                  ...stateAccess,
                  status: grantAccess ?? "pending",
                  eventType,
                }
              : stateAccess,
          )
        : [
            ...oldStateAccess,
            {
              id,
              email,
              role,
              territory: state,
              status: grantAccess ?? "pending",
              eventType,
              doneByEmail: email,
              doneByName: "Updating...",
            },
          ];
 
      queryClient.setQueryData<OneMacUserProfile>(["profile"], {
        ...previousProfile,
        stateAccess: updatedStateAccess,
      });
 
      return { previousProfile };
    },
 
    onError: (_error, _variables, context) => {
      if (context?.previousProfile) {
        queryClient.setQueryData(["profile"], context.previousProfile);
      }
    },
  });
};