All files / api/routes baseVerifyHandler.ts

99.19% Statements 247/249
84% Branches 21/25
100% Functions 1/1
99.19% Lines 247/249

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 2501x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 9x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 7x 7x 9x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x   1x 1x 1x 1x 1x 1x 1x 1x 6x 6x 6x 9x 1x 1x 9x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 5x 5x 5x 5x 5x 5x 5x 5x 9x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 3x 3x 3x 3x 3x 3x 3x 9x 1x 1x 1x 1x 1x 1x 3x 9x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 9x 2x 2x 2x 2x 2x 2x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 9x 9x 9x 3x   9x 9x 9x 9x 9x 3x  
import Koa from 'koa';
 
import { IVerifyRequestParams } from '@api/contracts/verifyRequestParam';
import { errorResponse } from '@api/misc/httpResponse/errorResponse';
import { IApiModule } from '@api/types/baseModule';
import { ApiStatusErrorCode, apiParams } from '@constants/api';
import {
  approvalStatusFromString,
  colourFromApprovalStatus,
  getFriendlyApprovalStatus,
} from '@constants/enum/approvalStatus';
import { lineBreak } from '@constants/form';
import { routes } from '@constants/route';
import { DiscordWebhookResponse } from '@contracts/generated/discordWebhookResponse';
import { ResultWithValue } from '@contracts/resultWithValue';
import { baseSubmissionMessageBuilder, getDescriptionLines } from '@helpers/discordMessageHelper';
import { anyObject } from '@helpers/typescriptHacks';
import { getDiscordService } from '@services/external/discord/discordService';
import { getGithubWorkflowService } from '@services/external/githubWorkflowService';
import { getConfig } from '@services/internal/configService';
import { getLog } from '@services/internal/logService';
 
export const baseVerifyHandler =
  <TD, TF, TP>(module: IApiModule<TD, TF, TP>) =>
  async (ctx: Koa.DefaultContext, next: () => Promise<Koa.BaseResponse>) => {
    const params: IVerifyRequestParams = {
      id: ctx.params[apiParams.verify.id],
      decision: ctx.params[apiParams.verify.decision],
      check: ctx.params[apiParams.verify.check],
    };
    const handlerName = `verifyHandler-${module.segment}-${params.id}`;
    getLog().i(handlerName);
 
    const approvalStatus = approvalStatusFromString(params.decision);
    if (approvalStatus == null) {
      const errMsg = `${handlerName} - Approval status not understood: ${params.decision}`;
      getLog().e(errMsg);
      await errorResponse({
        ctx,
        next,
        statusCode: ApiStatusErrorCode.decisionNotFound.code,
        message: errMsg,
      });
      return;
    }
 
    const urlSegments = [
      getConfig().getNmsUdFormWebUrl(),
      '/#/',
      routes.verify.path,
      '?',
      routes.verify.queryParam.id,
      '=',
      params.id,
    ];
 
    const readRecordResult = await module.readRecord(params.id);
    if (readRecordResult.isSuccess == false) {
      const errMsg = `${handlerName} - An error occurred while getting a db record with id: ${params.id}`;
      getLog().e(errMsg);
      const additionalUrlSegments = [
        '&',
        routes.verify.queryParam.code,
        '=',
        ApiStatusErrorCode.recordNotFound.code,
        '&',
        routes.verify.queryParam.message,
        '=',
        encodeURI('Could not find submission!'),
        '&',
        routes.verify.queryParam.detail,
        '=',
        encodeURI(
          'The link you clicked is no longer valid! The submission may have been deleted...',
        ),
      ];
      ctx.response.status = 303;
      ctx.response.body = ApiStatusErrorCode.recordNotFound.code;
      ctx.redirect([...urlSegments, ...additionalUrlSegments].join(''));
      await next();
      return;
    }
    const discordWebhookId = readRecordResult.value.discordWebhookId;
 
    if (readRecordResult.value.approvalStatus == approvalStatus) {
      getLog().i(`${handlerName} - Approval status received matches what is in the database`);
      const additionalUrlSegments = [
        '&',
        routes.verify.queryParam.code,
        '=',
        '200',
        '&',
        routes.verify.queryParam.message,
        '=',
        encodeURI('No changes made'),
        '&',
        routes.verify.queryParam.detail,
        '=',
        encodeURI('The selected decision was already made, so no changes required. '),
        encodeURI(
          discordWebhookId == null
            ? 'Unable to update Discord message'
            : 'Attempting to update discord message...',
        ),
      ];
      ctx.response.status = 303;
      ctx.response.body = 200;
      ctx.redirect([...urlSegments, ...additionalUrlSegments].join(''));
      await next();
      return;
    }
 
    try {
      const calculatedCheck = module.calculateCheck(readRecordResult.value);
      if (calculatedCheck != parseInt(params.check)) {
        throw 'calculated check value does not match the supplied check';
      }
    } catch (ex) {
      const errMsg = `${handlerName} - The calculated check value does not match the supplied check value. Maybe the data changed?`;
      getLog().e(errMsg);
      const additionalUrlSegments = [
        '&',
        routes.verify.queryParam.code,
        '=',
        ApiStatusErrorCode.calculatedCheckFailed.code,
        '&',
        routes.verify.queryParam.message,
        '=',
        encodeURI('Invalid check value'),
        '&',
        routes.verify.queryParam.detail,
        '=',
        encodeURI(errMsg),
      ];
      ctx.response.status = 303;
      ctx.response.body = ApiStatusErrorCode.calculatedCheckFailed.code;
      ctx.redirect([...urlSegments, ...additionalUrlSegments].join(''));
      await next();
      return;
    }
 
    const updatedPersistence = {
      ...readRecordResult.value,
      approvalStatus,
    };
 
    getLog().i(`${handlerName} - Updating database record`);
    const updateRecordResult = await module.updateRecord(updatedPersistence.id, updatedPersistence);
    if (updateRecordResult.isSuccess == false) {
      const errMsg = `${handlerName} - An error occurred while updating the approval status of record: ${params.id}`;
      getLog().e(errMsg);
      const additionalUrlSegments = [
        '&',
        routes.verify.queryParam.code,
        '=',
        ApiStatusErrorCode.couldNotPersistData.code,
        '&',
        routes.verify.queryParam.message,
        '=',
        encodeURI('Could not update the database'),
        '&',
        routes.verify.queryParam.detail,
        '=',
        encodeURI(errMsg),
      ];
      ctx.response.status = 303;
      ctx.response.body = ApiStatusErrorCode.couldNotPersistData.code;
      ctx.redirect([...urlSegments, ...additionalUrlSegments].join(''));
      await next();
      return;
    }
 
    const githubWorkflowTriggerTask = getGithubWorkflowService().triggerWorkflowIfNotRunRecently();
    let discordMessageTask: Promise<ResultWithValue<DiscordWebhookResponse>> =
      Promise.resolve(anyObject);
 
    const tempDto = module.mapPersistenceToDto(readRecordResult.value);
    let dtoForDiscord = { ...tempDto };
    if (module.mapRecordRelationshipsToDto != null) {
      const dtoResult = await module.mapRecordRelationshipsToDto(
        readRecordResult.value.id,
        tempDto,
      );
      dtoForDiscord = dtoResult.value;
    }
 
    if (discordWebhookId != null) {
      getLog().i(`${handlerName} - Updating Discord message`);
      const msgColour = colourFromApprovalStatus(approvalStatus);
      const authorName = module.getName(readRecordResult.value);
      const iconUrl = module.getIcon?.(readRecordResult.value);
      const descripLines = await getDescriptionLines({
        data: dtoForDiscord,
        dtoMeta: module.dtoMeta,
      });
      const webhookPayload = baseSubmissionMessageBuilder({
        content: '',
        colour: msgColour,
        authorName,
        iconUrl,
        descripLines: [
          ...descripLines,
          `\n**Decision: ${getFriendlyApprovalStatus(approvalStatus)}**`,
        ],
        additionalEmbeds: [],
      });
      discordMessageTask = getDiscordService().updateDiscordMessage(
        getConfig().getDiscordWebhookUrl(),
        discordWebhookId,
        webhookPayload,
      );
    } else {
      discordMessageTask = Promise.resolve({
        isSuccess: false,
        value: anyObject,
        errorMessage: 'Discord WebhookId was null in the database',
      });
    }
 
    const [githubWorkflowResult, discordMessageResult] = await Promise.all([
      githubWorkflowTriggerTask,
      discordMessageTask, //
    ]);
 
    const additionalUrlSegments = [
      '&',
      routes.verify.queryParam.code,
      '=',
      '200',
      '&',
      routes.verify.queryParam.message,
      '=',
      encodeURI(`Your action was successfully handled.`),
      '&',
      routes.verify.queryParam.detail,
      '=',
      encodeURI(`Github Action response: ${githubWorkflowResult.errorMessage}${lineBreak}`),
      encodeURI(
        `Discord webhook message update was ${discordMessageResult.isSuccess ? 'successful' : 'unsuccessful'}.${lineBreak}`,
      ),
      !discordMessageResult.isSuccess
        ? encodeURI(`Discord error message: "${discordMessageResult.errorMessage}".`)
        : '',
    ];
    ctx.response.status = 303;
    ctx.response.body = 200;
    ctx.redirect([...urlSegments, ...additionalUrlSegments].join(''));
    await next();
  };