feat(webhooks-config): Outgoing-Webhooks Tabelle + CRUD + UI [tsc:fail]

This commit is contained in:
Dennis (via Claude+Gemma) 2026-05-23 06:04:08 +02:00
parent 5642b34061
commit 791e6069d6
6 changed files with 493 additions and 0 deletions

5
.phase9-state.json Normal file
View File

@ -0,0 +1,5 @@
{
"completed_features": [],
"current_feature": "webhooks-config",
"started_at": "2026-05-23T06:02:21.166704"
}

View File

@ -1017,3 +1017,25 @@ Migrations completed successfully
Checking for admin user...
Admin user already exists
## 🚀 Phase-9 Codegen-Run gestartet (2026-05-23 06:02:21)
## Phase-3 Feature: webhooks-config (2026-05-23 06:02:21)
- `06:02:21` **INFO** Description: Outgoing-Webhooks Tabelle + CRUD + UI
- `06:02:21` **INFO** Generating apps/api/src/db/schema.ts (ERWEITERT — füge `webhooks` (pgTable 'webhooks'): id (uuid pk default …)
- `06:02:46` **INFO** wrote 2976 chars in 25.6s (attempt 1)
- `06:02:46` **INFO** Generating apps/api/src/routes/webhooks.ts (Fastify-Plugin /api/webhooks. Admin-only (preHandler checks role). CRU…)
- `06:03:18` **INFO** wrote 3402 chars in 31.4s (attempt 1)
- `06:03:18` **INFO** Generating apps/web/src/pages/Webhooks.tsx (Webhooks-Page (admin-only). Liste + Create-Form (url, event-select). T…)
- `06:04:06` **INFO** wrote 5951 chars in 48.8s (attempt 1)
- `06:04:06` **INFO** Running tsc --noEmit on api…
- `06:04:08` **WARN** tsc errors:
src/index.ts(27,25): error TS2769: No overload matches this call.
Overload 1 of 3, '(plugin: FastifyPluginCallback<{ limits: { fileSize: number; }; }, RawServerDefault, FastifyTypeProvider, FastifyBaseLogger>, opts?: FastifyRegisterOptions<...> | undefined): FastifyInstance<...> & PromiseLike<...>', gave the following error.
Argument of type 'Promise<FastifyMultipartPlugin>' is not assignable to parameter of type 'FastifyPluginCallback<{ limits: { fileSize: number; }; }, RawServerDefault, FastifyTypeProvider, FastifyBaseLogger>'.
Type 'Promise<FastifyMultipartPlugin>' provides no match for the signature '(instance: FastifyInstance<RawServerDefault, IncomingMessage, ServerResponse<IncomingMessage>, FastifyBaseLogger, FastifyTypeProvider>, opts: { ...; }, done: (err?: Error | undefined) => void): void'.
Overload 2 of 3, '(plugin: FastifyPluginAsync<{ limits: { fileSize: number; }; }, RawServerDefault, FastifyTypeProvider, FastifyBaseLogger>, opts?: FastifyRegisterOptions<...> | undefined): FastifyInstance<...> & PromiseLike<...>', gave the following error.
Argument of type 'Promise<FastifyMultipartPlugin>' is not assignable to parameter of type 'FastifyPluginAsync<{ limits: { fileSize: number; }; }, RawServerDefault, FastifyTypeProvider, FastifyBaseLogger>'.
Type 'Promise<FastifyMultipartPlugin>' provides no match for the signature '(instance: FastifyInstance<RawServerDefault, IncomingMessage, ServerResponse<IncomingMessage>, FastifyBaseLogger, FastifyTy

View File

@ -67,3 +67,12 @@ export const documents = pgTable("documents", {
content: bytea("content"),
createdAt: timestamp("created_at").notNull().defaultNow()
})
export const webhooks = pgTable("webhooks", {
id: uuid("id").primaryKey().defaultRandom(),
url: text("url").notNull(),
event: text("event").notNull(),
active: boolean("active").notNull().default(true),
createdAt: timestamp("created_at").notNull().defaultNow(),
createdBy: uuid("created_by").references(() => users.id)
})

View File

@ -0,0 +1,128 @@
import { FastifyInstance } from "fastify"
import { db } from "../db"
import { webhooks } from "../db/schema"
import { eq } from "drizzle-orm"
import { z } from "zod"
const WebhookCreateSchema = z.object({
url: z.string().url(),
event: z.string(),
secret: z.string().min(1).optional(),
active: z.boolean().optional()
})
const WebhookUpdateSchema = z.object({
url: z.string().url().optional(),
event: z.string().optional(),
secret: z.string().optional(),
active: z.boolean().optional()
})
export default async function webhookRoutes(fastify: FastifyInstance) {
fastify.addHook("preHandler", async (request, reply) => {
try {
await request.jwtVerify()
} catch (err) {
return reply.code(401).send({ message: "Unauthorized" })
}
})
const isAdmin = (request: any) => {
return (request.user as { sub: string, role: string })?.role === "admin"
}
fastify.get("/", async (request, reply) => {
if (!isAdmin(request)) {
return reply.code(403).send({ message: "Forbidden: Admin role required" })
}
return await db.select().from(webhooks)
})
fastify.post("/", async (request, reply) => {
if (!isAdmin(request)) {
return reply.code(403).send({ message: "Forbidden: Admin role required" })
}
const body = WebhookCreateSchema.parse(request.body)
const [webhook] = await db
.insert(webhooks)
.values(body)
.returning()
return reply.code(201).send(webhook)
})
fastify.patch("/:id", async (request, reply) => {
if (!isAdmin(request)) {
return reply.code(403).send({ message: "Forbidden: Admin role required" })
}
const { id } = request.params as { id: string }
const body = WebhookUpdateSchema.parse(request.body)
const [webhook] = await db
.update(webhooks)
.set(body)
.where(eq(webhooks.id, id))
.returning()
if (!webhook) {
return reply.code(404).send({ message: "Webhook not found" })
}
return webhook
})
fastify.delete("/:id", async (request, reply) => {
if (!isAdmin(request)) {
return reply.code(403).send({ message: "Forbidden: Admin role required" })
}
const { id } = request.params as { id: string }
const result = await db
.delete(webhooks)
.where(eq(webhooks.id, id))
if (result.rowCount === 0) {
return reply.code(404).send({ message: "Webhook not found" })
}
return reply.send({ message: "Webhook deleted successfully" })
})
fastify.post("/:id/test", async (request, reply) => {
if (!isAdmin(request)) {
return reply.code(403).send({ message: "Forbidden: Admin role required" })
}
const { id } = request.params as { id: string }
const [webhook] = await db
.select()
.from(webhooks)
.where(eq(webhooks.id, id))
.limit(1)
if (!webhook) {
return reply.code(404).send({ message: "Webhook not found" })
}
try {
await fastify.inject({
method: 'POST',
url: webhook.url,
payload: {
event: "webhook.test",
timestamp: new Date().toISOString(),
data: { message: "This is a test payload from EmberClone" }
}
})
return reply.send({ message: "Test payload sent successfully" })
} catch (error) {
return reply.code(500).send({ message: "Failed to send test payload", error })
}
})
}

View File

@ -0,0 +1,146 @@
import { useState } from "react"
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query"
import { api } from "../lib/api"
import type { Webhook } from "@emberclone/shared"
export default function Webhooks() {
const queryClient = useQueryClient()
const [url, setUrl] = useState("")
const [event, setEvent] = useState<string>("customer.created")
const { data: webhooks, isLoading, isError } = useQuery({
queryKey: ["webhooks"],
queryFn: () => api.listWebhooks()
})
const createMutation = useMutation({
mutationFn: (payload: { url: string; event: string }) => api.createWebhook(payload),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ["webhooks"] })
setUrl("")
}
})
const deleteMutation = useMutation({
mutationFn: (id: string) => api.deleteWebhook(id),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ["webhooks"] })
}
})
const testMutation = useMutation({
mutationFn: (id: string) => api.testWebhook(id),
onSuccess: () => {
alert("Test webhook sent successfully")
},
onError: (error: any) => {
alert(`Test failed: ${error.message || "Unknown error"}`)
}
})
const handleSubmit = (e: React.FormEvent) => {
e.preventDefault()
if (!url.trim()) return
createMutation.mutate({ url, event })
}
if (isLoading) return <div className="p-6 text-gray-500">Loading webhooks...</div>
if (isError) return <div className="p-6 text-red-500">Error loading webhooks.</div>
return (
<div className="p-6 max-w-6xl mx-auto space-y-8">
<header>
<h1 className="text-2xl font-bold text-gray-900">Webhooks</h1>
<p className="text-gray-500">Configure external notifications for system events</p>
</header>
<section className="bg-white p-6 rounded-lg border border-gray-200 shadow-sm">
<h2 className="text-lg font-semibold mb-4">Create New Webhook</h2>
<form onSubmit={handleSubmit} className="grid grid-cols-1 md:grid-cols-3 gap-4 items-end">
<div className="flex-1">
<label className="block text-sm font-medium text-gray-700 mb-1">Target URL</label>
<input
type="url"
required
className="w-full px-3 py-2 border border-gray-300 rounded-md focus:ring-2 focus:ring-blue-500 outline-none"
value={url}
onChange={(e) => setUrl(e.target.value)}
placeholder="https://your-api.com/webhook"
/>
</div>
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">Event Type</label>
<select
className="w-full px-3 py-2 border border-gray-300 rounded-md focus:ring-2 focus:ring-blue-500 outline-none bg-white"
value={event}
onChange={(e) => setEvent(e.target.value)}
>
<option value="customer.created">Customer Created</option>
<option value="customer.updated">Customer Updated</option>
<option value="customer.deleted">Customer Deleted</option>
<option value="system.alert">System Alert</option>
</select>
</div>
<div>
<button
type="submit"
disabled={createMutation.isPending}
className="w-full bg-blue-600 text-white px-4 py-2 rounded-md hover:bg-blue-700 transition-colors disabled:bg-blue-300 font-medium"
>
{createMutation.isPending ? "Saving..." : "Add Webhook"}
</button>
</div>
</form>
</section>
<section className="overflow-x-auto bg-white rounded-lg border border-gray-200 shadow-sm">
<table className="w-full text-left border-collapse">
<thead>
<tr className="bg-gray-50 border-b border-gray-200">
<th className="px-6 py-3 text-xs font-semibold text-gray-600 uppercase">Event</th>
<th className="px-6 py-3 text-xs font-semibold text-gray-600 uppercase">URL</th>
<th className="px-6 py-3 text-xs font-semibold text-gray-600 uppercase text-right">Actions</th>
</tr>
</thead>
<tbody className="divide-y divide-gray-200">
{webhooks?.length === 0 && (
<tr>
<td colSpan={3} className="px-6 py-8 text-center text-gray-500">No webhooks configured.</td>
</tr>
)}
{webhooks?.map((webhook: Webhook) => (
<tr key={webhook.id} className="hover:bg-gray-50 transition-colors">
<td className="px-6 py-4">
<span className="px-2 py-1 text-xs font-medium bg-gray-100 text-gray-700 rounded-full border border-gray-200">
{webhook.event}
</span>
</td>
<td className="px-6 py-4 text-sm text-gray-600 truncate max-w-xs">
{webhook.url}
</td>
<td className="px-6 py-4 text-right space-x-2">
<button
onClick={() => testMutation.mutate(webhook.id)}
disabled={testMutation.isPending}
className="text-sm text-blue-600 hover:text-blue-800 font-medium disabled:text-gray-400"
>
Test
</button>
<button
onClick={() => {
if (confirm("Delete this webhook?")) deleteMutation.mutate(webhook.id)
}}
disabled={deleteMutation.isPending}
className="text-sm text-red-600 hover:text-red-800 font-medium disabled:text-gray-400"
>
Delete
</button>
</td>
</tr>
))}
</tbody>
</table>
</section>
</div>
)
}

183
scripts/phase9_features.py Normal file
View File

@ -0,0 +1,183 @@
#!/usr/bin/env python3
"""Phase-9: webhooks, scheduled-reports, 2fa-stub, billing-stub, integrations."""
from __future__ import annotations
import asyncio
import datetime
import json
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent))
from phase2_features import Feature, FileGen, ROOT, log, log_section # noqa: E402
from phase3_features import run_feature_v2 # noqa: E402
PHASE9_STATE = ROOT / ".phase9-state.json"
FEATURES: list[Feature] = [
Feature(
name="webhooks-config",
description="Outgoing-Webhooks Tabelle + CRUD + UI",
files=[
FileGen(
path="apps/api/src/db/schema.ts",
purpose=(
"ERWEITERT — füge `webhooks` (pgTable 'webhooks'): "
"id (uuid pk default random), url (text notnull), event (text notnull, e.g. 'time_entry.created'), "
"active (boolean default true), createdAt (timestamp default now), createdBy (uuid references users id)."
),
refs=["apps/api/src/db/schema.ts"],
),
FileGen(
path="apps/api/src/routes/webhooks.ts",
purpose=(
"Fastify-Plugin /api/webhooks. Admin-only (preHandler checks role). "
"CRUD: GET / (list), POST /, PATCH /:id, DELETE /:id, POST /:id/test (sendet test-payload)."
),
refs=["apps/api/src/routes/users.ts"],
),
FileGen(
path="apps/web/src/pages/Webhooks.tsx",
purpose=(
"Webhooks-Page (admin-only). Liste + Create-Form (url, event-select). "
"Test-Button pro Webhook. Verwende api.listWebhooks, api.createWebhook, api.deleteWebhook, api.testWebhook."
),
refs=["apps/web/src/pages/Customers.tsx"],
),
],
),
Feature(
name="two-factor-auth-stub",
description="2FA-Setup-Page (TOTP-Stub, kein realer verify yet)",
files=[
FileGen(
path="apps/web/src/pages/TwoFactorAuth.tsx",
purpose=(
"2FA-Setup-Page. Zeigt fake QR-Code-Placeholder (SVG-Box mit 'QR-Code here'), "
"Secret-String (random base32, useState), Input für 6-stelligen Code. "
"Submit: stub, zeigt Toast 'TOTP-Setup-MVP — Verifikation kommt in v2'. "
"Tailwind, max-w-md."
),
refs=["apps/web/src/pages/Profile.tsx"],
),
],
),
Feature(
name="billing-stub",
description="Plans-Page mit Pricing-Tiers (UI only, kein Stripe)",
files=[
FileGen(
path="apps/web/src/pages/Billing.tsx",
purpose=(
"Billing/Plans-Page. 3 Pricing-Cards: 'Free' (0€, 1 User, 100 entries/Monat), "
"'Team' (12€/User/Monat, unbegrenzte entries, Customers + Projects), "
"'Enterprise' (custom, SSO, audit-log, priority support). "
"Aktueller Plan: Free badge oben. Upgrade-Button → Toast 'Stripe-Integration kommt in v2'. "
"Tailwind: grid-cols-3, hover-scale auf Cards."
),
refs=["apps/web/src/pages/AdminUsers.tsx"],
),
],
),
Feature(
name="integrations-page",
description="Integrations-Page mit Slack/Discord/Webhook-Cards",
files=[
FileGen(
path="apps/web/src/pages/Integrations.tsx",
purpose=(
"Integrations-Page. Grid mit Karten für: Slack, Discord, Webhooks, Calendar (Google), Email. "
"Pro Karte: Icon (lucide-react), Name, kurze Beschreibung, 'Configure'-Button. "
"Slack/Discord/Calendar: 'Coming Soon' Badge + disabled Button. "
"Webhooks: links zu /webhooks. Email: links zu /settings. "
"Tailwind cards, hover-shadow."
),
),
],
),
Feature(
name="api-client-phase9",
description="API um Webhooks endpoints erweitert",
files=[
FileGen(
path="apps/web/src/lib/api.ts",
purpose=(
"ERWEITERT — behalte ALLES. Füge: "
"listWebhooks(), createWebhook({url, event}), updateWebhook(id, data), deleteWebhook(id), testWebhook(id)."
),
refs=["apps/web/src/lib/api.ts"],
),
],
),
Feature(
name="router-phase9",
description="App + routes/index für phase9 Routes",
files=[
FileGen(
path="apps/api/src/routes/index.ts",
purpose="ERWEITERT — füge webhookRoutes ('/api/webhooks'). Behalte alle bestehenden.",
refs=["apps/api/src/routes/index.ts"],
),
FileGen(
path="apps/web/src/App.tsx",
purpose=(
"ERWEITERT — füge /webhooks (admin), /2fa, /billing, /integrations Routes. Behalte alles."
),
refs=["apps/web/src/App.tsx"],
),
FileGen(
path="apps/web/src/components/Nav.tsx",
purpose=(
"ERWEITERT — füge Integrations-Link (alle Users) + Webhooks-Link (admin) + Billing-Link (alle). "
"2FA-Link nur in Profile-Page (separate Section). Behalte alle bestehenden Links."
),
refs=["apps/web/src/components/Nav.tsx"],
),
],
),
]
def load_state() -> dict:
if PHASE9_STATE.exists():
return json.loads(PHASE9_STATE.read_text())
return {"completed_features": [], "current_feature": None, "started_at": datetime.datetime.now().isoformat()}
def save_state(state: dict) -> None:
PHASE9_STATE.write_text(json.dumps(state, indent=2))
async def main() -> int:
log_section("🚀 Phase-9 Codegen-Run gestartet")
state = load_state()
for feature in FEATURES:
if feature.name in state.get("completed_features", []):
continue
state["current_feature"] = feature.name; save_state(state)
try:
success = await run_feature_v2(feature)
if success:
state.setdefault("completed_features", []).append(feature.name)
else:
state.setdefault("attempted_features", []).append(feature.name)
save_state(state)
except Exception as e:
log(f"{feature.name} crashed: {e}", level="ERROR")
state.setdefault("attempted_features", []).append(feature.name); save_state(state)
log_section("Phase-9 Run beendet")
log(f"OK: {len(state.get('completed_features', []))}, Attempted: {len(state.get('attempted_features', []))}, Total: {len(FEATURES)}")
import subprocess
log("Running db:generate + db:migrate…")
r = subprocess.run(["pnpm", "--filter", "api", "db:generate"], cwd=ROOT, capture_output=True, text=True, timeout=60)
log(f" db:generate rc={r.returncode}: {r.stdout[-200:]}")
r = subprocess.run(["pnpm", "--filter", "api", "db:migrate"], cwd=ROOT, capture_output=True, text=True, timeout=60)
log(f" db:migrate rc={r.returncode}: {r.stdout[-200:]}")
return 0
if __name__ == "__main__":
sys.exit(asyncio.run(main()))