Compare commits

...
Author SHA1 Message Date
genja 00f54d117d Merge pull request 'Feature/standardize layout' (#324) from feature/standardize-layout into dev
LocationBasedServices/smartguide/pipeline/head This commit looks good
Reviewed-on: #324
2026-11-18 18:35:06 +01:00
genja d90bf9b837 navigate to founders with no threshold per default
LocationBasedServices/smartguide/pipeline/head This commit looks good
LocationBasedServices/smartguide/pipeline/pr-dev Build queued...
2026-11-18 18:21:55 +01:00
genja ea5e3ca942 added filter params to founders resolver 2026-11-18 18:21:34 +01:00
genja 722f95fad1 added founder table filters to the founder dashboard 2026-11-18 18:21:07 +01:00
genja eb2fa92225 show all founder profiles per default 2026-11-18 18:20:45 +01:00
genja e2be1fc57d added filters for founder table 2026-11-18 18:18:53 +01:00
genja e9a72f88c1 moved selected row to table detail row 2026-11-18 15:12:27 +01:00
genja 48a10dbca3 threshold is opt-in now 2026-11-18 15:10:58 +01:00
genja dc79d16dfb removed "suspicious profile" note next to person names 2026-11-18 15:10:22 +01:00
genja d1827cf86b new model files added
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-11-17 23:07:34 +01:00
genja 728d8c9646 added to_person_profile navigation 2026-11-17 23:07:21 +01:00
genja d60c17abf4 added highlighting for organization on navigation 2026-11-17 21:28:42 +01:00
genja 6b6a5c7cff added organization badge to person profile 2026-11-17 21:25:51 +01:00
genja 41cc3a7ac6 tests for verified organization and institution helper added 2026-11-17 21:20:28 +01:00
genja a1317810c9 added verified organization endpoint with models 2026-11-17 21:20:13 +01:00
genja 22997f6a16 added normalize org uri helper 2026-11-17 21:16:10 +01:00
genja 8322fea036 reused existing normalize org uri function 2026-11-17 21:10:51 +01:00
genja 492987100c added verified persons job 2026-11-16 14:43:12 +01:00
genja cb4e7465b1 added helper function to transfer NES credentials to the container/ added persistent directory for verified persons script 2026-11-16 14:42:45 +01:00
genja ef6df95b54 fixed verification helper for stop creating Edge/CollaborationGraph objects, added new helper function 2026-11-16 14:34:24 +01:00
genja a9e7a0f3ab optimized route-scroll behaviour 2026-11-15 00:03:59 +01:00
genja 23b112beb9 optimized charts rendering 2026-11-15 00:03:52 +01:00
genja 739669021b added explain panel to founder-dashobard component 2026-11-15 00:03:22 +01:00
genja 4c39933b8d minor layout fixes 2026-11-13 12:02:35 +01:00
genja e6e8d192cc fixed bug where the page title was shown as tooltip on mouse hover 2026-11-12 23:07:52 +01:00
genja 9535bfedf5 standartized "goBack" button 2026-11-12 23:01:38 +01:00
genja faa22e0a8f added skeleton loading to person-card's university display 2026-11-12 22:53:07 +01:00
genja 83e0bc3e01 minor ui fixes 2026-11-12 22:43:23 +01:00
genja 30eea4aa22 prevented hierarchy to reresolbe on node click 2026-11-12 22:35:38 +01:00
genja 8b374681c2 added page title service for displaying page title 2026-11-12 22:25:42 +01:00
genja e984372259 made the "Zurück" button visible only within components 2026-11-12 21:58:55 +01:00
genja 8c45c29fc6 standartized resolving state of components 2026-11-12 21:55:44 +01:00
genja 0775f3efc7 fixed hierarchy chart render warning 2026-11-12 21:17:36 +01:00
genja 5153e5876d adjusted tooltips for better explanability 2026-11-12 21:02:39 +01:00
genja 90c6fa56c8 research-wordcloud component replaced by the shared keywords-component 2026-11-12 14:26:13 +01:00
genja e63f2e99d8 created utils for research wordcloud to enable compatibility to the shared keywords-wordcloud component 2026-11-12 14:24:26 +01:00
genja 34c0235112 updated keywords-wordcloud component. Adde more optional fields for reusability 2026-11-12 14:22:57 +01:00
genja 50350fcc12 Merge pull request 'Feature/multipliers frontend' (#323) from feature/multipliers-frontend into dev
LocationBasedServices/smartguide/pipeline/head This commit looks good
Reviewed-on: #323
2026-11-12 13:13:34 +01:00
106 changed files with 4818 additions and 1158 deletions
+6
View File
@@ -1,3 +1,4 @@
# Root-context job images only need service code, never the webapp or repo data.
*
!background-jobs
!service
@@ -7,6 +8,11 @@ service/*
# Keyword extraction contract, shared with background-jobs/app/llm/client.py.
!service/src/main/inse/news/keyword_extraction.py
# UDE verified-persons job image imports the full service package and one
# institution hierarchy, so these are the only extra paths it needs.
!service/src/main/inse
!service/src/data/hierarchies/I62318514/hierarchy.json
# Data-only folders that do not belong in the job image.
service/scripts/multipliers
+3
View File
@@ -26,3 +26,6 @@ service/sentence_transformer/models/
llm_evaluations/bio_generation/.venv
.devcontainer
# Runtime checkpoint for the UDE OrgMiner verified-person uploader.
service/scripts/upload_orgminer_verified_persons_ude/orgminer_verified_persons_ude_progress.json
service/scripts/upload_orgminer_verified_persons_ude/orgminer_verified_persons_ude_progress.json.tmp
+29
View File
@@ -82,6 +82,7 @@ differ only by their `command`.
| Project-Topic-Mapping | `jobs/project-topics` | `map_project_topics --output-index docker-job_test` | reads projects_bund_v1; needs host backend |
| News-Topic-Mapping | `jobs/news-topics` | `map_news_topics --output-index aktuell_openalex_topics` | bundles both topic_mapper pkgs; needs host backend |
| News-Keyword-Extraction | `jobs/news-keywords` | `sync.py --update-keywords --target-index docker-job_test` | ES + LLM creds; writes to test index |
| UDE OrgMiner Verified Persons | `jobs/orgminer-verified-persons-ude` | `upload_orgminer_verified_persons_ude.py --progress-file /state/orgminer_verified_persons_ude_progress.json` | Writes `orgminer_verified_persons_ude`; image-scoped NES creds; persistent checkpoint |
| Demo-Job A / B / C | `jobs/demo` | `demo.py` (seconds via command: `20` / `25` / `30`) | no dependencies; one image, three job rows |
Each image is its own repository under the `jobs/` path namespace, prefixed
@@ -106,6 +107,30 @@ docker push docker.nes.uni-due.de/inse/jobs/news-crawl:latest
Each image's Dockerfile header lists its own build command.
### UDE OrgMiner verified persons
```bash
docker build -f service/scripts/jobs-image/orgminer-verified-persons-ude/Dockerfile \
-t docker.nes.uni-due.de/inse/jobs/orgminer-verified-persons-ude:latest .
docker push docker.nes.uni-due.de/inse/jobs/orgminer-verified-persons-ude:latest
```
Create a manual-only job in the Jobs UI with this image and set **Persistent
directory** to `/state`. The image's entrypoint writes its JSON checkpoint to
`/state/orgminer_verified_persons_ude_progress.json`; the runner mounts a task-specific Docker volume there so
separate runs resume. Keep the job definition if you need to keep its checkpoint
(deleting the definition also removes its volume). Leave **Command** empty for a
full resumable run, or set it to `--limit 5` for a small first run. Set **Command**
to `--fresh` if every invocation should delete the checkpoint and start at the
first organization. Organizations are processed sequentially; no concurrency
flags exist. The target index is `orgminer_verified_persons_ude`.
If the run stops without a `Finished:` line and reports exit `137`, the
container was killed (usually by the host's out-of-memory killer) and no Python
traceback exists. The run log then gets a `[system] ... ran out of memory ...`
note from the runner. A job without a **Persistent directory** always starts
from the first organization, which makes such a restart look identical.
## Running locally without pushing
Before each run the backend pulls the job's image from the registry when it is a
@@ -127,6 +152,10 @@ is enough for local runs.
Because every tag lives under the `docker.nes.uni-due.de` registry host, the
backend treats these as registry images and injects the INSE Elasticsearch / LLM
credentials automatically (plus any per-job `env`).
The `orgminer-verified-persons-ude` image also receives `ELASTICSEARCH_URL` and
`ELASTICSEARCH_API_KEY` from backend settings, and only that exact repository
gets those NES credentials. Other job images continue to receive INSE/LLM
credentials only.
Most images write to the test index by default: the crawlers upload into the
index named by `NEWS_UPLOAD_INDEX` / `BUND_UPLOAD_INDEX` (both baked to
@@ -0,0 +1,27 @@
# UDE OrgMiner staff verification using the collaboration graph.
# Build from the repository root:
# docker build -f service/scripts/jobs-image/orgminer-verified-persons-ude/Dockerfile \
# -t docker.nes.uni-due.de/inse/jobs/orgminer-verified-persons-ude:latest .
#
# The runner injects INSE credentials for registry images and NES credentials
# only for this image. The persistent /state volume holds the JSON checkpoint.
FROM python:3.13-slim
WORKDIR /app
ENV PYTHONUNBUFFERED=1 \
PYTHONPATH=/app/service/src/main
COPY service/scripts/jobs-image/orgminer-verified-persons-ude/requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY service/src/main/inse/ ./service/src/main/inse/
COPY service/src/data/hierarchies/I62318514/hierarchy.json \
./service/src/data/hierarchies/I62318514/hierarchy.json
COPY service/scripts/upload_orgminer_verified_persons_ude/ \
./service/scripts/upload_orgminer_verified_persons_ude/
# Fail the image build if the service verification code is missing a dependency.
RUN python -c "import inse.orgminer.logic"
ENTRYPOINT ["python", "/app/service/scripts/upload_orgminer_verified_persons_ude/upload_orgminer_verified_persons_ude.py", \
"--progress-file", "/state/orgminer_verified_persons_ude_progress.json"]
@@ -0,0 +1,5 @@
fastapi~=0.115.0
httpx~=0.27.0
pydantic-settings~=2.2.1
python-dotenv~=1.0
sqlmodel~=0.0.33
@@ -0,0 +1,56 @@
# Upload verified UDE OrgMiner persons
Run from the repository root:
```bash
python service/scripts/upload_orgminer_verified_persons_ude/upload_orgminer_verified_persons_ude.py
```
The script reads `ude_organization_content_august_2025_draft`, applies the
OrgMiner collaboration-graph verification rule, and upserts one document per
verified OpenAlex person and organization into `orgminer_verified_persons_ude`
on the INSE Elasticsearch cluster.
For the background-job image and persistent checkpoint setup, see
[`../jobs-image/README.md`](../jobs-image/README.md#ude-orgminer-verified-persons).
INSE credentials must be available as `ELASTICSEARCH_INSE_URL` and
`ELASTICSEARCH_INSE_API_KEY` for reading/writing OrgMiner data. NES credentials
must also be available as `ELASTICSEARCH_URL` and `ELASTICSEARCH_API_KEY` for
OpenAlex author resolution during verification. They can be set in the
environment or the service `.env` file.
The default checkpoint is `orgminer_verified_persons_ude_progress.json` next to
the script. It records completed source organization document IDs and the last
completed organization URI. On restart the scan resumes from that URI, skips
completed organizations, and safely retries upserts if an interrupted request did
not get checkpointed. Use `--progress-file PATH` to keep the checkpoint elsewhere.
The script processes one organization at a time, so a run needs no concurrency
flags.
Useful options:
```bash
# Run verification without writing to Elasticsearch or changing the checkpoint
python service/scripts/upload_orgminer_verified_persons_ude/upload_orgminer_verified_persons_ude.py --dry-run
# Smoke-test a limited number of pending organizations
python service/scripts/upload_orgminer_verified_persons_ude/upload_orgminer_verified_persons_ude.py --limit 5
# Delete the checkpoint and scan from the first organization again
python service/scripts/upload_orgminer_verified_persons_ude/upload_orgminer_verified_persons_ude.py --fresh
```
Verification requests only the collaboration weights towards the organization's
other staff candidates. It does not materialize every co-author pair, which is
unbounded for works with hundreds or thousands of authors. The progress log ends
each line with the process's peak `rss` so memory growth is visible.
`--fresh` removes the selected checkpoint and its temporary atomic-write file,
but does not clear the output index. Existing person/organization IDs are
upserted; output documents that are no longer produced are left in the index.
When configured on a background-job task, `--fresh` applies on every run, so the
task always restarts from the first source organization. If the checkpoint
directory is not a mounted volume, a warning is logged because progress cannot
survive the container.
@@ -0,0 +1,911 @@
"""Upload UDE OrgMiner staff that were verified by the collaboration graph.
What this script does
---------------------
For every organization in the UDE organization-content index (one at a time):
1. READ the organization and its staff list from Elasticsearch (INSE)
2. VERIFY each staff member against the collaboration graph (OpenAlex)
3. BUILD one document per (organization, OpenAlex person)
4. UPLOAD the documents to ``orgminer_verified_persons_ude`` (bulk upsert)
5. CHECKPOINT the organization as done in a small JSON progress file
Everything runs sequentially: one organization at a time, one graph query at a
time.
Resumability
------------
Document IDs are deterministic, so re-running is always safe (documents are
overwritten, never duplicated). The progress file stores only:
* ``processed_org_doc_ids``: organizations that were fully uploaded.
* ``last_source_uri``: a cursor; every organization sorted before it is done.
The cursor stops advancing at the first failed organization, so failures are
retried on the next run.
Usage (from any directory):
python service/scripts/upload_orgminer_verified_persons_ude/upload_orgminer_verified_persons_ude.py
Requires the INSE and NES Elasticsearch credentials in the service's ``.env``
file or the environment. ``--dry-run`` verifies and counts without creating the
index, uploading, or touching the progress file.
"""
from __future__ import annotations
import argparse
import asyncio
import hashlib
import json
import logging
import os
import sys
import time
from collections.abc import AsyncIterator, Awaitable, Callable, Iterable
from contextlib import aclosing
from dataclasses import dataclass, field
from datetime import UTC, datetime
from pathlib import Path
from typing import Any, TypeVar
import httpx
SERVICE_DIR = Path(__file__).resolve().parents[2]
sys.path.insert(0, str(SERVICE_DIR / "src" / "main"))
from inse import config # noqa: E402
from inse.model import ESIndex # noqa: E402
from inse.orgminer import logic # noqa: E402
from inse.orgminer.institutions_helper import ( # noqa: E402
DEFAULT_INSTITUTION_ID,
normalize_org_uri,
)
T = TypeVar("T")
Hit = dict[str, Any] # one Elasticsearch search hit
HierarchyLookup = dict[str, tuple[str, list[str]]] # uri -> (name, path from root)
# =============================================================================
# Configuration
# =============================================================================
SOURCE_INDEX = ESIndex.UDE_ORGANIZATION_CONTENT.value
OUTPUT_INDEX = "orgminer_verified_persons_ude"
INSTITUTION_URL = f"https://openalex.org/{DEFAULT_INSTITUTION_ID}"
DEFAULT_PROGRESS_FILE = (
Path(__file__).resolve().parent / "orgminer_verified_persons_ude_progress.json"
)
PROGRESS_VERSION = 2
# Scanning the source index (point-in-time search, paged).
SCAN_PAGE_SIZE = 100
PIT_KEEP_ALIVE = "10m"
MAX_PIT_RESTARTS = 5
# Bulk uploads.
BULK_MAX_DOCS = 250
BULK_MAX_BYTES = 5 * 1024 * 1024
MAX_ATTEMPTS = 4
RETRYABLE_STATUS = {429, 502, 503, 504}
# Collab-graph queries per organization. Kept at 1: fully sequential.
GRAPH_QUERIES_AT_A_TIME = 1
PROGRESS_SAVE_INTERVAL_S = 5.0
PROGRESS_LOG_INTERVAL_S = 30.0
INDEX_MAPPING = {
"dynamic": "strict",
"properties": {
"name": {"type": "text", "fields": {"keyword": {"type": "keyword"}}},
"org_name": {"type": "text", "fields": {"keyword": {"type": "keyword"}}},
"org_uri": {"type": "keyword"},
"org_hierarchy_path": {"type": "keyword"},
"openalex_id": {"type": "keyword"},
# Kept verbatim in _source; staff dicts vary, so don't index them.
"staff": {"type": "object", "dynamic": False},
"staff_entries": {"type": "object", "dynamic": False},
"source_index": {"type": "keyword"},
"source_org_doc_id": {"type": "keyword"},
"verification_method": {"type": "keyword"},
"verification_evidence": {
"type": "nested",
"properties": {
"openalex_id": {"type": "keyword"},
"collaborator_openalex_id": {"type": "keyword"},
"shared_work_weight": {"type": "float"},
},
},
"verified_at": {"type": "date"},
},
}
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s %(levelname)s %(name)s %(message)s",
)
logger = logging.getLogger("upload_orgminer_verified_persons_ude")
# =============================================================================
# Generic helpers
# =============================================================================
def backoff_delay(attempt: int) -> float:
return min(2.0**attempt, 30.0)
async def retry_async(
operation: Callable[[], Awaitable[T]],
*,
description: str,
attempts: int = MAX_ATTEMPTS,
) -> T:
"""Run ``operation``; on any exception wait (exponential backoff) and retry."""
for attempt in range(1, attempts + 1):
try:
return await operation()
except Exception as exc:
if attempt == attempts:
raise
logger.warning(
"%s failed (attempt %d/%d): %s. Retrying.",
description,
attempt,
attempts,
exc,
)
await asyncio.sleep(backoff_delay(attempt))
raise AssertionError("unreachable")
def require_es_credentials() -> tuple[str, str]:
"""Check both clusters are configured; return the INSE (url, api_key)."""
if (
not config.settings.elasticsearch_url
or not config.settings.elasticsearch_api_key
):
raise SystemExit(
"NES Elasticsearch credentials are missing. Collab-graph verification "
"needs ELASTICSEARCH_URL and ELASTICSEARCH_API_KEY."
)
url = config.settings.elasticsearch_inse_url
api_key = config.settings.elasticsearch_inse_api_key
if not url or not api_key:
raise SystemExit(
"INSE Elasticsearch credentials are missing. Set "
"ELASTICSEARCH_INSE_URL and ELASTICSEARCH_INSE_API_KEY in the "
"environment or service/src/main/inse/.env."
)
return url.rstrip("/"), api_key
def make_headers(api_key: str, content_type: str = "application/json") -> dict[str, str]:
return {"Authorization": f"ApiKey {api_key}", "Content-Type": content_type}
def checkpoint_dir_is_mounted(path: Path) -> bool | None:
"""Whether the checkpoint directory is a mount point (relevant in containers).
Returns ``None`` when the platform doesn't expose mount info (e.g. macOS).
"""
mountinfo = Path("/proc/self/mountinfo")
if not mountinfo.exists():
return None
try:
directory = str(path.parent.resolve())
lines = mountinfo.read_text(encoding="utf-8").splitlines()
except OSError:
return None
return any(
len(fields) > 4 and fields[4] == directory
for fields in (line.split() for line in lines)
)
# =============================================================================
# Run statistics and progress checkpoint
# =============================================================================
@dataclass
class Stats:
scanned: int = 0
orgs_done: int = 0
orgs_failed: int = 0
person_docs: int = 0
uploaded: int = 0
doc_errors: int = 0
started: float = field(default_factory=time.monotonic)
@property
def has_errors(self) -> bool:
return bool(self.orgs_failed or self.doc_errors)
def summary(self) -> str:
return (
f"scanned={self.scanned} orgs_done={self.orgs_done} "
f"orgs_failed={self.orgs_failed} person_docs={self.person_docs} "
f"uploaded={self.uploaded} doc_errors={self.doc_errors} "
f"elapsed={time.monotonic() - self.started:.0f}s"
)
@dataclass
class Progress:
"""Checkpoint saved to a JSON file (at most every few seconds, and on exit)."""
path: Path
persist: bool # False in --dry-run: never write the file
processed_org_ids: set[str] = field(default_factory=set)
last_source_uri: str | None = None
_dirty: bool = False
_last_save: float = 0.0
@classmethod
def load(cls, path: Path, *, persist: bool) -> Progress:
progress = cls(path=path, persist=persist)
if not path.exists():
return progress
try:
state = json.loads(path.read_text(encoding="utf-8"))
except (OSError, json.JSONDecodeError) as exc:
raise SystemExit(f"Could not read progress file {path}: {exc}") from exc
if (
state.get("source_index") != SOURCE_INDEX
or state.get("output_index") != OUTPUT_INDEX
):
raise SystemExit(
f"Progress file {path} belongs to a different source/output index. "
"Choose another --progress-file or move the old file."
)
progress.processed_org_ids = set(state.get("processed_org_doc_ids", []))
progress.last_source_uri = state.get("last_source_uri")
return progress
def reset(self) -> None:
self.processed_org_ids.clear()
self.last_source_uri = None
def mark_org_done(self, org_doc_id: str) -> None:
self.processed_org_ids.add(org_doc_id)
self._dirty = True
def advance_cursor(self, uri: str | None) -> None:
if uri and uri != self.last_source_uri:
self.last_source_uri = uri
self._dirty = True
def save(self, *, force: bool = False) -> None:
if not self.persist or not self._dirty:
return
now = time.monotonic()
if not force and now - self._last_save < PROGRESS_SAVE_INTERVAL_S:
return
state = {
"version": PROGRESS_VERSION,
"source_index": SOURCE_INDEX,
"output_index": OUTPUT_INDEX,
"processed_org_doc_ids": sorted(self.processed_org_ids),
"last_source_uri": self.last_source_uri,
"updated_at": datetime.now(UTC).isoformat(),
}
self.path.parent.mkdir(parents=True, exist_ok=True)
tmp = self.path.with_suffix(self.path.suffix + ".tmp")
tmp.write_text(
json.dumps(state, ensure_ascii=False, indent=2, sort_keys=True) + "\n",
encoding="utf-8",
)
os.replace(tmp, self.path) # atomic: never leaves a half-written file
self._dirty = False
self._last_save = now
# =============================================================================
# Step 1: READ organizations from the source index
# =============================================================================
class PitExpired(Exception):
"""The point-in-time search context is gone and must be reopened."""
def _scan_query(start_uri: str | None) -> dict[str, Any]:
if not start_uri:
return {"match_all": {}}
# Organizations without a URI sort first and can never satisfy a range
# filter, so include them explicitly; already-processed IDs are skipped later.
return {
"bool": {
"should": [
{"range": {"uri.keyword": {"gte": start_uri}}},
{"bool": {"must_not": {"exists": {"field": "uri.keyword"}}}},
],
"minimum_should_match": 1,
}
}
async def _scan_pages(
client: httpx.AsyncClient,
url: str,
headers: dict[str, str],
start_uri: str | None,
) -> AsyncIterator[list[Hit]]:
"""Open a point-in-time and yield pages of hits, sorted by URI."""
response = await client.post(
f"{url}/{SOURCE_INDEX}/_pit",
params={"keep_alive": PIT_KEEP_ALIVE},
headers=headers,
)
response.raise_for_status()
pit_id = response.json()["id"]
search_after: list[Any] | None = None
try:
while True:
payload: dict[str, Any] = {
"size": SCAN_PAGE_SIZE,
"query": _scan_query(start_uri),
"pit": {"id": pit_id, "keep_alive": PIT_KEEP_ALIVE},
"sort": [
{"uri.keyword": {"order": "asc", "missing": "_first"}},
{"_shard_doc": "asc"},
],
"track_total_hits": False,
"_source": ["uri", "staff", "name", "org_name", "organization_name"],
}
if search_after is not None:
payload["search_after"] = search_after
response = await client.post(f"{url}/_search", json=payload, headers=headers)
if response.status_code == 404 and "search_context_missing" in response.text:
raise PitExpired
response.raise_for_status()
result = response.json()
hits = result.get("hits", {}).get("hits", [])
if not hits:
return
pit_id = result.get("pit_id", pit_id)
search_after = hits[-1].get("sort")
yield hits
if search_after is None or len(hits) < SCAN_PAGE_SIZE:
return
finally:
try:
await client.request(
"DELETE", f"{url}/_pit", json={"id": pit_id}, headers=headers
)
except Exception:
logger.warning("Could not close the point-in-time.", exc_info=True)
async def scan_organizations(
client: httpx.AsyncClient,
url: str,
headers: dict[str, str],
start_after_uri: str | None,
) -> AsyncIterator[Hit]:
"""Yield organizations one by one, in URI order.
If the point-in-time expires, reopen it and continue from the last URI seen.
Organizations that were already finished are skipped by the caller.
"""
resume_uri = start_after_uri
restarts = 0
while True:
try:
async with aclosing(_scan_pages(client, url, headers, resume_uri)) as pages:
async for page in pages:
restarts = 0
resume_uri = page[-1].get("_source", {}).get("uri") or resume_uri
for hit in page:
yield hit
return
except PitExpired:
restarts += 1
if restarts > MAX_PIT_RESTARTS:
raise RuntimeError("Point-in-time kept expiring; giving up.") from None
logger.warning(
"Point-in-time expired; reopening from uri=%r (restart %d/%d).",
resume_uri,
restarts,
MAX_PIT_RESTARTS,
)
# =============================================================================
# Step 3: BUILD one document per (organization, OpenAlex person)
# =============================================================================
def build_hierarchy_lookup(hierarchy: Iterable[Any]) -> HierarchyLookup:
"""Map normalized organization links to (display name, path from the root)."""
lookup: HierarchyLookup = {}
def visit(node: Any, ancestors: list[str]) -> None:
name = getattr(node, "name_de", None) or getattr(node, "name_en", None)
path = [*ancestors, name] if name else ancestors
if name:
for link in (getattr(node, "link_de", None), getattr(node, "link_en", None)):
if normalized := normalize_org_uri(link):
lookup[normalized] = (name, path)
for child in getattr(node, "children", None) or []:
visit(child, path)
for root in hierarchy:
visit(root, [])
return lookup
def organization_details(
source: dict[str, Any], hierarchy_lookup: HierarchyLookup
) -> tuple[str, list[str], str | None]:
"""Return (org name, hierarchy path, org URI), with fallbacks for the name."""
org_uri = source.get("uri")
hierarchy_name, hierarchy_path = hierarchy_lookup.get(
normalize_org_uri(org_uri) or "", ("", [])
)
org_name = (
source.get("org_name")
or source.get("organization_name")
or source.get("name")
or hierarchy_name
or org_uri
or "Unknown organization"
)
return str(org_name), hierarchy_path, org_uri
def stable_document_id(org_uri: str | None, org_doc_id: str, openalex_id: str) -> str:
"""Deterministic ID so re-uploads overwrite instead of duplicating."""
org_identity = normalize_org_uri(org_uri) or org_doc_id
return hashlib.sha256(f"{org_identity}\0{openalex_id}".encode()).hexdigest()
def _canonical(value: Any) -> str:
return json.dumps(value, sort_keys=True, ensure_ascii=False, default=str)
def make_person_documents(
source: dict[str, Any],
source_doc_id: str,
verified_entries: list[dict[str, Any]],
hierarchy_lookup: HierarchyLookup,
verified_at: str,
) -> list[tuple[str, Hit]]:
"""Turn verified staff entries into [(doc_id, document)], one per OpenAlex person.
A person may be matched by several staff entries and several collaborators,
so entries and evidence are de-duplicated per person first.
"""
org_name, hierarchy_path, org_uri = organization_details(source, hierarchy_lookup)
# openalex_id -> {canonical staff json -> staff dict}
staff_by_person: dict[str, dict[str, dict[str, Any]]] = {}
# openalex_id -> {(openalex_id, collaborator_id) -> evidence dict}
evidence_by_person: dict[str, dict[tuple[Any, Any], dict[str, Any]]] = {}
for entry in verified_entries:
staff = entry["staff"]
staff_key = _canonical(staff)
for openalex_id in entry["openalex_ids"]:
staff_by_person.setdefault(openalex_id, {}).setdefault(staff_key, staff)
seen = evidence_by_person.setdefault(openalex_id, {})
for evidence in entry["collaboration_evidence"]:
if evidence["openalex_id"] == openalex_id:
key = (evidence["openalex_id"], evidence.get("collaborator_openalex_id"))
seen.setdefault(key, evidence)
documents: list[tuple[str, Hit]] = []
for openalex_id, staff_map in staff_by_person.items():
staff_entries = list(staff_map.values())
primary_staff = staff_entries[0]
document = {
"name": primary_staff.get("name"),
"org_name": org_name,
"org_uri": org_uri,
"org_hierarchy_path": hierarchy_path,
"openalex_id": openalex_id,
"staff": primary_staff,
"staff_entries": staff_entries,
"source_index": SOURCE_INDEX,
"source_org_doc_id": source_doc_id,
"verification_method": "collab_graph",
"verification_evidence": list(evidence_by_person[openalex_id].values()),
"verified_at": verified_at,
}
doc_id = stable_document_id(org_uri, source_doc_id, openalex_id)
documents.append((doc_id, document))
return documents
# =============================================================================
# Step 4: UPLOAD documents to the output index
# =============================================================================
async def ensure_output_index(
client: httpx.AsyncClient, url: str, headers: dict[str, str]
) -> None:
"""Create the output index with its mapping if it doesn't exist yet."""
head = await client.head(f"{url}/{OUTPUT_INDEX}", headers=headers)
if head.status_code == 200:
logger.info("Output index %r already exists.", OUTPUT_INDEX)
return
if head.status_code != 404:
head.raise_for_status()
response = await client.put(
f"{url}/{OUTPUT_INDEX}", json={"mappings": INDEX_MAPPING}, headers=headers
)
if response.status_code == 400 and "resource_already_exists" in response.text:
logger.info("Output index %r was created concurrently.", OUTPUT_INDEX)
return
response.raise_for_status()
logger.info("Created output index %r.", OUTPUT_INDEX)
def _bulk_chunk(doc_id: str, document: Hit) -> str:
action = json.dumps({"index": {"_index": OUTPUT_INDEX, "_id": doc_id}})
return f"{action}\n{json.dumps(document, ensure_ascii=False)}\n"
def _split_batches(items: list[tuple[str, str]]) -> Iterable[list[tuple[str, str]]]:
"""Group (doc_id, ndjson) items by document count and payload size."""
batch: list[tuple[str, str]] = []
size = 0
for item in items:
item_size = len(item[1].encode("utf-8"))
if batch and (len(batch) >= BULK_MAX_DOCS or size + item_size > BULK_MAX_BYTES):
yield batch
batch, size = [], 0
batch.append(item)
size += item_size
if batch:
yield batch
async def _post_bulk(
client: httpx.AsyncClient,
url: str,
api_key: str,
batch: list[tuple[str, str]],
) -> dict[str, Any]:
"""Send one bulk request, retrying on network errors and retryable statuses."""
body = "".join(chunk for _, chunk in batch).encode("utf-8")
headers = make_headers(api_key, "application/x-ndjson")
async def send() -> dict[str, Any]:
response = await client.post(f"{url}/_bulk", content=body, headers=headers)
response.raise_for_status()
return response.json()
return await retry_async(send, description="Bulk request")
async def bulk_index(
client: httpx.AsyncClient,
url: str,
api_key: str,
documents: list[tuple[str, Hit]],
) -> tuple[int, list[tuple[str, str]]]:
"""Upsert documents. Return (success count, [(doc_id, error), ...]).
Items rejected with a retryable status (typically 429 under load) are sent
again with backoff. Everything else that fails is reported as a failure.
"""
pending = [(doc_id, _bulk_chunk(doc_id, doc)) for doc_id, doc in documents]
succeeded = 0
failures: dict[str, str] = {}
for attempt in range(1, MAX_ATTEMPTS + 1):
retry: list[tuple[str, str]] = []
for batch in _split_batches(pending):
result = await _post_bulk(client, url, api_key, batch)
items = result.get("items", [])
if len(items) != len(batch):
raise RuntimeError(
"Elasticsearch bulk response item count did not match the request."
)
for (doc_id, chunk), item in zip(batch, items):
outcome = item.get("index", {})
status = outcome.get("status", 0)
error = json.dumps(outcome.get("error", outcome), ensure_ascii=False)
if 200 <= status < 300:
succeeded += 1
failures.pop(doc_id, None)
elif status in RETRYABLE_STATUS:
retry.append((doc_id, chunk))
failures[doc_id] = error
else:
failures[doc_id] = error
if not retry:
break
pending = retry
if attempt < MAX_ATTEMPTS:
logger.warning(
"%d bulk items were rejected; retrying (attempt %d/%d).",
len(retry),
attempt,
MAX_ATTEMPTS,
)
await asyncio.sleep(backoff_delay(attempt))
return succeeded, sorted(failures.items())
# =============================================================================
# Processing a single organization (steps 2-4)
# =============================================================================
@dataclass
class Context:
"""Everything `process_organization` needs, bundled in one place."""
client: httpx.AsyncClient
url: str
api_key: str
hierarchy_lookup: HierarchyLookup
stats: Stats
dry_run: bool
fail_fast: bool
verified_at: str
def staff_of(source: dict[str, Any]) -> list[dict[str, Any]]:
raw = source.get("staff")
if not isinstance(raw, list):
return []
return [staff for staff in raw if isinstance(staff, dict)]
async def process_organization(hit: Hit, ctx: Context) -> bool:
"""Verify one organization's staff and upload the result.
Returns True if the organization is completely done (nothing to retry).
"""
doc_id = str(hit.get("_id") or "")
source = hit.get("_source", {})
label = source.get("uri") or doc_id
staff_list = staff_of(source)
if not staff_list:
return True # nothing to verify
logger.info("Processing organization %s (%d staff entries).", label, len(staff_list))
try:
# Step 2: verify staff against the collaboration graph.
verified_entries = await retry_async(
lambda: logic.get_verified_staff_with_collab_graph(
staff_list,
INSTITUTION_URL,
max_concurrent_queries=GRAPH_QUERIES_AT_A_TIME,
),
description=f"Collab-graph verification for {label}",
)
# Step 3: build one document per OpenAlex person.
documents = make_person_documents(
source, doc_id, verified_entries, ctx.hierarchy_lookup, ctx.verified_at
)
ctx.stats.person_docs += len(documents)
if ctx.dry_run:
logger.info(
"DRY RUN org=%s verified_staff=%d person_org_docs=%d",
label,
len(verified_entries),
len(documents),
)
return True
# Step 4: upload.
uploaded, failures = await bulk_index(ctx.client, ctx.url, ctx.api_key, documents)
ctx.stats.uploaded += uploaded
for failed_id, error in failures:
ctx.stats.doc_errors += 1
logger.error("Failed to index document %s (org %s): %s", failed_id, label, error)
return not failures
except Exception:
logger.exception("Failed processing organization %s (_id=%s).", label, doc_id)
if ctx.fail_fast:
raise
return False
# =============================================================================
# Main flow
# =============================================================================
def reset_checkpoint_files(progress_file: Path) -> None:
"""Implements --fresh: delete the progress file (and a leftover .tmp file)."""
tmp_file = progress_file.with_suffix(progress_file.suffix + ".tmp")
existed = progress_file.exists()
removed = []
for path in (progress_file, tmp_file):
try:
path.unlink()
removed.append(str(path))
except FileNotFoundError:
pass
logger.info(
"--fresh: removed %s. Output index %r is kept and will be updated by upserts.",
removed,
OUTPUT_INDEX,
)
if existed:
logger.warning(
"--fresh discarded the existing checkpoint. If a saved job command "
"contains --fresh, it restarts from the first organization on every "
"run; remove the flag to resume instead."
)
def prepare_progress(args: argparse.Namespace) -> Progress:
"""Load (or reset) the checkpoint according to the CLI flags."""
if args.fresh:
reset_checkpoint_files(args.progress_file)
progress = Progress.load(args.progress_file, persist=not args.dry_run)
if args.ignore_progress:
progress.reset()
logger.info(
"Checkpoint %s: %d finished organizations, resume cursor=%r.",
args.progress_file,
len(progress.processed_org_ids),
progress.last_source_uri,
)
if not args.dry_run and checkpoint_dir_is_mounted(args.progress_file) is False:
logger.warning(
"Checkpoint directory %s is not a mounted volume, so progress is lost "
"as soon as the container is removed. Set the job's persistent directory "
"to %s.",
args.progress_file.parent,
args.progress_file.parent,
)
return progress
async def run(args: argparse.Namespace) -> int:
# Setup ---------------------------------------------------------------
url, api_key = require_es_credentials() # fail fast, before slow work
headers = make_headers(api_key)
progress = prepare_progress(args)
hierarchy = await logic.get_hierarchy(INSTITUTION_URL)
hierarchy_lookup = build_hierarchy_lookup(hierarchy)
logger.info("Loaded %d hierarchy URL mappings for UDE.", len(hierarchy_lookup))
stats = Stats()
organizations_handled = 0 # for --limit
cursor_blocked = False # set after the first failure; cursor stops moving
last_log = time.monotonic()
async with httpx.AsyncClient(timeout=httpx.Timeout(90.0)) as client:
if not args.dry_run:
await ensure_output_index(client, url, headers)
ctx = Context(
client=client,
url=url,
api_key=api_key,
hierarchy_lookup=hierarchy_lookup,
stats=stats,
dry_run=args.dry_run,
fail_fast=args.fail_fast,
verified_at=datetime.now(UTC).isoformat(),
)
# Main loop: one organization at a time -----------------------------
try:
async with aclosing(
scan_organizations(client, url, headers, progress.last_source_uri)
) as organizations:
async for hit in organizations:
stats.scanned += 1
org_doc_id = str(hit.get("_id") or "")
org_uri = hit.get("_source", {}).get("uri")
# Already uploaded in an earlier run.
if org_doc_id in progress.processed_org_ids:
if not cursor_blocked:
progress.advance_cursor(org_uri)
continue
if args.limit is not None and organizations_handled >= args.limit:
logger.info("Reached --limit=%d.", args.limit)
break
organizations_handled += 1
if await process_organization(hit, ctx):
stats.orgs_done += 1
if not args.dry_run:
progress.mark_org_done(org_doc_id)
if not cursor_blocked:
progress.advance_cursor(org_uri)
else:
stats.orgs_failed += 1
cursor_blocked = True # retry this one on the next run
progress.save()
if time.monotonic() - last_log >= PROGRESS_LOG_INTERVAL_S:
logger.info("Progress: %s", stats.summary())
last_log = time.monotonic()
finally:
progress.save(force=True)
logger.info("Finished: %s progress_file=%s", stats.summary(), args.progress_file)
return 1 if stats.has_errors else 0
# =============================================================================
# Command line
# =============================================================================
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(
description="Upload UDE OrgMiner persons verified by the collaboration graph."
)
parser.add_argument(
"--progress-file",
type=Path,
default=DEFAULT_PROGRESS_FILE,
help=f"JSON checkpoint file (default: {DEFAULT_PROGRESS_FILE})",
)
parser.add_argument(
"--limit",
type=int,
default=None,
help="Process at most this many not-yet-completed organizations.",
)
parser.add_argument(
"--dry-run",
action="store_true",
help=(
"Verify and count results without creating the index, uploading, "
"or writing progress. Still reads existing progress unless "
"--ignore-progress is given."
),
)
parser.add_argument(
"--ignore-progress",
action="store_true",
help="Start from scratch, ignoring any existing progress file contents.",
)
parser.add_argument(
"--fresh",
action="store_true",
help=(
"Delete the selected JSON progress checkpoint and start from the "
"first source organization. Existing output-index documents are kept."
),
)
parser.add_argument(
"--fail-fast",
action="store_true",
help="Stop at the first organization-level error instead of continuing.",
)
args = parser.parse_args()
if args.limit is not None and args.limit < 1:
parser.error("--limit must be at least 1.")
return args
if __name__ == "__main__":
raise SystemExit(asyncio.run(run(parse_args())))
@@ -28,6 +28,9 @@ settings = config.get_settings()
RUN_STATE_LOCK = RLock()
ORGMINER_DEFAULT_PERSISTENT_DIR = "/app/orgminer_pipeline/runs"
ORGMINER_VERIFIED_PERSONS_UDE_REPOSITORY = (
"inse/jobs/orgminer-verified-persons-ude"
)
_client: docker.DockerClient | None = None
@@ -131,6 +134,22 @@ def is_registry_image(image: str | None) -> bool:
return bool(image) and image.split("/", 1)[0] == registry_host()
def uses_nes_credentials(image: str | None) -> bool:
"""Only the OrgMiner verified-person job needs direct NES access."""
if not image or not is_registry_image(image):
return False
registry, _, image_path = image.partition("/")
image_path = image_path.split("@", 1)[0]
path_parts = image_path.rsplit("/", 1)
repository_name = path_parts[-1].split(":", 1)[0]
repository = "/".join([*path_parts[:-1], repository_name])
return (
registry == registry_host()
and repository == ORGMINER_VERIFIED_PERSONS_UDE_REPOSITORY
)
def container_name(definition: JobDefinition, run: JobRun) -> str:
slug = definition.name.lower()
slug = (
@@ -198,7 +217,20 @@ def is_orgminer(definition: JobDefinition) -> bool:
def resolve_environment(definition: JobDefinition) -> dict[str, str]:
base = job_environment() if is_registry_image(resolve_image(definition)) else {}
image = resolve_image(definition)
base = job_environment() if is_registry_image(image) else {}
if uses_nes_credentials(image):
nes_environment = {
"ELASTICSEARCH_URL": settings.elasticsearch_url,
"ELASTICSEARCH_API_KEY": settings.elasticsearch_api_key,
}
base.update(
{
key: value
for key, value in nes_environment.items()
if value
}
)
return {**base, **(definition.env or {})}
@@ -399,7 +431,16 @@ def _reconcile_runs(session: Session) -> None:
container.reload()
if container.status in ("exited", "dead"):
exit_code = container.attrs["State"]["ExitCode"]
state = container.attrs.get("State", {})
exit_code = state["ExitCode"]
logs = container.logs().decode("utf-8", errors="replace")
if state.get("OOMKilled"):
logs = append_system_log(
logs,
"The container ran out of memory and was killed by the kernel "
f"(exit {exit_code}). No Python traceback is written for this; "
"the log above simply stops.",
)
new_status = (
JobRunStatus.SUCCEEDED if exit_code == 0 else JobRunStatus.FAILED
)
@@ -408,7 +449,7 @@ def _reconcile_runs(session: Session) -> None:
run,
new_status=new_status,
exit_code=exit_code,
logs=container.logs().decode("utf-8", errors="replace"),
logs=logs,
)
if applied:
session.commit()
@@ -0,0 +1,49 @@
from types import SimpleNamespace
from . import runner
from .model import JobDefinition
def _settings():
return SimpleNamespace(
background_jobs_image="docker.nes.uni-due.de/inse/background-jobs:latest",
elasticsearch_url="https://nes.example/elastic",
elasticsearch_api_key="nes-api-key",
elasticsearch_inse_url="https://inse.example/elastic",
elasticsearch_inse_api_key="inse-api-key",
llm_api_url="https://llm.example",
llm_api_key="llm-api-key",
llm_model="test-model",
sentence_transformers_model_name="test-embedding-model",
)
def _job(image: str) -> JobDefinition:
return JobDefinition(name="test", image=image)
def test_nes_credentials_are_injected_only_for_verified_person_image(monkeypatch):
monkeypatch.setattr(runner, "settings", _settings())
verified_image = (
"docker.nes.uni-due.de/inse/jobs/orgminer-verified-persons-ude:v1"
)
regular_image = "docker.nes.uni-due.de/inse/jobs/news-topics:latest"
verified_environment = runner.resolve_environment(_job(verified_image))
regular_environment = runner.resolve_environment(_job(regular_image))
assert verified_environment["ELASTICSEARCH_URL"] == "https://nes.example/elastic"
assert verified_environment["ELASTICSEARCH_API_KEY"] == "nes-api-key"
assert regular_environment["ELASTICSEARCH_INSE_API_KEY"] == "inse-api-key"
assert "ELASTICSEARCH_URL" not in regular_environment
assert "ELASTICSEARCH_API_KEY" not in regular_environment
def test_nes_credentials_are_not_injected_for_non_registry_copy(monkeypatch):
monkeypatch.setattr(runner, "settings", _settings())
local_image = "localhost/inse/jobs/orgminer-verified-persons-ude:dev"
environment = runner.resolve_environment(_job(local_image))
assert "ELASTICSEARCH_URL" not in environment
assert "ELASTICSEARCH_API_KEY" not in environment
@@ -12,10 +12,16 @@ from .model import JobRun, JobRunStatus, JobTriggeredBy
class FakeContainer:
def __init__(
self, *, status: str, exit_code: int, logs: str, stop_error=None
self,
*,
status: str,
exit_code: int,
logs: str,
stop_error=None,
oom_killed: bool = False,
):
self.status = status
self.attrs = {"State": {"ExitCode": exit_code}}
self.attrs = {"State": {"ExitCode": exit_code, "OOMKilled": oom_killed}}
self._logs = logs
self.stop_calls = 0
self.removed = False
@@ -126,6 +132,26 @@ def test_reconciler_keeps_running_container_after_backend_restart(
assert container.removed is False
def test_reconciler_annotates_container_killed_by_oom(session, monkeypatch):
run = _run(session)
container = FakeContainer(
status="exited",
exit_code=137,
logs="last org: https://www.uni-due.de/zmb",
oom_killed=True,
)
_use_container(monkeypatch, container)
runner.reconcile_runs(session)
session.refresh(run)
assert run.status == JobRunStatus.FAILED
assert run.exit_code == 137
assert "last org: https://www.uni-due.de/zmb" in run.logs
assert "ran out of memory" in run.logs
assert container.removed is True
def test_failed_docker_stop_leaves_database_run_running(session, monkeypatch):
run = _run(session)
container = FakeContainer(
@@ -122,10 +122,10 @@ async def search_founder_candidates(
in_population: Annotated[
bool | None,
Query(
description="Restrict to researchers the model can score (default). "
"Pass false for the unscored, or leave unset for everyone."
description="Restrict to researchers the model can score. "
"Pass true for the scored, false for the unscored, or leave unset for everyone."
),
] = True,
] = None,
min_external_percentile: Annotated[
float | None,
Query(description="Minimum founder percentile (0-100, vs the external reference cohort).", ge=0, le=100),
@@ -39,6 +39,21 @@ def strip_openalex_prefix(institution_id: str) -> str:
return institution_id.rsplit("/", 1)[-1]
def normalize_org_uri(uri: str | None) -> str | None:
"""Normalize an organization URL so hierarchy links compare reliably.
Trims whitespace, drops a trailing slash and the common ``/index`` suffix,
so ``https://www.example.org/x/``, ``https://www.example.org/x/index`` and
``https://www.example.org/x`` all map to the same value.
"""
if not uri:
return None
normalized = uri.strip().rstrip("/")
if normalized.endswith("/index"):
normalized = normalized[: -len("/index")].rstrip("/")
return normalized or None
def full_institution_url(institution_id: str) -> str:
"""Normalize any institution id form to the full OpenAlex URL form."""
return f"https://openalex.org/{strip_openalex_prefix(institution_id)}"
+185 -56
View File
@@ -2,11 +2,14 @@
from collections import defaultdict
import asyncio
from typing import Any, Callable, Optional
from typing import Any, Awaitable, Callable, Optional
from inse.integrations.elasticsearch import search
from inse.utils import normalize_name
from inse.model import ESCluster, ESIndex
from inse.authors.v2.service import _build_collaboration_graph
from inse.authors.v2.service import (
_build_collaboration_graph,
_build_collaboration_graph_query,
)
from inse.auth.model import Account, Organization
from inse import config
from .model import (
@@ -134,6 +137,180 @@ async def get_person_collaborator_weights(
return weights
async def get_collaborator_weights_for_targets(
author_id: str,
institution_id: str,
target_ids: set[str] | frozenset[str] | list[str],
) -> dict[str, float]:
"""Return ``{collaborator_id: shared_work_weight}`` only for ``target_ids``.
The collaboration-graph builder expands every pair of authors on every work,
which explodes for works with hundreds or thousands of authors. Verification
only needs the weights towards the other staff candidates in the same
organization, so this asks Elasticsearch for those counts directly.
"""
targets = sorted(set(target_ids) - {author_id})
if not targets:
return {}
query = _build_collaboration_graph_query(
raw_oa_author_id=author_id,
institution_ids=[institution_id],
)
body = {
"size": 0,
"query": query,
"aggs": {
"collaborators": {
"nested": {"path": "authorships"},
"aggs": {
"targets": {
"terms": {
"field": "authorships.author.id",
"include": targets,
"size": len(targets),
}
}
},
}
},
}
results = await search(
body=body,
index=ESIndex.OPENALEX_WORKS_WILDCARD,
cluster=ESCluster.NES,
)
buckets = (
results.get("aggregations", {})
.get("collaborators", {})
.get("targets", {})
.get("buckets", [])
)
return {
bucket["key"]: float(bucket["doc_count"])
for bucket in buckets
if bucket.get("key")
}
async def get_verified_staff_with_collab_graph(
staff_list: list[dict[str, Any]],
institution_id: str = DEFAULT_INSTITUTION_ID,
max_concurrent_queries: int | None = None,
) -> list[dict[str, Any]]:
"""Return verified staff entries with the OpenAlex IDs and edges proving verification.
A staff entry is verified when at least one of its OpenAlex author candidates
has a collaboration edge to a candidate belonging to a different staff entry
in the same organization.
Only collaborator weights towards the organization's other staff candidates
are fetched, so verification memory does not grow with the size of an
author's full co-author network.
``max_concurrent_queries`` bounds the OpenAlex candidate and graph searches.
It is useful for batch jobs processing organizations with large staff lists.
"""
if max_concurrent_queries is not None and max_concurrent_queries < 1:
raise ValueError("max_concurrent_queries must be at least 1.")
query_semaphore = (
asyncio.Semaphore(max_concurrent_queries)
if max_concurrent_queries is not None
else None
)
async def _run_query(operation: Callable[[], Awaitable[Any]]) -> Any:
if query_semaphore is None:
return await operation()
async with query_semaphore:
return await operation()
async def _resolve_staff(staff: dict[str, Any]) -> set[str]:
name = staff.get("name")
if not name:
return set()
candidate_ids = await _run_query(
lambda: resolve_author_candidates(
normalize_name(name),
institution_id,
)
)
return set(candidate_ids)
async def _get_neighbor_weights(
author_id: str, target_ids: set[str]
) -> dict[str, float]:
return await _run_query(
lambda: get_collaborator_weights_for_targets(
author_id,
institution_id,
target_ids,
)
)
candidate_sets = await asyncio.gather(
*(_resolve_staff(staff) for staff in staff_list)
)
async def _verify_staff(
staff_index: int, own_ids: set[str]
) -> dict[str, Any] | None:
if not own_ids:
return None
other_ids = (
set().union(
*(
candidate_ids
for index, candidate_ids in enumerate(candidate_sets)
if index != staff_index
)
)
- own_ids
)
if not other_ids:
return None
# ``other_ids`` only contains OpenAlex candidates of the other staff
# entries in this organization, and every candidate set was resolved
# against ``institution_id``. Collaborator weights are therefore
# restricted to same-university colleagues; no external co-author can
# contribute evidence.
author_ids = sorted(own_ids)
neighbor_weights = await asyncio.gather(
*(_get_neighbor_weights(author_id, other_ids) for author_id in author_ids)
)
evidence = [
{
"openalex_id": author_id,
"collaborator_openalex_id": collaborator_id,
"shared_work_weight": weights[collaborator_id],
}
for author_id, weights in zip(author_ids, neighbor_weights)
for collaborator_id in sorted(weights.keys() & other_ids)
]
if not evidence:
return None
return {
"staff_index": staff_index,
"staff": staff_list[staff_index],
"openalex_ids": sorted({item["openalex_id"] for item in evidence}),
"collaboration_evidence": evidence,
}
checked_entries = await asyncio.gather(
*(
_verify_staff(staff_index, candidate_ids)
for staff_index, candidate_ids in enumerate(candidate_sets)
)
)
return [entry for entry in checked_entries if entry is not None]
async def find_org_for_person(
name: str,
institution_id: str = None,
@@ -567,62 +744,14 @@ async def get_orgminer_content_verified_by_collab_graph(
orgminer_content = hits[0]["_source"]
staff_list = orgminer_content.get("staff") or []
async def _resolve_staff(staff: dict) -> set[str]:
name = staff.get("name")
if not name:
return set()
candidate_ids = await resolve_author_candidates(
normalize_name(name),
institution_id,
)
return set(candidate_ids)
async def _get_neighbor_ids(author_id: str) -> set[str]:
collaborator_weights = await get_person_collaborator_weights(
author_id,
institution_id,
)
return set(collaborator_weights.keys())
candidate_sets = await asyncio.gather(
*(_resolve_staff(staff) for staff in staff_list)
)
async def _is_verified(staff_index: int) -> bool:
own_ids = candidate_sets[staff_index]
if not own_ids:
return False
# Candidates belonging to other staff members only.
other_ids = (
set().union(
*(
candidate_ids
for index, candidate_ids in enumerate(candidate_sets)
if index != staff_index
)
)
- own_ids
)
if not other_ids:
return False
neighbor_sets = await asyncio.gather(
*(_get_neighbor_ids(author_id) for author_id in own_ids)
)
return any(neighbor_ids & other_ids for neighbor_ids in neighbor_sets)
verified_flags = await asyncio.gather(
*(_is_verified(index) for index in range(len(staff_list)))
verified_entries = await get_verified_staff_with_collab_graph(
staff_list,
institution_id,
)
orgminer_content["verified_staff"] = [
staff
for staff, is_verified in zip(staff_list, verified_flags)
if is_verified
entry["staff"]
for entry in verified_entries
]
return OrgminerContent.from_elastic_hit(orgminer_content)
@@ -704,4 +833,4 @@ async def get_classified_pages(org_url: str,institution_id: str = DEFAULT_INSTIT
return ClassifiedPageResponse(
total=response["hits"]["total"]["value"],
pages=classified_pages
)
)
@@ -0,0 +1,32 @@
from inse.orgminer.institutions_helper import (
normalize_org_uri,
strip_openalex_prefix,
)
def test_normalize_org_uri_matches_equivalent_hierarchy_links():
assert (
normalize_org_uri(" https://www.uni-due.de/zmb/ ")
== "https://www.uni-due.de/zmb"
)
assert (
normalize_org_uri("https://www.uni-due.de/zmb/index")
== "https://www.uni-due.de/zmb"
)
assert (
normalize_org_uri("https://www.uni-due.de/zmb/index/")
== "https://www.uni-due.de/zmb"
)
def test_normalize_org_uri_returns_none_for_missing_values():
assert normalize_org_uri(None) is None
assert normalize_org_uri(" ") is None
def test_strip_openalex_prefix_accepts_raw_and_full_author_ids():
assert strip_openalex_prefix("A5018971503") == "A5018971503"
assert (
strip_openalex_prefix("https://openalex.org/A5018971503")
== "A5018971503"
)
@@ -1,8 +1,170 @@
import asyncio
import json
from inse.orgminer import logic
def test_get_verified_staff_with_collab_graph_returns_matching_ids_and_edges(
monkeypatch,
):
staff = [
{"name": "Person One", "email": "one@example.org"},
{"name": "Person Two"},
]
resolved = {
"person one": ["https://openalex.org/A1", "https://openalex.org/A2"],
"person two": ["https://openalex.org/B1"],
}
neighbors = {
"https://openalex.org/A1": {"https://openalex.org/B1": 2.5},
"https://openalex.org/A2": {},
"https://openalex.org/B1": {},
}
async def resolve_author_candidates(name, institution_id):
return resolved[name]
async def get_collaborator_weights_for_targets(
author_id, institution_id, target_ids
):
return {
collaborator_id: weight
for collaborator_id, weight in neighbors[author_id].items()
if collaborator_id in target_ids
}
monkeypatch.setattr(logic, "resolve_author_candidates", resolve_author_candidates)
monkeypatch.setattr(
logic, "get_collaborator_weights_for_targets", get_collaborator_weights_for_targets
)
result = asyncio.run(
logic.get_verified_staff_with_collab_graph(staff, "I123")
)
assert result == [
{
"staff_index": 0,
"staff": staff[0],
"openalex_ids": ["https://openalex.org/A1"],
"collaboration_evidence": [
{
"openalex_id": "https://openalex.org/A1",
"collaborator_openalex_id": "https://openalex.org/B1",
"shared_work_weight": 2.5,
}
],
}
]
def test_get_verified_staff_with_collab_graph_respects_query_concurrency(
monkeypatch,
):
staff = [{"name": "Person One"}, {"name": "Person Two"}]
active_queries = 0
peak_queries = 0
async def tracked(result):
nonlocal active_queries, peak_queries
active_queries += 1
peak_queries = max(peak_queries, active_queries)
try:
await asyncio.sleep(0.001)
return result
finally:
active_queries -= 1
async def resolve_author_candidates(name, institution_id):
author_id = "https://openalex.org/A1" if name == "person one" else "https://openalex.org/A2"
return await tracked([author_id])
async def get_collaborator_weights_for_targets(
author_id, institution_id, target_ids
):
neighbor_id = (
"https://openalex.org/A2"
if author_id == "https://openalex.org/A1"
else "https://openalex.org/A1"
)
return await tracked(
{neighbor_id: 1.0} if neighbor_id in target_ids else {}
)
monkeypatch.setattr(logic, "resolve_author_candidates", resolve_author_candidates)
monkeypatch.setattr(
logic, "get_collaborator_weights_for_targets", get_collaborator_weights_for_targets
)
result = asyncio.run(
logic.get_verified_staff_with_collab_graph(
staff,
"I123",
max_concurrent_queries=1,
)
)
assert len(result) == 2
assert peak_queries == 1
def test_get_collaborator_weights_for_targets_uses_bounded_aggregation(
monkeypatch,
):
captured = {}
async def fake_search(**kwargs):
captured.update(kwargs)
return {
"aggregations": {
"collaborators": {
"targets": {
"buckets": [
{"key": "https://openalex.org/B1", "doc_count": 7},
]
}
}
}
}
monkeypatch.setattr(logic, "search", fake_search)
result = asyncio.run(
logic.get_collaborator_weights_for_targets(
"https://openalex.org/A1",
"I123",
{"https://openalex.org/B1", "https://openalex.org/A1"},
)
)
assert result == {"https://openalex.org/B1": 7.0}
body = captured["body"]
assert body["size"] == 0
nested = body["aggs"]["collaborators"]
assert nested["nested"] == {"path": "authorships"}
assert nested["aggs"]["targets"]["terms"]["include"] == [
"https://openalex.org/B1"
]
assert "query" in body
def test_get_collaborator_weights_for_targets_without_targets_skips_request(
monkeypatch,
):
async def fail_search(**kwargs):
raise AssertionError("search must not be called")
monkeypatch.setattr(logic, "search", fail_search)
result = asyncio.run(
logic.get_collaborator_weights_for_targets(
"https://openalex.org/A1", "I123", set()
)
)
assert result == {}
def test_update_hierarchy_removes_deleted_nodes_and_edit_markers(tmp_path, monkeypatch):
monkeypatch.setattr(logic, "HIERARCHIES_DIR", tmp_path)
+78 -1
View File
@@ -15,14 +15,20 @@ from inse.exceptions import (
NotFoundException,
)
from inse.integrations import elasticsearch
from inse.model import ESIndex
from inse.model import ESCluster, ESIndex
from inse.models.openalex.author import Author
from inse.models.openalex.authors_list_response import AuthorsListResponse
from inse.models.openalex.meta import Meta
from inse.orgminer.institutions_helper import (
DEFAULT_INSTITUTION_ID,
normalize_org_uri,
strip_openalex_prefix,
)
from inse.persons.model import (
CareerMetrics,
CustomAuthor,
CustomAuthorsListResponse,
VerifiedOrganization,
)
from inse.persons.query_builder import build_authors_search_rescored
from inse.works.logic import enrich_topic_descriptions
@@ -32,6 +38,77 @@ from .. import config, util
logger = logging.getLogger(__name__)
INDEX_NAME = "openalex-authors"
UDE_INSTITUTION_ID = "https://openalex.org/I62318514" # Universität Duisburg-Essen
VERIFIED_PERSONS_INDEX = "orgminer_verified_persons_ude"
VERIFIED_PERSONS_INSTITUTION_ID = DEFAULT_INSTITUTION_ID
VERIFIED_PERSON_FIELDS = [
"openalex_id",
"org_name",
"org_uri",
"org_hierarchy_path",
"verified_at",
]
async def get_verified_organizations(author_id: str) -> list[VerifiedOrganization]:
"""Return organizations where ``author_id`` is a verified staff member.
Reads the OrgMiner verified-persons index on the INSE cluster. Documents are
keyed by the person's OpenAlex id field (both raw and full-URL forms are
accepted), so the lookup does not depend on the index's ``_id`` scheme.
An unavailable index must not break the person page, so failures are logged
and reported as "not verified".
"""
short_id = strip_openalex_prefix(author_id.strip().rstrip("/"))
if not short_id:
return []
query = {
"_source": VERIFIED_PERSON_FIELDS,
"size": 50,
"query": {
"terms": {
"openalex_id": [short_id, f"https://openalex.org/{short_id}"]
}
},
"sort": [
{"verified_at": {"order": "desc", "missing": "_last"}},
{"org_name.keyword": {"order": "asc", "missing": "_last"}},
],
}
try:
data = await elasticsearch.search(
body=query, index=VERIFIED_PERSONS_INDEX, cluster=ESCluster.INSE
)
except Exception:
logger.exception(
"Verified-organization lookup failed for author %r.", author_id
)
return []
organizations: dict[str, VerifiedOrganization] = {}
for hit in data.get("hits", {}).get("hits", []):
source = hit.get("_source") or {}
org_uri = normalize_org_uri(source.get("org_uri"))
org_name = (source.get("org_name") or "").strip()
key = org_uri or org_name.casefold()
if not key:
continue
# Old sha256-ID and new person-level documents can coexist until the
# index is rebuilt. The newest document wins because of the sort above.
organizations.setdefault(
key,
VerifiedOrganization(
org_name=org_name or org_uri or "Unbekannte Organisation",
org_uri=org_uri,
org_hierarchy_path=source.get("org_hierarchy_path") or [],
verified_at=source.get("verified_at"),
),
)
return list(organizations.values())
async def find_ude_author_by_name(display_name: str) -> dict | None:
+27
View File
@@ -4,6 +4,8 @@ Data models for persons / authors.
"""
from datetime import datetime
from pydantic import BaseModel, Field
from inse.models.openalex.author import Author
@@ -71,6 +73,31 @@ class PersonBio(BaseModel):
bio: str = Field(description="The generated biography.")
class VerifiedOrganization(BaseModel):
org_name: str = Field(description="Display name of the verified organization.")
org_uri: str | None = Field(
default=None, description="Organization URL, normalized for hierarchy matching."
)
org_hierarchy_path: list[str] = Field(
default_factory=list,
description="Path from the hierarchy root to the organization node.",
)
verified_at: datetime | None = Field(
default=None, description="When the organization membership was verified."
)
class VerifiedOrganizationsResponse(BaseModel):
institution_id: str | None = Field(
default=None,
description="OpenAlex institution ID that the verified memberships belong to.",
)
organizations: list[VerifiedOrganization] = Field(
default_factory=list,
description="Organizations where the person has verified staff membership.",
)
class PersonFilters(BaseModel):
institution: str | None = None
cited_by_count: int | None = None
+19
View File
@@ -75,6 +75,25 @@ async def get_person_by_id(
return await logic.get_person_by_id(author_id=id, include=include)
@router.get(
"/person/{id}/verified-organizations",
operation_id="getVerifiedOrganizations",
response_model=model.VerifiedOrganizationsResponse,
summary="Returns the organizations where a person is a verified staff member.",
tags=["Persons"],
)
async def get_verified_organizations(
id: Annotated[
str, Path(description="OpenAlex author ID", example=["A5093075883"])
],
):
organizations = await logic.get_verified_organizations(author_id=id)
return model.VerifiedOrganizationsResponse(
institution_id=logic.VERIFIED_PERSONS_INSTITUTION_ID,
organizations=organizations,
)
@router.get(
"/persons/searchByName",
operation_id="searchPersonsByName",
@@ -0,0 +1,119 @@
import asyncio
from inse.model import ESCluster
from inse.persons import logic, service
def _hit(
*,
org_name: str,
org_uri: str | None,
verified_at: str | None = "2026-01-02T03:04:05Z",
) -> dict:
return {
"_source": {
"openalex_id": "https://openalex.org/A5018971503",
"org_name": org_name,
"org_uri": org_uri,
"org_hierarchy_path": ["Fakultät", org_name],
"verified_at": verified_at,
}
}
def test_get_verified_organizations_uses_person_id_field_and_deduplicates(monkeypatch):
calls: list[dict] = []
async def fake_search(**kwargs):
calls.append(kwargs)
return {
"hits": {
"hits": [
_hit(
org_name="Zentrum für Mikroskopie",
org_uri="https://www.uni-due.de/zmb/",
),
# Same organization from an older sha256-ID document.
_hit(
org_name="Zentrum für Mikroskopie",
org_uri="https://www.uni-due.de/zmb/index",
),
_hit(org_name="Institut für Physik", org_uri=None),
_hit(org_name="Institut für Physik", org_uri=None),
]
}
}
monkeypatch.setattr(logic.elasticsearch, "search", fake_search)
result = asyncio.run(
logic.get_verified_organizations("https://openalex.org/A5018971503")
)
assert len(calls) == 1
assert calls[0]["index"] == logic.VERIFIED_PERSONS_INDEX
assert calls[0]["cluster"] == ESCluster.INSE
assert calls[0]["body"]["query"]["terms"]["openalex_id"] == [
"A5018971503",
"https://openalex.org/A5018971503",
]
assert [organization.org_name for organization in result] == [
"Zentrum für Mikroskopie",
"Institut für Physik",
]
assert result[0].org_uri == "https://www.uni-due.de/zmb"
assert result[0].org_hierarchy_path == [
"Fakultät",
"Zentrum für Mikroskopie",
]
assert result[0].verified_at is not None
def test_get_verified_organizations_accepts_raw_author_id(monkeypatch):
calls: list[dict] = []
async def fake_search(**kwargs):
calls.append(kwargs)
return {"hits": {"hits": []}}
monkeypatch.setattr(logic.elasticsearch, "search", fake_search)
assert asyncio.run(logic.get_verified_organizations(" A5018971503/ ")) == []
assert calls[0]["body"]["query"]["terms"]["openalex_id"] == [
"A5018971503",
"https://openalex.org/A5018971503",
]
def test_get_verified_organizations_returns_empty_on_search_failure(monkeypatch):
async def failing_search(**kwargs):
raise RuntimeError("INSE is unavailable")
monkeypatch.setattr(logic.elasticsearch, "search", failing_search)
assert asyncio.run(logic.get_verified_organizations("A5018971503")) == []
def test_get_verified_organizations_skips_search_without_author_id(monkeypatch):
async def unexpected_search(**kwargs):
raise AssertionError("search must not be called without an author id")
monkeypatch.setattr(logic.elasticsearch, "search", unexpected_search)
assert asyncio.run(logic.get_verified_organizations(" ")) == []
def test_service_response_includes_verified_data_institution(monkeypatch):
async def fake_get_verified_organizations(author_id: str):
return []
monkeypatch.setattr(
logic, "get_verified_organizations", fake_get_verified_organizations
)
response = asyncio.run(
service.get_verified_organizations(id="A5018971503")
)
assert response.institution_id == logic.VERIFIED_PERSONS_INSTITUTION_ID
assert response.organizations == []
@@ -356,6 +356,8 @@ model/userRole.ts
model/validationError.ts
model/validationErrorLocInner.ts
model/value.ts
model/verifiedOrganization.ts
model/verifiedOrganizationsResponse.ts
model/work.ts
model/workBiblio.ts
model/workCitationNormalizedPercentile.ts
+57
View File
@@ -24,6 +24,8 @@ import { CustomAuthorsListResponse } from '../model/customAuthorsListResponse';
import { HTTPValidationError } from '../model/hTTPValidationError';
// @ts-ignore
import { PersonBio } from '../model/personBio';
// @ts-ignore
import { VerifiedOrganizationsResponse } from '../model/verifiedOrganizationsResponse';
// @ts-ignore
import { BASE_PATH, COLLECTION_FORMATS } from '../variables';
@@ -747,4 +749,59 @@ export class PersonsService extends BaseService {
);
}
/**
* Returns the organizations where a person is a verified staff member.
* @endpoint get /api/inse-service/person/{id}/verified-organizations
* @param id OpenAlex author ID
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
* @param reportProgress flag to report request and response progress.
*/
public getVerifiedOrganizations(id: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<VerifiedOrganizationsResponse>;
public getVerifiedOrganizations(id: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<VerifiedOrganizationsResponse>>;
public getVerifiedOrganizations(id: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<VerifiedOrganizationsResponse>>;
public getVerifiedOrganizations(id: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
if (id === null || id === undefined) {
throw new Error('Required parameter id was null or undefined when calling getVerifiedOrganizations.');
}
let localVarHeaders = this.defaultHeaders;
const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([
'application/json'
]);
if (localVarHttpHeaderAcceptSelected !== undefined) {
localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected);
}
const localVarHttpContext: HttpContext = options?.context ?? new HttpContext();
const localVarTransferCache: boolean = options?.transferCache ?? true;
let responseType_: 'text' | 'json' | 'blob' = 'json';
if (localVarHttpHeaderAcceptSelected) {
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
responseType_ = 'text';
} else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) {
responseType_ = 'json';
} else {
responseType_ = 'blob';
}
}
let localVarPath = `/api/inse-service/person/${this.configuration.encodeParam({name: "id", value: id, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: undefined})}/verified-organizations`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<VerifiedOrganizationsResponse>('get', `${basePath}${localVarPath}`,
{
context: localVarHttpContext,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
reportProgress: reportProgress
}
);
}
}
+2
View File
@@ -319,6 +319,8 @@ export * from './userRole';
export * from './validationError';
export * from './validationErrorLocInner';
export * from './value';
export * from './verifiedOrganization';
export * from './verifiedOrganizationsResponse';
export * from './work';
export * from './workBiblio';
export * from './workCitationNormalizedPercentile';
@@ -0,0 +1,24 @@
/**
* Innovation Search Engine API
*
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
export interface VerifiedOrganization {
/**
* Display name of the verified organization.
*/
org_name: string;
org_uri?: string | null;
/**
* Path from the hierarchy root to the organization node.
*/
org_hierarchy_path?: Array<string>;
verified_at?: string | null;
}
@@ -0,0 +1,23 @@
/**
* Innovation Search Engine API
*
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
import { VerifiedOrganization } from './verifiedOrganization';
export interface VerifiedOrganizationsResponse {
/**
* OpenAlex institution ID that the verified memberships belong to.
*/
institution_id?: string | null;
/**
* Organizations where the person has verified staff membership.
*/
organizations?: Array<VerifiedOrganization>;
}
+20 -1
View File
@@ -284,7 +284,26 @@ export const routes: Routes = [
hierarchyData: hierarchyResolver,
suggestions: suggestionResolver,
},
runGuardsAndResolvers: 'always',
// Chart navigation only changes `path`/`lang`; do not refetch the whole
// hierarchy on every node click. An explicit same-URL reload (used by
// `reloadSuggestions`) still re-runs the resolvers.
runGuardsAndResolvers: (from, to) => {
if (from.routeConfig !== to.routeConfig) return true;
const keys = new Set([
...from.queryParamMap.keys,
...to.queryParamMap.keys,
]);
const changedKeys = [...keys].filter(
(key) => from.queryParamMap.get(key) !== to.queryParamMap.get(key),
);
// No query change at all -> explicit same-URL reload.
if (changedKeys.length === 0) return true;
// Only the chart's own state changed -> keep the loaded hierarchy.
return changedKeys.some((key) => key !== 'path' && key !== 'lang');
},
loadComponent: () =>
import('./modules/hierarchy/hierarchy.component').then(
(mod) => mod.HierarchyComponent,
@@ -0,0 +1,58 @@
import { Directive, ElementRef, inject } from '@angular/core';
const PASSIVE_WHEEL_SELECTOR = '[data-passive-wheel]';
let wheelPatchInstalled = false;
/**
* Chrome flags non-passive `wheel`/`mousewheel` listeners as scroll-blocking.
* zrender (ECharts) mounts them on the chart's inner viewport without listener
* options. The hierarchy tree only uses `roam: 'move'` and never calls
* `preventDefault()` on wheel events, so marking them passive is safe.
*
* The patch is global but only affects wheel listeners inside an element that
* carries this directive.
*/
function installPassiveWheelPatch(): void {
if (wheelPatchInstalled) return;
wheelPatchInstalled = true;
const nativeAddEventListener = EventTarget.prototype.addEventListener;
EventTarget.prototype.addEventListener = function (
this: EventTarget,
type: string,
listener: EventListenerOrEventListenerObject | null,
options?: boolean | AddEventListenerOptions,
): void {
const isWheelEvent = type === 'wheel' || type === 'mousewheel';
const hasOptions = options !== undefined && typeof options !== 'boolean';
if (
isWheelEvent &&
!hasOptions &&
this instanceof Element &&
this.closest(PASSIVE_WHEEL_SELECTOR)
) {
nativeAddEventListener.call(this, type, listener, {
capture: options === true,
passive: true,
});
return;
}
nativeAddEventListener.call(this, type, listener, options);
};
}
@Directive({
selector: '[appPassiveWheel]',
standalone: true,
})
export class PassiveWheelDirective {
private readonly host = inject<ElementRef<HTMLElement>>(ElementRef);
constructor() {
this.host.nativeElement.setAttribute('data-passive-wheel', '');
installPassiveWheelPatch();
}
}
@@ -69,7 +69,7 @@
<button
mat-icon-button
type="button"
aria-label="Impersonate"
aria-label="Als diesen Account anmelden"
matTooltip="Als dieser Account anmelden (Impersonation)"
[disabled]="!canImpersonate(row)"
(click)="impersonate(row)">
@@ -3,8 +3,17 @@
title="Wer hat Gründungspotenzial?"
subtitle="Kandidat:innen für Gründungsgespräche und -angebote."
[titleTooltip]="pageTooltip">
<button
pageActions
mat-stroked-button
color="primary"
type="button"
(click)="openExplainer()">
<mat-icon>{{ INSIGHTS_ICON }}</mat-icon>
Erklären
</button>
<div class="founder-dashboard">
@if (hasData() && hasScores()) {
@if (hasData()) {
<section class="statistics-grid" aria-label="Kennzahlen">
<app-dashboard-statistic-card
label="Forschende gesamt"
@@ -25,27 +34,18 @@
[detail]="scoreableDetail()" />
<app-dashboard-statistic-card
label="Unauffällige Profile"
[value]="kpis().passed"
[icon]="VERIFIED_ICON"
variant="quality"
[ariaLabel]="'Unauffällige Profile: ' + fmtInt(kpis().passed)"
[tooltip]="qualityTooltip()"
[detail]="qualityDetail()" />
<app-dashboard-statistic-card
label="Auf der Shortlist"
label="Top Kandidat:innen"
[value]="kpis().shortlisted"
[icon]="STAR_ICON"
variant="shortlist"
[ariaLabel]="'Auf der Shortlist: ' + fmtInt(kpis().shortlisted)"
[ariaLabel]="'Top Kandidat:innen: ' + fmtInt(kpis().shortlisted)"
[tooltip]="shortlistTooltip()"
[detail]="shortlistDetail()" />
</section>
<section class="shortlist-section">
<div class="section-heading">
<h2>Shortlist: Top-Kandidat:innen</h2>
<h2>Top-Kandidat:innen</h2>
<mat-icon
class="info-icon"
[matTooltip]="shortlistSectionTooltip"
@@ -55,6 +55,8 @@
</mat-icon>
</div>
<app-founder-filters [statistics]="statistics()" />
<div class="controls">
<span class="controls__range">
Mindestwert
@@ -66,20 +68,29 @@
{{ INFO_OUTLINE_ICON }}
</mat-icon>
</span>
<mat-slide-toggle
[checked]="thresholdEnabled()"
(change)="onThresholdEnabledChange($event.checked)"
[matTooltip]="thresholdToggleTooltip"
matTooltipClass="sg-tooltip-wide"
matTooltipPosition="above">
Aktiv
</mat-slide-toggle>
<mat-slider
class="controls__slider"
[min]="50"
[max]="100"
[step]="1"
[discrete]="true"
[displayWith]="formatThreshold">
[displayWith]="formatThreshold"
[disabled]="!thresholdEnabled()">
<input
matSliderThumb
[value]="thresholdDraft()"
(valueChange)="onSliderInput($event)"
(dragEnd)="onSliderCommit($event.value)"
(keyup)="onSliderCommit()"
aria-label="Mindestwert für die Shortlist" />
aria-label="Mindestwert für die Liste der Top-Kandidat:innen" />
</mat-slider>
<span class="controls__value">{{ thresholdDraft() }}</span>
<mat-slide-toggle
@@ -101,14 +112,13 @@
<app-data-table
[columns]="columns()"
[data]="rows()"
[selectedRow]="selectedRow()"
[detailTemplate]="detailTemplate()"
queryParamSortKey="sortBy"
queryParamSortDirectionKey="sortOrder"
(rowClick)="selectCandidate($event.candidate.author_id)" />
queryParamSortDirectionKey="sortOrder" />
} @else {
<div class="list__empty">
<p>{{ emptyListMessage() }}</p>
@if (threshold() > 50) {
@if (thresholdEnabled() && threshold() > 50) {
<button
mat-stroked-button
color="primary"
@@ -122,153 +132,10 @@
</mat-card-content>
</mat-card>
@if (selectedRow(); as row) {
<mat-card appearance="outlined" class="card">
<mat-card-content>
<div class="card__head">
<div>
<span class="card__eyebrow">Ausgewählt</span>
<h3>{{ row.name }}</h3>
<div class="card__meta">
<span
class="card__career"
[matTooltip]="careerBucketTooltip(row.candidate.career_bucket)"
matTooltipClass="sg-tooltip-wide"
matTooltipPosition="above">
{{ row.candidate.career_bucket ?? '–' }}
</span>
@if (row.areaLabel) {
· {{ row.areaLabel }}
}
· {{ fmtInt(row.candidate.active_years) }} Jahre mit
Publikationen
@if (!row.candidate.screen.passed && row.flagLabel) {
·
<span
class="card__flag"
[matTooltip]="flagTooltip"
matTooltipClass="sg-tooltip-wide"
matTooltipPosition="above">
auffällig: {{ row.flagLabel }}
</span>
}
</div>
</div>
</div>
<p class="score-caption">
Alle Werte sind Ränge von 0 bis 100 – keine Wahrscheinlichkeiten.
90 heißt: stärker als 90 % der Vergleichsgruppe.
</p>
<div class="score-tiles">
<div
class="score-tile score-tile--primary"
[matTooltip]="scoreTooltip"
matTooltipClass="sg-tooltip-wide"
matTooltipPosition="above">
<span class="score-tile__label">Potenzial</span>
<strong>{{ fmt1(row.score) }}</strong>
</div>
<div
class="score-tile"
[matTooltip]="withinTooltip"
matTooltipClass="sg-tooltip-wide"
matTooltipPosition="above">
<span class="score-tile__label">Signal 1 Jahr</span>
<strong>{{ fmt1(row.within[0]) }}</strong>
</div>
<div
class="score-tile"
[matTooltip]="withinTooltip"
matTooltipClass="sg-tooltip-wide"
matTooltipPosition="above">
<span class="score-tile__label">Signal 3 Jahre</span>
<strong>{{ fmt1(row.within[1]) }}</strong>
</div>
<div
class="score-tile"
[matTooltip]="withinTooltip"
matTooltipClass="sg-tooltip-wide"
matTooltipPosition="above">
<span class="score-tile__label">Signal 5 Jahre</span>
<strong>{{ fmt1(row.within[2]) }}</strong>
</div>
</div>
<div class="facts">
<app-chip
variant="outlined"
color="secondary"
matTooltip="Zahl der Publikationen der Person."
matTooltipClass="sg-tooltip-wide">
Publikationen
<b>{{
fmtInt(row.candidate.founder_features?.publications)
}}</b>
</app-chip>
<app-chip
variant="outlined"
color="secondary"
matTooltip="Zahl der Patente mit Bezug zur Einrichtung."
matTooltipClass="sg-tooltip-wide">
Patente
<b>{{
fmtInt(row.candidate.founder_features?.patents)
}}</b>
</app-chip>
<app-chip
variant="outlined"
color="secondary"
matTooltip="Arbeiten mit Beteiligung aus Unternehmen."
matTooltipClass="sg-tooltip-wide">
Arbeiten mit Industrie
<b>{{
fmtInt(
row.candidate.founder_features?.industry_collab_papers
)
}}</b>
</app-chip>
<app-chip
variant="outlined"
color="secondary"
matTooltip="Zahl der Förderprojekte."
matTooltipClass="sg-tooltip-wide">
Förderprojekte
<b>{{
fmtInt(row.candidate.founder_features?.grants)
}}</b>
</app-chip>
<app-chip
variant="outlined"
color="secondary"
matTooltip="Jahre mit mindestens einer Publikation."
matTooltipClass="sg-tooltip-wide">
Aktive Jahre
<b>{{ fmtInt(row.candidate.active_years) }}</b>
</app-chip>
</div>
</mat-card-content>
</mat-card>
}
<app-query-param-paginator
[total]="total()"
[pageSizeOptions]="[10, 25, 50]" />
</section>
} @else if (hasData()) {
<mat-card appearance="outlined" class="empty-state">
<mat-card-content>
<mat-icon class="empty-state__icon">{{ FOUNDER_ICON }}</mat-icon>
<h2>Noch keine Gründungspotenzial-Scores</h2>
<p>
Für die <strong>{{ universityName() }}</strong> liegen Forschungsdaten
vor, aber die Gründungspotenzial-Auswertung wurde noch nicht
berechnet. Sobald sie vorliegt, erscheinen hier die Kandidat:innen und
ihre Werte.
</p>
</mat-card-content>
</mat-card>
} @else {
<mat-card appearance="outlined" class="empty-state">
<mat-card-content>
@@ -305,7 +172,17 @@
</ng-template>
<ng-template #scoreTemplate let-row>
<span class="list__score-value">{{ fmt1(row.score) }}</span>
@if (row.score === null) {
<span
class="list__score-missing"
[matTooltip]="row.notScoredReason"
matTooltipClass="sg-tooltip-wide"
matTooltipPosition="above">
(nicht bewertet)
</span>
} @else {
<span class="list__score-value">{{ fmt1(row.score) }}</span>
}
</ng-template>
<ng-template #withinTemplate let-row>
@@ -366,3 +243,124 @@
</mat-icon>
</span>
</ng-template>
<ng-template #rowDetailTemplate let-row>
<div class="row-detail">
<div class="row-detail__head">
<span class="row-detail__eyebrow">Details</span>
<a
class="author-name author-link"
[routerLink]="['/person', row.candidate.author_id, 'overview']"
[appComponentTooltip]="AuthorTooltipComponent"
[tooltipInputs]="{ authorId: row.candidate.author_id }"
tooltipMaxWidth="500px"
[title]="row.name"
(click)="$event.stopPropagation()">
<h3>{{ row.name }}</h3>
</a>
<div class="row-detail__meta">
<span
class="row-detail__career"
[matTooltip]="careerBucketTooltip(row.candidate.career_bucket)"
matTooltipClass="sg-tooltip-wide"
matTooltipPosition="above">
{{ row.candidate.career_bucket ?? '–' }}
</span>
@if (row.areaLabel) {
· {{ row.areaLabel }}
}
· {{ fmtInt(row.candidate.active_years) }} Jahre mit Publikationen
</div>
</div>
<p class="score-caption">
Alle Werte sind Ränge von 0 bis 100 – keine Wahrscheinlichkeiten. 90
heißt: stärker als 90 % der Vergleichsgruppe.
</p>
<div class="score-tiles">
<div
class="score-tile score-tile--primary"
[matTooltip]="row.notScoredReason ?? scoreTooltip"
matTooltipClass="sg-tooltip-wide"
matTooltipPosition="above">
<span class="score-tile__label">Potenzial</span>
@if (row.score === null) {
<strong class="score-tile__missing">(nicht bewertet)</strong>
} @else {
<strong>{{ fmt1(row.score) }}</strong>
}
</div>
<div
class="score-tile"
[matTooltip]="withinTooltip"
matTooltipClass="sg-tooltip-wide"
matTooltipPosition="above">
<span class="score-tile__label">Signal 1 Jahr</span>
<strong>{{ fmt1(row.within[0]) }}</strong>
</div>
<div
class="score-tile"
[matTooltip]="withinTooltip"
matTooltipClass="sg-tooltip-wide"
matTooltipPosition="above">
<span class="score-tile__label">Signal 3 Jahre</span>
<strong>{{ fmt1(row.within[1]) }}</strong>
</div>
<div
class="score-tile"
[matTooltip]="withinTooltip"
matTooltipClass="sg-tooltip-wide"
matTooltipPosition="above">
<span class="score-tile__label">Signal 5 Jahre</span>
<strong>{{ fmt1(row.within[2]) }}</strong>
</div>
</div>
<div class="facts">
<app-chip
variant="outlined"
color="secondary"
matTooltip="Zahl der Publikationen der Person."
matTooltipClass="sg-tooltip-wide">
Publikationen
<b>{{ fmtInt(row.candidate.founder_features?.publications) }}</b>
</app-chip>
<app-chip
variant="outlined"
color="secondary"
matTooltip="Zahl der Patente mit Bezug zur Einrichtung."
matTooltipClass="sg-tooltip-wide">
Patente
<b>{{ fmtInt(row.candidate.founder_features?.patents) }}</b>
</app-chip>
<app-chip
variant="outlined"
color="secondary"
matTooltip="Arbeiten mit Beteiligung aus Unternehmen."
matTooltipClass="sg-tooltip-wide">
Arbeiten mit Industrie
<b>{{
fmtInt(row.candidate.founder_features?.industry_collab_papers)
}}</b>
</app-chip>
<app-chip
variant="outlined"
color="secondary"
matTooltip="Zahl der Förderprojekte."
matTooltipClass="sg-tooltip-wide">
Förderprojekte
<b>{{ fmtInt(row.candidate.founder_features?.grants) }}</b>
</app-chip>
<app-chip
variant="outlined"
color="secondary"
matTooltip="Jahre mit mindestens einer Publikation."
matTooltipClass="sg-tooltip-wide">
Aktive Jahre
<b>{{ fmtInt(row.candidate.active_years) }}</b>
</app-chip>
</div>
</div>
</ng-template>
@@ -142,6 +142,10 @@
color: var(--sg-text);
}
tr.detail-row .mat-mdc-cell {
padding: 0;
}
.mat-column-name {
width: 32%;
}
@@ -205,7 +209,7 @@
}
.list__career,
.card__career {
.row-detail__career {
cursor: help;
text-decoration: underline dotted;
text-underline-offset: 2px;
@@ -220,6 +224,14 @@
text-align: right;
}
.list__score-missing {
color: var(--sg-text-soft);
font-size: 11.5px;
font-style: italic;
cursor: help;
white-space: nowrap;
}
.list__within-nums {
color: var(--sg-text-muted);
font-size: 12px;
@@ -238,32 +250,28 @@
font-size: 13.5px;
}
// -- Detail card --------------------------------------------------------
// -- Detail row ---------------------------------------------------------
.card {
margin-top: 16px;
.row-detail {
padding: 18px 20px 20px;
border-top: 1px solid var(--sg-border);
background: var(--sg-surface-muted);
.mat-mdc-card-content {
padding: 20px;
}
h3 {
margin: 0 0 2px;
color: var(--sg-text);
font-size: 20px;
font-size: 18px;
}
}
.card__head {
.row-detail__head {
display: flex;
flex-wrap: wrap;
flex-direction: column;
align-items: flex-start;
justify-content: space-between;
gap: 12px;
gap: 2px;
}
.card__eyebrow {
.row-detail__eyebrow {
display: block;
margin-bottom: 2px;
color: var(--sg-text-soft);
@@ -273,17 +281,12 @@
text-transform: uppercase;
}
.card__meta {
margin-bottom: 16px;
.row-detail__meta {
margin-bottom: 14px;
color: var(--sg-text-soft);
font-size: 12.5px;
}
.card__flag {
color: var(--sg-error);
cursor: help;
}
.score-caption {
margin: 0 0 12px;
color: var(--sg-text-soft);
@@ -325,6 +328,13 @@
&--primary strong {
color: var(--sg-blue-highlight);
}
&__missing {
color: var(--sg-text-soft);
font-size: 15px;
font-weight: 600;
font-style: italic;
}
}
.facts {
@@ -13,11 +13,14 @@ import { ActivatedRoute, Router } from '@angular/router';
import { toSignal } from '@angular/core/rxjs-interop';
import { MatCardModule } from '@angular/material/card';
import { MatButtonModule } from '@angular/material/button';
import { MatDialog } from '@angular/material/dialog';
import { MatIconModule } from '@angular/material/icon';
import { MatSlideToggleModule } from '@angular/material/slide-toggle';
import { MatSliderModule } from '@angular/material/slider';
import { MatSlideToggleModule } from '@angular/material/slide-toggle';
import { MatTooltipModule } from '@angular/material/tooltip';
import { RouterLink } from '@angular/router';
import { ComponentTooltipDirective } from '../../../directives/component-tooltip.directive';
import { AppAuthorTooltipComponent } from '../../../shared/ui/app-author-tooltip/app-author-tooltip.component';
import {
FounderCandidate,
FounderCandidatePage,
@@ -42,18 +45,21 @@ import {
FOUNDER_ICON,
HELP_OUTLINE_ICON,
INFO_OUTLINE_ICON,
INSIGHTS_ICON,
PERSONS_ICON,
STAR_ICON,
VERIFIED_ICON,
} from '../../../shared/ui/icons';
import { CredentialService } from '../../../shared/services/credential.service';
import { FounderExplainerPanelComponent } from './founder-explainer-panel/founder-explainer-panel.component';
import { FounderFiltersComponent } from '../founder-filters/founder-filters.component';
const FALLBACK_UNIVERSITY = 'Universität Duisburg-Essen';
const DEFAULT_THRESHOLD = 90;
/**
* A shortlist row: the generated candidate plus only the values that the
* table derives from it (display name, the 1/3/5-year slice, the headline
* screen reason). Everything else is read from `candidate` directly.
* table derives from it (display name, the 1/3/5-year slice, and the reason a
* profile has no score).
*/
interface FounderRow {
candidate: FounderCandidate;
@@ -61,7 +67,8 @@ interface FounderRow {
areaLabel: string | null;
score: number | null;
within: (number | null)[];
flagLabel: string | null;
/** Explanation shown in the "(nicht bewertet)" tooltip; null when scored. */
notScoredReason: string | null;
}
@Component({
@@ -72,31 +79,36 @@ interface FounderRow {
MatCardModule,
MatButtonModule,
MatIconModule,
MatSlideToggleModule,
MatSliderModule,
MatSlideToggleModule,
MatTooltipModule,
QueryParamPaginatorComponent,
ChipComponent,
DataTableComponent,
DashboardStatisticCardComponent,
PageContainerComponent,
RouterLink,
ComponentTooltipDirective,
FounderFiltersComponent,
],
templateUrl: './founder-dashboard.component.html',
styleUrl: './founder-dashboard.component.scss',
})
export class FounderDashboardComponent {
readonly AuthorTooltipComponent = AppAuthorTooltipComponent;
readonly FOUNDER_ICON = FOUNDER_ICON;
readonly HELP_OUTLINE_ICON = HELP_OUTLINE_ICON;
readonly INFO_OUTLINE_ICON = INFO_OUTLINE_ICON;
readonly INSIGHTS_ICON = INSIGHTS_ICON;
readonly PERSONS_ICON = PERSONS_ICON;
readonly STAR_ICON = STAR_ICON;
readonly VERIFIED_ICON = VERIFIED_ICON;
readonly statistics = input.required<FounderStatistics>();
readonly candidates = input.required<FounderCandidatePage>();
private readonly router = inject(Router);
private readonly route = inject(ActivatedRoute);
private readonly dialog = inject(MatDialog);
private readonly credentials = inject(CredentialService, { optional: true });
/** The university whose cohort is shown; comes from the account profile. */
@@ -113,22 +125,22 @@ export class FounderDashboardComponent {
initialValue: this.route.snapshot.queryParamMap,
});
readonly threshold = computed(
() => Math.max(50, Math.min(100, toNumber(this.queryParams().get('threshold')) ?? 90)),
/** The threshold is opt-in: it only applies when the URL param is present. */
readonly thresholdEnabled = computed(
() => toNumber(this.queryParams().get('threshold')) !== null,
);
readonly threshold = computed(() => {
const value = toNumber(this.queryParams().get('threshold'));
return value === null
? DEFAULT_THRESHOLD
: Math.max(50, Math.min(100, value));
});
readonly screened = computed(
() => this.queryParams().get('screened') === 'true',
);
/** Live value while dragging the slider; committed to the URL on release. */
readonly thresholdDraft = signal<number>(90);
constructor() {
effect(() => this.thresholdDraft.set(this.threshold()), {
allowSignalWrites: true,
});
}
// -- Explanations (tooltips only) --------------------------------------
readonly pageTooltip =
@@ -140,28 +152,18 @@ export class FounderDashboardComponent {
readonly scoreableTooltip =
'Nur diese Personen haben genug Publikationen (mindestens 4), um vom Modell bewertet zu werden. Für alle anderen gibt es keinen Score.';
readonly qualityTooltip = computed(
() =>
`${this.kpis().passed.toLocaleString('de-DE')} von ${this.kpis().total.toLocaleString('de-DE')} Forschenden (${this.kpis().share} %) haben ein vollständiges und plausibles Profil. Nur diese Werte sind gut belastbar.`,
);
readonly shortlistTooltip = computed(
() =>
`Personen mit dem stärksten Gründungspotenzial. Angezeigt werden alle ab einem Rang von ${this.threshold()}. ${
this.screened()
? 'Auffällige Profile sind ausgeblendet.'
: 'Auffällige Profile sind enthalten.'
}`,
);
readonly shortlistTooltip = computed(() => {
const thresholdPart = this.thresholdEnabled()
? `Ab einem Rang von ${this.threshold()}.`
: 'Ohne Mindestwert werden alle Profile angezeigt.';
const screenPart = this.screened()
? 'Auffällige Profile sind ausgeblendet.'
: 'Auffällige Profile sind enthalten.';
return `Personen mit dem stärksten Gründungspotenzial. ${thresholdPart} ${screenPart}`;
});
readonly shortlistSectionTooltip =
'Hier stehen die Personen mit dem stärksten Gründungspotenzial. Der Regler legt fest, ab welchem Rang jemand in die Liste kommt.';
readonly thresholdTooltip =
'Legt fest, ab welchem Rang Personen in der Shortlist erscheinen. 90 ist streng und zeigt nur die obersten 10 % der Vergleichsgruppe; 50 zeigt die obere Hälfte.';
readonly screeningTooltip =
'Blendet Profile aus, die vermutlich unvollständig, falsch datiert oder mit anderen Personen vermischt sind. Die Scores dieser Personen sind weniger verlässlich.';
'Hier stehen die Personen mit dem stärksten Gründungspotenzial. Der Mindestwert ist optional: ohne ihn werden alle Profile angezeigt.';
readonly scoreTooltip =
'Rang des Gründungspotenzials von 0 bis 100. 90 heißt: stärker als 90 % der rund 9.000 vergleichbaren Wissenschaftler:innen anderer Universitäten. Kein Wahrscheinlichkeitswert.';
@@ -172,45 +174,52 @@ export class FounderDashboardComponent {
readonly evidenceTooltip =
'Die Signale, auf denen die Einschätzung beruht: Publikationen, Patente, Förderungen und gemeinsame Arbeiten mit der Industrie. Die Werte sind Zählungen, keine Bewertung der Person.';
readonly flagTooltip =
'Möglicherweise wurden mehrere Personen mit gleichem Namen zusammengeführt oder die Karriereangaben sind unplausibel. Die Werte sind dann unsicher. Bitte Identität und Profil prüfen, bevor Sie die Person ansprechen.';
readonly careerBucketTooltip = careerBucketDescription;
readonly thresholdTooltip =
'Legt fest, ab welchem Rang Personen in der Liste erscheinen. 90 ist streng und zeigt nur die obersten 10 % der Vergleichsgruppe; 50 zeigt die obere Hälfte. Ohne Mindestwert werden alle Profile angezeigt.';
readonly thresholdToggleTooltip =
'Standardmäßig werden alle Profile angezeigt. Aktiviere den Mindestwert, um nur Personen ab einem bestimmten Rang zu sehen.';
readonly screeningTooltip =
'Blendet Profile aus, die vermutlich unvollständig, falsch datiert oder mit anderen Personen vermischt sind. Die Werte dieser Personen sind weniger verlässlich. Ist die Option aus, werden alle Profile angezeigt.';
// -- KPIs ---------------------------------------------------------------
readonly kpis = computed(() => {
const stats = this.statistics();
const total = stats.provenance?.document_count ?? 0;
const scoreable = stats.overall?.in_population ?? 0;
const passed = stats.overall?.screened ?? 0;
const share = total ? Math.round((passed / total) * 100) : 0;
const shortlisted = this.candidates().total ?? 0;
return { total, scoreable, passed, share, shortlisted };
return { total, scoreable, shortlisted };
});
/** True when the pipeline has produced at least one score for this university. */
readonly hasScores = computed(
() => (this.statistics().overall?.in_population ?? 0) > 0,
);
readonly scoreableShare = computed(() => {
const { total, scoreable } = this.kpis();
return total ? Math.round((scoreable / total) * 100) : 0;
});
readonly qualityDetail = computed(
() => `${this.kpis().share} % der Forschenden`,
);
readonly scoreableDetail = computed(
() => `${this.scoreableShare()} % der Forschenden`,
);
readonly shortlistDetail = computed(() => `ab Rang ${this.threshold()}`);
readonly shortlistDetail = computed(() =>
this.thresholdEnabled() ? `ab Rang ${this.threshold()}` : 'alle Profile',
);
readonly emptyListMessage = computed(() =>
this.screened()
? `Niemand erreicht den Mindestwert von ${this.threshold()} und hat zugleich ein unauffälliges Profil. Senken Sie den Mindestwert oder blenden Sie auffällige Profile wieder ein.`
: `Niemand erreicht den Mindestwert von ${this.threshold()}. Senken Sie den Mindestwert, um mehr Personen zu sehen.`,
this.thresholdEnabled()
? `Niemand erreicht den Mindestwert von ${this.threshold()}${
this.screened() ? ' und hat zugleich ein unauffälliges Profil' : ''
}. Senken Sie den Mindestwert${
this.screened()
? ' oder blenden Sie auffällige Profile wieder ein'
: ' oder deaktivieren Sie ihn'
}, um mehr Profile zu sehen.`
: this.screened()
? 'Mit ausgeblendeten auffälligen Profilen wurde niemand gefunden. Blenden Sie auffällige Profile wieder ein, um mehr zu sehen.'
: 'Für diese Auswahl wurden keine Personen gefunden. Setzen Sie die Filter zurück, um mehr Profile zu sehen.',
);
// -- Shortlist ----------------------------------------------------------
@@ -229,6 +238,8 @@ export class FounderDashboardComponent {
viewChild.required<TemplateRef<void>>('withinHeader');
private readonly evidenceHeader =
viewChild.required<TemplateRef<void>>('evidenceHeader');
readonly detailTemplate =
viewChild.required<TemplateRef<FounderRow>>('rowDetailTemplate');
readonly columns = computed<GenericColumn<FounderRow>[]>(() => [
{
@@ -267,32 +278,36 @@ export class FounderDashboardComponent {
(this.candidates().elements ?? []).map((c) => toRow(c)),
);
readonly selectedId = signal<string | null>(null);
readonly selectedRow = computed<FounderRow | null>(() => {
const id = this.selectedId();
const rows = this.rows();
if (id) {
return rows.find((r) => r.candidate.author_id === id) ?? null;
}
return rows[0] ?? null;
});
selectCandidate(id: string): void {
this.selectedId.set(id);
}
// -- Controls -----------------------------------------------------------
/** Discrete label inside the Material slider thumb. */
/** Live slider value while dragging; committed to the URL on release. */
readonly thresholdDraft = signal<number>(DEFAULT_THRESHOLD);
constructor() {
effect(() => this.thresholdDraft.set(this.threshold()));
}
readonly formatThreshold = (value: number): string => String(value);
/** Enables or disables the threshold filter (writes/removes the URL param). */
onThresholdEnabledChange(enabled: boolean): void {
void this.router.navigate([], {
relativeTo: this.route,
queryParams: {
threshold: enabled ? this.thresholdDraft() : null,
page: 0,
},
queryParamsHandling: 'merge',
});
}
onSliderInput(value: number): void {
if (Number.isFinite(value)) this.thresholdDraft.set(value);
}
/** Commits the threshold value to the URL. */
onSliderCommit(value = this.thresholdDraft()): void {
if (!Number.isFinite(value)) return;
if (!this.thresholdEnabled() || !Number.isFinite(value)) return;
this.thresholdDraft.set(value);
if (value === this.threshold()) return;
void this.router.navigate([], {
@@ -302,17 +317,40 @@ export class FounderDashboardComponent {
});
}
/**
* `screened=false` means "only rejected profiles" on the backend, so turning
* the toggle off must REMOVE the param (everyone), not set false.
*/
onScreenedChange(checked: boolean): void {
void this.router.navigate([], {
relativeTo: this.route,
queryParams: { screened: checked ? 'true' : 'false', page: 0 },
queryParams: { screened: checked ? 'true' : null, page: 0 },
queryParamsHandling: 'merge',
});
}
onLowerThreshold(): void {
const next = Math.max(50, this.threshold() - 10);
this.onSliderCommit(next);
void this.router.navigate([], {
relativeTo: this.route,
queryParams: { threshold: next, page: 0 },
queryParamsHandling: 'merge',
});
}
/** Opens the global model explanation; independent of the selection. */
openExplainer(): void {
this.dialog.open(FounderExplainerPanelComponent, {
panelClass: 'sg-side-panel',
position: { right: '0', top: '0' },
height: '100dvh',
width: 'min(520px, 100vw)',
maxWidth: '100vw',
maxHeight: '100dvh',
ariaLabel: 'Modell-Erklärung zum Gründungspotenzial',
autoFocus: 'first-tabbable',
restoreFocus: true,
});
}
// -- Formatting helpers for the template --------------------------------
@@ -323,24 +361,32 @@ export class FounderDashboardComponent {
function toRow(c: FounderCandidate): FounderRow {
const fp = c.founder_potential;
const reasons = c.screen.reasons ?? [];
const score = fp?.external_percentile ?? null;
return {
candidate: c,
name: c.display_name ?? c.author_id,
areaLabel: c.founder_features?.publication_research_area_label ?? null,
score: fp?.external_percentile ?? null,
score,
within: [
fp?.external_percentile_within_1y ?? null,
fp?.external_percentile_within_3y ?? null,
fp?.external_percentile_within_5y ?? null,
],
flagLabel:
reasons.length > 0
? (SCREEN_REASON_LABELS[reasons[0]] ?? reasons[0])
: null,
notScoredReason: score === null ? notScoredReason(c) : null,
};
}
/** Plain-language explanation for why a profile has no score. */
function notScoredReason(c: FounderCandidate): string {
const reasons = (c.screen.reasons ?? []).map(
(reason) => SCREEN_REASON_LABELS[reason] ?? reason,
);
const detail = reasons.length
? ` Gründe: ${reasons.join(', ')}.`
: '';
return `Für dieses Profil liegt kein Score vor. Das Modell braucht mindestens 4 Publikationen und ein vollständiges, plausibles Profil.${detail}`;
}
function toNumber(value: string | null): number | null {
if (value === null || value === '') return null;
const parsed = Number(value);
@@ -0,0 +1,116 @@
<div class="explainer">
<header class="explainer__head">
<div class="explainer__heading">
<p class="explainer__eyebrow">Modell-Erklärung</p>
<h2 class="explainer__title">Woher kommt das Gründungspotenzial?</h2>
</div>
<button
mat-icon-button
type="button"
class="explainer__close"
aria-label="Erklärung schließen"
(click)="close()">
<mat-icon>{{ CLOSE_ICON }}</mat-icon>
</button>
</header>
<div class="explainer__body">
@if (loading()) {
<div class="explainer__state">
<mat-spinner diameter="32" />
<p>Modellinformationen werden geladen …</p>
</div>
} @else if (error()) {
<div class="explainer__state explainer__state--error">
<mat-icon>{{ ERROR_OUTLINE_ICON }}</mat-icon>
<p>Die Modellinformationen konnten nicht geladen werden.</p>
<button mat-stroked-button type="button" (click)="load()">
Erneut versuchen
</button>
</div>
} @else {
<p class="explainer__lead">
Das Modell schätzt aus Publikationen, Patenten, Förderungen und
Industriekontakten, wie wahrscheinlich eine Person gründet. Die Balken
zeigen, auf welche Merkmale sich das Modell insgesamt am stärksten
stützt.
</p>
<div class="explainer__metrics" aria-label="Modellgüte">
<span>
ROC-AUC <strong>{{ fmtAuc(modelInfo()?.oof_roc_auc) }}</strong>
</span>
<span>
PR-AUC <strong>{{ fmtAuc(modelInfo()?.oof_pr_auc) }}</strong>
</span>
@if (modelInfo()?.reference_cohort_size) {
<span>
Referenz
<strong>{{ fmtInt(modelInfo()?.reference_cohort_size) }}</strong>
Profile
</span>
}
@if (modelInfo()?.reference_founders) {
<span>
<strong>{{ fmtInt(modelInfo()?.reference_founders) }}</strong>
Gründer:innen
</span>
}
</div>
@if (entries().length) {
<div
echarts
[options]="chartOptions()"
[autoResize]="true"
class="explainer__chart"
[style.height.px]="chartHeight()"
role="img"
aria-label="Balkendiagramm: Einfluss der Merkmale auf die Gründungsprognose"></div>
<section
class="explainer__origin"
aria-labelledby="explainer-origin-title">
<h3 id="explainer-origin-title">Woher kommen die Zahlen?</h3>
<p>
Für jedes Merkmal – zum Beispiel Publikationen pro Jahr, Patente
oder Industriekontakte – macht das Modell denselben Test:
</p>
<ol class="explainer__steps">
<li>
Ein Merkmal wird zufällig vertauscht, alle anderen bleiben gleich.
</li>
<li>Das Modell bewertet dieselben Personen erneut.</li>
<li>
Je stärker die Trefferqualität danach sinkt, desto größer ist der
Balken.
</li>
</ol>
<p>
Ein großer Balken heißt also: Das Modell verlässt sich stark auf
dieses Merkmal. Die Prozentwerte sind der Anteil an der
Gesamtbedeutung der angezeigten Merkmale. Sie sind keine Punkte,
keine Wahrscheinlichkeit und kein Beitrag einer einzelnen Person.
Die Werte gelten für das Modell insgesamt und sind für alle Personen
gleich.
</p>
</section>
<p class="explainer__note">
Ausgeblendet: Das wichtigste Trainingsmerkmal (Patent-Fachgebiet) ist
im aktuellen Datenbestand für alle gleich und trennt daher niemanden.
Institutionsmerkmale sind im Produktionsmodell nicht enthalten.
</p>
} @else {
<p class="explainer__note">
Für dieses Modell sind keine darstellbaren Merkmale verfügbar.
</p>
}
<p class="explainer__caveat">
Die Werte beschreiben das trainierte Modell, nicht die einzelne Person.
Sie belegen keinen Ursache-Wirkungs-Zusammenhang.
</p>
}
</div>
</div>
@@ -0,0 +1,161 @@
:host {
display: block;
height: 100%;
}
.explainer {
display: flex;
flex-direction: column;
height: 100%;
background: var(--sg-card-bg);
color: var(--sg-text);
}
.explainer__head {
display: flex;
flex: none;
align-items: flex-start;
gap: 12px;
padding: 20px 18px 14px 24px;
border-bottom: 1px solid var(--sg-border);
}
.explainer__heading {
flex: 1;
min-width: 0;
}
.explainer__eyebrow {
margin: 0 0 4px;
color: var(--sg-text-soft);
font-size: 11px;
font-weight: 600;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.explainer__title {
margin: 0;
color: var(--sg-text);
font-size: 19px;
font-weight: 700;
line-height: 1.3;
}
.explainer__close {
flex: none;
margin: -4px -4px 0 0;
color: var(--sg-text-muted);
}
.explainer__body {
flex: 1;
min-height: 0;
overflow-y: auto;
padding: 18px 24px 24px;
}
.explainer__lead {
margin: 0 0 14px;
color: var(--sg-text-muted);
font-size: 13px;
line-height: 1.55;
}
.explainer__metrics {
display: flex;
flex-wrap: wrap;
gap: 6px 14px;
margin-bottom: 18px;
padding: 10px 12px;
border: 1px solid var(--sg-border);
border-radius: 10px;
background: var(--sg-surface-muted);
color: var(--sg-text-muted);
font-size: 12px;
line-height: 1.4;
strong {
color: var(--sg-text);
font-variant-numeric: tabular-nums;
}
}
.explainer__chart {
width: 100%;
}
.explainer__origin {
margin-top: 18px;
padding: 14px 16px 16px;
border: 1px solid var(--sg-border);
border-radius: 12px;
background: var(--sg-surface-muted);
h3 {
margin: 0 0 8px;
color: var(--sg-text);
font-size: 13px;
font-weight: 700;
}
p {
margin: 0;
color: var(--sg-text-muted);
font-size: 12px;
line-height: 1.5;
}
}
.explainer__steps {
margin: 10px 0;
padding-left: 18px;
color: var(--sg-text-muted);
font-size: 12px;
line-height: 1.5;
li + li {
margin-top: 4px;
}
li::marker {
color: var(--sg-primary);
font-weight: 700;
}
}
.explainer__note,
.explainer__caveat {
margin: 10px 0 0;
color: var(--sg-text-soft);
font-size: 11.5px;
line-height: 1.5;
}
.explainer__caveat {
margin-top: 16px;
padding-top: 12px;
border-top: 1px solid var(--sg-border);
}
.explainer__state {
display: flex;
flex-direction: column;
align-items: center;
gap: 12px;
padding: 48px 12px;
color: var(--sg-text-muted);
font-size: 13px;
text-align: center;
p {
margin: 0;
}
&--error mat-icon {
width: 30px;
height: 30px;
color: var(--sg-error);
font-size: 30px;
}
}
@@ -0,0 +1,242 @@
import {
ChangeDetectionStrategy,
Component,
computed,
inject,
signal,
} from '@angular/core';
import { MatButtonModule } from '@angular/material/button';
import { MatDialogRef } from '@angular/material/dialog';
import { MatIconModule } from '@angular/material/icon';
import { MatProgressSpinnerModule } from '@angular/material/progress-spinner';
import { EChartsOption } from 'echarts';
import { NgxEchartsDirective } from 'ngx-echarts';
import { FounderModelInfo, MultiplicatorsService } from '../../../../api';
import { ChartThemeService } from '../../../../shared/services/chart-theme.service';
import { CLOSE_ICON, ERROR_OUTLINE_ICON } from '../../../../shared/ui/icons';
import { fmtInt } from '../../founder-potential.utils';
/**
* German labels for the features the founder classifier exposes. Features
* missing here fall back to a readable version of their technical name.
*/
const FEATURE_LABELS: Record<string, string> = {
pub_rate: 'Publikationen pro Jahr',
first_publication_year: 'Jahr der ersten Publikation',
industry_collab_at_index: 'Publikationen mit Industriebeteiligung',
career_age_at_index: 'Karrierealter',
patents_at_index: 'Patente',
patent_rate: 'Patente pro Jahr',
patent_research_area_46: 'Patent-Fachgebiet: Informatik',
publication_research_area_32: 'Fachgebiet: Biomedizin & Klinik',
years_since_first_grant: 'Jahre seit erster Förderung',
grant_research_area_51: 'Förder-Fachgebiet: Physik',
};
/** One bar in the chart, with the share of the displayed total. */
interface ImportanceEntry {
label: string;
share: number;
importance: number;
std: number | null;
}
function isVisibleFeature(feature: string): boolean {
// Constant in this deployment (no IPC-to-FOR mapping) and dropped from the
// production bundle, respectively. Showing them would mislead locally.
return (
feature !== 'patent_research_area_n.' &&
!feature.startsWith('institution_')
);
}
function featureLabel(feature: string): string {
return (
FEATURE_LABELS[feature] ??
feature
.replace(/_/g, ' ')
.replace(/\b\w/g, (letter) => letter.toUpperCase())
);
}
function fmtShare(value: number): string {
return value.toLocaleString('de-DE', {
minimumFractionDigits: 1,
maximumFractionDigits: 1,
});
}
function fmtImportance(value: number): string {
return value.toLocaleString('de-DE', {
minimumFractionDigits: 3,
maximumFractionDigits: 3,
});
}
function fmtAuc(value: number | null | undefined): string {
if (value === null || value === undefined) return '—';
return value.toLocaleString('de-DE', {
minimumFractionDigits: 2,
maximumFractionDigits: 2,
});
}
/**
* Right-hand overlay that explains where the founder score comes from.
*
* It shows the model's global permutation importances, not per-person
* contributions: the API exposes only raw feature values per candidate.
*/
@Component({
selector: 'app-founder-explainer-panel',
standalone: true,
imports: [
MatButtonModule,
MatIconModule,
MatProgressSpinnerModule,
NgxEchartsDirective,
],
templateUrl: './founder-explainer-panel.component.html',
styleUrl: './founder-explainer-panel.component.scss',
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class FounderExplainerPanelComponent {
readonly CLOSE_ICON = CLOSE_ICON;
readonly ERROR_OUTLINE_ICON = ERROR_OUTLINE_ICON;
private readonly service = inject(MultiplicatorsService);
private readonly dialogRef = inject(
MatDialogRef<FounderExplainerPanelComponent>,
);
private readonly chartTheme = inject(ChartThemeService);
readonly modelInfo = signal<FounderModelInfo | null>(null);
readonly loading = signal(false);
readonly error = signal(false);
readonly fmtInt = fmtInt;
readonly fmtAuc = fmtAuc;
readonly entries = computed<ImportanceEntry[]>(() => {
const importances = (this.modelInfo()?.importances ?? []).filter((item) =>
isVisibleFeature(item.feature),
);
const total = importances.reduce(
(sum, item) => sum + item.importance_mean,
0,
);
if (total <= 0) return [];
return [...importances]
.sort((a, b) => b.importance_mean - a.importance_mean)
.map((item) => ({
label: featureLabel(item.feature),
share: (item.importance_mean / total) * 100,
importance: item.importance_mean,
std: item.importance_std ?? null,
}));
});
/** Enough vertical room for every bar; the panel body scrolls if needed. */
readonly chartHeight = computed(() =>
Math.max(240, this.entries().length * 44 + 24),
);
readonly chartOptions = computed<EChartsOption>(() => {
const colors = this.chartTheme.colors();
const entries = this.entries();
return {
animationDuration: 350,
grid: { left: 4, right: 50, top: 8, bottom: 4, containLabel: true },
tooltip: {
trigger: 'item',
confine: true,
backgroundColor: colors.tooltipBg,
borderColor: colors.tooltipBorder,
textStyle: { color: colors.tooltipTextColor, fontSize: 12 },
formatter: (params: any) => {
const entry = entries[params.dataIndex];
if (!entry) return '';
const std =
entry.std !== null
? ` ± ${fmtImportance(entry.std)}`
: '';
return [
`<strong>${entry.label}</strong>`,
`Anteil an der Gesamtbedeutung: <strong>${fmtShare(entry.share)} %</strong>`,
`Beitrag zur Trefferqualität: ${fmtImportance(entry.importance)}${std}`,
].join('<br/>');
},
},
xAxis: {
type: 'value',
axisLabel: {
color: colors.mutedTextColor,
fontSize: 11,
formatter: (value: any) =>
`${value.toLocaleString('de-DE', { maximumFractionDigits: 0 })} %`,
},
axisLine: { show: false },
axisTick: { show: false },
splitLine: { lineStyle: { color: colors.splitLine } },
},
yAxis: {
type: 'category',
inverse: true,
data: entries.map((entry) => entry.label),
axisLabel: {
color: colors.text,
fontSize: 12,
width: 170,
overflow: 'break',
lineHeight: 15,
},
axisLine: { show: false },
axisTick: { show: false },
},
series: [
{
type: 'bar',
data: entries.map((entry) => entry.share),
barMaxWidth: 20,
itemStyle: {
color: colors.primary,
borderRadius: [0, 4, 4, 0],
},
label: {
show: true,
position: 'right',
color: colors.text,
fontSize: 11,
formatter: (params: any) => `${fmtShare(params.value)} %`,
},
},
],
};
});
constructor() {
this.load();
}
load(): void {
this.loading.set(true);
this.error.set(false);
this.service.getFounderModelInfo().subscribe({
next: (info) => {
this.modelInfo.set(info);
this.loading.set(false);
},
error: () => {
this.error.set(true);
this.loading.set(false);
},
});
}
close(): void {
this.dialogRef.close();
}
}
@@ -0,0 +1,28 @@
<div class="content">
<app-query-param-input
queryParamKey="name"
label="Name suchen"
[debounceTime]="300" />
<div class="filter-grid">
<app-query-param-selector
[options]="careerOptions"
queryParamKey="careerBucket"
label="Karrierestufe"
[multiple]="true"
matTooltip="Early: 1–4 aktive Publikationsjahre, Emerging: 5–9, Established: 10–14, Senior: 15 oder mehr."
matTooltipClass="sg-tooltip-wide"
matTooltipPosition="above" />
<app-query-param-selector
[options]="researchAreaOptions()"
queryParamKey="researchArea"
label="Forschungsgebiet"
[multiple]="true"
matTooltip="Filtert nach dem Fachgebiet der Publikationen (2-stelliger FOR-Code)."
matTooltipClass="sg-tooltip-wide"
matTooltipPosition="above" />
</div>
<app-selected-filters [observers]="observers" />
</div>
@@ -0,0 +1,12 @@
.content {
display: flex;
flex-direction: column;
gap: 1rem;
}
.filter-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));
gap: 1rem;
align-items: start;
}
@@ -0,0 +1,89 @@
import { Component, computed, input } from '@angular/core';
import { MatTooltipModule } from '@angular/material/tooltip';
import { CareerBucket, FounderStatistics } from '../../../api';
import { QueryParamInputComponent } from '../../../shared/ui/query-param-input/query-param-input.component';
import {
QueryParamSelectorComponent,
SelectorOption,
} from '../../../shared/ui/query-param-selector/query-param-selector.component';
import {
FilterObserver,
SelectedFiltersComponent,
} from '../../../shared/ui/selected-filters/selected-filters.component';
import { PERSON_ICON, SEARCH_ICON } from '../../../shared/ui/icons';
@Component({
selector: 'app-founder-filters',
standalone: true,
imports: [
MatTooltipModule,
QueryParamInputComponent,
QueryParamSelectorComponent,
SelectedFiltersComponent,
],
templateUrl: './founder-filters.component.html',
styleUrl: './founder-filters.component.scss',
})
export class FounderFiltersComponent {
/** Stats carry the research-area codes/labels that the backend filters on. */
readonly statistics = input.required<FounderStatistics>();
readonly careerOptions: SelectorOption[] = [
{ value: CareerBucket.Early, display_name: 'Early (1–4 Jahre)' },
{ value: CareerBucket.Emerging, display_name: 'Emerging (5–9 Jahre)' },
{
value: CareerBucket.Established,
display_name: 'Established (10–14 Jahre)',
},
{ value: CareerBucket.Senior, display_name: 'Senior (15+ Jahre)' },
];
/**
* The backend filters research areas by the 2-digit FOR division code
* (`founding_features.publication_research_area`), so the selector must use
* the code as its value, not the human-readable label.
*/
readonly researchAreaOptions = computed<SelectorOption[]>(() =>
(this.statistics().research_areas ?? [])
.filter((area) => !!area.code)
.map((area) => ({
value: area.code,
display_name: area.label ? `${area.label} (${area.code})` : area.code,
}))
.sort((a, b) => a.display_name.localeCompare(b.display_name, 'de')),
);
readonly observers: FilterObserver[] = [
{
id: 'name',
queryParamKey: 'name',
icon: SEARCH_ICON,
removable: true,
template: undefined,
},
{
id: 'researchArea',
queryParamKey: 'researchArea',
icon: SEARCH_ICON,
valueFormatter: (value) =>
value
.split(',')
.map((code) => {
const area = this.statistics().research_areas?.find(
(a) => a.code === code,
);
return area?.label ? `${area.label} (${code})` : code;
})
.join(', '),
removable: true,
},
{
id: 'career',
queryParamKey: 'careerBucket',
icon: PERSON_ICON,
valueFormatter: (value) => value.split(',').join(', '),
removable: true,
},
];
}
@@ -92,15 +92,6 @@ export const METRIC_GROUP_META: Record<
},
};
/** German labels for the funnel stages, keyed by their stable key. */
export const FUNNEL_STAGE_LABELS: Record<string, string> = {
ALL: 'Alle Forschenden im Index',
IN_POPULATION: 'Vom Modell bewertbar (mind. 4 Publikationen)',
NOT_SUSPICIOUS: 'Kein zusammengeführtes Profil',
CAREER_AGE_PLAUSIBLE: 'Plausible Karrieredauer (max. 40 Jahre)',
MIN_PUBLICATIONS: 'Mind. 7 Publikationen',
};
/** Ordered metric definitions for the researcher detail table. */
export interface MetricDef {
key: keyof ResearcherMetrics;
@@ -78,20 +78,6 @@
}
}
.warning {
display: inline-flex;
align-items: center;
gap: 3px;
color: var(--sg-warning);
cursor: help;
&__icon {
width: 13px;
height: 13px;
font-size: 13px;
}
}
.th-help {
display: inline-flex;
align-items: center;
@@ -12,7 +12,6 @@ import { MatButtonModule } from '@angular/material/button';
import { MatCardModule } from '@angular/material/card';
import { MatIconModule } from '@angular/material/icon';
import { MatTooltipModule } from '@angular/material/tooltip';
import {
MultiplierTag,
ResearcherSummary,
@@ -1,13 +1,22 @@
<app-page-container
[eyebrow]="'Multiplikatoren · ' + universityName()"
[title]="unavailable()?.title ?? name()"
[subtitle]="unavailable()?.body ?? null"
[titleTooltip]="unavailable() ? null : pageTooltip">
<div pageMeta class="meta-block">
<a class="back-link" routerLink="/multipliers">
<mat-icon>{{ ARROW_BACK_ICON }}</mat-icon>
Zurück zur Multiplikatoren-Übersicht
</a>
<h3 class="author-name">
@if (researcher()?.author_id; as authorId) {
<a
class="author-name__link"
[routerLink]="['/person', authorId, 'overview']"
[appComponentTooltip]="AuthorTooltipComponent"
[tooltipInputs]="{ authorId: authorId }"
tooltipMaxWidth="500px">
{{ name() }}
</a>
} @else {
{{ name() }}
}
</h3>
@if (!unavailable()) {
<div class="meta-line">
@if (careerBucket()) {
@@ -20,17 +29,6 @@
{{ fmtInt(nWorks()) }} Publikationen ·
{{ fmtInt(activeYears()) }} aktive Jahre
</span>
@if (suspicious()) {
<span
class="suspicious"
[matTooltip]="suspiciousTooltip"
matTooltipClass="sg-tooltip-wide"
matTooltipPosition="above">
<mat-icon>{{ WARNING_ICON }}</mat-icon>
Zusammengeführtes Profil · Daten vorsichtig interpretieren
<mat-icon class="help-icon">{{ HELP_OUTLINE_ICON }}</mat-icon>
</span>
}
</div>
@if (tags().length) {
<div class="tags">
@@ -147,8 +145,8 @@
</mat-icon>
</h2>
<p class="metrics-caption">
Rang 0–100 im Vergleich zu Personen derselben Karrierestufe.
Ab 85 % wird ein Rollen-Badge vergeben.
Rang 0–100 im Vergleich zu Personen derselben Karrierestufe. Ab
85 % wird ein Rollen-Badge vergeben.
</p>
@for (group of metricGroups(); track group.key) {
<div class="metric-group">
@@ -3,26 +3,6 @@
min-width: 0;
}
.back-link {
display: inline-flex;
align-items: center;
gap: 4px;
margin-bottom: 6px;
color: var(--sg-text-muted);
font-size: 13px;
text-decoration: none;
mat-icon {
font-size: 18px;
width: 18px;
height: 18px;
}
&:hover {
color: var(--sg-blue-highlight);
}
}
.meta-block {
margin-top: 8px;
}
@@ -47,28 +27,6 @@
margin: 2px 0 8px;
}
.suspicious {
display: inline-flex;
align-items: center;
gap: 4px;
color: var(--sg-error);
font-size: 12.5px;
cursor: help;
mat-icon {
font-size: 16px;
width: 16px;
height: 16px;
}
.help-icon {
color: var(--sg-text-soft);
font-size: 15px;
width: 15px;
height: 15px;
}
}
.tags {
display: flex;
flex-wrap: wrap;
@@ -236,7 +194,25 @@
line-height: 1.4;
}
}
.author-name {
margin: 0;
color: var(--sg-text);
}
.author-name__link {
color: inherit;
text-decoration: none;
&:hover {
text-decoration: underline;
}
&:focus-visible {
border-radius: 2px;
outline: 2px solid var(--sg-blue-highlight);
outline-offset: 2px;
}
}
.metric-label {
cursor: help;
text-decoration: underline dotted;
@@ -1,6 +1,13 @@
import { Component, computed, inject, input, TemplateRef, viewChild } from '@angular/core';
import {
Component,
computed,
inject,
input,
TemplateRef,
viewChild,
} from '@angular/core';
import { CommonModule } from '@angular/common';
import { Router, RouterModule } from '@angular/router';
import { Router, RouterLink } from '@angular/router';
import { MatButtonModule } from '@angular/material/button';
import { MatCardModule } from '@angular/material/card';
import { MatIconModule } from '@angular/material/icon';
@@ -36,8 +43,9 @@ import {
HELP_OUTLINE_ICON,
INFO_OUTLINE_ICON,
PERSON_OFF_ICON,
WARNING_ICON,
} from '../../../shared/ui/icons';
import { ComponentTooltipDirective } from '../../../directives/component-tooltip.directive';
import { AppAuthorTooltipComponent } from '../../../shared/ui/app-author-tooltip/app-author-tooltip.component';
const ROLE_ORDER = ['ego', 'cohort', 'mentee', 'industry', 'external'];
const FALLBACK_UNIVERSITY = 'Universität Duisburg-Essen';
@@ -70,7 +78,6 @@ interface MetricGroup {
standalone: true,
imports: [
CommonModule,
RouterModule,
MatButtonModule,
MatCardModule,
MatIconModule,
@@ -81,17 +88,18 @@ interface MetricGroup {
ChipComponent,
MultiplierRoleScoresComponent,
PageContainerComponent,
RouterLink,
ComponentTooltipDirective,
],
templateUrl: './researcher-network.component.html',
styleUrl: './researcher-network.component.scss',
})
export class ResearcherNetworkComponent {
readonly ARROW_BACK_ICON = ARROW_BACK_ICON;
readonly WARNING_ICON = WARNING_ICON;
readonly PERSON_OFF_ICON = PERSON_OFF_ICON;
readonly HELP_OUTLINE_ICON = HELP_OUTLINE_ICON;
readonly INFO_OUTLINE_ICON = INFO_OUTLINE_ICON;
readonly AuthorTooltipComponent = AppAuthorTooltipComponent;
readonly page = input.required<ResearcherPageState>();
private readonly router = inject(Router);
@@ -146,10 +154,11 @@ export class ResearcherNetworkComponent {
this.researcher()?.author_id ??
'Unbekannt',
);
readonly careerBucket = computed(() => this.researcher()?.career_bucket ?? null);
readonly careerBucket = computed(
() => this.researcher()?.career_bucket ?? null,
);
readonly activeYears = computed(() => this.researcher()?.active_years ?? 0);
readonly nWorks = computed(() => this.researcher()?.n_works ?? 0);
readonly suspicious = computed(() => this.researcher()?.suspicious_profile ?? false);
readonly tags = computed(() => this.researcher()?.tags ?? []);
readonly tagLabel = tagLabel;
readonly tagDescription = tagDescription;
@@ -159,9 +168,6 @@ export class ResearcherNetworkComponent {
readonly pageTooltip =
'Das Netzwerk zeigt, mit wem diese Person gemeinsam publiziert hat. Je dicker die Linie, desto häufiger haben die beiden zusammengearbeitet.';
readonly suspiciousTooltip =
'Bei diesem Profil wurden vermutlich mehrere Personen vermischt, zum Beispiel wegen gleicher Namen oder einer unplausibel langen Karriere. Die Angaben zu Publikationen, Netzwerk und Rollen sind deshalb unsicher.';
readonly rolesTooltip =
'Wie stark die drei Rollen ausgeprägt sind. Ab 85 % wird ein Badge vergeben.';
@@ -189,8 +195,9 @@ export class ResearcherNetworkComponent {
private readonly metricTemplate =
viewChild.required<TemplateRef<MetricRow>>('metricTemplate');
private readonly metricValueTemplate =
viewChild.required<TemplateRef<MetricRow>>('metricValueTemplate');
private readonly metricValueTemplate = viewChild.required<
TemplateRef<MetricRow>
>('metricValueTemplate');
private readonly metricRankTemplate =
viewChild.required<TemplateRef<MetricRow>>('metricRankTemplate');
private readonly metricHeader =
@@ -88,13 +88,13 @@
</div>
<mat-card-content class="uh-chart-viewport">
<div
echarts
[options]="level.options"
[autoResize]="true"
(chartClick)="onNodeClick($event, i)"
class="uh-chart"
[style.height.px]="level.height"></div>
@if (expanded()) {
<div
#chartHost
appPassiveWheel
class="uh-chart"
[style.height.px]="level.height"></div>
}
</mat-card-content>
</mat-card>
}
@@ -66,11 +66,14 @@
.uh-row {
display: flex;
flex-grow: 1;
flex-grow: 0;
flex-shrink: 0;
flex-basis: auto;
flex-direction: row;
flex-wrap: nowrap;
align-items: stretch;
gap: var(--uh-gap);
height: var(--uh-row-height);
overflow-x: auto;
overflow-y: hidden;
padding-bottom: 2px;
@@ -132,6 +135,7 @@
flex: 1 1 100%;
display: flex;
flex-direction: column;
min-height: 0;
overflow: hidden;
}
@@ -167,13 +171,14 @@
}
.uh-chart-viewport {
flex: 1 1 auto;
min-height: 0;
overflow-x: hidden;
overflow-y: auto;
height: 100%;
padding: 0 !important;
}
.uh-chart {
height: 100% !important;
width: 100%;
height: 100% !important;
}
@@ -1,6 +1,7 @@
import {
Component,
DestroyRef,
ElementRef,
OnInit,
signal,
inject,
@@ -10,10 +11,10 @@ import {
EventEmitter,
effect,
untracked,
viewChild,
} from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { Router, ActivatedRoute } from '@angular/router';
import { NgxEchartsDirective } from 'ngx-echarts';
import { MatProgressSpinnerModule } from '@angular/material/progress-spinner';
import { MatToolbarModule } from '@angular/material/toolbar';
import { MatCardModule } from '@angular/material/card';
@@ -21,7 +22,8 @@ import { MatButtonModule } from '@angular/material/button';
import { MatIconModule } from '@angular/material/icon';
import { MatChipsModule } from '@angular/material/chips';
import { MatTooltipModule } from '@angular/material/tooltip';
import type { EChartsOption } from 'echarts';
import type { ECharts, EChartsOption } from 'echarts';
import { PassiveWheelDirective } from '../../../directives/passive-wheel.directive';
import { CredentialService } from '../../../shared/services/credential.service';
import { ChartThemeService } from '../../../shared/services/chart-theme.service';
import { HierarchyEditDialogComponent } from './hierarchy-edit-dialog/hierarchy-edit-dialog.component';
@@ -48,6 +50,9 @@ interface TreeLevel {
const QUERY_PARAM_PATH = 'path';
const QUERY_PARAM_LANG = 'lang';
const QUERY_PARAM_ORGANIZATION_FOCUS = 'orgFocus';
const QUERY_PARAM_ORGANIZATION_FOCUS_PATH = 'orgFocusPath';
const QUERY_PARAM_ORGANIZATION_URL = 'orgUrl';
const LEAF_ROW_HEIGHT = 22;
const MIN_TREE_HEIGHT = 200;
@@ -64,7 +69,7 @@ const MIN_TREE_HEIGHT = 200;
selector: 'app-hierarchy-chart',
standalone: true,
imports: [
NgxEchartsDirective,
PassiveWheelDirective,
MatProgressSpinnerModule,
MatToolbarModule,
MatCardModule,
@@ -92,12 +97,27 @@ export class HierarchyChartComponent implements OnInit {
private readonly credentialService = inject(CredentialService);
private readonly orgminerService = inject(OrgminerService);
private readonly chartTheme = inject(ChartThemeService);
/** Reference of the theme colors used for the current chart options. */
private lastChartTheme = this.chartTheme.colors();
readonly loading = signal<boolean>(true);
readonly lang = signal<'de' | 'en'>('de');
readonly levels = signal<TreeLevel[]>([]);
/** Node highlighted after a badge navigation or an analysis click. */
readonly highlightedId = signal<string | null>(null);
private readonly chartHost =
viewChild<ElementRef<HTMLDivElement>>('chartHost');
private chart: ECharts | null = null;
private chartHostElement: HTMLDivElement | null = null;
private chartResizeObserver: ResizeObserver | null = null;
private chartInitToken = 0;
private readonly snackBar = inject(MatSnackBar);
private readonly idMap = new Map<string, RawNode>();
/** Several hierarchy nodes can share one URL; keep every candidate. */
private readonly urlToNodeIds = new Map<string, string[]>();
/** Last `orgFocus` value + path that was applied, so unrelated query changes don't re-focus. */
private lastFocusKey: string | null = null;
universityRoot: RawNode | null = null;
/**
@@ -109,6 +129,8 @@ export class HierarchyChartComponent implements OnInit {
private isOwnNavigation = false;
hierarchyData = input.required<HierarchyResponse>();
/** False while the parent expansion panel is collapsed. */
readonly expanded = input<boolean>(true);
pendingSuggestion = input<HierarchySuggestion | null>(null);
can_edit = computed(() => this.hierarchyData().can_edit ?? false);
can_suggest = computed(() => this.hierarchyData().can_suggest ?? false);
@@ -133,7 +155,10 @@ export class HierarchyChartComponent implements OnInit {
});
});
effect(() => {
this.chartTheme.colors();
const colors = this.chartTheme.colors();
if (colors === this.lastChartTheme) return;
this.lastChartTheme = colors;
untracked(() => {
if (!this.universityRoot) return;
this.levels.update((levels) =>
@@ -148,6 +173,15 @@ export class HierarchyChartComponent implements OnInit {
const suggestion = this.pendingSuggestion();
untracked(() => this.loadPendingSuggestionIntoEditor(suggestion));
});
effect(() => {
const levels = this.levels();
const expanded = this.expanded();
const host = this.chartHost()?.nativeElement ?? null;
const level = expanded ? (levels[levels.length - 1] ?? null) : null;
untracked(() => this.syncChart(host, level));
});
this.destroyRef.onDestroy(() => this.disposeChart());
}
ngOnInit(): void {
@@ -162,7 +196,37 @@ export class HierarchyChartComponent implements OnInit {
this.isOwnNavigation = false;
return;
}
const langParam = params.get(QUERY_PARAM_LANG);
if (langParam === 'de' || langParam === 'en') {
this.lang.set(langParam);
}
const focus = this.normalizeOrgUrl(
params.get(QUERY_PARAM_ORGANIZATION_FOCUS),
);
const focusPath = this.parseFocusPath(
params.get(QUERY_PARAM_ORGANIZATION_FOCUS_PATH),
);
const focusKey = focus
? `${focus}\u0000${focusPath.join('\u0000')}`
: null;
if (
focus &&
focusKey !== this.lastFocusKey &&
this.focusOrganization(focus, focusPath)
) {
this.lastFocusKey = focusKey;
return;
}
if (!focus) {
this.lastFocusKey = null;
}
this.restoreFromUrl(params);
this.highlightAnalyzedOrganization(
params.get(QUERY_PARAM_ORGANIZATION_URL),
);
});
this.initialized = true;
}
@@ -216,6 +280,7 @@ export class HierarchyChartComponent implements OnInit {
const copy = structuredClone(children ?? []) as RawNode[];
this.idMap.clear();
this.urlToNodeIds.clear();
this.assignIds(copy, 'root');
this.universityRoot = {
@@ -242,6 +307,16 @@ export class HierarchyChartComponent implements OnInit {
node.id = id;
if (registerInMap) {
this.idMap.set(id, node);
for (const link of [node.link_de, node.link_en]) {
const normalized = this.normalizeOrgUrl(link);
if (!normalized) continue;
const candidates = this.urlToNodeIds.get(normalized);
if (candidates) {
if (!candidates.includes(id)) candidates.push(id);
} else {
this.urlToNodeIds.set(normalized, [id]);
}
}
}
if (node.children?.length) {
this.assignIds(node.children, id, registerInMap);
@@ -276,6 +351,184 @@ export class HierarchyChartComponent implements OnInit {
this.updateQueryParams();
}
/* --------------------------- organization focus --------------------------- */
/**
* Normalizes a hierarchy organization URL the same way the backend does:
* trim, drop trailing slashes and the common `/index` suffix.
*/
private normalizeOrgUrl(value: string | null | undefined): string | null {
if (!value) return null;
const normalized = value.trim().replace(/\/+$/, '');
const withoutIndex = normalized.endsWith('/index')
? normalized.slice(0, -'/index'.length).replace(/\/+$/, '')
: normalized;
return withoutIndex || null;
}
private findNodeIdByUrl(
value: string | null | undefined,
expectedPath: string[] = [],
preferVisible = false,
): string | null {
const normalized = this.normalizeOrgUrl(value);
const candidates = normalized
? (this.urlToNodeIds.get(normalized) ?? [])
: [];
if (!candidates.length) return null;
// Hierarchy URLs are not unique (several nodes can link to the same site),
// so the index-provided name path decides which node is meant.
if (expectedPath.length) {
const pathMatch = candidates.find((id) =>
this.matchesNamePath(id, expectedPath),
);
if (pathMatch) return pathMatch;
}
// Reloads only carry `orgUrl`; prefer the candidate on the open path.
if (preferVisible) {
const visible = candidates.find((id) => this.isNodeVisible(id));
if (visible) return visible;
}
return candidates[0];
}
/** Parses the hierarchy path (`orgFocusPath`) sent by the person badge. */
private parseFocusPath(value: string | null | undefined): string[] {
if (!value) return [];
try {
const parsed: unknown = JSON.parse(value);
if (!Array.isArray(parsed)) return [];
return parsed
.filter((segment): segment is string => typeof segment === 'string')
.map((segment) => segment.trim())
.filter(Boolean);
} catch {
return [];
}
}
/** Ancestor + node names from the faculty down (synthetic `root` excluded). */
private nodeNamePath(nodeId: string): RawNode[] {
return [...this.ancestorIds(nodeId).slice(1), nodeId]
.map((id) => this.idMap.get(id))
.filter((node): node is RawNode => !!node);
}
private matchesNamePath(nodeId: string, expectedPath: string[]): boolean {
if (!expectedPath.length) return false;
const actual = this.nodeNamePath(nodeId);
if (actual.length !== expectedPath.length) return false;
return expectedPath.every((name, index) =>
this.nodeMatchesName(actual[index], name),
);
}
private nodeMatchesName(node: RawNode, expected: string): boolean {
const normalize = (value: string | null | undefined) =>
(value ?? '').replace(/\s+/g, ' ').trim().toLocaleLowerCase();
const wanted = normalize(expected);
return (
normalize(node.name_de) === wanted || normalize(node.name_en) === wanted
);
}
/** Mirrors `buildLevel`: a level shows its children and group grandchildren. */
private levelRendersNode(levelId: string, nodeId: string): boolean {
const level = this.idMap.get(levelId);
if (!level) return false;
if (level.id === nodeId) return true;
for (const child of level.children ?? []) {
if (child.id === nodeId) return true;
const isGroup = child.type === 'institutes' || child.type === 'chairs';
if (
isGroup &&
child.children?.some((grandchild) => grandchild.id === nodeId)
) {
return true;
}
}
return false;
}
private isNodeVisible(nodeId: string): boolean {
return this.levels().some((level) =>
this.levelRendersNode(level.id, nodeId),
);
}
/** Positional parent ids of a node, e.g. `root-2-0-5` -> `root`, `root-2`, `root-2-0`. */
private ancestorIds(nodeId: string): string[] {
const ids = ['root'];
const parts = nodeId.split('-');
for (let index = 2; index < parts.length; index++) {
ids.push(parts.slice(0, index).join('-'));
}
return ids;
}
/**
* Opens the levels that display the requested organization and highlights
* its node. Used by the person-page badge (`orgFocus` query param).
*/
private focusOrganization(
orgUrl: string,
expectedPath: string[] = [],
): boolean {
const nodeId = this.findNodeIdByUrl(orgUrl, expectedPath);
if (!nodeId) return false;
// Open the faculty level, not the group directly above the target: the
// faculty chart shows the organization inside the full faculty subtree.
// For deeper nodes, keep opening levels until the target is rendered.
const fullPath = [...this.ancestorIds(nodeId), nodeId];
let lastLevelIndex = fullPath.findIndex(
(id) => this.idMap.get(id)?.type === 'faculty',
);
if (lastLevelIndex < 0) {
lastLevelIndex = Math.max(0, fullPath.length - 2);
}
while (
lastLevelIndex < fullPath.length - 1 &&
!this.levelRendersNode(fullPath[lastLevelIndex], nodeId)
) {
lastLevelIndex++;
}
const levels = fullPath
.slice(0, lastLevelIndex + 1)
.map((id) => this.idMap.get(id))
.filter((node): node is RawNode => !!node)
.map((node) => this.buildLevel(node));
if (!levels.length) return false;
this.highlightedId.set(nodeId);
this.levels.set(levels);
this.updateQueryParams();
return true;
}
/** Keeps the analyzed organization highlighted after query-param navigation. */
private highlightAnalyzedOrganization(orgUrl: string | null): void {
const nodeId = this.findNodeIdByUrl(orgUrl, [], true);
if (!nodeId || nodeId === this.highlightedId()) return;
this.highlightedId.set(nodeId);
if (this.universityRoot) {
this.rebuildLevelsKeepingPath();
}
}
private setHighlightedNode(nodeId: string | null): void {
if (this.highlightedId() === nodeId) return;
this.highlightedId.set(nodeId);
if (this.universityRoot) {
this.rebuildLevelsKeepingPath();
}
}
/** Writes the current levels path + language into the URL as query params. */
private updateQueryParams(): void {
const path = this.levels()
@@ -361,6 +614,7 @@ export class HierarchyChartComponent implements OnInit {
}
private onLeafSelect(raw: RawNode): void {
this.setHighlightedNode(raw.id);
this.analyzeOrgEvent.emit({
name: raw.name_de ?? raw.name_en ?? '',
url: raw.link_de ?? raw.link_en ?? '',
@@ -369,6 +623,18 @@ export class HierarchyChartComponent implements OnInit {
/* ------------------------------ tree building ----------------------------- */
/** Extra ECharts item style that marks the focused/analyzed node. */
private highlightStyle(nodeId: string): Record<string, unknown> {
if (this.highlightedId() !== nodeId) return {};
const warning = this.chartTheme.colors().warning;
return {
borderColor: warning,
borderWidth: 3,
shadowBlur: 10,
shadowColor: warning,
};
}
private getLink(raw: RawNode): string | null | undefined {
return this.lang() === 'en'
? (raw.link_en ?? raw.link_de)
@@ -403,6 +669,7 @@ export class HierarchyChartComponent implements OnInit {
(isGroup
? this.chartTheme.colors().blueHighlight
: this.chartTheme.colors().success),
...this.highlightStyle(raw.id),
},
};
@@ -426,7 +693,15 @@ export class HierarchyChartComponent implements OnInit {
}
private buildLevel(raw: RawNode): TreeLevel {
const children = (raw.children || []).map((c) => this.toChartNode(c, true));
// Leaves inherit the icon of the group that contains them, including the
// direct children of a group that is itself the root of this level.
const parentType =
raw.type === 'institutes' || raw.type === 'chairs'
? raw.type
: undefined;
const children = (raw.children || []).map((c) =>
this.toChartNode(c, true, parentType),
);
const rootData = {
id: raw.id,
@@ -434,7 +709,10 @@ export class HierarchyChartComponent implements OnInit {
nodeType: raw.type,
hasChildren: true,
link: this.getLink(raw),
itemStyle: { color: raw['color'] || this.chartTheme.colors().primary },
itemStyle: {
color: raw['color'] || this.chartTheme.colors().primary,
...this.highlightStyle(raw.id),
},
children,
};
@@ -472,7 +750,7 @@ export class HierarchyChartComponent implements OnInit {
const colors = this.chartTheme.colors();
return {
backgroundColor: this.chartTheme.colors().backgroundColor,
backgroundColor: '#ffffff',
tooltip: {
trigger: 'item',
triggerOn: 'mousemove',
@@ -499,7 +777,7 @@ export class HierarchyChartComponent implements OnInit {
verticalAlign: 'middle',
align: 'right',
fontSize: 11,
color: colors.text,
color: 'black',
formatter: (params: any) => {
if (params.data.hasChildren) {
return '{bold|' + params.name + '}';
@@ -539,6 +817,70 @@ export class HierarchyChartComponent implements OnInit {
};
}
/* ------------------------------ chart instance ---------------------------- */
/**
* Owns the ECharts instance directly instead of delegating to ngx-echarts.
* This avoids two async `init()` calls racing when the options change while
* the chart is still being created (the "already initialized" warning).
*/
private syncChart(
host: HTMLDivElement | null,
level: TreeLevel | null,
): void {
if (!host || !level) {
this.disposeChart();
return;
}
if (this.chart && this.chartHostElement === host) {
this.chart.setOption(level.options, true);
return;
}
this.disposeChart();
this.chartHostElement = host;
const token = ++this.chartInitToken;
requestAnimationFrame(() => {
if (token !== this.chartInitToken || this.chartHostElement !== host) {
return;
}
void import('echarts').then(({ init }) => {
if (token !== this.chartInitToken || this.chartHostElement !== host) {
return;
}
const chart = init(host);
this.chart = chart;
chart.setOption(level.options, true);
chart.on('click', (params) => this.onChartNodeClick(params));
this.observeChartSize(host);
});
});
}
private onChartNodeClick(params: unknown): void {
const levelIndex = Math.max(0, this.levels().length - 1);
this.onNodeClick(params, levelIndex);
}
private observeChartSize(host: HTMLDivElement): void {
this.chartResizeObserver?.disconnect();
this.chartResizeObserver = new ResizeObserver(() => this.chart?.resize());
this.chartResizeObserver.observe(host);
}
private disposeChart(): void {
this.chartInitToken++;
this.chartResizeObserver?.disconnect();
this.chartResizeObserver = null;
this.chart?.dispose();
this.chart = null;
this.chartHostElement = null;
}
/* --------------------------------- saving -------------------------------- */
/**
@@ -551,7 +893,7 @@ export class HierarchyChartComponent implements OnInit {
this.orgminerService.saveHierarchy(children as any).subscribe({
next: (response) => {
this.snackBar.open('Hierarchy saved successfully', 'Close', {
this.snackBar.open('Hierarchie gespeichert.', 'OK', {
duration: 3000,
});
@@ -573,9 +915,13 @@ export class HierarchyChartComponent implements OnInit {
}
},
error: (error) => {
this.snackBar.open('Error saving hierarchy', 'Close', {
duration: 3000,
});
this.snackBar.open(
'Hierarchie konnte nicht gespeichert werden.',
'OK',
{
duration: 4000,
},
);
console.error('[HierarchyChart] error saving hierarchy:', error);
this.hierarchySaved.set(false);
},
@@ -25,9 +25,12 @@
</mat-expansion-panel-header>
<app-hierarchy-chart
[hierarchyData]="hierarchyData()"
[expanded]="hierarchyExpanded()"
[pendingSuggestion]="
suggestions().find((suggestion) => suggestion.status === 'new') ?? null
"
suggestions().find(
(suggestion) => suggestion.status === 'new'
) ?? null
"
(analyzeOrgEvent)="analyzeOrg($event)"
(suggestionSaved)="reloadSuggestions()" />
</mat-expansion-panel>
@@ -21,6 +21,8 @@ import { HierarchySuggestion } from '../../api/model/hierarchySuggestion';
import { PageContainerComponent } from '../../shared/ui/page-container/page-container.component';
const ORGANIZATION_URL_PARAM = 'orgUrl';
const ORGANIZATION_NAME_PARAM = 'orgName';
const ORGANIZATION_FOCUS_PARAM = 'orgFocus';
const ORGANIZATION_FOCUS_PATH_PARAM = 'orgFocusPath';
const ORGMINER_EXPANDED_PARAM = 'orgExpanded';
const ORGMINER_SELECTION_CATEGORY_PARAM = 'orgSelectionCategory';
const ORGMINER_SELECTION_INDEX_PARAM = 'orgSelectionIndex';
@@ -119,6 +121,8 @@ export class HierarchyComponent implements OnInit {
queryParams: {
[ORGANIZATION_URL_PARAM]: organizationUrl,
[ORGANIZATION_NAME_PARAM]: org.name,
[ORGANIZATION_FOCUS_PARAM]: null,
[ORGANIZATION_FOCUS_PATH_PARAM]: null,
[ORGMINER_EXPANDED_PARAM]: null,
[ORGMINER_SELECTION_CATEGORY_PARAM]: null,
[ORGMINER_SELECTION_INDEX_PARAM]: null,
@@ -4,6 +4,7 @@
subtitle="Suche nach Hochschulen, Forschungszentren und weiteren Einrichtungen.">
<app-card-search
[page]="page()"
[loading]="loading()"
[cardMinWidth]="550"
[cardTmp]="cardTmp"
[observers]="observers"
@@ -1,4 +1,4 @@
import { Component, computed, input } from '@angular/core';
import { Component, computed, inject, input } from '@angular/core';
import { InstitutionPage } from '../../api';
import { MatButtonModule } from '@angular/material/button';
import { MatCardModule } from '@angular/material/card';
@@ -14,6 +14,7 @@ import { FilterObserver } from '../../shared/ui/selected-filters/selected-filter
import { AppInstitutionCardComponent } from '../../shared/ui/app-institution-card/app-institution-card.component';
import { SEARCH_ICON } from '../../shared/ui/icons';
import { PageContainerComponent } from '../../shared/ui/page-container/page-container.component';
import { ResolverStateService } from '../../shared/services/resolver-state.service';
@Component({
selector: 'app-institutions',
@@ -32,6 +33,11 @@ import { PageContainerComponent } from '../../shared/ui/page-container/page-cont
export class InstitutionsComponent {
institutionPage = input.required<InstitutionPage>();
private readonly resolverState = inject(ResolverStateService);
readonly loading = computed(() =>
this.resolverState.isResolvingInside('/institutions'),
);
observers: FilterObserver[] = [
{
id: 'name',
@@ -1,14 +1,5 @@
<app-page-container>
<div class="detail-page">
<button
type="button"
class="back-link"
(click)="navigateBack()"
aria-label="Zurück zu den Nachrichten">
<mat-icon>{{ ARROW_BACK_ICON }}</mat-icon>
Alle Nachrichten
</button>
@if (loading) {
<app-loading
text="Nachricht wird geladen..."
@@ -3,29 +3,6 @@
min-width: 0;
}
.back-link {
display: inline-flex;
align-items: center;
gap: 6px;
background: none;
border: none;
cursor: pointer;
font-size: 14px;
color: var(--sg-text-muted);
padding: 0;
margin-bottom: 32px;
&:hover {
color: var(--sg-text);
}
mat-icon {
font-size: 18px;
width: 18px;
height: 18px;
}
}
.state {
display: flex;
flex-direction: column;
@@ -20,7 +20,6 @@ import { WorksService } from '../../api';
import { topicHierarchyColor } from '../../resolvers/utils/topic-colors';
import { LoadingComponent } from '../../shared/ui/loading/loading.component';
import {
ARROW_BACK_ICON,
CANCEL_ICON,
CHECK_CIRCLE_ICON,
CHEVRON_LEFT_ICON,
@@ -80,7 +79,6 @@ interface NewsArticleDetail {
styleUrl: './news-detail.component.scss',
})
export class NewsDetailComponent implements OnInit {
readonly ARROW_BACK_ICON = ARROW_BACK_ICON;
readonly NEWS_ICON = NEWS_ICON;
readonly SEARCH_OFF_ICON = SEARCH_OFF_ICON;
readonly CHECK_CIRCLE_ICON = CHECK_CIRCLE_ICON;
@@ -182,10 +180,6 @@ export class NewsDetailComponent implements OnInit {
});
}
navigateBack(): void {
this.router.navigate(['/news']);
}
formatDate(dateStr?: string | null): string {
if (!dateStr) return '-';
const date = new Date(dateStr);
@@ -1,14 +1,5 @@
<app-page-container>
<div class="detail-page">
<button
type="button"
class="back-link"
(click)="navigateBack()"
aria-label="Zurück zu den Patenten">
<mat-icon>{{ ARROW_BACK_ICON }}</mat-icon>
Alle Patente
</button>
@if (loading) {
<app-loading
text="Patent wird geladen..."
@@ -8,27 +8,6 @@
min-width: 0;
}
.back-link {
display: inline-flex;
align-items: center;
gap: 7px;
margin-bottom: 22px;
padding: 0;
border: 0;
background: transparent;
color: var(--sg-text-muted);
font-size: 13px;
font-weight: 600;
text-decoration: none;
cursor: pointer;
}
.back-link mat-icon {
width: 18px;
height: 18px;
font-size: 18px;
}
.hero {
display: grid;
grid-template-columns: minmax(0, 1fr) 420px;
@@ -1,4 +1,3 @@
import { Location } from '@angular/common';
import { Component, DestroyRef, OnInit, inject } from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { MatButtonModule } from '@angular/material/button';
@@ -16,7 +15,6 @@ import {
} from '../../resolvers/utils/topic-colors';
import { LoadingComponent } from '../../shared/ui/loading/loading.component';
import {
ARROW_BACK_ICON,
BUSINESS_ICON,
CATEGORY_ICON,
ENGINEERING_ICON,
@@ -58,7 +56,6 @@ import { PageContainerComponent } from '../../shared/ui/page-container/page-cont
styleUrl: './patent-detail.component.scss',
})
export class PatentDetailComponent implements OnInit {
readonly ARROW_BACK_ICON = ARROW_BACK_ICON;
readonly PATENT_ICON = PATENT_ICON;
readonly SEARCH_OFF_ICON = SEARCH_OFF_ICON;
readonly OPEN_IN_NEW_ICON = OPEN_IN_NEW_ICON;
@@ -76,7 +73,6 @@ export class PatentDetailComponent implements OnInit {
private readonly destroyRef = inject(DestroyRef);
private readonly route = inject(ActivatedRoute);
private readonly patentsService = inject(PatentsService);
private readonly location = inject(Location);
patent: PatentEntry | null = null;
loading = true;
@@ -104,10 +100,6 @@ export class PatentDetailComponent implements OnInit {
});
}
navigateBack(): void {
this.location.back();
}
formatDate(date: string | null | undefined): string {
return formatPatentDate(date);
}
@@ -10,17 +10,6 @@
? null
: 'Suche Patente aus EPO und USPTO und filtere nach Zeitraum, Themen und Klassifikationen.'
">
@if (showDetail && selectedPatent) {
<button
pageActions
mat-stroked-button
color="primary"
type="button"
(click)="closeDetail()">
← Zurück zu den Patenten
</button>
}
@if (error) {
<p class="state-message error">Fehler beim Laden der Patente.</p>
} @else if (showDetail && selectedPatent) {
@@ -24,6 +24,7 @@ import {
import { FilterCardComponent } from '../../shared/ui/filter-card/filter-card.component';
import { HELP_ICON, PATENT_ICON } from '../../shared/ui/icons';
import { PageContainerComponent } from '../../shared/ui/page-container/page-container.component';
import { BackNavigationService } from '../../shared/services/back-navigation.service';
type PatentSource = 'EPO' | 'USPTO';
@@ -69,6 +70,8 @@ export class PatentsComponent {
private route = inject(ActivatedRoute);
private patentsApi = inject(PatentsService);
private destroyRef = inject(DestroyRef);
private backNavigation = inject(BackNavigationService);
private unregisterLocalBack: (() => void) | null = null;
patents: PatentEntry[] = [];
total = 0;
@@ -92,6 +95,8 @@ export class PatentsComponent {
readonly expandedClassificationKeys = new Set<string>();
constructor() {
this.destroyRef.onDestroy(() => this.unregisterLocalBack?.());
this.route.queryParams
.pipe(takeUntilDestroyed(this.destroyRef))
.subscribe((qp) => {
@@ -181,12 +186,20 @@ export class PatentsComponent {
}
selectPatent(patent: PatentEntry): void {
this.unregisterLocalBack?.();
this.unregisterLocalBack = this.backNavigation.registerLocalBack(() =>
this.closeDetail(),
);
this.selectedPatent = patent;
this.showDetail = true;
this.expandedClassificationKeys.clear();
}
closeDetail(): void {
this.unregisterLocalBack?.();
this.unregisterLocalBack = null;
this.showDetail = false;
this.selectedPatent = null;
this.expandedClassificationKeys.clear();
@@ -53,6 +53,7 @@
<div class="institution-row">
<app-institution-chip
[institution]="inst"
[skText]="loading()"
size="mini"
[showIcon]="true"
[isClickable]="true"
@@ -34,7 +34,7 @@
<div class="toggle-group">
<mat-button-toggle-group
class="mat-button-toggle-group"
aria-label="Select view"
aria-label="Ansicht wählen"
(change)="onToggleChange($event)"
[value]="displayedTable()"
style="width: 100%">
@@ -33,10 +33,11 @@
(expandedChange)="onSubfieldLegendExpandedChange($event)">
</app-topic-legend>
<div class="view-toggle" aria-label="Ansicht wechseln">
<div class="view-toggle" role="group" aria-label="Ansicht wechseln">
<button
type="button"
[class.active]="timelineViewMode === 'years'"
[attr.aria-pressed]="timelineViewMode === 'years'"
(click)="setTimelineViewMode('years')">
Jahre
</button>
@@ -44,6 +45,7 @@
<button
type="button"
[class.active]="timelineViewMode === 'compact'"
[attr.aria-pressed]="timelineViewMode === 'compact'"
(click)="setTimelineViewMode('compact')">
Kompakt
</button>
@@ -51,6 +53,7 @@
<button
type="button"
[class.active]="timelineViewMode === 'wordcloud'"
[attr.aria-pressed]="timelineViewMode === 'wordcloud'"
(click)="setTimelineViewMode('wordcloud')">
Wordcloud
</button>
@@ -1,30 +0,0 @@
@if (loading) {
<div class="word-cloud-state">Forschungsthemen werden geladen ...</div>
} @else if (loadFailed) {
<div class="word-cloud-state">
Forschungsthemen konnten nicht geladen werden.
</div>
} @else if (words.length) {
<div class="word-cloud-chart">
@for (word of words; track word.name) {
<button
type="button"
class="word-cloud-word"
[class.word-cloud-word-active]="isWordActiveByLegend(word)"
[style.color]="word.color"
[style.fontSize.px]="word.fontSize"
[style.fontWeight]="word.fontWeight"
[disabled]="!word.topicId"
[attr.aria-label]="wordAriaLabel(word)"
[appComponentTooltip]="AppTopicTooltipComponent"
[tooltipInputs]="tooltipInputsFor(word)"
[tooltipDisabled]="!word.rawTopicId"
[tooltipMaxWidth]="'500px'"
(click)="selectWord(word)">
{{ word.name }}
</button>
}
</div>
} @else {
<p class="word-cloud-state">Keine Forschungsthemen gefunden.</p>
}
@@ -1,59 +0,0 @@
:host {
display: block;
min-height: 420px;
}
.word-cloud-chart {
width: 100%;
min-height: 420px;
display: flex;
flex-wrap: wrap;
align-content: center;
align-items: baseline;
justify-content: center;
gap: 0.35em 1em;
padding: 1.5rem 1rem;
box-sizing: border-box;
}
.word-cloud-word {
appearance: none;
border: none;
background: none;
padding: 0.1em 0.3em;
margin: 0;
border-radius: 6px;
font-family: 'Open Sans', Arial, sans-serif;
line-height: 1.1;
cursor: pointer;
transition:
transform 0.15s ease,
background-color 0.15s ease,
box-shadow 0.15s ease;
&:hover:not(:disabled),
&:focus-visible {
transform: scale(1.08);
outline: none;
}
&:disabled {
cursor: default;
}
}
.word-cloud-word-active {
background: color-mix(in srgb, currentColor 14%, transparent);
box-shadow: inset 0 0 0 1.5px currentColor;
}
.word-cloud-state {
margin: 0;
min-height: 420px;
display: flex;
align-items: center;
justify-content: center;
color: var(--sg-text-muted);
font-size: 14px;
text-align: center;
}
@@ -1,305 +0,0 @@
import { Component, EventEmitter, Input, Output } from '@angular/core';
import { ComponentTooltipDirective } from '../../../../directives/component-tooltip.directive';
import { AppTopicTooltipComponent } from '../../../../shared/ui/app-topic-tooltip/app-topic-tooltip.component';
import { topicHierarchyColor } from '../../../../resolvers/utils/topic-colors';
import {
getTopicLegendFieldId,
getTopicLegendSubfieldId,
TopicLegendTopic,
} from '../../../../resolvers/utils/topic-legend';
import type {
TopicTimelineElement,
TopicTimelineTopic,
} from '../research-timeline/research-timeline.component';
import {
formatYearRange,
normalizeSelectedYears,
} from '../../../../resolvers/utils/year-range';
import { workQueryParamKeys } from '../../../../resolvers/work-page.resolver';
interface WordTooltipInputs {
topicId: string;
secondaryActionLabel: string | null;
secondaryActionLink: unknown[] | null;
secondaryActionQueryParams: Record<string, string | number | number[]>;
}
export interface WordCloudWord {
name: string;
topicId: string;
rawTopicId: string;
fieldLegendId: string;
subfieldLegendId: string;
color: string;
fontSize: number;
fontWeight: number;
}
export interface ResearchWordcloud {
words: WordCloudWord[];
legendTopics: TopicLegendTopic[];
}
const displayedWordLimit = 30;
const minimumFontSize = 12;
const maximumFontSize = 32;
interface AggregatedTopic {
name: string;
count: number;
legendTopic: TopicLegendTopic;
}
export function buildResearchWordcloud(
elements: readonly TopicTimelineElement[],
startYear: number | undefined,
endYear: number | undefined,
): ResearchWordcloud {
const yearsInRange = elements.filter((element) =>
isWithinYearRange(element.year, startYear, endYear),
);
const aggregated = aggregateTopics(yearsInRange);
if (aggregated.size === 0) {
return { words: [], legendTopics: [] };
}
const displayed = Array.from(aggregated.values())
.sort(
(left, right) =>
right.count - left.count || left.name.localeCompare(right.name),
)
.slice(0, displayedWordLimit);
const intensity = buildIntensityScale(displayed);
const words = displayed.map((topic): WordCloudWord => {
const legendTopic = topic.legendTopic;
const scale = intensity(topic.count);
return {
name: topic.name,
topicId: legendTopic.id ?? '',
rawTopicId: stripOpenAlexId(legendTopic.id),
fieldLegendId: getTopicLegendFieldId(legendTopic),
subfieldLegendId: getTopicLegendSubfieldId(legendTopic),
color: topicHierarchyColor(legendTopic),
fontSize: Math.round(
minimumFontSize + scale * (maximumFontSize - minimumFontSize),
),
fontWeight: scale > 0.66 ? 800 : scale > 0.33 ? 600 : 400,
};
});
return {
words: centreWords(words),
legendTopics: displayed.map((topic) => topic.legendTopic),
};
}
function aggregateTopics(
elements: readonly TopicTimelineElement[],
): Map<string, AggregatedTopic> {
const aggregated = new Map<string, AggregatedTopic>();
for (const element of elements) {
for (const topic of element.primary_topics ?? []) {
if (!topic.name) {
continue;
}
const key = topic.id ?? topic.name;
const existing = aggregated.get(key);
if (existing) {
existing.count += topic.count;
continue;
}
aggregated.set(key, {
name: topic.name,
count: topic.count,
legendTopic: toLegendTopic(topic),
});
}
}
return aggregated;
}
function buildIntensityScale(
topics: readonly AggregatedTopic[],
): (count: number) => number {
const weights = topics.map((topic) => Math.sqrt(Math.max(topic.count, 0)));
const minimumWeight = Math.min(...weights);
const maximumWeight = Math.max(...weights);
if (maximumWeight === minimumWeight) {
return () => 0.5;
}
return (count) =>
(Math.sqrt(Math.max(count, 0)) - minimumWeight) /
(maximumWeight - minimumWeight);
}
function toLegendTopic(topic: TopicTimelineTopic): TopicLegendTopic {
return {
id: topic.id,
name: topic.name,
field_id: topic.field_id,
field_name: topic.field_name,
field_description: topic.field_description,
domain_id: topic.domain_id,
domain_name: topic.domain_name,
domain_description: topic.domain_description,
subfield_id: topic.subfield_id,
subfield_name: topic.subfield_name,
subfield_description: topic.subfield_description,
};
}
function isWithinYearRange(
year: number | undefined,
startYear: number | undefined,
endYear: number | undefined,
): boolean {
if (startYear !== undefined && (year === undefined || year < startYear)) {
return false;
}
if (endYear !== undefined && (year === undefined || year > endYear)) {
return false;
}
return true;
}
function centreWords(words: WordCloudWord[]): WordCloudWord[] {
const centred: WordCloudWord[] = [];
words.forEach((word, index) => {
if (index % 2 === 0) {
centred.push(word);
return;
}
centred.unshift(word);
});
return centred;
}
function stripOpenAlexId(id: string | null | undefined): string {
return (id ?? '').replace('https://openalex.org/', '');
}
@Component({
selector: 'app-research-wordcloud',
standalone: true,
imports: [ComponentTooltipDirective],
templateUrl: './research-wordcloud.component.html',
styleUrl: './research-wordcloud.component.scss',
})
export class ResearchWordcloudComponent {
readonly AppTopicTooltipComponent = AppTopicTooltipComponent;
@Input() set words(value: WordCloudWord[]) {
this._words = value;
this.rebuildTooltipInputs();
}
get words(): WordCloudWord[] {
return this._words;
}
@Input() set personPublicationsLink(value: unknown[] | null) {
this._personPublicationsLink = value;
this.rebuildTooltipInputs();
}
@Input() set personName(value: string) {
this._personName = value;
this.rebuildTooltipInputs();
}
@Input() set selectedYears(value: number[]) {
this._selectedYears = normalizeSelectedYears(value);
this.rebuildTooltipInputs();
}
@Input() loading = false;
@Input() loadFailed = false;
@Input() activeFieldIds: ReadonlySet<string> = new Set();
@Input() activeSubfieldIds: ReadonlySet<string> = new Set();
@Output() wordSelect = new EventEmitter<WordCloudWord>();
private _words: WordCloudWord[] = [];
private _personPublicationsLink: unknown[] | null = null;
private _personName = '';
private _selectedYears: number[] = [];
private tooltipInputsByTopic = new Map<string, WordTooltipInputs>();
selectWord(word: WordCloudWord): void {
if (!word.topicId) {
return;
}
this.wordSelect.emit(word);
}
isWordActiveByLegend(word: WordCloudWord): boolean {
return (
this.activeFieldIds.has(word.fieldLegendId) ||
(word.subfieldLegendId.length > 0 &&
this.activeSubfieldIds.has(word.subfieldLegendId))
);
}
tooltipInputsFor(word: WordCloudWord): WordTooltipInputs | null {
return this.tooltipInputsByTopic.get(word.topicId) ?? null;
}
wordAriaLabel(word: WordCloudWord): string {
return `${this.publicationsLabel()} zum Thema ${word.name}${this.yearRangeSuffix()}`;
}
private publicationsLabel(): string {
return this._personName
? `Publikationen von ${this._personName}`
: 'Publikationen dieser Person';
}
private yearRangeSuffix(): string {
return this._selectedYears.length > 0
? ` ${formatYearRange(this._selectedYears)}`
: '';
}
private rebuildTooltipInputs(): void {
const label = `${this.publicationsLabel()}${this.yearRangeSuffix()}`;
const link = this._personPublicationsLink;
this.tooltipInputsByTopic = new Map(
this._words
.filter((word) => word.topicId)
.map((word) => [
word.topicId,
{
topicId: word.rawTopicId,
secondaryActionLabel: link ? label : null,
secondaryActionLink: link,
secondaryActionQueryParams: {
[workQueryParamKeys.page]: 0,
...(this._selectedYears.length > 0
? { [workQueryParamKeys.years]: this._selectedYears }
: {}),
[workQueryParamKeys.topicId]: word.topicId,
},
},
]),
);
}
}
@@ -22,16 +22,22 @@
(yearSelect)="onTimelineYearSelect($event)"
(loadEarlierYears)="onTimelineLoadEarlierYears()"
(legendSelectionChange)="onLegendSelectionChange($event)">
<app-research-wordcloud
<app-keyword-wordcloud
timeline-wordcloud-content
variant="bare"
[title]="null"
[words]="wordCloudWords"
[loading]="loadingWordCloud"
[loadFailed]="wordCloudLoadFailed"
[activeFieldIds]="activeLegendFieldIds"
[activeSubfieldIds]="activeLegendSubfieldIds"
[selectedYears]="wordCloudYears"
[personName]="personName"
[personPublicationsLink]="personPublicationsLink"
(wordSelect)="onWordClick($event)" />
loadingMessage="Forschungsthemen werden geladen ..."
loadFailedMessage="Forschungsthemen konnten nicht geladen werden."
emptyTitle="Keine Forschungsthemen gefunden."
emptyMessage=""
[interactive]="true"
chartAriaLabel="Wordcloud der Forschungsthemen"
[isWordActive]="isWordActiveByLegend"
[wordAriaLabel]="wordCloudAriaLabel"
[wordTooltip]="wordCloudTooltip"
(wordClick)="onWordClick($event)" />
</app-research-timeline>
</section>
@@ -14,20 +14,33 @@ import {
} from './components/research-timeline/research-timeline.component';
import {
buildResearchWordcloud,
ResearchWordcloudComponent,
WordCloudWord,
} from './components/research-wordcloud/research-wordcloud.component';
} from './research-wordcloud.utils';
import { workQueryParamKeys } from '../../resolvers/work-page.resolver';
import {
TopicLegendSelectionState,
TopicLegendTopic,
} from '../../resolvers/utils/topic-legend';
import { PersonDataResolved } from '../../resolvers/person.resolver';
import { formatYearRange } from '../../resolvers/utils/year-range';
import { AppTopicTooltipComponent } from '../../shared/ui/app-topic-tooltip/app-topic-tooltip.component';
import {
KeywordWordcloudComponent,
WordCloudTooltipConfig,
WordCloudWordData,
} from '../../shared/ui/keyword-wordcloud/keyword-wordcloud.component';
type WordTooltipInputs = {
topicId: string;
secondaryActionLabel: string | null;
secondaryActionLink: unknown[] | null;
secondaryActionQueryParams: Record<string, string | number | number[]>;
};
@Component({
selector: 'app-person-overview',
standalone: true,
imports: [ResearchTimelineComponent, ResearchWordcloudComponent],
imports: [ResearchTimelineComponent, KeywordWordcloudComponent],
templateUrl: './person-overview.component.html',
styleUrl: './person-overview.component.scss',
})
@@ -73,6 +86,27 @@ export class PersonOverviewComponent implements OnInit {
personName = '';
personPublicationsLink: unknown[] | null = null;
readonly wordCloudTooltip: WordCloudTooltipConfig = {
component: AppTopicTooltipComponent,
inputs: (word) => this.tooltipInputsFor(word as WordCloudWord),
disabled: (word) => !(word as WordCloudWord).rawTopicId,
maxWidth: '500px',
};
readonly isWordActiveByLegend = (word: WordCloudWordData): boolean => {
const topicWord = word as WordCloudWord;
return (
this.activeLegendFieldIds.has(topicWord.fieldLegendId) ||
(topicWord.subfieldLegendId.length > 0 &&
this.activeLegendSubfieldIds.has(topicWord.subfieldLegendId))
);
};
readonly wordCloudAriaLabel = (word: WordCloudWordData): string => {
const topicWord = word as WordCloudWord;
return `${this.publicationsLabel()} zum Thema ${topicWord.name}${this.yearRangeSuffix()}`;
};
ngOnInit(): void {
combineLatest(this.route.pathFromRoot.map((route) => route.paramMap))
.pipe(
@@ -222,8 +256,9 @@ export class PersonOverviewComponent implements OnInit {
this.loadCompleteTopicTimeline(this.currentAuthorId);
}
onWordClick(word: WordCloudWord): void {
if (!word.topicId) return;
onWordClick(word: WordCloudWordData): void {
const topicWord = word as WordCloudWord;
if (!topicWord.topicId) return;
void this.router.navigate(['../publications'], {
relativeTo: this.route,
queryParams: {
@@ -231,7 +266,7 @@ export class PersonOverviewComponent implements OnInit {
...(this.wordCloudYears.length > 0
? { [workQueryParamKeys.years]: this.wordCloudYears }
: {}),
[workQueryParamKeys.topicId]: word.topicId,
[workQueryParamKeys.topicId]: topicWord.topicId,
},
});
}
@@ -241,6 +276,39 @@ export class PersonOverviewComponent implements OnInit {
this.activeLegendSubfieldIds = selection.subfieldIds;
}
private tooltipInputsFor(word: WordCloudWord): WordTooltipInputs | null {
if (!word.topicId) return null;
const link = this.personPublicationsLink;
return {
topicId: word.rawTopicId,
secondaryActionLabel: link
? `${this.publicationsLabel()}${this.yearRangeSuffix()}`
: null,
secondaryActionLink: link,
secondaryActionQueryParams: {
[workQueryParamKeys.page]: 0,
...(this.wordCloudYears.length > 0
? { [workQueryParamKeys.years]: this.wordCloudYears }
: {}),
[workQueryParamKeys.topicId]: word.topicId,
},
};
}
private publicationsLabel(): string {
return this.personName
? `Publikationen von ${this.personName}`
: 'Publikationen dieser Person';
}
private yearRangeSuffix(): string {
return this.wordCloudYears.length > 0
? ` ${formatYearRange(this.wordCloudYears)}`
: '';
}
private findAuthorId(paramMaps: readonly ParamMap[]): string {
return (
paramMaps
@@ -0,0 +1,166 @@
import { topicHierarchyColor } from '../../resolvers/utils/topic-colors';
import {
getTopicLegendFieldId,
getTopicLegendSubfieldId,
TopicLegendTopic,
} from '../../resolvers/utils/topic-legend';
import type { WordCloudWordData } from '../../shared/ui/keyword-wordcloud/keyword-wordcloud.component';
import type {
TopicTimelineElement,
TopicTimelineTopic,
} from './components/research-timeline/research-timeline.component';
export interface WordCloudWord extends WordCloudWordData {
topicId: string;
rawTopicId: string;
fieldLegendId: string;
subfieldLegendId: string;
color: string;
fontSize: number;
fontWeight: number;
}
export interface ResearchWordcloud {
words: WordCloudWord[];
legendTopics: TopicLegendTopic[];
}
const displayedWordLimit = 30;
const minimumFontSize = 12;
const maximumFontSize = 32;
interface AggregatedTopic {
name: string;
count: number;
legendTopic: TopicLegendTopic;
}
export function buildResearchWordcloud(
elements: readonly TopicTimelineElement[],
startYear: number | undefined,
endYear: number | undefined,
): ResearchWordcloud {
const yearsInRange = elements.filter((element) =>
isWithinYearRange(element.year, startYear, endYear),
);
const aggregated = aggregateTopics(yearsInRange);
if (aggregated.size === 0) {
return { words: [], legendTopics: [] };
}
const displayed = Array.from(aggregated.values())
.sort(
(left, right) =>
right.count - left.count || left.name.localeCompare(right.name),
)
.slice(0, displayedWordLimit);
const intensity = buildIntensityScale(displayed);
const words = displayed.map((topic): WordCloudWord => {
const legendTopic = topic.legendTopic;
const scale = intensity(topic.count);
return {
name: topic.name,
topicId: legendTopic.id ?? '',
rawTopicId: stripOpenAlexId(legendTopic.id),
fieldLegendId: getTopicLegendFieldId(legendTopic),
subfieldLegendId: getTopicLegendSubfieldId(legendTopic),
color: topicHierarchyColor(legendTopic),
fontSize: Math.round(
minimumFontSize + scale * (maximumFontSize - minimumFontSize),
),
fontWeight: scale > 0.66 ? 800 : scale > 0.33 ? 600 : 400,
};
});
return {
words,
legendTopics: displayed.map((topic) => topic.legendTopic),
};
}
function aggregateTopics(
elements: readonly TopicTimelineElement[],
): Map<string, AggregatedTopic> {
const aggregated = new Map<string, AggregatedTopic>();
for (const element of elements) {
for (const topic of element.primary_topics ?? []) {
if (!topic.name) {
continue;
}
const key = topic.id ?? topic.name;
const existing = aggregated.get(key);
if (existing) {
existing.count += topic.count;
continue;
}
aggregated.set(key, {
name: topic.name,
count: topic.count,
legendTopic: toLegendTopic(topic),
});
}
}
return aggregated;
}
function buildIntensityScale(
topics: readonly AggregatedTopic[],
): (count: number) => number {
const weights = topics.map((topic) => Math.sqrt(Math.max(topic.count, 0)));
const minimumWeight = Math.min(...weights);
const maximumWeight = Math.max(...weights);
if (maximumWeight === minimumWeight) {
return () => 0.5;
}
return (count) =>
(Math.sqrt(Math.max(count, 0)) - minimumWeight) /
(maximumWeight - minimumWeight);
}
function toLegendTopic(topic: TopicTimelineTopic): TopicLegendTopic {
return {
id: topic.id,
name: topic.name,
field_id: topic.field_id,
field_name: topic.field_name,
field_description: topic.field_description,
domain_id: topic.domain_id,
domain_name: topic.domain_name,
domain_description: topic.domain_description,
subfield_id: topic.subfield_id,
subfield_name: topic.subfield_name,
subfield_description: topic.subfield_description,
};
}
function isWithinYearRange(
year: number | undefined,
startYear: number | undefined,
endYear: number | undefined,
): boolean {
if (startYear !== undefined && (year === undefined || year < startYear)) {
return false;
}
if (endYear !== undefined && (year === undefined || year > endYear)) {
return false;
}
return true;
}
function stripOpenAlexId(id: string | null | undefined): string {
return (id ?? '').replace('https://openalex.org/', '');
}
@@ -29,27 +29,61 @@
}}</mat-icon>
</button>
</div>
@if (resolvedInstitution(); as inst) {
@if (resolvedInstitution() || verifiedOrganizations().length > 0) {
<div class="institution-line">
<app-institution-chip
[institution]="inst"
size="normal"
[showIcon]="true"
[isClickable]="false" />
@if (secondaryInstitutions().length > 0) {
<button
type="button"
class="more-institutions-btn"
[appComponentTooltip]="PersonInstitutionTooltipListComponent"
[tooltipInputs]="{ institutions: secondaryInstitutions() }"
[attr.aria-label]="
secondaryInstitutions().length + ' weitere Institutionen'
">
<mat-icon class="more-info-icon">{{ MORE_INFO_ICON }}</mat-icon>
<span class="count-text"
>+{{ secondaryInstitutions().length }}</span
>
</button>
@if (resolvedInstitution(); as inst) {
<app-institution-chip
[institution]="inst"
size="normal"
[showIcon]="true"
[isClickable]="false" />
@if (secondaryInstitutions().length > 0) {
<button
type="button"
class="more-institutions-btn"
[appComponentTooltip]="PersonInstitutionTooltipListComponent"
[tooltipInputs]="{ institutions: secondaryInstitutions() }"
[attr.aria-label]="
secondaryInstitutions().length + ' weitere Institutionen'
">
<mat-icon class="more-info-icon">{{ MORE_INFO_ICON }}</mat-icon>
<span class="count-text"
>+{{ secondaryInstitutions().length }}</span
>
</button>
}
}
@for (org of verifiedOrganizations(); track $index) {
@if (canOpenOrganizationHierarchy(org)) {
<button
type="button"
class="verified-org-chip"
[matTooltip]="
'Verifizierte Organisation: ' +
org.org_name +
' – Hierarchie öffnen'
"
matTooltipPosition="right"
[matTooltipShowDelay]="250"
[attr.aria-label]="
'Verifizierte Organisation: ' +
org.org_name +
'. Hierarchie öffnen.'
"
(click)="openOrganizationHierarchy(org)">
<mat-icon>{{ VERIFIED_ICON }}</mat-icon>
<span>{{ org.org_name }}</span>
</button>
} @else {
<span
class="verified-org-chip static"
[matTooltip]="'Verifizierte Organisation: ' + org.org_name"
matTooltipPosition="right"
[matTooltipShowDelay]="250">
<mat-icon>{{ VERIFIED_ICON }}</mat-icon>
<span>{{ org.org_name }}</span>
</span>
}
}
</div>
}
@@ -146,6 +146,55 @@
font-size: 13px;
}
.verified-org-chip {
display: inline-flex;
align-items: center;
gap: 6px;
min-height: 24px;
max-width: 100%;
padding: 2px 10px;
border: 1px solid var(--sg-border);
border-radius: 999px;
background: var(--sg-surface-muted);
color: var(--sg-text);
font-size: 13px;
font-weight: 600;
line-height: 1.2;
text-decoration: none;
transition:
border-color 0.15s,
background 0.15s;
span {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
mat-icon {
flex: 0 0 auto;
width: 16px;
height: 16px;
font-size: 16px;
color: var(--sg-success);
}
&[type='button'] {
cursor: pointer;
}
&[type='button']:hover,
&[type='button']:focus-visible {
border-color: var(--sg-success);
background: var(--sg-primary-soft);
outline: none;
}
&.static {
cursor: default;
}
}
.stats-line {
display: flex;
align-items: center;
@@ -39,12 +39,17 @@ import { CareerStageChipComponent } from '../../shared/ui/career-stage-chip/care
import { AppInstitutionChipComponent } from '../../shared/ui/app-institution-chip/app-institution-chip.component';
import { ComponentTooltipDirective } from '../../directives/component-tooltip.directive';
import { PersonInstitutionTooltipListComponent } from '../../shared/ui/person-institution-tooltip-list/person-institution-tooltip-list.component';
import { DehydratedInstitution, WorksService } from '../../api';
import {
DehydratedInstitution,
VerifiedOrganization,
WorksService,
} from '../../api';
import { LoadingComponent } from '../../shared/ui/loading/loading.component';
import { PersonBioResolved } from '../../resolvers/person-bio.resolver';
import { PersonDataResolved } from '../../resolvers/person.resolver';
import { BookmarkService } from '../../shared/services/bookmark.service';
import { AuthorAffiliationService } from '../../shared/services/author-affiliation.service';
import { CredentialService } from '../../shared/services/credential.service';
import { collaborationGraphQueryParamKeys } from '../../resolvers/collaboration-graph.resolver';
import { workQueryParamKeys } from '../../resolvers/work-page.resolver';
import {
@@ -73,6 +78,16 @@ import {
} from '../../shared/ui/icons';
import { PageContainerComponent } from '../../shared/ui/page-container/page-container.component';
/** Accepts raw and full-URL OpenAlex IDs, e.g. `I123` or `.../I123`. */
const normalizeInstitutionId = (
value: string | null | undefined,
): string =>
(value ?? '')
.trim()
.replace(/^https:\/\/openalex\.org\//i, '')
.replace(/\/+$/, '')
.toUpperCase();
@Component({
selector: 'app-person',
imports: [
@@ -116,6 +131,7 @@ export class PersonComponent {
private readonly destroyRef = inject(DestroyRef);
readonly bookmarkService = inject(BookmarkService);
private readonly authorAffiliationService = inject(AuthorAffiliationService);
private readonly credentialService = inject(CredentialService);
canFetchGdprRelevantData = input.required<boolean>();
@@ -206,6 +222,33 @@ export class PersonComponent {
.subscribe();
}
canOpenOrganizationHierarchy(organization: VerifiedOrganization): boolean {
return (
this.canOpenVerifiedOrganizationHierarchy() &&
!!organization.org_uri &&
(organization.org_hierarchy_path?.length ?? 0) > 0
);
}
openOrganizationHierarchy(organization: VerifiedOrganization): void {
if (!this.canOpenOrganizationHierarchy(organization)) return;
void this.router.navigate(['/hierarchy'], {
queryParams: {
orgFocus: organization.org_uri,
orgFocusPath: JSON.stringify(organization.org_hierarchy_path ?? []),
hierarchyExpanded: true,
organizationExpanded: false,
orgUrl: null,
orgName: null,
orgExpanded: null,
orgSelectionCategory: null,
orgSelectionIndex: null,
classifiedCategory: null,
classifiedPage: null,
},
});
}
readonly personBio = toSignal(
combineLatest([this.activatedRoute.data, toObservable(this.person)]).pipe(
switchMap(([data, person]) => {
@@ -249,6 +292,35 @@ export class PersonComponent {
readonly secondaryInstitutions = computed<DehydratedInstitution[]>(() =>
this.authorAffiliationService.resolveSecondaryInstitutions(this.person()),
);
readonly verifiedOrganizationData = toSignal(
this.activatedRoute.data.pipe(
switchMap((data) => {
const resolved = data['personData'] as PersonDataResolved | undefined;
return resolved?.verifiedOrganizations$ ?? of(null);
}),
),
{ initialValue: null },
);
readonly verifiedOrganizations = computed(
() => this.verifiedOrganizationData()?.organizations ?? [],
);
/**
* Verified organizations come from one institution's OrgMiner data. Only
* users of that institution have a hierarchy where the nodes can be found.
*/
readonly canOpenVerifiedOrganizationHierarchy = computed(() => {
const userInstitutionId = normalizeInstitutionId(
this.credentialService.effectiveInstitutionId(),
);
const dataInstitutionId = normalizeInstitutionId(
this.verifiedOrganizationData()?.institution_id,
);
return (
!!userInstitutionId &&
!!dataInstitutionId &&
userInstitutionId === dataInstitutionId
);
});
readonly worksCount = computed(() => this.person()?.works_count ?? null);
readonly citedByCount = computed(() => this.person()?.cited_by_count ?? null);
readonly h_index = computed(
@@ -172,7 +172,4 @@ export class BundDetailsComponent implements OnInit {
return 'var(--sg-text-muted)';
}
}
goBack(): void {
window.history.back();
}
}
@@ -279,8 +279,4 @@ export class DfgDetailsComponent implements OnInit {
queryParams: { search: institutionName },
});
}
goBack(): void {
window.history.back();
}
}
@@ -4,6 +4,7 @@
subtitle="Durchsuche geförderte Projekte aus DFG-, EU- und Bundesdatenquellen.">
<app-card-search
[page]="page()"
[loading]="loading()"
[cardTmp]="cardTmp"
[additionalFiltersTmp]="additionalFiltersTmp"
[cardMinWidth]="380"
@@ -1,4 +1,4 @@
import { Component, computed, input, signal } from '@angular/core';
import { Component, computed, inject, input, signal } from '@angular/core';
import { FundingProjectPage, ProjectType } from '../../api';
import { MatIconModule } from '@angular/material/icon';
import { MatCardModule } from '@angular/material/card';
@@ -16,6 +16,7 @@ import { FilterObserver } from '../../shared/ui/selected-filters/selected-filter
import { FilterCardComponent } from '../../shared/ui/filter-card/filter-card.component';
import { SEARCH_ICON } from '../../shared/ui/icons';
import { PageContainerComponent } from '../../shared/ui/page-container/page-container.component';
import { ResolverStateService } from '../../shared/services/resolver-state.service';
@Component({
selector: 'app-projects',
@@ -36,6 +37,11 @@ import { PageContainerComponent } from '../../shared/ui/page-container/page-cont
export class ProjectsComponent {
fundingProjectPage = input.required<FundingProjectPage>();
private readonly resolverState = inject(ResolverStateService);
readonly loading = computed(() =>
this.resolverState.isResolvingInside('/projects'),
);
page = computed<Page>(() => ({
page: this.fundingProjectPage().page || 0,
size: this.fundingProjectPage().size || 10,
@@ -1,14 +1,5 @@
<app-page-container>
<div class="detail-page">
<button
type="button"
class="back-link"
(click)="navigateBack()"
[attr.aria-label]="returnAriaLabel">
<mat-icon>{{ ARROW_BACK_ICON }}</mat-icon>
{{ returnLabel }}
</button>
@if (loading) {
<app-loading
text="Publikation wird geladen..."
@@ -8,27 +8,6 @@
min-width: 0;
}
.back-link {
display: inline-flex;
align-items: center;
gap: 7px;
margin-bottom: 22px;
padding: 0;
border: 0;
background: transparent;
color: var(--sg-text-muted);
font-size: 13px;
font-weight: 600;
text-decoration: none;
cursor: pointer;
}
.back-link mat-icon {
width: 18px;
height: 18px;
font-size: 18px;
}
.hero {
display: grid;
grid-template-columns: minmax(0, 1fr) 420px;
@@ -24,8 +24,8 @@ import { LanguageCodePipe } from '../../shared/pipes/language-code.pipe';
import { WorkPrimaryCategoryPipe } from '../../shared/pipes/work-primary-category.pipe';
import { ResearchProfileComponent } from './research-profile/research-profile.component';
import { PageContainerComponent } from '../../shared/ui/page-container/page-container.component';
import { BackNavigationService } from '../../shared/services/back-navigation.service';
import {
ARROW_BACK_ICON,
CHEVRON_LEFT_ICON,
CHEVRON_RIGHT_ICON,
CITATION_ICON,
@@ -82,7 +82,6 @@ interface InstitutionDetail {
styleUrl: './publication-detail.component.scss',
})
export class PublicationDetailComponent implements OnInit {
readonly ARROW_BACK_ICON = ARROW_BACK_ICON;
readonly PUBLICATION_ICON = PUBLICATION_ICON;
readonly SEARCH_OFF_ICON = SEARCH_OFF_ICON;
readonly OPEN_IN_NEW_ICON = OPEN_IN_NEW_ICON;
@@ -109,6 +108,7 @@ export class PublicationDetailComponent implements OnInit {
private readonly httpClient = inject(HttpClient);
private readonly location = inject(Location);
private readonly router = inject(Router);
private readonly backNavigation = inject(BackNavigationService);
private readonly worksService = inject(WorksService);
workClassification = input.required<WorkClassification | null>();
@@ -130,20 +130,22 @@ export class PublicationDetailComponent implements OnInit {
readonly institutionsPageSize = 5;
returnUrl: string | null = null;
returnLabel = 'Alle Publikationen';
returnAriaLabel = 'Zurück zu den Publikationen';
ngOnInit(): void {
this.loading = true;
const navigationState = this.location.getState() as {
returnUrl?: string;
returnLabel?: string;
} | null;
if (navigationState?.returnUrl) {
this.returnUrl = navigationState.returnUrl;
this.returnLabel = navigationState.returnLabel ?? 'Zurück';
this.returnAriaLabel = `Zurück zu ${this.returnLabel}`;
// The topbar back button should return to the page the user came from,
// not to an unrelated history entry.
const unregister = this.backNavigation.registerLocalBack(() =>
this.navigateBack(),
);
this.destroyRef.onDestroy(unregister);
}
this.route.data.pipe(takeUntilDestroyed(this.destroyRef)).subscribe({
@@ -4,6 +4,7 @@
subtitle="Durchsuche wissenschaftliche Publikationen nach Titel, Autor:innen, Themen oder Institutionen.">
<app-card-search
[page]="page()"
[loading]="loading()"
[cardMinWidth]="500"
[cardTmp]="cardTmp"
[additionalFiltersTmp]="additionalFiltersTmp"
@@ -19,6 +19,7 @@ import { PublicationFilterComponent } from '../../shared/ui/publication-filters/
import { SelectorOption } from '../../shared/ui/query-param-selector/query-param-selector.component';
import { workQueryParamKeys } from '../../resolvers/work-page.resolver';
import { PageContainerComponent } from '../../shared/ui/page-container/page-container.component';
import { ResolverStateService } from '../../shared/services/resolver-state.service';
@Component({
selector: 'app-publications',
@@ -34,6 +35,11 @@ import { PageContainerComponent } from '../../shared/ui/page-container/page-cont
export class PublicationsComponent {
private readonly route = inject(ActivatedRoute);
private readonly router = inject(Router);
private readonly resolverState = inject(ResolverStateService);
readonly loading = computed(() =>
this.resolverState.isResolvingInside('/publications'),
);
workPage = input.required<WorkPageV2>();
selectedAuthorsPage = input.required<AuthorPage>();
@@ -4,6 +4,7 @@
subtitle="Entdecke Forschungsfelder nach Namen, Publikationen und Zitierungen.">
<app-card-search
[page]="page()"
[loading]="loading()"
[cardMinWidth]="550"
[cardTmp]="cardTmp"
[observers]="observers"
@@ -1,4 +1,4 @@
import { Component, computed, input } from '@angular/core';
import { Component, computed, inject, input } from '@angular/core';
import {
CardSearchComponent,
Page,
@@ -10,20 +10,22 @@ import { topicQueryParamKeys } from '../../resolvers/topic-page.resolver';
import { SelectorOption } from '../../shared/ui/query-param-selector/query-param-selector.component';
import { SEARCH_ICON } from '../../shared/ui/icons';
import { PageContainerComponent } from '../../shared/ui/page-container/page-container.component';
import { ResolverStateService } from '../../shared/services/resolver-state.service';
@Component({
selector: 'app-topics',
imports: [
CardSearchComponent,
AppTopicCardComponent,
PageContainerComponent,
],
imports: [CardSearchComponent, AppTopicCardComponent, PageContainerComponent],
templateUrl: './topics.component.html',
styleUrl: './topics.component.scss',
})
export class TopicsComponent {
topicPage = input.required<TopicPageV2>();
private readonly resolverState = inject(ResolverStateService);
readonly loading = computed(() =>
this.resolverState.isResolvingInside('/topics'),
);
observers: FilterObserver[] = [
{
id: 'query',
@@ -1,6 +1,7 @@
import { ResolveFn } from '@angular/router';
import { inject } from '@angular/core';
import {
CareerBucket,
FounderCandidatePage,
FounderSortBy,
MultiplicatorsService,
@@ -9,12 +10,19 @@ import {
const FOUNDER_SORT_FIELDS = Object.values(FounderSortBy);
const SORT_DIRECTIONS = Object.values(SortDirection);
const DEFAULT_THRESHOLD = 90;
const VALID_CAREER_BUCKETS = Object.values(CareerBucket);
/**
* The founder-candidate list for the dashboard. Driven entirely by query
* params (threshold, screened, page, size, sort) so the page state stays in
* the URL and re-resolves when any of them change.
* params so the page state stays in the URL and re-resolves when any of them
* change.
*
* URL keys are the camelCase names used by the shared query-param controls and
* are mapped to the snake_case arguments of `searchFounderCandidates` here.
*
* Everyone is shown by default (`in_population` unset). The "Mindestwert" is
* opt-in: only when `threshold` is present is `min_external_percentile` sent.
* "Auffällige Profile ausblenden" sets `screened=true`.
*/
export const founderCandidatesResolver: ResolveFn<FounderCandidatePage> = (
route,
@@ -24,11 +32,14 @@ export const founderCandidatesResolver: ResolveFn<FounderCandidatePage> = (
const page = Math.max(0, toInt(params.get('page'), 0));
const size = clamp(toInt(params.get('size'), 25), 1, 100);
const thresholdRaw = toNumber(params.get('threshold'));
const threshold = clamp(thresholdRaw ?? DEFAULT_THRESHOLD, 0, 100);
const screenedRaw = params.get('screened');
const screened = screenedRaw === null ? undefined : screenedRaw === 'true';
const thresholdRaw = toNumber(params.get('threshold'));
const minPercentile =
thresholdRaw === null ? undefined : clamp(thresholdRaw, 0, 100);
// `screened=true` keeps only profiles that pass the data-quality screen.
// `screened=false` would mean "only the rejects", so it is never sent.
const screened = params.get('screened') === 'true' ? true : undefined;
const sortBy =
asMember(params.get('sortBy'), FOUNDER_SORT_FIELDS) ??
@@ -36,19 +47,26 @@ export const founderCandidatesResolver: ResolveFn<FounderCandidatePage> = (
const sortOrder =
asMember(params.get('sortOrder'), SORT_DIRECTIONS) ?? SortDirection.Desc;
const careerBuckets = splitCommaSeparated(params.getAll('careerBucket')).filter(
(value): value is CareerBucket =>
(VALID_CAREER_BUCKETS as readonly string[]).includes(value),
);
const researchAreas = splitCommaSeparated(params.getAll('researchArea'));
const name = params.get('name')?.trim() || undefined;
return service.searchFounderCandidates(
page,
size,
true, // in_population: only researchers the model can score
threshold,
undefined, // in_population: show everyone, scored and unscored
minPercentile,
undefined, // max_external_percentile
undefined, // career_bucket
careerBuckets.length ? careerBuckets : undefined,
screened,
undefined, // min_publications
undefined, // has_patents
undefined, // research_area
researchAreas.length ? researchAreas : undefined,
undefined, // tags
undefined, // name
name,
undefined, // screen_min_publications
undefined, // screen_max_career_age
sortBy,
@@ -65,6 +83,13 @@ function asMember<T extends string>(
: null;
}
function splitCommaSeparated(values: string[]): string[] {
return values
.flatMap((value) => value.split(','))
.map((value) => value.trim())
.filter(Boolean);
}
function clamp(value: number, min: number, max: number): number {
return Math.max(min, Math.min(max, value));
}
@@ -6,12 +6,15 @@ import { FounderStatistics, MultiplicatorsService } from '../api';
* Founder-potential statistics for the dashboard (KPIs, funnel, career-stage
* and research-area breakdowns). Re-resolved when the `threshold` query param
* changes, so the shortlist counts always match the slider in the URL.
*
* The threshold is opt-in. When the param is absent there is no shortlist cut,
* so 0 is used: every scored profile counts, matching the unfiltered list.
*/
export const founderStatisticsResolver: ResolveFn<FounderStatistics> = (
route,
) => {
const service = inject(MultiplicatorsService);
const threshold = toNumber(route.queryParamMap.get('threshold')) ?? 90;
const threshold = toNumber(route.queryParamMap.get('threshold')) ?? 0;
// Remaining cutoffs mirror the backend defaults; only the threshold is
// exposed to the user for now.
return service.getFounderStatistics(threshold, 7, 0.7, 40, 40);
+14 -1
View File
@@ -4,6 +4,7 @@ import {
CompanyConnectionsService,
CustomAuthorsListResponse,
PersonsService,
VerifiedOrganizationsResponse,
} from '../api';
import {
Observable,
@@ -20,6 +21,7 @@ import { toObservable } from '@angular/core/rxjs-interop';
export interface PersonDataResolved {
personData$: Observable<CustomAuthorsListResponse | null>;
companyConnectionsAvailable$: Observable<boolean>;
verifiedOrganizations$: Observable<VerifiedOrganizationsResponse | null>;
}
export const personResolver: ResolveFn<PersonDataResolved> = (route, state) => {
@@ -38,6 +40,7 @@ export const personResolver: ResolveFn<PersonDataResolved> = (route, state) => {
return {
personData$: of(null),
companyConnectionsAvailable$: of(false),
verifiedOrganizations$: of(null),
};
}
@@ -51,6 +54,16 @@ export const personResolver: ResolveFn<PersonDataResolved> = (route, state) => {
shareReplay(1),
);
const verifiedOrganizations$ = personsService
.getVerifiedOrganizations(authorId)
.pipe(
catchError((err) => {
console.error('Failed to load verified organizations:', err);
return of(null);
}),
shareReplay(1),
);
const companyConnectionsAvailable$ = toObservable(
credentialService.effectiveInstitutionId,
).pipe(
@@ -76,5 +89,5 @@ export const personResolver: ResolveFn<PersonDataResolved> = (route, state) => {
shareReplay({ bufferSize: 1, refCount: true }),
);
return { personData$, companyConnectionsAvailable$ };
return { personData$, companyConnectionsAvailable$, verifiedOrganizations$ };
};
@@ -0,0 +1,114 @@
import { Location } from '@angular/common';
import { Injectable, computed, inject, signal } from '@angular/core';
import { Router } from '@angular/router';
type BackHandler = () => void;
const ROOT_PATHS = new Set([
'/dashboard',
'/compare',
'/multipliers',
'/founders',
'/bookmarks',
'/persons',
'/keywords',
'/hierarchy',
'/news',
'/account',
'/accounts',
'/organizations',
'/jobs',
'/publications',
'/topics',
'/projects',
'/patents',
'/institutions',
'/login',
'/forgot-password',
'/reset-password',
'/icons',
'/error',
]);
const FALLBACKS: ReadonlyArray<{ prefix: string; target: string }> = [
{ prefix: '/person/', target: '/persons' },
{ prefix: '/publication/', target: '/publications' },
{ prefix: '/patent/', target: '/patents' },
{ prefix: '/news/', target: '/news' },
{ prefix: '/institution/', target: '/institutions' },
{ prefix: '/topic/', target: '/topics' },
{ prefix: '/projects/', target: '/projects' },
{ prefix: '/founders/', target: '/multipliers' },
{ prefix: '/keywords/', target: '/keywords' },
{ prefix: '/error', target: '/dashboard' },
];
@Injectable({ providedIn: 'root' })
export class BackNavigationService {
private readonly router = inject(Router);
private readonly location = inject(Location);
// In-page detail views (e.g. the inline patent detail) own the back action
// while they are open. The topbar button executes the newest handler.
private readonly localHandlers = signal<readonly BackHandler[]>([]);
readonly hasLocalHandler = computed(() => this.localHandlers().length > 0);
/**
* Registers a back action for an in-page detail view. Returns an unregister
* function that the component calls when the view closes or is destroyed.
*/
registerLocalBack(handler: BackHandler): () => void {
this.localHandlers.update((handlers) => [...handlers, handler]);
return () => {
this.localHandlers.update((handlers) =>
handlers.filter((candidate) => candidate !== handler),
);
};
}
/** True when this tab has at least one earlier in-app navigation. */
canGoBack(): boolean {
const state = history.state as { navigationId?: number } | null;
return (state?.navigationId ?? 0) > 1;
}
/**
* Goes back in history when that is safe, otherwise navigates to the
* section that owns the current detail page.
*/
back(fallback?: string): void {
const handlers = this.localHandlers();
const localHandler = handlers[handlers.length - 1];
if (localHandler) {
localHandler();
return;
}
if (this.canGoBack()) {
this.location.back();
return;
}
void this.router.navigateByUrl(
fallback ?? this.fallbackFor(this.router.url),
);
}
/** Whether the current URL is a top-level section. */
isRoot(url: string): boolean {
return ROOT_PATHS.has(this.pathOf(url));
}
fallbackFor(url: string): string {
const path = this.pathOf(url);
const match = FALLBACKS.find(({ prefix }) => path.startsWith(prefix));
return match?.target ?? '/dashboard';
}
private pathOf(url: string): string {
return url.split('?')[0].split('#')[0] || '/';
}
}
@@ -0,0 +1,71 @@
import { Injectable, inject } from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { NavigationEnd, Router } from '@angular/router';
import { filter } from 'rxjs';
const APP_NAME = 'AIIS';
const TITLES: ReadonlyArray<{ prefix: string; title: string }> = [
{ prefix: '/person/', title: 'Person' },
{ prefix: '/persons', title: 'Personen' },
{ prefix: '/publication/', title: 'Publikation' },
{ prefix: '/publications', title: 'Publikationen' },
{ prefix: '/patent/', title: 'Patent' },
{ prefix: '/patents', title: 'Patente' },
{ prefix: '/institution/', title: 'Institution' },
{ prefix: '/institutions', title: 'Institutionen' },
{ prefix: '/topic/', title: 'Thema' },
{ prefix: '/topics', title: 'Themen' },
{ prefix: '/news/', title: 'Nachricht' },
{ prefix: '/news', title: 'Nachrichten' },
{ prefix: '/projects/', title: 'Projekt' },
{ prefix: '/projects', title: 'Projekte' },
{ prefix: '/founders/', title: 'Multiplikator' },
{ prefix: '/founders', title: 'Gründungspotenzial' },
{ prefix: '/multipliers', title: 'Multiplikatoren' },
{ prefix: '/compare', title: 'Autorenvergleich' },
{ prefix: '/bookmarks', title: 'Bookmarks' },
{ prefix: '/keywords/', title: 'Keywords' },
{ prefix: '/keywords', title: 'Keywords' },
{ prefix: '/hierarchy', title: 'Hierarchie' },
{ prefix: '/account', title: 'Mein Konto' },
{ prefix: '/accounts', title: 'Accounts' },
{ prefix: '/organizations', title: 'Organisationen' },
{ prefix: '/jobs', title: 'Jobs' },
{ prefix: '/dashboard', title: 'Dashboard' },
{ prefix: '/login', title: 'Anmelden' },
{ prefix: '/forgot-password', title: 'Passwort vergessen' },
{ prefix: '/reset-password', title: 'Passwort zurücksetzen' },
{ prefix: '/error', title: 'Fehler' },
{ prefix: '/icons', title: 'Icons' },
];
@Injectable({ providedIn: 'root' })
export class PageTitleService {
private readonly router = inject(Router);
constructor() {
this.router.events
.pipe(
filter(
(event): event is NavigationEnd => event instanceof NavigationEnd,
),
takeUntilDestroyed(),
)
.subscribe((event) => this.update(event.urlAfterRedirects));
this.update(this.router.url);
}
private update(url: string): void {
document.title = `${this.titleFor(url)} · ${APP_NAME}`;
}
private titleFor(url: string): string {
const path = url.split('?')[0].split('#')[0] || '/';
if (path === '/' || path === '') return 'Start';
const match = TITLES.find(({ prefix }) => path.startsWith(prefix));
return match?.title ?? 'Übersicht';
}
}
@@ -0,0 +1,181 @@
import { Injectable, inject } from '@angular/core';
import { NavigationEnd, NavigationStart, Router } from '@angular/router';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
const STORAGE_PREFIX = 'inse.scroll.';
const STATE_KEY = 'sgScrollId';
/**
* Restores the scroll position of the app's inner scroll container.
*
* Rules:
* - a path change starts at the top,
* - back/forward restores the position of that history entry,
* - a query-only change on the same page keeps the current position, so
* selection, filter and pagination updates do not make the page jump.
*
* The app scrolls inside `main.content` (not the window), so Angular's
* built-in `withInMemoryScrolling` cannot handle it.
*/
@Injectable({ providedIn: 'root' })
export class RouteScrollService {
private readonly router = inject(Router);
private scroller: HTMLElement | null = null;
private currentScrollId: string | null = null;
private scrollFrame: number | null = null;
private nextNavigationIsPopstate = false;
private currentPath = '';
constructor() {
if ('scrollRestoration' in history) {
history.scrollRestoration = 'manual';
}
this.currentPath = this.pathOf(this.router.url);
this.router.events.pipe(takeUntilDestroyed()).subscribe((event) => {
if (event instanceof NavigationStart) {
this.persistCurrent();
this.nextNavigationIsPopstate = event.navigationTrigger === 'popstate';
return;
}
if (event instanceof NavigationEnd) {
this.handleNavigationEnd(event, this.nextNavigationIsPopstate);
}
});
}
/** Connects the persistent scroll container of the app shell. */
attach(scroller: HTMLElement): void {
if (this.scroller === scroller) return;
this.scroller?.removeEventListener('scroll', this.onScroll);
this.scroller = scroller;
this.scroller.addEventListener('scroll', this.onScroll, { passive: true });
const storedId = this.readStateId();
this.currentScrollId = storedId ?? this.writeStateId(this.createScrollId());
this.restore(this.currentScrollId);
}
/** Connects the scroll container after the first render. */
attachWhenReady(getScroller: () => HTMLElement | null | undefined): void {
requestAnimationFrame(() => {
const scroller = getScroller();
if (scroller) this.attach(scroller);
});
}
private handleNavigationEnd(
event: NavigationEnd,
isBackForward: boolean,
): void {
const nextPath = this.pathOf(event.urlAfterRedirects);
if (isBackForward) {
const id = this.readStateId() ?? this.writeStateId(this.createScrollId());
this.currentScrollId = id;
this.scheduleRestore(id);
this.currentPath = nextPath;
return;
}
const isNewPage = nextPath !== this.currentPath;
const previousPosition = this.scroller?.scrollTop ?? 0;
const id = this.writeStateId(this.createScrollId());
this.currentScrollId = id;
if (isNewPage) {
this.scheduleScrollTop();
} else {
// Query-only update on the same page: keep the user's position.
this.writePosition(id, previousPosition);
}
this.currentPath = nextPath;
}
private scheduleRestore(scrollId: string): void {
this.scheduleFrame(() => this.restore(scrollId));
}
private scheduleScrollTop(): void {
this.scheduleFrame(() => this.setScrollTop(0));
}
private scheduleFrame(callback: () => void): void {
// Two frames: one for the new component tree, one for its layout.
requestAnimationFrame(() => {
requestAnimationFrame(callback);
});
}
private restore(scrollId: string | null): void {
if (!this.scroller || !scrollId) return;
const stored = this.readPosition(scrollId);
this.setScrollTop(stored);
}
private setScrollTop(value: number): void {
if (!this.scroller) return;
this.scroller.scrollTop = Math.max(0, value);
}
private persistCurrent(): void {
if (!this.scroller || !this.currentScrollId) return;
this.writePosition(this.currentScrollId, this.scroller.scrollTop);
}
private readonly onScroll = (): void => {
if (this.scrollFrame !== null) return;
this.scrollFrame = requestAnimationFrame(() => {
this.scrollFrame = null;
this.persistCurrent();
});
};
private createScrollId(): string {
return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;
}
private readStateId(): string | null {
const state = history.state as Record<string, unknown> | null;
const id = state?.[STATE_KEY];
return typeof id === 'string' && id.length > 0 ? id : null;
}
private writeStateId(id: string): string {
const state = (history.state ?? {}) as Record<string, unknown>;
history.replaceState({ ...state, [STATE_KEY]: id }, '');
return id;
}
private readPosition(scrollId: string): number {
try {
const raw = sessionStorage.getItem(STORAGE_PREFIX + scrollId);
const value = raw === null ? 0 : Number(raw);
return Number.isFinite(value) ? value : 0;
} catch {
return 0;
}
}
private writePosition(scrollId: string, position: number): void {
try {
sessionStorage.setItem(STORAGE_PREFIX + scrollId, String(position));
} catch {
// Storage can be unavailable (private mode/quota). Position restoration
// is an enhancement, never a hard requirement.
}
}
private pathOf(url: string): string {
return url.split('?')[0].split('#')[0] || '/';
}
}
@@ -38,10 +38,16 @@
<mat-icon>{{ MENU_ICON }}</mat-icon>
</button>
}
<button (click)="navigateBack()" class="back-link" type="button">
<mat-icon>{{ ARROW_BACK_ICON }}</mat-icon>
<span>Zurück</span>
</button>
@if (showBack()) {
<button
(click)="navigateBack()"
class="back-link"
type="button"
aria-label="Zurück zur vorherigen Ansicht">
<mat-icon>{{ ARROW_BACK_ICON }}</mat-icon>
<span>Zurück</span>
</button>
}
</div>
<app-searchbar />
<div class="topbar-actions">
@@ -50,7 +56,7 @@
</mat-toolbar>
}
<main class="content">
<main class="content" #contentScroller>
<div class="main-content-body">
@if (resolverState.isResolvingFromOutside('/persons')) {
<app-loading
@@ -1,23 +1,34 @@
import {
afterNextRender,
ChangeDetectorRef,
Component,
DestroyRef,
ElementRef,
OnDestroy,
OnInit,
ViewChild,
computed,
inject,
signal,
viewChild,
} from '@angular/core';
import { CommonModule, Location } from '@angular/common';
import { CommonModule } from '@angular/common';
import { MatToolbarModule } from '@angular/material/toolbar';
import { MatButtonModule } from '@angular/material/button';
import { MatIconModule } from '@angular/material/icon';
import { MatDrawer, MatSidenavModule } from '@angular/material/sidenav';
import { Router } from '@angular/router';
import { NavigationEnd, Router } from '@angular/router';
import { filter } from 'rxjs';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { MediaMatcher } from '@angular/cdk/layout';
import { AppMenuComponent } from '../app-menu/app-menu.component';
import { MatTooltipModule } from '@angular/material/tooltip';
import { CredentialService } from '../../services/credential.service';
import { AppSearchbarComponent } from '../app-searchbar/app-searchbar.component';
import { ResolverStateService } from '../../services/resolver-state.service';
import { BackNavigationService } from '../../services/back-navigation.service';
import { PageTitleService } from '../../services/page-title.service';
import { RouteScrollService } from '../../services/route-scroll.service';
import { LoadingComponent } from '../loading/loading.component';
import {
ARROW_BACK_ICON,
@@ -72,6 +83,21 @@ export class AppLayoutComponent implements OnInit, OnDestroy {
protected resolverState = inject(ResolverStateService);
mediaQueryListener: () => void;
private readonly destroyRef = inject(DestroyRef);
private readonly backNavigation = inject(BackNavigationService);
private readonly scrollService = inject(RouteScrollService);
// Instantiated for its router subscription; keeps document.title in sync.
private readonly pageTitle = inject(PageTitleService);
private readonly contentScroller =
viewChild<ElementRef<HTMLElement>>('contentScroller');
private readonly currentPath = signal('/');
readonly showBack = computed(
() =>
this.backNavigation.hasLocalHandler() ||
!this.backNavigation.isRoot(this.currentPath()),
);
private readonly sidebarCollapsedStorageKey = 'inse.sidebar.collapsed';
sideNavOpen = false;
sideNavCollapsed = this.readSidebarCollapsedState();
@@ -79,11 +105,11 @@ export class AppLayoutComponent implements OnInit, OnDestroy {
constructor(
public credentialService: CredentialService,
public router: Router,
private readonly location: Location,
public changeDetector: ChangeDetectorRef,
media: MediaMatcher,
) {
this.mediaQuery = media.matchMedia('(max-width: 600px)');
this.currentPath.set(this.pathOf(this.router.url));
this.mediaQueryListener = () => {
this.sideNavOpen = !this.mediaQuery.matches;
@@ -93,6 +119,29 @@ export class AppLayoutComponent implements OnInit, OnDestroy {
changeDetector.detectChanges();
};
this.router.events
.pipe(
filter(
(event): event is NavigationEnd => event instanceof NavigationEnd,
),
takeUntilDestroyed(this.destroyRef),
)
.subscribe((event) => {
this.currentPath.set(this.pathOf(event.urlAfterRedirects));
// On phones the drawer is an overlay; keep it from covering the
// freshly opened page.
if (this.mediaQuery.matches && this.sideNavOpen) {
this.sideNavOpen = false;
this.drawer?.close();
}
});
afterNextRender(() => {
const scroller = this.contentScroller()?.nativeElement;
if (scroller) this.scrollService.attach(scroller);
});
}
toggle() {
@@ -147,6 +196,10 @@ export class AppLayoutComponent implements OnInit, OnDestroy {
}
navigateBack() {
this.location.back();
this.backNavigation.back();
}
private pathOf(url: string): string {
return url.split('?')[0].split('#')[0] || '/';
}
}
@@ -237,7 +237,6 @@ export class AppMenuComponent {
route: '/founders',
disabled: false,
queryParams: {
threshold: 90,
screened: 'true',
page: 0,
size: 10,
@@ -3,24 +3,31 @@
<input
matInput
type="search"
aria-label="Search"
aria-label="Personensuche"
[matAutocomplete]="auto"
[formControl]="searchControl"
(keydown.tab)="
filteredPersons.results?.length ? onKeydownTab($any($event)) : null
"
placeholder="Nach Personen suchen..."
(keyup.enter)="onEnter()"
(keydown.enter)="onEnter($event)"
(focus)="onFocus()" />
<mat-autocomplete #auto="matAutocomplete">
<mat-autocomplete
#auto="matAutocomplete"
(optionSelected)="selectPerson($event.option.value)">
@for (person of filteredPersons.results; track person.id) {
<mat-option
[value]="person.display_name"
(click)="selectPerson(person.display_name)">
<mat-option [value]="person.display_name">
<mat-icon>{{ PERSON_ICON }}</mat-icon>
<span>{{ person.display_name }}</span>
</mat-option>
}
@if (suggestionsLoading()) {
<mat-option disabled>Suche läuft …</mat-option>
} @else if (
searchControl.value &&
searchControl.value.length >= 2 &&
!filteredPersons.results?.length
) {
<mat-option disabled>Keine Personen gefunden</mat-option>
}
</mat-autocomplete>
</label>
@@ -1,4 +1,10 @@
import { Component, inject, ViewChild, DestroyRef } from '@angular/core';
import {
Component,
inject,
ViewChild,
DestroyRef,
signal,
} from '@angular/core';
import { MatIcon } from '@angular/material/icon';
import { FormControl, ReactiveFormsModule } from '@angular/forms';
import { Router, ActivatedRoute } from '@angular/router';
@@ -11,9 +17,11 @@ import { MatInputModule } from '@angular/material/input';
import { MatFormFieldModule } from '@angular/material/form-field';
import { switchMap, debounceTime, distinctUntilChanged } from 'rxjs/operators';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { of } from 'rxjs';
import { finalize, of } from 'rxjs';
import { PersonsService, AuthorsListResponse } from '../../../api';
import { PERSON_ICON, SEARCH_ICON } from '../icons';
import { CredentialService } from '../../services/credential.service';
import { activeInstitutionPersonListQueryParams } from '../../person-list-query-params';
@Component({
selector: 'app-searchbar',
@@ -48,12 +56,13 @@ export class AppSearchbarComponent {
private readonly router = inject(Router);
private readonly route = inject(ActivatedRoute);
private readonly personService = inject(PersonsService);
constructor() {
const route = inject(ActivatedRoute);
const router = inject(Router);
private readonly credentialService = inject(CredentialService);
readonly suggestionsLoading = signal(false);
constructor() {
// Sync searchControl from query param on every URL change
route.queryParams
this.route.queryParams
.pipe(takeUntilDestroyed(this.destroyRef))
.subscribe((params) => {
const query = params['query'] ?? '';
@@ -67,13 +76,17 @@ export class AppSearchbarComponent {
.pipe(
debounceTime(300),
distinctUntilChanged(),
switchMap((v) => {
const value = v ?? '';
if (value.length < 2) return of(this.emptyPersons());
return this.personService.searchPersonsAutocomplete(
value,
'display_name',
);
switchMap((value) => {
const term = (value ?? '').trim();
if (term.length < 2) {
this.suggestionsLoading.set(false);
return of(this.emptyPersons());
}
this.suggestionsLoading.set(true);
return this.personService
.searchPersonsAutocomplete(term, 'display_name')
.pipe(finalize(() => this.suggestionsLoading.set(false)));
}),
takeUntilDestroyed(this.destroyRef),
)
@@ -83,22 +96,23 @@ export class AppSearchbarComponent {
}
selectPerson(personName: string | undefined | null): void {
if (personName) {
this.searchControl.setValue(personName);
this.startSearch();
}
if (!personName) return;
this.searchControl.setValue(personName, { emitEvent: false });
this.startSearch();
}
onKeydownTab(event: KeyboardEvent): void {
onEnter(event: Event): void {
if (event.defaultPrevented) return;
// Let Material select the highlighted option; its optionSelected handler
// performs the navigation. Only free-text Enter starts a search here.
if (this.autocomplete?.isOpen && this.autocompleteTrigger?.activeOption) {
return;
}
event.preventDefault();
const first = this.filteredPersons?.results?.[0];
if (first?.display_name) {
this.searchControl.setValue(first.display_name);
}
}
onEnter(): void {
this.autocompleteTrigger.closePanel();
this.autocompleteTrigger?.closePanel();
this.startSearch();
}
@@ -107,16 +121,31 @@ export class AppSearchbarComponent {
}
startSearch(): void {
const search = this.searchControl.value ?? '';
const search = (this.searchControl.value ?? '').trim();
const currentPath = this.router.url.split('?')[0];
const onPersonList = currentPath.startsWith('/persons');
this.router.navigate(
this.router.url.startsWith('/persons') ? [] : ['/persons'],
{
relativeTo: this.route,
queryParams: { query: search || null, page: 1 },
queryParamsHandling: 'merge',
// On the person list, keep the active filters. Anywhere else, start from
// the account's institution defaults and never leak unrelated params
// (sort keys, titles, topics from other sections).
const baseParams: Record<string, unknown> = onPersonList
? { ...this.router.parseUrl(this.router.url).queryParams }
: activeInstitutionPersonListQueryParams(
this.credentialService.effectiveInstitutionId(),
this.credentialService.organizationName(),
);
delete baseParams['query'];
delete baseParams['page'];
void this.router.navigate(['/persons'], {
queryParams: {
...baseParams,
query: search || null,
page: 1,
pageSize: baseParams['pageSize'] ?? 10,
},
);
});
}
private emptyPersons(): AuthorsListResponse {
@@ -30,9 +30,12 @@
<mat-divider />
@let pageValue = page();
<div class="card-search-results">
<div class="card-search-results" [attr.aria-busy]="loading()">
@if (loading()) {
<div class="loading-overlay">
<div
class="loading-overlay"
role="status"
aria-label="Ergebnisse werden geladen">
<mat-spinner diameter="36"></mat-spinner>
</div>
}
@@ -45,7 +48,7 @@
</ng-container>
}
</div>
} @else {
} @else if (!loading()) {
@if (this.noResultsTmp()) {
<ng-container [ngTemplateOutlet]="noResultsTmp()"></ng-container>
} @else {
@@ -55,12 +58,14 @@
}
}
</div>
@if (pageValue.elements && pageValue.elements.length > 0) {
@if (!loading() && pageValue.elements && pageValue.elements.length > 0) {
<mat-divider />
}
<div class="pagination">
<app-query-param-paginator
[pageSizeOptions]="[10, 25, 100]"
[total]="page().total" />
</div>
@if (!loading() && page().total > 0) {
<div class="pagination">
<app-query-param-paginator
[pageSizeOptions]="[10, 25, 100]"
[total]="page().total" />
</div>
}
</div>
@@ -214,7 +214,7 @@ export class FileUploadComponent implements OnInit, OnDestroy {
if (file) {
this.files = this.files.filter((f) => f.id !== id);
this.emitFilesChange();
this.showError('Upload cancelled');
this.showError('Upload abgebrochen');
}
}
@@ -1,5 +1,10 @@
<section class="word-cloud-panel" aria-labelledby="word-cloud-heading">
@if (title) {
<section
class="word-cloud-panel"
[class.word-cloud-panel--bare]="variant === 'bare'"
[attr.aria-labelledby]="
title && variant !== 'bare' ? 'word-cloud-heading' : null
">
@if (title && variant !== 'bare') {
<div class="word-cloud-panel-header">
<div>
<h3 id="word-cloud-heading">{{ title }}</h3>
@@ -7,30 +12,63 @@
<p>{{ subtitle }}</p>
}
</div>
@if (showCount && displayWords.length) {
@if (showCount && !loading && !loadFailed && displayWords.length) {
<span class="word-count">{{ displayWords.length }} Begriffe</span>
}
</div>
}
@if (displayWords.length) {
<div class="word-cloud-chart" aria-label="Wordcloud der Keywords">
@if (loading) {
<div class="word-cloud-state">
<span>{{ loadingMessage }}</span>
</div>
} @else if (loadFailed) {
<div class="word-cloud-state">
<span>{{ loadFailedMessage }}</span>
</div>
} @else if (displayWords.length) {
<div class="word-cloud-chart" [attr.aria-label]="chartAriaLabel">
@for (word of displayWords; track word.id) {
<span
class="word-cloud-word"
[style.color]="word.color"
[style.fontSize.px]="word.fontSize"
[style.fontWeight]="word.fontWeight"
[title]="word.name">
{{ word.name }}
</span>
@if (wordTooltip; as tooltip) {
<button
type="button"
class="word-cloud-word"
[class.word-cloud-word-active]="isActive(word)"
[style.color]="word.color"
[style.fontSize.px]="word.fontSize"
[style.fontWeight]="word.fontWeight"
[disabled]="!interactive || word.disabled"
[attr.aria-label]="ariaLabelFor(word)"
[appComponentTooltip]="tooltip.component"
[tooltipInputs]="tooltipInputsFor(word)"
[tooltipDisabled]="tooltipDisabledFor(word)"
[tooltipMaxWidth]="tooltip.maxWidth ?? null"
(click)="selectWord(word)">
{{ word.name }}
</button>
} @else {
<button
type="button"
class="word-cloud-word"
[class.word-cloud-word-active]="isActive(word)"
[style.color]="word.color"
[style.fontSize.px]="word.fontSize"
[style.fontWeight]="word.fontWeight"
[disabled]="!interactive || word.disabled"
[attr.aria-label]="ariaLabelFor(word)"
(click)="selectWord(word)">
{{ word.name }}
</button>
}
}
</div>
} @else {
<div class="word-cloud-state">
<span class="state-icon" aria-hidden="true">☁️</span>
<strong>{{ emptyTitle }}</strong>
<span>{{ emptyMessage }}</span>
@if (emptyMessage) {
<span>{{ emptyMessage }}</span>
}
</div>
}
</section>
@@ -1,3 +1,7 @@
:host {
display: block;
}
.word-cloud-panel {
overflow: hidden;
border: 1px solid var(--sg-border, #e2e5ea);
@@ -53,21 +57,44 @@
}
.word-cloud-word {
appearance: none;
margin: 0;
padding: 3px 5px;
border: 1px solid transparent;
border-radius: 6px;
background: none;
color: inherit;
line-height: 1.1;
text-align: center;
font-family: inherit;
user-select: none;
cursor: default;
transition:
transform 150ms ease,
background-color 150ms ease;
&:not(:disabled) {
cursor: pointer;
}
&:hover {
background: var(--sg-surface-soft, #f2f4f7);
transform: translateY(-2px);
}
&:focus-visible {
outline: 2px solid var(--sg-primary, #5b8ff9);
outline-offset: 2px;
}
&:disabled {
opacity: 1;
}
}
.word-cloud-word-active {
background: color-mix(in srgb, currentColor 14%, transparent);
box-shadow: inset 0 0 0 1.5px currentColor;
}
.word-cloud-state {
@@ -102,6 +129,72 @@
font-size: 22px;
}
/* --------------------------------- bare ---------------------------------- */
.word-cloud-panel--bare {
overflow: visible;
border: none;
border-radius: 0;
background: transparent;
box-shadow: none;
.word-cloud-chart {
min-height: 420px;
gap: 0.35em 1em;
padding: 1.5rem 1rem;
background: transparent;
}
.word-cloud-word {
padding: 0.1em 0.3em;
border: none;
border-radius: 6px;
background: none;
font-family: 'Open Sans', Arial, sans-serif;
transition:
transform 0.15s ease,
background-color 0.15s ease,
box-shadow 0.15s ease;
&:hover:not(:disabled),
&:focus-visible {
background: none;
transform: scale(1.08);
outline: none;
}
&:disabled {
cursor: default;
}
}
.word-cloud-word-active {
background: color-mix(in srgb, currentColor 14%, transparent);
box-shadow: inset 0 0 0 1.5px currentColor;
&:hover:not(:disabled) {
background: color-mix(in srgb, currentColor 14%, transparent);
}
}
.word-cloud-state {
min-height: 420px;
padding: 0;
font-size: 14px;
.state-icon {
display: none;
}
strong {
margin: 0;
color: var(--sg-text-muted, #6b7280);
font-size: 14px;
font-weight: 400;
}
}
}
@media (max-width: 700px) {
.word-cloud-chart {
min-height: 240px;
@@ -1,16 +1,52 @@
import { ComponentType } from '@angular/cdk/portal';
import { CommonModule } from '@angular/common';
import { Component, Input, OnChanges, SimpleChanges } from '@angular/core';
import {
Component,
EventEmitter,
Input,
OnChanges,
Output,
SimpleChanges,
} from '@angular/core';
import { ComponentTooltipDirective } from '../../../directives/component-tooltip.directive';
/** A word with optional presentation overrides and arbitrary caller metadata. */
export interface WordCloudWordData {
name: string;
count?: number;
id?: string;
color?: string;
fontSize?: number;
fontWeight?: number;
active?: boolean;
disabled?: boolean;
}
/** A word can be a plain string or an object with an optional weight/count. */
export type WordCloudWord = string | { name: string; count?: number };
export type WordCloudWord = string | WordCloudWordData;
/**
* Optional per-word tooltip. The shared component owns the trigger element,
* the caller supplies the component and its inputs.
*/
export interface WordCloudTooltipConfig {
component: ComponentType<object>;
inputs?: (word: WordCloudWordData) => Record<string, unknown> | null;
disabled?: (word: WordCloudWordData) => boolean;
maxWidth?: string | number | null;
}
export type WordCloudVariant = 'panel' | 'bare';
interface DisplayWord {
id: string;
name: string;
count: number;
color: string;
fontSize: number;
fontWeight: number;
active: boolean;
disabled: boolean;
source: WordCloudWordData;
}
const DEFAULT_COLORS = [
@@ -29,13 +65,13 @@ const DEFAULT_COLORS = [
@Component({
selector: 'app-keyword-wordcloud',
standalone: true,
imports: [CommonModule],
imports: [CommonModule, ComponentTooltipDirective],
templateUrl: './keyword-wordcloud.component.html',
styleUrl: './keyword-wordcloud.component.scss',
})
export class KeywordWordcloudComponent implements OnChanges {
/** The keywords to display. Accepts plain strings or { name, count? } objects. */
@Input() words: WordCloudWord[] = [];
@Input() words: readonly WordCloudWord[] = [];
/** Panel header title. Set to '' / null to hide the header entirely. */
@Input() title: string | null = 'Keywords';
@@ -43,9 +79,18 @@ export class KeywordWordcloudComponent implements OnChanges {
/** Optional descriptive subtitle under the title. */
@Input() subtitle?: string;
/** `panel` renders the card chrome, `bare` embeds the words without it. */
@Input() variant: WordCloudVariant = 'panel';
/** Show the "N Begriffe" count badge in the header. */
@Input() showCount = true;
@Input() loading = false;
@Input() loadingMessage = 'Keywords werden geladen …';
@Input() loadFailed = false;
@Input() loadFailedMessage = 'Keywords konnten nicht geladen werden.';
@Input() emptyTitle = 'Keine Keywords gefunden';
@Input() emptyMessage = 'Für dieses Element sind keine Keywords vorhanden.';
@@ -53,7 +98,22 @@ export class KeywordWordcloudComponent implements OnChanges {
@Input() maxFontSize = 34;
/** Override the color palette used to cycle through words. */
@Input() colors: string[] = DEFAULT_COLORS;
@Input() colors: readonly string[] = DEFAULT_COLORS;
/** Words become focusable buttons that emit `wordClick`; otherwise they are static. */
@Input() interactive = false;
@Input() chartAriaLabel = 'Wordcloud der Keywords';
/** Optional predicate to mark a word as active (e.g. a legend selection). */
@Input() isWordActive?: (word: WordCloudWordData) => boolean;
/** Optional per-word accessible label. Falls back to the word itself. */
@Input() wordAriaLabel?: (word: WordCloudWordData) => string | null;
@Input() wordTooltip?: WordCloudTooltipConfig | null;
@Output() wordClick = new EventEmitter<WordCloudWordData>();
displayWords: DisplayWord[] = [];
@@ -68,51 +128,88 @@ export class KeywordWordcloudComponent implements OnChanges {
}
}
private buildWords(input: WordCloudWord[]): DisplayWord[] {
selectWord(word: DisplayWord): void {
if (!this.interactive || word.disabled) return;
this.wordClick.emit(word.source);
}
isActive(word: DisplayWord): boolean {
return word.active || (this.isWordActive?.(word.source) ?? false);
}
ariaLabelFor(word: DisplayWord): string {
return this.wordAriaLabel?.(word.source) ?? word.name;
}
tooltipInputsFor(word: DisplayWord): Record<string, unknown> | null {
return this.wordTooltip?.inputs?.(word.source) ?? null;
}
tooltipDisabledFor(word: DisplayWord): boolean {
return this.wordTooltip?.disabled?.(word.source) ?? false;
}
private buildWords(input: readonly WordCloudWord[]): DisplayWord[] {
if (!input.length) return [];
const normalized = this.normalize(input);
const counts = normalized.map((w) => w.count);
const counts = normalized.map((word) => word.count);
const minimum = Math.min(...counts);
const maximum = Math.max(...counts);
const scaled = normalized.map((word, index) => {
const intensity =
maximum === minimum ? 1 : (word.count - minimum) / (maximum - minimum);
const source = word.source;
return {
id: `${word.name}-${index}`,
name: word.name,
count: word.count,
color: this.colors[index % this.colors.length],
fontSize: Math.round(
this.minFontSize + intensity * (this.maxFontSize - this.minFontSize),
),
fontWeight: intensity > 0.66 ? 800 : intensity > 0.33 ? 600 : 400,
id: source.id ?? `${source.name}-${index}`,
name: source.name,
color: source.color ?? this.colors[index % this.colors.length],
fontSize:
source.fontSize ??
Math.round(
this.minFontSize +
intensity * (this.maxFontSize - this.minFontSize),
),
fontWeight:
source.fontWeight ??
(intensity > 0.66 ? 800 : intensity > 0.33 ? 600 : 400),
active: source.active ?? false,
disabled: source.disabled ?? false,
source,
};
});
// Alternating push/unshift → bigger/earlier words gravitate toward the middle
return this.centre(scaled);
}
/** Resolves each word to a { name, count } pair, falling back to rank-based sizing. */
private normalize(
input: readonly WordCloudWord[],
): { name: string; count: number; source: WordCloudWordData }[] {
const objects: WordCloudWordData[] = input.map((word) =>
typeof word === 'string' ? { name: word } : word,
);
const hasAllCounts = objects.every(
(word) => typeof word.count === 'number',
);
return objects.map((word, index) => ({
name: word.name,
count: hasAllCounts ? (word.count as number) : objects.length - index,
source: word,
}));
}
/** Alternating push/unshift → bigger/earlier words gravitate toward the middle. */
private centre(words: DisplayWord[]): DisplayWord[] {
const centred: DisplayWord[] = [];
scaled.forEach((word, index) => {
words.forEach((word, index) => {
if (index % 2 === 0) centred.push(word);
else centred.unshift(word);
});
return centred;
}
/** Resolves each word to a { name, count } pair, falling back to rank-based sizing. */
private normalize(input: WordCloudWord[]): { name: string; count: number }[] {
const hasAllCounts = input.every(
(w) => typeof w !== 'string' && typeof w.count === 'number',
);
return input.map((w, index) => {
const name = typeof w === 'string' ? w : w.name;
const count = hasAllCounts
? (w as { name: string; count: number }).count
: input.length - index; // rank-based decay: first = biggest
return { name, count };
});
}
}
@@ -38,3 +38,9 @@
opacity: 0.7;
}
}
@media (prefers-reduced-motion: reduce) {
.spinner-icon {
animation: none;
}
}
@@ -107,9 +107,6 @@ export class MultiplierNetworkGraphComponent {
if (d.role === 'ego' && d.nWorks != null) {
lines.push(`${d.nWorks} Publikationen`);
}
if (d.suspicious) {
lines.push('Profil möglicherweise zusammengeführt');
}
return lines.join('<br>');
},
},
@@ -167,7 +164,6 @@ export class MultiplierNetworkGraphComponent {
role,
inst: node.inst ?? '',
activeYears,
suspicious: node.suspicious ?? false,
nWorks: isEgo ? nWorks : undefined,
symbolSize: isEgo ? 24 : clamp(8 + activeYears * 1.1, 8, 26),
itemStyle: {
@@ -1,4 +1,4 @@
import { Component, input } from '@angular/core';
import { Component, ElementRef, inject, input } from '@angular/core';
import { PageHeaderComponent } from '../page-header/page-header.component';
/** Shared full-width page frame with a consistent page heading. */
@@ -14,4 +14,14 @@ export class PageContainerComponent {
readonly subtitle = input<string | null>(null);
readonly eyebrow = input<string | null>(null);
readonly titleTooltip = input<string | null>(null);
constructor() {
// `title` is an input, but a static `title="..."` attribute would also be
// written to the host element. Browsers then show it as a native tooltip
// when hovering anywhere inside the page. Remove the attribute; the input
// value itself is unaffected.
inject<ElementRef<HTMLElement>>(ElementRef).nativeElement.removeAttribute(
'title',
);
}
}
@@ -67,7 +67,7 @@ h3.page-header__title {
}
.page-header__subtitle {
max-width: 90ch;
max-width: 120ch;
margin: 6px 0 0;
color: var(--sg-text-muted);
font-size: 14px;

Some files were not shown because too many files have changed in this diff Show More