'use client'
import { use, useState, useEffect } from 'react'
import { useRouter } from 'next/navigation'
import { trpc } from '@/lib/trpc-client'
import { getTrpcErrorMessage } from '@/lib/trpc-error'
import Link from 'next/link'
import dynamic from 'next/dynamic'
const MDEditor = dynamic(() => import('@uiw/react-md-editor'), { ssr: false })
const KATEGORIEN = [
{ value: 'Wichtig', label: 'Wichtig' },
{ value: 'Pruefung', label: 'Prüfung' },
{ value: 'Foerderung', label: 'Förderung' },
{ value: 'Veranstaltung', label: 'Veranstaltung' },
{ value: 'Allgemein', label: 'Allgemein' },
]
export default function NewsEditPage({ params }: { params: Promise<{ id: string }> }) {
const { id } = use(params)
const router = useRouter()
const { data: news, isLoading } = trpc.news.byId.useQuery({ id })
const updateMutation = trpc.news.update.useMutation({
onSuccess: () => router.push('/dashboard/news'),
})
const deleteMutation = trpc.news.delete.useMutation({
onSuccess: () => router.push('/dashboard/news'),
})
const [title, setTitle] = useState('')
const [body, setBody] = useState('')
const [kategorie, setKategorie] = useState('Allgemein')
const [uploading, setUploading] = useState(false)
const [attachments, setAttachments] = useState<
Array<{ name: string; storagePath: string; sizeBytes: number; mimeType?: string | null }>
>([])
useEffect(() => {
if (news) {
setTitle(news.title)
setBody(news.body)
setKategorie(news.kategorie)
if (news.attachments) {
setAttachments(news.attachments.map((a: typeof news.attachments[number]) => ({ ...a, sizeBytes: a.sizeBytes ?? 0 })))
}
}
}, [news])
if (isLoading) return
Wird geladen...
if (!news) return Beitrag nicht gefunden.
async function handleFileUpload(e: React.ChangeEvent) {
const file = e.target.files?.[0]
if (!file) return
setUploading(true)
const formData = new FormData()
formData.append('file', file)
try {
const res = await fetch('/api/upload', { method: 'POST', body: formData })
const data = await res.json()
setAttachments((prev) => [...prev, data])
} catch {
alert('Upload fehlgeschlagen')
} finally {
setUploading(false)
}
}
function handleSave(publishNow: boolean) {
if (!title.trim() || !body.trim()) return
updateMutation.mutate({
id,
data: {
title,
body,
kategorie: kategorie as never,
publishedAt: publishNow ? new Date().toISOString() : undefined,
attachments: attachments.map((a) => ({
name: a.name,
storagePath: a.storagePath,
sizeBytes: a.sizeBytes,
mimeType: a.mimeType || 'application/pdf',
})),
},
})
}
function handleUnpublish() {
updateMutation.mutate({ id, data: { publishedAt: null } })
}
const isPublished = !!news.publishedAt
return (
← Zurück
/
Beitrag bearbeiten
{isPublished && (
Publiziert
)}
{!isPublished && (
Entwurf
)}
setBody(v ?? '')}
height={400}
preview="live"
/>
{/* Attachments */}
{updateMutation.error && (
{getTrpcErrorMessage(updateMutation.error)}
)}
{!isPublished && (
)}
{isPublished && (
)}
)
}