All files / server/src/features/admin emailTestController.ts

66.1% Statements 39/59
55% Branches 11/20
100% Functions 3/3
66.1% Lines 39/59

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                                                                                    42x             2x 1x         1x 1x       1x 2x   1x       1x               1x         42x       5x   5x 5x         5x 5x 2x             2x 1x   1x 1x 1x     3x 3x             3x         3x       3x   2x       2x         2x     1x       1x         1x                                                                                                                                             3x 3x   2x     2x   1x 1x      
import { Request, Response } from "express";
import { config } from "shared/config";
import { PostEmailTestRequest } from "shared/test-types/api/testData";
import { EmailNotificationTrigger } from "shared/types/emailNotification";
import {
  Result,
  makeErrorResult,
  makeSuccessResult,
} from "shared/utils/result";
import { getLotteriedSpan } from "server/features/assignment/utils/addAssignmentNotifications";
import { EmailSender } from "server/features/notifications/email";
import {
  EmailMessage,
  buildEmail,
  getAcceptedEmailTemplate,
  getProgramItemCancelledEmailTemplate,
  getProgramItemDeletedEmailTemplate,
  getProgramItemNoKonstiSignupEmailTemplate,
  getProgramItemNoLotteryEmailTemplate,
  getProgramItemTimeChangedEmailTemplate,
  getRejectedEmailTemplate,
} from "server/features/notifications/senderCommon";
import {
  findProgramItemById,
  findProgramItems,
} from "server/features/program-item/programItemRepository";
import { logger } from "server/utils/logger";
import {
  NotificationTask,
  NotificationTaskType,
} from "server/utils/notificationQueue";
 
interface GetBatchedRejectionEmailParams {
  parentId: string;
  batchStartTime: string;
  notificationType: EmailNotificationTrigger;
  email: string;
  fromAddress: string;
}
 
// Built from the batch's own program items through the same span helper a run uses, so what the
// admin reads in their inbox is what a rejected attendee would have read
const getBatchedRejectionEmail = async ({
  parentId,
  batchStartTime,
  notificationType,
  email,
  fromAddress,
}: GetBatchedRejectionEmailParams): Promise<Result<EmailMessage, string>> => {
  if (notificationType !== EmailNotificationTrigger.REJECTED) {
    return makeErrorResult(
      `${parentId} is a batch, which only the ${EmailNotificationTrigger.REJECTED} message covers`,
    );
  }
 
  const programItemsResult = await findProgramItems();
  Iif (!programItemsResult.ok) {
    return makeErrorResult("Failed to read the programme");
  }
 
  const batchProgramItems = programItemsResult.value.filter(
    (programItem) => programItem.parentId === parentId,
  );
  Iif (batchProgramItems.length === 0) {
    return makeErrorResult(`No program items are in batch ${parentId}`);
  }
 
  const mockNotification: NotificationTask = {
    username: "test-user",
    // A rejection names no program item, the same as the one a run writes
    programItemId: "",
    type: NotificationTaskType.SEND_EMAIL_REJECTED,
    ...getLotteriedSpan(batchProgramItems, batchStartTime),
  };
 
  return makeSuccessResult(
    buildEmail(getRejectedEmailTemplate(mockNotification), email, fromAddress),
  );
};
 
export const postEmailTest = async (
  req: Request<unknown, unknown, PostEmailTestRequest>,
  res: Response,
): Promise<Response> => {
  const { email, notificationType, programId } = req.body;
 
  try {
    const fromAddress = config.server().emailSendFromAddress;
 
    // A batched lottery decides several starting times at once and its rejection names the span
    // rather than one hour, so it has no single program item to be tested through. The parent
    // the batch is configured under stands in for it.
    const batchStartTime = config.event().startTimesByParentIds.get(programId);
    if (batchStartTime !== undefined) {
      const batchMessageResult = await getBatchedRejectionEmail({
        parentId: programId,
        batchStartTime,
        notificationType,
        email,
        fromAddress,
      });
      if (!batchMessageResult.ok) {
        return res.status(400).json({ message: batchMessageResult.error });
      }
      await new EmailSender().sendEmail(batchMessageResult.value);
      logger.info(`Test email sent to ${email} for batch ${programId}`);
      return res.status(200).json({ message: "Test email sent successfully" });
    }
 
    const programItemResult = await findProgramItemById(programId);
    Iif (!programItemResult.ok) {
      logger.error(
        new Error(`Failed to find program for programItemId ${programId}`),
      );
      return res.status(500).json({ message: "Failed to send test email" });
    }
 
    const baseMockNotification = {
      username: "test-user",
      programItemId: programId,
      programItemStartTime: programItemResult.value.startTime,
    };
    const programTitle = programItemResult.value.title;
 
    let message: EmailMessage;
 
    switch (notificationType) {
      case EmailNotificationTrigger.ACCEPTED: {
        const mockNotification: NotificationTask = {
          ...baseMockNotification,
          type: NotificationTaskType.SEND_EMAIL_ACCEPTED,
        };
        message = buildEmail(
          getAcceptedEmailTemplate(programTitle, mockNotification),
          email,
          fromAddress,
        );
        break;
      }
      case EmailNotificationTrigger.REJECTED: {
        const mockNotification: NotificationTask = {
          ...baseMockNotification,
          type: NotificationTaskType.SEND_EMAIL_REJECTED,
        };
        message = buildEmail(
          getRejectedEmailTemplate(mockNotification),
          email,
          fromAddress,
        );
        break;
      }
      case EmailNotificationTrigger.PROGRAM_ITEM_CANCELLED: {
        const mockNotification: NotificationTask = {
          ...baseMockNotification,
          type: NotificationTaskType.SEND_EMAIL_PROGRAM_ITEM_CANCELLED,
          programItemTitle: programTitle,
        };
        message = buildEmail(
          getProgramItemCancelledEmailTemplate(mockNotification),
          email,
          fromAddress,
        );
        break;
      }
      case EmailNotificationTrigger.PROGRAM_ITEM_DELETED: {
        const mockNotification: NotificationTask = {
          ...baseMockNotification,
          type: NotificationTaskType.SEND_EMAIL_PROGRAM_ITEM_DELETED,
          programItemTitle: programTitle,
        };
        message = buildEmail(
          getProgramItemDeletedEmailTemplate(mockNotification),
          email,
          fromAddress,
        );
        break;
      }
      case EmailNotificationTrigger.PROGRAM_ITEM_NO_KONSTI_SIGNUP_ANYMORE: {
        const mockNotification: NotificationTask = {
          ...baseMockNotification,
          type: NotificationTaskType.SEND_EMAIL_PROGRAM_ITEM_NO_KONSTI_SIGNUP_ANYMORE,
          programItemTitle: programTitle,
        };
        message = buildEmail(
          getProgramItemNoKonstiSignupEmailTemplate(mockNotification),
          email,
          fromAddress,
        );
        break;
      }
      case EmailNotificationTrigger.PROGRAM_ITEM_NO_LOTTERY_ANYMORE: {
        const mockNotification: NotificationTask = {
          ...baseMockNotification,
          type: NotificationTaskType.SEND_EMAIL_PROGRAM_ITEM_NO_LOTTERY_ANYMORE,
          programItemTitle: programTitle,
        };
        message = buildEmail(
          getProgramItemNoLotteryEmailTemplate(mockNotification),
          email,
          fromAddress,
        );
        break;
      }
      case EmailNotificationTrigger.PROGRAM_ITEM_TIME_CHANGED: {
        const mockNotification: NotificationTask = {
          ...baseMockNotification,
          type: NotificationTaskType.SEND_EMAIL_PROGRAM_ITEM_TIME_CHANGED,
          programItemTitle: programTitle,
        };
        message = buildEmail(
          getProgramItemTimeChangedEmailTemplate(mockNotification),
          email,
          fromAddress,
        );
        break;
      }
      default:
        return res.status(400).json({ message: "Invalid notification type" });
    }
 
    const emailSender = new EmailSender();
    await emailSender.sendEmail(message);
 
    logger.info(
      `Test email sent to ${email} for notification type ${notificationType}`,
    );
    return res.status(200).json({ message: "Test email sent successfully" });
  } catch (error) {
    logger.error(new Error("Failed to send test email", { cause: error }));
    return res.status(500).json({ message: "Failed to send test email" });
  }
};