Compare commits

..
Author SHA1 Message Date
Rudi 998434e4eb Changed the name to 'AllSongsTable' 2026-10-13 21:25:53 +02:00
Rudi 1d047c06a7 Changed the Sender Page 2026-10-13 21:22:54 +02:00
22 changed files with 2047 additions and 10820 deletions

No files matched your search

+3 -3
View File
@@ -11,13 +11,13 @@ COPY package.json pnpm-lock.yaml* pnpm-workspace.yaml* ./
RUN apk add --no-cache python3 make g++ RUN apk add --no-cache python3 make g++
# Installation mit deiner funktionierenden Workspace-Konfiguration # Installation mit deiner funktionierenden Workspace-Konfiguration
RUN npm i --frozen-lockfile RUN pnpm i --frozen-lockfile
FROM base AS builder FROM base AS builder
WORKDIR /app WORKDIR /app
COPY --from=deps /app/node_modules ./node_modules COPY --from=deps /app/node_modules ./node_modules
COPY . . COPY . .
RUN npm run openapi:generate; npm run build RUN pnpm run build
FROM base AS runner FROM base AS runner
WORKDIR /app WORKDIR /app
@@ -33,4 +33,4 @@ EXPOSE 3000
ENV PORT=3000 ENV PORT=3000
ENV HOSTNAME="0.0.0.0" ENV HOSTNAME="0.0.0.0"
CMD ["node", "server.js"] CMD ["node", "server.js"]
+6 -3
View File
@@ -1,8 +1,11 @@
"use server"; "use server";
import { error } from "console"; //import { error } from "console";
import Papa from "papaparse"; import Papa from "papaparse";
import { addSongToSongbook } from "@/lib/db/managing"; import { createSong } from "@/lib/db/song";
//import { createSongBook } from "@/lib/db/songbook.ts";
import { addSongToBook } from "@/lib/db/songbooksongs.ts";
interface CSVRow { interface CSVRow {
nummer: string; nummer: string;
@@ -40,4 +43,4 @@ export async function uploadCSVAction(formData:FormData) {
console.error(error); console.error(error);
return { success: false, error: "Error"}; return { success: false, error: "Error"};
} }
} }
+54 -61
View File
@@ -1,46 +1,39 @@
"use client"; "use client";
import { uploadCSVAction } from "./actions"; import { uploadCSVAction } from "./actions";
import { JSXElementConstructor, Key, ReactElement, ReactNode, ReactPortal, useEffect, useState } from "react"; import { useEffect, useState } from "react";
import Card from "@/components/Card" import Card from "@/components/Card"
import { Input } from "@/components/FormElements"; import { Input } from "@/components/FormElements";
import { Screens } from "@/components/DatabaseOverview"; import { Screens } from "@/components/AllSongsTable";
interface Songbook { import { Song, SongBook, SongDetailed } from "@/lib/db/response";
id: number;
name: string;
language: string;
}
interface Song {
song_id: number;
songbook_id: number;
song_number: string;
title: string;
}
interface SongInfo {
songbook_id: number;
songbook_name: string;
song_number: string;
title: string;
}
export default function AdminPage() { export default function AdminPage() {
const [songbooks, setSongbooks] = useState<Songbook[]>([]); // New Songbook
const [selectedSongbookId, setSelectedSongbookId] = useState(""); const [newBookTitle, setNewBookTitle] = useState("");
const [newBookLanguage, setNewBookLanguage] = useState("");
// New Song
const [addSongSelectedSongbookId, addSongSetSelectedSongbookId] = useState("");
const [number, setNumber] = useState(""); const [number, setNumber] = useState("");
const [title, setTitle] = useState(""); const [title, setTitle] = useState("");
const [newBookName, setNewBookName] = useState(""); // Import Songs
const [newBookLanguage, setNewBookLanguage] = useState(""); const [importSelectedSongbookId, importSetSelectedSongbookId] = useState("");
const [uploadStatus, setUploadStatus] = useState<string | null>(null); const [uploadStatus, setUploadStatus] = useState<string | null>(null);
//
const [songbooks, setSongbooks] = useState<SongBook[]>([]);
const [selectedSong, setSelectedSong] = useState<Song | null>(null); const [selectedSong, setSelectedSong] = useState<Song | null>(null);
const [songInfos, setSongInfos] = useState<SongInfo[]>([]) const [songInfos, setSongInfos] = useState<SongDetailed[]>([])
async function handleCSVUpload(formData: FormData) { async function handleCSVUpload(formData: FormData) {
setUploadStatus("Verarbeite..."); setUploadStatus("Verarbeite...");
@@ -61,7 +54,7 @@ export default function AdminPage() {
async function fetchSongInfos() { async function fetchSongInfos() {
try { try {
const res = await fetch(`/api/songs/${selectedSong?.song_id}`); const res = await fetch(`/api/songs/${selectedSong?.id}`);
if (res.ok) { if (res.ok) {
const data = await res.json(); const data = await res.json();
setSongInfos(data); setSongInfos(data);
@@ -90,17 +83,17 @@ export default function AdminPage() {
}, []); }, []);
const addSong = async () => { const addSong = async () => {
if (!selectedSongbookId || !number || !title) { if (!addSongSelectedSongbookId || !number || !title) {
alert("Alle Felder ausfüllen!"); alert("Alle Felder ausfüllen!");
return; return;
} }
try { try {
const res = await fetch("/api/songs", { const res = await fetch("/api/songs", {
method: "POST", method: "POST",
headers: { "Content-Type": "application/json" }, headers: { "Content-Type": "application/json" },
body: JSON.stringify({ body: JSON.stringify({
songbookId: Number(selectedSongbookId), songbookId: Number(addSongSelectedSongbookId),
number: number, number: number,
title: title title: title
}) })
@@ -118,7 +111,7 @@ export default function AdminPage() {
}; };
const attachSong = async () => { const attachSong = async () => {
if (!selectedSongbookId || !number || !selectedSong) { if (!addSongSelectedSongbookId || !number || !selectedSong) {
alert("Alle Felder ausfüllen!"); alert("Alle Felder ausfüllen!");
return; return;
} }
@@ -128,8 +121,8 @@ export default function AdminPage() {
method: "POST", method: "POST",
headers: { "Content-Type": "application/json" }, headers: { "Content-Type": "application/json" },
body: JSON.stringify({ body: JSON.stringify({
songbookId: selectedSongbookId, songbookId: addSongSelectedSongbookId,
songId: selectedSong.song_id, songId: selectedSong.id,
number: number, number: number,
}) })
}); });
@@ -144,7 +137,7 @@ export default function AdminPage() {
} }
const removeSong = async () => { const removeSong = async () => {
if (!selectedSongbookId || !selectedSong) { if (!addSongSelectedSongbookId || !selectedSong) {
alert("Alle Felder ausfüllen!"); alert("Alle Felder ausfüllen!");
return; return;
} }
@@ -154,8 +147,8 @@ export default function AdminPage() {
method: "POST", method: "POST",
headers: { "Content-Type": "application/json" }, headers: { "Content-Type": "application/json" },
body: JSON.stringify({ body: JSON.stringify({
songbookId: selectedSongbookId, songbookId: addSongSelectedSongbookId,
songId: selectedSong.song_id songId: selectedSong.id
}) })
}); });
if (res.ok) { if (res.ok) {
@@ -169,7 +162,7 @@ export default function AdminPage() {
} }
const addSongbook = async () => { const addSongbook = async () => {
if (!newBookName) { if (!newBookTitle) {
alert("Der Name des Liederbuches darf nicht leer sein!"); alert("Der Name des Liederbuches darf nicht leer sein!");
return; return;
} }
@@ -178,14 +171,14 @@ export default function AdminPage() {
const res = await fetch("/api/songbooks", { const res = await fetch("/api/songbooks", {
method: "POST", method: "POST",
headers: { "Content-Type": "application/json" }, headers: { "Content-Type": "application/json" },
body: JSON.stringify({ name: newBookName, language: newBookLanguage }) body: JSON.stringify({ name: newBookTitle, language: newBookLanguage })
}); });
if (res.ok) { if (res.ok) {
const createdBook = await res.json(); const createdBook = await res.json();
setSongbooks([...songbooks, createdBook]); setSongbooks([...songbooks, createdBook]);
alert("Liederbuch erfolgreich erstellt!"); alert("Liederbuch erfolgreich erstellt!");
setNewBookName(""); setNewBookTitle("");
setNewBookLanguage(""); setNewBookLanguage("");
} else { } else {
alert("Failed adding songbook!"); alert("Failed adding songbook!");
@@ -198,9 +191,9 @@ export default function AdminPage() {
return ( return (
<div className="font-sans p-4 sm:p-6 lg:p-8"> <div className="font-sans p-4 sm:p-6 lg:p-8">
<div className="max-w-6xl mx-auto space-y-6"> <div className="max-w-6xl mx-auto space-y-6">
{/* HEADER */} {/* HEADER */}
<h2 className="text-lg font-semibold mb-3 flex items-center gap-2"> <h2 className="text-lg font-semibold mb-3 flex items-center gap-2">
Datenbank verwalten, neue Bücher erstellen und Lieder einpflegen Datenbank verwalten, neue Bücher erstellen und Lieder einpflegen
</h2> </h2>
@@ -215,8 +208,8 @@ export default function AdminPage() {
<Input.Text <Input.Text
type="text" type="text"
placeholder="z.B. Gesangbuch" placeholder="z.B. Gesangbuch"
value={newBookName} value={newBookTitle}
onChange={(e) => setNewBookName(e.target.value)} onChange={(e) => setNewBookTitle(e.target.value)}
/> />
</div> </div>
<div> <div>
@@ -228,7 +221,7 @@ export default function AdminPage() {
onChange={(e) => setNewBookLanguage(e.target.value)} onChange={(e) => setNewBookLanguage(e.target.value)}
/> />
</div> </div>
<Input.Button <Input.Button
onClick={addSongbook} onClick={addSongbook}
className="w-full mt-6 bg-blue-600 hover:bg-blue-700 text-white font-semibold rounded-lg px-4 py-2.5 transition text-sm shadow-sm" className="w-full mt-6 bg-blue-600 hover:bg-blue-700 text-white font-semibold rounded-lg px-4 py-2.5 transition text-sm shadow-sm"
> >
@@ -242,13 +235,13 @@ export default function AdminPage() {
<div> <div>
<Input.Label>Liederbuch wählen</Input.Label> <Input.Label>Liederbuch wählen</Input.Label>
<Input.Select <Input.Select
value={selectedSongbookId} value={addSongSelectedSongbookId}
onChange={(e) => setSelectedSongbookId(e.target.value)} onChange={(e) => addSongSetSelectedSongbookId(e.target.value)}
> >
<option value="">-- Bitte wählen --</option> <option value="">-- Bitte wählen --</option>
{songbooks.map((book) => ( {songbooks.map((book) => (
<option key={book.id} value={String(book.id)}> <option key={book.id} value={String(book.id)}>
{book.name}{book.language ? ` (${book.language})` : ""} {book.title}{book.language ? ` (${book.language})` : ""}
</option> </option>
))} ))}
</Input.Select> </Input.Select>
@@ -279,18 +272,18 @@ export default function AdminPage() {
<Card title="CSV-Massenimport"> <Card title="CSV-Massenimport">
<form action={handleCSVUpload} className="flex flex-col justify-between"> <form action={handleCSVUpload} className="flex flex-col justify-between">
<input type="hidden" name="songbookId" value={selectedSongbookId} /> <input type="hidden" name="songbookId" value={addSongSelectedSongbookId} />
<div className="space-y-4"> <div className="space-y-4">
<div> <div>
<Input.Label>Ziel-Liederbuch</Input.Label> <Input.Label>Ziel-Liederbuch</Input.Label>
<Input.Select <Input.Select
value={selectedSongbookId} value={addSongSelectedSongbookId}
onChange={(e) => setSelectedSongbookId(e.target.value)} onChange={(e) => addSongSetSelectedSongbookId(e.target.value)}
> >
<option value="">-- Bitte wählen --</option> <option value="">-- Bitte wählen --</option>
{songbooks.map((book) => ( {songbooks.map((book) => (
<option key={book.id} value={String(book.id)}> <option key={book.id} value={String(book.id)}>
{book.name}{book.language ? ` (${book.language})` : ""} {book.title}{book.language ? ` (${book.language})` : ""}
</option> </option>
))} ))}
</Input.Select> </Input.Select>
@@ -304,7 +297,7 @@ export default function AdminPage() {
/> />
</div> </div>
<div className="mt-6 space-y-3"> <div className="mt-6 space-y-3">
<Input.Button <Input.Button
type="submit" type="submit"
> >
Hochladen & Verarbeiten Hochladen & Verarbeiten
@@ -329,7 +322,7 @@ export default function AdminPage() {
<Input.Text value={selectedSong ? selectedSong.title : ""} disabled></Input.Text> <Input.Text value={selectedSong ? selectedSong.title : ""} disabled></Input.Text>
<Card title="Informationen" className="mt-4"> <Card title="Informationen" className="mt-4">
<div className="text-sm space-y-1"> <div className="text-sm space-y-1">
<p><span className="font-semibold">Lied-ID:</span> {selectedSong?.song_id ?? "-"}</p> <p><span className="font-semibold">Lied-ID:</span> {selectedSong?.id ?? "-"}</p>
<p><span className="font-semibold">In Liederbüchern:</span></p> <p><span className="font-semibold">In Liederbüchern:</span></p>
{songInfos.length > 0 ? ( {songInfos.length > 0 ? (
<ul className="list-disc list-inside pl-2 text-xs text-neutral-400"> <ul className="list-disc list-inside pl-2 text-xs text-neutral-400">
@@ -350,13 +343,13 @@ export default function AdminPage() {
<div> <div>
<Input.Label>Ziel-Liederbuch</Input.Label> <Input.Label>Ziel-Liederbuch</Input.Label>
<Input.Select <Input.Select
value={selectedSongbookId} value={addSongSelectedSongbookId}
onChange={(e) => setSelectedSongbookId(e.target.value)} onChange={(e) => addSongSetSelectedSongbookId(e.target.value)}
> >
<option value="">-- Bitte wählen --</option> <option value="">-- Bitte wählen --</option>
{songbooks.map((book) => ( {songbooks.map((book) => (
<option key={book.id} value={String(book.id)}> <option key={book.id} value={String(book.id)}>
{book.name}{book.language ? ` (${book.language})` : ""} {book.title}{book.language ? ` (${book.language})` : ""}
</option> </option>
))} ))}
</Input.Select> </Input.Select>
@@ -370,7 +363,7 @@ export default function AdminPage() {
onChange={(e) => setNumber(e.target.value)} onChange={(e) => setNumber(e.target.value)}
/> />
</div> </div>
<Input.Button <Input.Button
onClick={attachSong} onClick={attachSong}
className="w-full mt-6 bg-blue-600 hover:bg-blue-700 text-white font-semibold rounded-lg px-4 py-2.5 transition text-sm shadow-sm" className="w-full mt-6 bg-blue-600 hover:bg-blue-700 text-white font-semibold rounded-lg px-4 py-2.5 transition text-sm shadow-sm"
> >
@@ -383,8 +376,8 @@ export default function AdminPage() {
<div> <div>
<Input.Label>Ziel-Liederbuch</Input.Label> <Input.Label>Ziel-Liederbuch</Input.Label>
<Input.Select <Input.Select
value={selectedSongbookId} value={addSongSelectedSongbookId}
onChange={(e) => setSelectedSongbookId(e.target.value)} onChange={(e) => addSongSetSelectedSongbookId(e.target.value)}
> >
<option value="">-- Bitte wählen --</option> <option value="">-- Bitte wählen --</option>
{songInfos.length > 0 ? ( {songInfos.length > 0 ? (
@@ -396,7 +389,7 @@ export default function AdminPage() {
): ""} ): ""}
</Input.Select> </Input.Select>
</div> </div>
<Input.Button <Input.Button
onClick={removeSong} onClick={removeSong}
className="w-full mt-6 bg-blue-600 hover:bg-blue-700 text-white font-semibold rounded-lg px-4 py-2.5 transition text-sm shadow-sm" className="w-full mt-6 bg-blue-600 hover:bg-blue-700 text-white font-semibold rounded-lg px-4 py-2.5 transition text-sm shadow-sm"
> >
@@ -410,4 +403,4 @@ export default function AdminPage() {
</div> </div>
</div> </div>
); );
} }
-25
View File
@@ -1,25 +0,0 @@
// @/app/api/docs/api/routes.ts
/**
* @openapi
* /api/docs/api:
* get:
* summary: OpenAPI-Spezifikation abrufen
* tags:
* - Docs
* description: Gibt die vollständige OpenAPI-JSON-Spezifikation der API zurück.
* responses:
* 200:
* description: Erfolgreich generierte OpenAPI-Spezifikation.
* content:
* application/json:
* schema:
* type: object
*/
import { NextResponse } from 'next/server';
import spec from '@/src/generated/openapi.json';
export function GET() {
return NextResponse.json(spec);
}
+14 -70
View File
@@ -1,5 +1,3 @@
// @/app/api/songbooks/[songBookId]/route.ts
import { NextResponse } from "next/server"; import { NextResponse } from "next/server";
import { getSongBookById, updateSongBook, deleteSongBook } from "@/lib/db/songbook"; import { getSongBookById, updateSongBook, deleteSongBook } from "@/lib/db/songbook";
@@ -11,51 +9,38 @@ interface RouteParams {
/** /**
* @openapi * @openapi
* /api/songbooks/{songBookId}: * /api/songbooks/{id}:
* get: * get:
* summary: Einzelnes Songbook abrufen * summary: Einzelnen Songbook abrufen
* tags: * tags:
* - Songbooks * - Songbooks
* parameters: * parameters:
* - in: path * - in: path
* name: songBookId * name: id
* required: true * required: true
* schema: * schema:
* type: integer * type: integer
* description: Die ID des Songbooks * description: Die ID des Songbooks
* example: 1
* responses: * responses:
* 200: * 200:
* description: Songbook erfolgreich gefunden * description: Songbook erfolgreich gefunden
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/SongBook'
* 400: * 400:
* description: Ungültige Songbook-ID * description: Ungültige Songbook-ID
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/Error'
* 404: * 404:
* description: Songbook nicht gefunden * description: Songbook nicht gefunden
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/Error'
* 500: * 500:
* description: Serverfehler * description: Serverfehler
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/Error'
*/ */
export async function GET(_request: Request, { params }: RouteParams) { export async function GET(_request: Request, { params }: RouteParams) {
try { try {
const { songBookId } = await params; const { songBookId } = await params;
const res = await getSongBookById(parseInt(songBookId)); const res = await getSongBookById(parseInt(songBookId));
if (!res.success) { if (!res.success) {
return NextResponse.json({ message: res.error }, { status: res.status }); return NextResponse.json({ message: res.error }, { status: res.status });
} }
@@ -73,57 +58,33 @@ export async function GET(_request: Request, { params }: RouteParams) {
/** /**
* @openapi * @openapi
* /api/songbooks/{songBookId}: * /api/songbooks/{id}:
* patch: * patch:
* summary: Songbook aktualisieren * summary: Songbook aktualisieren
* tags: * tags:
* - Songbooks * - Songbooks
* parameters: * parameters:
* - in: path * - in: path
* name: songBookId * name: id
* required: true * required: true
* schema: * schema:
* type: integer * type: integer
* description: Die ID des Songbooks * description: Die ID des Songbooks
* example: 1
* requestBody: * requestBody:
* required: true * required: true
* content: * content:
* application/json: * application/json:
* schema: * schema:
* type: object * type: object
* properties:
* title:
* type: string
* example: "Feiert Jesus 1"
* language:
* type: string
* example: "DE"
* responses: * responses:
* 200: * 200:
* description: Songbook erfolgreich aktualisiert * description: Songbook erfolgreich aktualisiert
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/SongBook'
* 400: * 400:
* description: Ungültige Parameter oder Daten * description: Ungültige Parameter oder Daten
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/Error'
* 404: * 404:
* description: Songbook nicht gefunden * description: Songbook nicht gefunden
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/Error'
* 500: * 500:
* description: Serverfehler * description: Serverfehler
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/Error'
*/ */
export async function PATCH(request: Request, { params }: RouteParams) { export async function PATCH(request: Request, { params }: RouteParams) {
try { try {
@@ -139,7 +100,7 @@ export async function PATCH(request: Request, { params }: RouteParams) {
} catch (error) { } catch (error) {
console.error("API Error:", error); console.error("API Error:", error);
return NextResponse.json( return NextResponse.json(
{ error: "Fehler beim Aktualisieren des Songbooks" }, { error: "Fehler beim Laden der Songbookinfos" },
{ status: 500 } { status: 500 }
); );
} }
@@ -148,44 +109,27 @@ export async function PATCH(request: Request, { params }: RouteParams) {
/** /**
* @openapi * @openapi
* /api/songbooks/{songBookId}: * /api/songbooks/{id}:
* delete: * delete:
* summary: Songbook löschen * summary: Songbook löschen
* tags: * tags:
* - Songbooks * - Songbooks
* parameters: * parameters:
* - in: path * - in: path
* name: songBookId * name: id
* required: true * required: true
* schema: * schema:
* type: integer * type: integer
* description: Die ID des Songbooks * description: Die ID des Songbooks
* example: 1
* responses: * responses:
* 200: * 200:
* description: Songbook erfolgreich gelöscht (gibt das gelöschte Songbook zurück) * description: Songbook erfolgreich gelöscht
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/SongBook'
* 400: * 400:
* description: Ungültige Songbook-ID * description: Ungültige Songbook-ID
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/Error'
* 404: * 404:
* description: Songbook nicht gefunden * description: Songbook nicht gefunden
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/Error'
* 500: * 500:
* description: Serverfehler * description: Serverfehler
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/Error'
*/ */
export async function DELETE(_request: Request, { params }: RouteParams) { export async function DELETE(_request: Request, { params }: RouteParams) {
try { try {
@@ -200,7 +144,7 @@ export async function DELETE(_request: Request, { params }: RouteParams) {
} catch (error) { } catch (error) {
console.error("API Error:", error); console.error("API Error:", error);
return NextResponse.json( return NextResponse.json(
{ error: "Fehler beim Löschen des Songbooks" }, { error: "Fehler beim Laden der Songbookinfos" },
{ status: 500 } { status: 500 }
); );
} }
@@ -1,5 +1,3 @@
// @/app/api/songbooks/[songBookId]/songs/[songId]/route.ts
import { NextResponse } from "next/server"; import { NextResponse } from "next/server";
import { addSongToBook, updateSongInBook, removeSongFromBook } from "@/lib/db/songbooksongs"; import { addSongToBook, updateSongInBook, removeSongFromBook } from "@/lib/db/songbooksongs";
@@ -16,7 +14,7 @@ interface RouteParams {
* post: * post:
* summary: Song zu Liederbuch hinzufügen * summary: Song zu Liederbuch hinzufügen
* tags: * tags:
* - Songbooks * - Songbook
* parameters: * parameters:
* - in: path * - in: path
* name: songBookId * name: songBookId
@@ -24,14 +22,12 @@ interface RouteParams {
* schema: * schema:
* type: integer * type: integer
* description: Die ID des Liederbuchs * description: Die ID des Liederbuchs
* example: 1
* - in: path * - in: path
* name: songId * name: songId
* required: true * required: true
* schema: * schema:
* type: integer * type: integer
* description: Die ID des Songs * description: Die ID des Songs
* example: 1
* requestBody: * requestBody:
* required: true * required: true
* content: * content:
@@ -48,28 +44,12 @@ interface RouteParams {
* responses: * responses:
* 200: * 200:
* description: Song erfolgreich zugewiesen * description: Song erfolgreich zugewiesen
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/SongBookEntry'
* 400: * 400:
* description: Ungültige Parameter oder fehlende Songnummer * description: Ungültige Parameter oder fehlende Songnummer
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/Error'
* 409: * 409:
* description: Songnummer bereits vergeben oder Song existiert bereits im Buch * description: Songnummer bereits vergeben oder Song existiert bereits im Buch
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/Error'
* 500: * 500:
* description: Serverfehler * description: Serverfehler
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/Error'
*/ */
export async function POST(request: Request, { params }: RouteParams) { export async function POST(request: Request, { params }: RouteParams) {
try { try {
@@ -88,7 +68,7 @@ export async function POST(request: Request, { params }: RouteParams) {
} catch (error) { } catch (error) {
console.error("API Error:", error); console.error("API Error:", error);
return NextResponse.json( return NextResponse.json(
{ error: "Fehler beim Zuweisen des Songs" }, { error: "Fehler beim Laden der Songbookinfos" },
{ status: 500 } { status: 500 }
); );
} }
@@ -101,7 +81,7 @@ export async function POST(request: Request, { params }: RouteParams) {
* patch: * patch:
* summary: Songnummer eines Songs im Liederbuch aktualisieren * summary: Songnummer eines Songs im Liederbuch aktualisieren
* tags: * tags:
* - Songbooks * - Songbook
* parameters: * parameters:
* - in: path * - in: path
* name: songBookId * name: songBookId
@@ -109,14 +89,12 @@ export async function POST(request: Request, { params }: RouteParams) {
* schema: * schema:
* type: integer * type: integer
* description: Die ID des Liederbuchs * description: Die ID des Liederbuchs
* example: 1
* - in: path * - in: path
* name: songId * name: songId
* required: true * required: true
* schema: * schema:
* type: integer * type: integer
* description: Die ID des Songs * description: Die ID des Songs
* example: 1
* requestBody: * requestBody:
* required: true * required: true
* content: * content:
@@ -133,34 +111,14 @@ export async function POST(request: Request, { params }: RouteParams) {
* responses: * responses:
* 200: * 200:
* description: Songnummer erfolgreich aktualisiert * description: Songnummer erfolgreich aktualisiert
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/SongBookEntry'
* 400: * 400:
* description: Ungültige Parameter oder fehlende Daten * description: Ungültige Parameter oder fehlende Daten
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/Error'
* 404: * 404:
* description: Zuweisung nicht gefunden * description: Zuweisung nicht gefunden
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/Error'
* 409: * 409:
* description: Neue Songnummer bereits vergeben * description: Neue Songnummer bereits vergeben
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/Error'
* 500: * 500:
* description: Serverfehler * description: Serverfehler
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/Error'
*/ */
export async function PATCH(request: Request, { params }: RouteParams) { export async function PATCH(request: Request, { params }: RouteParams) {
try { try {
@@ -176,7 +134,7 @@ export async function PATCH(request: Request, { params }: RouteParams) {
} catch (error) { } catch (error) {
console.error("API Error:", error); console.error("API Error:", error);
return NextResponse.json( return NextResponse.json(
{ error: "Fehler beim Aktualisieren der Songnummer" }, { error: "Fehler beim Laden der Songbookinfos" },
{ status: 500 } { status: 500 }
); );
} }
@@ -189,7 +147,7 @@ export async function PATCH(request: Request, { params }: RouteParams) {
* delete: * delete:
* summary: Song aus Liederbuch entfernen * summary: Song aus Liederbuch entfernen
* tags: * tags:
* - Songbooks * - Songbook
* parameters: * parameters:
* - in: path * - in: path
* name: songBookId * name: songBookId
@@ -197,39 +155,21 @@ export async function PATCH(request: Request, { params }: RouteParams) {
* schema: * schema:
* type: integer * type: integer
* description: Die ID des Liederbuchs * description: Die ID des Liederbuchs
* example: 1
* - in: path * - in: path
* name: songId * name: songId
* required: true * required: true
* schema: * schema:
* type: integer * type: integer
* description: Die ID des Songs * description: Die ID des Songs
* example: 1
* responses: * responses:
* 200: * 200:
* description: Song erfolgreich aus dem Liederbuch entfernt (gibt die entfernte Zuweisung zurück) * description: Song erfolgreich aus dem Liederbuch entfernt
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/SongBookEntry'
* 400: * 400:
* description: Ungültige Parameter * description: Ungültige Parameter
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/Error'
* 404: * 404:
* description: Zuweisung nicht gefunden * description: Zuweisung nicht gefunden
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/Error'
* 500: * 500:
* description: Serverfehler * description: Serverfehler
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/Error'
*/ */
export async function DELETE(_request: Request, { params }: RouteParams) { export async function DELETE(_request: Request, { params }: RouteParams) {
try { try {
@@ -245,7 +185,7 @@ export async function DELETE(_request: Request, { params }: RouteParams) {
} catch (error) { } catch (error) {
console.error("API Error:", error); console.error("API Error:", error);
return NextResponse.json( return NextResponse.json(
{ error: "Fehler beim Entfernen des Songs" }, { error: "Fehler beim Laden der Songbookinfos" },
{ status: 500 } { status: 500 }
); );
} }
+6 -39
View File
@@ -1,5 +1,3 @@
// @/app/api/songbooks/[songBookId]/songs/route.ts
import { NextResponse } from "next/server"; import { NextResponse } from "next/server";
import { getSongByNumber } from "@/lib/db/songbooksongs"; import { getSongByNumber } from "@/lib/db/songbooksongs";
@@ -11,58 +9,27 @@ interface RouteParams {
/** /**
* @openapi * @openapi
* /api/songbooks/{songBookId}/songs: * /api/songbooks/{id}/songs:
* get: * get:
* summary: Einen Song nach Nummer in einem Songbook suchen * summary: Einen Song nach Nummer in einem Songbook suchen
* tags: * tags:
* - Songbooks * - Songbook
* parameters: * parameters:
* - in: path * - in: path
* name: songBookId * name: id
* required: true * required: true
* schema: * schema:
* type: integer * type: integer
* description: Die ID des Songbooks * description: Die ID des Songbooks
* example: 1
* - in: query
* name: number
* required: true
* schema:
* type: string
* description: Die Nummer des Songs im Songbook
* example: "123"
* - in: query
* name: n
* required: false
* schema:
* type: string
* description: Alias für `number`
* example: "123"
* responses: * responses:
* 200: * 200:
* description: Song im Songbook erfolgreich gefunden * description: Songbook erfolgreich gefunden
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/SongBookEntry'
* 400: * 400:
* description: Ungültige Songbook-ID oder fehlender number-Parameter * description: Ungültige Songbook-ID
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/Error'
* 404: * 404:
* description: Songbook oder Song nicht gefunden * description: Songbook nicht gefunden
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/Error'
* 500: * 500:
* description: Serverfehler * description: Serverfehler
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/Error'
*/ */
export async function GET(request: Request, { params }: RouteParams) { export async function GET(request: Request, { params }: RouteParams) {
try { try {
+21 -47
View File
@@ -1,45 +1,22 @@
// @/app/api/songbooks/route.ts // @wikiCategory: Liederbücher
import { NextResponse } from "next/server"; import { NextResponse } from "next/server";
import { getSongBooks, searchSongBooksByTitle, createSongBook } from "@/lib/db/songbook"; import { getSongBooks, searchSongBooksByTitle, createSongBook } from "@/lib/db/songbook";
/** /**
* @openapi * @openapi
* /api/songbooks: * /api/songbooks:
* get: * get:
* summary: Get all songbooks or search songbooks by title * summary: Get all songbooks
* tags:
* - Songbooks
* parameters:
* - in: query
* name: query
* required: false
* schema:
* type: string
* description: Search term for the songbook title
* example: "Feiert Jesus"
* - in: query
* name: q
* required: false
* schema:
* type: string
* description: Alias for `query`
* example: "Feiert Jesus"
* responses: * responses:
* 200: * 200:
* description: List of songbooks (filtered by title if a query is given) * description: List of songbooks
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: '#/components/schemas/SongBook'
* 500: * 500:
* description: Internal Server Error * description: Internal Server Error
* content: *
* application/json: * @wikiDescription: Liste aller Liederbücher abrufen
* schema:
* $ref: '#/components/schemas/Error'
*/ */
export async function GET(request: Request) { export async function GET(request: Request) {
try { try {
@@ -83,8 +60,6 @@ export async function GET(request: Request) {
* /api/songbooks: * /api/songbooks:
* post: * post:
* summary: Creates a new songbook * summary: Creates a new songbook
* tags:
* - Songbooks
* requestBody: * requestBody:
* required: true * required: true
* content: * content:
@@ -93,7 +68,6 @@ export async function GET(request: Request) {
* type: object * type: object
* required: * required:
* - title * - title
* - language
* properties: * properties:
* title: * title:
* type: string * type: string
@@ -113,25 +87,25 @@ export async function GET(request: Request) {
* type: boolean * type: boolean
* example: true * example: true
* songBook: * songBook:
* $ref: '#/components/schemas/SongBook' * type: object
* properties:
* id:
* type: integer
* example: 1
* title:
* type: string
* example: "Feiert Jesus 1"
* language:
* type: string
* example: "DE"
* 400: * 400:
* description: Bad Request (missing title or language) * description: Bad Request (missing title)
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/Error'
* 409: * 409:
* description: Conflict (title already exists) * description: Conflict (title already exists)
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/Error'
* 500: * 500:
* description: Internal Server Error * description: Internal Server Error
* content: *
* application/json: * @wikiDescription: Neues Liederbuch erstellen
* schema:
* $ref: '#/components/schemas/Error'
*/ */
export async function POST(request: Request) { export async function POST(request: Request) {
try { try {
+9 -66
View File
@@ -1,5 +1,3 @@
// @/app/api/songs/[songId]/route.ts
import { NextResponse } from "next/server"; import { NextResponse } from "next/server";
import { getSongById, updateSong, deleteSong } from "@/lib/db/song"; import { getSongById, updateSong, deleteSong } from "@/lib/db/song";
@@ -11,44 +9,27 @@ interface RouteParams {
/** /**
* @openapi * @openapi
* /api/songs/{songId}: * /api/songs/{id}:
* get: * get:
* summary: Einzelnen Song abrufen * summary: Einzelnen Song abrufen
* tags: * tags:
* - Songs * - Songs
* parameters: * parameters:
* - in: path * - in: path
* name: songId * name: id
* required: true * required: true
* schema: * schema:
* type: integer * type: integer
* description: Die ID des Songs * description: Die ID des Songs
* example: 1
* responses: * responses:
* 200: * 200:
* description: Song erfolgreich gefunden * description: Song erfolgreich gefunden
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/Song'
* 400: * 400:
* description: Ungültige Song-ID * description: Ungültige Song-ID
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/Error'
* 404: * 404:
* description: Song nicht gefunden * description: Song nicht gefunden
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/Error'
* 500: * 500:
* description: Serverfehler * description: Serverfehler
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/Error'
*/ */
export async function GET(_request: Request, { params }: RouteParams) { export async function GET(_request: Request, { params }: RouteParams) {
try { try {
@@ -72,54 +53,33 @@ export async function GET(_request: Request, { params }: RouteParams) {
/** /**
* @openapi * @openapi
* /api/songs/{songId}: * /api/songs/{id}:
* patch: * patch:
* summary: Song aktualisieren * summary: Song aktualisieren
* tags: * tags:
* - Songs * - Songs
* parameters: * parameters:
* - in: path * - in: path
* name: songId * name: id
* required: true * required: true
* schema: * schema:
* type: integer * type: integer
* description: Die ID des Songs * description: Die ID des Songs
* example: 1
* requestBody: * requestBody:
* required: true * required: true
* content: * content:
* application/json: * application/json:
* schema: * schema:
* type: object * type: object
* properties:
* title:
* type: string
* example: "Großer Gott"
* responses: * responses:
* 200: * 200:
* description: Song erfolgreich aktualisiert * description: Song erfolgreich aktualisiert
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/Song'
* 400: * 400:
* description: Ungültige Parameter oder Daten * description: Ungültige Parameter oder Daten
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/Error'
* 404: * 404:
* description: Song nicht gefunden * description: Song nicht gefunden
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/Error'
* 500: * 500:
* description: Serverfehler * description: Serverfehler
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/Error'
*/ */
export async function PATCH(request: Request, { params }: RouteParams) { export async function PATCH(request: Request, { params }: RouteParams) {
try { try {
@@ -135,7 +95,7 @@ export async function PATCH(request: Request, { params }: RouteParams) {
} catch (error) { } catch (error) {
console.error("API Error:", error); console.error("API Error:", error);
return NextResponse.json( return NextResponse.json(
{ error: "Fehler beim Aktualisieren des Songs" }, { error: "Fehler beim Laden der Songinfos" },
{ status: 500 } { status: 500 }
); );
} }
@@ -144,44 +104,27 @@ export async function PATCH(request: Request, { params }: RouteParams) {
/** /**
* @openapi * @openapi
* /api/songs/{songId}: * /api/songs/{id}:
* delete: * delete:
* summary: Song löschen * summary: Song löschen
* tags: * tags:
* - Songs * - Songs
* parameters: * parameters:
* - in: path * - in: path
* name: songId * name: id
* required: true * required: true
* schema: * schema:
* type: integer * type: integer
* description: Die ID des Songs * description: Die ID des Songs
* example: 1
* responses: * responses:
* 200: * 200:
* description: Song erfolgreich gelöscht (gibt den gelöschten Song zurück) * description: Song erfolgreich gelöscht
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/Song'
* 400: * 400:
* description: Ungültige Song-ID * description: Ungültige Song-ID
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/Error'
* 404: * 404:
* description: Song nicht gefunden * description: Song nicht gefunden
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/Error'
* 500: * 500:
* description: Serverfehler * description: Serverfehler
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/Error'
*/ */
export async function DELETE(_request: Request, { params }: RouteParams) { export async function DELETE(_request: Request, { params }: RouteParams) {
try { try {
@@ -196,7 +139,7 @@ export async function DELETE(_request: Request, { params }: RouteParams) {
} catch (error) { } catch (error) {
console.error("API Error:", error); console.error("API Error:", error);
return NextResponse.json( return NextResponse.json(
{ error: "Fehler beim Löschen des Songs" }, { error: "Fehler beim Laden der Songinfos" },
{ status: 500 } { status: 500 }
); );
} }
+23 -53
View File
@@ -1,51 +1,27 @@
// @/app/api/songs/route.ts // @wikiCategory: Lieder
import { NextResponse } from "next/server"; import { NextResponse } from "next/server";
import { getSongs, searchSongsByTitle, createSong } from "@/lib/db/song"; import { getSongs, searchSongsByTitle, createSong, } from "@/lib/db/song";
/** /**
* @openapi * @openapi
* /api/songs: * /api/songs:
* get: * get:
* summary: Get all songs or search songs by title * summary: Get all songs
* tags:
* - Songs
* parameters:
* - in: query
* name: query
* required: false
* schema:
* type: string
* description: Search term for the song title
* example: "Großer Gott"
* - in: query
* name: q
* required: false
* schema:
* type: string
* description: Alias for `query`
* example: "Großer Gott"
* responses: * responses:
* 200: * 200:
* description: List of songs (filtered by title if a query is given) * description: List of songs
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: '#/components/schemas/Song'
* 500: * 500:
* description: Internal Server Error * description: Internal Server Error
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/Error'
*/ */
export async function GET(request: Request) { export async function GET(request: Request) {
try { try {
const { searchParams } = new URL(request.url); const { searchParams } = new URL(request.url);
const query = searchParams.get("query") || searchParams.get("q"); const query = searchParams.get("query") || searchParams.get("q");
if (query) { if (query) {
const res = await searchSongsByTitle(query/*, 20*/); // You can enter a limit (default: 20) const res = await searchSongsByTitle(query/*, 20*/); // You can enter a limit (default: 20)
@@ -66,7 +42,7 @@ export async function GET(request: Request) {
return NextResponse.json(res.songs, { status: res.status }); return NextResponse.json(res.songs, { status: res.status });
} catch (error) { } catch (error) {
console.error("GET /api/songs error:", error); console.error("POST /api/songs error:", error);
return NextResponse.json( return NextResponse.json(
{ message: "Internal Server Error" }, { message: "Internal Server Error" },
{ status: 500 } { status: 500 }
@@ -74,13 +50,12 @@ export async function GET(request: Request) {
} }
} }
/** /**
* @openapi * @openapi
* /api/songs: * /api/songs:
* post: * post:
* summary: Creates a new song * summary: Creates a new song
* tags:
* - Songs
* requestBody: * requestBody:
* required: true * required: true
* content: * content:
@@ -88,14 +63,14 @@ export async function GET(request: Request) {
* schema: * schema:
* type: object * type: object
* required: * required:
* - title * - name
* properties: * properties:
* title: * name:
* type: string * type: string
* example: "Großer Gott" * example: "Großer Gott"
* responses: * responses:
* 201: * 201:
* description: Song successfully created * description: Songbook successfully created
* content: * content:
* application/json: * application/json:
* schema: * schema:
@@ -104,26 +79,21 @@ export async function GET(request: Request) {
* success: * success:
* type: boolean * type: boolean
* example: true * example: true
* song: * songBook:
* $ref: '#/components/schemas/Song' * type: object
* properties:
* id:
* type: integer
* example: 1
* title:
* type: string
* example: "Großer Gott"
* 400: * 400:
* description: Bad Request (missing title) * description: Bad Request (missing name)
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/Error'
* 409: * 409:
* description: Conflict (title already exists) * description: Conflict (title already exists)
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/Error'
* 500: * 500:
* description: Internal Server Error * description: Internal Server Error
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/Error'
*/ */
export async function POST(request: Request) { export async function POST(request: Request) {
try { try {
@@ -131,7 +101,7 @@ export async function POST(request: Request) {
if (!data.title) { if (!data.title) {
return NextResponse.json( return NextResponse.json(
{ message: "Field 'title' is required" }, { message: "Field 'title' is required"},
{ status: 400 } { status: 400 }
); );
} }
+3 -97
View File
@@ -1,22 +1,7 @@
// @/app/api/stream/route.ts // @wikiCategory: Stream
import { NextResponse } from "next/server"; import { NextResponse } from "next/server";
/**
* @openapi
* components:
* schemas:
* StreamError:
* type: object
* properties:
* success:
* type: boolean
* example: false
* error:
* type: string
* example: "Fields incomplete!"
*/
let currentSong = { let currentSong = {
number: "", number: "",
@@ -26,23 +11,7 @@ let currentSong = {
const clients = new Set<ReadableStreamDefaultController>(); const clients = new Set<ReadableStreamDefaultController>();
/** // @wikiDescription: Akutell gestreamtes Lied abrufen
* @openapi
* /api/stream:
* get:
* summary: Aktuell gestreamtes Lied abrufen (Server-Sent Events)
* description: Öffnet einen SSE-Stream. Beim Verbinden wird das aktuelle Lied gesendet (falls gesetzt), danach bei jeder Änderung ein neues Event.
* tags:
* - Stream
* responses:
* 200:
* description: Event-Stream mit dem aktuellen Lied
* content:
* text/event-stream:
* schema:
* type: string
* example: 'data: {"number":"104a","song":"Großer Gott","songbook":"Feiert Jesus 1"}'
*/
export async function GET() { export async function GET() {
let controllerRef: ReadableStreamDefaultController; let controllerRef: ReadableStreamDefaultController;
@@ -69,70 +38,7 @@ export async function GET() {
}); });
} }
/** // @wikiDescription: Lied zum Streamen festlegen
* @openapi
* /api/stream:
* post:
* summary: Lied zum Streamen festlegen
* description: Setzt das aktuelle Lied und sendet es an alle verbundenen Stream-Clients.
* tags:
* - Stream
* requestBody:
* required: true
* content:
* application/json:
* schema:
* type: object
* required:
* - song
* - songBook
* - number
* properties:
* song:
* type: string
* example: "Großer Gott"
* songBook:
* type: string
* example: "Feiert Jesus 1"
* number:
* type: string
* example: "104a"
* responses:
* 200:
* description: Lied gesetzt und an alle Clients gesendet
* content:
* application/json:
* schema:
* type: object
* properties:
* success:
* type: boolean
* example: true
* currentSong:
* type: object
* properties:
* number:
* type: string
* example: "104a"
* song:
* type: string
* example: "Großer Gott"
* songbook:
* type: string
* example: "Feiert Jesus 1"
* 400:
* description: Felder unvollständig
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/StreamError'
* 500:
* description: Serverfehler
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/StreamError'
*/
export async function POST(request: Request) { export async function POST(request: Request) {
try { try {
const data = await request.json(); const data = await request.json();
-8
View File
@@ -1,8 +0,0 @@
'use client';
import SwaggerUI from 'swagger-ui-react';
import 'swagger-ui-react/swagger-ui.css';
export default function DocsPage() {
return <SwaggerUI url="/api/docs/api" />;
}
+8 -78
View File
@@ -1,97 +1,27 @@
"use client"; "use client";
import { useState, useEffect } from "react"; import { Screens } from "@/components/AllSongsTable";
import { Input } from "@/components/FormElements";
import { Screens } from "@/components/DatabaseOverview";
interface Songbook {
id: number;
name: string;
language: string;
}
interface Song {
song_id: number;
songbook_id: number;
song_number: string;
title: string;
}
export default function SenderPage() { export default function SenderPage() {
const [songbooks, setSongbooks] = useState<Songbook[]>([]); const sendSong = async (title: string, bookTitle: string, number: string) => {
const [song_search_name, setSongSearchName] = useState("");
const [allSongs, setAllSongs] = useState<Song[]>([]);
const [searchResults, setSearchResults] = useState<Song[]>([]);
const getSongslist = async () => {
try { try {
const res = await fetch("/api/songs"); const res = await fetch("/api/stream", {
if (res.ok) {
const data = await res.json();
setAllSongs(data);
setSearchResults(data);
}
} catch (error) {
setAllSongs([]);
console.error("Failed fetching songslist!");
}
};
useEffect(() => {
async function loadSongbooks() {
try {
const res = await fetch("/api/songbooks");
if (res.ok) {
const data = await res.json();
setSongbooks(data);
}
} catch (error) {
console.error("Loading songbooks failed: ", error);
}
}
loadSongbooks();
getSongslist();
}, []);
const sendID = async (sID: string, sbID: string) => {
if (!sID || !sbID) {
alert("Bitte Liederbuch UND SongID auswählen/eingeben!");
return;
}
try {
const res = await fetch("/api/stream/currentID", {
method: "POST", method: "POST",
headers: { "Content-Type": "application/json" }, headers: { "Content-Type": "application/json" },
body: JSON.stringify({ songbookID: sbID, songID: sID }), body: JSON.stringify({ song: title, songBook: bookTitle, number }),
}); });
if (!res.ok) { if (!res.ok) {
alert("Fehler beim Senden."); alert("Fehler beim Senden.");
} }
} catch (error) { } catch (error) {
console.error("Failed sending current songID:", error); console.error("Failed sending current song:", error);
}
};
const search = (query: string) => {
setSongSearchName(query);
if (query.trim() !== "") {
setSearchResults(
allSongs.filter((song) =>
song.title.toLowerCase().includes(query.toLowerCase()) ||
song.song_number.includes(query)
)
);
} else {
setSearchResults(allSongs);
} }
}; };
return ( return (
<Screens.Songs <Screens.Songs
actionName="Anzeigen" actionName="Anzeigen"
onSelectSong={(song) => sendID(String(song.song_id), String(song.songbook_id))} onSelectSong={(song, book, number) => sendSong(song.title, book.title, number)}
/> />
); );
} }
+34
View File
@@ -0,0 +1,34 @@
import { getAllApis } from "@/lib/wiki";
import Article from '@/components/wiki/Article';
import { API } from '@/components/mdx-components';
export default async function Page() {
const allApis = await getAllApis();
// Gruppiert die APIs nach ihrer Kategorie
const groupedApis = Object.groupBy(allApis, (api) => api.category);
return (
<Article title="API-Endpunkte">
{Object.entries(groupedApis).map(([category, apis]) => (
<div key={category} className="mb-10">
{/* Kategorie-Überschrift wird nur EINMAL pro Kategorie gerendert */}
<h2 className="text-2xl font-bold text-white mt-10 mb-4 border-b border-zinc-800 pb-2">
{category}
</h2>
{/* Routen innerhalb dieser Kategorie durchgehen */}
{apis?.map((api, index) => (
<div key={index} className="my-4">
{api.methods.map((method, mIndex) => (
<API route={api.route} method={method.method} key={mIndex}>
{method.description}
</API>
))}
</div>
))}
</div>
))}
</Article>
);
}
+146
View File
@@ -0,0 +1,146 @@
import { useState, useEffect, useMemo, ComponentPropsWithoutRef } from "react";
import Card from "./Card"
import { Input } from "./FormElements"
import { Song, SongBookDetailed } from "@/lib/db/response";
interface SongsProps extends Omit<ComponentPropsWithoutRef<typeof Card>, "title" | "children"> {
onSelectSong?: (song: Song, book: { id: number; title: string }, songNumber: string) => void;
actionName?: string;
songBooks?: SongBookDetailed[];
}
function Songs({ actionName, onSelectSong, songBooks, className = "", ...props }: SongsProps) {
const [query, setQuery] = useState("");
const [fetchedBooks, setFetchedBooks] = useState<SongBookDetailed[]>([]);
useEffect(() => {
if (songBooks) return;
async function load() {
try {
const res = await fetch("/api/songbooks");
if (!res.ok) return;
const list: { id: number }[] = await res.json();
const details = await Promise.all(
list.map(async (b) => {
const r = await fetch(`/api/songbooks/${b.id}`);
return r.ok ? await r.json() : null;
})
);
setFetchedBooks(details.filter(Boolean));
} catch (error) {
console.error("Loading songbooks failed: ", error);
}
}
load();
}, [songBooks]);
const books = songBooks ?? fetchedBooks;
// Pro Buch filtern; Bücher ohne Treffer werden ausgeblendet
const groups = useMemo(() => {
const q = query.trim().toLowerCase();
return books
.map((book) => {
const bookMatches = q !== "" && book.title.toLowerCase().includes(q);
const songs = (book.songs ?? []).filter(
(e) =>
!q ||
bookMatches ||
e.song.title.toLowerCase().includes(q) ||
String(e.songNumber).toLowerCase().includes(q)
);
return { book, songs };
})
.filter((g) => g.songs.length > 0);
}, [books, query]);
const th = "p-3 text-xs font-semibold text-neutral-600 dark:text-neutral-400 uppercase tracking-wider";
return (
<Card
{...props}
title="Alle Lieder"
className={`h-[500px] ${className}`}
>
<div className="mb-4">
<Input.Text
type="text"
placeholder="Nach Songtitel, Nummer oder Liederbuch suchen..."
value={query}
onChange={(e) => setQuery(e.target.value)}
/>
</div>
<div className="flex-1 min-h-0 overflow-auto border border-neutral-200 dark:border-neutral-800 rounded-lg bg-white dark:bg-black">
<table className="w-full text-left border-collapse text-sm">
<thead className="bg-neutral-100 dark:bg-neutral-900 sticky top-0 border-b border-neutral-200 dark:border-neutral-800 z-10">
<tr>
<th className={`${th} w-24 text-center`}>Nummer</th>
<th className={th}>Titel</th>
<th className={`${th} text-right`}>Aktion</th>
</tr>
</thead>
{groups.length === 0 ? (
<tbody>
<tr>
<td colSpan={3} className="p-8 text-center text-neutral-400 dark:text-neutral-500">
Keine Lieder gefunden
</td>
</tr>
</tbody>
) : (
groups.map(({ book, songs }) => (
<tbody key={book.id} className="divide-y divide-neutral-200 dark:divide-neutral-800">
<tr className="bg-neutral-50 dark:bg-neutral-950">
<th
colSpan={3}
className="p-3 text-sm font-bold text-neutral-900 dark:text-white border-y border-neutral-200 dark:border-neutral-800"
>
{book.title}
{book.language && (
<span className="ml-2 text-xs font-normal text-neutral-500 dark:text-neutral-400">
({book.language})
</span>
)}
</th>
</tr>
{songs.map((entry) => (
<tr
key={`${book.id}-${entry.song.id}`}
className="hover:bg-neutral-100/60 dark:hover:bg-neutral-900/40 transition"
>
<td className="p-3 text-center font-mono text-blue-600 dark:text-blue-400 font-bold">
{entry.songNumber}
</td>
<td className="p-3 font-medium text-neutral-900 dark:text-white">
{entry.song.title}
</td>
<td className="p-3 text-right">
<Input.Button
onClick={() =>
onSelectSong?.(
entry.song,
{ id: book.id, title: book.title },
String(entry.songNumber)
)
}
className="bg-white dark:bg-black hover:bg-blue-600 dark:hover:bg-blue-600 border border-neutral-300 dark:border-neutral-700 hover:border-blue-600 dark:hover:border-blue-500 hover:text-white font-medium rounded-md px-3 py-1.5 transition text-xs"
>
{actionName}
</Input.Button>
</td>
</tr>
))}
</tbody>
))
)}
</table>
</div>
</Card>
)
}
export const Screens = {
Songs: Songs,
}
-143
View File
@@ -1,143 +0,0 @@
import { useState, useEffect, ComponentPropsWithoutRef } from "react";
import Card from "./Card"
import { Input } from "./FormElements"
interface SongsProps extends Omit<ComponentPropsWithoutRef<typeof Card>, "title" | "children"> {
onSelectSong?: (song: Song) => void;
actionName?: string;
}
interface Song {
song_id: number;
songbook_id: number;
song_number: string;
title: string;
}
interface Songbook {
id: number;
name: string;
language: string;
}
function Songs({ actionName, onSelectSong, className = "", ...props }: SongsProps) {
const [song_search_name, setSongSearchName] = useState("");
const [searchResults, setSearchResults] = useState<Song[]>([]);
const [allSongs, setAllSongs] = useState<Song[]>([]);
const [songbooks, setSongbooks] = useState<Songbook[]>([]);
const search = (query: string) => {
setSongSearchName(query);
if (query.trim() !== "") {
setSearchResults(
allSongs.filter((song) =>
song.title.toLowerCase().includes(query.toLowerCase()) ||
song.song_number.includes(query)
)
);
} else {
setSearchResults(allSongs);
}
};
useEffect(() => {
const getSongslist = async () => {
try {
const res = await fetch("/api/songs");
if (res.ok) {
const data = await res.json();
setAllSongs(data);
setSearchResults(data);
}
} catch (error) {
setAllSongs([]);
console.error("Failed fetching songslist!");
}
};
async function loadSongbooks() {
try {
const res = await fetch("/api/songbooks");
if (res.ok) {
const data = await res.json();
setSongbooks(data);
}
} catch (error) {
console.error("Loading songbooks failed: ", error);
}
}
loadSongbooks();
getSongslist();
}, []);
return (
<Card
{...props}
title="Alle Lieder"
className={`h-[500px] ${className}`}
>
<div className="mb-4">
<Input.Text
type="text"
placeholder="Nach Songtitel oder Nummer suchen..."
value={song_search_name}
onChange={(e) => search(e.target.value)}
/>
</div>
{/* TABELLE */}
<div className="flex-1 min-h-0 overflow-auto border border-neutral-200 dark:border-neutral-800 rounded-lg bg-white dark:bg-black">
<table className="w-full text-left border-collapse text-sm">
<thead className="bg-neutral-100 dark:bg-neutral-900 sticky top-0 border-b border-neutral-200 dark:border-neutral-800 z-10">
<tr>
<th className="p-3 text-xs font-semibold text-neutral-600 dark:text-neutral-400 uppercase tracking-wider">Titel</th>
<th className="p-3 text-xs font-semibold text-neutral-600 dark:text-neutral-400 uppercase tracking-wider">Liederbuch</th>
<th className="p-3 text-xs font-semibold text-neutral-600 dark:text-neutral-400 uppercase tracking-wider text-center">Nummer</th>
<th className="p-3 text-xs font-semibold text-neutral-600 dark:text-neutral-400 uppercase tracking-wider text-right">Aktion</th>
</tr>
</thead>
<tbody className="divide-y divide-neutral-200 dark:divide-neutral-800">
{searchResults.length === 0 ? (
<tr>
<td colSpan={4} className="p-8 text-center text-neutral-400 dark:text-neutral-500">Keine Lieder gefunden</td>
</tr>
) : (
searchResults.map((song) => {
const songBook = songbooks.find((book) => book.id === song.songbook_id);
return (
<tr key={`${song.songbook_id}-${song.song_id}`} className="hover:bg-neutral-100/60 dark:hover:bg-neutral-900/40 transition">
<td className="p-3 font-medium text-neutral-900 dark:text-white max-w-[180px] sm:max-w-none truncate">
{song.title}
<span className="block text-xs text-neutral-500 dark:text-neutral-400 sm:hidden mt-0.5">
{songBook ? songBook.name : "Unbekannt"}
</span>
</td>
<td className="p-3 text-neutral-700 dark:text-neutral-300 hidden sm:table-cell">
{songBook ? songBook.name : "Unbekannt"}
</td>
<td className="p-3 text-center font-mono text-blue-600 dark:text-blue-400 font-bold">
{song.song_number}
</td>
<td className="p-3 text-right">
<Input.Button
onClick={() => onSelectSong?.(song)}
className="bg-white dark:bg-black hover:bg-blue-600 dark:hover:bg-blue-600 border border-neutral-300 dark:border-neutral-700 hover:border-blue-600 dark:hover:border-blue-500 hover:text-white font-medium rounded-md px-3 py-1.5 transition text-xs"
>
{actionName}
</Input.Button>
</td>
</tr>
);
})
)}
</tbody>
</table>
</div>
</Card>
)
}
export const Screens = {
Songs: Songs,
}
+10
View File
@@ -18,6 +18,16 @@ export interface SongDetailed {
}; };
} }
export interface SongBookDetailed {
id: number;
title: string;
language: string;
songs?: {
songNumber: string;
song: Song;
}[]
}
export type APIResponse<T> = export type APIResponse<T> =
| { success: true; status: number; data: T } | { success: true; status: number; data: T }
| { success: false; status: number; error: string }; | { success: false; status: number; error: string };
+228
View File
@@ -0,0 +1,228 @@
import fs from 'fs';
import path from 'path';
import matter from 'gray-matter';
import ts from 'typescript';
import { ApiRoute, ApiMethod } from '@/types/api';
export type WikiArticle = {
slug: string;
title: string;
rawContent: string;
updatedAt?: string;
};
export type WikiPage = {
title: string;
path: string;
}
const wikiDirectory = path.join(process.cwd(), "data/wiki/pages");
export async function getWikiPageBySlug(slug: string): Promise<WikiArticle | null> {
try {
const fullPath = path.join(wikiDirectory, `${slug}.mdx`);
const fileContents = fs.readFileSync(fullPath, "utf-8");
const { data, content } = matter(fileContents);
return {
slug,
rawContent: content,
title: data.title || 'Unbenannt',
updatedAt: data.updatedAt || null,
...data,
} as WikiArticle;
} catch (error) {
return null;
}
}
/**
* Liest rekursiv alle Dateien aus einem Verzeichnis aus.
* @param dirPath - Der Startordner
* @param extension - Optionale Dateiendung zur Filterung (z. B. ".ts" oder "ts")
* @returns Array mit den Dateipfaden
*/
export function getAllFiles(dirPath: string, extension?: string): string[] {
if (!fs.existsSync(dirPath)) return [];
let results: string[] = [];
// optionales führendes Dot sicherstellen (z. B. aus "ts" wird ".ts")
const targetExt = extension && !extension.startsWith('.')
? `.${extension}`
: extension;
// withFileTypes: true spart zusätzliche fs.statSync Aufrufe
const entries = fs.readdirSync(dirPath, { withFileTypes: true });
for (const entry of entries) {
const fullPath = path.join(dirPath, entry.name);
if (entry.isDirectory()) {
results = results.concat(getAllFiles(fullPath, targetExt));
} else if (!targetExt || entry.name.endsWith(targetExt)) {
results.push(fullPath);
}
}
return results;
}
/**
* Liest die Kategorie aus der Datei aus (@wikiCategory) oder ermittelt sie aus dem Ordnernamen.
*/
export function filterCategory(
content: string,
filePath: string,
prefix: string = '@wikiCategory'
): string {
// 1. In Kommentaren nach @wikiCategory suchen
const lines = content.split('\n');
for (const line of lines) {
const cleaned = line.replace(/^\/\/\s*/, '').replace(/^\/\*\*?\s*/, '').replace(/\*\/$/, '').trim();
if (cleaned.startsWith(prefix)) {
let category = cleaned.slice(prefix.length).trim().replace(/^:\s*/, '');
if (category) return category;
}
}
// 2. Fallback: Ersten Ordnernamen unter app/api/ als Kategorie nutzen
const normalizedPath = filePath.replace(/\\/g, '/');
const apiMatch = normalizedPath.match(/app\/api\/([^/]+)/);
if (apiMatch && apiMatch[1]) {
const folderName = apiMatch[1];
// Ersten Buchstaben großschreiben (z. B. "stream" -> "Stream")
return folderName.charAt(0).toUpperCase() + folderName.slice(1);
}
return 'Allgemein';
}
/**
* Parst TypeScript-Code via AST und extrahiert HTTP-Methoden sowie deren Kommentare.
*/
export function filterMethods(
content: string,
prefix: string = '@wikiDescription'
): ApiMethod[] {
const sourceFile = ts.createSourceFile(
'temp.ts',
content,
ts.ScriptTarget.Latest,
/* setParentNodes */ true
);
const methods: ApiMethod[] = [];
const validMethods = new Set(['GET', 'POST', 'PUT', 'PATCH', 'DELETE']);
ts.forEachChild(sourceFile, (node) => {
if (ts.isFunctionDeclaration(node) && node.name) {
const functionName = node.name.text;
if (validMethods.has(functionName)) {
let description = '';
const commentRanges = ts.getLeadingCommentRanges(content, node.pos);
if (commentRanges && commentRanges.length > 0) {
const lastCommentRange = commentRanges[commentRanges.length - 1];
const rawComment = content.substring(
lastCommentRange.pos,
lastCommentRange.end
);
const cleanedComment = rawComment
.replace(/^\/\/\s*/, '')
.replace(/^\/\*\*?\s*/, '')
.replace(/\*\/$/, '')
.split('\n')
.map((line) => line.replace(/^\s*\*\s?/, '').trim())
.join(' ')
.trim();
if (cleanedComment.startsWith(prefix)) {
let textAfterPrefix = cleanedComment.slice(prefix.length).trim();
textAfterPrefix = textAfterPrefix.replace(/^:\s*/, '');
description = textAfterPrefix;
}
}
methods.push({
method: functionName,
description: description || 'Keine Beschreibung vorhanden.',
});
}
}
});
return methods;
}
/**
* Liest alle API-Dateien dynamisch aus und wandelt sie in ApiRoute-Objekte um.
*/
export async function getAllApis(): Promise<ApiRoute[]> {
try {
const apiBasePath = path.join(process.cwd(), "app/api");
const allTsFiles = getAllFiles(apiBasePath, ".ts");
const routes: ApiRoute[] = [];
allTsFiles.forEach((filePath) => {
const fileContents = fs.readFileSync(filePath, "utf-8");
// 1. Methoden extrahieren
const methods = filterMethods(fileContents, "@wikiDescription");
// Nur Routen hinzufügen, die auch API-Methoden exportieren
if (methods.length > 0) {
// 2. Kategorie ermitteln
const category = filterCategory(fileContents, filePath, "@wikiCategory");
// 3. Route-Pfad automatisch aus dem Dateipfad generieren (app/api/stream/currentID/route.ts -> stream/currentID)
const relativePath = path.relative(apiBasePath, filePath).replace(/\\/g, '/');
const routePath = relativePath
.replace(/\/route\.ts$/, '')
.replace(/\.ts$/, '');
routes.push({
route: routePath,
category,
methods,
});
}
});
return routes;
} catch (error) {
console.error("Fehler beim Auslesen der API-Dateien:", error);
return [];
}
}
export async function getAllWikiPages(): Promise<WikiPage[]> {
try {
const pagesBasePath = path.join(process.cwd(), "data/wiki/pages");
const allPaths = getAllFiles(pagesBasePath, ".mdx");
const allPages: WikiPage[] = [];
for (const filePath of allPaths) {
// extract filename of the path (e. g. "test" at "data/wiki/pages/test.mdx")
const slug = path.parse(filePath).name;
const wikiPage = await getWikiPageBySlug(slug);
if (wikiPage) {
allPages.push({
path: slug,
title: wikiPage.title,
});
}
}
console.log(allPages);
return allPages;
} catch (error) {
console.error("Fehler beim Auslesen der Wiki-Seiten:", error);
return [];
}
}
+1470 -8860
View File
File diff suppressed because it is too large. Load diff
+5 -10
View File
@@ -6,20 +6,20 @@
"dev": "next dev", "dev": "next dev",
"build": "next build", "build": "next build",
"start": "next start", "start": "next start",
"lint": "eslint", "lint": "eslint"
"openapi:generate": "node scripts/generate-openapi.mjs"
}, },
"dependencies": { "dependencies": {
"@prisma/adapter-better-sqlite3": "^7.9.1", "@prisma/adapter-better-sqlite3": "^7.9.1",
"@prisma/client": "^7.10.0", "@prisma/client": "^7.9.1",
"@types/papaparse": "^5.5.2", "@types/papaparse": "^5.5.2",
"argon2": "^0.45.1", "argon2": "^0.45.1",
"better-sqlite3": "^13.0.2", "better-sqlite3": "^13.0.2",
"dotenv": "^17.4.2", "dotenv": "^17.4.2",
"gray-matter": "^4.0.3", "gray-matter": "^4.0.3",
"next": "^16.4.0", "next": "16.2.9",
"next-mdx-remote": "^6.0.0", "next-mdx-remote": "^6.0.0",
"papaparse": "^5.5.4", "papaparse": "^5.5.4",
"prisma": "^7.9.1",
"react": "19.2.4", "react": "19.2.4",
"react-dom": "19.2.4", "react-dom": "19.2.4",
"rehype-autolink-headings": "^7.1.0", "rehype-autolink-headings": "^7.1.0",
@@ -31,8 +31,7 @@
"remark-html": "^16.0.1", "remark-html": "^16.0.1",
"remark-parse": "^11.0.0", "remark-parse": "^11.0.0",
"remark-rehype": "^11.1.2", "remark-rehype": "^11.1.2",
"shiki": "^4.4.1", "shiki": "^4.4.1"
"swagger-ui-react": "^5.33.2"
}, },
"devDependencies": { "devDependencies": {
"@tailwindcss/postcss": "^4", "@tailwindcss/postcss": "^4",
@@ -41,12 +40,8 @@
"@types/node": "^20", "@types/node": "^20",
"@types/react": "^19", "@types/react": "^19",
"@types/react-dom": "^19", "@types/react-dom": "^19",
"@types/swagger-jsdoc": "^6.0.4",
"@types/swagger-ui-react": "^5.18.0",
"eslint": "^9", "eslint": "^9",
"eslint-config-next": "16.2.9", "eslint-config-next": "16.2.9",
"prisma": "^8.0.0-rc.22",
"swagger-jsdoc": "^6.3.0",
"tailwindcss": "^4", "tailwindcss": "^4",
"typescript": "^5.9.3" "typescript": "^5.9.3"
}, },
-18
View File
@@ -1,18 +0,0 @@
import swaggerJsdoc from 'swagger-jsdoc';
import { mkdirSync, writeFileSync } from 'node:fs';
import { dirname } from 'node:path';
const spec = swaggerJsdoc({
definition: {
openapi: '3.0.0',
info: { title: 'PsalmTafel API', version: '1.0.0' },
},
apis: ['./app/api/**/*.ts'],
failOnErrors: true,
});
const out = 'src/generated/openapi.json';
mkdirSync(dirname(out), { recursive: true });
writeFileSync(out, JSON.stringify(spec, null, 2));
console.log(`OpenAPI: ${Object.keys(spec.paths ?? {}).length} Pfade -> ${out}`);
File diff suppressed because it is too large. Load diff