diff --git a/.claude/docs/working/ACCESS_LAYER_ENDPOINT_AUDIT.md b/.claude/docs/working/ACCESS_LAYER_ENDPOINT_AUDIT.md
index 8b557e9..ae722fe 100644
--- a/.claude/docs/working/ACCESS_LAYER_ENDPOINT_AUDIT.md
+++ b/.claude/docs/working/ACCESS_LAYER_ENDPOINT_AUDIT.md
@@ -30,7 +30,7 @@ Fortlaufend gemäß `ACCESS_LAYER_AND_GOVERNANCE_PLAN.md` Stufe A–C.
| 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` | ja | `get_tenant_context` | ja | Privat: Besitzer; Verein: `club_admin` und freigeschalteter Verein; global: nur `superadmin`. Schlüssel legt der Mandant an. Vereinsfreischaltung nur `superadmin`. Der Release-Abgleich zeigt nur Übungen, die der Aufrufer erneut freigeben darf |
+| 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 |
diff --git a/backend/distribution_contract.py b/backend/distribution_contract.py
index 5cbd1e0..d643a6f 100644
--- a/backend/distribution_contract.py
+++ b/backend/distribution_contract.py
@@ -226,6 +226,96 @@ def decode_cursor(secret: str, recipient_id: str, token: Optional[str]) -> int:
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_document(exercise: dict, variants: list[dict], media: list[dict]) -> dict:
+ """Aktueller Übungsstand. Die Reihenfolge der Varianten und Medien gehört zum Inhalt."""
+ 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")),
+ "title": exercise.get("title") or "",
+ "summary": plaintext(exercise.get("summary")),
+ "goal": plaintext(exercise.get("goal")),
+ "execution": plaintext(exercise.get("execution")),
+ "preparation": plaintext(exercise.get("preparation")),
+ "trainer_notes": plaintext(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": plaintext(item.get("description")),
+ "execution_changes": plaintext(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
diff --git a/backend/distribution_service.py b/backend/distribution_service.py
index 9fe0a2e..5031bc0 100644
--- a/backend/distribution_service.py
+++ b/backend/distribution_service.py
@@ -17,11 +17,19 @@ from distribution_contract import (
REASON_CODES,
can_withdraw,
canonical_json,
+ catalog_available,
+ catalog_changes,
+ catalog_document,
+ catalog_hash,
+ decode_catalog_cursor,
+ encode_catalog_cursor,
changed_areas,
collect_blockers,
cut_hash,
decide_confirm,
+ cursor_secret,
exercise_offerable,
+ InvalidCursor,
key_covers,
package_state,
scope_denial,
@@ -1624,6 +1632,145 @@ def _may_rerelease(cur, exercise: dict, profile_id: int, role: str) -> bool:
return _denial_for(cur, exercise, {"kind": kind, "club_id": exercise.get("club_id")}, profile_id, role) is None
+def _rows_for_ids(cur, sql: str, ids: list[int]) -> list[dict]:
+ if not ids:
+ return []
+ placeholders = ", ".join(["%s"] * len(ids))
+ cur.execute(sql.format(placeholders=placeholders), tuple(ids))
+ return [r2d(row) for row in _rows(cur)]
+
+
+def _offered_exercises(cur) -> list[dict]:
+ cur.execute(
+ """
+ SELECT id, public_id, title, summary, goal, execution, preparation, trainer_notes,
+ equipment, duration_min, duration_max, visibility, club_id, created_by, api_offered
+ FROM exercises
+ WHERE api_offered = true
+ ORDER BY title, id
+ """
+ )
+ return [r2d(row) for row in _rows(cur)]
+
+
+def _catalog_parts(cur, exercises: list[dict]) -> tuple[dict, dict]:
+ ids = [int(item["id"]) for item in exercises]
+ variants = _rows_for_ids(
+ cur,
+ """
+ SELECT id, exercise_id, public_id, variant_name, description, execution_changes, sequence_order
+ FROM exercise_variants
+ WHERE exercise_id IN ({placeholders})
+ ORDER BY sequence_order NULLS LAST, id
+ """,
+ ids,
+ )
+ media = _rows_for_ids(
+ cur,
+ """
+ SELECT id, exercise_id, public_id, media_type, title, sort_order
+ FROM exercise_media
+ WHERE exercise_id IN ({placeholders})
+ ORDER BY sort_order NULLS LAST, id
+ """,
+ ids,
+ )
+ by_variant: dict[int, list] = {}
+ by_media: dict[int, list] = {}
+ for item in variants:
+ by_variant.setdefault(int(item["exercise_id"]), []).append(item)
+ for item in media:
+ by_media.setdefault(int(item["exercise_id"]), []).append(item)
+ return by_variant, by_media
+
+
+def _catalog_entry(exercise: dict, variants: list[dict], media: list[dict]) -> tuple[dict, str]:
+ document = catalog_document(exercise, variants, media)
+ return document, catalog_hash(document)
+
+
+def load_catalog(cur, binding: dict, cursor_token: Optional[str]) -> dict:
+ previous: dict = {}
+ if cursor_token:
+ snapshot_id = decode_catalog_cursor(cursor_secret(), binding["binding_id"], cursor_token)
+ cur.execute(
+ "SELECT binding_id, snapshot FROM distribution_catalog_snapshots WHERE id = %s",
+ (snapshot_id,),
+ )
+ stored = _one(cur)
+ if not stored or str(stored.get("binding_id")) != str(binding["binding_id"]):
+ raise InvalidCursor()
+ snapshot = stored.get("snapshot") or {}
+ if isinstance(snapshot, str):
+ import json
+
+ snapshot = json.loads(snapshot)
+ previous = {str(key): value for key, value in dict(snapshot).items()}
+ offered = _offered_exercises(cur)
+ visible = [
+ item
+ for item in offered
+ if catalog_available(True, grant_allows(cur, binding, item))
+ ]
+ by_variant, by_media = _catalog_parts(cur, visible)
+ current: dict[str, str] = {}
+ exercises = []
+ for item in visible:
+ document, digest = _catalog_entry(
+ item,
+ by_variant.get(int(item["id"]), []),
+ by_media.get(int(item["id"]), []),
+ )
+ current[document["source_id"]] = digest
+ exercises.append(
+ {"source_id": document["source_id"], "title": document["title"], "content_hash": digest}
+ )
+ snapshot_id = new_id()
+ import json
+
+ cur.execute(
+ """
+ INSERT INTO distribution_catalog_snapshots (id, binding_id, snapshot)
+ VALUES (%s, %s, %s::jsonb)
+ """,
+ (snapshot_id, binding["binding_id"], json.dumps(current, ensure_ascii=False, sort_keys=True)),
+ )
+ return {
+ "exercises": exercises,
+ "changes": catalog_changes(previous, current),
+ "next_cursor": encode_catalog_cursor(cursor_secret(), binding["binding_id"], snapshot_id),
+ }
+
+
+def load_catalog_exercise(cur, binding: dict, source_id: str) -> dict:
+ import uuid
+
+ try:
+ uuid.UUID(str(source_id))
+ except ValueError:
+ raise HTTPException(status_code=404, detail={"code": "not_found", "message": "Übung nicht verfügbar."})
+ cur.execute(
+ """
+ SELECT id, public_id, title, summary, goal, execution, preparation, trainer_notes,
+ equipment, duration_min, duration_max, visibility, club_id, created_by, api_offered
+ FROM exercises
+ WHERE public_id = %s
+ """,
+ (str(source_id),),
+ )
+ exercise = _one(cur)
+ in_scope = bool(exercise) and grant_allows(cur, binding, exercise)
+ if not exercise or not catalog_available(bool(exercise.get("api_offered")), in_scope):
+ raise HTTPException(status_code=404, detail={"code": "not_found", "message": "Übung nicht verfügbar."})
+ by_variant, by_media = _catalog_parts(cur, [exercise])
+ document, digest = _catalog_entry(
+ exercise,
+ by_variant.get(int(exercise["id"]), []),
+ by_media.get(int(exercise["id"]), []),
+ )
+ return {**document, "content_hash": digest}
+
+
def list_release_drift(cur, profile_id: int, role: str) -> list[dict]:
cur.execute(
"""
diff --git a/backend/migrations/102_exercise_api_offering.sql b/backend/migrations/102_exercise_api_offering.sql
new file mode 100644
index 0000000..c8f985d
--- /dev/null
+++ b/backend/migrations/102_exercise_api_offering.sql
@@ -0,0 +1,18 @@
+-- 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);
diff --git a/backend/routers/distribution.py b/backend/routers/distribution.py
index bdc985b..69ceb27 100644
--- a/backend/routers/distribution.py
+++ b/backend/routers/distribution.py
@@ -30,6 +30,8 @@ from distribution_service import (
issue_key,
list_changes,
list_release_drift,
+ load_catalog,
+ load_catalog_exercise,
load_asset,
load_availability,
load_manifest,
@@ -144,6 +146,65 @@ 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,
diff --git a/backend/routers/exercises.py b/backend/routers/exercises.py
index 7778789..19e529e 100644
--- a/backend/routers/exercises.py
+++ b/backend/routers/exercises.py
@@ -451,6 +451,11 @@ _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)."""
@@ -1501,6 +1506,41 @@ 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,
@@ -2140,7 +2180,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,
+ SELECT e.id, e.title, e.summary, e.visibility, e.status, e.api_offered,
e.exercise_kind, e.method_archetype,
e.created_by, p.name as creator_name,
e.club_id, c.name as club_name,
@@ -2213,6 +2253,7 @@ 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):
diff --git a/backend/tests/test_distribution_contract.py b/backend/tests/test_distribution_contract.py
index f1d863b..cb070d7 100644
--- a/backend/tests/test_distribution_contract.py
+++ b/backend/tests/test_distribution_contract.py
@@ -29,6 +29,10 @@ from distribution_contract import (
official_write_allowed,
plan_available,
rate_decision,
+ catalog_available,
+ catalog_changes,
+ catalog_document,
+ catalog_hash,
changed_areas,
release_denial,
retrievable_release_ids,
@@ -282,6 +286,52 @@ def test_release_screen_keeps_the_application_key() -> 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_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",
diff --git a/backend/version.py b/backend/version.py
index 5bb2c5a..11d32e7 100644
--- a/backend/version.py
+++ b/backend/version.py
@@ -1,6 +1,6 @@
# Shinkan Jinkendo Version Information
-APP_VERSION = "0.8.256"
+APP_VERSION = "0.8.257"
BUILD_DATE = "2026-11-23"
DB_SCHEMA_VERSION = "20261123101"
@@ -38,8 +38,8 @@ 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.38.0", # Globale Übungen schreibt und gibt nur superadmin frei
- "distribution": "1.4.0", # Arbeitsfassung gegen letztes Release: Übung und zentrale Abgleichliste
+ "exercises": "2.39.0", # API-Bereitstellung je Übung, einzeln und als Auswahl
+ "distribution": "1.5.0", # Aktueller Katalogabruf mit Änderung seit dem letzten Cursor
"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",
@@ -55,6 +55,13 @@ MODULE_VERSIONS = {
}
CHANGELOG = [
+ {
+ "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",
diff --git a/frontend/src/api/exercises.js b/frontend/src/api/exercises.js
index 4e72274..8f6cf38 100644
--- a/frontend/src/api/exercises.js
+++ b/frontend/src/api/exercises.js
@@ -474,6 +474,14 @@ 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', {
diff --git a/frontend/src/components/exercises/ExerciseListBulkToolbar.jsx b/frontend/src/components/exercises/ExerciseListBulkToolbar.jsx
index 1fd134d..cff2141 100644
--- a/frontend/src/components/exercises/ExerciseListBulkToolbar.jsx
+++ b/frontend/src/components/exercises/ExerciseListBulkToolbar.jsx
@@ -6,6 +6,8 @@ export default function ExerciseListBulkToolbar({
onClearSelection,
onOpenBulkModal,
onOpenSaveModuleModal,
+ onSetApiOffering,
+ apiOfferingBusy = false,
}) {
if (selectedCount < 1) return null
@@ -21,6 +23,22 @@ export default function ExerciseListBulkToolbar({
+
+
Bis zu {bulkMaxIds} pro Anfrage. Für „Verein“ ohne Auswahl: aktiver Vereinskontext (
X-Active-Club-Id
diff --git a/frontend/src/components/exercises/ExerciseListCard.jsx b/frontend/src/components/exercises/ExerciseListCard.jsx
index 2fd4a58..fce5edf 100644
--- a/frontend/src/components/exercises/ExerciseListCard.jsx
+++ b/frontend/src/components/exercises/ExerciseListCard.jsx
@@ -223,6 +223,12 @@ export default function ExerciseListCard({
{name}
))}
+
+ {exercise.api_offered ? 'API bereitgestellt' : 'API aus'}
+
{(exercise.exercise_kind || '').toLowerCase().trim() === 'combination' ? (
{
+ 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('')
@@ -727,6 +761,8 @@ function ExercisesListPageRoot() {
onClearSelection={clearSelection}
onOpenBulkModal={openBulkModal}
onOpenSaveModuleModal={() => setSaveModuleModalOpen(true)}
+ onSetApiOffering={handleApiOffering}
+ apiOfferingBusy={apiOfferingBusy}
/>