All files / lib/lambda/user-management getApprovers.ts

79.48% Statements 31/39
47.61% Branches 10/21
100% Functions 3/3
81.57% Lines 31/38

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                              1x 5x 1x             4x 4x   1x 1x           3x 3x 3x   3x   3x 3x   3x                             3x 3x   3x     3x 3x 12x 2x   12x         3x   3x 2x 2x   2x   4x     2x                                 3x                                     1x  
import { APIGatewayEvent } from "aws-lambda";
import { getAuthDetails, lookupUserAttributes } from "libs/api/auth/user";
import { response } from "libs/handler-lib";
import { StateCode } from "shared-types";
 
import { getUserProfileSchema } from "./getUserProfile";
import {
  getAllUserRolesByEmail,
  getApproversByRole,
  getLatestActiveRoleByEmail,
} from "./userManagementService";
 
type Territory = StateCode | "N/A";
type approverListType = { id: string; role: string; email: string; territory: Territory };
 
const getApprovers = async (event: APIGatewayEvent) => {
  if (!event?.requestContext) {
    return response({
      statusCode: 400,
      body: { message: "Request context required" },
    });
  }
 
  let authDetails;
  try {
    authDetails = getAuthDetails(event);
  } catch (err) {
    console.error(err);
    return response({
      statusCode: 401,
      body: { message: "User not authenticated" },
    });
  }
 
  try {
    const { userId, poolId } = authDetails;
    const { email } = await lookupUserAttributes(userId, poolId);
 
    let lookupEmail = email;
 
    const eventBody = typeof event.body === "string" ? JSON.parse(event.body) : event.body;
    const safeEventBody = getUserProfileSchema.safeParse(eventBody);
 
    Iif (
      safeEventBody.success &&
      safeEventBody?.data?.userEmail &&
      safeEventBody.data.userEmail !== email
    ) {
      const currUserLatestActiveRoleObj = await getLatestActiveRoleByEmail(email);
      if (
        ["systemadmin", "statesystemadmin", "cmsroleapprover", "helpdesk"].includes(
          currUserLatestActiveRoleObj?.role,
        )
      ) {
        lookupEmail = safeEventBody.data.userEmail;
      }
    }
 
    const userRoles = await getAllUserRolesByEmail(lookupEmail);
    Iif (!userRoles) throw Error;
 
    const roleStateMap = new Map<string, Territory[]>();
 
    // we make a map for state submitters but also use the roles for all other users
    Eif (userRoles) {
      userRoles.forEach(({ role, territory }: approverListType) => {
        if (!roleStateMap.has(role)) {
          roleStateMap.set(role, []);
        }
        roleStateMap.get(role)!.push(territory);
      });
    }
 
    // loop through roles
    const approverList = [];
 
    for (const [role, territories] of roleStateMap.entries()) {
      try {
        const allApprovers = await getApproversByRole(role); // pass in the role of current user NOT approving role
        const filtered =
          role === "statesubmitter"
            ? allApprovers.filter((approver) =>
                territories.includes(approver.territory as Territory),
              )
            : allApprovers;
        approverList.push({
          role: role,
          territory: territories,
          approvers: filtered,
        });
      } catch (err) {
        console.log("ERROR: ", err);
        approverList.push({
          role: role,
          territory: territories,
          approvers: [
            { id: "error", fullName: "Error Fetching Approvers", email: "", territory: "N/A" },
          ],
        });
      }
    }
 
    return response({
      statusCode: 200,
      body: {
        message: "Approver list successfully retrieved.",
        approverList: approverList,
      },
    });
  } catch (err: unknown) {
    console.error("Unhandled error in getApprovers:", err);
    return response({
      statusCode: 500,
      body: {
        message: "Internal server error",
        error: err instanceof Error ? err.message : JSON.stringify(err),
      },
    });
  }
};
 
export const handler = getApprovers;