Publish frozen exercise releases and report whether they stay offerable.
Deploy Development / deploy (push) Successful in 1m12s
Test Suite / pytest-backend (push) Failing after 30s
Test Suite / lint-backend (push) Successful in 0s
Test Suite / build-frontend (push) Successful in 16s
Test Suite / k6 /health Baseline (push) Successful in 35s
Test Suite / playwright-tests (push) Failing after 7m42s

Recipients can ask whether a released exercise is still offerable. Archiving or removing the source stops new offers; the frozen copy stays fetchable until withdrawal.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
LarsandCursor committed 2026-11-23 13:07:47 +01:00
1 parent b537750671
commit fe3633ba8b
21 files changed
+3862 -12

No files matched your search

+460
View File
@@ -0,0 +1,460 @@
"""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 (
backlog_count,
confirm_draft,
create_draft,
issue_key,
list_changes,
load_asset,
load_availability,
load_manifest,
overview,
resolve_bearer,
retire_release,
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: str
recipient_id: str
cut: Optional[dict] = None
class CutBody(BaseModel):
cut: dict
class ReasonBody(BaseModel):
reason_code: str
@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,
)
with get_db() as conn:
cur = get_cursor(conn)
payload = list_changes(cur, binding["recipient_id"], seq, limit)
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:
payload = load_availability(cur, binding["recipient_id"], 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("/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:
body = load_manifest(cur, binding["recipient_id"], release_id)
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:
path, media_type = load_asset(cur, binding["recipient_id"], release_id, asset_id)
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)
result = create_draft(
cur,
exercise_id,
body.publisher_id,
body.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)}
+29 -7
View File
@@ -29,6 +29,7 @@ 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
@@ -39,6 +40,8 @@ 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,
@@ -563,11 +566,13 @@ 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):
@@ -1458,9 +1463,13 @@ 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:
@@ -1468,11 +1477,6 @@ 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
@@ -1598,6 +1602,9 @@ 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
@@ -2833,6 +2840,11 @@ 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()
@@ -3040,6 +3052,11 @@ 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(
@@ -3840,6 +3857,11 @@ 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: