Enhance Skill Scoring and Profile Features
Deploy Development / deploy (push) Successful in 39s
Test Suite / pytest-backend (push) Successful in 42s
Test Suite / lint-backend (push) Successful in 0s
Test Suite / build-frontend (push) Successful in 13s
Test Suite / k6 /health Baseline (push) Successful in 33s
Test Suite / playwright-tests (push) Successful in 1m15s

- Updated the skill scoring specification to include club-specific metrics and improved aggregation methods for skill profiles.
- Introduced new API endpoints for batch skill profile summaries, allowing for efficient retrieval of compact skill data.
- Enhanced frontend components to display skill profiles with club comparisons, improving user interaction and visibility of skill strengths.
- Added filtering options for skills in the framework programs, enabling users to refine selections based on training weight relative to club maximums.
- Improved CSS styles for skill profile displays, ensuring a cohesive and user-friendly interface across the application.
This commit is contained in:
Lars committed 2026-05-21 09:05:13 +02:00
1 parent 5200895a73
commit 78c6c51520
15 files changed
+1131 -141

No files matched your search

+340 -95
View File
@@ -471,6 +471,337 @@ def merge_skill_weights_into_max(
target[sid] = w
def merge_skill_weights_with_reference(
max_by_skill: Dict[int, float],
ref_by_skill: Dict[int, Dict[str, Any]],
profile: Dict[str, Any],
*,
artifact_type: str,
artifact_id: int,
artifact_title: Optional[str] = None,
) -> None:
"""Aktualisiert Vereins-Maximum je Fähigkeit inkl. Quell-Artefakt."""
for sk in profile.get("skills") or []:
sid = int(sk["skill_id"])
w = float(sk.get("weight") or 0)
if w <= 0:
continue
if w > max_by_skill.get(sid, 0.0):
max_by_skill[sid] = w
ref_by_skill[sid] = {
"artifact_type": artifact_type,
"artifact_id": int(artifact_id),
"artifact_title": (artifact_title or "").strip() or None,
"weight": _round2(w),
}
def top_categories_summary(profile: Dict[str, Any], limit: int = 6) -> List[Dict[str, Any]]:
"""Top-Fähigkeit je Unterkategorie (kompakt für Listen/Discovery)."""
out: List[Dict[str, Any]] = []
for mc in profile.get("by_main_category") or []:
for cat in mc.get("categories") or []:
top = cat.get("top_skill")
if not top:
continue
out.append(
{
"main_category_name": mc.get("main_category_name"),
"category_name": cat.get("category_name"),
"skill_id": top.get("skill_id"),
"skill_name": top.get("skill_name"),
"score": top.get("score") or top.get("weight"),
"weight": top.get("weight"),
"universal_percent": top.get("universal_percent"),
}
)
if len(out) >= limit:
return out
return out
def _apply_reference_to_profile(
profile: Dict[str, Any],
reference_max_by_skill: Optional[Dict[int, float]],
) -> None:
_apply_reference_universal_percent(profile.get("skills") or [], reference_max_by_skill)
profile["by_main_category"] = _build_by_main_category(profile.get("skills") or [])
for mc in profile.get("by_main_category") or []:
for cat in mc.get("categories") or []:
top = cat.get("top_skill")
if top and reference_max_by_skill:
sid = int(top["skill_id"])
ref = float(reference_max_by_skill.get(sid) or 0)
if ref > 0:
top["universal_percent"] = _round2(float(top["weight"]) / ref * 100.0)
profile["has_reference_scale"] = bool(reference_max_by_skill)
def compact_profile_summary(
profile: Dict[str, Any],
ref_by_skill: Optional[Dict[int, Dict[str, Any]]] = None,
*,
skills_limit: int = 20,
) -> Dict[str, Any]:
"""Leichtgewichtiges Profil für Listen — ohne Übungsdetails."""
skills_out: List[Dict[str, Any]] = []
for s in profile.get("skills") or []:
sid = int(s["skill_id"])
w = float(s.get("weight") or 0)
entry: Dict[str, Any] = {
"skill_id": sid,
"skill_name": s.get("skill_name"),
"category_name": s.get("category_name") or s.get("category"),
"main_category_name": s.get("main_category_name"),
"weight": s.get("weight"),
"universal_percent": s.get("universal_percent"),
}
ref = (ref_by_skill or {}).get(sid)
if ref and w < float(ref.get("weight") or 0) - 0.01:
entry["club_best"] = ref
skills_out.append(entry)
if len(skills_out) >= skills_limit:
break
return {
"total_score": profile.get("total_score"),
"total_weight": profile.get("total_weight"),
"exercise_occurrence_count": profile.get("exercise_occurrence_count"),
"skills_count": len(profile.get("skills") or []),
"top_by_category": top_categories_summary(profile),
"skills": skills_out,
}
def batch_framework_occurrences_by_id(
cur, framework_ids: Sequence[int]
) -> Dict[int, List[ExerciseOccurrence]]:
ids = sorted({int(x) for x in framework_ids if x})
if not ids:
return {}
ph = ",".join(["%s"] * len(ids))
cur.execute(
f"""
SELECT s.framework_program_id,
COALESCE(NULLIF(TRIM(s.title), ''), 'Session ' || (s.sort_order + 1)::text) AS slot_label,
tusi.exercise_id,
tusi.planned_duration_min
FROM training_framework_slots s
INNER JOIN training_units tu ON tu.framework_slot_id = s.id
INNER JOIN training_unit_sections tus ON tus.training_unit_id = tu.id
INNER JOIN training_unit_section_items tusi ON tusi.section_id = tus.id
WHERE s.framework_program_id IN ({ph})
AND tusi.item_type = 'exercise'
AND tusi.exercise_id IS NOT NULL
ORDER BY s.framework_program_id, s.sort_order, tus.order_index, tusi.order_index
""",
ids,
)
out: Dict[int, List[ExerciseOccurrence]] = defaultdict(list)
for row in cur.fetchall():
fid = int(row["framework_program_id"])
out[fid].append(
ExerciseOccurrence(
exercise_id=int(row["exercise_id"]),
planned_duration_min=row.get("planned_duration_min"),
context_label=row.get("slot_label"),
)
)
return dict(out)
def batch_module_occurrences_by_id(
cur, module_ids: Sequence[int]
) -> Dict[int, List[ExerciseOccurrence]]:
ids = sorted({int(x) for x in module_ids if x})
if not ids:
return {}
ph = ",".join(["%s"] * len(ids))
cur.execute(
f"""
SELECT module_id, exercise_id, planned_duration_min
FROM training_module_items
WHERE module_id IN ({ph})
AND item_type = 'exercise'
AND exercise_id IS NOT NULL
ORDER BY module_id, order_index
""",
ids,
)
out: Dict[int, List[ExerciseOccurrence]] = defaultdict(list)
for row in cur.fetchall():
mid = int(row["module_id"])
out[mid].append(
ExerciseOccurrence(
exercise_id=int(row["exercise_id"]),
planned_duration_min=row.get("planned_duration_min"),
)
)
return dict(out)
def batch_compute_profiles(
occ_by_artifact: Dict[int, List[ExerciseOccurrence]],
skills_map: Dict[int, List[Dict[str, Any]]],
*,
reference_max_by_skill: Optional[Dict[int, float]] = None,
default_item_minutes: int = DEFAULT_ITEM_MINUTES,
) -> Dict[int, Dict[str, Any]]:
return {
aid: compute_skill_profile(
occ,
skills_map,
default_item_minutes=default_item_minutes,
reference_max_by_skill=reference_max_by_skill,
)
for aid, occ in occ_by_artifact.items()
}
def compute_club_corpus_reference(
cur,
*,
profile_id: int,
effective_club_id: Optional[int],
include_artifact_summaries: bool = False,
) -> Dict[str, Any]:
"""
Stärkstes Trainingsgewicht je Fähigkeit über alle Vereins-Artefakte (sichtbar im aktiven Verein).
Optional: kompakte Profile aller gescannten Artefakte (ein Durchlauf für Listen).
"""
from tenant_context import club_library_visibility_sql
max_by_skill: Dict[int, float] = {}
ref_by_skill: Dict[int, Dict[str, Any]] = {}
artifact_count = 0
raw_profiles: Dict[str, Dict[str, Any]] = {}
if effective_club_id is None:
return {
"club_id": None,
"max_by_skill": max_by_skill,
"ref_by_skill": ref_by_skill,
"artifact_count": 0,
"artifact_summaries": {},
}
def ingest(artifact_type: str, artifact_id: int, title: Optional[str], prof: Dict[str, Any]) -> None:
nonlocal artifact_count
if not prof.get("skills"):
return
artifact_count += 1
merge_skill_weights_with_reference(
max_by_skill,
ref_by_skill,
prof,
artifact_type=artifact_type,
artifact_id=artifact_id,
artifact_title=title,
)
if include_artifact_summaries:
raw_profiles[f"{artifact_type}:{artifact_id}"] = prof
vis_clause, vis_params = club_library_visibility_sql(
alias="fp",
profile_id=profile_id,
effective_club_id=effective_club_id,
)
cur.execute(
f"""
SELECT fp.id, fp.title
FROM training_framework_programs fp
WHERE ({vis_clause})
ORDER BY fp.updated_at DESC NULLS LAST
""",
vis_params,
)
fw_rows = cur.fetchall()
if fw_rows:
fw_ids = [int(r["id"]) for r in fw_rows]
titles = {int(r["id"]): r.get("title") for r in fw_rows}
occ_map = batch_framework_occurrences_by_id(cur, fw_ids)
all_eids = {o.exercise_id for occs in occ_map.values() for o in occs}
skills_map = fetch_exercise_skills_bulk(cur, all_eids)
profiles = batch_compute_profiles(occ_map, skills_map)
for fid, prof in profiles.items():
ingest("framework_program", fid, titles.get(fid), prof)
vis_clause, vis_params = club_library_visibility_sql(
alias="m",
profile_id=profile_id,
effective_club_id=effective_club_id,
)
cur.execute(
f"""
SELECT m.id, m.title
FROM training_modules m
WHERE ({vis_clause})
ORDER BY m.updated_at DESC NULLS LAST
""",
vis_params,
)
mod_rows = cur.fetchall()
if mod_rows:
mod_ids = [int(r["id"]) for r in mod_rows]
titles = {int(r["id"]): r.get("title") for r in mod_rows}
occ_map = batch_module_occurrences_by_id(cur, mod_ids)
all_eids = {o.exercise_id for occs in occ_map.values() for o in occs}
skills_map = fetch_exercise_skills_bulk(cur, all_eids)
profiles = batch_compute_profiles(occ_map, skills_map)
for mid, prof in profiles.items():
ingest("training_module", mid, titles.get(mid), prof)
vis_clause, vis_params = club_library_visibility_sql(
alias="g",
profile_id=profile_id,
effective_club_id=effective_club_id,
)
cur.execute(
f"""
SELECT g.id, g.name
FROM exercise_progression_graphs g
WHERE ({vis_clause})
ORDER BY g.updated_at DESC NULLS LAST
""",
vis_params,
)
for row in cur.fetchall():
gid = int(row["id"])
occ = collect_progression_graph_exercise_occurrences(cur, gid)
if not occ:
continue
prof = profile_for_occurrences(
cur, occ, default_item_minutes=GRAPH_DEFAULT_ITEM_MINUTES
)
ingest("progression_graph", gid, row.get("name"), prof)
artifact_summaries: Dict[str, Dict[str, Any]] = {}
if include_artifact_summaries and raw_profiles:
for key, prof in raw_profiles.items():
_apply_reference_to_profile(prof, max_by_skill)
artifact_summaries[key] = compact_profile_summary(prof, ref_by_skill)
return {
"club_id": effective_club_id,
"max_by_skill": max_by_skill,
"ref_by_skill": ref_by_skill,
"artifact_count": artifact_count,
"artifact_summaries": artifact_summaries,
}
def reference_scale_meta(corpus: Dict[str, Any]) -> Dict[str, Any]:
return {
"scope": "club",
"club_id": corpus.get("club_id"),
"skills_in_corpus": len(corpus.get("max_by_skill") or {}),
"artifacts_scanned": corpus.get("artifact_count") or 0,
"description": (
"universal_percent = Anteil am stärksten genutzten Vereins-Artefakt je Fähigkeit "
"(nur visibility=club im aktiven Verein)"
),
}
def compute_corpus_skill_max_weights(
cur,
*,
@@ -480,102 +811,16 @@ def compute_corpus_skill_max_weights(
limit_per_type: int = 50,
) -> Dict[int, float]:
"""
Maximum absolutes Trainingsgewicht je Fähigkeit über sichtbare Bibliotheksartefakte.
Basis für universal_percent (Skala über alle Programme).
Vereins-Referenz je Fähigkeit (Legacy-Hülle — nutzt compute_club_corpus_reference).
role/limit_per_type werden ignoriert (Vereinskontext, alle Vereins-Artefakte).
"""
from tenant_context import library_content_visibility_sql
max_by_skill: Dict[int, float] = {}
def scan_frameworks():
vis_clause, vis_params = library_content_visibility_sql(
alias="fp",
profile_id=profile_id,
role=role,
effective_club_id=effective_club_id,
)
cur.execute(
f"""
SELECT fp.id FROM training_framework_programs fp
WHERE ({vis_clause})
ORDER BY fp.updated_at DESC NULLS LAST
LIMIT %s
""",
(*vis_params, limit_per_type),
)
for row in cur.fetchall():
fid = int(row["id"])
cur.execute(
"""
SELECT tu.id
FROM training_framework_slots s
INNER JOIN training_units tu ON tu.framework_slot_id = s.id
WHERE s.framework_program_id = %s
""",
(fid,),
)
occ: List[ExerciseOccurrence] = []
for u in cur.fetchall():
occ.extend(collect_unit_exercise_occurrences(cur, int(u["id"])))
if not occ:
continue
prof = profile_for_occurrences(cur, occ)
merge_skill_weights_into_max(max_by_skill, prof)
def scan_modules():
vis_clause, vis_params = library_content_visibility_sql(
alias="m",
profile_id=profile_id,
role=role,
effective_club_id=effective_club_id,
)
cur.execute(
f"""
SELECT m.id FROM training_modules m
WHERE ({vis_clause})
ORDER BY m.updated_at DESC NULLS LAST
LIMIT %s
""",
(*vis_params, limit_per_type),
)
for row in cur.fetchall():
mid = int(row["id"])
occ = collect_module_exercise_occurrences(cur, mid)
if not occ:
continue
prof = profile_for_occurrences(cur, occ)
merge_skill_weights_into_max(max_by_skill, prof)
def scan_graphs():
vis_clause, vis_params = library_content_visibility_sql(
alias="g",
profile_id=profile_id,
role=role,
effective_club_id=effective_club_id,
)
cur.execute(
f"""
SELECT g.id FROM exercise_progression_graphs g
WHERE ({vis_clause})
ORDER BY g.updated_at DESC NULLS LAST
LIMIT %s
""",
(*vis_params, limit_per_type),
)
for row in cur.fetchall():
gid = int(row["id"])
occ = collect_progression_graph_exercise_occurrences(cur, gid)
if not occ:
continue
prof = profile_for_occurrences(
cur, occ, default_item_minutes=GRAPH_DEFAULT_ITEM_MINUTES
)
merge_skill_weights_into_max(max_by_skill, prof)
scan_frameworks()
scan_modules()
scan_graphs()
return max_by_skill
del role, limit_per_type
corpus = compute_club_corpus_reference(
cur,
profile_id=profile_id,
effective_club_id=effective_club_id,
)
return corpus["max_by_skill"]
def match_score_for_skill_ids(profile: Dict[str, Any], skill_ids: Sequence[int]) -> Dict[str, Any]: