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

87.93% Statements 102/116
79.48% Branches 31/39
87.09% Functions 27/31
88.67% Lines 94/106

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 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343          21x   21x       60x 60x 60x   60x                 60x     21x 24x 24x         131x 125x                 24x   50x 50x           21x 27x   27x                 74x     21x 6x   6x                         6x     21x 4x   4x             196x     21x 7x   7x                 15x     21x 14x 4x     108x 10x   10x 108x 108x   108x             10x     21x 74x   74x                               72x     21x           3x 3x 3x   3x   3x             3x                 3x 3x 3x     3x 3x 3x 3x 3x 3x       3x     21x       3x 3x 3x 3x     3x                 3x               3x 6x 6x       3x 6x       3x 3x   3x 6x 6x               3x     21x       54x   54x                             54x 300x 300x   54x     21x               26x 26x   26x                           26x 26x               26x                                            
import { search } from "libs";
import { getDomainAndNamespace } from "libs/utils";
import { Index } from "shared-types/opensearch";
import { getApprovingRole } from "shared-utils";
 
const QUERY_LIMIT = 2000;
 
export const getUserByEmail = async (
  email: string,
  domainNamespace?: { domain: string; index: Index },
) => {
  console.log("Looking up user by email:", email);
  if (!domainNamespace) domainNamespace = getDomainAndNamespace("users");
  const { domain, index } = domainNamespace;
 
  const result = await search(domain, index, {
    size: 1,
    query: {
      term: {
        "email.keyword": email,
      },
    },
  });
 
  return result.hits.hits[0]?._source ?? null;
};
 
export const getUsersByEmails = async (emails: string[]) => {
  const { domain, index } = getDomainAndNamespace("users");
  const results = await search(domain, index, {
    size: QUERY_LIMIT,
    query: {
      bool: {
        should: emails
          ?.filter((email) => email)
          .map((email) => ({
            term: {
              "email.keyword": email,
            },
          })),
      },
    },
  });
 
  return results.hits.hits.reduce(
    (acc: any, hit: any) => {
      acc[hit._source.email] = hit._source;
      return acc;
    },
    {} as Record<string, { fullName?: string }>,
  );
};
 
export const getAllUserRolesByEmail = async (email: string) => {
  const { domain, index } = getDomainAndNamespace("roles");
 
  const result = await search(domain, index, {
    size: QUERY_LIMIT,
    query: {
      term: {
        "email.keyword": email,
      },
    },
  });
 
  return result.hits.hits.map((hit: any) => ({ ...hit._source }));
};
 
export const userHasThisRole = async (email: string, state: string, role: string) => {
  const { domain, index } = getDomainAndNamespace("roles");
 
  const result = await search(domain, index, {
    size: 100,
    query: {
      bool: {
        must: [
          { term: { "email.keyword": email } },
          { term: { status: "active" } },
          { term: { role: role } },
          { term: { "territory.keyword": state } },
        ],
      },
    },
  });
  return result.hits.hits.length > 0;
};
 
export const getAllUserRoles = async () => {
  const { domain, index } = getDomainAndNamespace("roles");
 
  const results = await search(domain, index, {
    query: {
      match_all: {},
    },
    size: QUERY_LIMIT,
  });
 
  return results.hits.hits.map((hit: any) => ({ ...hit._source }));
};
 
export const getAllUserRolesByState = async (state: string) => {
  const { domain, index } = getDomainAndNamespace("roles");
 
  const results = await search(domain, index, {
    query: {
      term: {
        "territory.keyword": state,
      },
    },
    size: QUERY_LIMIT,
  });
 
  return results.hits.hits.map((hit: any) => ({ ...hit._source }));
};
 
export const getUserRolesWithNames = async (roleRequests: any[]) => {
  if (!Array.isArray(roleRequests) || !roleRequests.length) {
    throw new Error("No role requests found");
  }
 
  const emails = roleRequests.map((role) => role.email);
  const users = await getUsersByEmails(emails);
 
  const rolesWithName = roleRequests.map((roleObj) => {
    const email = roleObj.email;
    const fullName = users[email]?.fullName || "Unknown";
 
    return {
      ...roleObj,
      email,
      fullName,
    };
  });
 
  return rolesWithName;
};
 
export const getLatestActiveRoleByEmail = async (email: string) => {
  const { domain, index } = getDomainAndNamespace("roles");
 
  const result = await search(domain, index, {
    size: 1,
    query: {
      bool: {
        must: [{ term: { "email.keyword": email } }, { term: { status: "active" } }],
      },
    },
    sort: [
      {
        lastModifiedDate: {
          order: "desc",
        },
      },
    ],
  });
 
  return result.hits.hits[0]?._source ?? null;
};
 
export const getApproversByRoleState = async (
  role: string,
  state: string,
  domainNamespace?: { domain: string; index: Index },
  userDomainNamespace?: { domain: string; index: Index },
) => {
  if (!domainNamespace) domainNamespace = getDomainAndNamespace("roles");
  if (!userDomainNamespace) userDomainNamespace = getDomainAndNamespace("users");
  const { domain, index } = domainNamespace;
 
  const approverRole = getApprovingRole(role);
  const queryRequirements =
    role === "statesubmitter"
      ? [
          { term: { status: "active" } },
          { term: { role: approverRole } },
          { term: { "territory.keyword": state } },
        ]
      : [{ term: { status: "active" } }, { term: { role: approverRole } }];
  const results = await search(domain, index, {
    query: {
      bool: {
        must: queryRequirements,
      },
    },
    size: QUERY_LIMIT,
  });
 
  const approverRoleList: { id: string; email: string }[] = results.hits.hits.map((hit: any) => {
    const { id, email } = hit._source;
    return { id, email };
  });
 
  const approversInfo = [];
  for (const approver of approverRoleList) {
    Eif (approver.email) {
      const userInfo = await getUserByEmail(approver.email, userDomainNamespace);
      const fullName = userInfo?.fullName ?? "Unknown";
      approversInfo.push({ email: approver.email, fullName: fullName, id: approver.id });
    }
  }
 
  return approversInfo;
};
 
export const getApproversByRole = async (
  role: string,
  domainNamespace?: { domain: string; index: Index },
) => {
  const resolvedDomain = domainNamespace ?? getDomainAndNamespace("roles");
  const { domain, index } = resolvedDomain;
  const approverRole = getApprovingRole(role);
  Iif (!approverRole) {
    throw new Error(`Approving role not found for role: ${role}`);
  }
  const results = await search(domain, index, {
    query: {
      bool: {
        must: [{ term: { status: "active" } }, { term: { role: approverRole } }],
      },
    },
    size: QUERY_LIMIT,
  });
 
  Iif (!results) {
    console.log("ERROR with results");
    throw Error;
  }
  // this is used for state submitters to filter out the territory AFTER the search
 
  // format search results to match what is needed
  const approverRoleList: { id: string; email: string; territory: string }[] =
    results.hits.hits.map((hit: any) => {
      const { id, email, territory } = hit._source;
      return { id, email, territory };
    });
 
  // remove any dups
  const uniqueEmails = Array.from(
    new Set(approverRoleList.map((approver) => approver.email).filter(Boolean)),
  );
 
  // // needed to get fullName
  const userInfoResults = await getUsersByEmails(uniqueEmails);
  Iif (!userInfoResults) console.log("ERROR WITH getting full name... continuing anyways.. ");
 
  const approversInfo = approverRoleList
    .filter((approver) => approver.email)
    .map((approver) => ({
      id: approver.id,
      email: approver.email,
      fullName:
        (userInfoResults[approver.email] && userInfoResults[approver.email].fullName) ?? "Unknown",
      territory: approver.territory,
    }));
 
  return approversInfo;
};
 
export const getActiveStatesForUserByEmail = async (
  email: string,
  latestActiveRole?: string,
): Promise<string[]> => {
  const { domain, index } = getDomainAndNamespace("roles");
 
  const result = await search(domain, index, {
    size: QUERY_LIMIT,
    query: {
      bool: {
        must: [
          { term: { "email.keyword": email } },
          { term: { status: "active" } },
          ...(latestActiveRole ? [{ term: { role: latestActiveRole } }] : []),
        ],
        must_not: [{ terms: { territory: ["N/A"] } }],
      },
    },
    _source: ["territory"],
  });
 
  const states = result.hits?.hits
    .map((hit: any) => hit._source.territory)
    .filter((v: any): v is string => typeof v === "string");
 
  return Array.from(new Set(states));
};
 
export const getStateUsersByState = async (
  state: string,
): Promise<
  {
    email: string;
    fullName: string;
  }[]
> => {
  const { domain: rolesDomain, index: rolesIndex } = getDomainAndNamespace("roles");
  const { domain: usersDomain, index: usersIndex } = getDomainAndNamespace("users");
 
  const rolesResult = await search(rolesDomain, rolesIndex, {
    size: QUERY_LIMIT,
    query: {
      bool: {
        must: [
          { term: { status: "active" } },
          { term: { "territory.keyword": state } },
          { terms: { role: ["statesubmitter", "statesystemadmin"] } },
        ],
      },
    },
    _source: ["email"],
  });
 
  const seen = new Set<string>();
  const emails = rolesResult.hits.hits
    .map((hit: any) => hit._source.email)
    .filter((email: string): email is string => {
      if (seen.has(email)) return false;
      seen.add(email);
      return true;
    });
 
  Eif (!emails.length) return [];
 
  const usersResult = await search(usersDomain, usersIndex, {
    size: QUERY_LIMIT,
    query: {
      bool: {
        should: emails.map((email: string) => ({
          term: { "email.keyword": email },
        })),
      },
    },
    _source: ["email", "fullName"],
  });
 
  return usersResult.hits.hits.map((hit: any) => {
    const user = hit._source;
    return {
      email: user.email,
      fullName: user.fullName,
    };
  });
};