All files / src/components/aws/services aws-ses.service.ts

13.27% Statements 13/98
0% Branches 0/51
4.55% Functions 1/22
13.83% Lines 13/94

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 3001x   1x 1x 1x 1x   1x     1x 1x         1x       1x 1x     1x 1x                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    
import { SES } from 'aws-sdk';
import { CreateTemplateRequest, DeleteTemplateRequest } from 'aws-sdk/clients/ses';
import { AwsConfigs, Constants } from '../../../configs';
import * as nodemailer from 'nodemailer';
import * as handlebars from 'handlebars';
import path from 'path';
import Mail from 'nodemailer/lib/mailer';
import { HttpErrors } from '@loopback/rest';
import { User } from '@logchain/models';
import { AnyObject } from 'loopback-datasource-juggler';
import { DateUtils } from '@logchain/utils';
const fs = require('fs').promises;
 
/**
 * AWS SES Service
 */
export class AwsSesService {
  ses: SES;
  transporter: nodemailer.Transporter;
 
  sender = `${AwsConfigs.sender}`;
  listActionHeader = ['Job ID', 'Job Name', 'Action Type', 'Action Item', 'Expected Date'];
 
  constructor() {
    this.ses = new SES();
    this.transporter = nodemailer.createTransport({
      SES: { ses: this.ses, aws: SES },
    } as any);
  }
  
  /**
   * Send an email.
   * @param template The template email.
   * @param recipients The recipient email.
   * @param replacement_data The replacement data.
   */
  async sendTemplatedEmail(
    template: string,
    recipientObjects: User | User[],
    replacement_data: Object = {},
  ): Promise<SES.Types.SendTemplatedEmailResponse> {
    const recipients: User[] = Array.isArray(recipientObjects) ? recipientObjects : [recipientObjects];
    const params = {
      Source: this.sender,
      Template: template + '-' + recipients[0].language,
      Destination: {
        ToAddresses: recipients.map(recipient => recipient.contact_email),
      },
      TemplateData: JSON.stringify(replacement_data),
    };
 
    try {
      return this.ses.sendTemplatedEmail(params).promise();
    } catch (err) {
      // Because we use sandbox environment on dev, so sometime when we
      // delete a user, it'll send MessageRejected code for unverify user
      // we will by pass this and log on our system then return success
      if (err.code === 'MessageRejected') {
        console.log(err.message);
        return <SES.Types.SendTemplatedEmailResponse>{};
      }
      else throw new HttpErrors.BadRequest(err);
    }
  }
 
  /**
   * Send bulk email.
   * @param template The email template.
   * @param recipients The recipients email.
   * @param replacements_data The replacements data.
   */
  async sendBulkTemplatedEmail(
    template: string,
    recipients: { email: string; language: string, replacement_data: Object }[],
  ): Promise<SES.Types.SendTemplatedEmailResponse[] | void> {
    const sendMailTasks = [];
    for(const recipient of recipients){
      const params: SES.Types.SendTemplatedEmailRequest = {
        Source: this.sender,
        Destination: { ToAddresses: [recipient.email] },
        Template: template + '-' + recipient.language,
        TemplateData: JSON.stringify(recipient.replacement_data),
      };
 
      sendMailTasks.push(this.ses.sendTemplatedEmail(params).promise());
    }
 
    try {
      await Promise.all(sendMailTasks);
    } catch (err) {
      if (err.code === 'MessageRejected') {
        console.log(err.message);
        return;
      }
      throw err;
    }
  }
 
  /**
   * Create or update new email template.
   * @param template The template object.
   */
  async createOrUpdateTemplate(
    template: CreateTemplateRequest,
  ): Promise<SES.Types.CreateTemplateResponse> {
    try {
      return await this.ses.createTemplate(template).promise();
    } catch (error) {
      if (error.code === 'AlreadyExists') {
        return await this.ses.updateTemplate(template).promise();
      }
 
      throw error;
    }
  }
 
  /**
   * Deletes a template.
   *
   * @param {DeleteTemplateRequest} template - The template to delete.
   * @return {Promise<SES.Types.DeleteTemplateResponse>} A promise that resolves with the response from deleting the template.
   */
  async deleteTemplate(
    template: DeleteTemplateRequest,
  ): Promise<SES.Types.DeleteTemplateResponse> {
    return this.ses.deleteTemplate(template).promise();
  }
 
  /**
   * Sends an email with attachments.
   *
   * @param {string} subject - The subject of the email.
   * @param {string} templateFile - The file name of the email template.
   * @param {string | string[]} recipients - The email recipients.
   * @param {string[]} cc - The email CC recipients.
   * @param {Object} replacements - The object containing replacement values for the email template.
   * @param {{ filename: string; content: Buffer; contentType: string }[]} attachments - The email attachments.
   * @return {Promise<void>} - A promise that resolves after the email is sent.
   */
  async sendEmailWithAttachment(subject: string, templateFile: string, recipients: string | string[], cc: string[], replacements: Object = {}, attachments: { filename: string; content: Buffer, contentType: string }[] = []) {
    if (typeof recipients === 'string') {
      recipients = [recipients];
    }
    const filePath = path.join(__dirname, '..', 'email-templates', 'en', 'html', templateFile);
    const source = await fs.readFile(filePath, 'utf-8');
    const htmlToSend = handlebars.compile(source)(replacements);
    const subjectToSend = handlebars.compile(subject)(replacements);
    const mailOptions: Mail.Options = {
      from: this.sender,
      to: recipients,
      cc,
      subject: subjectToSend,
      html: htmlToSend,
      attachments
    };
    try {
      await this.transporter.sendMail(mailOptions);
    } catch (error) {
      if (error.code === 'MessageRejected') {
        console.log(error.message);
        return;
      }
      throw error;
    }
  }
 
  /**
   * Generates a template actions Text.
   *
   * @param {AnyObject[]} actions - An array of AnyObject representing the actions.
   * @param {string[]} headers - An array of header representing the actions.
   * @return {void} This function does not return a value.
   */
  generateTemplateTableText(actions: AnyObject[], headers: string[]): string {
    if (!actions?.length) {
      return '';
    }
 
    const content = [];
    if (actions.length > Constants.MaxItemsForActionListInEmail) {
      actions = actions.slice(0, Constants.MaxItemsForActionListInEmail);
    }
 
    content.push(headers.map((header: string) => `${header}`).join('\t'));
    content.push('\r\n');
 
    for (const action of actions) {
      content.push(
        Object.keys(action).map((property) => `${action[property]}\t`).join(''),
      );
      content.push('\n');
    }
 
    return `\r\n\r\n${content.join('')}\r\n\r\n`;
  }
 
  /**
   * Generates a template table HTML.
   *
   * @param {AnyObject[]} actions - An array of AnyObject representing the actions.
   * @param {string[]} headers - An array of header representing the data.
   * @return {string} The HTML table.
   */
  generateTemplateTableHTML(actions: AnyObject[], headers: string[]): string {
    if (!actions?.length) {
      return '';
    }
 
    if (actions.length > Constants.MaxItemsForActionListInEmail) {
      actions = actions.slice(0, Constants.MaxItemsForActionListInEmail);
    }
 
    const strHeader = headers.map((header: string) => `<th>${header}</th>`).join('');
    const strRows = actions.map((row: AnyObject, index: number) => {
      const content = [];
      content.push(`<tr ${index % 2 !== 0 ? 'style="background-color: rgb(245, 245, 245);"': ''}>`);
      Object.keys(row).forEach((property) => {
        content.push(`<td>${row[property]}</td>`);
      });
      content.push('</tr>');
 
      return content.join('');
    }).join('');
 
    return `<table class="table" style="border: 1px solid;"><thead><tr style="background-color: rgb(236, 236, 236); text-align: left;">${strHeader}</tr></thead><tbody>${strRows}</tbody></table>\r\n`;
  }
 
  /**
   * Generates a template actions Text.
   *
   * @param {AnyObject[]} actions - An array of AnyObject representing the actions.
   * @return {void} This function does not return a value.
   */
  generateTemplateActionsText(actions: AnyObject[]): string {
    if (actions?.length) {
      // If actions bigger than 100 we should truncate it to 100
      if (actions.length > Constants.MaxItemsForActionListInEmail) {
        actions = actions.slice(0, Constants.MaxItemsForActionListInEmail);
      }
      const strHeader = this.listActionHeader.map((header: string) => `${header}`).join('\t');
      const strAction = actions.map((action: AnyObject) => {
        return (
          `${action.flow_id}\t
           ${action.flow_name}\t
           ${action.action_type}\t
           ${action.action_item}\t
           ${action.expected_date}\r\n
          `
        );
      }).join('');
 
      return `\r\n\r\n${strHeader}\r\n${strAction}\r\n\r\n`;
    }
 
    return '';
  }
 
  /**
   * Generates a template actions HTML.
   *
   * @param {AnyObject[]} actions - An array of AnyObject representing the actions.
   * @return {void} This function does not return a value.
   */
  generateTemplateActionsHTML(actions: AnyObject[]): string {
    if (!actions?.length) {
      return '';
    }
 
    if (actions.length > Constants.MaxItemsForActionListInEmail) {
      actions = actions.slice(0, Constants.MaxItemsForActionListInEmail);
    }
 
    const strHeader = this.createTableHeader();
    const strAction = this.createTableRows(actions);
 
    return `<table class="table" style="border: 1px solid;">
              <thead><tr style="background-color: rgb(236, 236, 236); text-align: left;">${strHeader}</tr></thead>
              <tbody>${strAction}</tbody>
            </table>\r\n`;
  }
 
  private createTableHeader(): string {
    return this.listActionHeader.map((header: string) => `<th>${header}</th>`).join('');
  }
 
  private createTableRows(actions: AnyObject[]): string {
    return actions.map((action: AnyObject, index: number) => {
      return (
        `<tr ${index % 2 !== 0 ? 'style="background-color: rgb(245, 245, 245);"' : ''}>
          <td>${action.flow_id}</td>
          <td>${action.flow_name}</td>
          <td>${action.action_type}</td>
          <td>${action.action_item}</td>
          <td>${DateUtils.formatDate(action.expected_date, 'DD/MM/YY HH:mm')}</td>
        </tr>`
      );
    }).join('');
  }
}