All files / lib/libs/email index.ts

97.29% Statements 36/37
83.33% Branches 20/24
100% Functions 9/9
97.29% Lines 36/37

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                                                                                                  4x                                               4x     2x 2x               6x 6x           28x           31x       30x             33x 2x     31x 3x     28x   28x   28x 27x     1x                     5x 5x     4x 1x 1x       3x 6x       3x 2x 2x       1x 4x 4x 4x       1x   1x   1x 1x          
import { Authority, Events } from "shared-types";
import { changelog } from "shared-types/opensearch";
 
import { getPackageChangelog } from "../api/package";
import * as EmailContent from "./content";
 
export type UserType = "cms" | "state";
 
export interface EmailTemplate {
  to: string[];
  cc?: string[];
  subject: string;
  body: string;
}
 
export type EmailTemplateFunction<T> = (variables: T) => Promise<EmailTemplate>;
export type UserTypeOnlyTemplate = {
  [U in UserType]: EmailTemplateFunction<any>;
};
export type AuthoritiesWithUserTypesTemplate = {
  [A in Authority]?: { [U in UserType]?: EmailTemplateFunction<any> };
};
 
export type EmailTemplates = {
  "new-medicaid-submission": AuthoritiesWithUserTypesTemplate;
  "new-chip-submission": AuthoritiesWithUserTypesTemplate;
  "new-chip-details-submission": AuthoritiesWithUserTypesTemplate;
  "temporary-extension": AuthoritiesWithUserTypesTemplate;
  "withdraw-package": AuthoritiesWithUserTypesTemplate;
  "withdraw-rai": AuthoritiesWithUserTypesTemplate;
  "contracting-initial": AuthoritiesWithUserTypesTemplate;
  "capitated-initial": AuthoritiesWithUserTypesTemplate;
  "contracting-amendment": AuthoritiesWithUserTypesTemplate;
  "capitated-amendment": AuthoritiesWithUserTypesTemplate;
  "contracting-renewal": AuthoritiesWithUserTypesTemplate;
  "capitated-renewal": AuthoritiesWithUserTypesTemplate;
  "contracting-amendment-state": AuthoritiesWithUserTypesTemplate;
  "capitated-amendment-state": AuthoritiesWithUserTypesTemplate;
  "contracting-renewal-state": AuthoritiesWithUserTypesTemplate;
  "capitated-renewal-state": AuthoritiesWithUserTypesTemplate;
  "respond-to-rai": AuthoritiesWithUserTypesTemplate;
  "seatool-withdraw": AuthoritiesWithUserTypesTemplate;
  "app-k": AuthoritiesWithUserTypesTemplate;
  "upload-subsequent-documents": AuthoritiesWithUserTypesTemplate;
};
 
type EmailEvent = keyof EmailTemplates;
 
// Create a type-safe mapping of email templates
const emailTemplates: EmailTemplates = {
  "new-medicaid-submission": EmailContent.newSubmission,
  "new-chip-submission": EmailContent.newSubmission,
  "new-chip-details-submission": EmailContent.newSubmission,
  "temporary-extension": EmailContent.tempExtension,
  "withdraw-package": EmailContent.withdrawPackage,
  "withdraw-rai": EmailContent.withdrawRai,
  "contracting-initial": EmailContent.newSubmission,
  "capitated-initial": EmailContent.newSubmission,
  "contracting-amendment": EmailContent.newSubmission,
  "capitated-amendment": EmailContent.newSubmission,
  "contracting-renewal": EmailContent.newSubmission,
  "capitated-renewal": EmailContent.newSubmission,
  "contracting-amendment-state": EmailContent.newSubmission,
  "capitated-amendment-state": EmailContent.newSubmission,
  "contracting-renewal-state": EmailContent.newSubmission,
  "capitated-renewal-state": EmailContent.newSubmission,
  "respond-to-rai": EmailContent.respondToRai,
  "seatool-withdraw": EmailContent.withdrawConfirmation,
  "app-k": EmailContent.newSubmission,
  "upload-subsequent-documents": EmailContent.uploadSubsequentDocuments,
};
 
// user roles are so different they will be their own thing for now
export const getUserRoleTemplate = async (
  userRoleAction: keyof typeof EmailContent.userRoleTemplate,
): Promise<(variables: EmailContent.UserRoleEmailType) => Promise<EmailTemplate>> => {
  const userRoleTemplate = EmailContent.userRoleTemplate;
  return userRoleTemplate[userRoleAction];
};
 
// Create a type-safe lookup function
export function getEmailTemplate(
  action: keyof EmailTemplates,
): AuthoritiesWithUserTypesTemplate | UserTypeOnlyTemplate {
  // Handle -state suffix variants
  const baseAction = action?.replace(/-state$/, "") as keyof EmailTemplates;
  return emailTemplates[baseAction];
}
 
function hasAuthority(
  obj: Events[keyof Events],
): obj is Extract<Events[keyof Events], { authority: string }> {
  return "authority" in obj;
}
 
function hasEvent(
  obj: Events[keyof Events],
): obj is Extract<Events[keyof Events], { event: string }> {
  return "event" in obj;
}
 
function isEmailEvent(event: unknown): event is EmailEvent {
  return typeof event === "string" && event in emailTemplates;
}
 
// Update the getEmailTemplates function to use the new lookup
export async function getEmailTemplates(
  record: Events[keyof Events],
): Promise<EmailTemplateFunction<typeof record>[]> {
  if (!record) {
    throw new Error("Invalid record");
  }
 
  if (!hasEvent(record) || !isEmailEvent(record.event)) {
    throw new Error("Missing event or email template for event");
  }
 
  Eif (hasAuthority(record)) {
    const authorityTemplates =
      emailTemplates[record.event][record.authority.toLowerCase() as Authority];
 
    if (authorityTemplates) {
      return Object.values(authorityTemplates);
    }
 
    throw new Error("No email template found for authority");
  }
 
  throw new Error("Missing event authority or email template for event");
}
 
// I think this needs to be written to handle not finding any matching events and so forth
export async function getLatestMatchingEvent(
  id: string,
  actionType: string,
): Promise<changelog.Document | null> {
  try {
    const item = await getPackageChangelog(id);
 
    // Check if item exists and has hits
    if (!item?.hits?.hits?.length) {
      console.log(`No changelog found for package ${id}`);
      return null;
    }
 
    // Filter events with _source and matching events
    const events = item.hits.hits.filter(
      (event) => event?._source && event._source.event === actionType,
    );
 
    // Check if any matching events were found
    if (!events.length) {
      console.log(`No events found for package ${id}`);
      return null;
    }
 
    // Sort events by timestamp (most recent first)
    events.sort((a, b) => {
      const timestampA = a._source?.timestamp ?? 0;
      const timestampB = b._source?.timestamp ?? 0;
      return timestampB - timestampA;
    });
 
    // Get the latest event
    const latestMatchingEvent = events?.[0]?._source ?? null;
 
    return latestMatchingEvent;
  } catch (error) {
    console.error("Error getting latest matching event:", { id, error });
    return null;
  }
}
 
export * from "./getAllStateUsers";