All files / lib/lambda processEmails.ts

90.2% Statements 129/143
81.81% Branches 36/44
93.75% Functions 15/16
90.44% Lines 123/136

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 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420                                              3x 3x                                             2x 35x                     280x 35x 1x     34x 34x 34x 34x 34x 34x 34x 34x 34x 34x                       34x   34x 34x     34x     34x   34x 34x 3x 3x   31x   3x   3x 3x 3x 3x                       3x 3x               34x 34x 34x   34x 6x 6x       6x   6x 6x 6x   6x 1x 1x     5x 1x 1x     4x                   4x   4x                   4x           4x     28x         28x 1x 1x     27x       27x   27x 27x 2x 2x 2x   1x 1x   1x     25x 1x 1x     24x 24x 24x   2x       2x         52x 156x   52x 1x                 28x   26x             26x 26x   26x   26x 26x         26x         26x 26x   26x   26x 26x 26x   26x                     26x   26x     26x 48x 48x 48x 48x             48x 48x 48x                 48x 48x   26x     26x       26x                 50x                                       50x 50x       52x 52x   52x 52x 52x 51x   1x 1x       50x                                                                                          
import { SendEmailCommand, SendEmailCommandInput, SESClient } from "@aws-sdk/client-ses";
import { SendMessageCommand, SQSClient } from "@aws-sdk/client-sqs";
import { Handler } from "aws-lambda";
import { htmlToText, HtmlToTextOptions } from "html-to-text";
import { getAllStateUsersFromOpenSearch, getEmailTemplates } from "libs/email";
import { EMAIL_CONFIG, getCpocEmail, getSrtEmails } from "libs/email/content/email-components";
import * as os from "libs/opensearch-lib";
import { getOsNamespace } from "libs/utils";
import {
  EmailAddresses,
  Events,
  KafkaEvent,
  KafkaRecord,
  opensearch,
  SEATOOL_STATUS,
} from "shared-types";
import { decodeBase64WithUtf8, formatActionType, getSecret } from "shared-utils";
import { retry } from "shared-utils/retry";
 
import { sendUserRoleEmails } from "./processUserRoleEmails";
 
class TemporaryError extends Error {
  constructor(message: string) {
    super(message);
    this.name = "TemporaryError";
  }
}
 
export interface ProcessEmailConfig {
  emailAddressLookupSecretName: string;
  applicationEndpointUrl: string;
  osDomain: string;
  indexNamespace?: string;
  region: string;
  DLQ_URL: string;
  userPoolId: string;
  configurationSetName: string;
  isDev: boolean;
}
 
interface EmailTemplate {
  to: string[];
  cc?: string[];
  subject: string;
  body: string;
}
 
export const handler: Handler<KafkaEvent> = async (event) => {
  const requiredEnvVars = [
    "emailAddressLookupSecretName",
    "applicationEndpointUrl",
    "osDomain",
    "region",
    "DLQ_URL",
    "userPoolId",
    "configurationSetName",
    "isDev",
  ] as const;
 
  const missingVars = requiredEnvVars.filter((varName) => !process.env[varName]);
  if (missingVars.length > 0) {
    throw new Error(`Missing required environment variables: ${missingVars.join(", ")}`);
  }
 
  const emailAddressLookupSecretName = process.env.emailAddressLookupSecretName!;
  const applicationEndpointUrl = process.env.applicationEndpointUrl!;
  const osDomain = process.env.osDomain!;
  const indexNamespace = process.env.indexNamespace;
  const region = process.env.region!;
  const DLQ_URL = process.env.DLQ_URL!;
  const userPoolId = process.env.userPoolId!;
  const configurationSetName = process.env.configurationSetName!;
  const isDev = process.env.isDev!;
  const config: ProcessEmailConfig = {
    emailAddressLookupSecretName,
    applicationEndpointUrl,
    osDomain,
    indexNamespace,
    region,
    DLQ_URL,
    userPoolId,
    configurationSetName,
    isDev: isDev === "true",
  };
 
  console.log("config: ", JSON.stringify(config, null, 2));
 
  try {
    const results = await Promise.allSettled(
      Object.values(event.records)
        .flat()
        .map((rec) => processRecord(rec, config)),
    );
 
    console.log("results: ", JSON.stringify(results, null, 2));
 
    const failures = results.filter((r) => r.status === "rejected");
    if (failures.length > 0) {
      console.error("Some records failed:", JSON.stringify(failures, null, 2));
      throw new TemporaryError("Some records failed processing");
    }
    console.log("All records processed successfully", JSON.stringify(failures, null, 2));
  } catch (error) {
    console.error("Permanent failure:", error);
 
    Eif (config.DLQ_URL) {
      const sqsClient = new SQSClient({ region: config.region });
      try {
        await sqsClient.send(
          new SendMessageCommand({
            QueueUrl: config.DLQ_URL,
            MessageBody: JSON.stringify({
              error: error.message,
              originalEvent: event,
              timestamp: new Date().toISOString(),
            }),
          }),
        );
        console.log("Failed message sent to DLQ");
      } catch (dlqError) {
        console.error("Failed to send to DLQ:", dlqError);
        throw dlqError;
      }
    }
    throw error;
  }
};
 
export async function processRecord(kafkaRecord: KafkaRecord, config: ProcessEmailConfig) {
  console.log("processRecord called with kafkaRecord: ", JSON.stringify(kafkaRecord, null, 2));
  const { key, value, timestamp } = kafkaRecord;
  const id: string = decodeBase64WithUtf8(key);
 
  if (kafkaRecord.topic === "aws.seatool.ksql.onemac.three.agg.State_Plan") {
    const safeID = id.replace(/^"|"$/g, "").toUpperCase();
    const seatoolRecord: Document = {
      safeID,
      ...JSON.parse(decodeBase64WithUtf8(value)),
    };
    const safeSeatoolRecord = opensearch.main.seatool.transform(safeID).safeParse(seatoolRecord);
 
    Eif (safeSeatoolRecord.data?.seatoolStatus === SEATOOL_STATUS.WITHDRAWN) {
      try {
        const item = await os.getItem(config.osDomain, getOsNamespace("main"), safeID);
 
        if (!item?.found || !item?._source) {
          console.log(`The package was not found for id: ${id} in mako. Doing nothing.`);
          return;
        }
 
        if (item._source.withdrawEmailSent) {
          console.log("Withdraw email previously sent");
          return;
        }
 
        const recordToPass = {
          timestamp,
          ...safeSeatoolRecord.data,
          submitterName: item._source.submitterName,
          submitterEmail: item._source.submitterEmail,
          event: "seatool-withdraw",
          proposedEffectiveDate: safeSeatoolRecord.data?.proposedDate,
          origin: "seatool",
        };
 
        await processAndSendEmails(recordToPass as Events[keyof Events], safeID, config);
 
        const indexObject = {
          index: getOsNamespace("main"),
          id: safeID,
          body: {
            doc: {
              withdrawEmailSent: true,
            },
          },
        };
 
        await os.updateData(config.osDomain, indexObject);
      } catch (error) {
        console.error("Error processing record:", JSON.stringify(error, null, 2));
        throw error;
      }
    }
    return;
  }
 
  Iif (typeof key !== "string") {
    console.log("key is not a string ", JSON.stringify(key, null, 2));
    throw new Error("Key is not a string");
  }
 
  if (!value) {
    console.log("Tombstone detected. Doing nothing for this event");
    return;
  }
 
  const record = {
    timestamp,
    ...JSON.parse(decodeBase64WithUtf8(value)),
  };
  console.log("record: ", JSON.stringify(record, null, 2));
 
  const valueParsed = JSON.parse(decodeBase64WithUtf8(value));
  if (valueParsed.eventType === "user-role" || valueParsed.eventType === "legacy-user-role") {
    try {
      console.log("Sending user role email...");
      await sendUserRoleEmails(valueParsed, timestamp, config);
    } catch (error) {
      console.error("Error sending user email", error);
      throw error;
    }
    return;
  }
 
  if (record.origin !== "mako") {
    console.log("Kafka event is not of mako origin. Doing nothing.");
    return;
  }
 
  try {
    console.log("Config:", JSON.stringify(config, null, 2));
    await processAndSendEmails(record, id, config);
  } catch (error) {
    console.error(
      "Error processing record: { record, id, config }",
      JSON.stringify({ record, id, config }, null, 2),
    );
    throw error;
  }
}
 
export function validateEmailTemplate(template: any) {
  const requiredFields = ["to", "subject", "body"];
  const missingFields = requiredFields.filter((field) => !template[field]);
 
  if (missingFields.length > 0) {
    throw new Error(`Email template missing required fields: ${missingFields.join(", ")}`);
  }
}
 
export async function processAndSendEmails(
  record: Events[keyof Events],
  id: string,
  config: ProcessEmailConfig,
) {
  const templates = await getEmailTemplates(record);
 
  Iif (!templates) {
    console.log(
      `The kafka record has an event type that does not have email support. event: ${record.event}. Doing nothing.`,
    );
    return;
  }
 
  const territory = id.slice(0, 2);
  const allStateUsers = await getAllStateUsersFromOpenSearch(territory);
 
  const sec = await getSecret(config.emailAddressLookupSecretName);
 
  const item = await retry(
    () => os.getItemAndThrowAllErrors(config.osDomain, getOsNamespace("main"), id),
    10,
    10 * 1000,
  );
 
  Iif (!item?.found || !item?._source) {
    console.log(`The package was not found for id: ${id}. Doing nothing.`);
    return;
  }
 
  const cpocEmail = [...getCpocEmail(item)];
  const srtEmails = [...getSrtEmails(item)];
 
  const emails: EmailAddresses = JSON.parse(sec);
 
  const allStateUsersEmails = allStateUsers.map((user) => user.formattedEmailAddress);
  const isChipEligibility = record.authority === "CHIP SPA" && !!item._source?.chipSubmissionType;
  console.log("mappped to formatted email address for all state users: ", allStateUsers);
 
  const templateVariables = {
    ...record,
    id,
    isChipEligibility,
    applicationEndpointUrl: config.applicationEndpointUrl,
    territory,
    emails: { ...emails, cpocEmail, srtEmails },
    allStateUsersEmails,
    ...(item._source.actionType && { actionType: formatActionType(item._source.actionType) }),
  };
 
  console.log("Template variables:", JSON.stringify(templateVariables, null, 2));
 
  const results = [];
 
  // Process templates sequentially
  for (const template of templates) {
    try {
      const filledTemplate = await template(templateVariables);
      validateEmailTemplate(filledTemplate);
      const params = createEmailParams(
        filledTemplate,
        emails.sourceEmail,
        config.applicationEndpointUrl,
        config.isDev,
      );
 
      const result = await sendEmail(params, config.region);
      results.push({ success: true, result });
      console.log(`Successfully sent email for template: ${JSON.stringify(result)}`);
    } catch (error) {
      console.error("Error processing template:", error);
      results.push({ success: false, error });
      // Continue with next template instead of throwing
    }
  }
 
  // Log final results
  const successCount = results.filter((r) => r.success).length;
  const failureCount = results.filter((r) => !r.success).length;
 
  console.log(`Email sending complete. Success: ${successCount}, Failures: ${failureCount}`);
 
  // If all emails failed, throw an error to trigger retry/DLQ logic
  Iif (failureCount === templates.length) {
    throw new Error(`All ${failureCount} email(s) failed to send`);
  }
 
  return results;
}
 
export function createEmailParams(
  filledTemplate: EmailTemplate,
  sourceEmail: string,
  baseUrl: string,
  isDev: boolean,
): SendEmailCommandInput {
  const params: SendEmailCommandInput = {
    Destination: {
      ToAddresses: filledTemplate.to,
      CcAddresses: isDev
        ? [...(filledTemplate.cc || []), `State Submitter <${EMAIL_CONFIG.DEV_EMAIL}>`]
        : filledTemplate.cc,
    },
    Message: {
      Body: {
        Html: { Data: filledTemplate.body, Charset: "UTF-8" },
        Text: {
          Data: htmlToText(filledTemplate.body, htmlToTextOptions(baseUrl)),
          Charset: "UTF-8",
        },
      },
      Subject: { Data: filledTemplate.subject, Charset: "UTF-8" },
    },
    Source: sourceEmail,
    ConfigurationSetName: process.env.configurationSetName,
  };
  console.log("Email params:", JSON.stringify(params, null, 2));
  return params;
}
 
export async function sendEmail(params: SendEmailCommandInput, region: string): Promise<any> {
  const sesClient = new SESClient({ region: region });
  console.log("sendEmail called with params:", JSON.stringify(params, null, 2));
 
  const command = new SendEmailCommand(params);
  try {
    const result = await sesClient.send(command);
    return { status: result.$metadata.httpStatusCode };
  } catch (error) {
    console.error("Error sending email:", error);
    throw error;
  }
}
 
const htmlToTextOptions = (baseUrl: string): HtmlToTextOptions => ({
  wordwrap: 80,
  preserveNewlines: true,
  selectors: [
    {
      selector: "h1",
      options: {
        uppercase: true,
        leadingLineBreaks: 2,
        trailingLineBreaks: 1,
      },
    },
    {
      selector: "img",
      options: {
        ignoreHref: true,
        src: true,
      },
    },
    {
      selector: "p",
      options: {
        leadingLineBreaks: 1,
        trailingLineBreaks: 1,
      },
    },
    {
      selector: "a",
      options: {
        linkBrackets: ["[", "]"],
        baseUrl,
        hideLinkHrefIfSameAsText: true,
      },
    },
  ],
  limits: {
    maxInputLength: 50000,
    ellipsis: "...",
    maxBaseElements: 1000,
  },
  longWordSplit: {
    forceWrapOnLimit: false,
    wrapCharacters: ["-", "/"],
  },
});