feat: add Discord webhook configuration support to forms and create dedicated admin settings page
This commit is contained in:
+1
-1
@@ -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;
|
||||
|
||||
@@ -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 };
|
||||
}
|
||||
|
||||
@@ -0,0 +1,102 @@
|
||||
"use client";
|
||||
|
||||
import React, { useState, useTransition } from "react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Textarea } from "@/components/ui/textarea";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { toast } from "sonner";
|
||||
import { updateForm } from "@/app/actions/form";
|
||||
import { Loader2, Save } from "lucide-react";
|
||||
|
||||
interface FormExtraClientProps {
|
||||
form: {
|
||||
id: string;
|
||||
discordWebhookUrl: string | null;
|
||||
discordWebhookTemplate: string | null;
|
||||
discordWebhookUpdateTemplate: string | null;
|
||||
};
|
||||
}
|
||||
|
||||
export default function FormExtraClient({ form }: FormExtraClientProps) {
|
||||
const router = useRouter();
|
||||
const [webhookUrl, setWebhookUrl] = useState(form.discordWebhookUrl || "");
|
||||
const [webhookTemplate, setWebhookTemplate] = useState(form.discordWebhookTemplate || "");
|
||||
const [webhookUpdateTemplate, setWebhookUpdateTemplate] = useState(form.discordWebhookUpdateTemplate || "");
|
||||
const [isSaving, startSaveTransition] = useTransition();
|
||||
|
||||
const handleSave = () => {
|
||||
startSaveTransition(async () => {
|
||||
try {
|
||||
await updateForm(form.id, {
|
||||
discordWebhookUrl: webhookUrl.trim() || null,
|
||||
discordWebhookTemplate: webhookTemplate.trim() || null,
|
||||
discordWebhookUpdateTemplate: webhookUpdateTemplate.trim() || null,
|
||||
});
|
||||
toast.success("Extra settings saved!");
|
||||
router.refresh();
|
||||
} catch (err: any) {
|
||||
toast.error(err.message || "Failed to update settings.");
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Discord Webhook</CardTitle>
|
||||
<CardDescription>
|
||||
Send notifications to a Discord channel when a new submission is received.
|
||||
Leave URL empty to disable.
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="webhook-url">Webhook URL</Label>
|
||||
<Input
|
||||
id="webhook-url"
|
||||
value={webhookUrl}
|
||||
onChange={(e) => setWebhookUrl(e.target.value)}
|
||||
placeholder="https://discord.com/api/webhooks/..."
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="webhook-template">New Submission Template</Label>
|
||||
<Textarea
|
||||
id="webhook-template"
|
||||
value={webhookTemplate}
|
||||
onChange={(e) => setWebhookTemplate(e.target.value)}
|
||||
placeholder="New submission received from {Name} for skill: {skill}!"
|
||||
className="min-h-24"
|
||||
/>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Use <code>{`{QuestionLabel}`}</code> to insert answers. Example: <code>{`{Name}`}</code> or <code>{`{skill}`}</code>.
|
||||
</p>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="webhook-update-template">Update Submission Template</Label>
|
||||
<Textarea
|
||||
id="webhook-update-template"
|
||||
value={webhookUpdateTemplate}
|
||||
onChange={(e) => setWebhookUpdateTemplate(e.target.value)}
|
||||
placeholder="Submission updated by {Name} for skill: {skill}!"
|
||||
className="min-h-24"
|
||||
/>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Used when a user updates their existing submission. Use <code>{`{QuestionLabel}`}</code> to insert answers.
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex justify-end pt-2">
|
||||
<Button onClick={handleSave} disabled={isSaving} className="gap-2">
|
||||
{isSaving ? <Loader2 className="w-4 h-4 animate-spin" /> : <Save className="w-4 h-4" />}
|
||||
Save Settings
|
||||
</Button>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
import { db } from "@/db";
|
||||
import { forms } from "@/db/schema";
|
||||
import FormExtraClient from "./client";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
export default async function AdminExtraPage() {
|
||||
let form = await db.query.forms.findFirst();
|
||||
if (!form) {
|
||||
const [newForm] = await db
|
||||
.insert(forms)
|
||||
.values({
|
||||
title: "Erika Custom Form",
|
||||
description: "Welcome! Please fill out the form below.",
|
||||
})
|
||||
.returning();
|
||||
form = newForm;
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-6 max-w-4xl mx-auto pb-12">
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<h1 className="text-3xl font-bold tracking-tight">Extra Settings</h1>
|
||||
<p className="text-muted-foreground mt-1">
|
||||
Configure Discord webhook integrations.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<FormExtraClient form={form} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user