Compare commits
52
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4e5a7b466f | ||
|
|
b719f85c4e | ||
|
|
ea7de64061 | ||
|
|
dbc2dfacb9 | ||
|
|
9b4d091637 | ||
|
|
4724da28b1 | ||
|
|
50c9beb4b3 | ||
|
|
29a5db63e0 | ||
|
|
6db31e7312 | ||
|
|
16187fbbd0 | ||
|
|
9ba35dc022 | ||
|
|
fc5748bef1 | ||
|
|
3bf012a8f4 | ||
|
|
69f238d9b8 | ||
|
|
a1b85cd865 | ||
|
|
4720d70af0 | ||
|
|
57c464c9f6 | ||
|
|
d42eb3ac52 | ||
|
|
f9df2d31db | ||
|
|
1e2fdeeb0f | ||
|
|
7450c269a5 | ||
|
|
99a5fccaa5 | ||
|
|
55d87d8d17 | ||
|
|
b35a5ae216 | ||
|
|
bd9cfaa6e4 | ||
|
|
639392e133 | ||
|
|
d153a22545 | ||
|
|
81d1e9bdfd | ||
|
|
3214055531 | ||
|
|
4c974620d8 | ||
|
|
3134160003 | ||
|
|
b19940c997 | ||
|
|
dbc9057601 | ||
|
|
6136813f60 | ||
|
|
d82b805ffa | ||
|
|
c8c40474d1 | ||
|
|
f035b5bb0b | ||
|
|
696cb09bf4 | ||
|
|
33fedd5ec6 | ||
|
|
c8a08f8a94 | ||
|
|
d04ebee1f6 | ||
|
|
0c1fbab0ef | ||
|
|
a7d68c0646 | ||
|
|
a34dc19f5d | ||
|
|
9227b98431 | ||
|
|
390b0ecb73 | ||
|
|
7e7adfab54 | ||
|
|
bce235b9f6 | ||
|
|
5334836207 | ||
|
|
38d78abc3b | ||
|
|
a143532486 | ||
|
|
2f54fef88e |
No files matched your search
@@ -8,10 +8,7 @@
|
||||
|
||||
**Ist-Stand API (Superadmin):**
|
||||
- `GET /api/admin/ai-prompts`, `GET /api/admin/ai-prompts/{id}`, `PUT …`, `POST …/preview`, `POST …/reset-template`, `GET /api/admin/ai-prompts/catalog/placeholders`
|
||||
- Spalte **`openrouter_model`** (Migration **070**): Optional pro Prompt-Zeile; OpenRouter **`model`**-Parameter. Leer ⇒ Plattform-Standard.
|
||||
- **Plattform-Standard** (Migration **097**, `platform_ai_settings.openrouter_model`): Superadmin unter `/admin/openrouter`. `GET/PUT /api/admin/openrouter/settings`, Katalog `GET /api/admin/openrouter/models`. Leer ⇒ **`OPENROUTER_MODEL`** aus der Umgebung.
|
||||
- Auflösung: Prompt-Override, sonst Aufgabengruppe (`ai_prompts.model_role`, Migration **098**: `reasoning` Denken, `drafting` Formulieren, `matching` Zuordnen), sonst Datenbank-Standard, sonst Umgebung.
|
||||
- Gruppenmodelle: `GET/PUT /api/admin/openrouter/roles` und `PUT /api/admin/openrouter/prompts/{id}/role`.
|
||||
- Spalte **`openrouter_model`** (Migration **070**): Optional pro Prompt-Zeile; OpenRouter **`model`**-Parameter; **`NULL`/leer ⇒ `OPENROUTER_MODEL`** aus der Umgebung.
|
||||
|
||||
**Autor:** Claude Code
|
||||
**Vorbild:** Mitai Jinkendo Issue #53 + `backend/routers/prompts.py` + Placeholder-System
|
||||
|
||||
@@ -271,7 +271,6 @@ exercise_variants (id, exercise_id, name, description, ...)
|
||||
exercise_media (id, exercise_id, media_asset_id NULL FK, embed_url, file_path, …)
|
||||
media_assets (id, sha256, visibility, club_id, lifecycle_state, copyright_notice, storage_key, …)
|
||||
platform_media_storage (id, local_relative_root, …)
|
||||
platform_ai_settings (id = 1, openrouter_model NULL = OPENROUTER_MODEL, …) -- Migration 097
|
||||
```
|
||||
|
||||
### Trainingsrahmenprogramm Bibliothek (Migrationen **035–036**)
|
||||
|
||||
@@ -1,91 +0,0 @@
|
||||
# Produktions-Deployments (Raspberry Pi + llm-node)
|
||||
|
||||
Stand: 2026-10-29
|
||||
|
||||
**Seit dem Cutover am 2026-10-29 ist llm-node die einzige Prod.** Der Reverse-Proxy für `shinkan.jinkendo.de` zeigt auf llm-node. Nur `deploy-prod-llm-node.yml` startet bei Push auf `main`; `deploy-prod.yml` (Pi) ist nur noch per „Run workflow“ startbar und dient als Rückfallweg (siehe „Rückfall auf den Pi“). Die Tabelle beschreibt beide Seiten.
|
||||
|
||||
Backup, Recovery und Erstbefüllung der llm-node-DB: `RECOVERY_CONTRACT.md`.
|
||||
|
||||
| | Raspberry Pi (alt) | llm-node (neu) |
|
||||
|---|---|---|
|
||||
| Workflow | `.gitea/workflows/deploy-prod.yml` | `.gitea/workflows/deploy-prod-llm-node.yml` |
|
||||
| Workflow-Name | `Deploy Production` | `Deploy Production llm-node` |
|
||||
| Host | 192.168.2.49, `raspberrypi5`, aarch64 | 192.168.2.144, `llm-node`, x86_64 |
|
||||
| Runner | `Raspi5-Paperless`, Label `ubuntu-latest` (Host-Modus) | `llm-node-runner`, Label `linux_host` (Host-Modus) |
|
||||
| Deploy-Verzeichnis | `/home/lars/docker/shinkan` | `/home/llmadmin/docker/shinkan-prod` |
|
||||
| Compose | `docker-compose.yml`, Projekt `shinkan` (Verzeichnisname) | `docker-compose.yml` + `docker-compose.llm-node.yml`, Projekt `shinkan-prod` |
|
||||
| Konfiguration | `/home/lars/docker/shinkan/.env` | `/etc/shinkan/prod.env` (Workflow-Variable `ENV_FILE`) |
|
||||
| Datenbank | Volume `shinkan_shinkan-db-data` auf dem Pi | Volume `shinkan-prod_shinkan-db-data` auf llm-node |
|
||||
| Medien (Host) | `SHINKAN_MEDIA_HOST` laut Pi-`.env` | `/srv/shinkan/prod/media` (NFSv4 von `192.168.2.63:/volume1/shinkan-media/prod`) |
|
||||
| Medien (Container) | `/app/media` | `/app/media` |
|
||||
| Medienbereinigung | `retention-cron` läuft bei jedem Lauf mit; nach Cutover gestoppt | an (`MEDIA_RETENTION: enabled`) |
|
||||
| Ports | 3003, 127.0.0.1:8003, 127.0.0.1:5434 | 3003, 127.0.0.1:8003, 127.0.0.1:5434 |
|
||||
| Auslösen | nur Gitea „Run workflow“ (`workflow_dispatch`) | Push auf `main` oder Gitea „Run workflow“ |
|
||||
|
||||
Die Runner-Labels sind am 2026-10-29 aus den `.runner`-Dateien beider Hosts abgelesen worden (act_runner v0.2.11). Jeder Workflow prüft im ersten Schritt Hostname und Architektur und bricht auf einem fremden Runner ab. Wer Labels an einem Runner ändert, muss beide Workflows mitprüfen; `ubuntu-latest` darf nicht auf llm-node, `linux_host` nicht auf dem Pi registriert werden.
|
||||
|
||||
Das llm-node-Deployment braucht vom Pi nichts: Code kommt aus dem Gitea auf llm-node selbst, DB und Konfiguration liegen lokal, Medien direkt auf dem NAS.
|
||||
|
||||
## Server-Voraussetzungen auf llm-node
|
||||
|
||||
Außerhalb des Repos eingerichtet und nicht Teil des Workflows:
|
||||
|
||||
- `/etc/shinkan/prod.env`, lesbar für `llmadmin` (Runner-User), Pflicht: `DB_PASSWORD`. `SHINKAN_MEDIA_HOST` und `MEDIA_ROOT` sind optional; wenn gesetzt, müssen sie `/srv/shinkan/prod/media` bzw. `/app/media` sein. `COMPOSE_PROFILES` darf dort nicht stehen.
|
||||
- NFS-Mount `/srv/shinkan/prod/media`, dauerhaft und beim Boot abgesichert. Erreichbarkeit und Monitoring des NAS liegen beim Server, nicht im Deployment.
|
||||
- `/home/llmadmin/docker/shinkan-prod`; das Git-Checkout legt der Workflow beim ersten Lauf selbst an.
|
||||
|
||||
## docker-compose.llm-node.yml
|
||||
|
||||
Override nur für llm-node; Pi und Dev nutzen ihn nicht. Alle Compose-Aufrufe im Workflow (build, up, rm, ps, logs) laufen als
|
||||
|
||||
```bash
|
||||
docker compose -p shinkan-prod -f docker-compose.yml -f docker-compose.llm-node.yml --env-file /etc/shinkan/prod.env ...
|
||||
```
|
||||
|
||||
- Ersetzt den Medien-Mount von `backend` und `retention-cron` durch einen Bind-Mount `/srv/shinkan/prod/media` → `/app/media` mit `create_host_path: false`. Ist der Mount nicht da, startet der Container nicht, statt Medien auf die lokale Platte zu schreiben.
|
||||
- Hängt `retention-cron` an das Profil `media-retention`. Ohne Profil wird der Dienst weder gebaut noch gestartet.
|
||||
|
||||
## Ablauf je Lauf (llm-node)
|
||||
|
||||
1. Runner-Guard (`llm-node`/`x86_64`)
|
||||
2. `ENV_FILE` prüfen: lesbar, `DB_PASSWORD` gesetzt, kein `COMPOSE_PROFILES`, Medienwerte passend. Es werden keine Werte ausgegeben.
|
||||
3. `git fetch origin main` + `git reset --hard origin/main` im Deploy-Verzeichnis
|
||||
4. `build --no-cache` und `up -d --remove-orphans`. Bei `MEDIA_RETENTION: disabled` wird ein noch vorhandener `retention-cron` entfernt.
|
||||
5. Healthchecks mit Wiederholung (bis ca. 3 min je Prüfung):
|
||||
- `127.0.0.1:8003/api/version`
|
||||
- `127.0.0.1:8003/api/health/ready` mit `status=ready`, `database=true`, `schema_complete=true` (HTTP 200 allein reicht nicht)
|
||||
- `127.0.0.1:3003/api/version` und `127.0.0.1:3003/api/health/ready` (gleiche Bedingung, über Frontend-Nginx)
|
||||
- `127.0.0.1:3003/`
|
||||
|
||||
Bei Fehler: `compose ps` und Backend-Logs, Lauf rot.
|
||||
|
||||
## Medienbereinigung
|
||||
|
||||
Pi und llm-node nutzen denselben Medienbestand, aber getrennte Datenbanken. Eine Bereinigung auf einer Seite kann Dateien löschen, die die andere Datenbank noch referenziert. Deshalb darf immer nur eine Seite bereinigen.
|
||||
|
||||
Seit 0.8.247 bereinigt llm-node (`MEDIA_RETENTION: enabled`): Der Lauf baut und startet `retention-cron` mit Profil `media-retention`. Voraussetzung: Der Pi-`retention-cron` ist gestoppt.
|
||||
|
||||
Abschalten: `MEDIA_RETENTION: disabled` setzen und über `develop` → `main` ausrollen; der Lauf entfernt den Container.
|
||||
|
||||
Die Bereinigungslogik (`backend/scripts/media_retention_scheduler.py`, täglich 03:00 Europe/Berlin, kein Löschen beim Start) ist auf beiden Seiten dieselbe.
|
||||
|
||||
## Pi-Deployment (abgeschaltet)
|
||||
|
||||
Seit 0.8.247 hat `deploy-prod.yml` nur noch `on: workflow_dispatch`; ein Push oder Merge auf `main` startet es nicht. Der Pi-Runner bleibt aktiv, er bedient `Deploy Development` und `Test Suite`.
|
||||
|
||||
Nach dem Cutover auf dem Pi stoppen (manuell, nicht Teil eines Workflows):
|
||||
|
||||
```bash
|
||||
cd /home/lars/docker/shinkan && docker compose down
|
||||
```
|
||||
|
||||
Das DB-Volume `shinkan_shinkan-db-data` bleibt dabei erhalten.
|
||||
|
||||
`test.yml` läuft nur für `develop` gegen Dev und hängt an keinem Prod-Workflow. Prod prüfen allein die Healthchecks des Deploy-Workflows. (Bis 0.8.246 startete `test.yml` nach `Deploy Production` per `workflow_run`. Die Weiche über `workflow_run.name` griff in Gitea nicht, und repariert hätten die Integrationstests in die Prod-DB geschrieben.)
|
||||
|
||||
### Rückfall auf den Pi
|
||||
|
||||
1. In `deploy-prod-llm-node.yml` `MEDIA_RETENTION: disabled` setzen und ausrollen; nie beide Bereinigungen gleichzeitig.
|
||||
2. Pi-DB auf den aktuellen Stand bringen: Sie ist seit dem Cutover veraltet.
|
||||
3. Gitea → Actions → `Deploy Production` → „Run workflow“ (Branch `main`).
|
||||
4. Reverse-Proxy zurück auf den Pi.
|
||||
@@ -1,200 +0,0 @@
|
||||
# Shinkan Backup & Recovery – Schnittstelle zum Backup-Orchestrator
|
||||
|
||||
Stand: 2026-10-29 · Status: **Entwurf zur Abstimmung, nichts umgesetzt**
|
||||
|
||||
Dieses Dokument legt fest, wie der Backup-Orchestrator (`pi-backup-orchestrator`, eigenes Projekt) und Shinkan bei Backup, Wiederherstellung und Restore-Test zusammenarbeiten. Es richtet sich an den Orchestrator-Agenten und an die Umsetzung der Shinkan-Skripte.
|
||||
|
||||
Grundsatz: **Der Orchestrator weiß, wann und wohin gesichert wird. Shinkan weiß, wie die eigene Datenbank sicher eingespielt und geprüft wird.** Der Orchestrator ruft Shinkan-Skripte auf und wertet Exit-Code und JSON aus. Shinkan-Interna (Migrationen, Sessions, Medienpfade, Healthchecks) stehen nicht im Orchestrator.
|
||||
|
||||
Verwandt: `PROD_DEPLOYMENTS.md` (Deployments Pi + llm-node), `MEDIA_ASSETS_AND_ARCHIVE_SPEC.md` (Medien-Lifecycle).
|
||||
|
||||
---
|
||||
|
||||
## 1. Ist-Stand (geprüft am 2026-10-29, nur lesend)
|
||||
|
||||
| Punkt | Stand |
|
||||
|---|---|
|
||||
| Orchestrator | `pi-backup-orchestrator` v0.3 auf dem Pi, Timer `backup-orchestrator-daily` täglich 05:30, Job `shinkan-prod-db` (Phase 10, kritisch), danach `nas-data` (Phase 20) |
|
||||
| Dump | `pg_dump` im Container `shinkan-db-prod`, **Plain SQL**, PostgreSQL 16.12, ca. 1,2 MB, 94 Tabellen |
|
||||
| Ablage | `/media/lars/paperless/db-backup/shinkan-prod.sql` auf der **lokalen NVMe** des Pi, fester Dateiname (bis 2026-10-28 mit Zeitstempel); auf das NAS über `nas-data` |
|
||||
| Migrationen | Tabelle `schema_migrations(id, migration, executed_at)`; `migration` = Dateiname ohne `.sql`, z. B. `096_login_lockout_and_totp`. Maßgeblich ist `backend/run_migrations.py` (läuft beim Backend-Start). Die Variante in `db_init.py` (Spalte `filename`) wird beim Start nicht genutzt. |
|
||||
| Medien | Gemeinsamer Bestand auf dem NAS (`192.168.2.63:/volume1/shinkan-media/prod`), im Container `/app/media`. `media_assets.storage_key` relativ (`library/…`) mit `sha256` und `byte_size`; ältere `exercise_media.file_path` als `/media/<storage_key>` |
|
||||
| Ziel-Prod | llm-node, Compose-Projekt `shinkan-prod`, `docker-compose.yml` + `docker-compose.llm-node.yml`, Konfiguration `/etc/shinkan/prod.env`, Container `shinkan-db-prod` (Postgres nur `127.0.0.1:5434`) |
|
||||
|
||||
## 2. Begriffe
|
||||
|
||||
- **Backup-Satz:** Dump + Prüfsumme + Backup-Manifest + Medien-Manifest, alle mit demselben Zeitstempel. Nur ein vollständiger Satz gilt als Backup.
|
||||
- **Ziel (target):** benannte, fest im Skript hinterlegte Umgebung. Kein freies Zusammenbauen von Pfaden über Parameter.
|
||||
|
||||
| target | Host | Zweck | Schreibt in DB |
|
||||
|---|---|---|---|
|
||||
| `pi-prod` | raspberrypi5 | Manifest zum bestehenden Pi-Dump | nein (nur lesend) |
|
||||
| `llm-prod` | llm-node | Manifest, Recovery, Erstbefüllung | ja, nur `restore` |
|
||||
| `llm-restoretest` | llm-node | Restore-Test, wird danach entfernt | ja, nur eigene Wegwerf-DB |
|
||||
|
||||
Jedes Skript prüft wie die Workflows Hostname und Architektur und bricht auf einem fremden Host ab. Restore auf `pi-prod` gibt es nicht.
|
||||
|
||||
## 3. Schnittstelle
|
||||
|
||||
Alle Skripte liegen im Shinkan-Repo unter `scripts/ops/` und laufen auf dem Host der Zielumgebung, aus dem jeweiligen Deploy-Checkout. Die Code-Version, gegen die geprüft wird, ist damit immer die dort deployte.
|
||||
|
||||
Gemeinsam für alle Befehle:
|
||||
|
||||
- Ergebnis als JSON in die Datei `--result <pfad>` (Orchestrator legt den Pfad fest, z. B. im Run-Log-Verzeichnis). Auf stdout nur menschenlesbares Log.
|
||||
- Keine Secrets, keine Dump-Inhalte, keine personenbezogenen Daten in Log oder JSON. Tabellennamen, Zeilenzahlen, Dateipfade im Medienbestand und Versionsangaben sind erlaubt.
|
||||
- Exit-Codes:
|
||||
|
||||
| Code | Bedeutung |
|
||||
|---|---|
|
||||
| 0 | erfolgreich |
|
||||
| 1 | Fehler während der Ausführung (Details im JSON) |
|
||||
| 2 | Aufruf oder Vorbedingung falsch (falscher Host, fehlende Datei, fehlende Bestätigung) |
|
||||
| 3 | Dump passt nicht zum Code (enthält Migrationen, die der Code nicht kennt) |
|
||||
| 4 | Prüfsumme stimmt nicht |
|
||||
| 5 | Wiederherstellung durchgeführt, Prüfung danach fehlgeschlagen (Rollback ausgeführt bzw. im JSON beschrieben) |
|
||||
|
||||
### 3.1 `shinkan-backup-manifest`
|
||||
|
||||
Aufruf direkt nach dem Dump, im selben Orchestrator-Job.
|
||||
|
||||
```
|
||||
shinkan-backup-manifest --target pi-prod|llm-prod --dump <datei> --out-dir <verzeichnis> --result <json>
|
||||
```
|
||||
|
||||
Schreibt neben den Dump:
|
||||
|
||||
- `<dump>.sha256`
|
||||
- `<dump>.manifest.json`:
|
||||
- `created_at`, `host`, `target`
|
||||
- `app_version` (aus `/api/version`), `git_commit` (Deploy-Checkout)
|
||||
- `migrations`: Liste aus `schema_migrations.migration`, `last_migration`
|
||||
- `dump_format` (`plain` | `custom`), `dump_bytes`, `dump_sha256`
|
||||
- `row_counts` je Tabelle, nur informativ (eigener Lesezugriff, nicht derselbe Snapshot wie der Dump)
|
||||
- `media_manifest` (Dateiname + sha256)
|
||||
- `<dump>.media.jsonl`, eine Zeile je Datei im Medienbestand: `path` (relativ zu `/app/media`), `size`, `mtime`. `sha256` nur für neue oder geänderte Dateien (Cache über `path`+`size`+`mtime`), damit der Lauf bei wachsendem Bestand kurz bleibt.
|
||||
|
||||
Der Manifest-Job liest nur; ein Fehler darin macht den Backup-Satz unvollständig, aber nicht den Dump ungültig. Empfehlung: Job unkritisch, Kuma-Meldung eigener Monitor.
|
||||
|
||||
### 3.2 `shinkan-restore`
|
||||
|
||||
```
|
||||
shinkan-restore --target llm-prod|llm-restoretest --dump <datei> --result <json>
|
||||
[--confirm <db>@<host>] [--allow-overwrite] [--sessions clear|keep]
|
||||
```
|
||||
|
||||
- `--confirm shinkan@llm-node` ist bei `llm-prod` Pflicht.
|
||||
- `--allow-overwrite` ist Pflicht, wenn die Ziel-DB echte Daten hat (mindestens ein Eintrag in `profiles`). Eine frisch migrierte DB ohne Profile gilt als leer.
|
||||
- `--sessions`: Default `clear`. `keep` nur bei Recovery desselben Systems nach einem Crash, wenn angemeldete Nutzer angemeldet bleiben sollen.
|
||||
|
||||
Ablauf (verbindlich):
|
||||
|
||||
1. **Vorbedingungen:** Host-Guard, Dump lesbar, `<dump>.sha256` vorhanden und passend (sonst Exit 4), Zielkonfiguration vorhanden.
|
||||
2. **In eine Staging-DB einspielen,** nicht direkt in die Live-DB: `shinkan_restore_<zeitstempel>` im laufenden Postgres-Container anlegen und den Dump in **einer Transaktion** einspielen, bei Fehler Abbruch ohne Teilstand.
|
||||
- Plain SQL: `psql -v ON_ERROR_STOP=1 --single-transaction`
|
||||
- Custom-Format (`PGDMP`-Kopf): `pg_restore --single-transaction --exit-on-error --no-owner --no-acl`
|
||||
3. **Migrationsabgleich in der Staging-DB:** Jeder Eintrag in `schema_migrations.migration` muss als `backend/migrations/<eintrag>.sql` im deployten Code existieren. Sonst ist der Dump neuer als der Code → Staging-DB löschen, Exit 3. Fehlende Einträge (Dump älter als Code) sind normal; sie werden beim Backend-Start nachgezogen.
|
||||
4. **Plausibilität in der Staging-DB:** Pflichttabellen wie im Ready-Check vorhanden; `profiles`, `skills` nicht leer. Abweichung der Zeilenzahlen zum Manifest nur als Hinweis im JSON.
|
||||
5. **Sessions:** bei `clear` `TRUNCATE sessions` in der Staging-DB.
|
||||
6. **Umschalten:**
|
||||
- Backend, Frontend und `retention-cron` stoppen (Compose `stop`, Postgres läuft weiter).
|
||||
- Live-DB umbenennen: `shinkan` → `shinkan_before_<zeitstempel>`.
|
||||
- Staging-DB umbenennen: `shinkan_restore_<zeitstempel>` → `shinkan`.
|
||||
- Backend und Frontend starten; `retention-cron` nur, wenn es im Deployment aktiviert ist (llm-node: `MEDIA_RETENTION`).
|
||||
7. **Prüfen:** dieselben Healthchecks wie im Deploy-Workflow, insbesondere `/api/health/ready` mit `status=ready`, `database=true`, `schema_complete=true`.
|
||||
8. **Bei Fehler in 6–7:** Dienste stoppen, Umbenennung rückgängig machen (`shinkan_before_<zeitstempel>` → `shinkan`), Dienste starten, erneut prüfen. Exit 5 mit beiden Ergebnissen im JSON.
|
||||
9. **Aufräumen:** `shinkan_before_<zeitstempel>` bleibt stehen, bis jemand sie ausdrücklich löscht (eigener Befehl `--drop-previous <name>` oder manuell). Kein automatisches Löschen.
|
||||
|
||||
Ergebnis-JSON u. a.: `dump_sha256`, `dump_last_migration`, `code_last_migration`, `migrations_applied_on_start`, `sessions`, `previous_db`, `health`, `duration_seconds`.
|
||||
|
||||
### 3.3 `shinkan-restore-test`
|
||||
|
||||
```
|
||||
shinkan-restore-test --dump <datei> --result <json> [--playwright] [--keep]
|
||||
```
|
||||
|
||||
Baut eine Wegwerf-Umgebung auf llm-node, spielt den Dump mit `shinkan-restore --target llm-restoretest` ein, prüft und räumt auf.
|
||||
|
||||
- **Eigenes Compose-Projekt** `shinkan-restoretest` mit **eigener Compose-Datei ohne `container_name`**. Die Basisdatei setzt feste Namen (`shinkan-db-prod` …) und kollidiert sonst mit Prod auf demselben Host.
|
||||
- **Ports:** Frontend und Backend nur auf `127.0.0.1`, Postgres ohne veröffentlichten Port. Konkrete Ports vor Umsetzung auf llm-node prüfen.
|
||||
- **Medien nur lesend:** `/srv/shinkan/prod/media:/app/media:ro`. Der Medienbestand ist gemeinsam; ein Test darf dort nichts schreiben oder löschen.
|
||||
- **Aus:** `retention-cron`, SMTP (Variablen leer), `AUTO_ADMIN_FIRST_USER`, `ADMIN_BOOTSTRAP_EMAILS`, OpenRouter.
|
||||
- **Prüfungen:** Ready-Check, Plausibilität wie 3.2, Medien-Abgleich (3.4) gegen den aktuellen Bestand.
|
||||
- **`--playwright`:** lesende Smoke-Tests gegen `PLAYWRIGHT_BASE_URL` der Testumgebung. Tests, die hochladen oder Medien ändern, müssen ausgeschlossen werden (schreibgeschützter Mount). Testzugang über einen eigens im Test angelegten Nutzer, nicht über echte Nutzerkonten.
|
||||
- **Ende:** `docker compose -p shinkan-restoretest down -v`, außer bei `--keep` (zur Fehlersuche).
|
||||
|
||||
Empfohlener Takt: wöchentlich mit dem jüngsten Backup-Satz, zusätzlich nach Änderungen an Dump-Format oder Migrationsrunner.
|
||||
|
||||
### 3.4 `shinkan-media-diff`
|
||||
|
||||
```
|
||||
shinkan-media-diff --target llm-prod|llm-restoretest --result <json> [--manifest <dump>.media.jsonl]
|
||||
```
|
||||
|
||||
Vergleicht die Medienverweise der (wiederhergestellten) DB mit dem aktuellen Medienbestand. Löscht und ändert nichts.
|
||||
|
||||
Kategorien im Ergebnis:
|
||||
|
||||
| Kategorie | Bedeutung | Folge |
|
||||
|---|---|---|
|
||||
| `missing` | in `media_assets` / `exercise_media` referenziert, Datei fehlt | reparieren oder Eintrag bereinigen |
|
||||
| `mismatch` | Datei vorhanden, `byte_size` oder `sha256` passt nicht | prüfen |
|
||||
| `added_after_backup` | Datei vorhanden, nicht referenziert, nicht im Medien-Manifest des Backups | Upload nach dem Backup; DB-Eintrag ging mit dem Restore verloren → Kandidat für Nachpflege |
|
||||
| `orphan` | Datei vorhanden, nicht referenziert, bereits im Manifest | Kandidat zum Aufräumen |
|
||||
|
||||
Solange Pi und llm-node denselben Bestand mit getrennten Datenbanken nutzen, gehören `orphan` und `added_after_backup` teilweise zur anderen Installation. **Keine automatische Bereinigung** auf Basis dieses Berichts.
|
||||
|
||||
Der Bericht enthält immer das Versions-Tripel: App-Version und Commit des Ziels, letzte Migration der DB, Medien-Manifest des Backups.
|
||||
|
||||
## 4. Zuständigkeiten
|
||||
|
||||
| Aufgabe | Orchestrator | Shinkan |
|
||||
|---|---|---|
|
||||
| Zeitplan (täglich, später 2-stündlich) | ✓ | |
|
||||
| Dump erzeugen (`pg_dump` im Container) | ✓ | |
|
||||
| Manifest erzeugen | ruft auf | `shinkan-backup-manifest` |
|
||||
| Ablage, Generationen, Kopie auf NAS | ✓ | |
|
||||
| Meldungen (Kuma, Webhooks) | ✓ | liefert Exit-Code + JSON |
|
||||
| Restore-Test planen | ✓ | `shinkan-restore-test` |
|
||||
| Recovery auslösen | manuell über Orchestrator-CLI | `shinkan-restore` |
|
||||
| Medienabgleich | ruft nach Restore auf | `shinkan-media-diff` |
|
||||
| Installation auf llm-node | ✓ | |
|
||||
|
||||
## 5. Anforderungen an den Orchestrator
|
||||
|
||||
1. **Generationen auf dem NAS.** Mit festem Dateinamen gibt es lokal nur einen Stand. Auf dem NAS müssen mehrere Backup-Sätze erhalten bleiben. Vorschlag: 2-stündliche Sätze 2 Tage, tägliche 30 Tage, monatliche 12 Monate. Ein Satz wird erst überschrieben bzw. rotiert, wenn der neue vollständig ist (Dump + `.sha256` + Manifest).
|
||||
2. **Atomar schreiben:** Dump erst in eine temporäre Datei, nach Erfolg umbenennen. Ein abgebrochener Dump darf den letzten guten nicht ersetzen.
|
||||
3. **Dump-Format:** Plain SQL funktioniert. Empfohlen für die Zukunft: `pg_dump -Fc` (kleiner, Inhaltsverzeichnis mit `pg_restore --list`, gezielte Teil-Restores). `shinkan-restore` erkennt beide Formate.
|
||||
4. **llm-node:** Eigene Orchestrator-Instanz auf llm-node für `shinkan-prod` (`docker exec shinkan-db-prod pg_dump …`). Postgres ist dort nur lokal erreichbar; Fern-Dumps vom Pi sind nicht vorgesehen.
|
||||
5. **Bis zum Cutover** laufen beide Sicherungen: Pi für das alte Prod, llm-node für das neue. Ablage getrennt (`shinkan-prod-pi/`, `shinkan-prod-llm/`), damit Sätze nicht verwechselt werden.
|
||||
6. **Takt für externe Kunden:** Vollständige Dumps alle 2 Stunden sind bei der aktuellen Größe unproblematisch und jeder Satz ist eigenständig einspielbar. Ein „Diff zum ersten Dump des Tages“ ist mit `pg_dump` nicht möglich; ein Textvergleich von SQL-Dumps ist kein verlässliches Backup. Für Datenverlust im Minutenbereich ist der Weg WAL-Archivierung mit Basis-Backup (z. B. pgBackRest oder WAL-G, Point-in-Time-Recovery). Das ändert die Postgres-Konfiguration und ist ein eigenes Vorhaben.
|
||||
|
||||
## 6. Erstbefüllung llm-node (einmalig)
|
||||
|
||||
Nutzt bewusst denselben Weg wie die Recovery; die Erstbefüllung ist damit der erste echte Recovery-Test.
|
||||
|
||||
1. Deploy-Workflow `Deploy Production llm-node` ist mindestens einmal erfolgreich gelaufen (DB frisch migriert, keine Profile).
|
||||
2. Jüngsten Pi-Backup-Satz (`shinkan-prod.sql` + `.sha256` + Manifest) nach llm-node kopieren, Ablage `/var/lib/shinkan/restore/` (Verzeichnis 700, Dateien 600, Eigentümer `llmadmin`).
|
||||
3. Optional vorher `shinkan-restore-test` mit diesem Satz.
|
||||
4. `shinkan-restore --target llm-prod --dump … --confirm shinkan@llm-node --sessions clear` (ohne `--allow-overwrite`, da die DB als leer gilt).
|
||||
5. `shinkan-media-diff --target llm-prod` und Bericht ansehen.
|
||||
6. Fachliche Stichprobe (Login, Übungen, Medien).
|
||||
|
||||
Vor Schritt 4 klären: SMTP in `/etc/shinkan/prod.env` für die Testphase aus oder bewusst an (echte Nutzerdaten → echte Mails möglich).
|
||||
|
||||
Für den Cutover wird Schritt 2–6 mit Schreibstopp auf dem Pi wiederholt (Pi-Backend stoppen, Dump, Restore mit `--allow-overwrite`).
|
||||
|
||||
## 7. Sicherheit und Datenschutz
|
||||
|
||||
- Dumps enthalten E-Mail-Adressen, Passwort-Hashes und TOTP-Geheimnisse. Ablage nur mit Rechten 600/640, Transport nur im LAN per SSH, nie ins Repo, nie in Webhooks, Logs oder Kuma-Nachrichten.
|
||||
- Skripte geben keine Umgebungsvariablen aus und lesen Zugangsdaten nur aus der Zielkonfiguration bzw. dem Container.
|
||||
- Auf dem Pi-Prod nur lesende Zugriffe (Manifest). Kein Restore auf dem Pi.
|
||||
- Restore-Test nie mit beschreibbarem Medien-Mount, nie mit aktivem SMTP.
|
||||
|
||||
## 8. Offene Entscheidungen
|
||||
|
||||
1. Dump-Format künftig `-Fc` oder weiter Plain SQL?
|
||||
2. Aufbewahrung der Generationen (Vorschlag in 5.1) und ob das NAS zusätzlich Snapshots führt.
|
||||
3. Ports und Takt des Restore-Tests; welche Playwright-Tests als lesender Smoke-Satz gelten.
|
||||
4. Default `--sessions` bei Crash-Recovery (`clear` sicherer, `keep` bequemer).
|
||||
5. Zeitpunkt für WAL-Archivierung/PITR (spätestens mit dem ersten externen Kunden mit Zusage zur Verfügbarkeit).
|
||||
6. Wiederherstellung einzelner Vereine bei mehreren Kunden: mit beiden Verfahren nicht direkt möglich; bei Bedarf eigenes Export/Import-Konzept je Mandant.
|
||||
@@ -29,8 +29,6 @@ Fortlaufend gemäß `ACCESS_LAYER_AND_GOVERNANCE_PLAN.md` Stufe A–C.
|
||||
| media_assets | `PATCH /api/media-assets/{id}` | ja | `get_tenant_context` | ja | Copyright, `original_filename`, optional `visibility`/`club_id`; Rechte pro Stufe |
|
||||
| media_assets | `GET /api/media-assets/{id}/file` | ja | `get_tenant_context_flexible` | ja | aktiv: Bibliotheks-Sichtbarkeit; `trash_soft`/`trash_hidden`: wie Lifecycle-Verwaltung |
|
||||
| exercises | `POST /api/exercises/{id}/media/from-asset` | ja | `get_tenant_context` | ja | Verknüpfung `exercise_media` → bestehendes `media_asset_id`; Bearbeitungsrecht Übung + Leserecht Archiv |
|
||||
| distribution | `GET /api/distribution/v1/*` | Kanal aus Schlüssel | kein Trainer-Tenant | ja, Empfänger der Anbindung | ACCESS_LAYER exempt: Bearer-Distributions-Schlüssel, nicht `X-Auth-Token`. `GET …/exercises/{source_id}/availability` meldet Quelle und Paketstand dieses Kanals |
|
||||
| distribution | `POST /api/exercises/{id}/distribution/*`, `/api/distribution/access/*`, `GET /api/distribution/release-updates`, `PATCH /api/exercises/api-offering` | ja | `get_tenant_context` | ja | API-Bereitstellung nutzt die Bearbeitungsrechte: global nur `superadmin`, sonst Ersteller, Plattform-Admin oder Planungsrecht im Verein. Katalogabruf `/api/distribution/v1/catalog` ist maschinell und vom Mandantenkontext ausgenommen |
|
||||
| auth | `/api/auth/*` | nein | — | Login/Session | EXEMPT |
|
||||
| catalogs | Katalog-CRUD | nein (global) | `require_auth` | Admin/Trainer je Endpoint | EXEMPT; bei späterem `club_id` nachziehen |
|
||||
| skills | `/api/skills*` | nein (global) | `require_auth` | je Endpoint | EXEMPT |
|
||||
@@ -40,7 +38,6 @@ Fortlaufend gemäß `ACCESS_LAYER_AND_GOVERNANCE_PLAN.md` Stufe A–C.
|
||||
| import_wiki / import_wiki_admin | Wiki-Import | Werkzeug | `require_auth`/Admin | Admin | EXEMPT |
|
||||
| ai_skill_retrieval_admin | `/api/admin/ai-skill-retrieval-profiles*` (CRUD) | Plattform | `require_auth` | nur `superadmin`; JSON `config` | EXEMPT wie `admin_users`; kein Vereinsbezug |
|
||||
| ai_prompts_admin | `/api/admin/ai-prompts*` (Liste, Detail, PUT, Preview, Reset) | Plattform | `require_auth` | nur `superadmin` | EXEMPT; globale `ai_prompts` ohne Mandantenkontext |
|
||||
| openrouter_admin | `GET/PUT /api/admin/openrouter/settings`, `GET /api/admin/openrouter/models`, `GET/PUT /api/admin/openrouter/roles`, `PUT /api/admin/openrouter/prompts/{id}/role` | Plattform | `require_auth` | nur `superadmin` | EXEMPT; Plattform-Standard, Aufgabengruppen und OpenRouter-Katalog, kein Vereinsbezug, kein API-Key in der Antwort |
|
||||
| exercise_enrichment_admin | `/api/admin/exercise-enrichment/*` (Kandidaten, Preview, Apply) | Plattform | `require_auth` | nur `superadmin` | EXEMPT; plattformweite Übungsliste + Skill-Schreibung; kein TenantContext |
|
||||
| admin_user_content | `/api/admin/user-content/*` (Meta, Nutzer-Summary, Items, PATCH, DELETE) | Plattform | `require_auth` | nur `superadmin` | EXEMPT; Moderation nutzerangelegter Inhalte inkl. privat; kein TenantContext |
|
||||
|
||||
@@ -48,7 +45,7 @@ Fortlaufend gemäß `ACCESS_LAYER_AND_GOVERNANCE_PLAN.md` Stufe A–C.
|
||||
|
||||
**Pflege / Drift:** Änderungen an Mandanten, Governance (`visibility`/`club_id`) oder neuen inhaltsbezogenen Endpoints → eine Zeile in dieser Tabelle anpassen und `PRODUCTION_READINESS_AUDIT_2026-05.md` prüfen.
|
||||
|
||||
Letzte Änderung: 2026-11-23 — Superadmin `/api/admin/openrouter/settings` und `/api/admin/openrouter/models`.
|
||||
Letzte Änderung: 2026-06-06 — Superadmin `/api/admin/user-content/*` (Nutzer-Inhalte Moderation).
|
||||
|
||||
---
|
||||
|
||||
|
||||
+2
-3
@@ -38,9 +38,8 @@ OPENROUTER_MODEL=anthropic/claude-sonnet-4
|
||||
# Vereins-Kontingente hart blockieren (KI-Kosten!). Nur 1, true oder yes aktivieren.
|
||||
# Nach Änderung: docker compose -f docker-compose.dev-env.yml up -d backend
|
||||
CLUB_FEATURE_ENFORCE=1
|
||||
# Fallback-OpenRouter-Modell, wenn kein Plattform-Standard gespeichert ist.
|
||||
# Superadmin: Administration → KI-Modell (platform_ai_settings, Migration 097).
|
||||
# Optional pro Prompt in ai_prompts.openrouter_model (Migration 070, „KI Prompts“).
|
||||
# Standard-OpenRouter-Modell (alle Aufrufe). Optional pro Prompt in ai_prompts.openrouter_model
|
||||
# ueberschreibbar (Migration 070, Superadmin unter „KI Prompts“).
|
||||
|
||||
# Übungs-KI (Docker): ohne Eintrag im compose „environment:“ landet keine .env-Zeile im Container.
|
||||
# Hier ist SHINKAN_AI_DEBUG in docker-compose*.yml angebunden — 1 = ausführliche WARN-Logs (exercise_ai, openrouter).
|
||||
|
||||
@@ -1,165 +0,0 @@
|
||||
name: Deploy Production llm-node
|
||||
|
||||
# Prod-Deployment auf llm-node (192.168.2.144, AMD64), seit dem Cutover 2026-10-29 die einzige Prod.
|
||||
# "Deploy Production" (Raspberry Pi) ist nur noch manuell startbar.
|
||||
# Runner: llm-node-runner mit einzigem Label linux_host (Host-Modus).
|
||||
# Der Pi-Runner (Raspi5-Paperless) hat nur ubuntu-latest und nimmt diesen Job nie an.
|
||||
# Compose: docker-compose.yml + docker-compose.llm-node.yml, Konfiguration aus ENV_FILE.
|
||||
# Doku: .claude/docs/technical/PROD_DEPLOYMENTS.md
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
workflow_dispatch:
|
||||
|
||||
jobs:
|
||||
deploy:
|
||||
runs-on: linux_host
|
||||
env:
|
||||
APP_DIR: /home/llmadmin/docker/shinkan-prod
|
||||
ENV_FILE: /etc/shinkan/prod.env
|
||||
COMPOSE_PROJECT: shinkan-prod
|
||||
REPO_URL: http://192.168.2.144:3000/Lars/shinkan-jinkendo.git
|
||||
MEDIA_HOST: /srv/shinkan/prod/media
|
||||
# Medienbereinigung (retention-cron): disabled | enabled.
|
||||
# Seit dem Cutover führt nur llm-node den Medienbestand. Der Pi-retention-cron muss gestoppt sein:
|
||||
# beide Seiten teilen den Bestand bei getrennten Datenbanken.
|
||||
MEDIA_RETENTION: enabled
|
||||
steps:
|
||||
- name: Runner prüfen (nur llm-node)
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
if [ "$(hostname)" != "llm-node" ] || [ "$(uname -m)" != "x86_64" ]; then
|
||||
echo "✗ Falscher Runner: $(hostname)/$(uname -m), erwartet llm-node/x86_64. Abbruch."
|
||||
exit 1
|
||||
fi
|
||||
echo "✓ Runner $(hostname)/$(uname -m)"
|
||||
|
||||
- name: Konfiguration prüfen
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
if [ ! -r "$ENV_FILE" ]; then
|
||||
echo "✗ $ENV_FILE fehlt oder ist nicht lesbar."
|
||||
exit 1
|
||||
fi
|
||||
env_value() {
|
||||
grep -E "^$1=" "$ENV_FILE" | tail -1 | cut -d= -f2- | tr -d "\"'" || true
|
||||
}
|
||||
if [ -z "$(env_value DB_PASSWORD)" ]; then
|
||||
echo "✗ DB_PASSWORD ist in $ENV_FILE nicht gesetzt."
|
||||
exit 1
|
||||
fi
|
||||
# Profile steuert allein MEDIA_RETENTION in diesem Workflow.
|
||||
if grep -Eq "^COMPOSE_PROFILES=" "$ENV_FILE"; then
|
||||
echo "✗ COMPOSE_PROFILES in $ENV_FILE entfernen; die Bereinigung schaltet MEDIA_RETENTION im Workflow."
|
||||
exit 1
|
||||
fi
|
||||
# Override mountet fest $MEDIA_HOST -> /app/media; abweichende Werte ergäben einen zweiten Mount.
|
||||
media_host="$(env_value SHINKAN_MEDIA_HOST)"
|
||||
media_root="$(env_value MEDIA_ROOT)"
|
||||
if [ -n "$media_host" ] && [ "$media_host" != "$MEDIA_HOST" ]; then
|
||||
echo "✗ SHINKAN_MEDIA_HOST=$media_host, erwartet $MEDIA_HOST."
|
||||
exit 1
|
||||
fi
|
||||
if [ -n "$media_root" ] && [ "$media_root" != "/app/media" ]; then
|
||||
echo "✗ MEDIA_ROOT=$media_root, erwartet /app/media."
|
||||
exit 1
|
||||
fi
|
||||
case "$MEDIA_RETENTION" in
|
||||
disabled|enabled) ;;
|
||||
*) echo "✗ MEDIA_RETENTION=$MEDIA_RETENTION, erlaubt: disabled | enabled."; exit 1 ;;
|
||||
esac
|
||||
echo "✓ $ENV_FILE geprüft, Medien $MEDIA_HOST -> /app/media, Bereinigung $MEDIA_RETENTION"
|
||||
|
||||
- name: Code aktualisieren
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
cd "$APP_DIR"
|
||||
if [ ! -d .git ]; then
|
||||
git init -q
|
||||
git remote add origin "$REPO_URL"
|
||||
fi
|
||||
git fetch origin main
|
||||
git reset --hard origin/main
|
||||
git log -1 --oneline
|
||||
|
||||
- name: Build und Start
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
echo "=== Deploying Shinkan to PRODUCTION (llm-node) ==="
|
||||
cd "$APP_DIR"
|
||||
dc() {
|
||||
docker compose -p "$COMPOSE_PROJECT" -f docker-compose.yml -f docker-compose.llm-node.yml \
|
||||
--env-file "$ENV_FILE" "$@"
|
||||
}
|
||||
if [ "$MEDIA_RETENTION" = enabled ]; then
|
||||
dc --profile media-retention build --no-cache
|
||||
dc --profile media-retention up -d --remove-orphans
|
||||
else
|
||||
dc build --no-cache
|
||||
dc up -d --remove-orphans
|
||||
# Ein früher gestarteter retention-cron läuft sonst weiter.
|
||||
dc --profile media-retention rm -s -f retention-cron
|
||||
fi
|
||||
|
||||
- name: Healthchecks
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
cd "$APP_DIR"
|
||||
dc() {
|
||||
docker compose -p "$COMPOSE_PROJECT" -f docker-compose.yml -f docker-compose.llm-node.yml \
|
||||
--env-file "$ENV_FILE" "$@"
|
||||
}
|
||||
wait_for() {
|
||||
local url="$1" label="$2" i
|
||||
for i in $(seq 1 60); do
|
||||
if curl -sf -o /dev/null "$url"; then
|
||||
echo "✓ $label healthy ($url)"
|
||||
return 0
|
||||
fi
|
||||
sleep 3
|
||||
done
|
||||
echo "✗ $label nicht erreichbar ($url)"
|
||||
return 1
|
||||
}
|
||||
# HTTP 200 reicht nicht: status=ready, database=true und schema_complete=true.
|
||||
wait_ready() {
|
||||
local url="$1" label="$2" i body=""
|
||||
for i in $(seq 1 60); do
|
||||
body="$(curl -sf "$url" || true)"
|
||||
if [ -n "$body" ] && printf '%s' "$body" \
|
||||
| jq -e '.status == "ready" and .database == true and .schema_complete == true' >/dev/null 2>&1; then
|
||||
echo "✓ $label ready ($url)"
|
||||
return 0
|
||||
fi
|
||||
sleep 3
|
||||
done
|
||||
echo "✗ $label nicht ready ($url):"
|
||||
printf '%s' "$body" | jq -c '{status, database, schema_complete}' 2>/dev/null || echo " keine gültige Antwort"
|
||||
return 1
|
||||
}
|
||||
ok=1
|
||||
wait_for http://127.0.0.1:8003/api/version "PROD API (direkt)" || ok=0
|
||||
if [ "$ok" = 1 ]; then
|
||||
wait_ready http://127.0.0.1:8003/api/health/ready "PROD API (direkt)" || ok=0
|
||||
fi
|
||||
if [ "$ok" = 1 ]; then
|
||||
wait_for http://127.0.0.1:3003/api/version "PROD API über Frontend-Nginx" || ok=0
|
||||
fi
|
||||
if [ "$ok" = 1 ]; then
|
||||
wait_ready http://127.0.0.1:3003/api/health/ready "PROD API über Frontend-Nginx" || ok=0
|
||||
fi
|
||||
if [ "$ok" = 1 ]; then
|
||||
wait_for http://127.0.0.1:3003/ "PROD Frontend" || ok=0
|
||||
fi
|
||||
if [ "$ok" != 1 ]; then
|
||||
dc ps || true
|
||||
dc logs backend --tail 120 || true
|
||||
exit 1
|
||||
fi
|
||||
echo "=== Shinkan PROD Deploy (llm-node) complete ==="
|
||||
@@ -1,28 +1,13 @@
|
||||
name: Deploy Production
|
||||
|
||||
# ABGESCHALTET seit dem Cutover auf llm-node (2026-10-29): kein Trigger auf main mehr.
|
||||
# Prod läuft über deploy-prod-llm-node.yml. Nur noch manuell startbar, als Rückfallweg.
|
||||
# Ein manueller Lauf startet auch den Pi-retention-cron auf dem gemeinsamen Medienbestand:
|
||||
# vorher MEDIA_RETENTION auf llm-node abschalten. Details: .claude/docs/technical/PROD_DEPLOYMENTS.md
|
||||
# Runner: Raspi5-Paperless mit einzigem Label ubuntu-latest (Host-Modus); der
|
||||
# llm-node-Runner trägt dieses Label nicht. Der Guard bricht auf jedem anderen Host ab.
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
push:
|
||||
branches: [main]
|
||||
|
||||
jobs:
|
||||
deploy:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Runner prüfen (nur Raspberry Pi)
|
||||
run: |
|
||||
set -e
|
||||
if [ "$(hostname)" != "raspberrypi5" ] || [ "$(uname -m)" != "aarch64" ]; then
|
||||
echo "✗ Falscher Runner: $(hostname)/$(uname -m), erwartet raspberrypi5/aarch64. Abbruch."
|
||||
exit 1
|
||||
fi
|
||||
echo "✓ Runner $(hostname)/$(uname -m)"
|
||||
|
||||
- name: Deploy to Production
|
||||
run: |
|
||||
set -e
|
||||
|
||||
+121
-29
@@ -1,18 +1,21 @@
|
||||
name: Test Suite
|
||||
|
||||
# Eigener Workflow, getrennt von Deploy Development.
|
||||
# push/PR auf develop: Ziel ist ausschließlich das Testsystem.
|
||||
# Kein Lauf gegen Produktion: die Integrationstests schreiben in die Datenbank.
|
||||
# Prod prüfen nur die Healthchecks der Deploy-Workflows.
|
||||
# develop: push/PR → Tests gegen Dev (parallel oder vor Deploy Development).
|
||||
# main: kein push/PR-Trigger — vermeidet doppelten Dev-Lauf beim Merge develop→main;
|
||||
# Prod-Tests nur via workflow_run nach erfolgreichem Deploy Production.
|
||||
on:
|
||||
push:
|
||||
branches: [develop]
|
||||
pull_request:
|
||||
branches: [develop]
|
||||
workflow_run:
|
||||
workflows: ["Deploy Development", "Deploy Production"]
|
||||
types: [completed]
|
||||
|
||||
jobs:
|
||||
# Pytest im laufenden backend-Container; ACCESS_LAYER + TRAINING_PLANNING Integration gegen dieselbe PostgreSQL wie Deploy (Schema via Container-Start migriert).
|
||||
pytest-backend:
|
||||
if: ${{ github.event_name != 'workflow_run' || github.event.workflow_run.conclusion == 'success' }}
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Backend pytest im deployten Container
|
||||
@@ -21,15 +24,19 @@ jobs:
|
||||
EVENT_NAME="${{ github.event_name }}"
|
||||
REF_NAME="${{ github.ref_name }}"
|
||||
BASE_REF="${{ github.base_ref }}"
|
||||
RUN_WORKFLOW="${{ github.event.workflow_run.name }}"
|
||||
APP_DIR="/home/lars/docker/shinkan"
|
||||
COMPOSE_FILE="docker-compose.yml"
|
||||
|
||||
if [ "$REF_NAME" = "develop" ] || [ "$BASE_REF" = "develop" ]; then
|
||||
if [ "$EVENT_NAME" = "workflow_run" ]; then
|
||||
if [ "$RUN_WORKFLOW" = "Deploy Development" ]; then
|
||||
APP_DIR="/home/lars/docker/shinkan-dev"
|
||||
COMPOSE_FILE="docker-compose.dev-env.yml"
|
||||
fi
|
||||
elif [ "$REF_NAME" = "develop" ] || [ "$BASE_REF" = "develop" ]; then
|
||||
APP_DIR="/home/lars/docker/shinkan-dev"
|
||||
COMPOSE_FILE="docker-compose.dev-env.yml"
|
||||
else
|
||||
echo "Kein Dev-Ziel (event=$EVENT_NAME ref=$REF_NAME base=$BASE_REF). Abbruch."
|
||||
exit 1
|
||||
fi
|
||||
echo "CI-Ziel: $APP_DIR ($COMPOSE_FILE)"
|
||||
|
||||
cd "$APP_DIR"
|
||||
echo "Warte auf stabilen backend-Container …"
|
||||
@@ -56,41 +63,45 @@ jobs:
|
||||
"
|
||||
|
||||
lint-backend:
|
||||
if: ${{ github.event_name != 'workflow_run' || github.event.workflow_run.conclusion == 'success' }}
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Check backend syntax
|
||||
run: |
|
||||
EVENT_NAME="${{ github.event_name }}"
|
||||
REF_NAME="${{ github.ref_name }}"
|
||||
BASE_REF="${{ github.base_ref }}"
|
||||
RUN_WORKFLOW="${{ github.event.workflow_run.name }}"
|
||||
APP_DIR="/home/lars/docker/shinkan"
|
||||
|
||||
if [ "$REF_NAME" = "develop" ] || [ "$BASE_REF" = "develop" ]; then
|
||||
if [ "$EVENT_NAME" = "workflow_run" ]; then
|
||||
if [ "$RUN_WORKFLOW" = "Deploy Development" ]; then
|
||||
APP_DIR="/home/lars/docker/shinkan-dev"
|
||||
fi
|
||||
elif [ "$REF_NAME" = "develop" ]; then
|
||||
APP_DIR="/home/lars/docker/shinkan-dev"
|
||||
else
|
||||
echo "Kein Dev-Ziel (event=$EVENT_NAME ref=$REF_NAME base=$BASE_REF). Abbruch."
|
||||
exit 1
|
||||
fi
|
||||
echo "CI-Ziel: $APP_DIR"
|
||||
|
||||
python3 -m py_compile "$APP_DIR/backend/main.py"
|
||||
echo "✓ Backend syntax OK"
|
||||
|
||||
build-frontend:
|
||||
if: ${{ github.event_name != 'workflow_run' || github.event.workflow_run.conclusion == 'success' }}
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Build frontend
|
||||
run: |
|
||||
EVENT_NAME="${{ github.event_name }}"
|
||||
REF_NAME="${{ github.ref_name }}"
|
||||
BASE_REF="${{ github.base_ref }}"
|
||||
RUN_WORKFLOW="${{ github.event.workflow_run.name }}"
|
||||
APP_DIR="/home/lars/docker/shinkan"
|
||||
|
||||
if [ "$REF_NAME" = "develop" ] || [ "$BASE_REF" = "develop" ]; then
|
||||
if [ "$EVENT_NAME" = "workflow_run" ]; then
|
||||
if [ "$RUN_WORKFLOW" = "Deploy Development" ]; then
|
||||
APP_DIR="/home/lars/docker/shinkan-dev"
|
||||
fi
|
||||
elif [ "$REF_NAME" = "develop" ]; then
|
||||
APP_DIR="/home/lars/docker/shinkan-dev"
|
||||
else
|
||||
echo "Kein Dev-Ziel (event=$EVENT_NAME ref=$REF_NAME base=$BASE_REF). Abbruch."
|
||||
exit 1
|
||||
fi
|
||||
echo "CI-Ziel: $APP_DIR"
|
||||
|
||||
cd "$APP_DIR/frontend"
|
||||
npm install
|
||||
@@ -100,6 +111,7 @@ jobs:
|
||||
# Phase-0 Lastsmoke: nur k6 — eigener Job (kein Node/Playwright), klare CI-Zuordnung.
|
||||
k6-health-baseline:
|
||||
name: k6 /health Baseline
|
||||
if: ${{ github.event_name != 'workflow_run' || github.event.workflow_run.conclusion == 'success' }}
|
||||
runs-on: ubuntu-latest
|
||||
env:
|
||||
E2E_TARGET_URL: https://dev.shinkan.jinkendo.de
|
||||
@@ -107,9 +119,26 @@ jobs:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Dev /health abwarten
|
||||
- name: E2E-Ziel wählen (Dev über Proxy vs. Production)
|
||||
id: e2e
|
||||
run: |
|
||||
BASE="${{ env.E2E_TARGET_URL }}"
|
||||
EVENT="${{ github.event_name }}"
|
||||
WF_NAME="${{ github.event.workflow_run.name }}"
|
||||
DEV_BASE="${{ env.E2E_TARGET_URL }}"
|
||||
if [ "$EVENT" = "workflow_run" ] && [ "$WF_NAME" = "Deploy Production" ]; then
|
||||
echo "mode=prod" >> $GITHUB_OUTPUT
|
||||
echo "base_url=https://shinkan.jinkendo.de" >> $GITHUB_OUTPUT
|
||||
echo "→ k6 gegen Prod-Basis."
|
||||
else
|
||||
echo "mode=dev" >> $GITHUB_OUTPUT
|
||||
echo "base_url=${DEV_BASE}" >> $GITHUB_OUTPUT
|
||||
echo "→ k6 gegen Dev (${DEV_BASE})."
|
||||
fi
|
||||
|
||||
- name: Dev /health abwarten
|
||||
if: ${{ steps.e2e.outputs.mode == 'dev' }}
|
||||
run: |
|
||||
BASE="${{ steps.e2e.outputs.base_url }}"
|
||||
echo "Warte auf $BASE/health …"
|
||||
for i in $(seq 1 90); do
|
||||
if curl -sf "$BASE/health" >/dev/null 2>&1; then
|
||||
@@ -122,6 +151,22 @@ jobs:
|
||||
curl -v "$BASE/health" || true
|
||||
exit 1
|
||||
|
||||
- name: Prod /health abwarten
|
||||
if: ${{ steps.e2e.outputs.mode == 'prod' }}
|
||||
run: |
|
||||
BASE="${{ steps.e2e.outputs.base_url }}"
|
||||
echo "Warte auf $BASE/health …"
|
||||
for i in $(seq 1 60); do
|
||||
if curl -sf "$BASE/health" >/dev/null 2>&1; then
|
||||
echo "Health OK (Versuch $i)"
|
||||
exit 0
|
||||
fi
|
||||
sleep 5
|
||||
done
|
||||
echo "Timeout: Prod /health nicht erreichbar"
|
||||
curl -v "$BASE/health" || true
|
||||
exit 1
|
||||
|
||||
- name: Install k6
|
||||
run: |
|
||||
set -e
|
||||
@@ -140,7 +185,7 @@ jobs:
|
||||
|
||||
- name: k6 Health-Baseline (parallele /health)
|
||||
env:
|
||||
BASE_URL: ${{ env.E2E_TARGET_URL }}
|
||||
BASE_URL: ${{ steps.e2e.outputs.base_url }}
|
||||
run: |
|
||||
set -e
|
||||
echo "k6 gegen BASE_URL=$BASE_URL"
|
||||
@@ -148,9 +193,10 @@ jobs:
|
||||
echo "✓ k6 Health-Baseline passed"
|
||||
|
||||
playwright-tests:
|
||||
if: ${{ github.event_name != 'workflow_run' || github.event.workflow_run.conclusion == 'success' }}
|
||||
runs-on: ubuntu-latest
|
||||
# Kein zusätzlicher docker-compose im Job: keine zweiten Container/Host-Ports.
|
||||
# Tests gegen die bereits deployte Dev-URL (HTTPS, Reverse-Proxy).
|
||||
# Dev: Tests gegen bereits deployte URL (HTTPS, Reverse-Proxy). Prod: gleicher Ablauf.
|
||||
env:
|
||||
# Öffentliche Dev-Basis — muss ALLOWED_ORIGINS / Nginx entsprechen; bei anderer Domain Workflow anpassen.
|
||||
E2E_TARGET_URL: https://dev.shinkan.jinkendo.de
|
||||
@@ -163,9 +209,26 @@ jobs:
|
||||
with:
|
||||
node-version: '20'
|
||||
|
||||
- name: Dev /health abwarten
|
||||
- name: E2E-Ziel wählen (Dev über Proxy vs. Production)
|
||||
id: e2e
|
||||
run: |
|
||||
BASE="${{ env.E2E_TARGET_URL }}"
|
||||
EVENT="${{ github.event_name }}"
|
||||
WF_NAME="${{ github.event.workflow_run.name }}"
|
||||
DEV_BASE="${{ env.E2E_TARGET_URL }}"
|
||||
if [ "$EVENT" = "workflow_run" ] && [ "$WF_NAME" = "Deploy Production" ]; then
|
||||
echo "mode=prod" >> $GITHUB_OUTPUT
|
||||
echo "base_url=https://shinkan.jinkendo.de" >> $GITHUB_OUTPUT
|
||||
echo "→ Prod. Secrets: E2E_PROD_TEST_EMAIL / E2E_PROD_TEST_PASSWORD."
|
||||
else
|
||||
echo "mode=dev" >> $GITHUB_OUTPUT
|
||||
echo "base_url=${DEV_BASE}" >> $GITHUB_OUTPUT
|
||||
echo "→ Deployte Dev-Umgebung (${DEV_BASE}). Secrets: E2E_DEV_TEST_EMAIL / E2E_DEV_TEST_PASSWORD."
|
||||
fi
|
||||
|
||||
- name: Dev /health abwarten
|
||||
if: ${{ steps.e2e.outputs.mode == 'dev' }}
|
||||
run: |
|
||||
BASE="${{ steps.e2e.outputs.base_url }}"
|
||||
echo "Warte auf $BASE/health …"
|
||||
for i in $(seq 1 90); do
|
||||
if curl -sf "$BASE/health" >/dev/null 2>&1; then
|
||||
@@ -178,12 +241,29 @@ jobs:
|
||||
curl -v "$BASE/health" || true
|
||||
exit 1
|
||||
|
||||
- name: Prod /health abwarten
|
||||
if: ${{ steps.e2e.outputs.mode == 'prod' }}
|
||||
run: |
|
||||
BASE="${{ steps.e2e.outputs.base_url }}"
|
||||
echo "Warte auf $BASE/health …"
|
||||
for i in $(seq 1 60); do
|
||||
if curl -sf "$BASE/health" >/dev/null 2>&1; then
|
||||
echo "Health OK (Versuch $i)"
|
||||
exit 0
|
||||
fi
|
||||
sleep 5
|
||||
done
|
||||
echo "Timeout: Prod /health nicht erreichbar"
|
||||
curl -v "$BASE/health" || true
|
||||
exit 1
|
||||
|
||||
- name: Testnutzer registrieren (Dev, nur wenn möglich)
|
||||
if: ${{ steps.e2e.outputs.mode == 'dev' }}
|
||||
env:
|
||||
E2E_DEV_TEST_EMAIL: ${{ secrets.E2E_DEV_TEST_EMAIL }}
|
||||
E2E_DEV_TEST_PASSWORD: ${{ secrets.E2E_DEV_TEST_PASSWORD }}
|
||||
run: |
|
||||
BASE="${{ env.E2E_TARGET_URL }}"
|
||||
BASE="${{ steps.e2e.outputs.base_url }}"
|
||||
if [ -z "$E2E_DEV_TEST_EMAIL" ] || [ -z "$E2E_DEV_TEST_PASSWORD" ]; then
|
||||
echo "(Registrierung übersprungen — Secrets E2E_DEV_* nicht gesetzt.)"
|
||||
exit 0
|
||||
@@ -204,13 +284,25 @@ jobs:
|
||||
E2E_DEV_TEST_PASSWORD: ${{ secrets.E2E_DEV_TEST_PASSWORD }}
|
||||
run: |
|
||||
set -e
|
||||
export PLAYWRIGHT_BASE_URL="${{ env.E2E_TARGET_URL }}"
|
||||
MODE="${{ steps.e2e.outputs.mode }}"
|
||||
BASE_URL="${{ steps.e2e.outputs.base_url }}"
|
||||
export PLAYWRIGHT_BASE_URL="$BASE_URL"
|
||||
|
||||
if [ "$MODE" = "prod" ]; then
|
||||
export TEST_EMAIL="${{ secrets.E2E_PROD_TEST_EMAIL }}"
|
||||
export TEST_PASSWORD="${{ secrets.E2E_PROD_TEST_PASSWORD }}"
|
||||
if [ -z "$TEST_EMAIL" ] || [ -z "$TEST_PASSWORD" ]; then
|
||||
echo "Fehler: E2E_PROD_TEST_EMAIL und E2E_PROD_TEST_PASSWORD setzen."
|
||||
exit 1
|
||||
fi
|
||||
else
|
||||
export TEST_EMAIL="$E2E_DEV_TEST_EMAIL"
|
||||
export TEST_PASSWORD="$E2E_DEV_TEST_PASSWORD"
|
||||
if [ -z "$TEST_EMAIL" ] || [ -z "$TEST_PASSWORD" ]; then
|
||||
echo "Fehler: E2E_DEV_TEST_EMAIL und E2E_DEV_TEST_PASSWORD setzen (Playwright soll gegen Dev einloggen)."
|
||||
exit 1
|
||||
fi
|
||||
fi
|
||||
|
||||
mkdir -p screenshots
|
||||
npx playwright test
|
||||
|
||||
@@ -137,15 +137,10 @@ Internet → Fritz!Box (privat.stommer.com) → Synology NAS → Raspberry Pi 5
|
||||
|
||||
Git Workflow:
|
||||
develop → Auto-Deploy → dev.shinkan.jinkendo.de (shinkan-dev/, Port 3098/8098)
|
||||
main → Auto-Deploy → shinkan.jinkendo.de auf llm-node (192.168.2.144, /home/llmadmin/docker/shinkan-prod)
|
||||
Workflow deploy-prod-llm-node.yml, Port 3003/8003
|
||||
Compose-Override docker-compose.llm-node.yml, Config /etc/shinkan/prod.env
|
||||
Pi-Prod (shinkan/, deploy-prod.yml) seit Cutover 2026-10-29 nur noch manuell
|
||||
Details: .claude/docs/technical/PROD_DEPLOYMENTS.md
|
||||
main → Auto-Deploy → shinkan.jinkendo.de (shinkan/, Port 3003/8003)
|
||||
|
||||
Gitea: http://192.168.2.144:3000/Lars/shinkan-jinkendo
|
||||
Runner: Raspberry Pi (/home/lars/gitea-runner/, Label ubuntu-latest)
|
||||
llm-node (act_runner.service, Label linux_host)
|
||||
Runner: Raspberry Pi (/home/lars/gitea-runner/)
|
||||
|
||||
Manuell:
|
||||
cd /home/lars/docker/shinkan[-dev]
|
||||
|
||||
@@ -1,38 +0,0 @@
|
||||
"""Aufgabengruppen für OpenRouter-Modelle. Die Zuordnung der Prompts lebt in ai_prompts.model_role."""
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Optional, Tuple
|
||||
|
||||
ROLE_KEYS = frozenset({"reasoning", "drafting", "matching"})
|
||||
|
||||
_FALLBACK_MODEL = "anthropic/claude-sonnet-4"
|
||||
|
||||
|
||||
def resolve_prompt_openrouter_model(
|
||||
*,
|
||||
prompt_model: Optional[str],
|
||||
role_model: Optional[str],
|
||||
platform_model: Optional[str],
|
||||
env_model: Optional[str],
|
||||
) -> Tuple[str, str]:
|
||||
"""
|
||||
Auflösung und Quelle.
|
||||
|
||||
Quelle ist `prompt`, `role`, `database` oder `environment`.
|
||||
Ungültige IDs werden übersprungen.
|
||||
"""
|
||||
from openrouter_chat import normalize_openrouter_model_id
|
||||
|
||||
for raw, source in (
|
||||
(prompt_model, "prompt"),
|
||||
(role_model, "role"),
|
||||
(platform_model, "database"),
|
||||
):
|
||||
try:
|
||||
model = normalize_openrouter_model_id(raw)
|
||||
except ValueError:
|
||||
model = None
|
||||
if model:
|
||||
return model, source
|
||||
env = (str(env_model or "").strip() or _FALLBACK_MODEL)
|
||||
return env, "environment"
|
||||
@@ -57,7 +57,7 @@ def load_ai_prompt_row(cur, slug: str, *, active_only: bool = True) -> Optional[
|
||||
if active_only:
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT slug, display_name, template, output_format, active, openrouter_model, model_role
|
||||
SELECT slug, display_name, template, output_format, active, openrouter_model
|
||||
FROM ai_prompts
|
||||
WHERE slug = %s AND active = true
|
||||
""",
|
||||
@@ -66,7 +66,7 @@ def load_ai_prompt_row(cur, slug: str, *, active_only: bool = True) -> Optional[
|
||||
else:
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT slug, display_name, template, output_format, active, openrouter_model, model_role
|
||||
SELECT slug, display_name, template, output_format, active, openrouter_model
|
||||
FROM ai_prompts
|
||||
WHERE slug = %s
|
||||
""",
|
||||
|
||||
@@ -1,833 +0,0 @@
|
||||
"""Vertrag v1: kanonisches Manifest, Ereignisse, Freigaberegeln, Cursor.
|
||||
|
||||
Reine Funktionen. Die Datenbankschicht ruft sie auf, die Tests prüfen sie ohne Postgres.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import hashlib
|
||||
import hmac
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import uuid
|
||||
from datetime import datetime, timezone
|
||||
from html import unescape
|
||||
from typing import Any, Iterable, Optional
|
||||
|
||||
from exercise_rich_text import normalize_inline_exercise_media_markup
|
||||
|
||||
PART_ROLES = (
|
||||
"goal",
|
||||
"prerequisites",
|
||||
"preparation",
|
||||
"instructions",
|
||||
"trainer_notes",
|
||||
"equipment",
|
||||
"duration_note",
|
||||
)
|
||||
ASSET_ROLES = ("demonstration", "worksheet", "illustration")
|
||||
ACTIONS = (
|
||||
"store",
|
||||
"render",
|
||||
"stream",
|
||||
"download",
|
||||
"print",
|
||||
"course_display",
|
||||
"commercial_course_use",
|
||||
"adapt",
|
||||
"public_preview",
|
||||
"grant_customer_use",
|
||||
)
|
||||
REASON_CODES = ("rights", "safety", "privacy", "expired", "editorial_error")
|
||||
WITHDRAW_TYPES = ("release.withdrawn", "variant.withdrawn", "asset.withdrawn")
|
||||
EVENT_TYPES = ("release.published", "release.retired", *WITHDRAW_TYPES)
|
||||
|
||||
_TAG = re.compile(r"<[^>]+>")
|
||||
_MEDIA_TOKEN = re.compile(r"\{\{exerciseMedia:(\d+)\}\}")
|
||||
_DATA_MEDIA = re.compile(r'data-exercise-media-id=["\'](\d+)["\']', re.I)
|
||||
|
||||
LEGAL_HOLD_REASON = {
|
||||
"rights_dispute": "rights",
|
||||
"copyright_complaint": "rights",
|
||||
"consent_withdrawn": "privacy",
|
||||
"privacy_complaint": "privacy",
|
||||
"youth_protection": "safety",
|
||||
"illegal_content": "safety",
|
||||
"other": "safety",
|
||||
}
|
||||
|
||||
OFFICIAL_WRITE_DENIED = "Globale Übungen dürfen nur von Superadmins bearbeitet werden."
|
||||
RATE_LIMIT_PER_MINUTE = 60
|
||||
|
||||
|
||||
def distribution_enabled() -> bool:
|
||||
return os.getenv("DISTRIBUTION_ENABLED", "").strip().lower() in ("1", "true", "yes")
|
||||
|
||||
|
||||
def cursor_secret() -> str:
|
||||
secret = os.getenv("DISTRIBUTION_CURSOR_SECRET", "").strip()
|
||||
if secret:
|
||||
return secret
|
||||
if os.getenv("ENVIRONMENT", "development").strip().lower() in ("production", "prod"):
|
||||
material = os.getenv("DB_PASSWORD", "").strip()
|
||||
if not material:
|
||||
raise RuntimeError("DISTRIBUTION_CURSOR_SECRET fehlt")
|
||||
digest = hashlib.sha256(f"shinkan-distribution-cursor:{material}".encode()).hexdigest()
|
||||
return digest
|
||||
return "shinkan-distribution-dev-cursor"
|
||||
|
||||
|
||||
def format_utc(dt: datetime) -> str:
|
||||
if dt.tzinfo is None:
|
||||
dt = dt.replace(tzinfo=timezone.utc)
|
||||
return dt.astimezone(timezone.utc).replace(microsecond=0).strftime("%Y-%m-%dT%H:%M:%SZ")
|
||||
|
||||
|
||||
def parse_utc(value: str) -> datetime:
|
||||
raw = value.strip()
|
||||
if raw.endswith("Z"):
|
||||
raw = raw[:-1] + "+00:00"
|
||||
parsed = datetime.fromisoformat(raw)
|
||||
if parsed.tzinfo is None:
|
||||
parsed = parsed.replace(tzinfo=timezone.utc)
|
||||
return parsed.astimezone(timezone.utc)
|
||||
|
||||
|
||||
def canonical_json(value: Any) -> bytes:
|
||||
return json.dumps(value, ensure_ascii=False, separators=(",", ":")).encode("utf-8")
|
||||
|
||||
|
||||
def sha256_bytes(data: bytes) -> str:
|
||||
return hashlib.sha256(data).hexdigest()
|
||||
|
||||
|
||||
def _copy_if(source: dict, key: str, required: bool = False, keep_null: bool = False) -> Any:
|
||||
if key not in source:
|
||||
if required:
|
||||
raise ValueError(f"Feld fehlt: {key}")
|
||||
return None
|
||||
value = source[key]
|
||||
if value is None and not keep_null:
|
||||
return None
|
||||
return value
|
||||
|
||||
|
||||
def order_manifest(source: dict) -> dict:
|
||||
"""Feldreihenfolge des Übergabevertrags. Optionale leere Felder entfallen, null bleibt bei Fristen."""
|
||||
exercise = source["exercise"]
|
||||
ordered_exercise: dict[str, Any] = {"title": exercise["title"]}
|
||||
if exercise.get("summary") is not None:
|
||||
ordered_exercise["summary"] = exercise["summary"]
|
||||
if exercise.get("audience") is not None:
|
||||
ordered_exercise["audience"] = exercise["audience"]
|
||||
ordered_exercise["rights_id"] = exercise["rights_id"]
|
||||
ordered_exercise["parts"] = [
|
||||
{
|
||||
"id": part["id"],
|
||||
"role": part["role"],
|
||||
"text": part["text"],
|
||||
"rights_id": part["rights_id"],
|
||||
}
|
||||
for part in exercise["parts"]
|
||||
]
|
||||
assets = []
|
||||
for asset in exercise["assets"]:
|
||||
item = {
|
||||
"id": asset["id"],
|
||||
"role": asset["role"],
|
||||
"media_type": asset["media_type"],
|
||||
"size_bytes": asset["size_bytes"],
|
||||
"sha256": asset["sha256"],
|
||||
"rights_id": asset["rights_id"],
|
||||
}
|
||||
if asset.get("label") is not None:
|
||||
item["label"] = asset["label"]
|
||||
assets.append(item)
|
||||
ordered_exercise["assets"] = assets
|
||||
ordered_exercise["common_part_ids"] = list(exercise["common_part_ids"])
|
||||
ordered_exercise["common_asset_ids"] = list(exercise["common_asset_ids"])
|
||||
ordered_exercise["variants"] = [
|
||||
{
|
||||
"id": variant["id"],
|
||||
"label": variant["label"],
|
||||
"part_ids": list(variant["part_ids"]),
|
||||
"asset_ids": list(variant["asset_ids"]),
|
||||
}
|
||||
for variant in exercise["variants"]
|
||||
]
|
||||
rights = []
|
||||
for right in source["rights"]:
|
||||
item = {
|
||||
"id": right["id"],
|
||||
"evidence_ref": right["evidence_ref"],
|
||||
"actions": list(right["actions"]),
|
||||
"territories": right["territories"],
|
||||
"valid_from": right["valid_from"],
|
||||
"valid_until": right["valid_until"],
|
||||
}
|
||||
if right.get("attribution") is not None:
|
||||
item["attribution"] = right["attribution"]
|
||||
rights.append(item)
|
||||
return {
|
||||
"schema_version": source["schema_version"],
|
||||
"resource_type": source["resource_type"],
|
||||
"release_id": source["release_id"],
|
||||
"source_id": source["source_id"],
|
||||
"revision": source["revision"],
|
||||
"publisher_id": source["publisher_id"],
|
||||
"published_at": source["published_at"],
|
||||
"exercise": ordered_exercise,
|
||||
"rights": rights,
|
||||
}
|
||||
|
||||
|
||||
def manifest_bytes(source: dict) -> bytes:
|
||||
return canonical_json(order_manifest(source))
|
||||
|
||||
|
||||
def order_event(event: dict) -> dict:
|
||||
ordered = {
|
||||
"event_id": event["event_id"],
|
||||
"type": event["type"],
|
||||
"release_id": event["release_id"],
|
||||
"occurred_at": event["occurred_at"],
|
||||
}
|
||||
if event["type"] == "release.published":
|
||||
ordered["source_id"] = event["source_id"]
|
||||
ordered["revision"] = event["revision"]
|
||||
ordered["manifest_sha256"] = event["manifest_sha256"]
|
||||
elif event["type"] in WITHDRAW_TYPES:
|
||||
if event["type"] != "release.withdrawn":
|
||||
ordered["target_id"] = event["target_id"]
|
||||
ordered["reason_code"] = event["reason_code"]
|
||||
return ordered
|
||||
|
||||
|
||||
def encode_cursor(secret: str, recipient_id: str, seq: int) -> str:
|
||||
payload = f"{recipient_id}:{int(seq)}".encode("utf-8")
|
||||
sig = hmac.new(secret.encode("utf-8"), payload, hashlib.sha256).hexdigest()
|
||||
raw = payload + b"." + sig.encode("ascii")
|
||||
return base64.urlsafe_b64encode(raw).decode("ascii").rstrip("=")
|
||||
|
||||
|
||||
def decode_cursor(secret: str, recipient_id: str, token: Optional[str]) -> int:
|
||||
if token is None or token == "":
|
||||
return 0
|
||||
pad = "=" * (-len(token) % 4)
|
||||
try:
|
||||
raw = base64.urlsafe_b64decode(token + pad)
|
||||
payload, sig = raw.rsplit(b".", 1)
|
||||
expected = hmac.new(secret.encode("utf-8"), payload, hashlib.sha256).hexdigest().encode("ascii")
|
||||
if not hmac.compare_digest(sig, expected):
|
||||
raise ValueError("sig")
|
||||
rec, seq_raw = payload.decode("utf-8").split(":", 1)
|
||||
if rec != recipient_id:
|
||||
raise ValueError("channel")
|
||||
seq = int(seq_raw)
|
||||
if seq < 0:
|
||||
raise ValueError("seq")
|
||||
return seq
|
||||
except Exception as exc:
|
||||
raise InvalidCursor() from exc
|
||||
|
||||
|
||||
def catalog_available(offered: bool, in_scope: bool) -> bool:
|
||||
"""Der aktuelle Abruf liefert eine Übung nur bei ausdrücklicher Auswahl und passendem Schlüsselumfang."""
|
||||
return bool(offered) and bool(in_scope)
|
||||
|
||||
|
||||
def catalog_html(value: Optional[str]) -> str:
|
||||
"""Gespeichertes Übungs-HTML. Absätze, Umbrüche, Listen und Hervorhebungen bleiben erhalten."""
|
||||
if value is None:
|
||||
return ""
|
||||
normalized = normalize_inline_exercise_media_markup(str(value))
|
||||
return normalized or ""
|
||||
|
||||
|
||||
def catalog_document(exercise: dict, variants: list[dict], media: list[dict]) -> dict:
|
||||
"""Aktueller Übungsstand. Die Reihenfolge der Varianten und Medien gehört zum Inhalt.
|
||||
|
||||
text_format html gilt für summary, goal, execution, preparation, trainer_notes
|
||||
und variants.execution_changes. Titel, Variantenbeschreibung und Material bleiben Text.
|
||||
"""
|
||||
ordered_variants = sorted(
|
||||
variants,
|
||||
key=lambda item: (item.get("sequence_order") is None, item.get("sequence_order") or 0, int(item.get("id") or 0)),
|
||||
)
|
||||
ordered_media = sorted(
|
||||
media,
|
||||
key=lambda item: (item.get("sort_order") is None, item.get("sort_order") or 0, int(item.get("id") or 0)),
|
||||
)
|
||||
return {
|
||||
"source_id": str(exercise.get("public_id")),
|
||||
"text_format": "html",
|
||||
"title": exercise.get("title") or "",
|
||||
"summary": catalog_html(exercise.get("summary")),
|
||||
"goal": catalog_html(exercise.get("goal")),
|
||||
"execution": catalog_html(exercise.get("execution")),
|
||||
"preparation": catalog_html(exercise.get("preparation")),
|
||||
"trainer_notes": catalog_html(exercise.get("trainer_notes")),
|
||||
"equipment": _equipment_text(exercise) or "",
|
||||
"duration_min": exercise.get("duration_min"),
|
||||
"duration_max": exercise.get("duration_max"),
|
||||
"variants": [
|
||||
{
|
||||
"id": str(item.get("public_id")),
|
||||
"name": item.get("variant_name") or "",
|
||||
"description": (item.get("description") or "").strip(),
|
||||
"execution_changes": catalog_html(item.get("execution_changes")),
|
||||
"sequence_order": item.get("sequence_order"),
|
||||
}
|
||||
for item in ordered_variants
|
||||
],
|
||||
"media": [
|
||||
{
|
||||
"id": str(item.get("public_id")),
|
||||
"media_type": item.get("media_type") or "",
|
||||
"title": item.get("title") or "",
|
||||
"sort_order": item.get("sort_order"),
|
||||
}
|
||||
for item in ordered_media
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
def catalog_hash(document: dict) -> str:
|
||||
return sha256_bytes(canonical_json(document))
|
||||
|
||||
|
||||
def catalog_changes(previous: dict, current: dict) -> list[dict]:
|
||||
"""Differenz seit dem letzten erfolgreichen Abruf. Gleiche Prüfsumme gilt als unverändert."""
|
||||
changes = []
|
||||
for source_id in sorted(current):
|
||||
digest = current[source_id]
|
||||
if source_id not in previous:
|
||||
changes.append({"source_id": source_id, "change": "added", "content_hash": digest})
|
||||
elif previous[source_id] != digest:
|
||||
changes.append({"source_id": source_id, "change": "updated", "content_hash": digest})
|
||||
for source_id in sorted(previous):
|
||||
if source_id not in current:
|
||||
changes.append({"source_id": source_id, "change": "removed"})
|
||||
return changes
|
||||
|
||||
|
||||
def encode_catalog_cursor(secret: str, binding_id: str, snapshot_id: str) -> str:
|
||||
payload = f"{binding_id}:{snapshot_id}".encode("utf-8")
|
||||
sig = hmac.new(secret.encode("utf-8"), payload, hashlib.sha256).hexdigest()
|
||||
raw = payload + b"." + sig.encode("ascii")
|
||||
return base64.urlsafe_b64encode(raw).decode("ascii").rstrip("=")
|
||||
|
||||
|
||||
def decode_catalog_cursor(secret: str, binding_id: str, token: Optional[str]) -> str:
|
||||
pad = "=" * (-len(token) % 4)
|
||||
try:
|
||||
raw = base64.urlsafe_b64decode(token + pad)
|
||||
payload, sig = raw.rsplit(b".", 1)
|
||||
expected = hmac.new(secret.encode("utf-8"), payload, hashlib.sha256).hexdigest().encode("ascii")
|
||||
if not hmac.compare_digest(sig, expected):
|
||||
raise ValueError("sig")
|
||||
bound, snapshot_id = payload.decode("utf-8").split(":", 1)
|
||||
if bound != str(binding_id):
|
||||
raise ValueError("channel")
|
||||
return snapshot_id
|
||||
except Exception as exc:
|
||||
raise InvalidCursor() from exc
|
||||
|
||||
|
||||
class InvalidCursor(Exception):
|
||||
pass
|
||||
|
||||
|
||||
def official_write_allowed(visibility: Optional[str], role: Optional[str]) -> bool:
|
||||
if (visibility or "").strip().lower() != "official":
|
||||
return True
|
||||
return (role or "").strip().lower() == "superadmin"
|
||||
|
||||
|
||||
def _same_club(left: Any, right: Any) -> bool:
|
||||
try:
|
||||
return left is not None and right is not None and int(left) == int(right)
|
||||
except (TypeError, ValueError):
|
||||
return False
|
||||
|
||||
|
||||
def release_denial(
|
||||
*,
|
||||
visibility: Optional[str],
|
||||
role: Optional[str],
|
||||
publisher_kind: str,
|
||||
is_owner: bool,
|
||||
is_club_admin: bool,
|
||||
publisher_club_id: Any = None,
|
||||
exercise_club_id: Any = None,
|
||||
) -> Optional[str]:
|
||||
"""Freigabe folgt der Zugehörigkeit der Übung, nicht einer gesonderten Zuordnungsliste."""
|
||||
vis = (visibility or "").strip().lower()
|
||||
role_l = (role or "").strip().lower()
|
||||
kind = (publisher_kind or "").strip().lower()
|
||||
if vis == "official":
|
||||
if role_l != "superadmin":
|
||||
return "Globale Übungen dürfen nur von Superadmins freigegeben werden."
|
||||
if kind != "platform":
|
||||
return "Globale Übungen werden nur über den Plattformbestand freigegeben."
|
||||
return None
|
||||
if kind == "platform":
|
||||
return "Der Plattformbestand gibt nur globale Übungen frei."
|
||||
if vis == "private":
|
||||
if not is_owner:
|
||||
return "Private Übungen gibt nur die Person frei, der sie gehören."
|
||||
if kind != "own":
|
||||
return "Private Übungen werden über den eigenen Bestand freigegeben."
|
||||
return None
|
||||
if vis == "club":
|
||||
if not is_club_admin:
|
||||
return "Vereinsübungen gibt ein Vereinsadmin dieses Vereins frei."
|
||||
if kind != "club" or not _same_club(publisher_club_id, exercise_club_id):
|
||||
return "Vereinsübungen werden über den Bestand dieses Vereins freigegeben."
|
||||
return None
|
||||
return "Diese Übung kann so nicht freigegeben werden."
|
||||
|
||||
|
||||
def can_withdraw(*, role: Optional[str], denial: Optional[str]) -> bool:
|
||||
if (role or "").strip().lower() == "superadmin":
|
||||
return True
|
||||
return denial is None
|
||||
|
||||
|
||||
OBJECT_SCOPES = ("exercise", "training_plan", "framework", "training_module")
|
||||
CONTEXT_VISIBILITIES = {
|
||||
"platform": ("official", "private"),
|
||||
"club": ("club", "private"),
|
||||
"personal": ("private",),
|
||||
"user": ("official", "club", "private"),
|
||||
}
|
||||
|
||||
|
||||
def scope_denial(context_kind: str, objects: Iterable[str], visibilities: Iterable[str]) -> Optional[str]:
|
||||
allowed = CONTEXT_VISIBILITIES.get(context_kind)
|
||||
if allowed is None:
|
||||
return "Unbekannter Schlüsselkontext."
|
||||
chosen_objects = [str(item) for item in objects]
|
||||
chosen_visibilities = [str(item) for item in visibilities]
|
||||
if not chosen_objects:
|
||||
return "Der Schlüssel braucht mindestens eine Objektart."
|
||||
if any(item not in OBJECT_SCOPES for item in chosen_objects):
|
||||
return "Unbekannte Objektart."
|
||||
if not chosen_visibilities:
|
||||
return "Der Schlüssel braucht mindestens eine Sichtbarkeit."
|
||||
if any(item not in allowed for item in chosen_visibilities):
|
||||
return "Diese Sichtbarkeit ist in diesem Kontext nicht erlaubt."
|
||||
return None
|
||||
|
||||
|
||||
def key_covers(objects: Optional[Iterable[str]], visibilities: Optional[Iterable[str]], *, resource: str, visibility: str) -> bool:
|
||||
chosen_objects = list(objects) if objects else ["exercise"]
|
||||
chosen_visibilities = list(visibilities) if visibilities else ["official", "club", "private"]
|
||||
return resource in chosen_objects and visibility in chosen_visibilities
|
||||
|
||||
|
||||
def package_state(*, fetch_blocked: bool, retired: bool) -> str:
|
||||
if fetch_blocked:
|
||||
return "withdrawn"
|
||||
if retired:
|
||||
return "retired"
|
||||
return "available"
|
||||
|
||||
|
||||
def exercise_offerable(source_status: Optional[str], package_states: Iterable[str]) -> tuple[str, bool]:
|
||||
"""Die eingefrorene Kopie bleibt abrufbar. Neu anbieten darf der Empfänger sie nur, solange die Quelle approved und ein Paket verfügbar ist."""
|
||||
status = "deleted" if not (source_status or "").strip() else str(source_status).strip().lower()
|
||||
states = list(package_states)
|
||||
return status, status == "approved" and any(item == "available" for item in states)
|
||||
|
||||
|
||||
def decide_confirm(stored_release_id: Optional[str], new_release_id: str) -> tuple[str, bool]:
|
||||
"""Technische Wiederholung liefert die gespeicherte Paket-ID. Eine neue Bestätigung legt ein Paket an."""
|
||||
if stored_release_id:
|
||||
return stored_release_id, False
|
||||
return new_release_id, True
|
||||
|
||||
|
||||
def rate_decision(hits: int, window_age_seconds: float, limit: int = RATE_LIMIT_PER_MINUTE) -> tuple[int, bool]:
|
||||
if window_age_seconds >= 60:
|
||||
return 1, False
|
||||
if hits >= limit:
|
||||
return hits, True
|
||||
return hits + 1, False
|
||||
|
||||
|
||||
def plaintext(value: Optional[str]) -> str:
|
||||
text = value or ""
|
||||
text = _MEDIA_TOKEN.sub("", text)
|
||||
text = _DATA_MEDIA.sub("", text)
|
||||
text = _TAG.sub("", text)
|
||||
return unescape(text).strip()
|
||||
|
||||
|
||||
def inline_media_ids(value: Optional[str]) -> set[int]:
|
||||
if not value:
|
||||
return set()
|
||||
ids = {int(item) for item in _MEDIA_TOKEN.findall(value)}
|
||||
ids.update(int(item) for item in _DATA_MEDIA.findall(value))
|
||||
return ids
|
||||
|
||||
|
||||
def snapshot_hash(exercise: dict, variants: list[dict], media: list[dict]) -> str:
|
||||
body = {
|
||||
"title": exercise.get("title") or "",
|
||||
"summary": exercise.get("summary") or "",
|
||||
"goal": exercise.get("goal") or "",
|
||||
"execution": exercise.get("execution") or "",
|
||||
"preparation": exercise.get("preparation") or "",
|
||||
"trainer_notes": exercise.get("trainer_notes") or "",
|
||||
"equipment": exercise.get("equipment"),
|
||||
"duration_min": exercise.get("duration_min"),
|
||||
"duration_max": exercise.get("duration_max"),
|
||||
"status": exercise.get("status"),
|
||||
"exercise_kind": exercise.get("exercise_kind") or "simple",
|
||||
"variants": [
|
||||
{
|
||||
"id": str(item.get("public_id")),
|
||||
"name": item.get("variant_name") or "",
|
||||
"description": item.get("description") or "",
|
||||
"execution_changes": item.get("execution_changes") or "",
|
||||
"duration_min": item.get("duration_min"),
|
||||
"duration_max": item.get("duration_max"),
|
||||
}
|
||||
for item in variants
|
||||
],
|
||||
"media": [
|
||||
{
|
||||
"id": str(item.get("public_id")),
|
||||
"sha256": item.get("sha256") or "",
|
||||
"media_type": item.get("media_type") or "",
|
||||
}
|
||||
for item in media
|
||||
],
|
||||
}
|
||||
return sha256_bytes(canonical_json(body))
|
||||
|
||||
|
||||
def _duration_note(exercise: dict) -> Optional[str]:
|
||||
low = exercise.get("duration_min")
|
||||
high = exercise.get("duration_max")
|
||||
if low and high:
|
||||
return f"{low}–{high} Minuten"
|
||||
if low or high:
|
||||
return f"{low or high} Minuten"
|
||||
return None
|
||||
|
||||
|
||||
def _manifest_part_text(manifest: dict, role: str) -> str:
|
||||
parts = ((manifest.get("exercise") or {}).get("parts") or [])
|
||||
return "\n".join((part.get("text") or "").strip() for part in parts if part.get("role") == role).strip()
|
||||
|
||||
|
||||
def _instruction_texts(exercise: dict, variants: list[dict]) -> list[str]:
|
||||
texts = []
|
||||
base = plaintext(exercise.get("execution"))
|
||||
if variants:
|
||||
for variant in variants:
|
||||
extra = plaintext(variant.get("execution_changes"))
|
||||
combined = "\n".join(piece for piece in (base, extra) if piece)
|
||||
if combined:
|
||||
texts.append(combined)
|
||||
elif base:
|
||||
texts.append(base)
|
||||
return texts
|
||||
|
||||
|
||||
def changed_areas(exercise: dict, variants: list[dict], media: list[dict], manifest: dict) -> list[str]:
|
||||
"""Benannte Abweichungen der Arbeitsfassung vom gespeicherten Release-Manifest."""
|
||||
body = manifest.get("exercise") or {}
|
||||
areas: list[str] = []
|
||||
if (exercise.get("title") or "") != (body.get("title") or ""):
|
||||
areas.append("Titel")
|
||||
if (plaintext(exercise.get("summary")) or "") != (body.get("summary") or ""):
|
||||
areas.append("Kurztext")
|
||||
for role, label, current in (
|
||||
("goal", "Ziel", plaintext(exercise.get("goal"))),
|
||||
("preparation", "Vorbereitung", plaintext(exercise.get("preparation"))),
|
||||
("trainer_notes", "Trainerhinweise", plaintext(exercise.get("trainer_notes"))),
|
||||
("equipment", "Material", plaintext(_equipment_text(exercise))),
|
||||
("duration_note", "Dauer", plaintext(_duration_note(exercise))),
|
||||
):
|
||||
if (current or "") != _manifest_part_text(manifest, role):
|
||||
areas.append(label)
|
||||
released_instructions = sorted(
|
||||
(part.get("text") or "").strip()
|
||||
for part in (body.get("parts") or [])
|
||||
if part.get("role") == "instructions" and (part.get("text") or "").strip()
|
||||
)
|
||||
if sorted(_instruction_texts(exercise, variants)) != released_instructions:
|
||||
areas.append("Durchführung")
|
||||
released_variants = list(body.get("variants") or [])
|
||||
if variants:
|
||||
current_variants = sorted((str(item.get("public_id")), item.get("variant_name") or "") for item in variants)
|
||||
released_pairs = sorted((str(item.get("id")), item.get("label") or "") for item in released_variants)
|
||||
if current_variants != released_pairs:
|
||||
areas.append("Varianten")
|
||||
elif len(released_variants) != 1:
|
||||
areas.append("Varianten")
|
||||
current_by_id = {str(item.get("public_id")): item.get("sha256") or "" for item in media}
|
||||
released_by_id = {str(item.get("id")): item.get("sha256") or "" for item in (body.get("assets") or [])}
|
||||
media_changed = set(current_by_id) != set(released_by_id)
|
||||
if not media_changed:
|
||||
for key, digest in current_by_id.items():
|
||||
released_digest = released_by_id.get(key) or ""
|
||||
if digest and released_digest and digest != released_digest:
|
||||
media_changed = True
|
||||
break
|
||||
if media_changed:
|
||||
areas.append("Medien")
|
||||
return areas
|
||||
|
||||
|
||||
def _equipment_text(exercise: dict) -> Optional[str]:
|
||||
raw = exercise.get("equipment")
|
||||
if isinstance(raw, str):
|
||||
try:
|
||||
raw = json.loads(raw)
|
||||
except json.JSONDecodeError:
|
||||
raw = [raw] if raw.strip() else []
|
||||
if isinstance(raw, list):
|
||||
parts = [str(item).strip() for item in raw if str(item).strip()]
|
||||
return ", ".join(parts) or None
|
||||
return None
|
||||
|
||||
|
||||
def default_cut(exercise: dict, variants: list[dict], media: list[dict]) -> dict:
|
||||
parts: list[dict] = []
|
||||
|
||||
def add(key: str, role: str, text: Optional[str]) -> None:
|
||||
cleaned = plaintext(text)
|
||||
if cleaned:
|
||||
parts.append({"key": key, "role": role, "text": cleaned})
|
||||
|
||||
add("field:goal", "goal", exercise.get("goal"))
|
||||
add("field:preparation", "preparation", exercise.get("preparation"))
|
||||
add("field:trainer_notes", "trainer_notes", exercise.get("trainer_notes"))
|
||||
add("field:equipment", "equipment", _equipment_text(exercise))
|
||||
add("field:duration", "duration_note", _duration_note(exercise))
|
||||
common_keys = [part["key"] for part in parts]
|
||||
variant_rows = []
|
||||
if variants:
|
||||
for variant in variants:
|
||||
key = f"variant:{variant['public_id']}:instructions"
|
||||
text = plaintext(exercise.get("execution"))
|
||||
extra = plaintext(variant.get("execution_changes"))
|
||||
combined = "\n".join(piece for piece in (text, extra) if piece)
|
||||
if combined:
|
||||
parts.append({"key": key, "role": "instructions", "text": combined})
|
||||
variant_rows.append(
|
||||
{
|
||||
"key": str(variant["public_id"]),
|
||||
"label": variant.get("variant_name") or "Variante",
|
||||
"part_keys": [key] if combined else [],
|
||||
"media_ids": [],
|
||||
}
|
||||
)
|
||||
else:
|
||||
key = "variant:default:instructions"
|
||||
text = plaintext(exercise.get("execution"))
|
||||
if text:
|
||||
parts.append({"key": key, "role": "instructions", "text": text})
|
||||
variant_rows.append(
|
||||
{
|
||||
"key": "default",
|
||||
"label": "Standard",
|
||||
"part_keys": [key] if text else [],
|
||||
"media_ids": [],
|
||||
}
|
||||
)
|
||||
assets = []
|
||||
for item in media:
|
||||
kind = (item.get("media_type") or "").lower()
|
||||
if kind == "video":
|
||||
role = "demonstration"
|
||||
elif kind in ("document", "pdf"):
|
||||
role = "worksheet"
|
||||
else:
|
||||
role = "illustration"
|
||||
assets.append(
|
||||
{
|
||||
"media_id": str(item["public_id"]),
|
||||
"role": role,
|
||||
"label": item.get("title") or None,
|
||||
}
|
||||
)
|
||||
return {
|
||||
"title": exercise.get("title") or "",
|
||||
"summary": plaintext(exercise.get("summary")) or None,
|
||||
"audience": None,
|
||||
"rights": [],
|
||||
"parts": parts,
|
||||
"assets": assets,
|
||||
"common_part_keys": common_keys,
|
||||
"common_media_ids": [],
|
||||
"variants": variant_rows,
|
||||
}
|
||||
|
||||
|
||||
def cut_hash(cut: dict) -> str:
|
||||
return sha256_bytes(canonical_json(cut))
|
||||
|
||||
|
||||
def collect_blockers(exercise: dict, variants: list[dict], media: list[dict], cut: dict, now: datetime) -> list[str]:
|
||||
blockers: list[str] = []
|
||||
if (exercise.get("exercise_kind") or "simple") != "simple":
|
||||
blockers.append("Kombinationsübungen können in dieser Fassung nicht herausgegeben werden.")
|
||||
if (exercise.get("status") or "") != "approved":
|
||||
blockers.append("Nur Übungen mit Status approved können freigegeben werden.")
|
||||
texts = " ".join(
|
||||
str(exercise.get(field) or "")
|
||||
for field in ("goal", "execution", "preparation", "trainer_notes", "summary")
|
||||
)
|
||||
selected_media = {str(item.get("media_id")) for item in cut.get("assets") or []}
|
||||
known_media = {str(item.get("public_id")): item for item in media}
|
||||
referenced = inline_media_ids(texts)
|
||||
for media_id in referenced:
|
||||
match = next((item for item in media if int(item.get("id") or 0) == media_id), None)
|
||||
if match is None or str(match.get("public_id")) not in selected_media:
|
||||
blockers.append("Ein Medienanker im Text ist nicht als Medium im Paket enthalten.")
|
||||
break
|
||||
part_keys = [part.get("key") for part in cut.get("parts") or []]
|
||||
if len(part_keys) != len(set(part_keys)):
|
||||
blockers.append("Teilschlüssel sind nicht eindeutig.")
|
||||
if not any(part.get("role") == "goal" and str(part.get("text") or "").strip() for part in cut.get("parts") or []):
|
||||
blockers.append("Das Paket braucht ein Lernziel.")
|
||||
rights = {item.get("id"): item for item in cut.get("rights") or []}
|
||||
if None in rights or "" in rights:
|
||||
blockers.append("Jeder Rechtevermerk braucht eine Kennung.")
|
||||
for right in cut.get("rights") or []:
|
||||
actions = set(right.get("actions") or [])
|
||||
unknown = actions - set(ACTIONS)
|
||||
if unknown:
|
||||
blockers.append("Unbekannte Nutzungsaktion im Rechtevermerk.")
|
||||
if "store" not in actions:
|
||||
blockers.append("Jeder Rechtevermerk muss die Übernahme erlauben.")
|
||||
if not str(right.get("evidence_ref") or "").strip():
|
||||
blockers.append("Jeder Rechtevermerk braucht eine Nachweisreferenz.")
|
||||
try:
|
||||
start = parse_utc(right["valid_from"])
|
||||
except Exception:
|
||||
blockers.append("valid_from ist kein UTC-Zeitpunkt.")
|
||||
continue
|
||||
until_raw = right.get("valid_until")
|
||||
until = None
|
||||
if until_raw is not None:
|
||||
try:
|
||||
until = parse_utc(until_raw)
|
||||
except Exception:
|
||||
blockers.append("valid_until ist kein UTC-Zeitpunkt.")
|
||||
continue
|
||||
if start > now or (until is not None and not (start <= now < until)):
|
||||
blockers.append("Ein Rechtevermerk ist zum Freigabezeitpunkt nicht wirksam.")
|
||||
territories = right.get("territories")
|
||||
if territories is not None:
|
||||
if not isinstance(territories, list) or any(not re.fullmatch(r"[A-Z]{2}", str(code)) for code in territories):
|
||||
blockers.append("territories sind ISO-Ländercodes oder null.")
|
||||
editorial = cut.get("editorial_rights_id")
|
||||
if editorial not in rights:
|
||||
blockers.append("Die redaktionellen Angaben brauchen einen Rechtevermerk.")
|
||||
used_parts: set[str] = set(cut.get("common_part_keys") or [])
|
||||
used_media: set[str] = set(str(item) for item in (cut.get("common_media_ids") or []))
|
||||
variant_keys = []
|
||||
for variant in cut.get("variants") or []:
|
||||
variant_keys.append(variant.get("key"))
|
||||
used_parts.update(variant.get("part_keys") or [])
|
||||
used_media.update(str(item) for item in (variant.get("media_ids") or []))
|
||||
for key in variant.get("part_keys") or []:
|
||||
if key not in part_keys:
|
||||
blockers.append("Eine Variante verweist auf einen unbekannten Teil.")
|
||||
for media_id in variant.get("media_ids") or []:
|
||||
if str(media_id) not in selected_media:
|
||||
blockers.append("Eine Variante verweist auf ein unbekanntes Medium.")
|
||||
for key in cut.get("common_part_keys") or []:
|
||||
if key not in part_keys:
|
||||
blockers.append("Ein gemeinsamer Teil ist unbekannt.")
|
||||
for media_id in cut.get("common_media_ids") or []:
|
||||
if str(media_id) not in selected_media:
|
||||
blockers.append("Ein gemeinsames Medium ist unbekannt.")
|
||||
if len(variant_keys) != len(set(variant_keys)) or not variant_keys:
|
||||
blockers.append("Das Paket braucht mindestens eine Variante.")
|
||||
for part in cut.get("parts") or []:
|
||||
if part.get("role") not in PART_ROLES:
|
||||
blockers.append("Unbekannte Textrolle.")
|
||||
if part.get("key") not in used_parts:
|
||||
blockers.append("Ein Textteil hängt an keiner Variante.")
|
||||
if part.get("rights_id") not in rights:
|
||||
blockers.append("Ein Textteil hat keinen wirksamen Rechtevermerk.")
|
||||
for asset in cut.get("assets") or []:
|
||||
media_id = str(asset.get("media_id"))
|
||||
if media_id not in used_media:
|
||||
blockers.append("Ein Medium hängt an keiner Variante.")
|
||||
if asset.get("role") not in ASSET_ROLES:
|
||||
blockers.append("Unbekannte Medienrolle.")
|
||||
if asset.get("rights_id") not in rights:
|
||||
blockers.append("Ein Medium hat keinen wirksamen Rechtevermerk.")
|
||||
stored = known_media.get(media_id)
|
||||
if stored is None:
|
||||
blockers.append("Ein ausgewähltes Medium gehört nicht zu dieser Übung.")
|
||||
continue
|
||||
if stored.get("legal_hold_active"):
|
||||
blockers.append("Ein ausgewähltes Medium ist gesperrt.")
|
||||
if not stored.get("file_path"):
|
||||
blockers.append("Ein ausgewähltes Medium hat keine gespeicherten Bytes.")
|
||||
if (stored.get("rights_status") or "legacy_unreviewed") in ("legacy_unreviewed", "blocked", ""):
|
||||
blockers.append("Die Upload-Erklärung eines Mediums trägt die Herausgabe nicht.")
|
||||
if variants:
|
||||
known_variant_ids = {str(item.get("public_id")) for item in variants}
|
||||
for variant in cut.get("variants") or []:
|
||||
if variant.get("key") not in known_variant_ids and variant.get("key") != "default":
|
||||
blockers.append("Eine Variante gehört nicht zur Übung.")
|
||||
return list(dict.fromkeys(blockers))
|
||||
|
||||
|
||||
def resolved_asset_ids(manifest: dict, variant_id: str) -> set[str]:
|
||||
exercise = manifest["exercise"]
|
||||
variant = next(item for item in exercise["variants"] if item["id"] == variant_id)
|
||||
return set(exercise["common_asset_ids"]) | set(variant["asset_ids"])
|
||||
|
||||
|
||||
def package_fetch_blocked(events: Iterable[dict], release_id: str) -> bool:
|
||||
return any(
|
||||
event.get("type") in WITHDRAW_TYPES and event.get("release_id") == release_id
|
||||
for event in events
|
||||
)
|
||||
|
||||
|
||||
def retrievable_release_ids(events: Iterable[dict]) -> set[str]:
|
||||
published: set[str] = set()
|
||||
blocked: set[str] = set()
|
||||
for event in events:
|
||||
if event.get("type") == "release.published":
|
||||
published.add(event["release_id"])
|
||||
elif event.get("type") in WITHDRAW_TYPES:
|
||||
blocked.add(event["release_id"])
|
||||
return published - blocked
|
||||
|
||||
|
||||
def plan_available(plan: dict, manifest: dict, events: Iterable[dict]) -> bool:
|
||||
release_id = plan["release_id"]
|
||||
variant_id = plan["variant_id"]
|
||||
relevant = [event for event in events if event.get("release_id") == release_id]
|
||||
if any(event.get("type") == "release.withdrawn" for event in relevant):
|
||||
return False
|
||||
if any(event.get("type") == "variant.withdrawn" and event.get("target_id") == variant_id for event in relevant):
|
||||
return False
|
||||
withdrawn_assets = {
|
||||
event["target_id"] for event in relevant if event.get("type") == "asset.withdrawn"
|
||||
}
|
||||
if withdrawn_assets & resolved_asset_ids(manifest, variant_id):
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def actions_cover(actions: Iterable[str], required: Iterable[str]) -> bool:
|
||||
return set(required).issubset(set(actions))
|
||||
|
||||
|
||||
def new_id() -> str:
|
||||
return str(uuid.uuid4())
|
||||
File diff suppressed because it is too large.
Load diff
+1
-4
@@ -243,7 +243,7 @@ def read_root():
|
||||
return out
|
||||
|
||||
# Register routers
|
||||
from routers import auth, profiles, exercises, exercise_progression_graphs, clubs, club_memberships, club_join_requests, club_creation_requests, admin_users, admin_user_content, admin_rights, me_entitlements, platform_media_storage, media_assets, skills, skill_profiles, training_planning, planning_exercise_suggest, dashboard, training_modules, training_framework_programs, catalogs, catalog_prompt_slots, maturity_models, matrix_stack_bundle, matrix_editor, import_wiki, import_wiki_admin, legal_documents, content_reports, ai_prompts_admin, ai_skill_retrieval_admin, exercise_enrichment_admin, openrouter_admin, distribution
|
||||
from routers import auth, profiles, exercises, exercise_progression_graphs, clubs, club_memberships, club_join_requests, club_creation_requests, admin_users, admin_user_content, admin_rights, me_entitlements, platform_media_storage, media_assets, skills, skill_profiles, training_planning, planning_exercise_suggest, dashboard, training_modules, training_framework_programs, catalogs, catalog_prompt_slots, maturity_models, matrix_stack_bundle, matrix_editor, import_wiki, import_wiki_admin, legal_documents, content_reports, ai_prompts_admin, ai_skill_retrieval_admin, exercise_enrichment_admin
|
||||
|
||||
app.include_router(auth.router)
|
||||
app.include_router(profiles.router)
|
||||
@@ -278,11 +278,8 @@ app.include_router(import_wiki_admin.router)
|
||||
app.include_router(legal_documents.router)
|
||||
app.include_router(content_reports.router)
|
||||
app.include_router(ai_prompts_admin.router)
|
||||
app.include_router(openrouter_admin.router)
|
||||
app.include_router(ai_skill_retrieval_admin.router)
|
||||
app.include_router(exercise_enrichment_admin.router)
|
||||
app.include_router(distribution.router)
|
||||
app.include_router(distribution.editorial)
|
||||
|
||||
# Lokale Übungs-Medien: standardmäßig nur über geschützten API-Pfad
|
||||
# GET /api/exercises/{id}/media/{mid}/file (?ssetoken = kurzlebiges Medien-Token, kein Sitzungstoken).
|
||||
|
||||
@@ -134,10 +134,6 @@ def set_legal_hold(
|
||||
updated_row = cur.fetchone()
|
||||
updated = r2d(updated_row)
|
||||
|
||||
from distribution_service import withdraw_assets_for_media_asset
|
||||
|
||||
withdraw_assets_for_media_asset(cur, asset_id, reason_code)
|
||||
|
||||
write_audit_log_entry(
|
||||
cur,
|
||||
asset_id=asset_id,
|
||||
|
||||
@@ -1,18 +0,0 @@
|
||||
-- Migration 097: Plattform-Standard für das OpenRouter-Modell (Superadmin).
|
||||
-- NULL = Umgebungsvariable OPENROUTER_MODEL.
|
||||
-- Ein Prompt-Override in ai_prompts.openrouter_model hat weiter Vorrang.
|
||||
|
||||
CREATE TABLE IF NOT EXISTS platform_ai_settings (
|
||||
id SMALLINT PRIMARY KEY DEFAULT 1,
|
||||
CONSTRAINT platform_ai_settings_singleton CHECK (id = 1),
|
||||
openrouter_model VARCHAR(200),
|
||||
updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
|
||||
updated_by_profile_id INT REFERENCES profiles(id) ON DELETE SET NULL
|
||||
);
|
||||
|
||||
INSERT INTO platform_ai_settings (id, openrouter_model)
|
||||
VALUES (1, NULL)
|
||||
ON CONFLICT (id) DO NOTHING;
|
||||
|
||||
COMMENT ON COLUMN platform_ai_settings.openrouter_model IS
|
||||
'Plattform-Standard OpenRouter model id; NULL = OPENROUTER_MODEL aus der Umgebung';
|
||||
@@ -1,86 +0,0 @@
|
||||
-- Migration 098: Aufgabengruppen für OpenRouter-Modelle.
|
||||
-- Ein Prompt nutzt: eigenes openrouter_model, sonst das Modell seiner Gruppe,
|
||||
-- sonst platform_ai_settings.openrouter_model, sonst OPENROUTER_MODEL.
|
||||
-- model_role IS NULL wird nur beim ersten Setzen gefüllt, damit spätere
|
||||
-- Umgruppierungen im Admin bei einem erneuten Lauf erhalten bleiben.
|
||||
|
||||
CREATE TABLE IF NOT EXISTS platform_ai_model_roles (
|
||||
role_key VARCHAR(40) PRIMARY KEY,
|
||||
display_name VARCHAR(120) NOT NULL,
|
||||
description TEXT NOT NULL,
|
||||
openrouter_model VARCHAR(200),
|
||||
sort_order INT NOT NULL DEFAULT 0,
|
||||
updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
|
||||
updated_by_profile_id INT REFERENCES profiles(id) ON DELETE SET NULL
|
||||
);
|
||||
|
||||
INSERT INTO platform_ai_model_roles (role_key, display_name, description, sort_order)
|
||||
VALUES
|
||||
(
|
||||
'reasoning',
|
||||
'Denken',
|
||||
'Didaktische Entwürfe und Qualitätsurteile: Start und Ziel, Zielanalyse, Roadmap, Stufen und die Prüfung eines Übungspfads.',
|
||||
10
|
||||
),
|
||||
(
|
||||
'drafting',
|
||||
'Formulieren',
|
||||
'Texte und eng gefasste Profile: Zusammenfassung, Anleitung, Suchabsicht, Semantik und Erwartungsprofil.',
|
||||
20
|
||||
),
|
||||
(
|
||||
'matching',
|
||||
'Zuordnen',
|
||||
'Auswahl aus einer vorgegebenen Menge: Fähigkeiten vorschlagen und Suchtreffer neu ordnen.',
|
||||
30
|
||||
)
|
||||
ON CONFLICT (role_key) DO UPDATE
|
||||
SET display_name = EXCLUDED.display_name,
|
||||
description = EXCLUDED.description,
|
||||
sort_order = EXCLUDED.sort_order;
|
||||
|
||||
ALTER TABLE ai_prompts ADD COLUMN IF NOT EXISTS model_role VARCHAR(40);
|
||||
|
||||
DO $$
|
||||
BEGIN
|
||||
IF NOT EXISTS (
|
||||
SELECT 1 FROM pg_constraint WHERE conname = 'ai_prompts_model_role_fkey'
|
||||
) THEN
|
||||
ALTER TABLE ai_prompts
|
||||
ADD CONSTRAINT ai_prompts_model_role_fkey
|
||||
FOREIGN KEY (model_role) REFERENCES platform_ai_model_roles(role_key);
|
||||
END IF;
|
||||
END $$;
|
||||
|
||||
COMMENT ON COLUMN ai_prompts.model_role IS
|
||||
'Aufgabengruppe für das Standardmodell; NULL = Plattformstandard. openrouter_model am Prompt hat Vorrang.';
|
||||
|
||||
UPDATE ai_prompts
|
||||
SET model_role = 'reasoning'
|
||||
WHERE model_role IS NULL
|
||||
AND slug IN (
|
||||
'planning_progression_start_target',
|
||||
'planning_progression_goal_analysis',
|
||||
'planning_progression_roadmap',
|
||||
'planning_progression_stage_spec',
|
||||
'planning_exercise_path_qa'
|
||||
);
|
||||
|
||||
UPDATE ai_prompts
|
||||
SET model_role = 'drafting'
|
||||
WHERE model_role IS NULL
|
||||
AND slug IN (
|
||||
'exercise_summary',
|
||||
'exercise_instruction_rewrite',
|
||||
'planning_exercise_search_intent',
|
||||
'planning_exercise_query_semantics',
|
||||
'planning_exercise_expectation_profile'
|
||||
);
|
||||
|
||||
UPDATE ai_prompts
|
||||
SET model_role = 'matching'
|
||||
WHERE model_role IS NULL
|
||||
AND slug IN (
|
||||
'exercise_skill_suggestions',
|
||||
'planning_exercise_search_rank'
|
||||
);
|
||||
@@ -1,191 +0,0 @@
|
||||
-- Distribution v1: eingefrorene Übungspakete für Empfängerkanäle.
|
||||
-- Produktiver Abruf bleibt über DISTRIBUTION_ENABLED aus, bis die Testinstanz ihn einschaltet.
|
||||
|
||||
ALTER TABLE exercises
|
||||
ADD COLUMN IF NOT EXISTS public_id UUID;
|
||||
|
||||
UPDATE exercises SET public_id = gen_random_uuid() WHERE public_id IS NULL;
|
||||
|
||||
ALTER TABLE exercises
|
||||
ALTER COLUMN public_id SET DEFAULT gen_random_uuid();
|
||||
|
||||
ALTER TABLE exercises
|
||||
ALTER COLUMN public_id SET NOT NULL;
|
||||
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS uq_exercises_public_id ON exercises (public_id);
|
||||
|
||||
ALTER TABLE exercise_variants
|
||||
ADD COLUMN IF NOT EXISTS public_id UUID;
|
||||
|
||||
UPDATE exercise_variants SET public_id = gen_random_uuid() WHERE public_id IS NULL;
|
||||
|
||||
ALTER TABLE exercise_variants
|
||||
ALTER COLUMN public_id SET DEFAULT gen_random_uuid();
|
||||
|
||||
ALTER TABLE exercise_variants
|
||||
ALTER COLUMN public_id SET NOT NULL;
|
||||
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS uq_exercise_variants_public_id ON exercise_variants (public_id);
|
||||
|
||||
ALTER TABLE exercise_media
|
||||
ADD COLUMN IF NOT EXISTS public_id UUID;
|
||||
|
||||
UPDATE exercise_media SET public_id = gen_random_uuid() WHERE public_id IS NULL;
|
||||
|
||||
ALTER TABLE exercise_media
|
||||
ALTER COLUMN public_id SET DEFAULT gen_random_uuid();
|
||||
|
||||
ALTER TABLE exercise_media
|
||||
ALTER COLUMN public_id SET NOT NULL;
|
||||
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS uq_exercise_media_public_id ON exercise_media (public_id);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS distribution_publishers (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
name TEXT NOT NULL,
|
||||
kind TEXT NOT NULL CHECK (kind IN ('platform', 'own', 'club')),
|
||||
club_id INT REFERENCES clubs (id),
|
||||
status TEXT NOT NULL DEFAULT 'active' CHECK (status IN ('active', 'suspended')),
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
CONSTRAINT distribution_publishers_kind_club CHECK (
|
||||
(kind = 'club' AND club_id IS NOT NULL)
|
||||
OR (kind <> 'club' AND club_id IS NULL)
|
||||
)
|
||||
);
|
||||
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS uq_distribution_platform_publisher
|
||||
ON distribution_publishers (kind)
|
||||
WHERE kind = 'platform';
|
||||
|
||||
CREATE TABLE IF NOT EXISTS distribution_recipients (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
name TEXT NOT NULL,
|
||||
status TEXT NOT NULL DEFAULT 'active' CHECK (status IN ('active', 'suspended')),
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS distribution_relationships (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
publisher_id UUID NOT NULL REFERENCES distribution_publishers (id),
|
||||
recipient_id UUID NOT NULL REFERENCES distribution_recipients (id),
|
||||
status TEXT NOT NULL DEFAULT 'active' CHECK (status IN ('active', 'suspended')),
|
||||
UNIQUE (publisher_id, recipient_id)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS distribution_bindings (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
recipient_id UUID NOT NULL REFERENCES distribution_recipients (id),
|
||||
name TEXT NOT NULL,
|
||||
status TEXT NOT NULL DEFAULT 'active' CHECK (status IN ('active', 'suspended')),
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS distribution_keys (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
binding_id UUID NOT NULL REFERENCES distribution_bindings (id),
|
||||
key_prefix TEXT NOT NULL UNIQUE,
|
||||
secret_hash TEXT NOT NULL,
|
||||
expires_at TIMESTAMPTZ,
|
||||
revoked_at TIMESTAMPTZ,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS distribution_releasers (
|
||||
publisher_id UUID NOT NULL REFERENCES distribution_publishers (id),
|
||||
profile_id INT NOT NULL REFERENCES profiles (id),
|
||||
PRIMARY KEY (publisher_id, profile_id)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS distribution_publisher_exercises (
|
||||
publisher_id UUID NOT NULL REFERENCES distribution_publishers (id),
|
||||
exercise_id INT NOT NULL REFERENCES exercises (id),
|
||||
PRIMARY KEY (publisher_id, exercise_id)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS distribution_part_identities (
|
||||
source_id UUID NOT NULL,
|
||||
part_key TEXT NOT NULL,
|
||||
part_id UUID NOT NULL,
|
||||
PRIMARY KEY (source_id, part_key)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS distribution_source_revisions (
|
||||
source_id UUID NOT NULL,
|
||||
revision INT NOT NULL CHECK (revision > 0),
|
||||
snapshot_hash TEXT NOT NULL,
|
||||
PRIMARY KEY (source_id, revision),
|
||||
UNIQUE (source_id, snapshot_hash)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS distribution_drafts (
|
||||
id UUID PRIMARY KEY,
|
||||
exercise_id INT NOT NULL REFERENCES exercises (id),
|
||||
publisher_id UUID NOT NULL REFERENCES distribution_publishers (id),
|
||||
recipient_id UUID NOT NULL REFERENCES distribution_recipients (id),
|
||||
prepared_by INT NOT NULL REFERENCES profiles (id),
|
||||
cut JSONB NOT NULL,
|
||||
preview_hash TEXT NOT NULL,
|
||||
release_id UUID,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
confirmed_at TIMESTAMPTZ
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS distribution_releases (
|
||||
release_id UUID PRIMARY KEY,
|
||||
recipient_id UUID NOT NULL REFERENCES distribution_recipients (id),
|
||||
publisher_id UUID NOT NULL REFERENCES distribution_publishers (id),
|
||||
source_id UUID NOT NULL,
|
||||
revision INT NOT NULL,
|
||||
cut_hash TEXT NOT NULL,
|
||||
manifest_text TEXT NOT NULL,
|
||||
manifest_sha256 TEXT NOT NULL,
|
||||
published_at TIMESTAMPTZ NOT NULL,
|
||||
fetch_blocked BOOLEAN NOT NULL DEFAULT FALSE,
|
||||
confirmed_by INT REFERENCES profiles (id)
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_distribution_releases_source ON distribution_releases (source_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_distribution_releases_recipient ON distribution_releases (recipient_id);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS distribution_release_assets (
|
||||
release_id UUID NOT NULL REFERENCES distribution_releases (release_id),
|
||||
asset_id UUID NOT NULL,
|
||||
sha256 TEXT NOT NULL,
|
||||
size_bytes INT NOT NULL,
|
||||
media_type TEXT NOT NULL,
|
||||
storage_path TEXT NOT NULL,
|
||||
source_media_public_id UUID,
|
||||
source_asset_id INT,
|
||||
PRIMARY KEY (release_id, asset_id)
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_distribution_release_assets_source
|
||||
ON distribution_release_assets (source_asset_id);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS distribution_events (
|
||||
event_id UUID PRIMARY KEY,
|
||||
recipient_id UUID NOT NULL REFERENCES distribution_recipients (id),
|
||||
seq BIGINT NOT NULL,
|
||||
event_type TEXT NOT NULL,
|
||||
release_id UUID NOT NULL,
|
||||
occurred_at TIMESTAMPTZ NOT NULL,
|
||||
body JSONB NOT NULL,
|
||||
UNIQUE (recipient_id, seq)
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_distribution_events_feed
|
||||
ON distribution_events (recipient_id, seq);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS distribution_evidence (
|
||||
id TEXT PRIMARY KEY,
|
||||
publisher_id UUID NOT NULL REFERENCES distribution_publishers (id),
|
||||
note TEXT NOT NULL,
|
||||
created_by INT NOT NULL REFERENCES profiles (id),
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS distribution_rate_windows (
|
||||
binding_id UUID PRIMARY KEY REFERENCES distribution_bindings (id),
|
||||
window_start TIMESTAMPTZ NOT NULL,
|
||||
hits INT NOT NULL
|
||||
);
|
||||
@@ -1,25 +0,0 @@
|
||||
-- API-Schnittstelle je Verein und benannte Schlüssel mit Objekt- und Sichtbarkeitsrechten.
|
||||
-- Bestehende Schlüssel behalten den Abruf von Übungen über alle Sichtbarkeiten, damit die Testschlüssel weiter gelten.
|
||||
|
||||
ALTER TABLE clubs
|
||||
ADD COLUMN IF NOT EXISTS distribution_api_enabled BOOLEAN NOT NULL DEFAULT false;
|
||||
|
||||
ALTER TABLE distribution_keys
|
||||
ADD COLUMN IF NOT EXISTS label TEXT;
|
||||
|
||||
ALTER TABLE distribution_keys
|
||||
ADD COLUMN IF NOT EXISTS objects TEXT[] NOT NULL DEFAULT ARRAY['exercise']::text[];
|
||||
|
||||
ALTER TABLE distribution_keys
|
||||
ADD COLUMN IF NOT EXISTS visibilities TEXT[] NOT NULL DEFAULT ARRAY['official', 'club', 'private']::text[];
|
||||
|
||||
ALTER TABLE distribution_keys
|
||||
ADD COLUMN IF NOT EXISTS context_kind TEXT NOT NULL DEFAULT 'platform';
|
||||
|
||||
ALTER TABLE distribution_keys
|
||||
ADD COLUMN IF NOT EXISTS context_club_id INT REFERENCES clubs (id);
|
||||
|
||||
ALTER TABLE distribution_keys
|
||||
ADD COLUMN IF NOT EXISTS context_profile_id INT REFERENCES profiles (id);
|
||||
|
||||
UPDATE distribution_keys SET label = key_prefix WHERE label IS NULL OR btrim(label) = '';
|
||||
@@ -1,7 +0,0 @@
|
||||
-- Ein Schlüssel kann mehrere Vereine und Sichtbarkeiten tragen. Der Wert bleibt für den Inhaber kopierbar.
|
||||
|
||||
ALTER TABLE distribution_keys
|
||||
ADD COLUMN IF NOT EXISTS token_value TEXT;
|
||||
|
||||
ALTER TABLE distribution_keys
|
||||
ADD COLUMN IF NOT EXISTS club_ids INT[] NOT NULL DEFAULT ARRAY[]::int[];
|
||||
@@ -1,18 +0,0 @@
|
||||
-- Auswahl, welche Übungen der aktuelle Abruf ausliefert. Frühere Lieferpakete schalten das nicht mit ein.
|
||||
|
||||
ALTER TABLE exercises
|
||||
ADD COLUMN IF NOT EXISTS api_offered BOOLEAN NOT NULL DEFAULT FALSE;
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_exercises_api_offered
|
||||
ON exercises (id)
|
||||
WHERE api_offered = TRUE;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS distribution_catalog_snapshots (
|
||||
id UUID PRIMARY KEY,
|
||||
binding_id UUID NOT NULL REFERENCES distribution_bindings (id),
|
||||
snapshot JSONB NOT NULL,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_distribution_catalog_snapshots_binding
|
||||
ON distribution_catalog_snapshots (binding_id, created_at DESC);
|
||||
+13
-299
@@ -1,19 +1,12 @@
|
||||
"""
|
||||
Minimal OpenRouter REST client (sync).
|
||||
|
||||
API-Key und Basis-URL aus der Umgebung. Das wirksame Standardmodell kommt aus
|
||||
platform_ai_settings (Superadmin), sonst aus OPENROUTER_MODEL.
|
||||
Minimal OpenRouter REST client (sync). Reads OPENROUTER_API_KEY / OPENROUTER_MODEL / OPENROUTER_BASE_URL from env.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import re
|
||||
import threading
|
||||
import time
|
||||
from datetime import datetime, timezone
|
||||
from typing import Any, Dict, List, Mapping, Optional, Tuple
|
||||
from typing import Any, Dict, List, Mapping, Optional
|
||||
|
||||
import httpx
|
||||
|
||||
@@ -213,305 +206,26 @@ def openrouter_chat_completion(
|
||||
return joined
|
||||
|
||||
|
||||
_MODEL_ID_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._:@+/-]{0,198}$")
|
||||
_CATALOG_TTL_SEC = 600
|
||||
_catalog_lock = threading.Lock()
|
||||
_catalog_cache: Dict[str, Any] = {"fetched_at": 0.0, "fetched_at_iso": None, "models": None}
|
||||
_settings_read_failed = False
|
||||
|
||||
_FALLBACK_MODEL = "anthropic/claude-sonnet-4"
|
||||
|
||||
|
||||
def openrouter_base_url() -> str:
|
||||
return (os.getenv("OPENROUTER_BASE_URL") or "").strip().rstrip("/") or "https://openrouter.ai/api/v1"
|
||||
|
||||
|
||||
def normalize_openrouter_model_id(raw: Optional[str]) -> Optional[str]:
|
||||
"""Leer wird None. Ungültige IDs werfen ValueError."""
|
||||
if raw is None:
|
||||
return None
|
||||
text = str(raw).strip()
|
||||
if not text:
|
||||
return None
|
||||
if any(ch.isspace() for ch in text):
|
||||
raise ValueError("OpenRouter-Modell-ID darf keine Leer- oder Steuerzeichen enthalten.")
|
||||
if (
|
||||
not _MODEL_ID_RE.match(text)
|
||||
or "/" not in text
|
||||
or text.startswith("/")
|
||||
or text.endswith("/")
|
||||
or "//" in text
|
||||
):
|
||||
raise ValueError("OpenRouter-Modell-ID muss wie anbieter/modell aussehen.")
|
||||
return text
|
||||
|
||||
|
||||
def env_openrouter_model_id() -> str:
|
||||
model = (os.getenv("OPENROUTER_MODEL") or _FALLBACK_MODEL).strip()
|
||||
return model or _FALLBACK_MODEL
|
||||
|
||||
|
||||
def resolve_default_openrouter_model_id(
|
||||
stored: Optional[str],
|
||||
env_model: Optional[str] = None,
|
||||
) -> Tuple[str, str]:
|
||||
"""Wirksame ID und Quelle (`database` oder `environment`)."""
|
||||
custom: Optional[str] = None
|
||||
try:
|
||||
custom = normalize_openrouter_model_id(stored)
|
||||
except ValueError:
|
||||
custom = None
|
||||
if custom:
|
||||
return custom, "database"
|
||||
env = env_openrouter_model_id() if env_model is None else (str(env_model).strip() or _FALLBACK_MODEL)
|
||||
return env or _FALLBACK_MODEL, "environment"
|
||||
|
||||
|
||||
def read_stored_platform_openrouter_model() -> Optional[str]:
|
||||
"""Gespeichertes Plattformmodell. Bei fehlender Tabelle oder DB-Fehler: None."""
|
||||
global _settings_read_failed
|
||||
try:
|
||||
from db import get_cursor, get_db
|
||||
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute("SELECT openrouter_model FROM platform_ai_settings WHERE id = 1")
|
||||
row = cur.fetchone()
|
||||
_settings_read_failed = False
|
||||
if not row:
|
||||
return None
|
||||
raw = row.get("openrouter_model") if isinstance(row, dict) else row[0]
|
||||
text = str(raw or "").strip()
|
||||
return text or None
|
||||
except Exception as exc:
|
||||
if not _settings_read_failed:
|
||||
_logger.warning(
|
||||
"Plattform-OpenRouter-Modell nicht lesbar, nutze OPENROUTER_MODEL: %s",
|
||||
exc,
|
||||
)
|
||||
_settings_read_failed = True
|
||||
return None
|
||||
|
||||
|
||||
def normalize_openrouter_env() -> tuple[str, str]:
|
||||
"""API-Key und Env-Modell. Das wirksame Modell liefert default_openrouter_model_id()."""
|
||||
key = (os.getenv("OPENROUTER_API_KEY") or "").strip()
|
||||
return key, env_openrouter_model_id()
|
||||
model = (os.getenv("OPENROUTER_MODEL") or "anthropic/claude-sonnet-4").strip()
|
||||
return key, model
|
||||
|
||||
|
||||
def default_openrouter_model_id() -> str:
|
||||
"""Plattform-Standard aus der Datenbank, sonst OPENROUTER_MODEL."""
|
||||
effective, _source = resolve_default_openrouter_model_id(read_stored_platform_openrouter_model())
|
||||
return effective
|
||||
|
||||
|
||||
def read_platform_role_models() -> Dict[str, str]:
|
||||
"""Gespeicherte Gruppenmodelle. Fehlende Tabelle oder DB-Fehler: leeres Dict."""
|
||||
try:
|
||||
from db import get_cursor, get_db
|
||||
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute(
|
||||
"SELECT role_key, openrouter_model FROM platform_ai_model_roles"
|
||||
)
|
||||
rows = cur.fetchall()
|
||||
except Exception as exc:
|
||||
_logger.warning("Aufgabengruppen-Modelle nicht lesbar: %s", exc)
|
||||
return {}
|
||||
out: Dict[str, str] = {}
|
||||
for row in rows or []:
|
||||
key = str((row.get("role_key") if isinstance(row, dict) else row[0]) or "").strip()
|
||||
raw = row.get("openrouter_model") if isinstance(row, dict) else row[1]
|
||||
text = str(raw or "").strip()
|
||||
if key and text:
|
||||
out[key] = text
|
||||
return out
|
||||
"""Standard-Modell aus OPENROUTER_MODEL (ohne API-Key zu pruefen)."""
|
||||
_, model = normalize_openrouter_env()
|
||||
return model
|
||||
|
||||
|
||||
def effective_openrouter_model_for_prompt_row(row: Optional[Mapping[str, Any]]) -> str:
|
||||
"""
|
||||
Prompt-Ausnahme, sonst Aufgabengruppe, sonst Plattform-Standard, sonst Umgebung.
|
||||
Pro-Prompt-Override in ai_prompts.openrouter_model, sonst Env-Default.
|
||||
|
||||
`row` kann eine partial Row aus load_ai_prompt_row sein
|
||||
(Felder slug, openrouter_model, model_role, …).
|
||||
`row` kann eine partial Row aus load_ai_prompt_row sein (Felder slug, openrouter_model, …).
|
||||
"""
|
||||
from ai_model_roles import resolve_prompt_openrouter_model
|
||||
|
||||
prompt_model = None
|
||||
role_key = ""
|
||||
if row:
|
||||
prompt_model = row.get("openrouter_model")
|
||||
role_key = str(row.get("model_role") or "").strip()
|
||||
role_model = read_platform_role_models().get(role_key) if role_key else None
|
||||
effective, _source = resolve_prompt_openrouter_model(
|
||||
prompt_model=None if prompt_model is None else str(prompt_model),
|
||||
role_model=role_model,
|
||||
platform_model=read_stored_platform_openrouter_model(),
|
||||
env_model=env_openrouter_model_id(),
|
||||
)
|
||||
return effective
|
||||
|
||||
|
||||
def _price_str(pricing: Any, key: str) -> Optional[str]:
|
||||
if not isinstance(pricing, dict):
|
||||
return None
|
||||
raw = pricing.get(key)
|
||||
if raw is None or raw == "":
|
||||
return None
|
||||
try:
|
||||
float(str(raw))
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
return str(raw)
|
||||
|
||||
|
||||
def _modalities(item: Mapping[str, Any], side: str) -> List[str]:
|
||||
arch = item.get("architecture") if isinstance(item.get("architecture"), dict) else {}
|
||||
key = "input_modalities" if side == "input" else "output_modalities"
|
||||
raw = arch.get(key)
|
||||
if isinstance(raw, list):
|
||||
out = [str(x).strip().lower() for x in raw if str(x).strip()]
|
||||
if out:
|
||||
return out
|
||||
modality = str(arch.get("modality") or "")
|
||||
parts = modality.split("->")
|
||||
chunk = parts[0] if side == "input" else (parts[1] if len(parts) > 1 else "")
|
||||
return [p.strip().lower() for p in chunk.split("+") if p.strip()]
|
||||
|
||||
|
||||
def _context_length(item: Mapping[str, Any]) -> Optional[int]:
|
||||
candidates = [item.get("context_length")]
|
||||
top = item.get("top_provider")
|
||||
if isinstance(top, dict):
|
||||
candidates.append(top.get("context_length"))
|
||||
for raw in candidates:
|
||||
try:
|
||||
value = int(raw)
|
||||
except (TypeError, ValueError):
|
||||
continue
|
||||
if value > 0:
|
||||
return value
|
||||
return None
|
||||
|
||||
|
||||
def parse_openrouter_models_payload(data: Any) -> List[Dict[str, Any]]:
|
||||
"""OpenRouter `/models` auf eine schlanke, stabile Liste bringen."""
|
||||
rows = data.get("data") if isinstance(data, dict) else None
|
||||
if not isinstance(rows, list):
|
||||
raise OpenRouterError("OpenRouter: Modellliste ohne data-Array")
|
||||
out: List[Dict[str, Any]] = []
|
||||
seen = set()
|
||||
for item in rows:
|
||||
if not isinstance(item, dict):
|
||||
continue
|
||||
model_id = str(item.get("id") or "").strip()
|
||||
if not model_id or model_id in seen:
|
||||
continue
|
||||
seen.add(model_id)
|
||||
provider = model_id.split("/", 1)[0]
|
||||
description = str(item.get("description") or "").replace("\r", " ").replace("\n", " ").strip()
|
||||
if len(description) > 400:
|
||||
description = description[:397].rstrip() + "…"
|
||||
prompt_price = _price_str(item.get("pricing"), "prompt")
|
||||
completion_price = _price_str(item.get("pricing"), "completion")
|
||||
try:
|
||||
prompt_num = float(prompt_price) if prompt_price is not None else None
|
||||
completion_num = float(completion_price) if completion_price is not None else None
|
||||
except ValueError:
|
||||
prompt_num = None
|
||||
completion_num = None
|
||||
is_free = model_id.endswith(":free") or (
|
||||
prompt_num == 0 and completion_num == 0 and (prompt_num is not None or completion_num is not None)
|
||||
)
|
||||
out.append(
|
||||
{
|
||||
"id": model_id,
|
||||
"name": str(item.get("name") or model_id).strip() or model_id,
|
||||
"description": description,
|
||||
"context_length": _context_length(item),
|
||||
"prompt_usd_per_token": prompt_price,
|
||||
"completion_usd_per_token": completion_price,
|
||||
"input_modalities": _modalities(item, "input"),
|
||||
"output_modalities": _modalities(item, "output"),
|
||||
"provider": provider,
|
||||
"is_free": bool(is_free),
|
||||
}
|
||||
)
|
||||
out.sort(key=lambda row: (row["name"].lower(), row["id"].lower()))
|
||||
return out
|
||||
|
||||
|
||||
def clear_openrouter_model_catalog_cache() -> None:
|
||||
with _catalog_lock:
|
||||
_catalog_cache["fetched_at"] = 0.0
|
||||
_catalog_cache["fetched_at_iso"] = None
|
||||
_catalog_cache["models"] = None
|
||||
|
||||
|
||||
def _download_openrouter_models() -> List[Dict[str, Any]]:
|
||||
url = f"{openrouter_base_url()}/models"
|
||||
headers: Dict[str, str] = {"Accept": "application/json"}
|
||||
key = (os.getenv("OPENROUTER_API_KEY") or "").strip()
|
||||
if key:
|
||||
headers["Authorization"] = f"Bearer {key}"
|
||||
referer = (os.getenv("APP_URL") or "").strip()
|
||||
if referer:
|
||||
headers["HTTP-Referer"] = referer
|
||||
title = (os.getenv("OPENROUTER_APP_TITLE") or "Shinkan Jinkendo").strip()
|
||||
if title:
|
||||
headers["X-Title"] = title
|
||||
try:
|
||||
with httpx.Client(timeout=25.0) as client:
|
||||
resp = client.get(url, headers=headers)
|
||||
except httpx.RequestError as exc:
|
||||
raise OpenRouterError("Verbindung zu OpenRouter fehlgeschlagen") from exc
|
||||
if resp.status_code >= 400:
|
||||
raise OpenRouterError(f"OpenRouter antwortet mit HTTP {resp.status_code}")
|
||||
try:
|
||||
payload = resp.json()
|
||||
except json.JSONDecodeError as exc:
|
||||
raise OpenRouterError("OpenRouter hat kein gültiges JSON geliefert") from exc
|
||||
return parse_openrouter_models_payload(payload)
|
||||
|
||||
|
||||
def fetch_openrouter_model_catalog(*, force: bool = False) -> Dict[str, Any]:
|
||||
"""Modellkatalog, zehn Minuten im Prozess zwischengespeichert."""
|
||||
now = time.monotonic()
|
||||
with _catalog_lock:
|
||||
cached = _catalog_cache.get("models")
|
||||
age = now - float(_catalog_cache.get("fetched_at") or 0)
|
||||
if isinstance(cached, list) and not force and age < _CATALOG_TTL_SEC:
|
||||
return {
|
||||
"models": cached,
|
||||
"count": len(cached),
|
||||
"cached": True,
|
||||
"stale": False,
|
||||
"fetched_at": _catalog_cache.get("fetched_at_iso"),
|
||||
}
|
||||
try:
|
||||
models = _download_openrouter_models()
|
||||
except OpenRouterError:
|
||||
with _catalog_lock:
|
||||
cached = _catalog_cache.get("models")
|
||||
if isinstance(cached, list):
|
||||
return {
|
||||
"models": cached,
|
||||
"count": len(cached),
|
||||
"cached": True,
|
||||
"stale": True,
|
||||
"fetched_at": _catalog_cache.get("fetched_at_iso"),
|
||||
}
|
||||
raise
|
||||
fetched_iso = datetime.now(timezone.utc).isoformat()
|
||||
with _catalog_lock:
|
||||
_catalog_cache["models"] = models
|
||||
_catalog_cache["fetched_at"] = time.monotonic()
|
||||
_catalog_cache["fetched_at_iso"] = fetched_iso
|
||||
return {
|
||||
"models": models,
|
||||
"count": len(models),
|
||||
"cached": False,
|
||||
"stale": False,
|
||||
"fetched_at": fetched_iso,
|
||||
}
|
||||
custom = str(row.get("openrouter_model") or "").strip()
|
||||
if custom:
|
||||
return custom
|
||||
return default_openrouter_model_id()
|
||||
@@ -21,7 +21,6 @@ from ai_prompt_planning_preview import (
|
||||
)
|
||||
from ai_prompt_runtime import render_ai_prompt_template_for_row
|
||||
from db import get_cursor, get_db, r2d
|
||||
from openrouter_chat import normalize_openrouter_model_id
|
||||
from prompt_resolver import exercise_placeholder_catalog
|
||||
from planning_prompt_variables import planning_prompt_placeholder_catalog
|
||||
|
||||
@@ -48,7 +47,7 @@ def _fetch_prompt_any(cur, prompt_id: int) -> Dict[str, Any]:
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT id, slug, display_name, description, template, category, output_format,
|
||||
output_schema, is_system_default, default_template, openrouter_model, model_role,
|
||||
output_schema, is_system_default, default_template, openrouter_model,
|
||||
active, sort_order, created_at, updated_at
|
||||
FROM ai_prompts WHERE id = %s
|
||||
""",
|
||||
@@ -96,7 +95,7 @@ def list_ai_prompts(session: dict = Depends(_require_superadmin)):
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT id, slug, display_name, description, category, output_format, active,
|
||||
sort_order, is_system_default, default_template, openrouter_model, model_role
|
||||
sort_order, is_system_default, default_template, openrouter_model
|
||||
FROM ai_prompts
|
||||
ORDER BY sort_order ASC NULLS LAST, id ASC
|
||||
"""
|
||||
@@ -162,10 +161,10 @@ def update_ai_prompt(
|
||||
|
||||
next_openrouter = old.get("openrouter_model")
|
||||
if body.openrouter_model is not None:
|
||||
try:
|
||||
next_openrouter = normalize_openrouter_model_id(body.openrouter_model)
|
||||
except ValueError as exc:
|
||||
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
||||
cand = body.openrouter_model.strip() if isinstance(body.openrouter_model, str) else ""
|
||||
if any(c in cand for c in ("\r", "\n", "\t")):
|
||||
raise HTTPException(status_code=400, detail="openrouter_model: keine Steuerzeichen erlaubt.")
|
||||
next_openrouter = cand or None
|
||||
|
||||
cur.execute(
|
||||
"""
|
||||
@@ -174,7 +173,7 @@ def update_ai_prompt(
|
||||
openrouter_model = %s, updated_at = NOW()
|
||||
WHERE id = %s
|
||||
RETURNING id, slug, display_name, description, template, category, output_format,
|
||||
output_schema, is_system_default, default_template, openrouter_model, model_role,
|
||||
output_schema, is_system_default, default_template, openrouter_model,
|
||||
active, sort_order,
|
||||
created_at, updated_at
|
||||
""",
|
||||
@@ -207,7 +206,7 @@ def reset_ai_prompt_template(prompt_id: int, session: dict = Depends(_require_su
|
||||
SET template = default_template, updated_at = NOW()
|
||||
WHERE id = %s AND default_template IS NOT NULL
|
||||
RETURNING id, slug, display_name, description, template, category, output_format,
|
||||
output_schema, is_system_default, default_template, openrouter_model, model_role,
|
||||
output_schema, is_system_default, default_template, openrouter_model,
|
||||
active, sort_order,
|
||||
created_at, updated_at
|
||||
""",
|
||||
|
||||
@@ -456,12 +456,12 @@ def submit_content_report(
|
||||
- Journaleintrag im Medien-Audit-Log (wenn target_type=media_asset)
|
||||
- E-Mail-Bestaetigung an Melder + Benachrichtigung an Plattform-Admins (best-effort)
|
||||
"""
|
||||
limiter._check_request_limit(request, _content_report_rate_marker, False)
|
||||
if not body.good_faith_confirmed:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail="Die Gutglaubenserklärung (good_faith_confirmed) muss bestätigt werden.",
|
||||
)
|
||||
limiter._check_request_limit(request, _content_report_rate_marker, False)
|
||||
|
||||
priority = "high" if body.report_reason in HIGH_PRIORITY_REASONS else "normal"
|
||||
|
||||
|
||||
@@ -1,613 +0,0 @@
|
||||
"""Distributionsfreigabe: Maschinenabruf und Redaktion.
|
||||
|
||||
Maschinenabruf authentifiziert allein über den Distributions-Schlüssel.
|
||||
# ACCESS_LAYER exempt: kein Trainer-Mandant; Kanal kommt aus der Anbindung.
|
||||
Die Redaktions- und Verwaltungsrouten nutzen TenantContext.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Optional
|
||||
|
||||
from fastapi import APIRouter, Depends, Header, HTTPException, Query
|
||||
from fastapi.responses import FileResponse, Response
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from club_tenancy import is_superadmin
|
||||
from db import get_cursor, get_db
|
||||
from distribution_contract import (
|
||||
InvalidCursor,
|
||||
cursor_secret,
|
||||
decode_cursor,
|
||||
distribution_enabled,
|
||||
)
|
||||
from distribution_service import (
|
||||
access_home,
|
||||
assert_exercise_object,
|
||||
backlog_count,
|
||||
confirm_draft,
|
||||
create_draft,
|
||||
create_named_key,
|
||||
issue_key,
|
||||
list_changes,
|
||||
list_release_drift,
|
||||
load_catalog,
|
||||
load_catalog_exercise,
|
||||
load_asset,
|
||||
load_availability,
|
||||
load_manifest,
|
||||
overview,
|
||||
resolve_bearer,
|
||||
retire_release,
|
||||
revoke_named_key,
|
||||
set_club_api,
|
||||
target_for_key,
|
||||
update_draft,
|
||||
withdraw_release,
|
||||
)
|
||||
from tenant_context import TenantContext, get_tenant_context
|
||||
|
||||
router = APIRouter(prefix="/api/distribution/v1", tags=["distribution"])
|
||||
editorial = APIRouter(tags=["distribution-editorial"])
|
||||
|
||||
NO_STORE = {"Cache-Control": "private, no-store"}
|
||||
|
||||
|
||||
def _machine(authorization: Optional[str]):
|
||||
if not distribution_enabled():
|
||||
raise HTTPException(status_code=404, detail="Nicht gefunden", headers=NO_STORE)
|
||||
if not authorization or not authorization.lower().startswith("bearer "):
|
||||
raise HTTPException(
|
||||
status_code=401,
|
||||
detail={"code": "invalid_key", "message": "Schlüssel ungültig."},
|
||||
headers=NO_STORE,
|
||||
)
|
||||
token = authorization.split(" ", 1)[1].strip()
|
||||
held: Optional[HTTPException] = None
|
||||
binding = None
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
try:
|
||||
binding = resolve_bearer(cur, token)
|
||||
except HTTPException as exc:
|
||||
held = exc
|
||||
if held is not None:
|
||||
held.headers = {**(held.headers or {}), **NO_STORE}
|
||||
raise held
|
||||
return binding
|
||||
|
||||
|
||||
def _superadmin(tenant: TenantContext) -> None:
|
||||
if not is_superadmin(tenant.global_role):
|
||||
raise HTTPException(status_code=403, detail="Nur Superadmins dürfen die Distribution verwalten.")
|
||||
|
||||
|
||||
class PublisherBody(BaseModel):
|
||||
name: str = Field(min_length=1, max_length=200)
|
||||
kind: str
|
||||
club_id: Optional[int] = None
|
||||
|
||||
|
||||
class RecipientBody(BaseModel):
|
||||
name: str = Field(min_length=1, max_length=200)
|
||||
|
||||
|
||||
class RelationshipBody(BaseModel):
|
||||
publisher_id: str
|
||||
recipient_id: str
|
||||
|
||||
|
||||
class BindingBody(BaseModel):
|
||||
recipient_id: str
|
||||
name: str = Field(min_length=1, max_length=200)
|
||||
|
||||
|
||||
class KeyBody(BaseModel):
|
||||
expires_at: Optional[str] = None
|
||||
|
||||
|
||||
class ProfileBody(BaseModel):
|
||||
profile_id: int
|
||||
|
||||
|
||||
class ExerciseAssignBody(BaseModel):
|
||||
exercise_id: int
|
||||
|
||||
|
||||
class SuspendBody(BaseModel):
|
||||
kind: str
|
||||
id: str
|
||||
|
||||
|
||||
class DraftBody(BaseModel):
|
||||
publisher_id: Optional[str] = None
|
||||
recipient_id: Optional[str] = None
|
||||
key_id: Optional[str] = None
|
||||
cut: Optional[dict] = None
|
||||
|
||||
|
||||
class AccessKeyBody(BaseModel):
|
||||
name: str = Field(min_length=1, max_length=200)
|
||||
objects: list[str]
|
||||
visibilities: list[str]
|
||||
context_kind: str = "user"
|
||||
club_id: Optional[int] = None
|
||||
club_ids: list[int] = []
|
||||
|
||||
|
||||
class ClubApiBody(BaseModel):
|
||||
enabled: bool
|
||||
|
||||
|
||||
class CutBody(BaseModel):
|
||||
cut: dict
|
||||
|
||||
|
||||
class ReasonBody(BaseModel):
|
||||
reason_code: str
|
||||
|
||||
|
||||
@router.get("/catalog")
|
||||
def get_catalog(cursor: Optional[str] = None, authorization: Optional[str] = Header(default=None)):
|
||||
binding = _machine(authorization)
|
||||
try:
|
||||
assert_exercise_object(binding.get("objects"))
|
||||
except HTTPException as exc:
|
||||
exc.headers = {**(exc.headers or {}), **NO_STORE}
|
||||
raise exc
|
||||
held: Optional[HTTPException] = None
|
||||
payload = None
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
try:
|
||||
payload = load_catalog(cur, binding, cursor)
|
||||
except InvalidCursor:
|
||||
held = HTTPException(
|
||||
status_code=400,
|
||||
detail={"code": "invalid_cursor", "message": "Cursor ungültig."},
|
||||
)
|
||||
except HTTPException as exc:
|
||||
held = exc
|
||||
else:
|
||||
conn.commit()
|
||||
if held is not None:
|
||||
held.headers = {**(held.headers or {}), **NO_STORE}
|
||||
raise held
|
||||
return Response(
|
||||
content=__import__("json").dumps(payload, ensure_ascii=False, separators=(",", ":")),
|
||||
media_type="application/json",
|
||||
headers=NO_STORE,
|
||||
)
|
||||
|
||||
|
||||
@router.get("/catalog/{source_id}")
|
||||
def get_catalog_exercise(source_id: str, authorization: Optional[str] = Header(default=None)):
|
||||
binding = _machine(authorization)
|
||||
try:
|
||||
assert_exercise_object(binding.get("objects"))
|
||||
except HTTPException as exc:
|
||||
exc.headers = {**(exc.headers or {}), **NO_STORE}
|
||||
raise exc
|
||||
held: Optional[HTTPException] = None
|
||||
payload = None
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
try:
|
||||
payload = load_catalog_exercise(cur, binding, source_id)
|
||||
except HTTPException as exc:
|
||||
held = exc
|
||||
if held is not None:
|
||||
held.headers = {**(held.headers or {}), **NO_STORE}
|
||||
raise held
|
||||
return Response(
|
||||
content=__import__("json").dumps(payload, ensure_ascii=False, separators=(",", ":")),
|
||||
media_type="application/json",
|
||||
headers=NO_STORE,
|
||||
)
|
||||
|
||||
|
||||
@router.get("/changes")
|
||||
def get_changes(
|
||||
cursor: Optional[str] = None,
|
||||
limit: Optional[int] = Query(default=None),
|
||||
authorization: Optional[str] = Header(default=None),
|
||||
):
|
||||
binding = _machine(authorization)
|
||||
if limit is None:
|
||||
limit = 50
|
||||
elif limit < 1 or limit > 100:
|
||||
raise HTTPException(status_code=400, detail={"code": "invalid_limit", "message": "limit ist 1 bis 100."}, headers=NO_STORE)
|
||||
try:
|
||||
seq = decode_cursor(cursor_secret(), binding["recipient_id"], cursor)
|
||||
except InvalidCursor:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail={"code": "invalid_cursor", "message": "Cursor ungültig."},
|
||||
headers=NO_STORE,
|
||||
)
|
||||
try:
|
||||
assert_exercise_object(binding.get("objects"))
|
||||
except HTTPException as exc:
|
||||
exc.headers = {**(exc.headers or {}), **NO_STORE}
|
||||
raise exc
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
payload = list_changes(cur, binding["recipient_id"], seq, limit, binding)
|
||||
return Response(
|
||||
content=__import__("json").dumps(payload, ensure_ascii=False, separators=(",", ":")),
|
||||
media_type="application/json",
|
||||
headers=NO_STORE,
|
||||
)
|
||||
|
||||
|
||||
@router.get("/exercises/{source_id}/availability")
|
||||
def get_availability(source_id: str, authorization: Optional[str] = Header(default=None)):
|
||||
binding = _machine(authorization)
|
||||
held: Optional[HTTPException] = None
|
||||
payload = None
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
try:
|
||||
assert_exercise_object(binding.get("objects"))
|
||||
payload = load_availability(
|
||||
cur, binding["recipient_id"], source_id, binding.get("visibilities"), binding
|
||||
)
|
||||
except HTTPException as exc:
|
||||
held = exc
|
||||
if held is not None:
|
||||
held.headers = {**(held.headers or {}), **NO_STORE}
|
||||
raise held
|
||||
return Response(
|
||||
content=__import__("json").dumps(payload, ensure_ascii=False, separators=(",", ":")),
|
||||
media_type="application/json",
|
||||
headers=NO_STORE,
|
||||
)
|
||||
|
||||
|
||||
@router.get("/releases/{release_id}")
|
||||
def get_release(release_id: str, authorization: Optional[str] = Header(default=None)):
|
||||
binding = _machine(authorization)
|
||||
held: Optional[HTTPException] = None
|
||||
body = b""
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
try:
|
||||
assert_exercise_object(binding.get("objects"))
|
||||
body = load_manifest(cur, binding["recipient_id"], release_id, binding.get("visibilities"), binding)
|
||||
except HTTPException as exc:
|
||||
held = exc
|
||||
if held is not None:
|
||||
held.headers = {**(held.headers or {}), **NO_STORE}
|
||||
raise held
|
||||
return Response(content=body, media_type="application/json", headers=NO_STORE)
|
||||
|
||||
|
||||
@router.get("/releases/{release_id}/assets/{asset_id}")
|
||||
def get_asset(release_id: str, asset_id: str, authorization: Optional[str] = Header(default=None)):
|
||||
binding = _machine(authorization)
|
||||
held: Optional[HTTPException] = None
|
||||
path = None
|
||||
media_type = "application/octet-stream"
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
try:
|
||||
assert_exercise_object(binding.get("objects"))
|
||||
path, media_type = load_asset(
|
||||
cur, binding["recipient_id"], release_id, asset_id, binding.get("visibilities"), binding
|
||||
)
|
||||
except HTTPException as exc:
|
||||
held = exc
|
||||
if held is not None:
|
||||
held.headers = {**(held.headers or {}), **NO_STORE}
|
||||
raise held
|
||||
return FileResponse(path, media_type=media_type, headers=NO_STORE)
|
||||
|
||||
|
||||
@editorial.get("/api/exercises/{exercise_id}/distribution")
|
||||
def exercise_distribution(exercise_id: int, tenant: TenantContext = Depends(get_tenant_context)):
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
return overview(cur, exercise_id, tenant.profile_id, tenant.global_role or "")
|
||||
|
||||
|
||||
@editorial.post("/api/exercises/{exercise_id}/distribution/drafts")
|
||||
def post_draft(exercise_id: int, body: DraftBody, tenant: TenantContext = Depends(get_tenant_context)):
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
from routers.exercises import _assert_can_edit_exercise
|
||||
|
||||
_assert_can_edit_exercise(cur, exercise_id, tenant)
|
||||
if body.key_id:
|
||||
publisher_id, recipient_id = target_for_key(
|
||||
cur, exercise_id, body.key_id, tenant.profile_id, tenant.global_role or ""
|
||||
)
|
||||
elif body.publisher_id and body.recipient_id:
|
||||
publisher_id, recipient_id = body.publisher_id, body.recipient_id
|
||||
else:
|
||||
raise HTTPException(status_code=400, detail="Wähle einen API-Schlüssel.")
|
||||
result = create_draft(
|
||||
cur,
|
||||
exercise_id,
|
||||
publisher_id,
|
||||
recipient_id,
|
||||
tenant.profile_id,
|
||||
tenant.global_role or "",
|
||||
body.cut,
|
||||
)
|
||||
conn.commit()
|
||||
return result
|
||||
|
||||
|
||||
@editorial.put("/api/exercises/{exercise_id}/distribution/drafts/{draft_id}")
|
||||
def put_draft(exercise_id: int, draft_id: str, body: CutBody, tenant: TenantContext = Depends(get_tenant_context)):
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
from routers.exercises import _assert_can_edit_exercise
|
||||
|
||||
_assert_can_edit_exercise(cur, exercise_id, tenant)
|
||||
result = update_draft(
|
||||
cur, exercise_id, draft_id, body.cut, tenant.profile_id, tenant.global_role or ""
|
||||
)
|
||||
conn.commit()
|
||||
return result
|
||||
|
||||
|
||||
@editorial.post("/api/exercises/{exercise_id}/distribution/drafts/{draft_id}/confirm")
|
||||
def post_confirm(exercise_id: int, draft_id: str, tenant: TenantContext = Depends(get_tenant_context)):
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
result = confirm_draft(cur, exercise_id, draft_id, tenant.profile_id, tenant.global_role or "")
|
||||
conn.commit()
|
||||
return result
|
||||
|
||||
|
||||
@editorial.post("/api/distribution/releases/{release_id}/retire")
|
||||
def post_retire(release_id: str, tenant: TenantContext = Depends(get_tenant_context)):
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
result = retire_release(cur, release_id, tenant.profile_id, tenant.global_role or "")
|
||||
conn.commit()
|
||||
return result
|
||||
|
||||
|
||||
@editorial.post("/api/distribution/releases/{release_id}/withdraw")
|
||||
def post_withdraw(release_id: str, body: ReasonBody, tenant: TenantContext = Depends(get_tenant_context)):
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
result = withdraw_release(cur, release_id, body.reason_code, tenant.profile_id, tenant.global_role or "", "release", None)
|
||||
conn.commit()
|
||||
return result
|
||||
|
||||
|
||||
@editorial.post("/api/distribution/releases/{release_id}/variants/{variant_id}/withdraw")
|
||||
def post_withdraw_variant(
|
||||
release_id: str,
|
||||
variant_id: str,
|
||||
body: ReasonBody,
|
||||
tenant: TenantContext = Depends(get_tenant_context),
|
||||
):
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
result = withdraw_release(
|
||||
cur, release_id, body.reason_code, tenant.profile_id, tenant.global_role or "", "variant", variant_id
|
||||
)
|
||||
conn.commit()
|
||||
return result
|
||||
|
||||
|
||||
@editorial.post("/api/distribution/releases/{release_id}/assets/{asset_id}/withdraw")
|
||||
def post_withdraw_asset(
|
||||
release_id: str,
|
||||
asset_id: str,
|
||||
body: ReasonBody,
|
||||
tenant: TenantContext = Depends(get_tenant_context),
|
||||
):
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
result = withdraw_release(
|
||||
cur, release_id, body.reason_code, tenant.profile_id, tenant.global_role or "", "asset", asset_id
|
||||
)
|
||||
conn.commit()
|
||||
return result
|
||||
|
||||
|
||||
@editorial.post("/api/distribution/admin/publishers")
|
||||
def post_publisher(body: PublisherBody, tenant: TenantContext = Depends(get_tenant_context)):
|
||||
_superadmin(tenant)
|
||||
if body.kind not in ("platform", "own", "club"):
|
||||
raise HTTPException(status_code=400, detail="kind ist platform, own oder club.")
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute(
|
||||
"""
|
||||
INSERT INTO distribution_publishers (name, kind, club_id)
|
||||
VALUES (%s, %s, %s)
|
||||
RETURNING id
|
||||
""",
|
||||
(body.name, body.kind, body.club_id),
|
||||
)
|
||||
row = cur.fetchone()
|
||||
conn.commit()
|
||||
return {"id": str(row["id"])}
|
||||
|
||||
|
||||
@editorial.post("/api/distribution/admin/recipients")
|
||||
def post_recipient(body: RecipientBody, tenant: TenantContext = Depends(get_tenant_context)):
|
||||
_superadmin(tenant)
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute(
|
||||
"INSERT INTO distribution_recipients (name) VALUES (%s) RETURNING id",
|
||||
(body.name,),
|
||||
)
|
||||
row = cur.fetchone()
|
||||
conn.commit()
|
||||
return {"id": str(row["id"])}
|
||||
|
||||
|
||||
@editorial.post("/api/distribution/admin/relationships")
|
||||
def post_relationship(body: RelationshipBody, tenant: TenantContext = Depends(get_tenant_context)):
|
||||
_superadmin(tenant)
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute(
|
||||
"""
|
||||
INSERT INTO distribution_relationships (publisher_id, recipient_id)
|
||||
VALUES (%s, %s)
|
||||
RETURNING id
|
||||
""",
|
||||
(body.publisher_id, body.recipient_id),
|
||||
)
|
||||
row = cur.fetchone()
|
||||
conn.commit()
|
||||
return {"id": str(row["id"])}
|
||||
|
||||
|
||||
@editorial.post("/api/distribution/admin/bindings")
|
||||
def post_binding(body: BindingBody, tenant: TenantContext = Depends(get_tenant_context)):
|
||||
_superadmin(tenant)
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute(
|
||||
"""
|
||||
INSERT INTO distribution_bindings (recipient_id, name)
|
||||
VALUES (%s, %s)
|
||||
RETURNING id
|
||||
""",
|
||||
(body.recipient_id, body.name),
|
||||
)
|
||||
row = cur.fetchone()
|
||||
conn.commit()
|
||||
return {"id": str(row["id"])}
|
||||
|
||||
|
||||
@editorial.post("/api/distribution/admin/bindings/{binding_id}/keys")
|
||||
def post_key(binding_id: str, body: KeyBody, tenant: TenantContext = Depends(get_tenant_context)):
|
||||
_superadmin(tenant)
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
result = issue_key(cur, binding_id, body.expires_at)
|
||||
conn.commit()
|
||||
return result
|
||||
|
||||
|
||||
@editorial.post("/api/distribution/admin/keys/{key_prefix}/revoke")
|
||||
def post_revoke(key_prefix: str, tenant: TenantContext = Depends(get_tenant_context)):
|
||||
_superadmin(tenant)
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute(
|
||||
"UPDATE distribution_keys SET revoked_at = NOW() WHERE key_prefix = %s AND revoked_at IS NULL",
|
||||
(key_prefix,),
|
||||
)
|
||||
conn.commit()
|
||||
return {"ok": True}
|
||||
|
||||
|
||||
@editorial.post("/api/distribution/admin/publishers/{publisher_id}/releasers")
|
||||
def post_releaser(publisher_id: str, body: ProfileBody, tenant: TenantContext = Depends(get_tenant_context)):
|
||||
_superadmin(tenant)
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute(
|
||||
"""
|
||||
INSERT INTO distribution_releasers (publisher_id, profile_id)
|
||||
VALUES (%s, %s)
|
||||
ON CONFLICT DO NOTHING
|
||||
""",
|
||||
(publisher_id, body.profile_id),
|
||||
)
|
||||
conn.commit()
|
||||
return {"ok": True}
|
||||
|
||||
|
||||
@editorial.post("/api/distribution/admin/publishers/{publisher_id}/exercises")
|
||||
def post_assign(publisher_id: str, body: ExerciseAssignBody, tenant: TenantContext = Depends(get_tenant_context)):
|
||||
_superadmin(tenant)
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute(
|
||||
"""
|
||||
INSERT INTO distribution_publisher_exercises (publisher_id, exercise_id)
|
||||
VALUES (%s, %s)
|
||||
ON CONFLICT DO NOTHING
|
||||
""",
|
||||
(publisher_id, body.exercise_id),
|
||||
)
|
||||
conn.commit()
|
||||
return {"ok": True}
|
||||
|
||||
|
||||
@editorial.post("/api/distribution/admin/suspend")
|
||||
def post_suspend(body: SuspendBody, tenant: TenantContext = Depends(get_tenant_context)):
|
||||
_superadmin(tenant)
|
||||
table = {
|
||||
"publisher": "distribution_publishers",
|
||||
"recipient": "distribution_recipients",
|
||||
"binding": "distribution_bindings",
|
||||
}.get(body.kind)
|
||||
if table is None:
|
||||
raise HTTPException(status_code=400, detail="kind ist publisher, recipient oder binding.")
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute(f"UPDATE {table} SET status = 'suspended' WHERE id = %s", (body.id,))
|
||||
conn.commit()
|
||||
return {"ok": True}
|
||||
|
||||
|
||||
@editorial.get("/api/distribution/admin/backlog")
|
||||
def get_backlog(tenant: TenantContext = Depends(get_tenant_context)):
|
||||
_superadmin(tenant)
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
return {"count": backlog_count(cur)}
|
||||
|
||||
|
||||
@editorial.get("/api/distribution/release-updates")
|
||||
def get_release_updates(tenant: TenantContext = Depends(get_tenant_context)):
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
return {"items": list_release_drift(cur, tenant.profile_id, tenant.global_role or "")}
|
||||
|
||||
|
||||
@editorial.get("/api/distribution/access")
|
||||
def get_access(tenant: TenantContext = Depends(get_tenant_context)):
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
return access_home(cur, tenant.profile_id, tenant.global_role or "")
|
||||
|
||||
|
||||
@editorial.put("/api/distribution/access/clubs/{club_id}")
|
||||
def put_club_api(club_id: int, body: ClubApiBody, tenant: TenantContext = Depends(get_tenant_context)):
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
result = set_club_api(cur, club_id, body.enabled, tenant.global_role or "")
|
||||
conn.commit()
|
||||
return result
|
||||
|
||||
|
||||
@editorial.post("/api/distribution/access/keys")
|
||||
def post_access_key(body: AccessKeyBody, tenant: TenantContext = Depends(get_tenant_context)):
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
result = create_named_key(
|
||||
cur,
|
||||
name=body.name,
|
||||
objects=body.objects,
|
||||
visibilities=body.visibilities,
|
||||
context_kind=body.context_kind,
|
||||
club_id=body.club_id,
|
||||
club_ids=body.club_ids,
|
||||
profile_id=tenant.profile_id,
|
||||
role=tenant.global_role or "",
|
||||
)
|
||||
conn.commit()
|
||||
return result
|
||||
|
||||
|
||||
@editorial.post("/api/distribution/access/keys/{key_id}/revoke")
|
||||
def post_revoke_named(key_id: str, tenant: TenantContext = Depends(get_tenant_context)):
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
result = revoke_named_key(cur, key_id, tenant.profile_id, tenant.global_role or "")
|
||||
conn.commit()
|
||||
return result
|
||||
@@ -29,7 +29,6 @@ from club_tenancy import (
|
||||
club_admin_shares_club_with_creator,
|
||||
has_club_role,
|
||||
is_platform_admin,
|
||||
is_superadmin,
|
||||
library_content_visible_to_profile,
|
||||
)
|
||||
from tenant_context import TenantContext, get_tenant_context, get_tenant_context_flexible, library_content_visibility_sql
|
||||
@@ -40,8 +39,6 @@ from ai_prompt_context import ExerciseFormAiFocusRow, ExerciseFormAiPromptContex
|
||||
from ai_prompt_job import run_exercise_form_ai_suggestion
|
||||
from account_lifecycle import assert_min_account_state
|
||||
from capabilities import probe_capability
|
||||
from distribution_contract import OFFICIAL_WRITE_DENIED, official_write_allowed
|
||||
from distribution_service import blocks_exercise_delete, blocks_media_delete, blocks_variant_delete
|
||||
from club_features import (
|
||||
consume_club_feature_with_usage,
|
||||
merge_feature_usage_into_response,
|
||||
@@ -451,11 +448,6 @@ _MAX_BULK_METADATA_IDS = 500
|
||||
_MAX_BULK_RELATION_IDS_PER_KIND = 80
|
||||
|
||||
|
||||
class ExerciseApiOfferingPatch(BaseModel):
|
||||
exercise_ids: list[int] = Field(..., min_length=1, max_length=_MAX_BULK_METADATA_IDS)
|
||||
api_offered: bool
|
||||
|
||||
|
||||
class ExerciseBulkMetadataPatch(BaseModel):
|
||||
"""Massenänderung: Sichtbarkeit/Status und/oder Zuordnungen (Kataloge)."""
|
||||
|
||||
@@ -571,13 +563,11 @@ def _assert_can_edit_exercise(cur, exercise_id: int, tenant: TenantContext) -> N
|
||||
owner = rd.get("created_by")
|
||||
if owner is not None:
|
||||
owner = int(owner)
|
||||
ex_vis = (rd.get("visibility") or "private").strip().lower()
|
||||
if not official_write_allowed(ex_vis, role):
|
||||
raise HTTPException(status_code=403, detail=OFFICIAL_WRITE_DENIED)
|
||||
if owner == profile_id:
|
||||
return
|
||||
if is_platform_admin(role):
|
||||
return
|
||||
ex_vis = (rd.get("visibility") or "private").strip().lower()
|
||||
ex_cid_raw = rd.get("club_id")
|
||||
ex_cid = int(ex_cid_raw) if ex_cid_raw is not None else None
|
||||
if ex_vis == "club" and ex_cid is not None and can_plan_in_club(cur, profile_id, ex_cid, role):
|
||||
@@ -1468,13 +1458,9 @@ def _exercise_delete_usage_message(counts: dict) -> str:
|
||||
def _assert_can_delete_exercise(cur, tenant: TenantContext, row: dict) -> None:
|
||||
pid = tenant.profile_id
|
||||
role = tenant.global_role
|
||||
vis = str(row.get("visibility") or "private").strip().lower()
|
||||
if vis == "official":
|
||||
if not is_superadmin(role):
|
||||
raise HTTPException(status_code=403, detail=OFFICIAL_WRITE_DENIED)
|
||||
return
|
||||
if is_platform_admin(role):
|
||||
return
|
||||
vis = str(row.get("visibility") or "private").strip().lower()
|
||||
cid = row.get("club_id")
|
||||
creator = row.get("created_by")
|
||||
try:
|
||||
@@ -1482,6 +1468,11 @@ def _assert_can_delete_exercise(cur, tenant: TenantContext, row: dict) -> None:
|
||||
except (TypeError, ValueError):
|
||||
creator_int = None
|
||||
|
||||
if vis == "official":
|
||||
raise HTTPException(
|
||||
status_code=403,
|
||||
detail="Globale Übungen dürfen nur von Plattform-Admins gelöscht werden.",
|
||||
)
|
||||
if vis == "club":
|
||||
try:
|
||||
ex_club = int(cid) if cid is not None else None
|
||||
@@ -1506,41 +1497,6 @@ def _assert_can_delete_exercise(cur, tenant: TenantContext, row: dict) -> None:
|
||||
)
|
||||
|
||||
|
||||
@router.patch("/exercises/api-offering")
|
||||
def patch_exercise_api_offering(
|
||||
body: ExerciseApiOfferingPatch,
|
||||
tenant: TenantContext = Depends(get_tenant_context),
|
||||
):
|
||||
"""Schaltet die aktuelle API-Bereitstellung. Rechte sind die Bearbeitungsrechte der Übung."""
|
||||
unique_ids = sorted({int(item) for item in body.exercise_ids if item is not None and int(item) > 0})
|
||||
if not unique_ids:
|
||||
raise HTTPException(status_code=400, detail="Keine gültigen Übungs-IDs")
|
||||
updated: List[Dict[str, Any]] = []
|
||||
denied: List[Dict[str, Any]] = []
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
for ex_id in unique_ids:
|
||||
cur.execute("SELECT id, title FROM exercises WHERE id = %s", (ex_id,))
|
||||
row = cur.fetchone()
|
||||
if not row:
|
||||
denied.append({"id": ex_id, "detail": "Übung nicht gefunden"})
|
||||
continue
|
||||
item = r2d(row)
|
||||
try:
|
||||
_assert_can_edit_exercise(cur, ex_id, tenant)
|
||||
except HTTPException as exc:
|
||||
detail = exc.detail if isinstance(exc.detail, str) else str(exc.detail)
|
||||
denied.append({"id": ex_id, "title": item.get("title"), "detail": detail})
|
||||
continue
|
||||
cur.execute(
|
||||
"UPDATE exercises SET api_offered = %s, updated_at = NOW() WHERE id = %s",
|
||||
(bool(body.api_offered), ex_id),
|
||||
)
|
||||
updated.append({"id": ex_id, "title": item.get("title"), "api_offered": bool(body.api_offered)})
|
||||
conn.commit()
|
||||
return {"updated": updated, "denied": denied}
|
||||
|
||||
|
||||
@router.patch("/exercises/bulk-metadata")
|
||||
def bulk_patch_exercises_metadata(
|
||||
body: ExerciseBulkMetadataPatch,
|
||||
@@ -1642,9 +1598,6 @@ def bulk_patch_exercises_metadata(
|
||||
owner = int(owner)
|
||||
|
||||
ex_vis = (rowd.get("visibility") or "private").strip().lower()
|
||||
if not official_write_allowed(ex_vis, role):
|
||||
failed.append({"id": ex_id, "detail": OFFICIAL_WRITE_DENIED})
|
||||
continue
|
||||
ex_cid_raw = rowd.get("club_id")
|
||||
ex_cid = int(ex_cid_raw) if ex_cid_raw is not None else None
|
||||
|
||||
@@ -2180,7 +2133,7 @@ def list_exercises(
|
||||
|
||||
# Query (primary_focus_name für Listen-Ansicht gemäß Spec-Beispiel „focus_area“-Label)
|
||||
query = f"""
|
||||
SELECT e.id, e.title, e.summary, e.visibility, e.status, e.api_offered,
|
||||
SELECT e.id, e.title, e.summary, e.visibility, e.status,
|
||||
e.exercise_kind, e.method_archetype,
|
||||
e.created_by, p.name as creator_name,
|
||||
e.club_id, c.name as club_name,
|
||||
@@ -2253,7 +2206,6 @@ def list_exercises(
|
||||
d["training_type_names"] = _coerce_json_str_list(d.get("training_type_names"))
|
||||
d["variant_count"] = int(d.get("variant_count") or 0)
|
||||
d["media_count"] = int(d.get("media_count") or 0)
|
||||
d["api_offered"] = bool(d.get("api_offered"))
|
||||
if include_variants:
|
||||
v = d.get("variants")
|
||||
if isinstance(v, str):
|
||||
@@ -2881,11 +2833,6 @@ def delete_exercise(
|
||||
usage_msg = _exercise_delete_usage_message(counts)
|
||||
if usage_msg:
|
||||
raise HTTPException(status_code=409, detail=usage_msg)
|
||||
if blocks_exercise_delete(cur, exercise_id):
|
||||
raise HTTPException(
|
||||
status_code=409,
|
||||
detail="Die Übung hat eine externe Freigabe und kann nicht gelöscht werden.",
|
||||
)
|
||||
|
||||
cur.execute("DELETE FROM exercises WHERE id = %s", (exercise_id,))
|
||||
conn.commit()
|
||||
@@ -3093,11 +3040,6 @@ def delete_exercise_variant(
|
||||
cur = get_cursor(conn)
|
||||
_assert_can_edit_exercise(cur, exercise_id, tenant)
|
||||
assert_exercise_not_combination(cur, exercise_id)
|
||||
if blocks_variant_delete(cur, variant_id):
|
||||
raise HTTPException(
|
||||
status_code=409,
|
||||
detail="Die Variante ist Teil einer externen Freigabe und kann nicht gelöscht werden.",
|
||||
)
|
||||
_fetch_variant_row(cur, exercise_id, variant_id)
|
||||
|
||||
cur.execute(
|
||||
@@ -3898,11 +3840,6 @@ def delete_exercise_media(
|
||||
row = cur.fetchone()
|
||||
if not row:
|
||||
raise HTTPException(status_code=404, detail="Medium nicht gefunden")
|
||||
if blocks_media_delete(cur, media_id):
|
||||
raise HTTPException(
|
||||
status_code=409,
|
||||
detail="Das Medium ist Teil einer externen Freigabe und kann nicht gelöst werden.",
|
||||
)
|
||||
rec = r2d(row)
|
||||
media_asset_id = rec.get("media_asset_id")
|
||||
if media_asset_id:
|
||||
|
||||
@@ -1,312 +0,0 @@
|
||||
"""
|
||||
Superadmin: OpenRouter-Modellkatalog und Plattform-Standardmodell.
|
||||
|
||||
# ACCESS_LAYER exempt: Plattform-KI-Konfiguration ohne Vereinsbezug;
|
||||
# require_auth + is_superadmin, kein TenantContext.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any, Optional
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query
|
||||
from pydantic import BaseModel, ConfigDict, Field
|
||||
|
||||
from auth import require_auth
|
||||
from club_tenancy import is_superadmin
|
||||
from db import get_cursor, get_db, r2d
|
||||
from ai_model_roles import ROLE_KEYS, resolve_prompt_openrouter_model
|
||||
from openrouter_chat import (
|
||||
OpenRouterError,
|
||||
env_openrouter_model_id,
|
||||
fetch_openrouter_model_catalog,
|
||||
normalize_openrouter_model_id,
|
||||
resolve_default_openrouter_model_id,
|
||||
)
|
||||
|
||||
router = APIRouter(tags=["admin_openrouter"])
|
||||
|
||||
|
||||
def _require_superadmin(session: dict = Depends(require_auth)) -> dict:
|
||||
role = (session.get("role") or "").strip().lower()
|
||||
if not is_superadmin(role):
|
||||
raise HTTPException(status_code=403, detail="Nur Superadmins")
|
||||
return session
|
||||
|
||||
|
||||
class OpenRouterSettingsUpdate(BaseModel):
|
||||
openrouter_model: Optional[str] = Field(None, max_length=200)
|
||||
|
||||
|
||||
class OpenRouterRoleUpdate(BaseModel):
|
||||
openrouter_model: Optional[str] = Field(None, max_length=200)
|
||||
|
||||
|
||||
class OpenRouterPromptRoleUpdate(BaseModel):
|
||||
model_config = ConfigDict(protected_namespaces=())
|
||||
model_role: Optional[str] = Field(None, max_length=40)
|
||||
|
||||
|
||||
def _iso(value: Any) -> Optional[str]:
|
||||
if value is None:
|
||||
return None
|
||||
if hasattr(value, "isoformat"):
|
||||
return value.isoformat()
|
||||
text = str(value).strip()
|
||||
return text or None
|
||||
|
||||
|
||||
def _settings_payload(stored: Optional[str], updated_at: Any = None) -> dict:
|
||||
effective, source = resolve_default_openrouter_model_id(stored)
|
||||
return {
|
||||
"openrouter_model": stored or None,
|
||||
"effective_model": effective,
|
||||
"env_model": env_openrouter_model_id(),
|
||||
"source": source,
|
||||
"updated_at": _iso(updated_at),
|
||||
}
|
||||
|
||||
|
||||
def _missing_table(exc: Exception) -> bool:
|
||||
text = str(exc).lower()
|
||||
return "platform_ai_settings" in text or "does not exist" in text or "undefinedtable" in text
|
||||
|
||||
|
||||
@router.get("/api/admin/openrouter/settings")
|
||||
def get_openrouter_settings(session: dict = Depends(_require_superadmin)):
|
||||
try:
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute(
|
||||
"SELECT openrouter_model, updated_at FROM platform_ai_settings WHERE id = 1"
|
||||
)
|
||||
row = r2d(cur.fetchone())
|
||||
except Exception as exc:
|
||||
if _missing_table(exc):
|
||||
raise HTTPException(
|
||||
status_code=503,
|
||||
detail="Tabelle platform_ai_settings fehlt. Migration 097 ausführen.",
|
||||
) from exc
|
||||
raise
|
||||
if not row:
|
||||
return _settings_payload(None, None)
|
||||
stored = str(row.get("openrouter_model") or "").strip() or None
|
||||
return _settings_payload(stored, row.get("updated_at"))
|
||||
|
||||
|
||||
@router.put("/api/admin/openrouter/settings")
|
||||
def put_openrouter_settings(
|
||||
body: OpenRouterSettingsUpdate,
|
||||
session: dict = Depends(_require_superadmin),
|
||||
):
|
||||
try:
|
||||
model = normalize_openrouter_model_id(body.openrouter_model)
|
||||
except ValueError as exc:
|
||||
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
||||
profile_id = session.get("profile_id")
|
||||
try:
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute(
|
||||
"""
|
||||
INSERT INTO platform_ai_settings (id, openrouter_model, updated_at, updated_by_profile_id)
|
||||
VALUES (1, %s, NOW(), %s)
|
||||
ON CONFLICT (id) DO UPDATE
|
||||
SET openrouter_model = EXCLUDED.openrouter_model,
|
||||
updated_at = NOW(),
|
||||
updated_by_profile_id = EXCLUDED.updated_by_profile_id
|
||||
RETURNING openrouter_model, updated_at
|
||||
""",
|
||||
(model, profile_id),
|
||||
)
|
||||
row = r2d(cur.fetchone())
|
||||
except Exception as exc:
|
||||
if _missing_table(exc):
|
||||
raise HTTPException(
|
||||
status_code=503,
|
||||
detail="Tabelle platform_ai_settings fehlt. Migration 097 ausführen.",
|
||||
) from exc
|
||||
raise
|
||||
if not row:
|
||||
raise HTTPException(status_code=500, detail="platform_ai_settings konnte nicht gespeichert werden.")
|
||||
stored = str(row.get("openrouter_model") or "").strip() or None
|
||||
return _settings_payload(stored, row.get("updated_at"))
|
||||
|
||||
|
||||
def _prompt_view(row: dict, role_models: dict, platform_model: Optional[str], env_model: str) -> dict:
|
||||
prompt_model = str(row.get("openrouter_model") or "").strip() or None
|
||||
role_key = str(row.get("model_role") or "").strip() or None
|
||||
effective, source = resolve_prompt_openrouter_model(
|
||||
prompt_model=prompt_model,
|
||||
role_model=role_models.get(role_key or ""),
|
||||
platform_model=platform_model,
|
||||
env_model=env_model,
|
||||
)
|
||||
return {
|
||||
"id": row.get("id"),
|
||||
"slug": row.get("slug"),
|
||||
"display_name": row.get("display_name"),
|
||||
"model_role": role_key,
|
||||
"openrouter_model": prompt_model,
|
||||
"effective_model": effective,
|
||||
"source": source,
|
||||
}
|
||||
|
||||
|
||||
def _load_role_overview(cur) -> dict:
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT role_key, display_name, description, openrouter_model, sort_order
|
||||
FROM platform_ai_model_roles
|
||||
ORDER BY sort_order ASC, role_key ASC
|
||||
"""
|
||||
)
|
||||
role_rows = [r2d(r) if not isinstance(r, dict) else r for r in cur.fetchall()]
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT id, slug, display_name, model_role, openrouter_model, sort_order
|
||||
FROM ai_prompts
|
||||
ORDER BY sort_order ASC NULLS LAST, id ASC
|
||||
"""
|
||||
)
|
||||
prompt_rows = [r2d(r) if not isinstance(r, dict) else r for r in cur.fetchall()]
|
||||
cur.execute("SELECT openrouter_model FROM platform_ai_settings WHERE id = 1")
|
||||
settings = r2d(cur.fetchone())
|
||||
platform_model = str((settings or {}).get("openrouter_model") or "").strip() or None
|
||||
env_model = env_openrouter_model_id()
|
||||
role_models = {
|
||||
str(row.get("role_key") or ""): str(row.get("openrouter_model") or "").strip() or None
|
||||
for row in role_rows
|
||||
}
|
||||
prompts = [_prompt_view(row, role_models, platform_model, env_model) for row in prompt_rows]
|
||||
roles = []
|
||||
for row in role_rows:
|
||||
key = str(row.get("role_key") or "")
|
||||
stored = role_models.get(key)
|
||||
effective, source = resolve_prompt_openrouter_model(
|
||||
prompt_model=None,
|
||||
role_model=stored,
|
||||
platform_model=platform_model,
|
||||
env_model=env_model,
|
||||
)
|
||||
roles.append(
|
||||
{
|
||||
"role_key": key,
|
||||
"display_name": row.get("display_name"),
|
||||
"description": row.get("description"),
|
||||
"openrouter_model": stored,
|
||||
"effective_model": effective,
|
||||
"source": source,
|
||||
"prompts": [p for p in prompts if p.get("model_role") == key],
|
||||
}
|
||||
)
|
||||
return {
|
||||
"roles": roles,
|
||||
"unassigned": [p for p in prompts if not p.get("model_role")],
|
||||
"platform_model": platform_model,
|
||||
"env_model": env_model,
|
||||
}
|
||||
|
||||
|
||||
@router.get("/api/admin/openrouter/roles")
|
||||
def get_openrouter_roles(session: dict = Depends(_require_superadmin)):
|
||||
try:
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
return _load_role_overview(cur)
|
||||
except Exception as exc:
|
||||
if _missing_table(exc) or "platform_ai_model_roles" in str(exc).lower():
|
||||
raise HTTPException(
|
||||
status_code=503,
|
||||
detail="Tabelle platform_ai_model_roles fehlt. Migration 098 ausführen.",
|
||||
) from exc
|
||||
raise
|
||||
|
||||
|
||||
@router.put("/api/admin/openrouter/roles/{role_key}")
|
||||
def put_openrouter_role(
|
||||
role_key: str,
|
||||
body: OpenRouterRoleUpdate,
|
||||
session: dict = Depends(_require_superadmin),
|
||||
):
|
||||
key = (role_key or "").strip()
|
||||
if key not in ROLE_KEYS:
|
||||
raise HTTPException(status_code=404, detail="Unbekannte Aufgabengruppe.")
|
||||
try:
|
||||
model = normalize_openrouter_model_id(body.openrouter_model)
|
||||
except ValueError as exc:
|
||||
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
||||
profile_id = session.get("profile_id")
|
||||
try:
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute(
|
||||
"""
|
||||
UPDATE platform_ai_model_roles
|
||||
SET openrouter_model = %s, updated_at = NOW(), updated_by_profile_id = %s
|
||||
WHERE role_key = %s
|
||||
RETURNING role_key
|
||||
""",
|
||||
(model, profile_id, key),
|
||||
)
|
||||
updated = cur.fetchone()
|
||||
if not updated:
|
||||
raise HTTPException(status_code=404, detail="Aufgabengruppe fehlt.")
|
||||
return _load_role_overview(cur)
|
||||
except HTTPException:
|
||||
raise
|
||||
except Exception as exc:
|
||||
if "platform_ai_model_roles" in str(exc).lower() or _missing_table(exc):
|
||||
raise HTTPException(
|
||||
status_code=503,
|
||||
detail="Tabelle platform_ai_model_roles fehlt. Migration 098 ausführen.",
|
||||
) from exc
|
||||
raise
|
||||
|
||||
|
||||
@router.put("/api/admin/openrouter/prompts/{prompt_id}/role")
|
||||
def put_openrouter_prompt_role(
|
||||
prompt_id: int,
|
||||
body: OpenRouterPromptRoleUpdate,
|
||||
session: dict = Depends(_require_superadmin),
|
||||
):
|
||||
role = str(body.model_role or "").strip() or None
|
||||
if role and role not in ROLE_KEYS:
|
||||
raise HTTPException(status_code=400, detail="Unbekannte Aufgabengruppe.")
|
||||
try:
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute(
|
||||
"""
|
||||
UPDATE ai_prompts
|
||||
SET model_role = %s, updated_at = NOW()
|
||||
WHERE id = %s
|
||||
RETURNING id
|
||||
""",
|
||||
(role, prompt_id),
|
||||
)
|
||||
if not cur.fetchone():
|
||||
raise HTTPException(status_code=404, detail="Prompt nicht gefunden.")
|
||||
return _load_role_overview(cur)
|
||||
except HTTPException:
|
||||
raise
|
||||
except Exception as exc:
|
||||
if "model_role" in str(exc).lower() or "platform_ai_model_roles" in str(exc).lower():
|
||||
raise HTTPException(
|
||||
status_code=503,
|
||||
detail="Aufgabengruppen fehlen. Migration 098 ausführen.",
|
||||
) from exc
|
||||
raise
|
||||
|
||||
|
||||
@router.get("/api/admin/openrouter/models")
|
||||
def list_openrouter_models(
|
||||
refresh: bool = Query(False),
|
||||
session: dict = Depends(_require_superadmin),
|
||||
):
|
||||
try:
|
||||
return fetch_openrouter_model_catalog(force=refresh)
|
||||
except OpenRouterError as exc:
|
||||
raise HTTPException(
|
||||
status_code=502,
|
||||
detail=f"OpenRouter-Modellliste nicht erreichbar: {exc}",
|
||||
) from exc
|
||||
@@ -25,7 +25,6 @@ EXEMPT_ROUTERS: frozenset[str] = frozenset(
|
||||
"legal_documents.py", # ACCESS_LAYER exempt: Plattform-Rechtstexte ohne Vereinsbezug; öffentlicher Endpoint ohne Auth, Admin-Endpoints require_auth + is_superadmin()
|
||||
"ai_skill_retrieval_admin.py", # Superadmin-Plattform-Konfiguration Skill-KI-Retrieval; require_auth + is_superadmin — kein Vereinsmandant
|
||||
"ai_prompts_admin.py", # Superadmin ai_prompts; require_auth + is_superadmin — kein Vereinsmandant
|
||||
"openrouter_admin.py", # Superadmin OpenRouter-Modell; require_auth + is_superadmin — kein Vereinsmandant
|
||||
"exercise_enrichment_admin.py", # Superadmin Batch-Übungs-Anreicherung KI; require_auth + is_superadmin — kein Vereinsmandant
|
||||
"admin_user_content.py", # Superadmin Moderation nutzerangelegter Inhalte; require_auth + is_superadmin — kein Vereinsmandant
|
||||
"admin_rights.py", # Superadmin Rollen/Rechte (Capabilities, Kontingent-Bypass, Pläne); require_auth + is_superadmin — kein Vereinsmandant
|
||||
|
||||
@@ -2,12 +2,12 @@
|
||||
"""
|
||||
Automatische Medien-Retention (Papierkorb Stufe 1→2, Purge wenn fällig).
|
||||
|
||||
Einzellauf (der tägliche Planer ist media_retention_scheduler.py):
|
||||
Lauf z. B. täglich per Cron:
|
||||
cd /path/to/backend && python scripts/media_retention_job.py
|
||||
|
||||
Umgebung wie Backend (DB_*), optional:
|
||||
MEDIA_TRASH_SOFT_TO_HIDDEN_DAYS (Default 30)
|
||||
MEDIA_TRASH_HIDDEN_TO_PURGE_DAYS (Default 30)
|
||||
MEDIA_TRASH_HIDDEN_TO_PURGE_DAYS (Default 90)
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
|
||||
@@ -1,121 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Täglicher Start von media_retention_job.py um 03:00 Europe/Berlin.
|
||||
|
||||
Der Prozess löscht beim Start nichts. Ein Lauf sofort nach dem Start nur mit
|
||||
RETENTION_RUN_ON_START=1. Ein fehlgeschlagener Lauf bleibt im Log
|
||||
(RETENTION_FAIL); der Prozess bleibt aktiv, damit Docker ihn nicht sofort
|
||||
erneut startet.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
from datetime import datetime, timedelta
|
||||
from zoneinfo import ZoneInfo
|
||||
|
||||
LOG = logging.getLogger("retention.scheduler")
|
||||
|
||||
DEFAULT_TZ = "Europe/Berlin"
|
||||
_RUN_ON_START = "RETENTION_RUN_ON_START"
|
||||
_TZ_ENV = "RETENTION_TZ"
|
||||
|
||||
|
||||
def retention_zone() -> ZoneInfo:
|
||||
name = os.environ.get(_TZ_ENV, DEFAULT_TZ).strip() or DEFAULT_TZ
|
||||
return ZoneInfo(name)
|
||||
|
||||
|
||||
def next_run_at(now: datetime, *, hour: int = 3) -> datetime:
|
||||
"""Nächste Uhrzeit `hour`:00 in der Zeitzone von `now`.
|
||||
|
||||
`now` muss zeitzonenbewusst sein. Die Zone von `now` ist die Planungszone.
|
||||
"""
|
||||
if now.tzinfo is None:
|
||||
raise ValueError("now muss eine Zeitzone tragen")
|
||||
zone = now.tzinfo
|
||||
local = now.astimezone(zone)
|
||||
day = local.date()
|
||||
target = datetime(day.year, day.month, day.day, hour, 0, 0, tzinfo=zone)
|
||||
if target.timestamp() <= local.timestamp():
|
||||
day = day + timedelta(days=1)
|
||||
target = datetime(day.year, day.month, day.day, hour, 0, 0, tzinfo=zone)
|
||||
return target
|
||||
|
||||
|
||||
def seconds_until_next_0300(now: datetime, *, hour: int = 3) -> float:
|
||||
"""Sekunden bis zum nächsten Lauf, als absolute Dauer.
|
||||
|
||||
`target - now` zieht bei gleicher tzinfo die Wanduhr ab und liegt an
|
||||
Umstellungstagen um eine Stunde daneben. `timestamp()` rechnet in UTC.
|
||||
"""
|
||||
target = next_run_at(now, hour=hour)
|
||||
local = now.astimezone(target.tzinfo)
|
||||
return target.timestamp() - local.timestamp()
|
||||
|
||||
|
||||
def _job_path() -> str:
|
||||
return os.path.join(os.path.dirname(os.path.abspath(__file__)), "media_retention_job.py")
|
||||
|
||||
|
||||
def _run_on_start() -> bool:
|
||||
return os.environ.get(_RUN_ON_START, "").strip() == "1"
|
||||
|
||||
|
||||
def run_job() -> int:
|
||||
"""Startet den Retention-Job. Führt keine Löschung in diesem Prozess aus."""
|
||||
LOG.info("Retention-Lauf startet")
|
||||
completed = subprocess.run([sys.executable, "-u", _job_path()], check=False)
|
||||
if completed.returncode != 0:
|
||||
LOG.error("RETENTION_FAIL exit=%s", completed.returncode)
|
||||
else:
|
||||
LOG.info("RETENTION_OK")
|
||||
return int(completed.returncode)
|
||||
|
||||
|
||||
def serve(
|
||||
*,
|
||||
iterations: int | None = None,
|
||||
sleep=time.sleep,
|
||||
clock=None,
|
||||
run=None,
|
||||
) -> None:
|
||||
zone = retention_zone()
|
||||
if clock is None:
|
||||
def clock() -> datetime:
|
||||
return datetime.now(zone)
|
||||
|
||||
execute = run if run is not None else run_job
|
||||
if _run_on_start():
|
||||
LOG.info("Sofortlauf wegen RETENTION_RUN_ON_START=1")
|
||||
execute()
|
||||
|
||||
completed = 0
|
||||
while iterations is None or completed < iterations:
|
||||
target = next_run_at(clock())
|
||||
LOG.info("Nächster Retention-Lauf %s", target.isoformat(timespec="seconds"))
|
||||
while True:
|
||||
remaining = target.timestamp() - clock().timestamp()
|
||||
if remaining <= 1:
|
||||
break
|
||||
LOG.info("Warte %.0f Sekunden bis %s", remaining, target.isoformat(timespec="seconds"))
|
||||
sleep(remaining)
|
||||
execute()
|
||||
completed += 1
|
||||
|
||||
|
||||
def main() -> int:
|
||||
logging.basicConfig(
|
||||
level=logging.INFO,
|
||||
format="%(asctime)s %(levelname)s %(message)s",
|
||||
stream=sys.stdout,
|
||||
force=True,
|
||||
)
|
||||
serve()
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -1,493 +0,0 @@
|
||||
{
|
||||
"fixture_version": 1,
|
||||
"note": "Synthetische Inhalte ohne produktive Rechte. Die Medienbytes dienen der Testung von Groesse und Hash. Sie sind keine abspielbare Filmdatei.",
|
||||
"manifest_serialization": "UTF-8, JSON ohne Leerraum, Reihenfolge der Felder aus manifest, kein abschliessender Zeilenumbruch",
|
||||
"channels": {
|
||||
"lara_felix": {
|
||||
"recipient_id": "caa20000-0000-4000-8000-0000000001f5",
|
||||
"events": [
|
||||
{
|
||||
"event_id": "caa20000-0000-4000-8000-000000000258",
|
||||
"type": "release.published",
|
||||
"release_id": "caa20000-0000-4000-8000-0000000000c9",
|
||||
"occurred_at": "2026-11-23T09:01:00Z",
|
||||
"source_id": "caa20000-0000-4000-8000-00000000000a",
|
||||
"revision": 1,
|
||||
"manifest_sha256": "fcebc8c4db56328a55dc7f350e705822cef19f02392f26625274e68c0abc239c"
|
||||
},
|
||||
{
|
||||
"event_id": "caa20000-0000-4000-8000-000000000259",
|
||||
"type": "release.published",
|
||||
"release_id": "caa20000-0000-4000-8000-0000000000ca",
|
||||
"occurred_at": "2026-11-23T09:02:00Z",
|
||||
"source_id": "caa20000-0000-4000-8000-00000000000b",
|
||||
"revision": 1,
|
||||
"manifest_sha256": "7dad43afb3077fb2d9fb3aa490bb91daf53f175c06575d648411021d352a1744"
|
||||
},
|
||||
{
|
||||
"event_id": "caa20000-0000-4000-8000-00000000025a",
|
||||
"type": "release.published",
|
||||
"release_id": "caa20000-0000-4000-8000-0000000000cb",
|
||||
"occurred_at": "2026-11-23T09:03:00Z",
|
||||
"source_id": "caa20000-0000-4000-8000-00000000000a",
|
||||
"revision": 2,
|
||||
"manifest_sha256": "f0c8051cee6feb0e6399f1bc5681e0ef1ecd640c1cbe6b634c5df1c1b1df9ed0"
|
||||
},
|
||||
{
|
||||
"event_id": "caa20000-0000-4000-8000-00000000025b",
|
||||
"type": "release.retired",
|
||||
"release_id": "caa20000-0000-4000-8000-0000000000c9",
|
||||
"occurred_at": "2026-11-23T09:04:00Z"
|
||||
},
|
||||
{
|
||||
"event_id": "caa20000-0000-4000-8000-00000000025c",
|
||||
"type": "asset.withdrawn",
|
||||
"release_id": "caa20000-0000-4000-8000-0000000000c9",
|
||||
"occurred_at": "2026-11-23T09:05:00Z",
|
||||
"target_id": "caa20000-0000-4000-8000-00000000012c",
|
||||
"reason_code": "rights"
|
||||
},
|
||||
{
|
||||
"event_id": "caa20000-0000-4000-8000-00000000025d",
|
||||
"type": "asset.withdrawn",
|
||||
"release_id": "caa20000-0000-4000-8000-0000000000cb",
|
||||
"occurred_at": "2026-11-23T09:05:00Z",
|
||||
"target_id": "caa20000-0000-4000-8000-00000000012c",
|
||||
"reason_code": "rights"
|
||||
}
|
||||
]
|
||||
},
|
||||
"zweiter_verein": {
|
||||
"recipient_id": "caa20000-0000-4000-8000-0000000001f6",
|
||||
"events": [
|
||||
{
|
||||
"event_id": "caa20000-0000-4000-8000-0000000002bc",
|
||||
"type": "release.published",
|
||||
"release_id": "caa20000-0000-4000-8000-0000000000cc",
|
||||
"occurred_at": "2026-11-23T09:03:00Z",
|
||||
"source_id": "caa20000-0000-4000-8000-00000000000c",
|
||||
"revision": 1,
|
||||
"manifest_sha256": "3e34007864d308ac1cf6b555bb7fd00dd6962fb6f396eca16492ace0fec59603"
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"releases": {
|
||||
"vereinsfassung_1": {
|
||||
"channel": "lara_felix",
|
||||
"manifest_sha256": "fcebc8c4db56328a55dc7f350e705822cef19f02392f26625274e68c0abc239c",
|
||||
"manifest": {
|
||||
"schema_version": 1,
|
||||
"resource_type": "exercise",
|
||||
"release_id": "caa20000-0000-4000-8000-0000000000c9",
|
||||
"source_id": "caa20000-0000-4000-8000-00000000000a",
|
||||
"revision": 1,
|
||||
"publisher_id": "caa20000-0000-4000-8000-00000000177a",
|
||||
"published_at": "2026-11-23T09:01:00Z",
|
||||
"exercise": {
|
||||
"title": "Raum und Wege wahrnehmen",
|
||||
"audience": "Kursleitungen",
|
||||
"rights_id": "caa20000-0000-4000-8000-000000000191",
|
||||
"parts": [
|
||||
{
|
||||
"id": "caa20000-0000-4000-8000-000000000065",
|
||||
"role": "goal",
|
||||
"text": "Die Gruppe nimmt freie Wege im Raum wahr.",
|
||||
"rights_id": "caa20000-0000-4000-8000-000000000191"
|
||||
},
|
||||
{
|
||||
"id": "caa20000-0000-4000-8000-000000000066",
|
||||
"role": "instructions",
|
||||
"text": "Die Kursleitung legt Karten aus und bespricht die freien Wege.",
|
||||
"rights_id": "caa20000-0000-4000-8000-000000000191"
|
||||
},
|
||||
{
|
||||
"id": "caa20000-0000-4000-8000-000000000067",
|
||||
"role": "trainer_notes",
|
||||
"text": "Vorab genug Platz vorsehen.",
|
||||
"rights_id": "caa20000-0000-4000-8000-000000000191"
|
||||
},
|
||||
{
|
||||
"id": "caa20000-0000-4000-8000-000000000068",
|
||||
"role": "instructions",
|
||||
"text": "Den kurzen Film ansehen und danach die gezeigten Wege vergleichen.",
|
||||
"rights_id": "caa20000-0000-4000-8000-000000000191"
|
||||
}
|
||||
],
|
||||
"assets": [
|
||||
{
|
||||
"id": "caa20000-0000-4000-8000-00000000012c",
|
||||
"role": "demonstration",
|
||||
"media_type": "video/mp4",
|
||||
"size_bytes": 32,
|
||||
"sha256": "0fb807ef5ec44b003f181dfa9ce317becbcfd5755ebf91a57702d2024df2b915",
|
||||
"rights_id": "caa20000-0000-4000-8000-000000000192",
|
||||
"label": "Demonstrationsfilm"
|
||||
}
|
||||
],
|
||||
"common_part_ids": [
|
||||
"caa20000-0000-4000-8000-000000000065",
|
||||
"caa20000-0000-4000-8000-000000000067"
|
||||
],
|
||||
"common_asset_ids": [],
|
||||
"variants": [
|
||||
{
|
||||
"id": "caa20000-0000-4000-8000-00000000006b",
|
||||
"label": "Kartenvariante",
|
||||
"part_ids": [
|
||||
"caa20000-0000-4000-8000-000000000066"
|
||||
],
|
||||
"asset_ids": []
|
||||
},
|
||||
{
|
||||
"id": "caa20000-0000-4000-8000-00000000006c",
|
||||
"label": "Filmvariante",
|
||||
"part_ids": [
|
||||
"caa20000-0000-4000-8000-000000000068"
|
||||
],
|
||||
"asset_ids": [
|
||||
"caa20000-0000-4000-8000-00000000012c"
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
"rights": [
|
||||
{
|
||||
"id": "caa20000-0000-4000-8000-000000000191",
|
||||
"evidence_ref": "test-textrechte",
|
||||
"actions": [
|
||||
"store",
|
||||
"render",
|
||||
"grant_customer_use",
|
||||
"commercial_course_use"
|
||||
],
|
||||
"territories": [
|
||||
"DE"
|
||||
],
|
||||
"valid_from": "2026-11-23T09:00:00Z",
|
||||
"valid_until": null
|
||||
},
|
||||
{
|
||||
"id": "caa20000-0000-4000-8000-000000000192",
|
||||
"evidence_ref": "test-filmrechte",
|
||||
"actions": [
|
||||
"store",
|
||||
"stream",
|
||||
"course_display",
|
||||
"grant_customer_use",
|
||||
"commercial_course_use"
|
||||
],
|
||||
"territories": [
|
||||
"DE"
|
||||
],
|
||||
"valid_from": "2026-11-23T09:00:00Z",
|
||||
"valid_until": null
|
||||
}
|
||||
]
|
||||
},
|
||||
"synthetic_asset_base64_by_id": {
|
||||
"caa20000-0000-4000-8000-00000000012c": "U2hpbmthbiBkaXN0cmlidXRpb24gZml4dHVyZSB2MQo="
|
||||
}
|
||||
},
|
||||
"eigener_bestand": {
|
||||
"channel": "lara_felix",
|
||||
"manifest_sha256": "7dad43afb3077fb2d9fb3aa490bb91daf53f175c06575d648411021d352a1744",
|
||||
"manifest": {
|
||||
"schema_version": 1,
|
||||
"resource_type": "exercise",
|
||||
"release_id": "caa20000-0000-4000-8000-0000000000ca",
|
||||
"source_id": "caa20000-0000-4000-8000-00000000000b",
|
||||
"revision": 1,
|
||||
"publisher_id": "caa20000-0000-4000-8000-00000000177b",
|
||||
"published_at": "2026-11-23T09:02:00Z",
|
||||
"exercise": {
|
||||
"title": "Aufmerksam im Raum ankommen",
|
||||
"audience": "Kursleitungen",
|
||||
"rights_id": "caa20000-0000-4000-8000-000000000191",
|
||||
"parts": [
|
||||
{
|
||||
"id": "caa20000-0000-4000-8000-00000000006f",
|
||||
"role": "goal",
|
||||
"text": "Die Gruppe nimmt freie Wege im Raum wahr.",
|
||||
"rights_id": "caa20000-0000-4000-8000-000000000191"
|
||||
},
|
||||
{
|
||||
"id": "caa20000-0000-4000-8000-000000000070",
|
||||
"role": "instructions",
|
||||
"text": "Die Kursleitung legt Karten aus und bespricht die freien Wege.",
|
||||
"rights_id": "caa20000-0000-4000-8000-000000000191"
|
||||
},
|
||||
{
|
||||
"id": "caa20000-0000-4000-8000-000000000071",
|
||||
"role": "trainer_notes",
|
||||
"text": "Vorab genug Platz vorsehen.",
|
||||
"rights_id": "caa20000-0000-4000-8000-000000000191"
|
||||
}
|
||||
],
|
||||
"assets": [],
|
||||
"common_part_ids": [
|
||||
"caa20000-0000-4000-8000-00000000006f",
|
||||
"caa20000-0000-4000-8000-000000000071"
|
||||
],
|
||||
"common_asset_ids": [],
|
||||
"variants": [
|
||||
{
|
||||
"id": "caa20000-0000-4000-8000-000000000075",
|
||||
"label": "Kartenvariante",
|
||||
"part_ids": [
|
||||
"caa20000-0000-4000-8000-000000000070"
|
||||
],
|
||||
"asset_ids": []
|
||||
}
|
||||
]
|
||||
},
|
||||
"rights": [
|
||||
{
|
||||
"id": "caa20000-0000-4000-8000-000000000191",
|
||||
"evidence_ref": "test-textrechte",
|
||||
"actions": [
|
||||
"store",
|
||||
"render",
|
||||
"grant_customer_use",
|
||||
"commercial_course_use"
|
||||
],
|
||||
"territories": [
|
||||
"DE"
|
||||
],
|
||||
"valid_from": "2026-11-23T09:00:00Z",
|
||||
"valid_until": null
|
||||
}
|
||||
]
|
||||
},
|
||||
"synthetic_asset_base64_by_id": {}
|
||||
},
|
||||
"vereinsfassung_2": {
|
||||
"channel": "lara_felix",
|
||||
"manifest_sha256": "f0c8051cee6feb0e6399f1bc5681e0ef1ecd640c1cbe6b634c5df1c1b1df9ed0",
|
||||
"manifest": {
|
||||
"schema_version": 1,
|
||||
"resource_type": "exercise",
|
||||
"release_id": "caa20000-0000-4000-8000-0000000000cb",
|
||||
"source_id": "caa20000-0000-4000-8000-00000000000a",
|
||||
"revision": 2,
|
||||
"publisher_id": "caa20000-0000-4000-8000-00000000177a",
|
||||
"published_at": "2026-11-23T09:03:00Z",
|
||||
"exercise": {
|
||||
"title": "Raum und Wege wahrnehmen",
|
||||
"audience": "Kursleitungen",
|
||||
"rights_id": "caa20000-0000-4000-8000-000000000191",
|
||||
"parts": [
|
||||
{
|
||||
"id": "caa20000-0000-4000-8000-000000000065",
|
||||
"role": "goal",
|
||||
"text": "Die Gruppe nimmt freie Wege im Raum wahr.",
|
||||
"rights_id": "caa20000-0000-4000-8000-000000000191"
|
||||
},
|
||||
{
|
||||
"id": "caa20000-0000-4000-8000-000000000066",
|
||||
"role": "instructions",
|
||||
"text": "Die Kursleitung legt Karten aus und bespricht die freien Wege.",
|
||||
"rights_id": "caa20000-0000-4000-8000-000000000191"
|
||||
},
|
||||
{
|
||||
"id": "caa20000-0000-4000-8000-000000000067",
|
||||
"role": "trainer_notes",
|
||||
"text": "Vorab genug Platz vorsehen und die Laufwege gemeinsam prüfen.",
|
||||
"rights_id": "caa20000-0000-4000-8000-000000000191"
|
||||
},
|
||||
{
|
||||
"id": "caa20000-0000-4000-8000-000000000068",
|
||||
"role": "instructions",
|
||||
"text": "Den kurzen Film ansehen und danach die gezeigten Wege vergleichen.",
|
||||
"rights_id": "caa20000-0000-4000-8000-000000000191"
|
||||
}
|
||||
],
|
||||
"assets": [
|
||||
{
|
||||
"id": "caa20000-0000-4000-8000-00000000012c",
|
||||
"role": "demonstration",
|
||||
"media_type": "video/mp4",
|
||||
"size_bytes": 32,
|
||||
"sha256": "0fb807ef5ec44b003f181dfa9ce317becbcfd5755ebf91a57702d2024df2b915",
|
||||
"rights_id": "caa20000-0000-4000-8000-000000000192",
|
||||
"label": "Demonstrationsfilm"
|
||||
}
|
||||
],
|
||||
"common_part_ids": [
|
||||
"caa20000-0000-4000-8000-000000000065",
|
||||
"caa20000-0000-4000-8000-000000000067"
|
||||
],
|
||||
"common_asset_ids": [],
|
||||
"variants": [
|
||||
{
|
||||
"id": "caa20000-0000-4000-8000-00000000006b",
|
||||
"label": "Kartenvariante",
|
||||
"part_ids": [
|
||||
"caa20000-0000-4000-8000-000000000066"
|
||||
],
|
||||
"asset_ids": []
|
||||
},
|
||||
{
|
||||
"id": "caa20000-0000-4000-8000-00000000006c",
|
||||
"label": "Filmvariante",
|
||||
"part_ids": [
|
||||
"caa20000-0000-4000-8000-000000000068"
|
||||
],
|
||||
"asset_ids": [
|
||||
"caa20000-0000-4000-8000-00000000012c"
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
"rights": [
|
||||
{
|
||||
"id": "caa20000-0000-4000-8000-000000000191",
|
||||
"evidence_ref": "test-textrechte",
|
||||
"actions": [
|
||||
"store",
|
||||
"render",
|
||||
"grant_customer_use",
|
||||
"commercial_course_use"
|
||||
],
|
||||
"territories": [
|
||||
"DE"
|
||||
],
|
||||
"valid_from": "2026-11-23T09:00:00Z",
|
||||
"valid_until": null
|
||||
},
|
||||
{
|
||||
"id": "caa20000-0000-4000-8000-000000000192",
|
||||
"evidence_ref": "test-filmrechte",
|
||||
"actions": [
|
||||
"store",
|
||||
"stream",
|
||||
"course_display",
|
||||
"grant_customer_use",
|
||||
"commercial_course_use"
|
||||
],
|
||||
"territories": [
|
||||
"DE"
|
||||
],
|
||||
"valid_from": "2026-11-23T09:00:00Z",
|
||||
"valid_until": null
|
||||
}
|
||||
]
|
||||
},
|
||||
"synthetic_asset_base64_by_id": {
|
||||
"caa20000-0000-4000-8000-00000000012c": "U2hpbmthbiBkaXN0cmlidXRpb24gZml4dHVyZSB2MQo="
|
||||
}
|
||||
},
|
||||
"zweiter_verein": {
|
||||
"channel": "zweiter_verein",
|
||||
"manifest_sha256": "3e34007864d308ac1cf6b555bb7fd00dd6962fb6f396eca16492ace0fec59603",
|
||||
"manifest": {
|
||||
"schema_version": 1,
|
||||
"resource_type": "exercise",
|
||||
"release_id": "caa20000-0000-4000-8000-0000000000cc",
|
||||
"source_id": "caa20000-0000-4000-8000-00000000000c",
|
||||
"revision": 1,
|
||||
"publisher_id": "caa20000-0000-4000-8000-00000000177c",
|
||||
"published_at": "2026-11-23T09:03:00Z",
|
||||
"exercise": {
|
||||
"title": "Gemeinsam den Raum erkunden",
|
||||
"audience": "Kursleitungen",
|
||||
"rights_id": "caa20000-0000-4000-8000-000000000191",
|
||||
"parts": [
|
||||
{
|
||||
"id": "caa20000-0000-4000-8000-000000000079",
|
||||
"role": "goal",
|
||||
"text": "Die Gruppe nimmt freie Wege im Raum wahr.",
|
||||
"rights_id": "caa20000-0000-4000-8000-000000000191"
|
||||
},
|
||||
{
|
||||
"id": "caa20000-0000-4000-8000-00000000007a",
|
||||
"role": "instructions",
|
||||
"text": "Die Kursleitung legt Karten aus und bespricht die freien Wege.",
|
||||
"rights_id": "caa20000-0000-4000-8000-000000000191"
|
||||
},
|
||||
{
|
||||
"id": "caa20000-0000-4000-8000-00000000007b",
|
||||
"role": "trainer_notes",
|
||||
"text": "Vorab genug Platz vorsehen.",
|
||||
"rights_id": "caa20000-0000-4000-8000-000000000191"
|
||||
}
|
||||
],
|
||||
"assets": [],
|
||||
"common_part_ids": [
|
||||
"caa20000-0000-4000-8000-000000000079",
|
||||
"caa20000-0000-4000-8000-00000000007b"
|
||||
],
|
||||
"common_asset_ids": [],
|
||||
"variants": [
|
||||
{
|
||||
"id": "caa20000-0000-4000-8000-00000000007f",
|
||||
"label": "Kartenvariante",
|
||||
"part_ids": [
|
||||
"caa20000-0000-4000-8000-00000000007a"
|
||||
],
|
||||
"asset_ids": []
|
||||
}
|
||||
]
|
||||
},
|
||||
"rights": [
|
||||
{
|
||||
"id": "caa20000-0000-4000-8000-000000000191",
|
||||
"evidence_ref": "test-textrechte",
|
||||
"actions": [
|
||||
"store",
|
||||
"render",
|
||||
"grant_customer_use",
|
||||
"commercial_course_use"
|
||||
],
|
||||
"territories": [
|
||||
"DE"
|
||||
],
|
||||
"valid_from": "2026-11-23T09:00:00Z",
|
||||
"valid_until": null
|
||||
}
|
||||
]
|
||||
},
|
||||
"synthetic_asset_base64_by_id": {}
|
||||
}
|
||||
},
|
||||
"plans": {
|
||||
"plan_a_mit_film": {
|
||||
"release_id": "caa20000-0000-4000-8000-0000000000c9",
|
||||
"variant_id": "caa20000-0000-4000-8000-00000000006c"
|
||||
},
|
||||
"plan_b_mit_karten": {
|
||||
"release_id": "caa20000-0000-4000-8000-0000000000c9",
|
||||
"variant_id": "caa20000-0000-4000-8000-00000000006b"
|
||||
},
|
||||
"plan_c_mit_film_neuere_fassung": {
|
||||
"release_id": "caa20000-0000-4000-8000-0000000000cb",
|
||||
"variant_id": "caa20000-0000-4000-8000-00000000006c"
|
||||
},
|
||||
"plan_d_eigener_bestand": {
|
||||
"release_id": "caa20000-0000-4000-8000-0000000000ca",
|
||||
"variant_id": "caa20000-0000-4000-8000-000000000075"
|
||||
}
|
||||
},
|
||||
"expected": {
|
||||
"plan_binding_after_revision": {
|
||||
"release_id": "caa20000-0000-4000-8000-0000000000c9",
|
||||
"variant_id": "caa20000-0000-4000-8000-00000000006c"
|
||||
},
|
||||
"blocked_plans_after_withdrawal": [
|
||||
"plan_a_mit_film",
|
||||
"plan_c_mit_film_neuere_fassung"
|
||||
],
|
||||
"available_plans_after_withdrawal": [
|
||||
"plan_b_mit_karten",
|
||||
"plan_d_eigener_bestand"
|
||||
],
|
||||
"lara_felix_can_retrieve_after_withdrawal": [
|
||||
"caa20000-0000-4000-8000-0000000000ca"
|
||||
],
|
||||
"zweiter_verein_can_retrieve": [
|
||||
"caa20000-0000-4000-8000-0000000000cc"
|
||||
],
|
||||
"course_film_allowed": true,
|
||||
"film_download_allowed": false
|
||||
}
|
||||
}
|
||||
@@ -1,435 +0,0 @@
|
||||
"""Vertrag v1, Referenzfall, Rollen und Bestätigung nach Rückzug."""
|
||||
from __future__ import annotations
|
||||
|
||||
import inspect
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import pytest
|
||||
from fastapi import HTTPException
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
os.environ.setdefault("SKIP_DB_MIGRATE", "1")
|
||||
|
||||
from auth import require_auth
|
||||
from distribution_service import _lock_recipient, release_keys_for_exercise
|
||||
from distribution_contract import (
|
||||
InvalidCursor,
|
||||
actions_cover,
|
||||
cursor_secret,
|
||||
decide_confirm,
|
||||
decode_cursor,
|
||||
encode_cursor,
|
||||
exercise_offerable,
|
||||
package_state,
|
||||
scope_denial,
|
||||
manifest_bytes,
|
||||
official_write_allowed,
|
||||
plan_available,
|
||||
rate_decision,
|
||||
catalog_available,
|
||||
catalog_changes,
|
||||
catalog_document,
|
||||
catalog_hash,
|
||||
changed_areas,
|
||||
release_denial,
|
||||
retrievable_release_ids,
|
||||
sha256_bytes,
|
||||
)
|
||||
from main import app
|
||||
from routers.exercises import _assert_can_edit_exercise
|
||||
from tenant_context import TenantContext, get_tenant_context
|
||||
|
||||
# Liegt im Backend-Baum, weil Pytest im API-Image läuft und dort kein Repo-docs-Ordner existiert.
|
||||
FIXTURE = json.loads(
|
||||
(Path(__file__).resolve().parent / "fixtures" / "Shinkan_Lara_Felix_Referenzfall_v1.json").read_text(encoding="utf-8")
|
||||
)
|
||||
|
||||
|
||||
def test_fixture_manifest_hashes_match_contract_order() -> None:
|
||||
for release in FIXTURE["releases"].values():
|
||||
body = manifest_bytes(release["manifest"])
|
||||
assert sha256_bytes(body) == release["manifest_sha256"]
|
||||
assert not body.endswith(b"\n")
|
||||
|
||||
|
||||
def test_reference_case_retrieval_and_plan_effect() -> None:
|
||||
lara_events = FIXTURE["channels"]["lara_felix"]["events"]
|
||||
second_events = FIXTURE["channels"]["zweiter_verein"]["events"]
|
||||
assert retrievable_release_ids(lara_events) == set(FIXTURE["expected"]["lara_felix_can_retrieve_after_withdrawal"])
|
||||
assert retrievable_release_ids(second_events) == set(FIXTURE["expected"]["zweiter_verein_can_retrieve"])
|
||||
manifests = {item["manifest"]["release_id"]: item["manifest"] for item in FIXTURE["releases"].values()}
|
||||
blocked = []
|
||||
available = []
|
||||
for name, plan in FIXTURE["plans"].items():
|
||||
if plan_available(plan, manifests[plan["release_id"]], lara_events):
|
||||
available.append(name)
|
||||
else:
|
||||
blocked.append(name)
|
||||
assert set(blocked) == set(FIXTURE["expected"]["blocked_plans_after_withdrawal"])
|
||||
assert set(available) == set(FIXTURE["expected"]["available_plans_after_withdrawal"])
|
||||
film_actions = FIXTURE["releases"]["vereinsfassung_1"]["manifest"]["rights"][1]["actions"]
|
||||
assert actions_cover(film_actions, ["stream", "course_display", "commercial_course_use"]) is FIXTURE["expected"]["course_film_allowed"]
|
||||
assert ("download" in film_actions) is FIXTURE["expected"]["film_download_allowed"]
|
||||
|
||||
|
||||
def test_replay_keeps_release_id_and_explicit_reconfirm_mints_a_new_one() -> None:
|
||||
drafts: dict[str, str] = {}
|
||||
releases: dict[str, dict] = {}
|
||||
events: list[tuple[str, str]] = []
|
||||
|
||||
def confirm(draft_id: str, revision: int, cut: str) -> tuple[str, bool]:
|
||||
release_id, created = decide_confirm(drafts.get(draft_id), f"rel-{len(releases) + 1}")
|
||||
if created:
|
||||
drafts[draft_id] = release_id
|
||||
releases[release_id] = {"withdrawn": False, "revision": revision, "cut": cut}
|
||||
events.append(("published", release_id))
|
||||
return release_id, created
|
||||
|
||||
first, created = confirm("draft-1", 1, "same-cut")
|
||||
again, replayed = confirm("draft-1", 1, "same-cut")
|
||||
assert first == again
|
||||
assert created is True
|
||||
assert replayed is False
|
||||
assert events == [("published", first)]
|
||||
|
||||
releases[first]["withdrawn"] = True
|
||||
second, created_again = confirm("draft-2", 1, "same-cut")
|
||||
assert created_again is True
|
||||
assert second != first
|
||||
assert releases[first]["withdrawn"] is True
|
||||
assert releases[second]["revision"] == 1
|
||||
assert releases[second]["cut"] == "same-cut"
|
||||
assert [kind for kind, _ in events] == ["published", "published"]
|
||||
|
||||
|
||||
def test_key_scope_follows_the_role_context() -> None:
|
||||
assert scope_denial("user", ["exercise"], ["official", "club", "private"]) is None
|
||||
assert scope_denial("personal", ["exercise"], ["private"]) is None
|
||||
assert scope_denial("personal", ["exercise"], ["official"])
|
||||
assert scope_denial("club", ["exercise", "framework"], ["club", "private"]) is None
|
||||
assert scope_denial("club", ["exercise"], ["official"])
|
||||
assert scope_denial("platform", ["training_plan"], ["official", "private"]) is None
|
||||
assert scope_denial("platform", [], ["official"])
|
||||
|
||||
|
||||
def test_availability_keeps_the_copy_and_stops_new_offers() -> None:
|
||||
assert package_state(fetch_blocked=False, retired=False) == "available"
|
||||
assert package_state(fetch_blocked=False, retired=True) == "retired"
|
||||
assert package_state(fetch_blocked=True, retired=True) == "withdrawn"
|
||||
status, offerable = exercise_offerable("approved", ["available"])
|
||||
assert status == "approved" and offerable is True
|
||||
status, offerable = exercise_offerable("archived", ["available"])
|
||||
assert status == "archived" and offerable is False
|
||||
status, offerable = exercise_offerable(None, ["withdrawn"])
|
||||
assert status == "deleted" and offerable is False
|
||||
status, offerable = exercise_offerable("approved", ["retired", "withdrawn"])
|
||||
assert offerable is False
|
||||
|
||||
|
||||
def test_cursor_is_bound_to_recipient() -> None:
|
||||
secret = cursor_secret()
|
||||
token = encode_cursor(secret, "recipient-a", 4)
|
||||
assert decode_cursor(secret, "recipient-a", token) == 4
|
||||
assert decode_cursor(secret, "recipient-a", None) == 0
|
||||
with pytest.raises(InvalidCursor):
|
||||
decode_cursor(secret, "recipient-b", token)
|
||||
|
||||
|
||||
def test_rate_window_blocks_at_sixty() -> None:
|
||||
hits, blocked = rate_decision(59, 10)
|
||||
assert hits == 60 and blocked is False
|
||||
hits, blocked = rate_decision(60, 10)
|
||||
assert blocked is True
|
||||
hits, blocked = rate_decision(60, 61)
|
||||
assert hits == 1 and blocked is False
|
||||
|
||||
|
||||
def test_official_release_and_edit_roles() -> None:
|
||||
assert official_write_allowed("official", "superadmin") is True
|
||||
assert official_write_allowed("official", "admin") is False
|
||||
assert official_write_allowed("official", "club_admin") is False
|
||||
assert official_write_allowed("club", "admin") is True
|
||||
assert release_denial(
|
||||
visibility="official",
|
||||
role="admin",
|
||||
publisher_kind="platform",
|
||||
is_owner=True,
|
||||
is_club_admin=False,
|
||||
)
|
||||
assert release_denial(
|
||||
visibility="official",
|
||||
role="superadmin",
|
||||
publisher_kind="platform",
|
||||
is_owner=False,
|
||||
is_club_admin=False,
|
||||
) is None
|
||||
assert release_denial(
|
||||
visibility="private",
|
||||
role="trainer",
|
||||
publisher_kind="own",
|
||||
is_owner=True,
|
||||
is_club_admin=False,
|
||||
) is None
|
||||
assert release_denial(
|
||||
visibility="private",
|
||||
role="admin",
|
||||
publisher_kind="own",
|
||||
is_owner=False,
|
||||
is_club_admin=False,
|
||||
)
|
||||
assert release_denial(
|
||||
visibility="club",
|
||||
role="trainer",
|
||||
publisher_kind="club",
|
||||
is_owner=True,
|
||||
is_club_admin=False,
|
||||
publisher_club_id=4,
|
||||
exercise_club_id=4,
|
||||
)
|
||||
assert release_denial(
|
||||
visibility="club",
|
||||
role="trainer",
|
||||
publisher_kind="club",
|
||||
is_owner=False,
|
||||
is_club_admin=True,
|
||||
publisher_club_id=4,
|
||||
exercise_club_id=4,
|
||||
) is None
|
||||
assert release_denial(
|
||||
visibility="club",
|
||||
role="trainer",
|
||||
publisher_kind="club",
|
||||
is_owner=False,
|
||||
is_club_admin=True,
|
||||
publisher_club_id=9,
|
||||
exercise_club_id=4,
|
||||
)
|
||||
|
||||
|
||||
def _tenant(role: str, profile_id: int = 7) -> TenantContext:
|
||||
return TenantContext(
|
||||
profile_id=profile_id,
|
||||
global_role=role,
|
||||
effective_club_id=None,
|
||||
club_ids=frozenset(),
|
||||
memberships=[],
|
||||
)
|
||||
|
||||
|
||||
def test_assert_edit_rejects_admin_and_club_role_for_official() -> None:
|
||||
cur = MagicMock()
|
||||
cur.fetchone.return_value = {"created_by": 7, "visibility": "official", "club_id": None}
|
||||
for role in ("admin", "trainer", "club_admin"):
|
||||
with pytest.raises(HTTPException) as caught:
|
||||
_assert_can_edit_exercise(cur, 3, _tenant(role))
|
||||
assert caught.value.status_code == 403
|
||||
_assert_can_edit_exercise(cur, 3, _tenant("superadmin", profile_id=1))
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def client() -> TestClient:
|
||||
return TestClient(app)
|
||||
|
||||
|
||||
def test_distribution_read_is_hidden_while_disabled(client: TestClient, monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
monkeypatch.delenv("DISTRIBUTION_ENABLED", raising=False)
|
||||
response = client.get("/api/distribution/v1/changes", headers={"Authorization": "Bearer shk.abc.def"})
|
||||
assert response.status_code == 404
|
||||
assert response.headers.get("cache-control") == "private, no-store"
|
||||
|
||||
|
||||
def test_cursor_secret_uses_database_password_in_production(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
monkeypatch.setenv("ENVIRONMENT", "production")
|
||||
monkeypatch.delenv("DISTRIBUTION_CURSOR_SECRET", raising=False)
|
||||
monkeypatch.setenv("DB_PASSWORD", "prod-db-secret")
|
||||
first = cursor_secret()
|
||||
assert first != "shinkan-distribution-dev-cursor"
|
||||
assert "prod-db-secret" not in first
|
||||
assert cursor_secret() == first
|
||||
monkeypatch.setenv("DISTRIBUTION_CURSOR_SECRET", "explicit")
|
||||
assert cursor_secret() == "explicit"
|
||||
|
||||
|
||||
def test_cursor_secret_requires_material_in_production(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
monkeypatch.setenv("ENVIRONMENT", "production")
|
||||
monkeypatch.delenv("DISTRIBUTION_CURSOR_SECRET", raising=False)
|
||||
monkeypatch.delenv("DB_PASSWORD", raising=False)
|
||||
with pytest.raises(RuntimeError):
|
||||
cursor_secret()
|
||||
|
||||
|
||||
class _DroppingCursor:
|
||||
"""Ein neues execute verwirft ein noch nicht gelesenes Ergebnis, wie psycopg2."""
|
||||
|
||||
def __init__(self, key: dict) -> None:
|
||||
self._key = key
|
||||
self._pending = None
|
||||
|
||||
def execute(self, sql, _params=None):
|
||||
if self._pending is not None:
|
||||
raise AssertionError("Ergebnis wurde vor dem Lesen überschrieben")
|
||||
self._pending = [self._key] if "FROM distribution_keys" in sql else []
|
||||
|
||||
def fetchall(self):
|
||||
rows = self._pending
|
||||
self._pending = None
|
||||
return rows or []
|
||||
|
||||
def fetchone(self):
|
||||
rows = self.fetchall()
|
||||
return rows[0] if rows else None
|
||||
|
||||
|
||||
def test_release_screen_keeps_the_application_key() -> None:
|
||||
key = {
|
||||
"id": "key-1",
|
||||
"label": "Lara",
|
||||
"context_kind": "user",
|
||||
"context_club_id": None,
|
||||
"context_profile_id": 7,
|
||||
"club_ids": [3],
|
||||
"recipient_id": "rec-1",
|
||||
"api_enabled": True,
|
||||
}
|
||||
cur = _DroppingCursor(key)
|
||||
keys, block = release_keys_for_exercise(
|
||||
cur,
|
||||
{"visibility": "official", "club_id": None, "created_by": 7},
|
||||
7,
|
||||
"superadmin",
|
||||
)
|
||||
assert block is None
|
||||
assert [item["label"] for item in keys] == ["Lara"]
|
||||
|
||||
|
||||
def _catalog_exercise() -> dict:
|
||||
return {
|
||||
"public_id": "11111111-1111-1111-1111-111111111111",
|
||||
"title": "Stand",
|
||||
"summary": "",
|
||||
"goal": "Sehen",
|
||||
"execution": "Weg",
|
||||
"preparation": "",
|
||||
"trainer_notes": "",
|
||||
"equipment": None,
|
||||
"duration_min": None,
|
||||
"duration_max": None,
|
||||
}
|
||||
|
||||
|
||||
def test_catalog_reports_variant_and_media_order_changes() -> None:
|
||||
exercise = _catalog_exercise()
|
||||
base_variant = [{"id": 1, "public_id": "var-1", "variant_name": "Karte", "description": "", "execution_changes": "Alt", "sequence_order": 1}]
|
||||
base_media = [
|
||||
{"id": 1, "public_id": "med-1", "media_type": "image", "title": "A", "sort_order": 1},
|
||||
{"id": 2, "public_id": "med-2", "media_type": "image", "title": "B", "sort_order": 2},
|
||||
]
|
||||
original = catalog_hash(catalog_document(exercise, base_variant, base_media))
|
||||
changed_variant = [{**base_variant[0], "execution_changes": "Neu"}]
|
||||
reordered = [base_media[1] | {"sort_order": 1}, base_media[0] | {"sort_order": 2}]
|
||||
assert catalog_hash(catalog_document(exercise, changed_variant, base_media)) != original
|
||||
assert catalog_hash(catalog_document(exercise, base_variant, reordered)) != original
|
||||
assert catalog_hash(catalog_document(exercise, base_variant, base_media)) == original
|
||||
source = exercise["public_id"]
|
||||
assert catalog_changes({source: original}, {source: original}) == []
|
||||
updated = catalog_hash(catalog_document(exercise, changed_variant, base_media))
|
||||
assert catalog_changes({source: original}, {source: updated}) == [
|
||||
{"source_id": source, "change": "updated", "content_hash": updated}
|
||||
]
|
||||
assert catalog_changes({source: original}, {}) == [{"source_id": source, "change": "removed"}]
|
||||
assert catalog_changes({}, {source: original}) == [
|
||||
{"source_id": source, "change": "added", "content_hash": original}
|
||||
]
|
||||
|
||||
|
||||
def test_catalog_keeps_stored_html() -> None:
|
||||
exercise = _catalog_exercise()
|
||||
exercise["execution"] = "<p>Stand aufrecht.</p><p>Drehe die <strong>Hüfte</strong>.</p><br><ul><li>eins</li><li>zwei</li></ul>"
|
||||
exercise["goal"] = "<script>alert(1)</script><p>Sehen</p>"
|
||||
variant = [{
|
||||
"id": 1,
|
||||
"public_id": "var-1",
|
||||
"variant_name": "Karte",
|
||||
"description": "Kurzer Text",
|
||||
"execution_changes": "<p>Langsamer.</p><p>Mit Partner.</p>",
|
||||
"sequence_order": 1,
|
||||
}]
|
||||
document = catalog_document(exercise, variant, [])
|
||||
assert document["text_format"] == "html"
|
||||
assert document["execution"] == "<p>Stand aufrecht.</p><p>Drehe die <strong>Hüfte</strong>.</p><br><ul><li>eins</li><li>zwei</li></ul>"
|
||||
assert document["goal"] == "<p>Sehen</p>"
|
||||
assert "<script>" not in document["goal"]
|
||||
assert document["variants"][0]["description"] == "Kurzer Text"
|
||||
assert document["variants"][0]["execution_changes"] == "<p>Langsamer.</p><p>Mit Partner.</p>"
|
||||
assert catalog_hash(catalog_document(exercise, variant, [])) == catalog_hash(document)
|
||||
|
||||
|
||||
def test_catalog_hides_unselected_and_out_of_scope_exercises() -> None:
|
||||
assert catalog_available(True, True) is True
|
||||
assert catalog_available(False, True) is False
|
||||
assert catalog_available(True, False) is False
|
||||
|
||||
|
||||
def test_changed_areas_names_the_edited_instruction() -> None:
|
||||
exercise = {
|
||||
"title": "Stand",
|
||||
"summary": "",
|
||||
"goal": "Sehen",
|
||||
"execution": "Neuer Weg",
|
||||
"preparation": "",
|
||||
"trainer_notes": "",
|
||||
"equipment": None,
|
||||
"duration_min": None,
|
||||
"duration_max": None,
|
||||
}
|
||||
manifest = {
|
||||
"exercise": {
|
||||
"title": "Stand",
|
||||
"summary": None,
|
||||
"parts": [
|
||||
{"role": "goal", "text": "Sehen"},
|
||||
{"role": "instructions", "text": "Alter Weg"},
|
||||
],
|
||||
"variants": [{"id": "v", "label": "Standard"}],
|
||||
"assets": [],
|
||||
}
|
||||
}
|
||||
assert changed_areas(exercise, [], [], manifest) == ["Durchführung"]
|
||||
exercise["execution"] = "Alter Weg"
|
||||
assert changed_areas(exercise, [], [], manifest) == []
|
||||
|
||||
|
||||
def test_channel_sequence_is_locked() -> None:
|
||||
assert "FOR UPDATE" in inspect.getsource(_lock_recipient)
|
||||
|
||||
|
||||
def test_variant_and_media_routes_reject_admin_on_official(client: TestClient) -> None:
|
||||
app.dependency_overrides[require_auth] = lambda: {"profile_id": 4, "role": "admin"}
|
||||
app.dependency_overrides[get_tenant_context] = lambda: _tenant("admin", 4)
|
||||
mock_cur = MagicMock()
|
||||
mock_cur.fetchone.return_value = {"created_by": 4, "visibility": "official", "club_id": None}
|
||||
mock_cm = MagicMock()
|
||||
mock_cm.__enter__.return_value = MagicMock()
|
||||
mock_cm.__exit__.return_value = False
|
||||
try:
|
||||
with patch("routers.exercises.get_db", return_value=mock_cm), patch(
|
||||
"routers.exercises.get_cursor", return_value=mock_cur
|
||||
):
|
||||
variant = client.post(
|
||||
"/api/exercises/9/variants",
|
||||
headers={"X-Auth-Token": "t"},
|
||||
json={"variant_name": "Kartenweg"},
|
||||
)
|
||||
media = client.post(
|
||||
"/api/exercises/9/media/from-asset",
|
||||
headers={"X-Auth-Token": "t"},
|
||||
json={"media_asset_id": 3},
|
||||
)
|
||||
assert variant.status_code == 403
|
||||
assert media.status_code == 403
|
||||
finally:
|
||||
app.dependency_overrides.pop(require_auth, None)
|
||||
app.dependency_overrides.pop(get_tenant_context, None)
|
||||
@@ -1,167 +0,0 @@
|
||||
"""Scheduler für den Papierkorb-Job: 03:00 Europe/Berlin, ohne echten Löschlauf."""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from datetime import datetime, timedelta
|
||||
from pathlib import Path
|
||||
from zoneinfo import ZoneInfo
|
||||
|
||||
import pytest
|
||||
|
||||
from scripts.media_retention_scheduler import (
|
||||
next_run_at,
|
||||
run_job,
|
||||
seconds_until_next_0300,
|
||||
serve,
|
||||
)
|
||||
|
||||
BERLIN = ZoneInfo("Europe/Berlin")
|
||||
|
||||
|
||||
def _compose_file() -> Path | None:
|
||||
"""Repo-Root lokal. Im Backend-Image liegt nur /app, ohne docker-compose.yml."""
|
||||
for parent in Path(__file__).resolve().parents:
|
||||
candidate = parent / "docker-compose.yml"
|
||||
if candidate.is_file():
|
||||
return candidate
|
||||
return None
|
||||
|
||||
|
||||
def test_winter_afternoon_waits_until_next_morning() -> None:
|
||||
now = datetime(2026, 1, 15, 10, 0, tzinfo=BERLIN)
|
||||
assert next_run_at(now).isoformat() == "2026-01-16T03:00:00+01:00"
|
||||
assert seconds_until_next_0300(now) == 17 * 3600
|
||||
|
||||
|
||||
def test_summer_before_three_is_same_morning() -> None:
|
||||
now = datetime(2026, 7, 15, 2, 0, tzinfo=BERLIN)
|
||||
assert next_run_at(now).isoformat() == "2026-07-15T03:00:00+02:00"
|
||||
assert seconds_until_next_0300(now) == 3600
|
||||
|
||||
|
||||
def test_exactly_0300_waits_until_next_day() -> None:
|
||||
now = datetime(2026, 1, 15, 3, 0, tzinfo=BERLIN)
|
||||
assert next_run_at(now).isoformat() == "2026-01-16T03:00:00+01:00"
|
||||
assert seconds_until_next_0300(now) == 24 * 3600
|
||||
|
||||
|
||||
def test_spring_forward_sleeps_absolute_22_hours() -> None:
|
||||
now = datetime(2026, 3, 28, 4, 0, tzinfo=BERLIN)
|
||||
target = next_run_at(now)
|
||||
assert target.isoformat() == "2026-03-29T03:00:00+02:00"
|
||||
assert seconds_until_next_0300(now) == 22 * 3600
|
||||
assert (target - now).total_seconds() == 23 * 3600
|
||||
|
||||
|
||||
def test_fall_back_sleeps_absolute_24_hours() -> None:
|
||||
now = datetime(2026, 10, 24, 4, 0, tzinfo=BERLIN)
|
||||
target = next_run_at(now)
|
||||
assert target.isoformat() == "2026-10-25T03:00:00+01:00"
|
||||
assert seconds_until_next_0300(now) == 24 * 3600
|
||||
assert (target - now).total_seconds() == 23 * 3600
|
||||
|
||||
|
||||
def test_naive_datetime_is_rejected() -> None:
|
||||
with pytest.raises(ValueError):
|
||||
next_run_at(datetime(2026, 1, 15, 10, 0))
|
||||
|
||||
|
||||
def test_serve_sleeps_before_first_run(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
monkeypatch.delenv("RETENTION_RUN_ON_START", raising=False)
|
||||
state = {"now": datetime(2026, 1, 15, 10, 0, tzinfo=BERLIN)}
|
||||
events: list[tuple] = []
|
||||
|
||||
def clock() -> datetime:
|
||||
return state["now"]
|
||||
|
||||
def sleep(seconds: float) -> None:
|
||||
events.append(("sleep", seconds))
|
||||
state["now"] = state["now"] + timedelta(seconds=seconds)
|
||||
|
||||
def run() -> None:
|
||||
events.append(("run",))
|
||||
|
||||
serve(iterations=1, sleep=sleep, clock=clock, run=run)
|
||||
assert events == [("sleep", 17 * 3600), ("run",)]
|
||||
|
||||
|
||||
def test_serve_can_run_once_on_start(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
monkeypatch.setenv("RETENTION_RUN_ON_START", "1")
|
||||
state = {"now": datetime(2026, 7, 15, 2, 0, tzinfo=BERLIN)}
|
||||
events: list[str] = []
|
||||
|
||||
def sleep(seconds: float) -> None:
|
||||
events.append("sleep")
|
||||
state["now"] = state["now"] + timedelta(seconds=seconds)
|
||||
|
||||
serve(
|
||||
iterations=1,
|
||||
sleep=sleep,
|
||||
clock=lambda: state["now"],
|
||||
run=lambda: events.append("run"),
|
||||
)
|
||||
assert events == ["run", "sleep", "run"]
|
||||
|
||||
|
||||
def test_serve_continues_after_failed_run(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
monkeypatch.delenv("RETENTION_RUN_ON_START", raising=False)
|
||||
state = {"now": datetime(2026, 1, 15, 10, 0, tzinfo=BERLIN)}
|
||||
runs: list[int] = []
|
||||
|
||||
def sleep(seconds: float) -> None:
|
||||
state["now"] = state["now"] + timedelta(seconds=seconds)
|
||||
|
||||
def run() -> int:
|
||||
runs.append(1)
|
||||
return 1
|
||||
|
||||
serve(iterations=2, sleep=sleep, clock=lambda: state["now"], run=run)
|
||||
assert runs == [1, 1]
|
||||
|
||||
|
||||
def test_run_job_logs_failure_without_starting_real_job(
|
||||
monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
|
||||
) -> None:
|
||||
class Done:
|
||||
returncode = 1
|
||||
|
||||
monkeypatch.setattr(
|
||||
"scripts.media_retention_scheduler.subprocess.run",
|
||||
lambda *args, **kwargs: Done(),
|
||||
)
|
||||
with caplog.at_level(logging.INFO, logger="retention.scheduler"):
|
||||
assert run_job() == 1
|
||||
assert "RETENTION_FAIL exit=1" in caplog.text
|
||||
|
||||
|
||||
def test_run_job_logs_success(
|
||||
monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
|
||||
) -> None:
|
||||
class Done:
|
||||
returncode = 0
|
||||
|
||||
seen: list[list[str]] = []
|
||||
|
||||
def fake_run(cmd, check=False):
|
||||
seen.append(list(cmd))
|
||||
return Done()
|
||||
|
||||
monkeypatch.setattr("scripts.media_retention_scheduler.subprocess.run", fake_run)
|
||||
with caplog.at_level(logging.INFO, logger="retention.scheduler"):
|
||||
assert run_job() == 0
|
||||
assert seen and seen[0][-1].endswith("media_retention_job.py")
|
||||
assert "RETENTION_OK" in caplog.text
|
||||
assert "RETENTION_FAIL" not in caplog.text
|
||||
|
||||
|
||||
def test_compose_starts_scheduler_script() -> None:
|
||||
compose = _compose_file()
|
||||
if compose is None:
|
||||
pytest.skip("docker-compose.yml liegt nicht im Backend-Image")
|
||||
text = compose.read_text(encoding="utf-8")
|
||||
start = text.index(" retention-cron:")
|
||||
block = text[start : text.index("\nvolumes:", start)]
|
||||
assert 'command: ["python", "-u", "scripts/media_retention_scheduler.py"]' in block
|
||||
assert "python -c" not in block
|
||||
assert 'PYTHONUNBUFFERED: "1"' in block
|
||||
assert "RETENTION_RUN_ON_START" not in block
|
||||
@@ -1,221 +0,0 @@
|
||||
"""OpenRouter-Modellkatalog und Plattform-Standard — ohne Live-API."""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import pytest
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
os.environ.setdefault("SKIP_DB_MIGRATE", "1")
|
||||
|
||||
from auth import require_auth
|
||||
from main import app
|
||||
from ai_model_roles import resolve_prompt_openrouter_model
|
||||
from openrouter_chat import (
|
||||
clear_openrouter_model_catalog_cache,
|
||||
normalize_openrouter_model_id,
|
||||
parse_openrouter_models_payload,
|
||||
resolve_default_openrouter_model_id,
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def client() -> TestClient:
|
||||
return TestClient(app)
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _clear_overrides():
|
||||
yield
|
||||
app.dependency_overrides.pop(require_auth, None)
|
||||
clear_openrouter_model_catalog_cache()
|
||||
|
||||
|
||||
def _superadmin():
|
||||
return {"profile_id": 7, "role": "superadmin"}
|
||||
|
||||
|
||||
def test_model_id_rejects_free_text():
|
||||
assert normalize_openrouter_model_id(" ") is None
|
||||
assert normalize_openrouter_model_id(None) is None
|
||||
assert normalize_openrouter_model_id("openai/gpt-4o-mini") == "openai/gpt-4o-mini"
|
||||
with pytest.raises(ValueError):
|
||||
normalize_openrouter_model_id("claude")
|
||||
with pytest.raises(ValueError):
|
||||
normalize_openrouter_model_id("openai/gpt\n4")
|
||||
with pytest.raises(ValueError):
|
||||
normalize_openrouter_model_id("openai//gpt")
|
||||
|
||||
|
||||
def test_resolve_prefers_stored_model():
|
||||
effective, source = resolve_default_openrouter_model_id(
|
||||
"anthropic/claude-3.5-haiku",
|
||||
"openai/gpt-4o",
|
||||
)
|
||||
assert effective == "anthropic/claude-3.5-haiku"
|
||||
assert source == "database"
|
||||
effective, source = resolve_default_openrouter_model_id("", "openai/gpt-4o")
|
||||
assert effective == "openai/gpt-4o"
|
||||
assert source == "environment"
|
||||
effective, source = resolve_default_openrouter_model_id("kein-slash", "openai/gpt-4o")
|
||||
assert effective == "openai/gpt-4o"
|
||||
assert source == "environment"
|
||||
|
||||
|
||||
def test_prompt_model_resolution_prefers_exception_then_role():
|
||||
model, source = resolve_prompt_openrouter_model(
|
||||
prompt_model="openai/gpt-4o-mini",
|
||||
role_model="anthropic/claude-sonnet-4",
|
||||
platform_model="google/gemini-2.5-pro",
|
||||
env_model="anthropic/claude-3.5-haiku",
|
||||
)
|
||||
assert model == "openai/gpt-4o-mini"
|
||||
assert source == "prompt"
|
||||
model, source = resolve_prompt_openrouter_model(
|
||||
prompt_model="",
|
||||
role_model="anthropic/claude-sonnet-4",
|
||||
platform_model="google/gemini-2.5-pro",
|
||||
env_model="anthropic/claude-3.5-haiku",
|
||||
)
|
||||
assert model == "anthropic/claude-sonnet-4"
|
||||
assert source == "role"
|
||||
model, source = resolve_prompt_openrouter_model(
|
||||
prompt_model=None,
|
||||
role_model=None,
|
||||
platform_model="google/gemini-2.5-pro",
|
||||
env_model="anthropic/claude-3.5-haiku",
|
||||
)
|
||||
assert source == "database"
|
||||
model, source = resolve_prompt_openrouter_model(
|
||||
prompt_model="kein-slash",
|
||||
role_model="",
|
||||
platform_model="",
|
||||
env_model="anthropic/claude-3.5-haiku",
|
||||
)
|
||||
assert model == "anthropic/claude-3.5-haiku"
|
||||
assert source == "environment"
|
||||
|
||||
|
||||
def test_role_update_rejects_unknown_role_and_invalid_model(client: TestClient):
|
||||
app.dependency_overrides[require_auth] = _superadmin
|
||||
missing = client.put(
|
||||
"/api/admin/openrouter/roles/unbekannt",
|
||||
headers={"X-Auth-Token": "t", "Content-Type": "application/json"},
|
||||
json={"openrouter_model": "openai/gpt-4o-mini"},
|
||||
)
|
||||
assert missing.status_code == 404
|
||||
invalid = client.put(
|
||||
"/api/admin/openrouter/roles/matching",
|
||||
headers={"X-Auth-Token": "t", "Content-Type": "application/json"},
|
||||
json={"openrouter_model": "nur-text"},
|
||||
)
|
||||
assert invalid.status_code == 400
|
||||
app.dependency_overrides[require_auth] = lambda: {"profile_id": 1, "role": "trainer"}
|
||||
forbidden = client.get("/api/admin/openrouter/roles", headers={"X-Auth-Token": "t"})
|
||||
assert forbidden.status_code == 403
|
||||
|
||||
|
||||
def test_parse_models_payload_keeps_filter_fields():
|
||||
rows = parse_openrouter_models_payload(
|
||||
{
|
||||
"data": [
|
||||
{
|
||||
"id": "openai/gpt-4o-mini",
|
||||
"name": "OpenAI: GPT-4o mini",
|
||||
"description": "Klein\nund schnell",
|
||||
"context_length": 128000,
|
||||
"architecture": {
|
||||
"input_modalities": ["text", "image"],
|
||||
"output_modalities": ["text"],
|
||||
},
|
||||
"pricing": {"prompt": "0.00000015", "completion": "0.0000006"},
|
||||
},
|
||||
{
|
||||
"id": "meta-llama/llama-3.1-8b-instruct:free",
|
||||
"name": "Llama 3.1 8B (free)",
|
||||
"architecture": {"modality": "text->text"},
|
||||
"pricing": {"prompt": "0", "completion": "0"},
|
||||
},
|
||||
{"id": "", "name": "leer"},
|
||||
"kein-objekt",
|
||||
]
|
||||
}
|
||||
)
|
||||
assert [row["id"] for row in rows] == [
|
||||
"meta-llama/llama-3.1-8b-instruct:free",
|
||||
"openai/gpt-4o-mini",
|
||||
]
|
||||
mini = rows[1]
|
||||
assert mini["provider"] == "openai"
|
||||
assert mini["context_length"] == 128000
|
||||
assert mini["input_modalities"] == ["text", "image"]
|
||||
assert mini["is_free"] is False
|
||||
assert "\n" not in mini["description"]
|
||||
assert rows[0]["is_free"] is True
|
||||
assert rows[0]["input_modalities"] == ["text"]
|
||||
|
||||
|
||||
def test_models_requires_superadmin(client: TestClient):
|
||||
app.dependency_overrides[require_auth] = lambda: {"profile_id": 1, "role": "admin"}
|
||||
response = client.get("/api/admin/openrouter/models", headers={"X-Auth-Token": "t"})
|
||||
assert response.status_code == 403
|
||||
|
||||
|
||||
def test_models_returns_catalog_for_superadmin(client: TestClient):
|
||||
app.dependency_overrides[require_auth] = _superadmin
|
||||
payload = {
|
||||
"models": [{"id": "openai/gpt-4o-mini", "name": "GPT-4o mini"}],
|
||||
"count": 1,
|
||||
"cached": False,
|
||||
"stale": False,
|
||||
"fetched_at": "2026-11-23T08:00:00+00:00",
|
||||
}
|
||||
with patch(
|
||||
"routers.openrouter_admin.fetch_openrouter_model_catalog",
|
||||
return_value=payload,
|
||||
) as fetch:
|
||||
response = client.get("/api/admin/openrouter/models?refresh=true", headers={"X-Auth-Token": "t"})
|
||||
assert response.status_code == 200
|
||||
assert response.json()["count"] == 1
|
||||
fetch.assert_called_once_with(force=True)
|
||||
|
||||
|
||||
def test_settings_put_rejects_invalid_id(client: TestClient):
|
||||
app.dependency_overrides[require_auth] = _superadmin
|
||||
response = client.put(
|
||||
"/api/admin/openrouter/settings",
|
||||
headers={"X-Auth-Token": "t", "Content-Type": "application/json"},
|
||||
json={"openrouter_model": "nur-text"},
|
||||
)
|
||||
assert response.status_code == 400
|
||||
|
||||
|
||||
@patch("routers.openrouter_admin.get_db")
|
||||
def test_settings_put_stores_model(mock_get_db, client: TestClient, monkeypatch: pytest.MonkeyPatch):
|
||||
monkeypatch.setenv("OPENROUTER_MODEL", "anthropic/claude-sonnet-4")
|
||||
app.dependency_overrides[require_auth] = _superadmin
|
||||
mock_cm = MagicMock()
|
||||
mock_cm.__enter__.return_value = MagicMock()
|
||||
mock_cm.__exit__.return_value = False
|
||||
mock_get_db.return_value = mock_cm
|
||||
cur = MagicMock()
|
||||
cur.fetchone.return_value = {
|
||||
"openrouter_model": "openai/gpt-4o-mini",
|
||||
"updated_at": "2026-11-23T08:00:00+00:00",
|
||||
}
|
||||
with patch("routers.openrouter_admin.get_cursor", return_value=cur):
|
||||
response = client.put(
|
||||
"/api/admin/openrouter/settings",
|
||||
headers={"X-Auth-Token": "t", "Content-Type": "application/json"},
|
||||
json={"openrouter_model": "openai/gpt-4o-mini"},
|
||||
)
|
||||
assert response.status_code == 200
|
||||
body = response.json()
|
||||
assert body["openrouter_model"] == "openai/gpt-4o-mini"
|
||||
assert body["effective_model"] == "openai/gpt-4o-mini"
|
||||
assert body["source"] == "database"
|
||||
assert body["env_model"] == "anthropic/claude-sonnet-4"
|
||||
params = cur.execute.call_args.args[1]
|
||||
assert params[0] == "openai/gpt-4o-mini"
|
||||
assert params[1] == 7
|
||||
@@ -73,24 +73,8 @@ def test_submit_requires_good_faith():
|
||||
good_faith_confirmed=False,
|
||||
)
|
||||
from routers.content_reports import submit_content_report
|
||||
from starlette.requests import Request
|
||||
|
||||
request = Request(
|
||||
{
|
||||
"type": "http",
|
||||
"http_version": "1.1",
|
||||
"method": "POST",
|
||||
"scheme": "http",
|
||||
"path": "/api/content-reports",
|
||||
"raw_path": b"/api/content-reports",
|
||||
"query_string": b"",
|
||||
"headers": [],
|
||||
"client": ("127.0.0.1", 50000),
|
||||
"server": ("testserver", 80),
|
||||
}
|
||||
)
|
||||
with pytest.raises(HTTPException) as exc:
|
||||
submit_content_report(request, body)
|
||||
submit_content_report(body)
|
||||
assert exc.value.status_code == 400
|
||||
assert "Gutglauben" in exc.value.detail
|
||||
|
||||
|
||||
+6
-129
@@ -1,8 +1,8 @@
|
||||
# Shinkan Jinkendo Version Information
|
||||
|
||||
APP_VERSION = "0.8.260"
|
||||
BUILD_DATE = "2026-11-23"
|
||||
DB_SCHEMA_VERSION = "20261123101"
|
||||
APP_VERSION = "0.8.243"
|
||||
BUILD_DATE = "2026-10-13"
|
||||
DB_SCHEMA_VERSION = "20261012096"
|
||||
|
||||
MODULE_VERSIONS = {
|
||||
"legal_documents": "1.4.0", # Admin: Live-Vorschau pro Abschnitt + modale Vollvorschau (Editor + Dokumentenliste)
|
||||
@@ -29,8 +29,7 @@ MODULE_VERSIONS = {
|
||||
"media_lifecycle": "1.1.0", # P-11: Retention-Job ueberspringt Legal-Hold-Assets
|
||||
"admin_ai_skill_retrieval": "1.0.0", # Superadmin CRUD /api/admin/ai-skill-retrieval-profiles (Migration 068)
|
||||
"exercise_enrichment_admin": "1.1.1", # Preview max 3/Request + parallel LLM (Gateway-504 vermeiden)
|
||||
"admin_ai_prompts": "1.0.6", # Prompt-Modell aus OpenRouter-Katalog statt Freitext
|
||||
"admin_openrouter": "1.1.0", # Aufgabengruppen Denken, Formulieren, Zuordnen
|
||||
"admin_ai_prompts": "1.0.5", # H2: granulare Katalog-Slot-Platzhalter im Katalog
|
||||
"ai_prompt_job": "0.2.1", # want_instructions; run_exercise_form_ai_suggestion
|
||||
"ai_prompt_context": "0.2.0", # preparation/trainer_notes; has_instruction_source_text
|
||||
"ai_prompt_runtime": "0.2.2", # Slug planning_exercise_expectation_profile
|
||||
@@ -38,8 +37,7 @@ MODULE_VERSIONS = {
|
||||
"skills": "0.1.1", # DB 065 karate_relevance + relevance_level; CRUD unterstützt Felder
|
||||
"skill_profiles": "1.0.0", # Phase 3: gewichtetes Fähigkeiten-Profil + skill-discovery/suggestions
|
||||
"methods": "0.1.0",
|
||||
"exercises": "2.39.0", # API-Bereitstellung je Übung, einzeln und als Auswahl
|
||||
"distribution": "1.6.0", # Katalogabruf liefert das gespeicherte Übungs-HTML
|
||||
"exercises": "2.37.2", # Upload-MIME nur aus Magic Bytes; PDF als Anhang; Rich-Text-Allowlist beim Speichern
|
||||
"planning_exercise_suggest": "0.23.8", # Progressionsgraph: Katalog-Kontext (Fokus/Stil/TT/ZG) im Match-Profil
|
||||
"training_units": "0.4.0", # POST .../publish-to-framework: Ablauf aus geplanter Einheit → Rahmen-Slot-Blueprint
|
||||
"training_programs": "0.1.0",
|
||||
@@ -51,131 +49,10 @@ MODULE_VERSIONS = {
|
||||
"membership": "1.0.0",
|
||||
"catalogs": "1.5.0", # Updated: Trainer Contexts API (Migration 012)
|
||||
"maturity_models": "1.4.0", # matrix_stack_bundle: vollständiger Katalog+Modelle+Bindings Export/Import
|
||||
"content_reports": "1.5.3", # Gutglauben vor dem Stundenlimit; Direktaufruf im Test mit Request
|
||||
"content_reports": "1.5.2", # POST /content-reports: 10 Meldungen pro Stunde und IP
|
||||
}
|
||||
|
||||
CHANGELOG = [
|
||||
{
|
||||
"version": "0.8.260",
|
||||
"date": "2026-11-23",
|
||||
"changes": [
|
||||
"Der Katalogabruf gibt Kurztext, Anleitung und Variantenabweichungen als gespeichertes HTML aus. Absätze, Zeilenumbrüche, Listen und Hervorhebungen bleiben erhalten.",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.259",
|
||||
"date": "2026-11-23",
|
||||
"changes": [
|
||||
"Der Distributionsabruf ist auf der Produktion standardmäßig an. Die Compose-Datei reicht den Schalter an den API-Container weiter.",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.258",
|
||||
"date": "2026-11-23",
|
||||
"changes": [
|
||||
"Die API-Schnittstelle nutzt die volle Adminbreite und die üblichen Seitenabstände.",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.257",
|
||||
"date": "2026-11-23",
|
||||
"changes": [
|
||||
"Übungen werden über einen Schalter in der Übersicht für den aktuellen API-Abruf ausgewählt. Der Schlüssel sieht die aktuelle Fassung und die Änderungen seit seinem letzten Abruf.",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.256",
|
||||
"date": "2026-11-23",
|
||||
"changes": [
|
||||
"Die Übungsfreigabe zeigt, wo die Arbeitsfassung vom letzten Release abweicht. Eine Adminseite listet diese Übungen zum gezielten neuen Release.",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.255",
|
||||
"date": "2026-11-23",
|
||||
"changes": [
|
||||
"Die Übungsfreigabe findet einen angelegten API-Schlüssel. Die Schlüsselabfrage wird gelesen, bevor die Rollenabfrage denselben Cursor überschreibt.",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.254",
|
||||
"date": "2026-11-23",
|
||||
"changes": [
|
||||
"Ein API-Schlüssel gehört zu einer Anwendung und kann globale Übungen, mehrere Vereine und eigene Übungen zugleich erlauben. Fällt die Rolle weg, wird dieser Bereich nicht mehr ausgeliefert. Der Schlüssel bleibt kopierbar.",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.253",
|
||||
"date": "2026-11-23",
|
||||
"changes": [
|
||||
"Die API-Schnittstelle zeigt dem Superadmin die Freigabe je Verein. Vereinsadmins und Nutzer legen selbst Schlüssel mit Namen, Inhaltsarten und Sichtbarkeit an. Die Übungsfreigabe liegt in der Registerkarte Freigabe und wählt einen solchen Schlüssel.",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.252",
|
||||
"date": "2026-11-23",
|
||||
"changes": [
|
||||
"Externe Freigabe folgt der Übung: private Übungen gibt der Besitzer frei, Vereinsübungen der Vereinsadmin, globale Übungen nur ein Superadmin.",
|
||||
"Empfänger fragen die Verfügbarkeit einer freigegebenen Übung ab. Archiv und Löschung der Quelle beenden neue Angebote, die eingefrorene Kopie bleibt bis zum Rückzug abrufbar.",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.251",
|
||||
"date": "2026-11-23",
|
||||
"changes": [
|
||||
"Eingefrorene Übungsfassungen können für einen Empfängerkanal freigegeben und per Distributions-Schlüssel abgerufen werden. Globale Übungen bearbeitet und gibt nur ein Superadmin frei. Die Distribution bleibt aus, bis DISTRIBUTION_ENABLED gesetzt ist.",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.250",
|
||||
"date": "2026-11-23",
|
||||
"changes": [
|
||||
"OpenRouter-Modelle lassen sich für die Aufgabengruppen Denken, Formulieren und Zuordnen hinterlegen. Die Zuordnung folgt den bestehenden KI-Aufrufen; eine Ausnahme am einzelnen Prompt bleibt möglich.",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.249",
|
||||
"date": "2026-11-23",
|
||||
"changes": [
|
||||
"Nach einem Deploy lädt ein fehlendes Frontend-Chunk die Seite einmal neu, statt die Fehlermaske zu zeigen. index.html wird nicht mehr lange gecacht.",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.248",
|
||||
"date": "2026-11-23",
|
||||
"changes": [
|
||||
"Superadmin wählt unter Administration → KI-Modell das OpenRouter-Standardmodell aus der live geladenen, filterbaren Modellliste. Gespeichert in platform_ai_settings (Migration 097); OPENROUTER_MODEL bleibt Fallback. Prompt-Overrides nutzen dieselbe Liste.",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.247",
|
||||
"date": "2026-10-29",
|
||||
"changes": [
|
||||
"Test Suite läuft nur noch für develop gegen Dev. Der Lauf nach Deploy Production entfällt: er brach in Gitea in jedem Job ab und hätte repariert Integrationstests gegen die Prod-Datenbank ausgeführt.",
|
||||
"Cutover auf llm-node: Deploy Production (Pi) startet nicht mehr bei Push auf main, nur noch manuell. Medienbereinigung (retention-cron) auf llm-node eingeschaltet.",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.246",
|
||||
"date": "2026-10-29",
|
||||
"changes": [
|
||||
"Zweites Prod-Deployment auf llm-node: eigener Workflow, Konfiguration aus /etc/shinkan/prod.env, Medien über docker-compose.llm-node.yml ohne automatisch angelegte Host-Pfade. Die Medienbereinigung startet dort nur nach ausdrücklicher Freigabe. Der Deploy gilt erst als erfolgreich, wenn /api/health/ready Datenbank und Schema bestätigt.",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.245",
|
||||
"date": "2026-10-28",
|
||||
"changes": [
|
||||
"Papierkorb-Retention läuft täglich um 03:00 Uhr Europe/Berlin. Ein fehlgeschlagener Lauf bleibt im Container-Log sichtbar und löscht beim Containerstart nichts.",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.244",
|
||||
"date": "2026-10-13",
|
||||
"changes": [
|
||||
"Inhaltsmeldungen ohne Gutglaubenserklärung zählen nicht auf das Stundenlimit.",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.243",
|
||||
"date": "2026-10-13",
|
||||
|
||||
@@ -38,7 +38,6 @@ services:
|
||||
APP_URL: "${APP_URL:-https://dev.shinkan.jinkendo.de}"
|
||||
ALLOWED_ORIGINS: "${ALLOWED_ORIGINS:-https://dev.shinkan.jinkendo.de,http://192.168.2.49:3098}"
|
||||
ENVIRONMENT: "${ENVIRONMENT:-development}"
|
||||
DISTRIBUTION_ENABLED: "${DISTRIBUTION_ENABLED:-1}"
|
||||
AUTO_ADMIN_FIRST_USER: "${AUTO_ADMIN_FIRST_USER:-false}"
|
||||
REQUIRE_ADMIN_TOTP: "${REQUIRE_ADMIN_TOTP:-false}"
|
||||
# M5: Hard-Block Vereins-Kontingente (Default aus — in .env auf 1 setzen zum Testen)
|
||||
|
||||
@@ -1,32 +0,0 @@
|
||||
# Ergänzung zu docker-compose.yml für das Prod-Deployment auf llm-node.
|
||||
# Nur zusammen mit der Basisdatei verwenden:
|
||||
# docker compose -p shinkan-prod -f docker-compose.yml -f docker-compose.llm-node.yml \
|
||||
# --env-file /etc/shinkan/prod.env ...
|
||||
# Pi und Dev nutzen diese Datei nicht.
|
||||
|
||||
services:
|
||||
backend:
|
||||
environment:
|
||||
MEDIA_ROOT: /app/media
|
||||
# Ersetzt den Medien-Mount der Basisdatei (gleiches Ziel /app/media).
|
||||
# Kein create_host_path: fehlt das NFS-Verzeichnis, startet der Container nicht,
|
||||
# statt auf die lokale Platte zu schreiben.
|
||||
volumes:
|
||||
- type: bind
|
||||
source: /srv/shinkan/prod/media
|
||||
target: /app/media
|
||||
bind:
|
||||
create_host_path: false
|
||||
|
||||
# Pi und llm-node teilen den Medienbestand, haben aber getrennte Datenbanken.
|
||||
# Die Bereinigung startet hier nur mit Profil media-retention (siehe PROD_DEPLOYMENTS.md).
|
||||
retention-cron:
|
||||
profiles: ["media-retention"]
|
||||
environment:
|
||||
MEDIA_ROOT: /app/media
|
||||
volumes:
|
||||
- type: bind
|
||||
source: /srv/shinkan/prod/media
|
||||
target: /app/media
|
||||
bind:
|
||||
create_host_path: false
|
||||
+14
-4
@@ -45,8 +45,6 @@ services:
|
||||
APP_URL: "${APP_URL:-https://shinkan.jinkendo.de}"
|
||||
ALLOWED_ORIGINS: "${ALLOWED_ORIGINS:-https://shinkan.jinkendo.de}"
|
||||
ENVIRONMENT: "${ENVIRONMENT:-production}"
|
||||
DISTRIBUTION_ENABLED: "${DISTRIBUTION_ENABLED:-1}"
|
||||
DISTRIBUTION_CURSOR_SECRET: "${DISTRIBUTION_CURSOR_SECRET:-}"
|
||||
CLUB_FEATURE_ENFORCE: "${CLUB_FEATURE_ENFORCE:-1}"
|
||||
# MediaWiki/SMW Import — in dev-env.yml bereits gesetzt; Prod brauchte diese Zeilen ebenfalls,
|
||||
# sonst: leere MEDIAWIKI_API_URL im Container → Import bricht ab (auf Test/Dev war es immer gesetzt).
|
||||
@@ -91,7 +89,20 @@ services:
|
||||
context: ./backend
|
||||
dockerfile: Dockerfile
|
||||
container_name: shinkan-retention-cron
|
||||
command: ["python", "-u", "scripts/media_retention_scheduler.py"]
|
||||
command: >
|
||||
python -c "
|
||||
import time, subprocess, sys, os, datetime
|
||||
def next_3am():
|
||||
now = datetime.datetime.now()
|
||||
target = now.replace(hour=3, minute=0, second=0, microsecond=0)
|
||||
if target <= now:
|
||||
target += datetime.timedelta(days=1)
|
||||
return (target - now).total_seconds()
|
||||
subprocess.run([sys.executable, 'scripts/media_retention_job.py'], check=False)
|
||||
while True:
|
||||
time.sleep(next_3am())
|
||||
subprocess.run([sys.executable, 'scripts/media_retention_job.py'], check=False)
|
||||
"
|
||||
working_dir: /app
|
||||
environment:
|
||||
DB_HOST: postgres
|
||||
@@ -99,7 +110,6 @@ services:
|
||||
DB_NAME: shinkan
|
||||
DB_USER: shinkan_user
|
||||
DB_PASSWORD: ${DB_PASSWORD}
|
||||
PYTHONUNBUFFERED: "1"
|
||||
MEDIA_ROOT: "${MEDIA_ROOT:-/app/media}"
|
||||
# Loeschkonzept (Audit P-03b): 30 Tage Soft-Trash, dann 30 Tage Hidden, dann Purge (gesamt 60 Tage).
|
||||
MEDIA_TRASH_SOFT_TO_HIDDEN_DAYS: "${MEDIA_TRASH_SOFT_TO_HIDDEN_DAYS:-30}"
|
||||
|
||||
+2
-2
@@ -156,10 +156,10 @@ Das Schema ist gegenüber dem Code zurück: Migration **`022_skills_schema_compl
|
||||
- **Planungs-Übungssuche:** siehe Tabelle oben — getrennt von Formular-KI.
|
||||
- **Doku:** Umsetzung `.claude/docs/working/AI_EXERCISE_IMPLEMENTATION_PLAN.md`; Profil-/JSON-Konzept `.claude/docs/working/AI_SKILL_RETRIEVAL_PROFILES_SPEC.md`; Ist-Prompt/UI **`AI_PROMPT_SYSTEM_SPEC.md`**; API-Felder **`KI_FEATURES_SPEC.md`** §5.2
|
||||
- **Kontext / Job:** **`ai_prompt_context`** (Titel, Ziel, Durchführung, Vorbereitung, Trainer-Hinweise, Fokus); **`ai_prompt_job`** — **`run_exercise_form_ai_suggestion`**; **`ai_prompt_runtime`**; **`exercise_ai`** — OpenRouter
|
||||
- **DB:** **`067`** ai_prompts · **`069`** default_template · **`068`** ai_skill_retrieval_profiles · **`070`** openrouter_model · **`071`** **`exercise_instruction_rewrite`** · **`097`** `platform_ai_settings` (Plattform-Standardmodell)
|
||||
- **DB:** **`067`** ai_prompts · **`069`** default_template · **`068`** ai_skill_retrieval_profiles · **`070`** openrouter_model · **`071`** **`exercise_instruction_rewrite`**
|
||||
- **Prompt-Slugs:** `exercise_summary`, `exercise_skill_suggestions`, **`exercise_instruction_rewrite`** (Anleitung JSON, prägnant, HTML p/ul/ol/li)
|
||||
- **API:** `POST /api/exercises/ai/suggest` — **`include_instructions`**, Body **`preparation`**, **`trainer_notes`**; Response **`instructions.fields`**; **`POST …/ai/regenerate`** mit **`instructions`** in `regenerate`
|
||||
- **Pflege:** Superadmin **`/admin/openrouter`** (Modellkatalog, Standardmodell), **`/admin/ai-prompts`** (Override pro Prompt aus derselben Liste), **`/admin/ai-skill-retrieval`**
|
||||
- **Pflege:** Superadmin **`/admin/ai-prompts`**, **`/admin/ai-skill-retrieval`**
|
||||
- **Diagnose:** **`SHINKAN_AI_DEBUG=1`** — Logs `shinkan.exercise_ai`, `shinkan.openrouter`
|
||||
- **Frontend Formular:** Tab **Anleitung** — **„KI: Anleitung überarbeiten“**; Vorschau-Dialog pro Feld (**`ExerciseFormPageRoot.jsx`**)
|
||||
- **Frontend Schnellanlage:** **`ExercisePickerModal`** (Planung/Rahmen) — Volltext vs. Planungs-KI; KI-Neuanlage im Picker. **`ExercisesListPageRoot`** — Schalter **„Neu mit KI-Assistent“**: Planungs-KI-Suche (`usePlanningExerciseSuggestSearch`) + **`ExerciseAiQuickCreateModal`**; normales **„+ Neu“** ausgeblendet solange aktiv.
|
||||
|
||||
@@ -1,493 +0,0 @@
|
||||
{
|
||||
"fixture_version": 1,
|
||||
"note": "Synthetische Inhalte ohne produktive Rechte. Die Medienbytes dienen der Testung von Groesse und Hash. Sie sind keine abspielbare Filmdatei.",
|
||||
"manifest_serialization": "UTF-8, JSON ohne Leerraum, Reihenfolge der Felder aus manifest, kein abschliessender Zeilenumbruch",
|
||||
"channels": {
|
||||
"lara_felix": {
|
||||
"recipient_id": "caa20000-0000-4000-8000-0000000001f5",
|
||||
"events": [
|
||||
{
|
||||
"event_id": "caa20000-0000-4000-8000-000000000258",
|
||||
"type": "release.published",
|
||||
"release_id": "caa20000-0000-4000-8000-0000000000c9",
|
||||
"occurred_at": "2026-11-23T09:01:00Z",
|
||||
"source_id": "caa20000-0000-4000-8000-00000000000a",
|
||||
"revision": 1,
|
||||
"manifest_sha256": "fcebc8c4db56328a55dc7f350e705822cef19f02392f26625274e68c0abc239c"
|
||||
},
|
||||
{
|
||||
"event_id": "caa20000-0000-4000-8000-000000000259",
|
||||
"type": "release.published",
|
||||
"release_id": "caa20000-0000-4000-8000-0000000000ca",
|
||||
"occurred_at": "2026-11-23T09:02:00Z",
|
||||
"source_id": "caa20000-0000-4000-8000-00000000000b",
|
||||
"revision": 1,
|
||||
"manifest_sha256": "7dad43afb3077fb2d9fb3aa490bb91daf53f175c06575d648411021d352a1744"
|
||||
},
|
||||
{
|
||||
"event_id": "caa20000-0000-4000-8000-00000000025a",
|
||||
"type": "release.published",
|
||||
"release_id": "caa20000-0000-4000-8000-0000000000cb",
|
||||
"occurred_at": "2026-11-23T09:03:00Z",
|
||||
"source_id": "caa20000-0000-4000-8000-00000000000a",
|
||||
"revision": 2,
|
||||
"manifest_sha256": "f0c8051cee6feb0e6399f1bc5681e0ef1ecd640c1cbe6b634c5df1c1b1df9ed0"
|
||||
},
|
||||
{
|
||||
"event_id": "caa20000-0000-4000-8000-00000000025b",
|
||||
"type": "release.retired",
|
||||
"release_id": "caa20000-0000-4000-8000-0000000000c9",
|
||||
"occurred_at": "2026-11-23T09:04:00Z"
|
||||
},
|
||||
{
|
||||
"event_id": "caa20000-0000-4000-8000-00000000025c",
|
||||
"type": "asset.withdrawn",
|
||||
"release_id": "caa20000-0000-4000-8000-0000000000c9",
|
||||
"occurred_at": "2026-11-23T09:05:00Z",
|
||||
"target_id": "caa20000-0000-4000-8000-00000000012c",
|
||||
"reason_code": "rights"
|
||||
},
|
||||
{
|
||||
"event_id": "caa20000-0000-4000-8000-00000000025d",
|
||||
"type": "asset.withdrawn",
|
||||
"release_id": "caa20000-0000-4000-8000-0000000000cb",
|
||||
"occurred_at": "2026-11-23T09:05:00Z",
|
||||
"target_id": "caa20000-0000-4000-8000-00000000012c",
|
||||
"reason_code": "rights"
|
||||
}
|
||||
]
|
||||
},
|
||||
"zweiter_verein": {
|
||||
"recipient_id": "caa20000-0000-4000-8000-0000000001f6",
|
||||
"events": [
|
||||
{
|
||||
"event_id": "caa20000-0000-4000-8000-0000000002bc",
|
||||
"type": "release.published",
|
||||
"release_id": "caa20000-0000-4000-8000-0000000000cc",
|
||||
"occurred_at": "2026-11-23T09:03:00Z",
|
||||
"source_id": "caa20000-0000-4000-8000-00000000000c",
|
||||
"revision": 1,
|
||||
"manifest_sha256": "3e34007864d308ac1cf6b555bb7fd00dd6962fb6f396eca16492ace0fec59603"
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"releases": {
|
||||
"vereinsfassung_1": {
|
||||
"channel": "lara_felix",
|
||||
"manifest_sha256": "fcebc8c4db56328a55dc7f350e705822cef19f02392f26625274e68c0abc239c",
|
||||
"manifest": {
|
||||
"schema_version": 1,
|
||||
"resource_type": "exercise",
|
||||
"release_id": "caa20000-0000-4000-8000-0000000000c9",
|
||||
"source_id": "caa20000-0000-4000-8000-00000000000a",
|
||||
"revision": 1,
|
||||
"publisher_id": "caa20000-0000-4000-8000-00000000177a",
|
||||
"published_at": "2026-11-23T09:01:00Z",
|
||||
"exercise": {
|
||||
"title": "Raum und Wege wahrnehmen",
|
||||
"audience": "Kursleitungen",
|
||||
"rights_id": "caa20000-0000-4000-8000-000000000191",
|
||||
"parts": [
|
||||
{
|
||||
"id": "caa20000-0000-4000-8000-000000000065",
|
||||
"role": "goal",
|
||||
"text": "Die Gruppe nimmt freie Wege im Raum wahr.",
|
||||
"rights_id": "caa20000-0000-4000-8000-000000000191"
|
||||
},
|
||||
{
|
||||
"id": "caa20000-0000-4000-8000-000000000066",
|
||||
"role": "instructions",
|
||||
"text": "Die Kursleitung legt Karten aus und bespricht die freien Wege.",
|
||||
"rights_id": "caa20000-0000-4000-8000-000000000191"
|
||||
},
|
||||
{
|
||||
"id": "caa20000-0000-4000-8000-000000000067",
|
||||
"role": "trainer_notes",
|
||||
"text": "Vorab genug Platz vorsehen.",
|
||||
"rights_id": "caa20000-0000-4000-8000-000000000191"
|
||||
},
|
||||
{
|
||||
"id": "caa20000-0000-4000-8000-000000000068",
|
||||
"role": "instructions",
|
||||
"text": "Den kurzen Film ansehen und danach die gezeigten Wege vergleichen.",
|
||||
"rights_id": "caa20000-0000-4000-8000-000000000191"
|
||||
}
|
||||
],
|
||||
"assets": [
|
||||
{
|
||||
"id": "caa20000-0000-4000-8000-00000000012c",
|
||||
"role": "demonstration",
|
||||
"media_type": "video/mp4",
|
||||
"size_bytes": 32,
|
||||
"sha256": "0fb807ef5ec44b003f181dfa9ce317becbcfd5755ebf91a57702d2024df2b915",
|
||||
"rights_id": "caa20000-0000-4000-8000-000000000192",
|
||||
"label": "Demonstrationsfilm"
|
||||
}
|
||||
],
|
||||
"common_part_ids": [
|
||||
"caa20000-0000-4000-8000-000000000065",
|
||||
"caa20000-0000-4000-8000-000000000067"
|
||||
],
|
||||
"common_asset_ids": [],
|
||||
"variants": [
|
||||
{
|
||||
"id": "caa20000-0000-4000-8000-00000000006b",
|
||||
"label": "Kartenvariante",
|
||||
"part_ids": [
|
||||
"caa20000-0000-4000-8000-000000000066"
|
||||
],
|
||||
"asset_ids": []
|
||||
},
|
||||
{
|
||||
"id": "caa20000-0000-4000-8000-00000000006c",
|
||||
"label": "Filmvariante",
|
||||
"part_ids": [
|
||||
"caa20000-0000-4000-8000-000000000068"
|
||||
],
|
||||
"asset_ids": [
|
||||
"caa20000-0000-4000-8000-00000000012c"
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
"rights": [
|
||||
{
|
||||
"id": "caa20000-0000-4000-8000-000000000191",
|
||||
"evidence_ref": "test-textrechte",
|
||||
"actions": [
|
||||
"store",
|
||||
"render",
|
||||
"grant_customer_use",
|
||||
"commercial_course_use"
|
||||
],
|
||||
"territories": [
|
||||
"DE"
|
||||
],
|
||||
"valid_from": "2026-11-23T09:00:00Z",
|
||||
"valid_until": null
|
||||
},
|
||||
{
|
||||
"id": "caa20000-0000-4000-8000-000000000192",
|
||||
"evidence_ref": "test-filmrechte",
|
||||
"actions": [
|
||||
"store",
|
||||
"stream",
|
||||
"course_display",
|
||||
"grant_customer_use",
|
||||
"commercial_course_use"
|
||||
],
|
||||
"territories": [
|
||||
"DE"
|
||||
],
|
||||
"valid_from": "2026-11-23T09:00:00Z",
|
||||
"valid_until": null
|
||||
}
|
||||
]
|
||||
},
|
||||
"synthetic_asset_base64_by_id": {
|
||||
"caa20000-0000-4000-8000-00000000012c": "U2hpbmthbiBkaXN0cmlidXRpb24gZml4dHVyZSB2MQo="
|
||||
}
|
||||
},
|
||||
"eigener_bestand": {
|
||||
"channel": "lara_felix",
|
||||
"manifest_sha256": "7dad43afb3077fb2d9fb3aa490bb91daf53f175c06575d648411021d352a1744",
|
||||
"manifest": {
|
||||
"schema_version": 1,
|
||||
"resource_type": "exercise",
|
||||
"release_id": "caa20000-0000-4000-8000-0000000000ca",
|
||||
"source_id": "caa20000-0000-4000-8000-00000000000b",
|
||||
"revision": 1,
|
||||
"publisher_id": "caa20000-0000-4000-8000-00000000177b",
|
||||
"published_at": "2026-11-23T09:02:00Z",
|
||||
"exercise": {
|
||||
"title": "Aufmerksam im Raum ankommen",
|
||||
"audience": "Kursleitungen",
|
||||
"rights_id": "caa20000-0000-4000-8000-000000000191",
|
||||
"parts": [
|
||||
{
|
||||
"id": "caa20000-0000-4000-8000-00000000006f",
|
||||
"role": "goal",
|
||||
"text": "Die Gruppe nimmt freie Wege im Raum wahr.",
|
||||
"rights_id": "caa20000-0000-4000-8000-000000000191"
|
||||
},
|
||||
{
|
||||
"id": "caa20000-0000-4000-8000-000000000070",
|
||||
"role": "instructions",
|
||||
"text": "Die Kursleitung legt Karten aus und bespricht die freien Wege.",
|
||||
"rights_id": "caa20000-0000-4000-8000-000000000191"
|
||||
},
|
||||
{
|
||||
"id": "caa20000-0000-4000-8000-000000000071",
|
||||
"role": "trainer_notes",
|
||||
"text": "Vorab genug Platz vorsehen.",
|
||||
"rights_id": "caa20000-0000-4000-8000-000000000191"
|
||||
}
|
||||
],
|
||||
"assets": [],
|
||||
"common_part_ids": [
|
||||
"caa20000-0000-4000-8000-00000000006f",
|
||||
"caa20000-0000-4000-8000-000000000071"
|
||||
],
|
||||
"common_asset_ids": [],
|
||||
"variants": [
|
||||
{
|
||||
"id": "caa20000-0000-4000-8000-000000000075",
|
||||
"label": "Kartenvariante",
|
||||
"part_ids": [
|
||||
"caa20000-0000-4000-8000-000000000070"
|
||||
],
|
||||
"asset_ids": []
|
||||
}
|
||||
]
|
||||
},
|
||||
"rights": [
|
||||
{
|
||||
"id": "caa20000-0000-4000-8000-000000000191",
|
||||
"evidence_ref": "test-textrechte",
|
||||
"actions": [
|
||||
"store",
|
||||
"render",
|
||||
"grant_customer_use",
|
||||
"commercial_course_use"
|
||||
],
|
||||
"territories": [
|
||||
"DE"
|
||||
],
|
||||
"valid_from": "2026-11-23T09:00:00Z",
|
||||
"valid_until": null
|
||||
}
|
||||
]
|
||||
},
|
||||
"synthetic_asset_base64_by_id": {}
|
||||
},
|
||||
"vereinsfassung_2": {
|
||||
"channel": "lara_felix",
|
||||
"manifest_sha256": "f0c8051cee6feb0e6399f1bc5681e0ef1ecd640c1cbe6b634c5df1c1b1df9ed0",
|
||||
"manifest": {
|
||||
"schema_version": 1,
|
||||
"resource_type": "exercise",
|
||||
"release_id": "caa20000-0000-4000-8000-0000000000cb",
|
||||
"source_id": "caa20000-0000-4000-8000-00000000000a",
|
||||
"revision": 2,
|
||||
"publisher_id": "caa20000-0000-4000-8000-00000000177a",
|
||||
"published_at": "2026-11-23T09:03:00Z",
|
||||
"exercise": {
|
||||
"title": "Raum und Wege wahrnehmen",
|
||||
"audience": "Kursleitungen",
|
||||
"rights_id": "caa20000-0000-4000-8000-000000000191",
|
||||
"parts": [
|
||||
{
|
||||
"id": "caa20000-0000-4000-8000-000000000065",
|
||||
"role": "goal",
|
||||
"text": "Die Gruppe nimmt freie Wege im Raum wahr.",
|
||||
"rights_id": "caa20000-0000-4000-8000-000000000191"
|
||||
},
|
||||
{
|
||||
"id": "caa20000-0000-4000-8000-000000000066",
|
||||
"role": "instructions",
|
||||
"text": "Die Kursleitung legt Karten aus und bespricht die freien Wege.",
|
||||
"rights_id": "caa20000-0000-4000-8000-000000000191"
|
||||
},
|
||||
{
|
||||
"id": "caa20000-0000-4000-8000-000000000067",
|
||||
"role": "trainer_notes",
|
||||
"text": "Vorab genug Platz vorsehen und die Laufwege gemeinsam prüfen.",
|
||||
"rights_id": "caa20000-0000-4000-8000-000000000191"
|
||||
},
|
||||
{
|
||||
"id": "caa20000-0000-4000-8000-000000000068",
|
||||
"role": "instructions",
|
||||
"text": "Den kurzen Film ansehen und danach die gezeigten Wege vergleichen.",
|
||||
"rights_id": "caa20000-0000-4000-8000-000000000191"
|
||||
}
|
||||
],
|
||||
"assets": [
|
||||
{
|
||||
"id": "caa20000-0000-4000-8000-00000000012c",
|
||||
"role": "demonstration",
|
||||
"media_type": "video/mp4",
|
||||
"size_bytes": 32,
|
||||
"sha256": "0fb807ef5ec44b003f181dfa9ce317becbcfd5755ebf91a57702d2024df2b915",
|
||||
"rights_id": "caa20000-0000-4000-8000-000000000192",
|
||||
"label": "Demonstrationsfilm"
|
||||
}
|
||||
],
|
||||
"common_part_ids": [
|
||||
"caa20000-0000-4000-8000-000000000065",
|
||||
"caa20000-0000-4000-8000-000000000067"
|
||||
],
|
||||
"common_asset_ids": [],
|
||||
"variants": [
|
||||
{
|
||||
"id": "caa20000-0000-4000-8000-00000000006b",
|
||||
"label": "Kartenvariante",
|
||||
"part_ids": [
|
||||
"caa20000-0000-4000-8000-000000000066"
|
||||
],
|
||||
"asset_ids": []
|
||||
},
|
||||
{
|
||||
"id": "caa20000-0000-4000-8000-00000000006c",
|
||||
"label": "Filmvariante",
|
||||
"part_ids": [
|
||||
"caa20000-0000-4000-8000-000000000068"
|
||||
],
|
||||
"asset_ids": [
|
||||
"caa20000-0000-4000-8000-00000000012c"
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
"rights": [
|
||||
{
|
||||
"id": "caa20000-0000-4000-8000-000000000191",
|
||||
"evidence_ref": "test-textrechte",
|
||||
"actions": [
|
||||
"store",
|
||||
"render",
|
||||
"grant_customer_use",
|
||||
"commercial_course_use"
|
||||
],
|
||||
"territories": [
|
||||
"DE"
|
||||
],
|
||||
"valid_from": "2026-11-23T09:00:00Z",
|
||||
"valid_until": null
|
||||
},
|
||||
{
|
||||
"id": "caa20000-0000-4000-8000-000000000192",
|
||||
"evidence_ref": "test-filmrechte",
|
||||
"actions": [
|
||||
"store",
|
||||
"stream",
|
||||
"course_display",
|
||||
"grant_customer_use",
|
||||
"commercial_course_use"
|
||||
],
|
||||
"territories": [
|
||||
"DE"
|
||||
],
|
||||
"valid_from": "2026-11-23T09:00:00Z",
|
||||
"valid_until": null
|
||||
}
|
||||
]
|
||||
},
|
||||
"synthetic_asset_base64_by_id": {
|
||||
"caa20000-0000-4000-8000-00000000012c": "U2hpbmthbiBkaXN0cmlidXRpb24gZml4dHVyZSB2MQo="
|
||||
}
|
||||
},
|
||||
"zweiter_verein": {
|
||||
"channel": "zweiter_verein",
|
||||
"manifest_sha256": "3e34007864d308ac1cf6b555bb7fd00dd6962fb6f396eca16492ace0fec59603",
|
||||
"manifest": {
|
||||
"schema_version": 1,
|
||||
"resource_type": "exercise",
|
||||
"release_id": "caa20000-0000-4000-8000-0000000000cc",
|
||||
"source_id": "caa20000-0000-4000-8000-00000000000c",
|
||||
"revision": 1,
|
||||
"publisher_id": "caa20000-0000-4000-8000-00000000177c",
|
||||
"published_at": "2026-11-23T09:03:00Z",
|
||||
"exercise": {
|
||||
"title": "Gemeinsam den Raum erkunden",
|
||||
"audience": "Kursleitungen",
|
||||
"rights_id": "caa20000-0000-4000-8000-000000000191",
|
||||
"parts": [
|
||||
{
|
||||
"id": "caa20000-0000-4000-8000-000000000079",
|
||||
"role": "goal",
|
||||
"text": "Die Gruppe nimmt freie Wege im Raum wahr.",
|
||||
"rights_id": "caa20000-0000-4000-8000-000000000191"
|
||||
},
|
||||
{
|
||||
"id": "caa20000-0000-4000-8000-00000000007a",
|
||||
"role": "instructions",
|
||||
"text": "Die Kursleitung legt Karten aus und bespricht die freien Wege.",
|
||||
"rights_id": "caa20000-0000-4000-8000-000000000191"
|
||||
},
|
||||
{
|
||||
"id": "caa20000-0000-4000-8000-00000000007b",
|
||||
"role": "trainer_notes",
|
||||
"text": "Vorab genug Platz vorsehen.",
|
||||
"rights_id": "caa20000-0000-4000-8000-000000000191"
|
||||
}
|
||||
],
|
||||
"assets": [],
|
||||
"common_part_ids": [
|
||||
"caa20000-0000-4000-8000-000000000079",
|
||||
"caa20000-0000-4000-8000-00000000007b"
|
||||
],
|
||||
"common_asset_ids": [],
|
||||
"variants": [
|
||||
{
|
||||
"id": "caa20000-0000-4000-8000-00000000007f",
|
||||
"label": "Kartenvariante",
|
||||
"part_ids": [
|
||||
"caa20000-0000-4000-8000-00000000007a"
|
||||
],
|
||||
"asset_ids": []
|
||||
}
|
||||
]
|
||||
},
|
||||
"rights": [
|
||||
{
|
||||
"id": "caa20000-0000-4000-8000-000000000191",
|
||||
"evidence_ref": "test-textrechte",
|
||||
"actions": [
|
||||
"store",
|
||||
"render",
|
||||
"grant_customer_use",
|
||||
"commercial_course_use"
|
||||
],
|
||||
"territories": [
|
||||
"DE"
|
||||
],
|
||||
"valid_from": "2026-11-23T09:00:00Z",
|
||||
"valid_until": null
|
||||
}
|
||||
]
|
||||
},
|
||||
"synthetic_asset_base64_by_id": {}
|
||||
}
|
||||
},
|
||||
"plans": {
|
||||
"plan_a_mit_film": {
|
||||
"release_id": "caa20000-0000-4000-8000-0000000000c9",
|
||||
"variant_id": "caa20000-0000-4000-8000-00000000006c"
|
||||
},
|
||||
"plan_b_mit_karten": {
|
||||
"release_id": "caa20000-0000-4000-8000-0000000000c9",
|
||||
"variant_id": "caa20000-0000-4000-8000-00000000006b"
|
||||
},
|
||||
"plan_c_mit_film_neuere_fassung": {
|
||||
"release_id": "caa20000-0000-4000-8000-0000000000cb",
|
||||
"variant_id": "caa20000-0000-4000-8000-00000000006c"
|
||||
},
|
||||
"plan_d_eigener_bestand": {
|
||||
"release_id": "caa20000-0000-4000-8000-0000000000ca",
|
||||
"variant_id": "caa20000-0000-4000-8000-000000000075"
|
||||
}
|
||||
},
|
||||
"expected": {
|
||||
"plan_binding_after_revision": {
|
||||
"release_id": "caa20000-0000-4000-8000-0000000000c9",
|
||||
"variant_id": "caa20000-0000-4000-8000-00000000006c"
|
||||
},
|
||||
"blocked_plans_after_withdrawal": [
|
||||
"plan_a_mit_film",
|
||||
"plan_c_mit_film_neuere_fassung"
|
||||
],
|
||||
"available_plans_after_withdrawal": [
|
||||
"plan_b_mit_karten",
|
||||
"plan_d_eigener_bestand"
|
||||
],
|
||||
"lara_felix_can_retrieve_after_withdrawal": [
|
||||
"caa20000-0000-4000-8000-0000000000ca"
|
||||
],
|
||||
"zweiter_verein_can_retrieve": [
|
||||
"caa20000-0000-4000-8000-0000000000cc"
|
||||
],
|
||||
"course_film_allowed": true,
|
||||
"film_download_allowed": false
|
||||
}
|
||||
}
|
||||
@@ -1,70 +0,0 @@
|
||||
# Übergabevertrag für Übungsfassungen aus Shinkan · Version 1.0
|
||||
|
||||
**23.11.2026 · Spezifikationsstand für die Beauftragung auf der Testinstanz**
|
||||
|
||||
Shinkan führt die importierten Übungsoriginale. Es gibt ausgewählte Fassungen pro Empfänger frei. Lara & Felix übernimmt sie als lokale Übungsfassungen und bindet sie in seine Trainingspläne und Artikel-Stände ein. Die Veröffentlichung für Kundinnen und Kunden, die Lizenzprüfung und die Auslieferung liegen bei Lara & Felix. Planeditor, Angebotsmodell und dauerhafte Pflege eigener Lara-&-Felix-Übungsoriginale können gesondert entschieden werden. Die Freigabe des Produktivbetriebs erfordert beiderseitige Abnahme und belegte Nutzungsrechte.
|
||||
|
||||
## 1. Identität, Herausgabe und Fassung
|
||||
|
||||
| Begriff | Bedeutung im Vertrag |
|
||||
|---|---|
|
||||
| Herausgeber | Verantwortet eine Freigabe aus dem eigenen oder gemeinsam gepflegten Vereinsbestand. Der Empfänger erhält eine opaque UUID und gegebenenfalls die vereinbarte öffentliche Namensnennung. |
|
||||
| Empfänger und Anbindung | Ein Empfänger hat einen eigenen Lieferkanal. Eine Maschinenanbindung ist an einen Kanal gebunden, mit einem separat widerrufbaren Schlüssel. Mehrere Herausgeber können für denselben Empfänger freigeben, sofern jede Herausgeber-Empfänger-Beziehung autorisiert ist. |
|
||||
| `source_id` | Stabile öffentliche Übungs-UUID in Shinkan. Sie bleibt bei redaktionellen Änderungen und einem autorisierten Wechsel des Verantwortlichen erhalten. |
|
||||
| `revision` | Positive Ganzzahl je `source_id` für den eingefrorenen fachlichen Stand. Dasselbe unveränderte Quellabbild kann für mehrere Kanäle verwendet werden. Redaktionelle Änderungen an einer Arbeitsfassung verändern einen eingefrorenen Stand nicht. |
|
||||
| `release_id` | UUID des unveränderlichen Lieferpakets für einen Empfänger. Ein erneuter Zuschnitt von Auswahl oder Rechten führt zu einem neuen Paket, auch wenn die Quellrevision gleich bleibt. Mehrere Pakete derselben Revision erhalten im Änderungsverlauf eine eindeutige Reihenfolge. |
|
||||
|
||||
Lara & Felix ordnet `source_id` einer stabilen lokalen Übung zu und `release_id` einem lokalen übernommenen Stand. Der Schlüssel hierfür umfasst das konfigurierte Quellsystem beziehungsweise die Quellinstanz. Die Prüfsumme dient der Integritätsprüfung. Gleiche Bytes mit unterschiedlicher Freigabe können einen unterschiedlichen Nutzungsumfang haben. Technische Schlüssel, Zugangsdaten, Vereinslisten, Profile, Gruppen, interne IDs und vertrauliche Nachweise sind von der Ausgabe ausgeschlossen. Die interne Shinkan-Sichtbarkeit regelt weiterhin die Nutzung im Trainerbereich.
|
||||
|
||||
## 2. Das unveränderliche Paket
|
||||
|
||||
`GET /api/distribution/v1/releases/{release_id}` liefert folgende Struktur als UTF-8-JSON. Zeiten im Vertrag verwenden UTC im Format `YYYY-MM-DDTHH:mm:ssZ`. Die angegebenen Objektfelder sind erforderlich, sofern sie hier als optional oder nullfähig beschrieben werden.
|
||||
|
||||
| Feld | Inhalt |
|
||||
|---|---|
|
||||
| `schema_version`, `resource_type` | Ganzzahl `1`, Zeichenkette `exercise`. Ein neuer fachlicher Ressourcentyp benötigt eine eigene Vereinbarung. |
|
||||
| `release_id`, `source_id`, `revision`, `publisher_id`, `published_at` | Kennungen und Zeitpunkt gemäß Abschnitt 1. |
|
||||
| `exercise` | `title`, optionale `summary`, optionales `audience` und `rights_id` für diese redaktionellen Angaben. Dazu `parts`, `assets`, `common_part_ids`, `common_asset_ids` und `variants`. `parts` enthält mindestens einen Eintrag für das Lernziel. Jede Variante kann nach Auflösung eine Durchführung anzeigen. |
|
||||
| `parts[]` | `id` als UUID, `role`, `text` als Klartext und `rights_id`. Rollen in v1 sind `goal`, `prerequisites`, `preparation`, `instructions`, `trainer_notes`, `equipment` und `duration_note`. Trainerhinweise behalten eine eigene Rolle für die spätere Rechteprüfung in Lara & Felix. |
|
||||
| `assets[]` | `id` als UUID, `role`, `media_type`, `size_bytes`, `sha256`, `rights_id` und optionales `label`. Rollen in v1 sind `demonstration`, `worksheet` und `illustration`. SHA-256 steht als 64-stellige kleingeschriebene Hex-Zeichenkette. |
|
||||
| `common_part_ids`, `common_asset_ids` | Geordnete Referenzen auf die Bestandteile, die jede Variante nutzt. |
|
||||
| `variants[]` | `id` als UUID, `label`, `part_ids` und `asset_ids` als geordnete zusätzliche Referenzen. Eine Übung ohne redaktionelle Alternativen erhält eine Standardvariante. Eine wiederverwendete Varianten-UUID bezeichnet dieselbe fachliche Variante über Fassungen hinweg. |
|
||||
| `rights[]` | `id` als UUID, `evidence_ref` als opaque Nachweisreferenz, `actions`, `territories`, `valid_from`, `valid_until` und optional `attribution`. `territories` ist eine Liste von ISO-Ländercodes oder explizit `null` für räumlich unbeschränkt. `valid_until` ist exklusiv oder explizit `null` für unbefristet. |
|
||||
|
||||
Für `actions` gelten `store`, `render`, `stream`, `download`, `print`, `course_display`, `commercial_course_use`, `adapt`, `public_preview` und `grant_customer_use`. `store` erlaubt die Übernahme durch den Empfänger, `render` die Anzeige eines Textes oder Bildes und `grant_customer_use` die Einräumung des abgedeckten Nutzungsumfangs an Endkunden. Die übrigen Aktionen begrenzen die jeweilige Nutzung. Kombinationen werden gemeinsam geprüft. Für kommerzielle Vorführung sind zum Beispiel neben `course_display` auch `commercial_course_use` und, bei gestreamtem Material, `stream` erforderlich. Lara & Felix prüft zusätzlich das eigene Rechteprofil. Auflagen außerhalb des Schemas müssen vor Veröffentlichung operationalisiert werden. [§ 31 UrhG](https://www.gesetze-im-internet.de/urhg/__31.html)
|
||||
|
||||
Alle IDs innerhalb ihrer Listen sind eindeutig. Alle Referenzen müssen im selben Paket aufgehen. Jeder übermittelte Teil und jedes Medium gehört zu mindestens einer freigegebenen Variante und verweist auf einen wirksamen Rechtevermerk, der die Übernahme abdeckt. Variantenbeschriftungen sind vom Rechtevermerk der redaktionellen Angaben abgedeckt. Zum Freigabezeitpunkt muss die vorgesehene Nutzung möglich sein. Die exportierte Fassung v1 verwendet Klartext und separate Medienreferenzen. Sind Inline-Medien oder die Anordnung für das Verständnis wesentlich, prüft die Redaktion die aufbereitete Exportfassung und ihre Medien vor Freigabe. Unaufgelöste Anker, fremde URLs im Medienmanifest und nicht exportierbare Kombinationsabhängigkeiten sperren die Freigabe.
|
||||
|
||||
Shinkan speichert den exakten JSON-Body und veröffentlicht seinen SHA-256 als `manifest_sha256` im Änderungsverlauf. Gehasht werden die UTF-8-Bytes des gespeicherten JSON-Bodys vor HTTP-Komprimierung. Der Empfänger hasht die empfangenen dekomprimierten Bytes vor dem Parsen. Für Medien werden die unveränderten Originalbytes geprüft. Setzt eine neue Paketfassung Teile neu zusammen, entsteht ein eigener Manifest-Hash. Der Status der Freigabe steht im Änderungsverlauf und verändert die gespeicherten Paketbytes nicht.
|
||||
|
||||
## 3. Schnittstelle und Änderungsverlauf
|
||||
|
||||
Die drei Lesezugriffe laufen serverseitig über TLS unter `/api/distribution/v1` mit `Authorization: Bearer <distribution-key>`. Shinkan leitet Empfänger und Kanal aus der Anbindung ab. Eine Änderung der URL-Parameter oder der Ressourcen-UUID wechselt den Kanal nicht.
|
||||
|
||||
| Zugriff | Verhalten |
|
||||
|---|---|
|
||||
| `GET /changes?cursor=&limit=` | Liefert `events`, `next_cursor` und `has_more`. Ohne Cursor beginnt die Wiedergabe am Anfang der für den Kanal verfügbaren v1-Historie. `limit` ist optional und auf 1–100 begrenzt, Standard 50. Ein Cursor ist opaque, kanalgebunden und bezieht sich auf die letzte gelieferte Position. |
|
||||
| `GET /releases/{release_id}` | Liefert Manifestbytes für zugängliche Pakete. |
|
||||
| `GET /releases/{release_id}/assets/{asset_id}` | Liefert die im Manifest festgeschriebenen Medienbytes. Der Abruf prüft zusätzlich die Verfügbarkeit und die Zugehörigkeit des Mediums zum Paket. |
|
||||
|
||||
Ein Ereignis enthält `event_id`, `type`, `release_id`, `occurred_at` und bei zielgenauen Rückzügen `target_id`. `release.published` enthält zusätzlich `source_id`, `revision` und `manifest_sha256`. Rückzüge enthalten `reason_code` aus `rights`, `safety`, `privacy`, `expired` und `editorial_error`. Vertrauliche Begründungen bleiben in Shinkan. `release.retired` sperrt eine redaktionell abgelöste Fassung für neue Planbindungen. Sie kann bei weiterbestehenden Rechten für bereits veröffentlichte Stände auslieferbar bleiben. `release.withdrawn`, `variant.withdrawn` und `asset.withdrawn` sperren das bezeichnete Ziel. Eine spätere Freigabe erfolgt als neues Paket. Ein unbekannter Ereignistyp in v1 löst einen Abgleichfehler aus. Der Empfänger bestätigt die Position erst, wenn das Ereignis verarbeitet werden kann.
|
||||
|
||||
Ereignisse sind je Kanal ab der letzten bestätigten Position lückenlos und in Commit-Reihenfolge abrufbar. Gleichzeitige Freigaben dürfen einen später bestätigten Cursor nicht an einer noch ungesicherten Änderung vorbeiführen. Lara & Felix verarbeitet eine Seite dauerhaft und speichert erst dann `next_cursor`. Nach einem Abbruch darf die Seite erneut bearbeitet werden. Fehlgeschlagene Downloads werden aus einer dauerhaften Importaufgabe wiederholt. So kann ein späterer Rückzug verarbeitet werden, während ein früherer Download noch aussteht. Ein Rückzug, den Lara & Felix vor dem Import erhält, wird vorgemerkt und verhindert ein verspätetes Freischalten.
|
||||
|
||||
Für v1 bleibt der Änderungsverlauf seit Einführung des Kanals abrufbar, soweit die erforderlichen Nachweise rechtmäßig gespeichert werden dürfen. Die Historie enthält Kennungen, Prüfsummen, Zeiten und Grundklassen. Ein unbrauchbarer Cursor liefert `400` mit `invalid_cursor`. Wiederaufbau erfolgt durch vollständige Wiedergabe und Abgleich mit der lokalen Sperrliste. Ungültige Schlüssel liefern `401`, gültige Schlüssel ohne Abrufumfang `403`, unbekannte oder kanalfremde Ressourcen `404`. Für zum Kanal gehörende Pakete mit Rückzug liefern Manifest und Medien `410`. Unterschreitet die Verfügbarkeit die technischen Anforderungen, sind vorübergehende Serverfehler wiederholbar. Abgerufene Daten und Antworten auf gesperrte Abrufe werden von gemeinsam genutzten HTTP-Zwischenspeichern ausgeschlossen.
|
||||
|
||||
## 4. Rückzug, Übernahme und lokale Verwendung
|
||||
|
||||
Beim Rückzug eines einzelnen Mediums oder einer Variante sperrt Shinkan das ursprüngliche Paket für weitere Übernahmen. Bereits übernommene lokale Daten werden anhand der gelieferten Ziel-ID bewertet. Ein bestehender Plan kann weiter ausgeliefert werden, sofern sein veröffentlichter Stand das gesperrte Ziel und alle davon abhängigen Bestandteile ausklammert, die Durchführung vollständig bleibt und die übrigen Freigaben wirksam sind. Für neue Übernahmen gibt der Herausgeber ein neues Paket ohne das gesperrte Material frei. Ein vollständiger Paketrückzug sperrt alle lokalen Verwendungen dieses Pakets. Bei einer Sperre am zentralen Quellmedium werden alle freigegebenen Pakete mit diesem Medium ermittelt und adressatengerecht gemeldet.
|
||||
|
||||
Lara & Felix nimmt Pakete zunächst in einen geschützten Importbereich auf und stellt sie nach vollständiger Prüfung der Redaktion bereit. Ein eindeutiger Schlüssel aus Quellinstanz und `release_id` verhindert Duplikate. Ändert sich das Manifest unter derselben ID, wird die Übernahme als Integritätsfehler gestoppt. Der veröffentlichte Trainingsplan bindet lokale Übungsfassung, Variante und tatsächlich eingeschlossene Teile und Medien. Eine neue Shinkan-Fassung erzeugt einen Hinweis mit Verwendungsnachweis. Übernahme in einen Plan und Veröffentlichung eines neuen Artikel-Stands sind lokale Redaktionsentscheidungen. [Fassungsbindung und Rückzug in Lara & Felix](C:/dev/lara-und-felix.de/docs/architektur/06_Versionierung_und_Veroeffentlichung.md:161)
|
||||
|
||||
Lara & Felix berücksichtigt Rechtefristen bei Veröffentlichung und Abruf anhand der gelieferten Gültigkeit. Shinkan setzt abgelaufene Freigaben beim Abruf durch und schreibt Rückzugseinträge. Die Aufnahme eines älteren Pakets in einen laufenden Lizenzartikel richtet sich nach der lokalen Freigabeentscheidung und dem Rechteumfang. Die Auslieferung aus Lara & Felix läuft bei einem gewöhnlichen Shinkan-Ausfall mit den dort gültigen und lokal ungesperrten Fassungen weiter. Bei einer dringenden Meldung kann der Betreiber in Lara & Felix direkt sperren. Bereits heruntergeladene Kopien werden über den dokumentierten Folgeprozess behandelt.
|
||||
|
||||
Als Startwerte für die Testinstanz gelten Abruf im 60-Sekunden-Takt und ein Ziel von höchstens fünf Minuten vom bestätigten Shinkan-Rückzug bis zur lokalen Sperre bei erreichbaren Systemen. Die Zeit schließt im End-to-End-Test die tatsächlich auslaufenden oder widerrufenen Abruflinks ein. Störungen werden über Abgleichalter und Rückzugslaufzeit sichtbar. Vor dem Produktivstart legen beide Betreiber Betriebsziel, Alarmweg, Zuständigkeit und Regeln für eine länger unterbrochene Synchronisation fest. Ein optionaler Hinweis über einen Webhook kann später denselben Abgleich anstoßen.
|
||||
|
||||
## 5. Referenzfall für beide Projekte
|
||||
|
||||
Die Übung „Raum und Wege wahrnehmen“ hat zwei Varianten. Die Filmvariante braucht das Medium, die Kartenvariante kommt mit ihrer eigenen Anleitung aus. Plan A bindet die Filmvariante, Plan B die Kartenvariante. Eine Korrektur in Shinkan erzeugt ein neues Paket. Beide bestehenden Pläne behalten ihre Bindung. Wird das gemeinsame Filmmedium der bisherigen Fassungen zurückgezogen, endet die Ausgabe von Plan A. Plan B bleibt bei vollständig aufgelöster Kartenvariante verfügbar. Für die nächste Übernahme kann eine bereinigte Übungsfassung veröffentlicht werden. Ein zweiter Testverein veröffentlicht eine eigene Übung für seine Website und erhält ausschließlich die Freigaben seines Kanals.
|
||||
|
||||
Das [maschinenlesbare Referenzpaket](./Shinkan_Lara_Felix_Referenzfall_v1.json) enthält vier Lieferpakete, sieben Ereignisse und vier Planbindungen. Die Medienbytes sind synthetisches Testmaterial für Prüfsummen und Übernahmelogik. Die Spezifikationsprobe vom 23.11.2026 prüfte die Referenzen, Hashes, Kanalzuordnung, wiederholte Ereignisverarbeitung, lokale Fassungsbindung und die Auswirkungen des Rückzugs. Beide Filmpläne waren betroffen. Der Kartenplan und der Plan aus dem eigenen Bestand blieben im Modell verfügbar. Die Probe lief mit Beispieldaten außerhalb der laufenden Anwendungen. Die technische Abnahme auf der Testinstanz steht aus. Die Fachanforderungen an den Shinkan-Teil stehen im [Shinkan-Fachkonzept v1](./Shinkan_Uebungsfreigabe_Fachkonzept_v1.md).
|
||||
@@ -1,58 +0,0 @@
|
||||
# Shinkan-Fachkonzept für die mandantenfähige Übungsfreigabe · Version 1.0
|
||||
|
||||
**23.11.2026 · Umsetzungsauftrag für die Testinstanz**
|
||||
|
||||
Implementiere in Shinkan die Freigabe eingefrorener Übungsfassungen für vereinbarte Empfänger. Der Pilot deckt einen eigenen Bestand, einen gemeinsam gepflegten Vereinsbestand und einen unabhängigen zweiten Verein mit eigener Website-Anbindung ab. Lara & Felix ist der erste produktive Anwendungsfall. Der Daten- und Schnittstellenvertrag gilt für alle Empfänger. Er steht im [Übergabevertrag v1](./Shinkan_Lara_Felix_Uebergabevertrag_v1.md). Die Freischaltung für reale Inhalte und Kunden erfolgt nach gesonderter Betriebsabnahme.
|
||||
|
||||
## 1. Ausgangslage und Umfang
|
||||
|
||||
Der geprüfte Repository-Stand meldet Shinkan 0.8.250. Übungen führen heute unter anderem interne Sichtbarkeit, Status, Ersteller und Vereinsbezug. Shinkan prüft Bearbeitungsrechte anhand von Ersteller, Plattformrolle und Vereinsfunktion. Medien können im Text eingebettet sein, und Kombinationsübungen können auf weitere Übungen verweisen. Die vorhandene Mediensperre erfasst unter anderem Rechtekonflikte. Diese Funktionen sind Anknüpfungspunkte für die neue externe Freigabe. [Versionsstand](C:/Dev/shinkan-jinkendo/backend/version.py:3) · [Übungsschema](C:/Dev/shinkan-jinkendo/backend/migrations/005_exercises.sql:6) · [Bearbeitungsrechte](C:/Dev/shinkan-jinkendo/backend/routers/exercises.py:551) · [Mediensperre](C:/Dev/shinkan-jinkendo/backend/media_legal_hold.py:68)
|
||||
|
||||
Der Auftrag umfasst einfache Übungen, deren Varianten, Texte und freigegebene Medien, einen Freigabeablauf an der Übung, einen lesenden Distributionszugang und einen nachholbaren Rückzug. Die v1-Anbindung nutzt eine administrativ eingerichtete Integration je Empfänger. Vereins-Selbstverwaltung für die Einrichtung, Webhooks, der Export von Kombinationsübungen oder ganzen Trainingsrahmen und die Umsetzung des Lara-&-Felix-Planeditors sind eigenständige Ausbauschritte. Alle Änderungen sind additiv zur produktiven Mandanten- und Sichtbarkeitslogik zu implementieren.
|
||||
|
||||
## 2. Zuständigkeiten im Pilot
|
||||
|
||||
| Rolle | Aufgabe und Prüfung |
|
||||
|---|---|
|
||||
| Person mit privater Übung | Gibt die Übungen frei, die ihr gehören. Das ist der gewöhnliche Fall. Sie sieht vor dem Absenden, welche Texte, Varianten und Medien im Lieferpaket landen. |
|
||||
| Vereinsadmin | Gibt die Vereinsübungen seines Vereins frei. Mitgliedschaft oder allgemeines Bearbeitungsrecht allein reichen nicht. |
|
||||
| Superadmin | Gibt globale Übungen frei. Das ist der seltene Fall. Der Plattformzugriff auf fremde private oder Vereinsübungen begründet keine Herausgabe. |
|
||||
| Shinkan-Betrieb | Richtet im Pilot Herausgeber, Empfänger, zugelassene Beziehungen und Anbindungen ein. Er kann im Eskalationsfall sperren und Zugänge widerrufen. |
|
||||
| Maschinenanbindung | Liest freigegebene Pakete ihres Empfängers mit eigenem Schlüssel. Freigeben, Bearbeiten und Wechseln des Quell- oder Empfängerkontexts bleiben menschlichen Rollen vorbehalten. |
|
||||
|
||||
Die Herkunft aus eigenem oder Vereinsbestand verwendet denselben Freigabeablauf. Austritt oder Entfernen der Rolle beendet die Berechtigung zu weiteren Freigaben. Bestehende Freigaben bleiben beim verantwortlichen Herausgeber und werden anhand der belegten Rechte und Laufzeit bewertet. Für verwaiste Bestände und das Ende einer Herausgeber-Empfänger-Beziehung muss der Betrieb klären können, wer übernimmt oder welche laufenden Freigaben auslaufen beziehungsweise zurückgezogen werden.
|
||||
|
||||
## 3. Redaktionsablauf
|
||||
|
||||
1. **Freigabe vorbereiten.** Die berechtigte Person wählt an der Übung einen zugelassenen Empfänger. Shinkan zeigt die Übungsdaten, Varianten, zugehörigen Medien, Rechtevermerke und gegebenenfalls blockierende Abhängigkeiten in einer Vorschau. Die kanalspezifische Auswahl bleibt ein Freigabeentwurf.
|
||||
2. **Rechte und Nutzbarkeit prüfen.** Für die Pilotfunktion sind einfache Übungen mit Shinkan-Status `approved` zur externen Freigabe zugelassen. Die Freigabe prüft den aktuellen Status, Befugnis, Herausgeber-Empfänger-Zuordnung, Rechteumfang, zeitliche Gültigkeit, Medienzustand und alle ausgewählten Abhängigkeiten. Material mit unbekanntem oder gesperrtem Status erfordert Klärung oder eine fachlich vollständige alternative Zusammenstellung. Die Vorschau muss für Klartext und Medienzuordnung vollständig sein. [Medienrechte](C:/Dev/shinkan-jinkendo/backend/media_rights.py:21) · [Inline-Medien](C:/Dev/shinkan-jinkendo/backend/exercise_rich_text.py:167)
|
||||
3. **Verbindlich freigeben.** Shinkan zeigt Empfänger, Titel, Varianten, Medien und Nutzungsumfang zur Bestätigung. Haben sich fachlicher Stand, Rechte oder Medien seit der Vorschau geändert, ist die Vorschau vor einer Bestätigung neu zu erstellen. Freigabe erzeugt ein unveränderliches Paket und einen Eintrag im Änderungsverlauf. Der Vorgang protokolliert verantwortliche Person, Zeitpunkt und private Nachweisreferenz. Wiederholen derselben Bestätigung erzeugt kein zweites Paket. Ein ausdrücklich neuer Empfängerzuschnitt darf eine neue Freigabe erzeugen.
|
||||
4. **Überarbeiten und zurückziehen.** Die Übung zeigt, welche Fassungen für welche Empfänger freigegeben sind. Eine Änderung am Original bleibt normale Redaktion. Eine neue Freigabe kann die bisherige für neue Pläne ablösen. Ein Rückzug kann ein gesamtes Paket, eine Variante oder ein Medium betreffen. Die Redaktion sieht vor der Bestätigung die betroffenen Pakete und Empfänger und erfasst eine Grundklasse. Ein bestätigter akuter Rückzug blockiert den Quellabruf und ist über den Änderungsverlauf nachholbar.
|
||||
|
||||
Der Freigabe-Check muss für Texte, Filme, Bilder und PDFs nachvollziehbar sein. Die Rechte an Training, Kursvorführung, kommerzieller Nutzung, Kopien und Bearbeitung folgen den belegten Vereinbarungen. Eine bestätigte Upload-Erklärung oder die Shinkan-Sichtbarkeit allein trägt die externe Veröffentlichung nicht. Bei erkennbaren Personen sind Rechtsgrundlage, Zweck, erforderliche Nachweise und Löschprozess zu klären. Vertrauliche Belege werden in Shinkan zugriffsbeschränkt gehalten. [§ 31 UrhG](https://www.gesetze-im-internet.de/urhg/__31.html) · [DSGVO, insbesondere Art. 5, 7, 17 und 19](https://eur-lex.europa.eu/legal-content/DE/TXT/?uri=CELEX%3A32016R0679)
|
||||
|
||||
## 4. Anforderungen an Daten und Betrieb
|
||||
|
||||
- **Unveränderliche Medien und nachvollziehbare Quelle.** Speichere oder referenziere persistente Medienobjekte mit überprüften Bytes und Hash. Eine Änderung oder Löschung am Arbeitsmaterial darf freigegebene Bytes nicht unbemerkt ändern. Erhalte stabile Übungs- und Variantenkennungen. Halte getrennt, welche Quellrevision eingefroren wurde und wie das Paket für den Empfänger zugeschnitten ist.
|
||||
- **Vollständige Freigabe.** Stelle die Medien vor der abschließenden Datenbankfreigabe bereit. Prüfe unmittelbar vor dem Commit Quellstatus, Rechte und Sperren. Paket, auditierbare Entscheidung und Ereignis werden gemeinsam sichtbar. Ein abgebrochener Vorgang hinterlässt keine abrufbare Teilfreigabe. Verwende für Freigabe und Sperre eine gemeinsame Synchronisationsgrenze pro betroffenem Objekt. Sichere die Commit-Reihenfolge des kanalgebundenen Änderungsverlaufs.
|
||||
- **Zugriff je Anbindung.** Schlüssel werden einmal angezeigt, serverseitig als nicht rückrechenbarer Prüfwert gespeichert und außerhalb von Logs, URLs und Browser-Auslieferung gehalten. Ziehe bestehenden Infrastruktur- und Schlüssellebenszyklus heran. Richte Ablauf, Widerruf, Rotation mit kontrollierter Übergangszeit und angemessene Abrufbegrenzung pro Anbindung ein. Prüfe Kanal und Ressource bei jedem Abruf von Liste, Manifest und Medium. Deaktiviere gemeinsam genutzte Caches für die Distributionspfade. Der Zugriff alter Schlüssel endet zum vorgesehenen Zeitpunkt, auch bei laufenden Abrufen in den vereinbarten Zeitgrenzen.
|
||||
- **Quellsperre und Verwendungen.** Halte fest, welche Pakete das jeweilige Quellmedium enthalten. Eine zentrale Mediensperre verhindert weiteren Abruf und erzeugt für alle betroffenen Kanäle und Pakete dauerhafte Rückzugsinformationen. Für einen Rückzug durch Datenbereinigung oder Löschung bleibt ein minimaler, rechtmäßig aufbewahrbarer Nachweis über Paket-ID, Zeitpunkt und Grundklasse nutzbar. Überprüfe Übungs-, Varianten- und Medienlöschung sowie Aufbewahrung und Löschung personenbezogener Inhalte bei aktiven Freigaben. Eine Löschkaskade darf laufende Veröffentlichungen nicht unbemerkt in einen unauflösbaren Zustand bringen.
|
||||
- **Wiederanlauf.** Protokolliere Freigaben, Rückzüge, Schlüsselereignisse und blockierte Vorgänge ohne Schlüssel oder vertrauliche Nachweise im Log. Mache Rückstand bei ausstehenden Rückzügen sichtbar. Das Wiederherstellungsverfahren muss Rückzüge und Medienzustände vor erneuter Auslieferung abgleichen. Der Ausfall der neuen Distributionsfunktion darf Planung und Übungen im bestehenden Trainerbetrieb nicht blockieren.
|
||||
|
||||
## 5. Umsetzung und Abnahme auf der Testinstanz
|
||||
|
||||
| Fall | Beobachtbares Ergebnis |
|
||||
|---|---|
|
||||
| Eigener Bestand und gemeinsam gepflegter Vereinsbestand | Beide veröffentlichen über dieselbe Freigabefunktion an Lara & Felix. Herkunft, befugte Person, Paket und Nutzungsumfang sind nachvollziehbar. |
|
||||
| Unabhängiger zweiter Verein | Der Verein veröffentlicht eine eigene Übung für seine Website. Beide Anbindungen rufen nur ihren Kanal ab. Für Paket, Medien und Änderungsverlauf ist dies durch positive und negative Mandantentests belegt. Empfänger und Zugangsdaten stammen aus Konfiguration und Verwaltung. |
|
||||
| Rollen und Status | Bearbeitung, interne Sichtbarkeit und externe Freigabebefugnis werden getrennt entschieden. Fehlende Rolle, ausgetretener Vereinsnutzer, falscher Empfänger, fehlender Nachweis, unzulässige Medien und gesperrter Übungsstand führen zu verständlichen Ablehnungen. |
|
||||
| Stabilität und Integrität | Die publizierte Fassung bleibt bei späterer Bearbeitung bytegleich. Bei Wiederholung, Abbruch oder paralleler Änderung entstehen weder doppelte Bestätigungen noch halbe Pakete. Der Hash für Manifest und Medien stimmt mit dem Abruf überein. |
|
||||
| Abruf und Schlüssel | Schlüsselwechsel, Ablauf und Widerruf wirken pro Anbindung. Ein neu autorisierter Schlüssel für denselben Kanal kann den bestehenden Änderungsverlauf weiter abrufen. Der Trainer-Login arbeitet nach den bisherigen Regeln. |
|
||||
| Rückzug und Wiederanlauf | Publizieren und Sperren können sich bei Parallelität nicht gegenseitig übergehen. Ein Medienrückzug erreicht jede betroffene Fassung und jeden berechtigten Kanal. Mehrseitiger Abruf mit Absturz, Wiederholung und Wiederherstellung verliert keine Rückzugsmeldung. Gesperrte Paket- und Medienrouten lehnen den Abruf auch direkt ab. |
|
||||
| Gemeinsamer Film- und Kartenfall | Eine Korrektur ergibt eine neue Fassung. Beim Filmrückzug liefern die Ereignisse genügend Informationen, damit ein Testempfänger Filmplan und Kartenplan gezielt beurteilen kann. Ein echter Lara-&-Felix-End-to-End-Test folgt vor produktiver Auslieferung. |
|
||||
|
||||
Bereitstellung als additive Migration mit zunächst deaktivierter produktiver Distribution. Verwende die vorhandenen Shinkan-Standards für Migrationen, Testinstanz und Deployment. Der Agent liefert den Abgleich mit dem aktuellen Repository, die Umsetzung, Testbefehle und Ergebnisse, Beispielantworten für beide Empfänger, den Ablauf für Schlüssel und Störung sowie offene Abweichungen. Vor Freischaltung ist ein Rückfalltest vorzulegen, bei dem die Distribution pausiert, Rückzüge erhalten bleiben und der Trainerbetrieb weiterläuft.
|
||||
|
||||
## 6. Freigabe für reale Inhalte
|
||||
|
||||
Für die technische Umsetzung auf der Testinstanz gelten synthetische Inhalte und Testbefugnisse. Für die produktive Freigabe müssen die tatsächlichen Pilotübungen aus beiden Beständen, Rechtebelege und vertretungsberechtigten Personen feststehen. Beide Betreiber stimmen Rechteablauf, Meldeweg und Reaktionszeit bei Rückzug ab. Lara & Felix weist die Sperre bis zur tatsächlichen Ausgabe einschließlich Altständen und noch gültiger Abruflinks nach. Änderungen an bestehendem Produktivbestand und eine Freischaltung von Vereinen erfolgen auf Grundlage dieser Abnahme.
|
||||
@@ -88,7 +88,7 @@ Schmale Ausführungsschicht für admin-konfigurierbare Prompts in `ai_prompts`:
|
||||
| **Begründung** | Modellwechsel ohne Router-Anpassung. |
|
||||
| **Quelle** | `AI_PROMPT_TARGET_ARCHITECTURE.md` §2.2 |
|
||||
| **Tragfähigkeit** | **hoch** |
|
||||
| **Einschränkung** | Auflösung: Prompt-Spalte `openrouter_model`, sonst `platform_ai_settings` (Migration 097), sonst `OPENROUTER_MODEL`. |
|
||||
| **Einschränkung** | Modell teils global Env, teils Spalte `openrouter_model` — Konvergenz offen. |
|
||||
|
||||
### 6. Reset-to-default für System-Prompts
|
||||
|
||||
|
||||
@@ -21,12 +21,10 @@ server {
|
||||
# auf /media/ den FastAPI StaticFiles-Mount unter /media und der Browser zeigt {"detail":"Not Found"}.
|
||||
location = /media {
|
||||
add_header Content-Security-Policy "default-src 'self'; base-uri 'self'; form-action 'self'; frame-ancestors 'self'; object-src 'none'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob: https:; font-src 'self' data:; connect-src 'self'; media-src 'self' blob: data:; worker-src 'self' blob:; manifest-src 'self';" always;
|
||||
add_header Cache-Control "no-cache" always;
|
||||
try_files /index.html =404;
|
||||
}
|
||||
location = /media/ {
|
||||
add_header Content-Security-Policy "default-src 'self'; base-uri 'self'; form-action 'self'; frame-ancestors 'self'; object-src 'none'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob: https:; font-src 'self' data:; connect-src 'self'; media-src 'self' blob: data:; worker-src 'self' blob:; manifest-src 'self';" always;
|
||||
add_header Cache-Control "no-cache" always;
|
||||
try_files /index.html =404;
|
||||
}
|
||||
|
||||
@@ -66,7 +64,6 @@ server {
|
||||
# Document-CSP für SPA/PWA — React nutzt häufig inline-styles; Mediendateien & API sind same-origin (Proxy).
|
||||
# Bei separater API-Origin: connect-src hier erweitern oder nginx-Envsubst nutzen.
|
||||
add_header Content-Security-Policy "default-src 'self'; base-uri 'self'; form-action 'self'; frame-ancestors 'self'; object-src 'none'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob: https:; font-src 'self' data:; connect-src 'self'; media-src 'self' blob: data:; worker-src 'self' blob:; manifest-src 'self';" always;
|
||||
add_header Cache-Control "no-cache" always;
|
||||
try_files $uri $uri/ /index.html;
|
||||
}
|
||||
|
||||
|
||||
@@ -27,8 +27,5 @@
|
||||
"jsdom": "^29.1.1",
|
||||
"vite": "^5.1.4",
|
||||
"vitest": "^3.0.5"
|
||||
},
|
||||
"overrides": {
|
||||
"@bramus/specificity": "2.4.3"
|
||||
}
|
||||
}
|
||||
+39
-58
@@ -1,4 +1,4 @@
|
||||
import React, { Suspense } from 'react'
|
||||
import React, { Suspense, lazy } from 'react'
|
||||
import LoginPage from './pages/LoginPage'
|
||||
import { lazyWithRetry } from './utils/lazyWithRetry'
|
||||
import {
|
||||
@@ -25,51 +25,48 @@ import TotpSetupCard from './components/TotpSetupCard'
|
||||
import './app.css'
|
||||
|
||||
const OnboardingPage = lazyWithRetry(() => import('./pages/OnboardingPage'))
|
||||
const VerifyPage = lazyWithRetry(() => import('./pages/VerifyPage'))
|
||||
const Dashboard = lazyWithRetry(() => import('./pages/Dashboard'))
|
||||
const AccountSettingsPage = lazyWithRetry(() => import('./pages/AccountSettingsPage'))
|
||||
const SettingsSystemInfoPage = lazyWithRetry(() => import('./pages/SettingsSystemInfoPage'))
|
||||
const ExercisesListPage = lazyWithRetry(() => import('./pages/ExercisesListPage'))
|
||||
const ExerciseDetailPage = lazyWithRetry(() => import('./pages/ExerciseDetailPage'))
|
||||
const ExerciseFormPage = lazyWithRetry(() => import('./pages/ExerciseFormPage'))
|
||||
const ProgressionGraphEditPage = lazyWithRetry(() => import('./pages/ProgressionGraphEditPage'))
|
||||
const ClubsPage = lazyWithRetry(() => import('./pages/ClubsPage'))
|
||||
const InboxPage = lazyWithRetry(() => import('./pages/InboxPage'))
|
||||
const SkillsPage = lazyWithRetry(() => import('./pages/SkillsPage'))
|
||||
const TrainingPlanningPage = lazyWithRetry(() => import('./pages/TrainingPlanningPage'))
|
||||
const TrainingPlanTemplatesListPage = lazyWithRetry(() => import('./pages/TrainingPlanTemplatesListPage'))
|
||||
const TrainingPlanTemplateEditPage = lazyWithRetry(() => import('./pages/TrainingPlanTemplateEditPage'))
|
||||
const PlanningLayout = lazyWithRetry(() => import('./layouts/PlanningLayout'))
|
||||
const TrainingFrameworkProgramsListPage = lazyWithRetry(() =>
|
||||
const VerifyPage = lazy(() => import('./pages/VerifyPage'))
|
||||
const Dashboard = lazy(() => import('./pages/Dashboard'))
|
||||
const AccountSettingsPage = lazy(() => import('./pages/AccountSettingsPage'))
|
||||
const SettingsSystemInfoPage = lazy(() => import('./pages/SettingsSystemInfoPage'))
|
||||
const ExercisesListPage = lazy(() => import('./pages/ExercisesListPage'))
|
||||
const ExerciseDetailPage = lazy(() => import('./pages/ExerciseDetailPage'))
|
||||
const ExerciseFormPage = lazy(() => import('./pages/ExerciseFormPage'))
|
||||
const ProgressionGraphEditPage = lazy(() => import('./pages/ProgressionGraphEditPage'))
|
||||
const ClubsPage = lazy(() => import('./pages/ClubsPage'))
|
||||
const InboxPage = lazy(() => import('./pages/InboxPage'))
|
||||
const SkillsPage = lazy(() => import('./pages/SkillsPage'))
|
||||
const TrainingPlanningPage = lazy(() => import('./pages/TrainingPlanningPage'))
|
||||
const TrainingPlanTemplatesListPage = lazy(() => import('./pages/TrainingPlanTemplatesListPage'))
|
||||
const TrainingPlanTemplateEditPage = lazy(() => import('./pages/TrainingPlanTemplateEditPage'))
|
||||
const PlanningLayout = lazy(() => import('./layouts/PlanningLayout'))
|
||||
const TrainingFrameworkProgramsListPage = lazy(() =>
|
||||
import('./pages/TrainingFrameworkProgramsListPage'),
|
||||
)
|
||||
const TrainingFrameworkProgramEditPage = lazyWithRetry(() =>
|
||||
const TrainingFrameworkProgramEditPage = lazy(() =>
|
||||
import('./pages/TrainingFrameworkProgramEditPage'),
|
||||
)
|
||||
const TrainingModulesListPage = lazyWithRetry(() => import('./pages/TrainingModulesListPage'))
|
||||
const TrainingModuleEditPage = lazyWithRetry(() => import('./pages/TrainingModuleEditPage'))
|
||||
const TrainingUnitRunPage = lazyWithRetry(() => import('./pages/TrainingUnitRunPage'))
|
||||
const TrainingUnitEditPage = lazyWithRetry(() => import('./pages/TrainingUnitEditPage'))
|
||||
const TrainingCoachPage = lazyWithRetry(() => import('./pages/TrainingCoachPage'))
|
||||
const AdminCatalogsPage = lazyWithRetry(() => import('./pages/AdminCatalogsPage'))
|
||||
const AdminHierarchyPage = lazyWithRetry(() => import('./pages/AdminHierarchyPage'))
|
||||
const AdminMaturityModelsPage = lazyWithRetry(() => import('./pages/AdminMaturityModelsPage'))
|
||||
const TrainerContextsPage = lazyWithRetry(() => import('./pages/TrainerContextsPage'))
|
||||
const MediaWikiImportPage = lazyWithRetry(() => import('./pages/MediaWikiImportPage'))
|
||||
const AdminUsersPage = lazyWithRetry(() => import('./pages/AdminUsersPage'))
|
||||
const AdminClubCreationRequestsPage = lazyWithRetry(() => import('./pages/AdminClubCreationRequestsPage'))
|
||||
const AdminRightsPage = lazyWithRetry(() => import('./pages/AdminRightsPage'))
|
||||
const AdminDistributionPage = lazyWithRetry(() => import('./pages/AdminDistributionPage'))
|
||||
const AdminReleaseUpdatesPage = lazyWithRetry(() => import('./pages/AdminReleaseUpdatesPage'))
|
||||
const MediaLibraryPage = lazyWithRetry(() => import('./pages/MediaLibraryPage'))
|
||||
const LegalPage = lazyWithRetry(() => import('./pages/LegalPage'))
|
||||
const AdminLegalDocumentsPage = lazyWithRetry(() => import('./pages/AdminLegalDocumentsPage'))
|
||||
const AdminAiSkillRetrievalPage = lazyWithRetry(() => import('./pages/AdminAiSkillRetrievalPage'))
|
||||
const AdminAiPromptsPage = lazyWithRetry(() => import('./pages/AdminAiPromptsPage'))
|
||||
const AdminOpenRouterPage = lazyWithRetry(() => import('./pages/AdminOpenRouterPage'))
|
||||
const AdminExerciseEnrichmentPage = lazyWithRetry(() => import('./pages/AdminExerciseEnrichmentPage'))
|
||||
const AdminUserContentPage = lazyWithRetry(() => import('./pages/AdminUserContentPage'))
|
||||
const SettingsLegalPage = lazyWithRetry(() => import('./pages/SettingsLegalPage'))
|
||||
const TrainingModulesListPage = lazy(() => import('./pages/TrainingModulesListPage'))
|
||||
const TrainingModuleEditPage = lazy(() => import('./pages/TrainingModuleEditPage'))
|
||||
const TrainingUnitRunPage = lazy(() => import('./pages/TrainingUnitRunPage'))
|
||||
const TrainingUnitEditPage = lazy(() => import('./pages/TrainingUnitEditPage'))
|
||||
const TrainingCoachPage = lazy(() => import('./pages/TrainingCoachPage'))
|
||||
const AdminCatalogsPage = lazy(() => import('./pages/AdminCatalogsPage'))
|
||||
const AdminHierarchyPage = lazy(() => import('./pages/AdminHierarchyPage'))
|
||||
const AdminMaturityModelsPage = lazy(() => import('./pages/AdminMaturityModelsPage'))
|
||||
const TrainerContextsPage = lazy(() => import('./pages/TrainerContextsPage'))
|
||||
const MediaWikiImportPage = lazy(() => import('./pages/MediaWikiImportPage'))
|
||||
const AdminUsersPage = lazy(() => import('./pages/AdminUsersPage'))
|
||||
const AdminClubCreationRequestsPage = lazy(() => import('./pages/AdminClubCreationRequestsPage'))
|
||||
const AdminRightsPage = lazy(() => import('./pages/AdminRightsPage'))
|
||||
const MediaLibraryPage = lazy(() => import('./pages/MediaLibraryPage'))
|
||||
const LegalPage = lazy(() => import('./pages/LegalPage'))
|
||||
const AdminLegalDocumentsPage = lazy(() => import('./pages/AdminLegalDocumentsPage'))
|
||||
const AdminAiSkillRetrievalPage = lazy(() => import('./pages/AdminAiSkillRetrievalPage'))
|
||||
const AdminAiPromptsPage = lazy(() => import('./pages/AdminAiPromptsPage'))
|
||||
const AdminExerciseEnrichmentPage = lazy(() => import('./pages/AdminExerciseEnrichmentPage'))
|
||||
const AdminUserContentPage = lazy(() => import('./pages/AdminUserContentPage'))
|
||||
const SettingsLegalPage = lazy(() => import('./pages/SettingsLegalPage'))
|
||||
|
||||
/** Shield „Admin“: nur Super-Admin (global). Vereinsorga: Vereine → Mitglieder. */
|
||||
function computeShowAdminNav(currentUser) {
|
||||
@@ -325,14 +322,6 @@ const appRouter = createBrowserRouter([
|
||||
</PlatformAdminRoute>
|
||||
),
|
||||
},
|
||||
{
|
||||
path: 'admin/distribution',
|
||||
element: <AdminDistributionPage />,
|
||||
},
|
||||
{
|
||||
path: 'admin/release-updates',
|
||||
element: <AdminReleaseUpdatesPage />,
|
||||
},
|
||||
{
|
||||
path: 'admin/rights',
|
||||
element: (
|
||||
@@ -398,14 +387,6 @@ const appRouter = createBrowserRouter([
|
||||
</PlatformAdminRoute>
|
||||
),
|
||||
},
|
||||
{
|
||||
path: 'admin/openrouter',
|
||||
element: (
|
||||
<PlatformAdminRoute>
|
||||
<AdminOpenRouterPage />
|
||||
</PlatformAdminRoute>
|
||||
),
|
||||
},
|
||||
{
|
||||
path: 'admin/exercise-enrichment',
|
||||
element: (
|
||||
|
||||
@@ -1,104 +0,0 @@
|
||||
import { request } from './client.js'
|
||||
|
||||
export function getExerciseDistribution(exerciseId) {
|
||||
return request(`/api/exercises/${exerciseId}/distribution`)
|
||||
}
|
||||
|
||||
export function createDistributionDraft(exerciseId, body) {
|
||||
return request(`/api/exercises/${exerciseId}/distribution/drafts`, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(body),
|
||||
})
|
||||
}
|
||||
|
||||
export function updateDistributionDraft(exerciseId, draftId, cut) {
|
||||
return request(`/api/exercises/${exerciseId}/distribution/drafts/${draftId}`, {
|
||||
method: 'PUT',
|
||||
body: JSON.stringify({ cut }),
|
||||
})
|
||||
}
|
||||
|
||||
export function confirmDistributionDraft(exerciseId, draftId) {
|
||||
return request(`/api/exercises/${exerciseId}/distribution/drafts/${draftId}/confirm`, {
|
||||
method: 'POST',
|
||||
body: '{}',
|
||||
})
|
||||
}
|
||||
|
||||
export function withdrawDistributionRelease(releaseId, reasonCode) {
|
||||
return request(`/api/distribution/releases/${releaseId}/withdraw`, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ reason_code: reasonCode }),
|
||||
})
|
||||
}
|
||||
|
||||
export function retireDistributionRelease(releaseId) {
|
||||
return request(`/api/distribution/releases/${releaseId}/retire`, { method: 'POST', body: '{}' })
|
||||
}
|
||||
|
||||
export function createDistributionPublisher(body) {
|
||||
return request('/api/distribution/admin/publishers', { method: 'POST', body: JSON.stringify(body) })
|
||||
}
|
||||
|
||||
export function createDistributionRecipient(body) {
|
||||
return request('/api/distribution/admin/recipients', { method: 'POST', body: JSON.stringify(body) })
|
||||
}
|
||||
|
||||
export function createDistributionRelationship(body) {
|
||||
return request('/api/distribution/admin/relationships', { method: 'POST', body: JSON.stringify(body) })
|
||||
}
|
||||
|
||||
export function createDistributionBinding(body) {
|
||||
return request('/api/distribution/admin/bindings', { method: 'POST', body: JSON.stringify(body) })
|
||||
}
|
||||
|
||||
export function issueDistributionKey(bindingId, expiresAt) {
|
||||
return request(`/api/distribution/admin/bindings/${bindingId}/keys`, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ expires_at: expiresAt || null }),
|
||||
})
|
||||
}
|
||||
|
||||
export function assignDistributionReleaser(publisherId, profileId) {
|
||||
return request(`/api/distribution/admin/publishers/${publisherId}/releasers`, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ profile_id: profileId }),
|
||||
})
|
||||
}
|
||||
|
||||
export function assignDistributionExercise(publisherId, exerciseId) {
|
||||
return request(`/api/distribution/admin/publishers/${publisherId}/exercises`, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ exercise_id: exerciseId }),
|
||||
})
|
||||
}
|
||||
|
||||
export function getDistributionBacklog() {
|
||||
return request('/api/distribution/admin/backlog')
|
||||
}
|
||||
|
||||
export function getDistributionAccess() {
|
||||
return request('/api/distribution/access')
|
||||
}
|
||||
|
||||
export function getDistributionReleaseUpdates() {
|
||||
return request('/api/distribution/release-updates')
|
||||
}
|
||||
|
||||
export function setClubDistributionApi(clubId, enabled) {
|
||||
return request(`/api/distribution/access/clubs/${clubId}`, {
|
||||
method: 'PUT',
|
||||
body: JSON.stringify({ enabled }),
|
||||
})
|
||||
}
|
||||
|
||||
export function createDistributionAccessKey(body) {
|
||||
return request('/api/distribution/access/keys', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(body),
|
||||
})
|
||||
}
|
||||
|
||||
export function revokeDistributionAccessKey(keyId) {
|
||||
return request(`/api/distribution/access/keys/${keyId}/revoke`, { method: 'POST', body: '{}' })
|
||||
}
|
||||
@@ -474,14 +474,6 @@ export async function updateExercise(id, data) {
|
||||
return response.json()
|
||||
}
|
||||
|
||||
/** API-Bereitstellung für die aktuelle Auswahl (`PATCH /api/exercises/api-offering`). */
|
||||
export async function patchExerciseApiOffering(data) {
|
||||
return request('/api/exercises/api-offering', {
|
||||
method: 'PATCH',
|
||||
body: JSON.stringify(data),
|
||||
})
|
||||
}
|
||||
|
||||
/** Massenänderung Übungen: Sichtbarkeit, Status, Katalog-Zuordnungen (`PATCH /api/exercises/bulk-metadata`). */
|
||||
export async function bulkPatchExercisesMetadata(data) {
|
||||
return request('/api/exercises/bulk-metadata', {
|
||||
|
||||
@@ -10075,179 +10075,3 @@ button.combo-coach-cand-link:hover {
|
||||
gap: 8px;
|
||||
justify-content: flex-end;
|
||||
}
|
||||
|
||||
/* Superadmin: OpenRouter-Modellkatalog */
|
||||
.or-settings {
|
||||
padding: 16px;
|
||||
margin-bottom: 16px;
|
||||
}
|
||||
.or-settings__line {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 8px 16px;
|
||||
margin: 0 0 8px;
|
||||
align-items: baseline;
|
||||
}
|
||||
.or-settings__line span {
|
||||
min-width: 6.5rem;
|
||||
color: var(--text3);
|
||||
font-size: 13px;
|
||||
}
|
||||
.or-settings__line code,
|
||||
.or-picker__id {
|
||||
font-size: 12px;
|
||||
word-break: break-all;
|
||||
}
|
||||
.or-settings__notice {
|
||||
margin: 8px 0 0;
|
||||
color: var(--accent-dark);
|
||||
}
|
||||
.or-settings__actions {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 8px;
|
||||
margin-top: 12px;
|
||||
}
|
||||
.or-picker__toolbar {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 8px;
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
.or-picker__count {
|
||||
margin: 0;
|
||||
color: var(--text2);
|
||||
font-size: 13px;
|
||||
}
|
||||
.or-picker__filters {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(160px, 1fr));
|
||||
gap: 10px 12px;
|
||||
}
|
||||
.or-picker__filters .form-row {
|
||||
margin-bottom: 0;
|
||||
}
|
||||
.or-picker__note,
|
||||
.or-picker__error,
|
||||
.or-picker__empty {
|
||||
margin: 8px 0;
|
||||
font-size: 13px;
|
||||
}
|
||||
.or-picker__error {
|
||||
color: var(--danger);
|
||||
}
|
||||
.or-picker__note,
|
||||
.or-picker__empty {
|
||||
color: var(--text2);
|
||||
}
|
||||
.or-picker__clear {
|
||||
margin: 12px 0;
|
||||
}
|
||||
.or-picker__list {
|
||||
list-style: none;
|
||||
margin: 12px 0 0;
|
||||
padding: 0;
|
||||
overflow: auto;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 12px;
|
||||
background: var(--surface);
|
||||
}
|
||||
.or-picker__option {
|
||||
width: 100%;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: flex-start;
|
||||
gap: 2px;
|
||||
text-align: left;
|
||||
border: 0;
|
||||
border-bottom: 1px solid var(--border);
|
||||
background: transparent;
|
||||
color: var(--text1);
|
||||
padding: 10px 12px;
|
||||
cursor: pointer;
|
||||
font: inherit;
|
||||
}
|
||||
.or-picker__list li:last-child .or-picker__option {
|
||||
border-bottom: 0;
|
||||
}
|
||||
.or-picker__option:hover {
|
||||
background: var(--surface2);
|
||||
}
|
||||
.or-picker__option--selected {
|
||||
background: var(--surface2);
|
||||
box-shadow: inset 3px 0 0 var(--accent);
|
||||
}
|
||||
.or-picker__option:focus-visible {
|
||||
outline: 2px solid var(--accent);
|
||||
outline-offset: -2px;
|
||||
}
|
||||
.or-picker__name {
|
||||
font-weight: 600;
|
||||
}
|
||||
.or-picker__meta {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 6px 12px;
|
||||
color: var(--text3);
|
||||
font-size: 12px;
|
||||
}
|
||||
.or-model-embed {
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 12px;
|
||||
padding: 10px 12px;
|
||||
background: var(--surface);
|
||||
}
|
||||
.or-model-embed summary {
|
||||
cursor: pointer;
|
||||
font-weight: 600;
|
||||
}
|
||||
.or-model-embed .or-picker {
|
||||
margin-top: 12px;
|
||||
}
|
||||
.or-slot-row {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 8px;
|
||||
margin-bottom: 12px;
|
||||
}
|
||||
.or-role-title {
|
||||
margin: 0 0 6px;
|
||||
font-size: 1.05rem;
|
||||
}
|
||||
.or-role-prompts {
|
||||
list-style: none;
|
||||
margin: 0 0 16px;
|
||||
padding: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
}
|
||||
.or-role-prompts__item {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
justify-content: space-between;
|
||||
gap: 10px 16px;
|
||||
align-items: center;
|
||||
padding: 10px 12px;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 12px;
|
||||
background: var(--surface);
|
||||
}
|
||||
.or-role-prompts__meta {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 6px 12px;
|
||||
margin-top: 4px;
|
||||
color: var(--text3);
|
||||
font-size: 12px;
|
||||
}
|
||||
.or-role-prompts__move {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 4px;
|
||||
min-width: 11rem;
|
||||
font-size: 12px;
|
||||
color: var(--text2);
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
import { NavLink } from 'react-router-dom'
|
||||
import { TreePine, FolderTree, Download, Grid3x3, Users, Scale, Sparkles, Bot, Wand2, Activity, Building2, Shield, Share2, FileDiff } from 'lucide-react'
|
||||
import { TreePine, FolderTree, Download, Grid3x3, Users, Scale, Sparkles, Wand2, Activity, Building2, Shield } from 'lucide-react'
|
||||
|
||||
/**
|
||||
* Admin-Seiten-Navigation (horizontal) — nur für Super-Admins (globaler Portal-Mandant).
|
||||
@@ -16,10 +16,7 @@ export default function AdminPageNav() {
|
||||
{ to: '/admin/mediawiki-import', label: 'Wiki-Import', icon: Download },
|
||||
{ to: '/admin/legal-documents', label: 'Rechtstexte', icon: Scale },
|
||||
{ to: '/admin/ai-prompts', label: 'KI Prompts', icon: Sparkles },
|
||||
{ to: '/admin/openrouter', label: 'KI-Modell', icon: Bot },
|
||||
{ to: '/admin/exercise-enrichment', label: 'Übungs-Anreicherung', icon: Wand2 },
|
||||
{ to: '/admin/distribution', label: 'API-Schnittstelle', icon: Share2 },
|
||||
{ to: '/admin/release-updates', label: 'Release-Abgleich', icon: FileDiff },
|
||||
]
|
||||
|
||||
return (
|
||||
|
||||
@@ -1,314 +0,0 @@
|
||||
import { useEffect, useId, useMemo, useState } from 'react'
|
||||
import api from '../utils/api'
|
||||
|
||||
function formatContext(value) {
|
||||
const n = Number(value)
|
||||
if (!Number.isFinite(n) || n <= 0) return '—'
|
||||
if (n >= 1000) {
|
||||
const k = n / 1000
|
||||
return Number.isInteger(k) ? `${k}k` : `${k.toFixed(1)}k`
|
||||
}
|
||||
return String(n)
|
||||
}
|
||||
|
||||
function tokenUsd(raw) {
|
||||
if (raw == null || raw === '') return null
|
||||
const n = Number(raw)
|
||||
return Number.isFinite(n) ? n : null
|
||||
}
|
||||
|
||||
function usdPerMillion(raw) {
|
||||
const n = tokenUsd(raw)
|
||||
if (n == null) return null
|
||||
const perM = n * 1_000_000
|
||||
if (perM === 0) return '0'
|
||||
if (perM < 0.01) return perM.toFixed(4)
|
||||
if (perM < 1) return perM.toFixed(3)
|
||||
return perM.toFixed(2)
|
||||
}
|
||||
|
||||
function priceLabel(model) {
|
||||
const prompt = usdPerMillion(model.prompt_usd_per_token)
|
||||
const completion = usdPerMillion(model.completion_usd_per_token)
|
||||
if (prompt == null && completion == null) return 'Preis unbekannt'
|
||||
return `${prompt ?? '—'} / ${completion ?? '—'} USD je 1 Mio. Tokens`
|
||||
}
|
||||
|
||||
function matchesFilters(model, filters) {
|
||||
const query = filters.query.trim().toLowerCase()
|
||||
if (query) {
|
||||
const hay = `${model.name || ''} ${model.id || ''} ${model.description || ''}`.toLowerCase()
|
||||
if (!hay.includes(query)) return false
|
||||
}
|
||||
if (filters.provider && model.provider !== filters.provider) return false
|
||||
const inputs = Array.isArray(model.input_modalities) ? model.input_modalities : []
|
||||
if (filters.modality === 'text' && !(inputs.length === 1 && inputs[0] === 'text')) return false
|
||||
if (filters.modality === 'image' && !inputs.includes('image')) return false
|
||||
if (filters.modality === 'audio' && !inputs.includes('audio')) return false
|
||||
if (filters.contextMin && (Number(model.context_length) || 0) < filters.contextMin) return false
|
||||
if (filters.price === 'free' && !model.is_free) return false
|
||||
if (filters.price === 'paid' && model.is_free) return false
|
||||
return true
|
||||
}
|
||||
|
||||
function compareModels(sort, a, b) {
|
||||
if (sort === 'context') {
|
||||
const diff = (Number(b.context_length) || 0) - (Number(a.context_length) || 0)
|
||||
if (diff) return diff
|
||||
}
|
||||
if (sort === 'price') {
|
||||
const ap = tokenUsd(a.prompt_usd_per_token)
|
||||
const bp = tokenUsd(b.prompt_usd_per_token)
|
||||
const aMissing = ap == null
|
||||
const bMissing = bp == null
|
||||
if (aMissing !== bMissing) return aMissing ? 1 : -1
|
||||
if (!aMissing && ap !== bp) return ap - bp
|
||||
}
|
||||
return String(a.name || a.id).localeCompare(String(b.name || b.id), 'de')
|
||||
}
|
||||
|
||||
/**
|
||||
* Durchsuchbare OpenRouter-Modellliste. value ist die Modell-ID oder leer.
|
||||
*/
|
||||
export default function OpenRouterModelPicker({
|
||||
value,
|
||||
onChange,
|
||||
allowClear = false,
|
||||
clearLabel = 'Plattformstandard verwenden',
|
||||
listMaxHeight = '22rem',
|
||||
}) {
|
||||
const [models, setModels] = useState([])
|
||||
const [meta, setMeta] = useState(null)
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [error, setError] = useState('')
|
||||
const [query, setQuery] = useState('')
|
||||
const [provider, setProvider] = useState('')
|
||||
const [modality, setModality] = useState('')
|
||||
const [contextMin, setContextMin] = useState(0)
|
||||
const [price, setPrice] = useState('')
|
||||
const [sort, setSort] = useState('name')
|
||||
const uid = useId()
|
||||
|
||||
async function load(refresh = false) {
|
||||
setLoading(true)
|
||||
setError('')
|
||||
try {
|
||||
const data = await api.listAdminOpenRouterModels(refresh)
|
||||
setModels(Array.isArray(data?.models) ? data.models : [])
|
||||
setMeta(data)
|
||||
} catch (e) {
|
||||
setError(e.message || 'Modellliste konnte nicht geladen werden.')
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false
|
||||
setLoading(true)
|
||||
api
|
||||
.listAdminOpenRouterModels(false)
|
||||
.then((data) => {
|
||||
if (cancelled) return
|
||||
setModels(Array.isArray(data?.models) ? data.models : [])
|
||||
setMeta(data)
|
||||
})
|
||||
.catch((e) => {
|
||||
if (!cancelled) setError(e.message || 'Modellliste konnte nicht geladen werden.')
|
||||
})
|
||||
.finally(() => {
|
||||
if (!cancelled) setLoading(false)
|
||||
})
|
||||
return () => {
|
||||
cancelled = true
|
||||
}
|
||||
}, [])
|
||||
|
||||
const providers = useMemo(() => {
|
||||
const names = new Set(models.map((model) => model.provider).filter(Boolean))
|
||||
return Array.from(names).sort((a, b) => a.localeCompare(b, 'de'))
|
||||
}, [models])
|
||||
|
||||
const visible = useMemo(() => {
|
||||
const filters = { query, provider, modality, contextMin, price }
|
||||
return models
|
||||
.filter((model) => matchesFilters(model, filters))
|
||||
.sort((a, b) => compareModels(sort, a, b))
|
||||
}, [models, query, provider, modality, contextMin, price, sort])
|
||||
|
||||
const selected = models.find((model) => model.id === value) || null
|
||||
const selectedHidden = Boolean(value) && !visible.some((model) => model.id === value)
|
||||
|
||||
return (
|
||||
<div className="or-picker">
|
||||
<div className="or-picker__toolbar">
|
||||
<p className="or-picker__count">
|
||||
{loading
|
||||
? 'Modelle werden geladen …'
|
||||
: `${visible.length} von ${models.length} Modellen`}
|
||||
</p>
|
||||
<button type="button" className="btn btn-secondary" disabled={loading} onClick={() => load(true)}>
|
||||
Liste aktualisieren
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{meta?.stale ? (
|
||||
<p className="or-picker__note">
|
||||
OpenRouter ist gerade nicht erreichbar. Angezeigt wird die zuletzt geladene Liste.
|
||||
</p>
|
||||
) : null}
|
||||
{error ? <p className="or-picker__error">{error}</p> : null}
|
||||
|
||||
<div className="form-row">
|
||||
<label className="form-label" htmlFor={`${uid}-search`}>
|
||||
Suche
|
||||
</label>
|
||||
<input
|
||||
id={`${uid}-search`}
|
||||
className="form-input"
|
||||
type="search"
|
||||
value={query}
|
||||
placeholder="Name oder Modell-ID"
|
||||
onChange={(e) => setQuery(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="or-picker__filters">
|
||||
<div className="form-row">
|
||||
<label className="form-label" htmlFor={`${uid}-provider`}>
|
||||
Anbieter
|
||||
</label>
|
||||
<select
|
||||
id={`${uid}-provider`}
|
||||
className="form-input"
|
||||
value={provider}
|
||||
onChange={(e) => setProvider(e.target.value)}
|
||||
>
|
||||
<option value="">Alle</option>
|
||||
{providers.map((name) => (
|
||||
<option key={name} value={name}>
|
||||
{name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
<div className="form-row">
|
||||
<label className="form-label" htmlFor={`${uid}-modality`}>
|
||||
Eingabe
|
||||
</label>
|
||||
<select
|
||||
id={`${uid}-modality`}
|
||||
className="form-input"
|
||||
value={modality}
|
||||
onChange={(e) => setModality(e.target.value)}
|
||||
>
|
||||
<option value="">Alle</option>
|
||||
<option value="text">Nur Text</option>
|
||||
<option value="image">Mit Bild</option>
|
||||
<option value="audio">Mit Audio</option>
|
||||
</select>
|
||||
</div>
|
||||
<div className="form-row">
|
||||
<label className="form-label" htmlFor={`${uid}-context`}>
|
||||
Kontext
|
||||
</label>
|
||||
<select
|
||||
id={`${uid}-context`}
|
||||
className="form-input"
|
||||
value={String(contextMin)}
|
||||
onChange={(e) => setContextMin(Number(e.target.value) || 0)}
|
||||
>
|
||||
<option value="0">Alle</option>
|
||||
<option value="32000">mindestens 32k</option>
|
||||
<option value="128000">mindestens 128k</option>
|
||||
<option value="200000">mindestens 200k</option>
|
||||
</select>
|
||||
</div>
|
||||
<div className="form-row">
|
||||
<label className="form-label" htmlFor={`${uid}-price`}>
|
||||
Preis
|
||||
</label>
|
||||
<select
|
||||
id={`${uid}-price`}
|
||||
className="form-input"
|
||||
value={price}
|
||||
onChange={(e) => setPrice(e.target.value)}
|
||||
>
|
||||
<option value="">Alle</option>
|
||||
<option value="free">Kostenlos</option>
|
||||
<option value="paid">Kostenpflichtig</option>
|
||||
</select>
|
||||
</div>
|
||||
<div className="form-row">
|
||||
<label className="form-label" htmlFor={`${uid}-sort`}>
|
||||
Sortierung
|
||||
</label>
|
||||
<select
|
||||
id={`${uid}-sort`}
|
||||
className="form-input"
|
||||
value={sort}
|
||||
onChange={(e) => setSort(e.target.value)}
|
||||
>
|
||||
<option value="name">Name</option>
|
||||
<option value="context">Kontext, größter zuerst</option>
|
||||
<option value="price">Eingabepreis, niedrigster zuerst</option>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{allowClear ? (
|
||||
<div className="or-picker__clear">
|
||||
<button
|
||||
type="button"
|
||||
className={`btn ${value ? 'btn-secondary' : 'btn-primary'}`}
|
||||
onClick={() => onChange('')}
|
||||
>
|
||||
{clearLabel}
|
||||
</button>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{value && !selected && !loading ? (
|
||||
<p className="or-picker__note">
|
||||
Gespeichert ist <code>{value}</code>. Diese ID steht in der aktuellen OpenRouter-Liste nicht.
|
||||
</p>
|
||||
) : null}
|
||||
{selectedHidden && selected ? (
|
||||
<p className="or-picker__note">
|
||||
Die aktuelle Auswahl <code>{selected.id}</code> passt nicht zu Suche oder Filtern.
|
||||
</p>
|
||||
) : null}
|
||||
|
||||
<ul className="or-picker__list" role="listbox" aria-label="OpenRouter-Modelle" style={{ maxHeight: listMaxHeight }}>
|
||||
{!loading && visible.length === 0 ? (
|
||||
<li className="or-picker__empty">Kein Modell passt zu Suche und Filtern.</li>
|
||||
) : null}
|
||||
{visible.map((model) => {
|
||||
const isSelected = model.id === value
|
||||
return (
|
||||
<li key={model.id}>
|
||||
<button
|
||||
type="button"
|
||||
role="option"
|
||||
aria-selected={isSelected}
|
||||
className={`or-picker__option${isSelected ? ' or-picker__option--selected' : ''}`}
|
||||
onClick={() => onChange(model.id)}
|
||||
>
|
||||
<span className="or-picker__name">{model.name}</span>
|
||||
<code className="or-picker__id">{model.id}</code>
|
||||
<span className="or-picker__meta">
|
||||
<span>Kontext {formatContext(model.context_length)}</span>
|
||||
<span>{priceLabel(model)}</span>
|
||||
{model.is_free ? <span>kostenlos</span> : null}
|
||||
{(model.input_modalities || []).length ? (
|
||||
<span>{model.input_modalities.join(', ')}</span>
|
||||
) : null}
|
||||
</span>
|
||||
</button>
|
||||
</li>
|
||||
)
|
||||
})}
|
||||
</ul>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,229 +0,0 @@
|
||||
import React, { useCallback, useEffect, useState } from 'react'
|
||||
import {
|
||||
confirmDistributionDraft,
|
||||
createDistributionDraft,
|
||||
getExerciseDistribution,
|
||||
retireDistributionRelease,
|
||||
updateDistributionDraft,
|
||||
withdrawDistributionRelease,
|
||||
} from '../../api/distribution'
|
||||
|
||||
const RELEASE_ACTIONS = ['store', 'render', 'stream', 'course_display', 'commercial_course_use']
|
||||
|
||||
const REASONS = [
|
||||
['rights', 'Rechte'],
|
||||
['safety', 'Sicherheit'],
|
||||
['privacy', 'Privatsphäre'],
|
||||
['expired', 'Frist'],
|
||||
['editorial_error', 'Redaktionsfehler'],
|
||||
]
|
||||
|
||||
export default function ExerciseDistributionPanel({ exerciseId }) {
|
||||
const [overview, setOverview] = useState(null)
|
||||
const [error, setError] = useState('')
|
||||
const [keyId, setKeyId] = useState('')
|
||||
const [draft, setDraft] = useState(null)
|
||||
const [evidence, setEvidence] = useState('nachweis')
|
||||
const [retirePrevious, setRetirePrevious] = useState(true)
|
||||
const [reason, setReason] = useState('rights')
|
||||
const [busy, setBusy] = useState(false)
|
||||
|
||||
const load = useCallback(async () => {
|
||||
try {
|
||||
const data = await getExerciseDistribution(exerciseId)
|
||||
setOverview(data)
|
||||
setError('')
|
||||
} catch (err) {
|
||||
setError(err.message || 'Distribution konnte nicht geladen werden.')
|
||||
}
|
||||
}, [exerciseId])
|
||||
|
||||
useEffect(() => {
|
||||
load()
|
||||
}, [load])
|
||||
|
||||
function withRights(cut) {
|
||||
const rightsId = 'rights-main'
|
||||
const next = {
|
||||
...cut,
|
||||
editorial_rights_id: rightsId,
|
||||
rights: [
|
||||
{
|
||||
id: rightsId,
|
||||
evidence_ref: evidence.trim(),
|
||||
actions: RELEASE_ACTIONS,
|
||||
territories: ['DE'],
|
||||
valid_from: new Date(Date.now() - 60000).toISOString().replace(/\.\d{3}Z$/, 'Z'),
|
||||
valid_until: null,
|
||||
note: '',
|
||||
},
|
||||
],
|
||||
parts: (cut.parts || []).map((part) => ({ ...part, rights_id: rightsId })),
|
||||
assets: (cut.assets || []).map((asset) => ({ ...asset, rights_id: rightsId })),
|
||||
}
|
||||
return next
|
||||
}
|
||||
|
||||
async function prepare() {
|
||||
setBusy(true)
|
||||
setError('')
|
||||
try {
|
||||
const created = await createDistributionDraft(exerciseId, { key_id: keyId })
|
||||
const cut = withRights(created.cut)
|
||||
const updated = await updateDistributionDraft(exerciseId, created.draft_id, cut)
|
||||
setDraft(updated)
|
||||
} catch (err) {
|
||||
setError(err.message || 'Vorschau fehlgeschlagen.')
|
||||
} finally {
|
||||
setBusy(false)
|
||||
}
|
||||
}
|
||||
|
||||
async function confirm() {
|
||||
if (!draft) return
|
||||
setBusy(true)
|
||||
setError('')
|
||||
try {
|
||||
const cut = withRights(draft.cut)
|
||||
await updateDistributionDraft(exerciseId, draft.draft_id, cut)
|
||||
const result = await confirmDistributionDraft(exerciseId, draft.draft_id)
|
||||
if (retirePrevious && overview?.releases?.length && !result.replayed) {
|
||||
const recipientId = (overview.keys || []).find((item) => item.id === keyId)?.recipient_id
|
||||
const previous = [...overview.releases]
|
||||
.reverse()
|
||||
.find((item) => item.recipient_id === recipientId && !item.fetch_blocked)
|
||||
if (previous) {
|
||||
await retireDistributionRelease(previous.release_id)
|
||||
}
|
||||
}
|
||||
setDraft(null)
|
||||
await load()
|
||||
} catch (err) {
|
||||
setError(err.message || 'Freigabe fehlgeschlagen.')
|
||||
} finally {
|
||||
setBusy(false)
|
||||
}
|
||||
}
|
||||
|
||||
async function withdraw(releaseId) {
|
||||
setBusy(true)
|
||||
setError('')
|
||||
try {
|
||||
await withdrawDistributionRelease(releaseId, reason)
|
||||
await load()
|
||||
} catch (err) {
|
||||
setError(err.message || 'Rückzug fehlgeschlagen.')
|
||||
} finally {
|
||||
setBusy(false)
|
||||
}
|
||||
}
|
||||
|
||||
if (!overview) {
|
||||
return <p>Freigabe wird geladen …</p>
|
||||
}
|
||||
|
||||
return (
|
||||
<div>
|
||||
{!overview.enabled ? (
|
||||
<p>Die Distribution ist auf dieser Instanz nicht aktiv. Bearbeitung und Planung bleiben davon unberührt.</p>
|
||||
) : (
|
||||
<>
|
||||
{overview.drift?.differs ? (
|
||||
<p>
|
||||
Die Arbeitsfassung weicht vom Release Revision {overview.drift.revision} ab
|
||||
{overview.drift.areas?.length ? `: ${overview.drift.areas.join(', ')}` : ''}. Ein neues Release
|
||||
veröffentlicht diesen Stand. Das bisherige Release bleibt unter seiner ID abrufbar.
|
||||
</p>
|
||||
) : overview.releases?.length ? (
|
||||
<p>Die Arbeitsfassung entspricht dem letzten Release.</p>
|
||||
) : null}
|
||||
{overview.release_block ? <p>{overview.release_block}</p> : null}
|
||||
<label className="form-label">
|
||||
API-Schlüssel
|
||||
<select className="form-input" value={keyId} onChange={(event) => setKeyId(event.target.value)}>
|
||||
<option value="">Bitte wählen</option>
|
||||
{(overview.keys || []).map((item) => (
|
||||
<option key={item.id} value={item.id}>
|
||||
{item.label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
<p style={{ color: 'var(--text2)', fontSize: '13px' }}>
|
||||
Der Empfänger darf die Fassung übernehmen und im Kurs zeigen, auch kommerziell. Herunterladen und Bearbeiten sind nicht enthalten.
|
||||
</p>
|
||||
<label className="form-label">
|
||||
Nachweis
|
||||
<input className="form-input" value={evidence} onChange={(event) => setEvidence(event.target.value)} />
|
||||
</label>
|
||||
<label style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
|
||||
<input type="checkbox" checked={retirePrevious} onChange={(event) => setRetirePrevious(event.target.checked)} />
|
||||
Bisherige Fassung für neue Pläne ablösen
|
||||
</label>
|
||||
<div style={{ display: 'flex', gap: 8, marginTop: 8 }}>
|
||||
<button type="button" className="btn btn-secondary" disabled={busy || !overview.may_release} onClick={prepare}>
|
||||
Vorschau
|
||||
</button>
|
||||
<button type="button" className="btn btn-primary" disabled={busy || !draft || !overview.may_release} onClick={confirm}>
|
||||
Verbindlich freigeben
|
||||
</button>
|
||||
</div>
|
||||
{draft ? (
|
||||
<div style={{ marginTop: 12 }}>
|
||||
<strong>Vorschau</strong>
|
||||
{draft.blockers?.length ? (
|
||||
<ul>
|
||||
{draft.blockers.map((item) => (
|
||||
<li key={item}>{item}</li>
|
||||
))}
|
||||
</ul>
|
||||
) : (
|
||||
<p>Keine blockierenden Punkte.</p>
|
||||
)}
|
||||
<ul>
|
||||
{(draft.cut?.parts || []).map((part) => (
|
||||
<li key={part.key}>
|
||||
{part.role}: {part.text}
|
||||
</li>
|
||||
))}
|
||||
{(draft.cut?.assets || []).map((asset) => (
|
||||
<li key={asset.media_id}>
|
||||
Medium {asset.role} {asset.label || ''}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
) : null}
|
||||
</>
|
||||
)}
|
||||
{overview.releases?.length ? (
|
||||
<>
|
||||
<h3>Freigegebene Fassungen</h3>
|
||||
<label className="form-label">
|
||||
Grundklasse für Rückzug
|
||||
<select className="form-input" value={reason} onChange={(event) => setReason(event.target.value)}>
|
||||
{REASONS.map(([value, label]) => (
|
||||
<option key={value} value={value}>
|
||||
{label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
<ul>
|
||||
{overview.releases.map((release) => (
|
||||
<li key={release.release_id}>
|
||||
{release.recipient_name} · Revision {release.revision} · {release.fetch_blocked ? 'zurückgezogen' : 'abrufbar'}
|
||||
{overview.enabled && !release.fetch_blocked ? (
|
||||
<button type="button" className="btn btn-secondary" style={{ marginLeft: 8 }} disabled={busy} onClick={() => withdraw(release.release_id)}>
|
||||
Zurückziehen
|
||||
</button>
|
||||
) : null}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</>
|
||||
) : null}
|
||||
{error ? <p role="alert">{error}</p> : null}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
import React, { useEffect, useState, useRef, useMemo, useCallback } from 'react'
|
||||
import { useNavigate, useParams, Link, useLocation, useSearchParams } from 'react-router-dom'
|
||||
import { useNavigate, useParams, Link, useLocation } from 'react-router-dom'
|
||||
import api, { buildExerciseApiPayload } from '../../utils/api'
|
||||
import { resolveExerciseMediaFileUrl, resolveMediaAssetFileUrl, useMediaAccessToken } from '../../utils/exerciseMediaUrl'
|
||||
import RichTextEditor from '../RichTextEditor'
|
||||
@@ -28,11 +28,10 @@ import {
|
||||
} from '../../utils/activeClub'
|
||||
import { COMBINATION_ARCHETYPE_OPTIONS, ARCHETYPE_DEFAULT_REP_SERIES_COUNT, defaultRepSeriesCountForArchetype } from '../../constants/combinationArchetypes'
|
||||
import { readSlotProfilesV1, normalizeAdvanceMode, parseComboRepSeriesCountUi } from '../../utils/combinationMethodProfileUi'
|
||||
import { GripVertical, FileText, BookOpen, Tags, Layers, GitBranch, Image as ImageIcon, Share2 } from 'lucide-react'
|
||||
import { GripVertical, FileText, BookOpen, Tags, Layers, GitBranch, Image as ImageIcon } from 'lucide-react'
|
||||
import UnsavedChangesPrompt from '../UnsavedChangesPrompt'
|
||||
import PageFormEditorChrome from '../PageFormEditorChrome'
|
||||
import { ExerciseFormTabBar, ExerciseFormPanel } from './ExerciseFormLayout'
|
||||
import ExerciseDistributionPanel from './ExerciseDistributionPanel'
|
||||
import { useNavReturn } from '../../hooks/useNavReturn'
|
||||
import {
|
||||
EXERCISES_LIST_PATH,
|
||||
@@ -647,13 +646,7 @@ function ExerciseFormPageRoot() {
|
||||
const [aiSuggestBusy, setAiSuggestBusy] = useState(false)
|
||||
const [aiSuggestionPreview, setAiSuggestionPreview] = useState(null)
|
||||
const [variantEditSelection, setVariantEditSelection] = useState(null)
|
||||
const [searchParams] = useSearchParams()
|
||||
const requestedTab = searchParams.get('tab')
|
||||
const [activeFormTab, setActiveFormTab] = useState(
|
||||
['stammdaten', 'anleitung', 'einordnung', 'kombination', 'varianten', 'medien', 'freigabe'].includes(requestedTab)
|
||||
? requestedTab
|
||||
: 'stammdaten',
|
||||
)
|
||||
const [activeFormTab, setActiveFormTab] = useState('stammdaten')
|
||||
const variantsSavedSnapshotRef = useRef({})
|
||||
|
||||
const exerciseFormTabs = useMemo(() => {
|
||||
@@ -674,11 +667,9 @@ function ExerciseFormPageRoot() {
|
||||
})
|
||||
}
|
||||
tabs.push({ id: 'medien', label: 'Medien & Mehr', icon: ImageIcon })
|
||||
tabs.push({ id: 'freigabe', label: 'Freigabe', icon: Share2 })
|
||||
} else {
|
||||
tabs.push({ id: 'varianten', label: 'Varianten', icon: GitBranch, disabled: true })
|
||||
tabs.push({ id: 'medien', label: 'Medien & Mehr', icon: ImageIcon, disabled: true })
|
||||
tabs.push({ id: 'freigabe', label: 'Freigabe', icon: Share2, disabled: true })
|
||||
}
|
||||
return tabs
|
||||
}, [formData.exercise_kind, isEdit, variants.length])
|
||||
@@ -2609,7 +2600,6 @@ function ExerciseFormPageRoot() {
|
||||
) : null}
|
||||
|
||||
{isEdit ? (
|
||||
<>
|
||||
<ExerciseFormPanel
|
||||
tab="medien"
|
||||
activeTab={activeFormTab}
|
||||
@@ -2912,15 +2902,6 @@ function ExerciseFormPageRoot() {
|
||||
/>
|
||||
)}
|
||||
</ExerciseFormPanel>
|
||||
<ExerciseFormPanel
|
||||
tab="freigabe"
|
||||
activeTab={activeFormTab}
|
||||
title="Freigabe"
|
||||
hint="Eingefrorene Fassung für einen Empfänger. Die Übung selbst bleibt davon unberührt."
|
||||
>
|
||||
<ExerciseDistributionPanel exerciseId={exerciseId} />
|
||||
</ExerciseFormPanel>
|
||||
</>
|
||||
) : null}
|
||||
|
||||
</form>
|
||||
|
||||
@@ -6,8 +6,6 @@ export default function ExerciseListBulkToolbar({
|
||||
onClearSelection,
|
||||
onOpenBulkModal,
|
||||
onOpenSaveModuleModal,
|
||||
onSetApiOffering,
|
||||
apiOfferingBusy = false,
|
||||
}) {
|
||||
if (selectedCount < 1) return null
|
||||
|
||||
@@ -23,22 +21,6 @@ export default function ExerciseListBulkToolbar({
|
||||
<button type="button" className="btn btn-primary btn-small" onClick={onOpenBulkModal}>
|
||||
Massenänderung…
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-secondary btn-small"
|
||||
disabled={apiOfferingBusy}
|
||||
onClick={() => onSetApiOffering(true)}
|
||||
>
|
||||
API bereitstellen
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-secondary btn-small"
|
||||
disabled={apiOfferingBusy}
|
||||
onClick={() => onSetApiOffering(false)}
|
||||
>
|
||||
API ausblenden
|
||||
</button>
|
||||
<span className="exercise-bulk-toolbar__meta">
|
||||
Bis zu {bulkMaxIds} pro Anfrage. Für „Verein“ ohne Auswahl: aktiver Vereinskontext (
|
||||
<code>X-Active-Club-Id</code>
|
||||
|
||||
@@ -223,12 +223,6 @@ export default function ExerciseListCard({
|
||||
{name}
|
||||
</span>
|
||||
))}
|
||||
<span
|
||||
className="exercise-tag"
|
||||
title={exercise.api_offered ? 'Über die API bereitgestellt' : 'Nicht über die API bereitgestellt'}
|
||||
>
|
||||
{exercise.api_offered ? 'API bereitgestellt' : 'API aus'}
|
||||
</span>
|
||||
{(exercise.exercise_kind || '').toLowerCase().trim() === 'combination' ? (
|
||||
<span
|
||||
className="exercise-tag"
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import React, { useState, useEffect, useMemo, useCallback, useRef, Suspense } from 'react'
|
||||
import React, { useState, useEffect, useMemo, useCallback, useRef, lazy, Suspense } from 'react'
|
||||
import { useNavigate } from 'react-router-dom'
|
||||
import api from '../../utils/api'
|
||||
import { lazyWithRetry } from '../../utils/lazyWithRetry'
|
||||
import { useAuth } from '../../context/AuthContext'
|
||||
import { activeClubMemberships, getTenantClubDependencyKey } from '../../utils/activeClub'
|
||||
import PageSectionNav from '../PageSectionNav'
|
||||
@@ -40,7 +39,7 @@ import {
|
||||
compactExerciseListPrefsPayload,
|
||||
} from '../../constants/exerciseListFilters'
|
||||
|
||||
const ExerciseProgressionGraphPanel = lazyWithRetry(() => import('../ExerciseProgressionGraphPanel'))
|
||||
const ExerciseProgressionGraphPanel = lazy(() => import('../ExerciseProgressionGraphPanel'))
|
||||
|
||||
const BULK_MAX_IDS = 500
|
||||
const EXERCISES_PAGE_TABS = [
|
||||
@@ -81,7 +80,6 @@ function ExercisesListPageRoot() {
|
||||
const [bulkClubSelect, setBulkClubSelect] = useState('')
|
||||
const [bulkClubManual, setBulkClubManual] = useState('')
|
||||
const [bulkSubmitting, setBulkSubmitting] = useState(false)
|
||||
const [apiOfferingBusy, setApiOfferingBusy] = useState(false)
|
||||
const [bulkPatchFocusAreas, setBulkPatchFocusAreas] = useState(false)
|
||||
const [bulkFocusAreaIds, setBulkFocusAreaIds] = useState([])
|
||||
const [bulkPatchStyleDirections, setBulkPatchStyleDirections] = useState(false)
|
||||
@@ -484,39 +482,6 @@ function ExercisesListPageRoot() {
|
||||
}
|
||||
}, [user?.id, filters, checkAuth])
|
||||
|
||||
const handleApiOffering = async (apiOffered) => {
|
||||
const ids = Array.from(selectedIds).filter((item) => Number.isFinite(item) && item > 0)
|
||||
if (!ids.length) {
|
||||
alert('Keine Übungen ausgewählt.')
|
||||
return
|
||||
}
|
||||
if (ids.length > BULK_MAX_IDS) {
|
||||
alert(`Maximal ${BULK_MAX_IDS} Übungen pro Vorgang. Bitte Auswahl oder mehrere Durchläufe verwenden.`)
|
||||
return
|
||||
}
|
||||
setApiOfferingBusy(true)
|
||||
try {
|
||||
const result = await api.patchExerciseApiOffering({ exercise_ids: ids, api_offered: apiOffered })
|
||||
const updatedIds = new Set((result.updated || []).map((item) => Number(item.id)))
|
||||
const apply = (exercise) =>
|
||||
updatedIds.has(Number(exercise.id)) ? { ...exercise, api_offered: apiOffered } : exercise
|
||||
setExercises((prev) => prev.map(apply))
|
||||
setSelectedEntries((prev) => prev.map(apply))
|
||||
const changed = (result.updated || []).map((item) => item.title || `Übung ${item.id}`)
|
||||
const blocked = (result.denied || []).map(
|
||||
(item) => `${item.title || `Übung ${item.id}`}: ${item.detail || 'Keine Berechtigung'}`
|
||||
)
|
||||
const lines = []
|
||||
if (changed.length) lines.push(`Geändert: ${changed.join(', ')}`)
|
||||
if (blocked.length) lines.push(`Nicht geändert: ${blocked.join(' · ')}`)
|
||||
if (lines.length) alert(lines.join('\n'))
|
||||
} catch (error) {
|
||||
alert(error.message || 'Die API-Bereitstellung konnte nicht gespeichert werden.')
|
||||
} finally {
|
||||
setApiOfferingBusy(false)
|
||||
}
|
||||
}
|
||||
|
||||
const openBulkModal = () => {
|
||||
setBulkVisibility('')
|
||||
setBulkStatus('')
|
||||
@@ -761,8 +726,6 @@ function ExercisesListPageRoot() {
|
||||
onClearSelection={clearSelection}
|
||||
onOpenBulkModal={openBulkModal}
|
||||
onOpenSaveModuleModal={() => setSaveModuleModalOpen(true)}
|
||||
onSetApiOffering={handleApiOffering}
|
||||
apiOfferingBusy={apiOfferingBusy}
|
||||
/>
|
||||
|
||||
<ExerciseListFilterModal
|
||||
|
||||
@@ -3,12 +3,6 @@ import ReactDOM from 'react-dom/client'
|
||||
import App from './App.jsx'
|
||||
import './app.css'
|
||||
|
||||
const bootUrl = new URL(window.location.href)
|
||||
if (bootUrl.searchParams.has('sj_reload')) {
|
||||
bootUrl.searchParams.delete('sj_reload')
|
||||
window.history.replaceState(window.history.state, '', bootUrl.pathname + bootUrl.search + bootUrl.hash)
|
||||
}
|
||||
|
||||
ReactDOM.createRoot(document.getElementById('root')).render(
|
||||
<React.StrictMode>
|
||||
<App />
|
||||
|
||||
@@ -607,12 +607,6 @@ function AccountSettingsPage() {
|
||||
</div>
|
||||
|
||||
<p className="muted" style={{ marginTop: '1.75rem', fontSize: '0.875rem', lineHeight: 1.5 }}>
|
||||
<Link to="/admin/distribution">API-Schlüssel</Link>
|
||||
{' · '}
|
||||
<Link to="/admin/release-updates">Offene Release-Änderungen</Link>
|
||||
{' — Schnittstelle für Übungen und spätere Planungsinhalte'}
|
||||
</p>
|
||||
<p className="muted" style={{ marginTop: '0.6rem', fontSize: '0.875rem', lineHeight: 1.5 }}>
|
||||
<Link to="/settings/system">Technische Systeminformationen</Link>
|
||||
{' — App-Version, Build, Umgebung, Datenbankschema'}
|
||||
</p>
|
||||
|
||||
@@ -1,16 +1,9 @@
|
||||
import { useCallback, useEffect, useState } from 'react'
|
||||
import { Link, Navigate } from 'react-router-dom'
|
||||
import { Navigate } from 'react-router-dom'
|
||||
import { Sparkles } from 'lucide-react'
|
||||
import { useAuth } from '../context/AuthContext'
|
||||
import api from '../utils/api'
|
||||
import AdminPageNav from '../components/AdminPageNav'
|
||||
import OpenRouterModelPicker from '../components/OpenRouterModelPicker'
|
||||
|
||||
const MODEL_ROLE_LABEL = {
|
||||
reasoning: 'Denken',
|
||||
drafting: 'Formulieren',
|
||||
matching: 'Zuordnen',
|
||||
}
|
||||
|
||||
/**
|
||||
* Pflege von ai_prompts (OpenRouter-Vorlagen) — nur Superadmin.
|
||||
@@ -32,7 +25,6 @@ export default function AdminAiPromptsPage() {
|
||||
const [draftTemplate, setDraftTemplate] = useState('')
|
||||
const [draftOpenrouterModel, setDraftOpenrouterModel] = useState('')
|
||||
const [draftActive, setDraftActive] = useState(true)
|
||||
const [modelListOpen, setModelListOpen] = useState(false)
|
||||
|
||||
const [pvTitle, setPvTitle] = useState('Testübung')
|
||||
const [pvGoal, setPvGoal] = useState('<p>Ziel hier</p>')
|
||||
@@ -88,7 +80,6 @@ export default function AdminAiPromptsPage() {
|
||||
setDetail(null)
|
||||
return
|
||||
}
|
||||
setModelListOpen(false)
|
||||
let cancelled = false
|
||||
;(async () => {
|
||||
try {
|
||||
@@ -273,37 +264,15 @@ export default function AdminAiPromptsPage() {
|
||||
/>
|
||||
</div>
|
||||
<div className="form-row">
|
||||
<label className="form-label">Ausnahme nur für diesen Prompt</label>
|
||||
<p style={{ margin: '0 0 8px', color: 'var(--text2)', fontSize: 13 }}>
|
||||
{draftOpenrouterModel ? (
|
||||
<>
|
||||
Ausnahme: <code>{draftOpenrouterModel}</code>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
{detail?.model_role
|
||||
? `Es gilt die Aufgabengruppe ${MODEL_ROLE_LABEL[detail.model_role] || detail.model_role}. `
|
||||
: 'Es gilt der Plattformstandard. '}
|
||||
<Link to="/admin/openrouter">Gruppen unter KI-Modell festlegen</Link>
|
||||
</>
|
||||
)}
|
||||
</p>
|
||||
<div className="or-model-embed">
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-secondary"
|
||||
onClick={() => setModelListOpen((open) => !open)}
|
||||
>
|
||||
{modelListOpen ? 'Liste schließen' : 'Modell aus der OpenRouter-Liste wählen'}
|
||||
</button>
|
||||
{modelListOpen ? (
|
||||
<OpenRouterModelPicker
|
||||
<label className="form-label">OpenRouter-Modell (optional)</label>
|
||||
<input
|
||||
className="form-input"
|
||||
placeholder="Leer = Server-OPENROUTER_MODEL · z.B. anthropic/claude-3.5-haiku"
|
||||
autoComplete="off"
|
||||
spellCheck={false}
|
||||
value={draftOpenrouterModel}
|
||||
onChange={setDraftOpenrouterModel}
|
||||
allowClear
|
||||
onChange={(e) => setDraftOpenrouterModel(e.target.value)}
|
||||
/>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
<label style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 12 }}>
|
||||
<input type="checkbox" checked={draftActive} onChange={(e) => setDraftActive(e.target.checked)} />
|
||||
|
||||
@@ -1,243 +0,0 @@
|
||||
import React, { useCallback, useEffect, useState } from 'react'
|
||||
import { Link } from 'react-router-dom'
|
||||
import AdminPageNav from '../components/AdminPageNav'
|
||||
import { useAuth } from '../context/AuthContext'
|
||||
import {
|
||||
createDistributionAccessKey,
|
||||
getDistributionAccess,
|
||||
revokeDistributionAccessKey,
|
||||
setClubDistributionApi,
|
||||
} from '../api/distribution'
|
||||
|
||||
const OBJECTS = [
|
||||
['exercise', 'Übung'],
|
||||
['training_plan', 'Trainingsplan'],
|
||||
['framework', 'Rahmenprogramm'],
|
||||
['training_module', 'Trainingsmodul'],
|
||||
]
|
||||
|
||||
function toggleValue(list, value, setter) {
|
||||
setter(list.includes(value) ? list.filter((item) => item !== value) : [...list, value])
|
||||
}
|
||||
|
||||
function KeyForm({ superadmin, clubs, onCreated }) {
|
||||
const [name, setName] = useState('')
|
||||
const [objects, setObjects] = useState(['exercise'])
|
||||
const [globalOn, setGlobalOn] = useState(false)
|
||||
const [privateOn, setPrivateOn] = useState(true)
|
||||
const [clubIds, setClubIds] = useState([])
|
||||
const [busy, setBusy] = useState(false)
|
||||
const [error, setError] = useState('')
|
||||
const adminClubs = clubs.filter((club) => club.is_club_admin)
|
||||
|
||||
async function submit(event) {
|
||||
event.preventDefault()
|
||||
const visibilities = [
|
||||
...(globalOn ? ['official'] : []),
|
||||
...(clubIds.length ? ['club'] : []),
|
||||
...(privateOn ? ['private'] : []),
|
||||
]
|
||||
setBusy(true)
|
||||
setError('')
|
||||
try {
|
||||
const result = await createDistributionAccessKey({
|
||||
name: name.trim(),
|
||||
objects,
|
||||
visibilities,
|
||||
context_kind: 'user',
|
||||
club_ids: clubIds,
|
||||
})
|
||||
setName('')
|
||||
onCreated(result)
|
||||
} catch (err) {
|
||||
setError(err.message || 'Schlüssel konnte nicht angelegt werden.')
|
||||
} finally {
|
||||
setBusy(false)
|
||||
}
|
||||
}
|
||||
|
||||
const visibilitiesChosen = globalOn || privateOn || clubIds.length > 0
|
||||
|
||||
return (
|
||||
<form onSubmit={submit}>
|
||||
<div className="form-row">
|
||||
<label className="form-label" htmlFor="distribution-key-name">Name der Anwendung</label>
|
||||
<input id="distribution-key-name" className="form-input" value={name} onChange={(event) => setName(event.target.value)} required />
|
||||
</div>
|
||||
<div className="form-section">
|
||||
<div className="form-section-title">Inhalte</div>
|
||||
<div style={{ display: 'flex', flexWrap: 'wrap', gap: '12px 20px' }}>
|
||||
{OBJECTS.map(([value, label]) => (
|
||||
<label key={value} style={{ display: 'inline-flex', gap: 8, alignItems: 'center' }}>
|
||||
<input type="checkbox" checked={objects.includes(value)} onChange={() => toggleValue(objects, value, setObjects)} />
|
||||
{label}
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
<div className="form-section">
|
||||
<div className="form-section-title">Rechte</div>
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
|
||||
{superadmin ? (
|
||||
<label style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
|
||||
<input type="checkbox" checked={globalOn} onChange={(event) => setGlobalOn(event.target.checked)} />
|
||||
Globale Übungen
|
||||
</label>
|
||||
) : null}
|
||||
{adminClubs.map((club) => (
|
||||
<label key={club.id} style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={clubIds.includes(club.id)}
|
||||
disabled={!club.api_enabled}
|
||||
onChange={() => toggleValue(clubIds, club.id, setClubIds)}
|
||||
/>
|
||||
{club.name}
|
||||
{club.api_enabled ? '' : ' (Schnittstelle noch nicht frei)'}
|
||||
</label>
|
||||
))}
|
||||
<label style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
|
||||
<input type="checkbox" checked={privateOn} onChange={(event) => setPrivateOn(event.target.checked)} />
|
||||
Eigene Übungen
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
{error ? <p role="alert">{error}</p> : null}
|
||||
<button type="submit" className="btn btn-primary" disabled={busy || !name.trim() || !objects.length || !visibilitiesChosen}>
|
||||
Schlüssel erzeugen
|
||||
</button>
|
||||
</form>
|
||||
)
|
||||
}
|
||||
|
||||
function KeyList({ keys, clubs, onRevoke }) {
|
||||
const [copied, setCopied] = useState('')
|
||||
if (!keys.length) return <p style={{ color: 'var(--text2)' }}>Noch kein Schlüssel.</p>
|
||||
|
||||
function rights(item) {
|
||||
const names = []
|
||||
if (item.visibilities.includes('official')) names.push('Global')
|
||||
for (const clubId of item.club_ids || []) {
|
||||
names.push(clubs.find((club) => club.id === clubId)?.name || `Verein ${clubId}`)
|
||||
}
|
||||
if (!item.club_ids?.length && item.club_name && item.visibilities.includes('club')) names.push(item.club_name)
|
||||
if (item.visibilities.includes('private')) names.push('Eigene')
|
||||
return names.join(', ')
|
||||
}
|
||||
|
||||
async function copy(token, id) {
|
||||
await navigator.clipboard.writeText(token)
|
||||
setCopied(id)
|
||||
}
|
||||
|
||||
return (
|
||||
<ul style={{ listStyle: 'none', margin: '1.25rem 0 0', padding: 0, display: 'flex', flexDirection: 'column', gap: '1.25rem' }}>
|
||||
{keys.map((item) => (
|
||||
<li key={item.id}>
|
||||
<strong>{item.label}</strong>
|
||||
<div style={{ color: 'var(--text2)', fontSize: 13, lineHeight: 1.45, marginTop: 4 }}>
|
||||
{item.objects.map((object) => OBJECTS.find(([value]) => value === object)?.[1] || object).join(', ')}
|
||||
{rights(item) ? ` · ${rights(item)}` : ''}
|
||||
</div>
|
||||
{item.token ? (
|
||||
<div style={{ display: 'flex', gap: 8, marginTop: 10, alignItems: 'center' }}>
|
||||
<input className="form-input" readOnly value={item.token} aria-label={`Schlüssel ${item.label}`} style={{ flex: '1 1 auto', width: 'auto' }} />
|
||||
<button type="button" className="btn btn-secondary" onClick={() => copy(item.token, item.id)}>
|
||||
{copied === item.id ? 'Kopiert' : 'Kopieren'}
|
||||
</button>
|
||||
</div>
|
||||
) : (
|
||||
<p style={{ color: 'var(--text3)', fontSize: 13, margin: '8px 0 0' }}>Dieser ältere Schlüssel kann nicht erneut angezeigt werden.</p>
|
||||
)}
|
||||
<button type="button" className="btn btn-secondary" style={{ marginTop: 12 }} onClick={() => onRevoke(item.id)}>
|
||||
Widerrufen
|
||||
</button>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)
|
||||
}
|
||||
|
||||
export default function AdminDistributionPage() {
|
||||
const { user } = useAuth()
|
||||
const superadmin = user?.role === 'superadmin'
|
||||
const [home, setHome] = useState(null)
|
||||
const [error, setError] = useState('')
|
||||
|
||||
const load = useCallback(async () => {
|
||||
try {
|
||||
setHome(await getDistributionAccess())
|
||||
setError('')
|
||||
} catch (err) {
|
||||
setError(err.message || 'Die API-Schnittstelle konnte nicht geladen werden.')
|
||||
}
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
load()
|
||||
}, [load])
|
||||
|
||||
async function toggleClub(club, enabled) {
|
||||
setError('')
|
||||
try {
|
||||
await setClubDistributionApi(club.id, enabled)
|
||||
await load()
|
||||
} catch (err) {
|
||||
setError(err.message || 'Die Freigabe konnte nicht gespeichert werden.')
|
||||
}
|
||||
}
|
||||
|
||||
async function revoke(keyId) {
|
||||
setError('')
|
||||
try {
|
||||
await revokeDistributionAccessKey(keyId)
|
||||
await load()
|
||||
} catch (err) {
|
||||
setError(err.message || 'Der Schlüssel konnte nicht widerrufen werden.')
|
||||
}
|
||||
}
|
||||
|
||||
const keys = home?.keys || []
|
||||
const clubs = home?.clubs || []
|
||||
|
||||
return (
|
||||
<div className="app-page">
|
||||
{superadmin ? <AdminPageNav /> : <p style={{ marginTop: 0 }}><Link to="/settings">Zurück zu Einstellungen</Link></p>}
|
||||
<h1 className="page-title">API-Schnittstelle</h1>
|
||||
<p style={{ color: 'var(--text2)', maxWidth: '52rem', lineHeight: 1.55, marginBottom: '0.75rem' }}>
|
||||
Ein Schlüssel gehört zu einer Anwendung. Du weist ihm die Bereiche zu, die diese Anwendung abrufen darf.
|
||||
Fällt dir eine Rolle weg, liefert der Schlüssel diesen Bereich nicht mehr aus.
|
||||
Trainingsplan, Rahmenprogramm und Trainingsmodul können schon erlaubt werden. Ausgeliefert werden derzeit Übungen.
|
||||
{' '}
|
||||
<Link to="/admin/release-updates">Offene Änderungen gegenüber dem letzten Release</Link>
|
||||
</p>
|
||||
{error ? <p role="alert">{error}</p> : null}
|
||||
{!home ? <p>Wird geladen …</p> : null}
|
||||
|
||||
{superadmin ? (
|
||||
<section className="card" style={{ marginBottom: '1.25rem' }}>
|
||||
<h2 style={{ margin: '0 0 0.75rem', fontSize: '1.05rem' }}>Vereine</h2>
|
||||
<p style={{ color: 'var(--text2)', lineHeight: 1.55, margin: '0 0 1rem' }}>
|
||||
Ein Verein kann auf Schlüssel gelegt werden, sobald die Schnittstelle für ihn frei ist.
|
||||
</p>
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
|
||||
{clubs.map((club) => (
|
||||
<label key={club.id} style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
|
||||
<input type="checkbox" checked={club.api_enabled} onChange={(event) => toggleClub(club, event.target.checked)} />
|
||||
{club.name}
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
) : null}
|
||||
|
||||
{home ? (
|
||||
<section className="card">
|
||||
<h2 style={{ margin: '0 0 0.75rem', fontSize: '1.05rem' }}>Schlüssel</h2>
|
||||
<KeyForm superadmin={superadmin} clubs={clubs} onCreated={() => load()} />
|
||||
<KeyList keys={keys} clubs={clubs} onRevoke={revoke} />
|
||||
</section>
|
||||
) : null}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,310 +0,0 @@
|
||||
import { useEffect, useState } from 'react'
|
||||
import { Navigate } from 'react-router-dom'
|
||||
import { Bot } from 'lucide-react'
|
||||
import { useAuth } from '../context/AuthContext'
|
||||
import api from '../utils/api'
|
||||
import AdminPageNav from '../components/AdminPageNav'
|
||||
import OpenRouterModelPicker from '../components/OpenRouterModelPicker'
|
||||
|
||||
const SOURCE_LABEL = {
|
||||
prompt: 'Ausnahme am Prompt',
|
||||
role: 'Aufgabengruppe',
|
||||
database: 'Plattformstandard',
|
||||
environment: 'Umgebung',
|
||||
}
|
||||
|
||||
/**
|
||||
* Plattform-Standard und Aufgabengruppen für OpenRouter — nur Superadmin.
|
||||
*/
|
||||
export default function AdminOpenRouterPage() {
|
||||
const { user } = useAuth()
|
||||
const isSuperadmin = user?.role === 'superadmin'
|
||||
|
||||
const [settings, setSettings] = useState(null)
|
||||
const [draft, setDraft] = useState('')
|
||||
const [rolesPayload, setRolesPayload] = useState(null)
|
||||
const [roleDrafts, setRoleDrafts] = useState({})
|
||||
const [slot, setSlot] = useState('platform')
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [saving, setSaving] = useState(false)
|
||||
const [error, setError] = useState('')
|
||||
const [notice, setNotice] = useState('')
|
||||
|
||||
function applyRoles(data) {
|
||||
setRolesPayload(data)
|
||||
const next = {}
|
||||
for (const role of data?.roles || []) {
|
||||
next[role.role_key] = role.openrouter_model || ''
|
||||
}
|
||||
setRoleDrafts(next)
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
if (!isSuperadmin) return undefined
|
||||
let cancelled = false
|
||||
setLoading(true)
|
||||
Promise.all([api.getAdminOpenRouterSettings(), api.getAdminOpenRouterRoles()])
|
||||
.then(([settingsData, rolesData]) => {
|
||||
if (cancelled) return
|
||||
setSettings(settingsData)
|
||||
setDraft(settingsData?.openrouter_model || '')
|
||||
applyRoles(rolesData)
|
||||
})
|
||||
.catch((e) => {
|
||||
if (!cancelled) setError(e.message || 'Einstellung konnte nicht geladen werden.')
|
||||
})
|
||||
.finally(() => {
|
||||
if (!cancelled) setLoading(false)
|
||||
})
|
||||
return () => {
|
||||
cancelled = true
|
||||
}
|
||||
}, [isSuperadmin])
|
||||
|
||||
async function savePlatform(nextModel) {
|
||||
setSaving(true)
|
||||
setError('')
|
||||
setNotice('')
|
||||
try {
|
||||
const data = await api.updateAdminOpenRouterSettings(nextModel)
|
||||
setSettings(data)
|
||||
setDraft(data?.openrouter_model || '')
|
||||
const rolesData = await api.getAdminOpenRouterRoles()
|
||||
applyRoles(rolesData)
|
||||
setNotice(nextModel ? 'Plattformstandard gespeichert.' : 'Es gilt wieder der Umgebungswert.')
|
||||
} catch (e) {
|
||||
setError(e.message || 'Speichern fehlgeschlagen.')
|
||||
} finally {
|
||||
setSaving(false)
|
||||
}
|
||||
}
|
||||
|
||||
async function saveRole(roleKey, nextModel) {
|
||||
setSaving(true)
|
||||
setError('')
|
||||
setNotice('')
|
||||
try {
|
||||
const data = await api.updateAdminOpenRouterRole(roleKey, nextModel)
|
||||
applyRoles(data)
|
||||
setNotice(nextModel ? 'Gruppenmodell gespeichert.' : 'Die Gruppe nutzt wieder den Plattformstandard.')
|
||||
} catch (e) {
|
||||
setError(e.message || 'Speichern fehlgeschlagen.')
|
||||
} finally {
|
||||
setSaving(false)
|
||||
}
|
||||
}
|
||||
|
||||
async function movePrompt(promptId, modelRole) {
|
||||
setSaving(true)
|
||||
setError('')
|
||||
setNotice('')
|
||||
try {
|
||||
const data = await api.updateAdminOpenRouterPromptRole(promptId, modelRole)
|
||||
applyRoles(data)
|
||||
setNotice('Aufgabengruppe des Prompts geändert.')
|
||||
} catch (e) {
|
||||
setError(e.message || 'Zuordnung fehlgeschlagen.')
|
||||
} finally {
|
||||
setSaving(false)
|
||||
}
|
||||
}
|
||||
|
||||
if (!isSuperadmin) return <Navigate to="/" replace />
|
||||
|
||||
const roles = rolesPayload?.roles || []
|
||||
const unassigned = rolesPayload?.unassigned || []
|
||||
const activeRole = roles.find((role) => role.role_key === slot) || null
|
||||
const stored = settings?.openrouter_model || ''
|
||||
const roleStored = activeRole?.openrouter_model || ''
|
||||
const roleDraft = roleDrafts[slot] || ''
|
||||
const platformDirty = draft !== stored
|
||||
const roleDirty = Boolean(activeRole) && roleDraft !== roleStored
|
||||
const pickerValue = slot === 'platform' ? draft : roleDraft
|
||||
const prompts = slot === 'unassigned' ? unassigned : activeRole?.prompts || []
|
||||
|
||||
return (
|
||||
<div className="admin-page" style={{ maxWidth: 1100, margin: '0 auto', padding: '16px', paddingBottom: 96 }}>
|
||||
<AdminPageNav />
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 8 }}>
|
||||
<Bot size={22} aria-hidden />
|
||||
<h1 style={{ margin: 0, fontSize: '1.25rem' }}>KI-Modell</h1>
|
||||
</div>
|
||||
<p style={{ fontSize: 13, color: 'var(--text3)', marginTop: 0, maxWidth: '46rem' }}>
|
||||
Ein Modell gilt für eine Aufgabengruppe. Denken entwirft und prüft Trainingswege, Formulieren schreibt
|
||||
Texte und Profile, Zuordnen wählt aus einer vorgegebenen Menge. Eine Ausnahme am einzelnen Prompt bleibt
|
||||
möglich und hat Vorrang.
|
||||
</p>
|
||||
|
||||
{loading ? (
|
||||
<div className="card" style={{ padding: 24, textAlign: 'center' }}>
|
||||
<div className="spinner" />
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
<div className="or-slot-row" role="tablist" aria-label="Aufgabengruppen">
|
||||
<button
|
||||
type="button"
|
||||
className={`btn ${slot === 'platform' ? 'btn-primary' : 'btn-secondary'}`}
|
||||
onClick={() => setSlot('platform')}
|
||||
>
|
||||
Plattformstandard
|
||||
</button>
|
||||
{roles.map((role) => (
|
||||
<button
|
||||
key={role.role_key}
|
||||
type="button"
|
||||
className={`btn ${slot === role.role_key ? 'btn-primary' : 'btn-secondary'}`}
|
||||
onClick={() => setSlot(role.role_key)}
|
||||
>
|
||||
{role.display_name}
|
||||
</button>
|
||||
))}
|
||||
{unassigned.length ? (
|
||||
<button
|
||||
type="button"
|
||||
className={`btn ${slot === 'unassigned' ? 'btn-primary' : 'btn-secondary'}`}
|
||||
onClick={() => setSlot('unassigned')}
|
||||
>
|
||||
Ohne Gruppe
|
||||
</button>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
<div className="card or-settings">
|
||||
{slot === 'platform' ? (
|
||||
<>
|
||||
<p className="or-settings__line">
|
||||
<span>Aktiv</span>
|
||||
<code>{settings?.effective_model || '—'}</code>
|
||||
</p>
|
||||
<p className="or-settings__line">
|
||||
<span>Quelle</span>
|
||||
<strong>{settings?.source === 'database' ? 'Datenbank' : 'Umgebung'}</strong>
|
||||
</p>
|
||||
<p className="or-settings__line">
|
||||
<span>Umgebung</span>
|
||||
<code>{settings?.env_model || '—'}</code>
|
||||
</p>
|
||||
<p className="or-picker__note">
|
||||
Gilt für Gruppen ohne eigenes Modell und für Prompts ohne Gruppe.
|
||||
</p>
|
||||
</>
|
||||
) : null}
|
||||
{activeRole ? (
|
||||
<>
|
||||
<h2 className="or-role-title">{activeRole.display_name}</h2>
|
||||
<p className="or-picker__note">{activeRole.description}</p>
|
||||
<p className="or-settings__line">
|
||||
<span>Aktiv</span>
|
||||
<code>{activeRole.effective_model || '—'}</code>
|
||||
</p>
|
||||
<p className="or-settings__line">
|
||||
<span>Quelle</span>
|
||||
<strong>{SOURCE_LABEL[activeRole.source] || activeRole.source}</strong>
|
||||
</p>
|
||||
</>
|
||||
) : null}
|
||||
{slot === 'unassigned' ? (
|
||||
<p className="or-picker__note">
|
||||
Diese Einträge haben keine Aufgabengruppe und nutzen den Plattformstandard. Der Schalter für die
|
||||
mehrstufige Gesamtanalyse ruft selbst kein Modell auf.
|
||||
</p>
|
||||
) : null}
|
||||
{slot === 'platform' && platformDirty ? (
|
||||
<p className="or-picker__note">Die Auswahl ist noch nicht gespeichert.</p>
|
||||
) : null}
|
||||
{roleDirty ? <p className="or-picker__note">Die Auswahl ist noch nicht gespeichert.</p> : null}
|
||||
{notice ? <p className="or-settings__notice">{notice}</p> : null}
|
||||
{error ? <p className="or-picker__error">{error}</p> : null}
|
||||
<div className="or-settings__actions">
|
||||
{slot === 'platform' ? (
|
||||
<>
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-primary"
|
||||
disabled={saving || !draft || !platformDirty}
|
||||
onClick={() => savePlatform(draft)}
|
||||
>
|
||||
Als Standard speichern
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-secondary"
|
||||
disabled={saving || !stored}
|
||||
onClick={() => savePlatform('')}
|
||||
>
|
||||
Umgebungswert verwenden
|
||||
</button>
|
||||
</>
|
||||
) : null}
|
||||
{activeRole ? (
|
||||
<>
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-primary"
|
||||
disabled={saving || !roleDraft || !roleDirty}
|
||||
onClick={() => saveRole(activeRole.role_key, roleDraft)}
|
||||
>
|
||||
Für {activeRole.display_name} speichern
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-secondary"
|
||||
disabled={saving || !roleStored}
|
||||
onClick={() => saveRole(activeRole.role_key, '')}
|
||||
>
|
||||
Plattformstandard verwenden
|
||||
</button>
|
||||
</>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{prompts.length ? (
|
||||
<ul className="or-role-prompts">
|
||||
{prompts.map((prompt) => (
|
||||
<li key={prompt.id} className="or-role-prompts__item">
|
||||
<div>
|
||||
<strong>{prompt.display_name}</strong>
|
||||
<div className="or-role-prompts__meta">
|
||||
<code>{prompt.slug}</code>
|
||||
<span>{SOURCE_LABEL[prompt.source] || prompt.source}</span>
|
||||
{prompt.openrouter_model ? <span>Ausnahme {prompt.openrouter_model}</span> : null}
|
||||
</div>
|
||||
</div>
|
||||
<label className="or-role-prompts__move">
|
||||
<span>Gruppe</span>
|
||||
<select
|
||||
className="form-input"
|
||||
value={prompt.model_role || ''}
|
||||
disabled={saving}
|
||||
onChange={(e) => movePrompt(prompt.id, e.target.value)}
|
||||
>
|
||||
<option value="">Ohne Gruppe</option>
|
||||
{roles.map((role) => (
|
||||
<option key={role.role_key} value={role.role_key}>
|
||||
{role.display_name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
) : null}
|
||||
|
||||
{slot !== 'unassigned' ? (
|
||||
<OpenRouterModelPicker
|
||||
value={pickerValue}
|
||||
onChange={(id) => {
|
||||
if (slot === 'platform') setDraft(id)
|
||||
else setRoleDrafts((prev) => ({ ...prev, [slot]: id }))
|
||||
}}
|
||||
listMaxHeight="min(62vh, 640px)"
|
||||
/>
|
||||
) : null}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,64 +0,0 @@
|
||||
import React, { useCallback, useEffect, useState } from 'react'
|
||||
import { Link } from 'react-router-dom'
|
||||
import AdminPageNav from '../components/AdminPageNav'
|
||||
import { useAuth } from '../context/AuthContext'
|
||||
import { getDistributionReleaseUpdates } from '../api/distribution'
|
||||
|
||||
const VISIBILITY = {
|
||||
official: 'Global',
|
||||
club: 'Verein',
|
||||
private: 'Eigene',
|
||||
}
|
||||
|
||||
export default function AdminReleaseUpdatesPage() {
|
||||
const { user } = useAuth()
|
||||
const superadmin = user?.role === 'superadmin'
|
||||
const [items, setItems] = useState(null)
|
||||
const [error, setError] = useState('')
|
||||
|
||||
const load = useCallback(async () => {
|
||||
try {
|
||||
const data = await getDistributionReleaseUpdates()
|
||||
setItems(data.items || [])
|
||||
setError('')
|
||||
} catch (err) {
|
||||
setError(err.message || 'Die offenen Änderungen konnten nicht geladen werden.')
|
||||
}
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
load()
|
||||
}, [load])
|
||||
|
||||
return (
|
||||
<div className="app-page">
|
||||
{superadmin ? <AdminPageNav /> : <p style={{ marginTop: 0 }}><Link to="/admin/distribution">Zurück zur API-Schnittstelle</Link></p>}
|
||||
<h1 className="page-title">Release-Abgleich</h1>
|
||||
<p style={{ color: 'var(--text2)', maxWidth: '52rem', lineHeight: 1.55, marginBottom: '0.75rem' }}>
|
||||
Hier stehen Übungen, deren Arbeitsfassung vom letzten veröffentlichten Release abweicht.
|
||||
Ein neues Release übernimmt den aktuellen Stand. Das bisherige Release bleibt unter seiner ID abrufbar.
|
||||
</p>
|
||||
{error ? <p role="alert">{error}</p> : null}
|
||||
{!items ? <p>Wird geladen …</p> : null}
|
||||
{items && !items.length ? (
|
||||
<p>Keine Arbeitsfassung weicht von ihrem letzten Release ab.</p>
|
||||
) : null}
|
||||
{items?.length ? (
|
||||
<ul style={{ paddingLeft: 18 }}>
|
||||
{items.map((item) => (
|
||||
<li key={item.exercise_id} style={{ marginBottom: 16 }}>
|
||||
<strong>{item.title}</strong>
|
||||
<div style={{ color: 'var(--text2)', fontSize: 13 }}>
|
||||
{item.visibility === 'club' && item.club_name ? item.club_name : VISIBILITY[item.visibility] || item.visibility}
|
||||
{' · Release Revision '}
|
||||
{item.revision}
|
||||
{item.areas?.length ? ` · ${item.areas.join(', ')}` : ''}
|
||||
</div>
|
||||
<Link to={`/exercises/${item.exercise_id}/edit?tab=freigabe`}>Freigabe öffnen</Link>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
) : null}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -5,7 +5,6 @@
|
||||
*/
|
||||
|
||||
import { request, ACTIVE_CLUB_STORAGE_KEY, requestText } from '../api/client.js'
|
||||
import * as distributionApi from '../api/distribution.js'
|
||||
import * as exercises from '../api/exercises.js'
|
||||
import * as planning from '../api/planning.js'
|
||||
import * as skillProfiles from '../api/skillProfiles.js'
|
||||
@@ -14,7 +13,6 @@ export { ACTIVE_CLUB_STORAGE_KEY }
|
||||
export * from '../api/exercises.js'
|
||||
export * from '../api/planning.js'
|
||||
export * from '../api/skillProfiles.js'
|
||||
export * from '../api/distribution.js'
|
||||
|
||||
// ============================================================================
|
||||
// Auth
|
||||
@@ -676,40 +674,6 @@ export async function getAdminAiPromptPlaceholdersCatalog() {
|
||||
return request('/api/admin/ai-prompts/catalog/placeholders')
|
||||
}
|
||||
|
||||
/** Superadmin: OpenRouter-Standardmodell und live Modellkatalog */
|
||||
export async function getAdminOpenRouterSettings() {
|
||||
return request('/api/admin/openrouter/settings')
|
||||
}
|
||||
|
||||
export async function updateAdminOpenRouterSettings(openrouterModel) {
|
||||
return request('/api/admin/openrouter/settings', {
|
||||
method: 'PUT',
|
||||
body: JSON.stringify({ openrouter_model: openrouterModel || '' }),
|
||||
})
|
||||
}
|
||||
|
||||
export async function listAdminOpenRouterModels(refresh = false) {
|
||||
return request(`/api/admin/openrouter/models${refresh ? '?refresh=true' : ''}`)
|
||||
}
|
||||
|
||||
export async function getAdminOpenRouterRoles() {
|
||||
return request('/api/admin/openrouter/roles')
|
||||
}
|
||||
|
||||
export async function updateAdminOpenRouterRole(roleKey, openrouterModel) {
|
||||
return request(`/api/admin/openrouter/roles/${encodeURIComponent(roleKey)}`, {
|
||||
method: 'PUT',
|
||||
body: JSON.stringify({ openrouter_model: openrouterModel || '' }),
|
||||
})
|
||||
}
|
||||
|
||||
export async function updateAdminOpenRouterPromptRole(promptId, modelRole) {
|
||||
return request(`/api/admin/openrouter/prompts/${promptId}/role`, {
|
||||
method: 'PUT',
|
||||
body: JSON.stringify({ model_role: modelRole || null }),
|
||||
})
|
||||
}
|
||||
|
||||
export async function listCatalogPromptSlotTypes() {
|
||||
return request('/api/catalog-prompt-slot-types')
|
||||
}
|
||||
@@ -1196,12 +1160,6 @@ export const api = {
|
||||
previewAdminAiPrompt,
|
||||
resetAdminAiPromptTemplate,
|
||||
getAdminAiPromptPlaceholdersCatalog,
|
||||
getAdminOpenRouterSettings,
|
||||
updateAdminOpenRouterSettings,
|
||||
listAdminOpenRouterModels,
|
||||
getAdminOpenRouterRoles,
|
||||
updateAdminOpenRouterRole,
|
||||
updateAdminOpenRouterPromptRole,
|
||||
listCatalogPromptSlotTypes,
|
||||
getCatalogPromptSlots,
|
||||
updateCatalogPromptSlots,
|
||||
@@ -1322,8 +1280,6 @@ export const api = {
|
||||
request(`/api/content-reports/${id}`, { method: 'PATCH', body: JSON.stringify(body) }),
|
||||
setLegalHoldFromReport: (id, body) =>
|
||||
request(`/api/content-reports/${id}/legal-hold`, { method: 'POST', body: JSON.stringify(body) }),
|
||||
|
||||
...distributionApi,
|
||||
}
|
||||
|
||||
export default api
|
||||
@@ -17,7 +17,6 @@ export function snapshotExerciseForSelection(exercise) {
|
||||
training_type_names: exercise.training_type_names,
|
||||
media_count: exercise.media_count,
|
||||
variant_count: exercise.variant_count,
|
||||
api_offered: Boolean(exercise.api_offered),
|
||||
media: Array.isArray(exercise.media) ? exercise.media : [],
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,25 +3,17 @@ import { lazy } from 'react'
|
||||
/**
|
||||
* Lazy-Import mit Reload bei fehlendem Chunk (nach Deploy alte Hashes im Browser-Cache).
|
||||
*/
|
||||
const RELOAD_KEY = 'sj_chunk_reload'
|
||||
|
||||
export function lazyWithRetry(importFn) {
|
||||
return lazy(() =>
|
||||
importFn()
|
||||
.then((mod) => {
|
||||
sessionStorage.removeItem(RELOAD_KEY)
|
||||
return mod
|
||||
})
|
||||
.catch((err) => {
|
||||
const reloaded = sessionStorage.getItem(RELOAD_KEY)
|
||||
importFn().catch((err) => {
|
||||
const key = 'sj_chunk_reload'
|
||||
const reloaded = sessionStorage.getItem(key)
|
||||
if (!reloaded) {
|
||||
sessionStorage.setItem(RELOAD_KEY, '1')
|
||||
const url = new URL(window.location.href)
|
||||
url.searchParams.set('sj_reload', String(Date.now()))
|
||||
window.location.replace(url.toString())
|
||||
sessionStorage.setItem(key, '1')
|
||||
window.location.reload()
|
||||
return new Promise(() => {})
|
||||
}
|
||||
sessionStorage.removeItem(RELOAD_KEY)
|
||||
sessionStorage.removeItem(key)
|
||||
throw err
|
||||
}),
|
||||
)
|
||||
|
||||
@@ -1,116 +0,0 @@
|
||||
#!/bin/sh
|
||||
# Prüfungen gegen den bereits deployten Stack. Ziel ist Pflicht: dev oder prod.
|
||||
# Kein Default auf Produktion.
|
||||
set -eu
|
||||
|
||||
TARGET="${1:-}"
|
||||
CHECK="${2:-}"
|
||||
|
||||
case "$TARGET" in
|
||||
dev)
|
||||
APP_DIR="/home/lars/docker/shinkan-dev"
|
||||
COMPOSE_FILE="docker-compose.dev-env.yml"
|
||||
BASE_URL="https://dev.shinkan.jinkendo.de"
|
||||
HEALTH_TRIES=90
|
||||
HEALTH_SLEEP=2
|
||||
;;
|
||||
prod)
|
||||
APP_DIR="/home/lars/docker/shinkan"
|
||||
COMPOSE_FILE="docker-compose.yml"
|
||||
BASE_URL="https://shinkan.jinkendo.de"
|
||||
HEALTH_TRIES=60
|
||||
HEALTH_SLEEP=5
|
||||
;;
|
||||
*)
|
||||
echo "Ziel muss dev oder prod sein, war: '${TARGET}'." >&2
|
||||
exit 1
|
||||
;;
|
||||
esac
|
||||
|
||||
echo "CI-Ziel: $TARGET ($APP_DIR, $BASE_URL), Prüfung: $CHECK"
|
||||
|
||||
wait_health() {
|
||||
echo "Warte auf $BASE_URL/health …"
|
||||
i=1
|
||||
while [ "$i" -le "$HEALTH_TRIES" ]; do
|
||||
if curl -sf "$BASE_URL/health" >/dev/null 2>&1; then
|
||||
echo "Health OK (Versuch $i)"
|
||||
return 0
|
||||
fi
|
||||
i=$((i + 1))
|
||||
sleep "$HEALTH_SLEEP"
|
||||
done
|
||||
echo "Timeout: $BASE_URL/health nicht erreichbar"
|
||||
curl -v "$BASE_URL/health" || true
|
||||
return 1
|
||||
}
|
||||
|
||||
run_pytest() {
|
||||
cd "$APP_DIR"
|
||||
echo "Warte auf stabilen backend-Container …"
|
||||
i=1
|
||||
while [ "$i" -le 60 ]; do
|
||||
if docker compose -f "$COMPOSE_FILE" exec -T backend true 2>/dev/null; then
|
||||
echo "Backend bereit (Versuch $i)"
|
||||
break
|
||||
fi
|
||||
if [ "$i" -eq 60 ]; then
|
||||
echo "Timeout: backend-Container nicht bereit"
|
||||
docker compose -f "$COMPOSE_FILE" ps || true
|
||||
docker compose -f "$COMPOSE_FILE" logs backend --tail 80 || true
|
||||
exit 1
|
||||
fi
|
||||
i=$((i + 1))
|
||||
sleep 5
|
||||
done
|
||||
docker compose -f "$COMPOSE_FILE" exec -T backend sh -lc "
|
||||
pip install -r /app/requirements-dev.txt &&
|
||||
cd /app &&
|
||||
ACCESS_LAYER_STRICT=1 python scripts/check_access_layer_hints.py &&
|
||||
python scripts/security_release_checks.py &&
|
||||
ACCESS_LAYER_INTEGRATION=1 TRAINING_PLANNING_INTEGRATION=1 SKIP_DB_MIGRATE=1 python -m pytest tests -m 'not slow' -ra -vv --tb=short
|
||||
"
|
||||
}
|
||||
|
||||
run_lint() {
|
||||
python3 -m py_compile "$APP_DIR/backend/main.py"
|
||||
echo "Backend syntax OK"
|
||||
}
|
||||
|
||||
run_frontend() {
|
||||
cd "$APP_DIR/frontend"
|
||||
npm install
|
||||
npm run build
|
||||
echo "Frontend build OK"
|
||||
}
|
||||
|
||||
run_k6() {
|
||||
wait_health
|
||||
K6_VER="v0.55.0"
|
||||
ARCH=$(uname -m)
|
||||
case "$ARCH" in
|
||||
x86_64) K6_ARCH=amd64 ;;
|
||||
aarch64|arm64) K6_ARCH=arm64 ;;
|
||||
*) echo "k6: unbekannte Architektur: $ARCH" >&2; exit 1 ;;
|
||||
esac
|
||||
echo "Installing k6 ${K6_VER} linux-${K6_ARCH}"
|
||||
curl -sSL "https://github.com/grafana/k6/releases/download/${K6_VER}/k6-${K6_VER}-linux-${K6_ARCH}.tar.gz" -o /tmp/k6.tgz
|
||||
tar -xzf /tmp/k6.tgz -C /tmp
|
||||
sudo mv "/tmp/k6-${K6_VER}-linux-${K6_ARCH}/k6" /usr/local/bin/k6
|
||||
k6 version
|
||||
cd "$APP_DIR"
|
||||
echo "k6 gegen BASE_URL=$BASE_URL"
|
||||
BASE_URL="$BASE_URL" k6 run scripts/load/k6-health-baseline.js
|
||||
echo "k6 Health-Baseline passed"
|
||||
}
|
||||
|
||||
case "$CHECK" in
|
||||
pytest) run_pytest ;;
|
||||
lint) run_lint ;;
|
||||
frontend) run_frontend ;;
|
||||
k6) run_k6 ;;
|
||||
*)
|
||||
echo "Prüfung muss pytest, lint, frontend oder k6 sein, war: '${CHECK}'." >&2
|
||||
exit 1
|
||||
;;
|
||||
esac
|
||||
Reference in new issue
Block a user