All files / helpers discordMessageHelper.ts

96.34% Statements 158/164
93.1% Branches 27/29
88.88% Functions 8/9
96.34% Lines 158/164

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 1651x 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 1x 1x 1x 1x 1x 1x 1x 1x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 1x 1x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 1x 1x 4x 4x 4x 8x     8x 8x 4x 4x 6x 8x 8x 8x 2x 2x 4x 8x 4x 4x 4x 4x 4x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x         1x 1x 1x 1x 1x 7x 7x 7x 7x 2x 2x 5x 5x 1x 1x 1x 4x 4x 4x 2x 2x  
import { api, apiParams } from '@constants/api';
import { ApprovalStatus, approvalStatusToString } from '@constants/enum/approvalStatus';
import { FormDtoMeta, FormDtoMetaDetails } from '@contracts/dto/forms/baseFormDto';
import {
  DiscordWebhook,
  DiscordWebhookAttachment,
  DiscordWebhookEmbed,
  DiscordWebhookField,
} from '@contracts/generated/discordWebhook';
import { ResultWithValue } from '@contracts/resultWithValue';
import { makeArrayOrDefault } from '@helpers/arrayHelper';
import { addSpacesForEnum, capitalizeFirstLetter } from '@helpers/stringHelper';
import { ObjectWithPropsOfValue, anyObject } from '@helpers/typescriptHacks';
import { getConfig } from '@services/internal/configService';
import { formatDate } from './dateHelper';
 
export interface IMessageBuilderProps<T, TP> {
  dbId: string;
  persistence: TP;
  segment: string;
  calculateCheck: number;
  dtoMeta: FormDtoMeta<T>;
  includeActionsEmbed: boolean;
  approvalStatus: ApprovalStatus;
}
 
export const discordActionLink = {
  heading: 'Quick action',
  reject: '❌ Reject',
  accept: '✅ Approve',
  defaultAuthorName: 'NMSUD form Submission',
};
 
export const baseSubmissionMessageEmbed = (
  dbId: string,
  check: number,
  segment: string,
): DiscordWebhookEmbed => {
  const apiUrl = getConfig().getNmsUdApiUrl();
 
  const quickRejectUrl =
    apiUrl +
    '/' +
    api.routes.verify
      .replaceAll(`:${apiParams.verify.id}`, dbId)
      .replaceAll(`:${apiParams.general.segment}`, segment)
      .replaceAll(`:${apiParams.verify.check}`, check.toString())
      .replaceAll(`:${apiParams.verify.decision}`, approvalStatusToString(ApprovalStatus.denied));
 
  const quickApproveUrl =
    apiUrl +
    '/' +
    api.routes.verify
      .replaceAll(`:${apiParams.verify.id}`, dbId)
      .replaceAll(`:${apiParams.general.segment}`, segment)
      .replaceAll(`:${apiParams.verify.check}`, check.toString())
      .replaceAll(`:${apiParams.verify.decision}`, approvalStatusToString(ApprovalStatus.approved));
 
  return {
    fields: [
      {
        name: discordActionLink.heading,
        value: `[${discordActionLink.reject}](${quickRejectUrl})`,
        inline: true,
      },
      {
        name: discordActionLink.heading,
        value: `[${discordActionLink.accept}](${quickApproveUrl})`,
        inline: true,
      },
    ],
  };
};
 
export const baseSubmissionMessageBuilder = (props: {
  content: string;
  colour: number;
  authorName?: string;
  iconUrl?: string | null;
  descripLines: Array<string>;
  fields?: Array<DiscordWebhookField>;
  additionalEmbeds: Array<DiscordWebhookEmbed>;
  attachments?: Array<DiscordWebhookAttachment>;
}): DiscordWebhook => {
  const embeds: Array<DiscordWebhookEmbed> = [
    {
      description: props.descripLines.join('\n'),
      color: props.colour,
      fields: props.fields,
      author: {
        name: props.authorName ?? discordActionLink.defaultAuthorName,
        icon_url: props.iconUrl ?? undefined,
      },
    },
    ...props.additionalEmbeds,
  ];
 
  return {
    content: props.content,
    embeds,
    attachments: props.attachments ?? [],
  };
};
 
export const getDescriptionLines = async <T>(props: { data: T; dtoMeta: FormDtoMeta<T> }) => {
  const descripLines: Array<string> = [];
 
  for (const dbMetaPropKey in props.dtoMeta) {
    if (Object.prototype.hasOwnProperty.call(props.dtoMeta, dbMetaPropKey) == false) {
      continue;
    }
    const dtoMetaProp = props.dtoMeta[dbMetaPropKey];
    if (dtoMetaProp?.discord?.display == null) continue;
 
    const localData =
      (props.data as ObjectWithPropsOfValue<string | Array<string>>)[dbMetaPropKey] ?? anyObject;
 
    let labelString = dtoMetaProp.discord?.label ?? dtoMetaProp.label;
    if (labelString?.length < 1) {
      labelString = capitalizeFirstLetter(addSpacesForEnum(dbMetaPropKey));
    }
 
    const lines = await dtoMetaProp?.discord?.display(labelString, localData);
    lines.map((line) => descripLines.push(line));
  }
 
  return descripLines;
};
 
export const basicDiscordLine = async (label: string, value: string) => [
  `**${label}**: ${value}`, //
];
export const shortLinkDiscordLine = (linkText: string) => async (label: string, value: string) => [
  `**${label}**: [${linkText}](${value})`,
];
export const arrayDiscordLine = async (label: string, values: Array<string>) => [
  `**${label}**: ${makeArrayOrDefault(values).join(', ')}`,
];
export const arrayOfLinksDiscordLine = async (label: string, values: Array<string>) => [
  `**${label}**: ${makeArrayOrDefault(values)
    .map((v, i) => `[Image${i + 1}](${v})`)
    .join(', ')}`,
];
export const shortDateDiscordLine = async (label: string, value: string) => [
  `**${label}**: ${formatDate(value, 'DD MMM YY')}`, //
];
export const arrayFromDatabaseDiscordLines =
  <T>(props: {
    dbCall: (id: string) => Promise<ResultWithValue<T>>;
    mapValue: (db: T) => string;
  }) =>
  async (label: string, values: Array<string>) => {
    const links: Array<string> = [];
    for (const value of values) {
      const dataResult = await props.dbCall(value);
      if (dataResult.isSuccess == false) {
        links.push('**error**');
        continue;
      }
      const dataValue = props.mapValue(dataResult.value);
      links.push(dataValue);
    }
    return [`**${label}**: ${makeArrayOrDefault(links).join(', ')}`];
  };