feat: add Discord webhook configuration support to forms and create dedicated admin settings page

This commit is contained in:
2026-05-28 18:51:55 +07:00 Unverified
parent 9675758535
commit bcae6ece38
11 changed files with 1269 additions and 2 deletions
+1 -1
View File
@@ -32,7 +32,7 @@ export async function createForm(formData: FormData) {
redirect(`/form/admin/${form.id}/edit`);
}
export async function updateForm(id: string, data: { title: string; description?: string; isOpen?: boolean }) {
export async function updateForm(id: string, data: { title?: string; description?: string | null; isOpen?: boolean; discordWebhookUrl?: string | null; discordWebhookTemplate?: string | null; discordWebhookUpdateTemplate?: string | null }) {
const session = await getServerSession(authOptions);
const adminIds = (process.env.ADMIN_DISCORD_IDS ?? "").split(",").map((s) => s.trim()).filter(Boolean);
const discordId = (session?.user as { discordId?: string } | undefined)?.discordId;
+42
View File
@@ -29,6 +29,7 @@ export async function submitForm(
});
let submissionId = "";
const isUpdate = !!existingSubmission;
if (existingSubmission) {
submissionId = existingSubmission.id;
@@ -89,6 +90,47 @@ export async function submitForm(
);
}
// Send Discord Webhook
const templateToUse = isUpdate ? (form as any).discordWebhookUpdateTemplate : form.discordWebhookTemplate;
if (form.discordWebhookUrl && templateToUse) {
try {
const questionsList = await db.query.questions.findMany({
where: (q, { eq }) => eq(q.formId, formId)
});
const questionMap = questionsList.reduce((acc, q) => {
acc[q.id] = q.label;
return acc;
}, {} as Record<string, string>);
const answersDict = answersList.reduce((acc, a) => {
const label = questionMap[a.questionId];
if (label) {
acc[label] = a.value;
}
return acc;
}, {} as Record<string, string>);
let message = templateToUse;
// Replace {Label} with value
message = message.replace(/\{([^}]+)\}/g, (match: string, p1: string) => {
return answersDict[p1] || "Not Provided";
});
await fetch(form.discordWebhookUrl, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
content: message,
}),
});
} catch (e) {
console.error("Failed to send webhook", e);
}
}
revalidatePath("/form/admin/result");
return { ok: true };
}