Files
erika/lib/submission-webhook.ts
T

57 lines
1.6 KiB
TypeScript

import {
answersByTemplateIndex,
submissionUpdateText,
type NormalizedSubmissionAnswer,
type OldAnswersByQuestionId,
type SubmissionQuestion,
} from "@/lib/submission-intake";
const NEW_SUBMISSION_TEMPLATE = "New submission from {username} ({id}).";
const UPDATED_SUBMISSION_TEMPLATE = "Submission updated by {username} ({id}).\n{update}";
type SubmissionWebhookMessageOptions = {
template: string | null;
isUpdate: boolean;
userName: string | null | undefined;
discordId: string;
submissionLink: string;
questions: SubmissionQuestion[];
answers: NormalizedSubmissionAnswer[];
oldAnswersByQuestionId: OldAnswersByQuestionId;
};
export function submissionWebhookMessage({
template,
isUpdate,
userName,
discordId,
submissionLink,
questions,
answers,
oldAnswersByQuestionId,
}: SubmissionWebhookMessageOptions) {
const answersByIndex = answersByTemplateIndex(questions, answers);
const updatesText = isUpdate
? submissionUpdateText(questions, answers, oldAnswersByQuestionId)
: "";
const messageTemplate = template?.trim()
|| (isUpdate ? UPDATED_SUBMISSION_TEMPLATE : NEW_SUBMISSION_TEMPLATE);
return messageTemplate.replace(/\{([^}]+)\}/g, (_match, variable: string) => {
const key = variable.toLowerCase();
if (key === "username" || key === "displayname") {
return userName || "Unknown User";
}
if (key === "id") {
return discordId;
}
if (key === "link") {
return submissionLink;
}
if (key === "update") {
return updatesText;
}
return answersByIndex[variable] || "Not Provided";
});
}