2026-04-21 14:26:12 +02:00
|
|
|
"""
|
|
|
|
|
Shinkan Jinkendo - Main Application Entry Point
|
|
|
|
|
|
|
|
|
|
Trainer- und Vereinsplattform für Kampfsport-Trainingsplanung
|
|
|
|
|
"""
|
2026-04-27 14:27:25 +02:00
|
|
|
from pathlib import Path
|
2026-04-29 12:29:39 +02:00
|
|
|
from typing import Optional
|
2026-04-27 14:27:25 +02:00
|
|
|
|
2026-04-21 14:26:12 +02:00
|
|
|
from fastapi import FastAPI
|
|
|
|
|
from fastapi.middleware.cors import CORSMiddleware
|
|
|
|
|
from fastapi.responses import JSONResponse
|
2026-04-27 14:27:25 +02:00
|
|
|
from fastapi.staticfiles import StaticFiles
|
2026-04-21 14:26:12 +02:00
|
|
|
import os
|
2026-04-29 12:29:39 +02:00
|
|
|
import sys
|
2026-04-21 14:26:12 +02:00
|
|
|
|
2026-04-29 09:57:36 +02:00
|
|
|
from slowapi import _rate_limit_exceeded_handler
|
|
|
|
|
from slowapi.errors import RateLimitExceeded
|
|
|
|
|
|
2026-04-21 14:26:12 +02:00
|
|
|
from version import APP_VERSION, BUILD_DATE, DB_SCHEMA_VERSION, MODULE_VERSIONS
|
2026-04-21 14:49:28 +02:00
|
|
|
|
2026-04-29 12:29:39 +02:00
|
|
|
# Run database migrations before API start — halbes Schema ist schlimmer als kein Start
|
|
|
|
|
# Lokal ohne DB / nur Tests: SKIP_DB_MIGRATE=1
|
|
|
|
|
if os.getenv("SKIP_DB_MIGRATE", "").strip().lower() in ("1", "true", "yes"):
|
2026-05-05 16:18:42 +02:00
|
|
|
print("[SKIP_DB_MIGRATE] Migrationen uebersprungen (nur fuer Entwicklung ohne DB)")
|
2026-04-29 12:29:39 +02:00
|
|
|
else:
|
|
|
|
|
try:
|
|
|
|
|
import run_migrations
|
|
|
|
|
|
|
|
|
|
rc = run_migrations.main()
|
|
|
|
|
if rc != 0:
|
2026-05-05 16:18:42 +02:00
|
|
|
print(f"[FAIL] Datenbank-Migration fehlgeschlagen (Exit-Code {rc}). Start abgebrochen.")
|
2026-04-29 12:29:39 +02:00
|
|
|
sys.exit(1)
|
2026-05-05 16:18:42 +02:00
|
|
|
print("[OK] Database migrations completed")
|
2026-04-29 12:29:39 +02:00
|
|
|
except SystemExit:
|
|
|
|
|
raise
|
|
|
|
|
except Exception as e:
|
2026-05-05 16:18:42 +02:00
|
|
|
print(f"[FAIL] Migration-Laufzeitfehler: {e}")
|
2026-04-29 12:29:39 +02:00
|
|
|
sys.exit(1)
|
2026-04-21 14:26:12 +02:00
|
|
|
|
2026-04-29 09:57:36 +02:00
|
|
|
from routers.auth import limiter as auth_rate_limiter
|
|
|
|
|
|
2026-04-21 14:26:12 +02:00
|
|
|
# Initialize FastAPI app
|
|
|
|
|
app = FastAPI(
|
|
|
|
|
title="Shinkan Jinkendo API",
|
|
|
|
|
description="Trainer- und Vereinsplattform für Kampfsport-Trainingsplanung",
|
|
|
|
|
version=APP_VERSION
|
|
|
|
|
)
|
|
|
|
|
|
2026-04-29 09:57:36 +02:00
|
|
|
# SlowAPI: Rate Limits auf /api/auth/* (Decorator in routers/auth.py)
|
|
|
|
|
app.state.limiter = auth_rate_limiter
|
|
|
|
|
app.add_exception_handler(RateLimitExceeded, _rate_limit_exceeded_handler)
|
|
|
|
|
|
|
|
|
|
# CORS — kommaseparierte Liste (z. B. https://dev.shinkan… und http://192.168.x.x:3098)
|
|
|
|
|
_cors_raw = os.getenv("ALLOWED_ORIGINS", "http://localhost:3098")
|
|
|
|
|
ALLOWED_ORIGINS = [o.strip() for o in _cors_raw.split(",") if o.strip()]
|
2026-04-21 14:26:12 +02:00
|
|
|
|
|
|
|
|
app.add_middleware(
|
|
|
|
|
CORSMiddleware,
|
|
|
|
|
allow_origins=ALLOWED_ORIGINS,
|
|
|
|
|
allow_credentials=True,
|
|
|
|
|
allow_methods=["*"],
|
|
|
|
|
allow_headers=["*"],
|
|
|
|
|
)
|
|
|
|
|
|
2026-04-21 14:49:28 +02:00
|
|
|
# TODO: Initialize Database with migrations
|
2026-04-21 14:26:12 +02:00
|
|
|
|
|
|
|
|
# Version Endpoint (public, no auth)
|
|
|
|
|
@app.get("/api/version")
|
|
|
|
|
def get_version():
|
|
|
|
|
"""Get application version and build info"""
|
|
|
|
|
return {
|
|
|
|
|
"app_version": APP_VERSION,
|
|
|
|
|
"build_date": BUILD_DATE,
|
|
|
|
|
"backend_version": APP_VERSION,
|
|
|
|
|
"modules": MODULE_VERSIONS,
|
|
|
|
|
"db_schema_version": DB_SCHEMA_VERSION,
|
|
|
|
|
"environment": os.getenv("ENVIRONMENT", "development")
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
# Health Check
|
|
|
|
|
@app.get("/health")
|
|
|
|
|
def health_check():
|
|
|
|
|
"""Health check endpoint"""
|
|
|
|
|
return {"status": "healthy", "version": APP_VERSION}
|
|
|
|
|
|
2026-04-29 12:29:39 +02:00
|
|
|
|
|
|
|
|
@app.get("/api/health/ready")
|
|
|
|
|
def health_ready():
|
|
|
|
|
"""
|
|
|
|
|
Verbindung + Kern-Tabellen prüfen (ohne Login).
|
|
|
|
|
Nutzen bei Prod-Debugging: wenn schema_complete=false, Migrationen nicht vollständig.
|
|
|
|
|
"""
|
|
|
|
|
from db import get_db, get_cursor
|
|
|
|
|
|
|
|
|
|
REQUIRED = (
|
|
|
|
|
"schema_migrations",
|
|
|
|
|
"skills",
|
|
|
|
|
"skill_main_categories",
|
|
|
|
|
"skill_categories",
|
|
|
|
|
"maturity_models",
|
|
|
|
|
"sessions",
|
2026-05-05 16:12:17 +02:00
|
|
|
"club_members",
|
|
|
|
|
"club_member_roles",
|
2026-04-29 12:29:39 +02:00
|
|
|
)
|
|
|
|
|
tables: dict = {}
|
|
|
|
|
err: Optional[str] = None
|
|
|
|
|
try:
|
|
|
|
|
with get_db() as conn:
|
|
|
|
|
cur = get_cursor(conn)
|
|
|
|
|
cur.execute("SELECT 1")
|
|
|
|
|
for tbl in REQUIRED:
|
|
|
|
|
cur.execute(
|
|
|
|
|
"""
|
|
|
|
|
SELECT EXISTS (
|
|
|
|
|
SELECT 1 FROM information_schema.tables
|
|
|
|
|
WHERE table_schema = 'public' AND table_name = %s
|
|
|
|
|
)
|
|
|
|
|
""",
|
|
|
|
|
(tbl,),
|
|
|
|
|
)
|
|
|
|
|
row = cur.fetchone()
|
|
|
|
|
tables[tbl] = bool(next(iter(row.values()))) if row else False
|
|
|
|
|
migration_count = 0
|
|
|
|
|
if tables.get("schema_migrations"):
|
|
|
|
|
cur.execute("SELECT COUNT(*)::int FROM schema_migrations")
|
|
|
|
|
mig_row = cur.fetchone()
|
|
|
|
|
migration_count = (
|
|
|
|
|
int(list(mig_row.values())[0]) if mig_row is not None else 0
|
|
|
|
|
)
|
|
|
|
|
except Exception as e:
|
|
|
|
|
err = str(e)
|
|
|
|
|
migration_count = 0
|
|
|
|
|
|
|
|
|
|
complete = bool(err is None and all(tables.get(t) for t in REQUIRED))
|
|
|
|
|
return {
|
|
|
|
|
"status": "ready" if complete else "degraded",
|
|
|
|
|
"database": err is None,
|
|
|
|
|
"detail": err,
|
|
|
|
|
"schema_complete": complete,
|
|
|
|
|
"tables": tables,
|
|
|
|
|
"schema_migrations_count": migration_count,
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
2026-04-21 14:26:12 +02:00
|
|
|
# Root Endpoint
|
|
|
|
|
@app.get("/")
|
|
|
|
|
def read_root():
|
|
|
|
|
"""Root endpoint - API info"""
|
|
|
|
|
return {
|
|
|
|
|
"app": "Shinkan Jinkendo API",
|
|
|
|
|
"version": APP_VERSION,
|
|
|
|
|
"docs": "/docs",
|
|
|
|
|
"health": "/health"
|
|
|
|
|
}
|
|
|
|
|
|
2026-04-21 14:56:16 +02:00
|
|
|
# Register routers
|
2026-05-05 16:40:49 +02:00
|
|
|
from routers import auth, profiles, exercises, exercise_progression_graphs, clubs, club_memberships, club_join_requests, skills, training_planning, training_framework_programs, catalogs, maturity_models, matrix_stack_bundle, import_wiki, import_wiki_admin
|
2026-04-21 14:56:16 +02:00
|
|
|
|
2026-04-21 16:12:25 +02:00
|
|
|
app.include_router(auth.router)
|
|
|
|
|
app.include_router(profiles.router)
|
2026-04-22 16:44:32 +02:00
|
|
|
app.include_router(exercises.router)
|
2026-04-30 11:47:50 +02:00
|
|
|
app.include_router(exercise_progression_graphs.router)
|
feat: Clubs & Organization Management complete
Backend:
- Created routers/clubs.py with full CRUD
- Clubs: list, get, create, update, delete (admin only)
- Divisions: list, create, update, delete (admin only)
- Training Groups: list, get, create, update, delete (admin/trainer)
- Registered clubs router in main.py
- Permission checks: admin for clubs/divisions, trainer for groups
Frontend:
- Complete ClubsPage with 3 tabs (Vereine, Sparten, Gruppen)
- Role-based UI (admin sees all actions, trainer can manage groups)
- Full CRUD forms with modals
- Mobile-responsive card layouts
- Updated api.js with all club/division/group functions
Migration already exists: 002_organization.sql (clubs, divisions, training_groups)
Next: Skills & Methods display (read-only)
2026-04-22 16:48:02 +02:00
|
|
|
app.include_router(clubs.router)
|
2026-05-05 16:40:49 +02:00
|
|
|
app.include_router(club_join_requests.router)
|
feat: Skills & Methods catalog complete
Backend:
- Created routers/skills.py with full CRUD
- Skills: list (with category filter), get, create, update, delete
- Methods: list (with category filter), get, create, update, delete
- Default: only show active items
- Read access: all authenticated users
- Write access: admin only
- Registered skills router in main.py
Frontend:
- Complete SkillsPage with 2 tabs (Fähigkeiten, Trainingsmethoden)
- Browse by category with cards layout
- Admin CRUD forms (importance rating for skills, duration/group size for methods)
- Mobile-responsive grid layout
- Updated api.js with all skill/method functions
- Added /skills route to App.jsx
Migration already exists: 003_catalogs.sql (skills, training_methods + seed data)
Next: Training Planning (core feature)
2026-04-22 16:50:31 +02:00
|
|
|
app.include_router(skills.router)
|
feat: Training Planning (core feature) complete
Backend:
- Created migration 006_training_planning.sql
- training_units table (planned vs actual, status, notes)
- training_unit_exercises M:N (order, duration, modifications)
- Created routers/training_planning.py with full CRUD
- List with filters (group, date range, status)
- Get detail with exercises
- Create/Update/Delete with access control
- Quick create endpoint (auto-fills from group defaults)
- Permission: trainer for own groups, admin for all
- Registered training_planning router in main.py
Frontend:
- Complete TrainingPlanningPage with full planning workflow
- Group selector + date range picker
- List view with status badges (planned/completed/cancelled)
- Create/Edit modal with exercise management
- Drag to reorder exercises (▲▼)
- Quick create button (one-click with group defaults)
- Durchführung section (actual date/time, attendance, status)
- Public notes + trainer-only notes
- Updated api.js with deleteTrainingUnit and quickCreateTrainingUnit
- Added /planning route to App.jsx
- Navigation already configured (Calendar icon)
This is the CORE feature - trainers can now plan and document training sessions.
Next: Admin routes, role system refinement, testing
2026-04-22 16:54:34 +02:00
|
|
|
app.include_router(training_planning.router)
|
2026-05-05 08:41:43 +02:00
|
|
|
app.include_router(training_framework_programs.router)
|
feat: Exercise Catalogs - Admin-verwaltbare Stammdaten (Backend)
Problem: Hard-codierte Werte (Fokusbereich, Trainingscharakter) + fehlende
Dimensionen (Stil, Fähigkeiten-Matrix) + keine Rollen-basierte Sichtbarkeit
Lösung: Dynamische Kataloge mit Admin-CRUD
Migration 007_exercise_catalogs.sql:
- focus_areas (statt hard-coded 'karate', 'selbstverteidigung', 'gewaltschutz')
- training_styles (NEU: Shotokan, Goju-Ryu, Wado-Ryu, etc. mit Hierarchie)
- training_characters (statt hard-coded 'grundlage', 'aufbau', etc.)
- skill_categories (Matrix: Kategorien → Einzelfähigkeiten)
- trainer_focus_areas (Zuordnung: Trainer → Fokusbereiche)
- exercises erweitert: training_style_id, training_character_id, focus_area_id
- skills erweitert: category_id, parent_skill_id, level, sort_order
- Seed-Daten für alle Kataloge
Backend (routers/catalogs.py):
- CRUD für focus_areas (admin only)
- CRUD für training_styles (admin only, mit parent_style_id)
- CRUD für training_characters (admin only)
- CRUD für skill_categories (admin only, mit parent_category_id)
- CRUD für trainer_focus_areas (admin: assign, trainer: read own)
- Alle mit status-Filter (active/inactive)
Backend (routers/exercises.py):
- CREATE/UPDATE erweitert um training_style_id, training_character_id, focus_area_id
- Legacy-Felder (focus_area text, training_character text) bleiben parallel
Backend (main.py):
- catalogs Router registriert
Nächster Schritt: Frontend-UI (Admin-Kataloge + Exercise-Formular-Update)
2026-04-22 22:06:11 +02:00
|
|
|
app.include_router(catalogs.router)
|
2026-04-27 11:32:30 +02:00
|
|
|
app.include_router(maturity_models.router)
|
2026-04-27 13:13:36 +02:00
|
|
|
app.include_router(matrix_stack_bundle.router)
|
2026-04-24 14:41:52 +02:00
|
|
|
app.include_router(import_wiki.router)
|
2026-04-27 08:52:05 +02:00
|
|
|
app.include_router(import_wiki_admin.router)
|
2026-04-21 14:26:12 +02:00
|
|
|
|
2026-04-27 14:27:25 +02:00
|
|
|
# Lokale Medien (Übungen-Uploads) unter MEDIA_ROOT, ausliefern unter /media/...
|
|
|
|
|
_media_dir = os.getenv("MEDIA_ROOT", str(Path(__file__).resolve().parent / "media"))
|
|
|
|
|
Path(_media_dir).mkdir(parents=True, exist_ok=True)
|
|
|
|
|
app.mount("/media", StaticFiles(directory=_media_dir), name="media")
|
|
|
|
|
|
2026-04-21 14:26:12 +02:00
|
|
|
if __name__ == "__main__":
|
|
|
|
|
import uvicorn
|
|
|
|
|
uvicorn.run(
|
|
|
|
|
"main:app",
|
|
|
|
|
host="0.0.0.0",
|
|
|
|
|
port=8000,
|
|
|
|
|
reload=True
|
|
|
|
|
)
|