dashboard-statics #207
@@ -0,0 +1 @@
|
||||
"""Dashboard statistics package."""
|
||||
@@ -0,0 +1,52 @@
|
||||
from pydantic import BaseModel
|
||||
|
||||
|
||||
class DashboardStatistics(BaseModel):
|
||||
institution_id: str
|
||||
organization_name: str
|
||||
publications: int
|
||||
persons: int
|
||||
projects: int
|
||||
dfg_projects: int
|
||||
eu_projects: int
|
||||
bmbf_projects: int
|
||||
|
||||
|
||||
class DashboardStatisticValue(BaseModel):
|
||||
institution_id: str
|
||||
organization_name: str
|
||||
value: int
|
||||
|
||||
|
||||
class TopAuthor(BaseModel):
|
||||
id: str | None = None
|
||||
name: str
|
||||
count: int
|
||||
|
||||
|
||||
class TopAuthorStatistics(BaseModel):
|
||||
institution_id: str
|
||||
works: list[TopAuthor]
|
||||
projects: list[TopAuthor]
|
||||
patents: list[TopAuthor]
|
||||
news: list[TopAuthor]
|
||||
|
||||
|
||||
class TopicHeatmapValue(BaseModel):
|
||||
year: int
|
||||
count: int
|
||||
share: float
|
||||
|
||||
|
||||
class TopicHeatmapField(BaseModel):
|
||||
id: str
|
||||
name: str
|
||||
total: int
|
||||
values: list[TopicHeatmapValue]
|
||||
|
||||
|
||||
class TopicHeatmap(BaseModel):
|
||||
institution_id: str
|
||||
organization_name: str
|
||||
years: list[int]
|
||||
fields: list[TopicHeatmapField]
|
||||
@@ -0,0 +1,168 @@
|
||||
from typing import Literal
|
||||
|
||||
from fastapi import APIRouter, Depends, Query
|
||||
from sqlmodel import Session
|
||||
|
||||
from inse.auth import service as auth_service
|
||||
from inse.auth.model import AccessToken
|
||||
from inse.database import get_session
|
||||
from inse.tags import Tags
|
||||
|
||||
from .model import (
|
||||
DashboardStatisticValue,
|
||||
DashboardStatistics,
|
||||
TopAuthorStatistics,
|
||||
TopicHeatmap,
|
||||
)
|
||||
from .service import (
|
||||
get_dashboard_bmbf_projects,
|
||||
get_dashboard_dfg_projects,
|
||||
get_dashboard_eu_projects,
|
||||
get_dashboard_organization,
|
||||
get_dashboard_persons,
|
||||
get_dashboard_publications,
|
||||
get_dashboard_statistics,
|
||||
get_top_authors,
|
||||
get_topic_heatmap,
|
||||
)
|
||||
|
||||
router = APIRouter(prefix="/api/dashboard", tags=[Tags.DASHBOARD])
|
||||
|
||||
|
||||
@router.get(
|
||||
"/statistics",
|
||||
operation_id="getDashboardStatistics",
|
||||
response_model=DashboardStatistics,
|
||||
)
|
||||
async def dashboard_statistics(
|
||||
session: Session = Depends(get_session),
|
||||
access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
|
||||
) -> DashboardStatistics:
|
||||
organization = get_dashboard_organization(session, access_token)
|
||||
return await get_dashboard_statistics(
|
||||
organization.openalex_institution_id,
|
||||
organization.name,
|
||||
)
|
||||
|
||||
|
||||
@router.get(
|
||||
"/statistics/publications",
|
||||
operation_id="getDashboardPublications",
|
||||
response_model=DashboardStatisticValue,
|
||||
)
|
||||
async def dashboard_publications(
|
||||
session: Session = Depends(get_session),
|
||||
access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
|
||||
) -> DashboardStatisticValue:
|
||||
organization = get_dashboard_organization(session, access_token)
|
||||
return await get_dashboard_publications(
|
||||
organization.openalex_institution_id,
|
||||
organization.name,
|
||||
)
|
||||
|
||||
|
||||
@router.get(
|
||||
"/statistics/persons",
|
||||
operation_id="getDashboardPersons",
|
||||
response_model=DashboardStatisticValue,
|
||||
)
|
||||
async def dashboard_persons(
|
||||
session: Session = Depends(get_session),
|
||||
access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
|
||||
) -> DashboardStatisticValue:
|
||||
organization = get_dashboard_organization(session, access_token)
|
||||
return await get_dashboard_persons(
|
||||
organization.openalex_institution_id,
|
||||
organization.name,
|
||||
)
|
||||
|
||||
|
||||
@router.get(
|
||||
"/statistics/projects/eu",
|
||||
operation_id="getDashboardEuProjects",
|
||||
response_model=DashboardStatisticValue,
|
||||
)
|
||||
async def dashboard_eu_projects(
|
||||
session: Session = Depends(get_session),
|
||||
access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
|
||||
) -> DashboardStatisticValue:
|
||||
organization = get_dashboard_organization(session, access_token)
|
||||
return await get_dashboard_eu_projects(
|
||||
organization.openalex_institution_id,
|
||||
organization.name,
|
||||
)
|
||||
|
||||
|
||||
@router.get(
|
||||
"/statistics/projects/bmbf",
|
||||
operation_id="getDashboardBmbfProjects",
|
||||
response_model=DashboardStatisticValue,
|
||||
)
|
||||
async def dashboard_bmbf_projects(
|
||||
session: Session = Depends(get_session),
|
||||
access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
|
||||
) -> DashboardStatisticValue:
|
||||
organization = get_dashboard_organization(session, access_token)
|
||||
return await get_dashboard_bmbf_projects(
|
||||
organization.openalex_institution_id,
|
||||
organization.name,
|
||||
)
|
||||
|
||||
|
||||
@router.get(
|
||||
"/statistics/projects/dfg",
|
||||
operation_id="getDashboardDfgProjects",
|
||||
response_model=DashboardStatisticValue,
|
||||
)
|
||||
async def dashboard_dfg_projects(
|
||||
session: Session = Depends(get_session),
|
||||
access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
|
||||
) -> DashboardStatisticValue:
|
||||
organization = get_dashboard_organization(session, access_token)
|
||||
return await get_dashboard_dfg_projects(
|
||||
organization.openalex_institution_id,
|
||||
organization.name,
|
||||
)
|
||||
|
||||
|
||||
@router.get(
|
||||
"/top-authors",
|
||||
operation_id="getDashboardTopAuthors",
|
||||
response_model=TopAuthorStatistics,
|
||||
)
|
||||
async def dashboard_top_authors(
|
||||
works_period: Literal["all_time", "last_5_years"] = Query(
|
||||
default="all_time",
|
||||
pattern="^(all_time|last_5_years)$",
|
||||
),
|
||||
session: Session = Depends(get_session),
|
||||
access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
|
||||
) -> TopAuthorStatistics:
|
||||
organization = get_dashboard_organization(session, access_token)
|
||||
return await get_top_authors(
|
||||
organization.openalex_institution_id,
|
||||
organization.name,
|
||||
works_period=works_period,
|
||||
)
|
||||
|
||||
|
||||
@router.get(
|
||||
"/topic-heatmap",
|
||||
operation_id="getDashboardTopicHeatmap",
|
||||
response_model=TopicHeatmap,
|
||||
)
|
||||
async def dashboard_topic_heatmap(
|
||||
from_year: int | None = Query(default=None, ge=1900, le=2100),
|
||||
to_year: int | None = Query(default=None, ge=1900, le=2100),
|
||||
limit: int = Query(default=25, ge=1, le=50),
|
||||
session: Session = Depends(get_session),
|
||||
access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
|
||||
) -> TopicHeatmap:
|
||||
organization = get_dashboard_organization(session, access_token)
|
||||
return await get_topic_heatmap(
|
||||
institution_id=organization.openalex_institution_id,
|
||||
organization_name=organization.name,
|
||||
from_year=from_year,
|
||||
to_year=to_year,
|
||||
limit=limit,
|
||||
)
|
||||
@@ -0,0 +1,734 @@
|
||||
import asyncio
|
||||
import logging
|
||||
from datetime import datetime
|
||||
from typing import Any, Literal
|
||||
|
||||
from fastapi import HTTPException, status
|
||||
from sqlmodel import Session
|
||||
|
||||
from inse import config
|
||||
from inse.auth.model import AccessToken, Organization
|
||||
from inse.integrations import elasticsearch
|
||||
from inse.institutions.institutions_search_client import InstitutionsSearchClient
|
||||
from inse.model import ESCluster, ESIndex
|
||||
from inse.patents.org.elastic_search_client import OrgPatentsSearchClient
|
||||
|
||||
from .model import (
|
||||
DashboardStatisticValue,
|
||||
DashboardStatistics,
|
||||
TopAuthor,
|
||||
TopAuthorStatistics,
|
||||
TopicHeatmap,
|
||||
TopicHeatmapField,
|
||||
TopicHeatmapValue,
|
||||
)
|
||||
|
||||
TOP_AUTHOR_LIMIT = 10
|
||||
TOPIC_HEATMAP_LIMIT = 25
|
||||
TOPIC_HEATMAP_YEARS = 5
|
||||
WorksPeriod = Literal["all_time", "last_5_years"]
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
DFG_INSTITUTION_FIELDS = [
|
||||
"Antragstellende Institution",
|
||||
"Mitantragstellende Institution",
|
||||
"Beteiligte Einrichtung",
|
||||
"Beteiligte Hochschule",
|
||||
"Beteiligte Institution",
|
||||
"IGK-Partnerinstitution",
|
||||
"Partnerorganisation",
|
||||
"Unternehmen",
|
||||
]
|
||||
|
||||
|
||||
def _total(response: dict[str, Any]) -> int:
|
||||
total = response.get("hits", {}).get("total", 0)
|
||||
if isinstance(total, dict):
|
||||
return int(total.get("value", 0))
|
||||
return int(total or 0)
|
||||
|
||||
|
||||
def get_dashboard_organization(
|
||||
session: Session,
|
||||
access_token: AccessToken,
|
||||
) -> Organization:
|
||||
organization = session.get(Organization, access_token.effective_organization_id)
|
||||
if organization is None or organization.deleted:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND,
|
||||
detail="Organization not found.",
|
||||
)
|
||||
if not organization.openalex_institution_id:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
||||
detail="Organization has no OpenAlex institution ID configured.",
|
||||
)
|
||||
return organization
|
||||
|
||||
|
||||
async def get_dashboard_statistics(
|
||||
institution_id: str,
|
||||
organization_name: str,
|
||||
) -> DashboardStatistics:
|
||||
normalized_id = _normalize_institution_id(institution_id)
|
||||
publications, persons, eu_projects, bmbf_projects, dfg_projects = (
|
||||
await asyncio.gather(
|
||||
get_dashboard_publications(institution_id, organization_name),
|
||||
get_dashboard_persons(institution_id, organization_name),
|
||||
get_dashboard_eu_projects(institution_id, organization_name),
|
||||
get_dashboard_bmbf_projects(institution_id, organization_name),
|
||||
get_dashboard_dfg_projects(institution_id, organization_name),
|
||||
)
|
||||
)
|
||||
return DashboardStatistics(
|
||||
institution_id=normalized_id,
|
||||
organization_name=organization_name,
|
||||
publications=publications.value,
|
||||
persons=persons.value,
|
||||
projects=eu_projects.value + bmbf_projects.value + dfg_projects.value,
|
||||
dfg_projects=dfg_projects.value,
|
||||
eu_projects=eu_projects.value,
|
||||
bmbf_projects=bmbf_projects.value,
|
||||
)
|
||||
|
||||
|
||||
async def get_dashboard_publications(
|
||||
institution_id: str,
|
||||
organization_name: str,
|
||||
) -> DashboardStatisticValue:
|
||||
normalized_id = _normalize_institution_id(institution_id)
|
||||
response = await elasticsearch.search(
|
||||
index=config.settings.openalex_works_search_index,
|
||||
query=_institution_works_query(normalized_id),
|
||||
size=0,
|
||||
track_total_hits=True,
|
||||
cluster=ESCluster.NES,
|
||||
)
|
||||
return _dashboard_statistic_value(normalized_id, organization_name, response)
|
||||
|
||||
|
||||
async def get_dashboard_persons(
|
||||
institution_id: str,
|
||||
organization_name: str,
|
||||
) -> DashboardStatisticValue:
|
||||
normalized_id = _normalize_institution_id(institution_id)
|
||||
response = await elasticsearch.search(
|
||||
index=ESIndex.OPENALEX_AUTHORS,
|
||||
query={
|
||||
"nested": {
|
||||
"path": "affiliations",
|
||||
"query": {"term": {"affiliations.institution.id": normalized_id}},
|
||||
}
|
||||
},
|
||||
size=0,
|
||||
track_total_hits=True,
|
||||
cluster=ESCluster.NES,
|
||||
)
|
||||
return _dashboard_statistic_value(normalized_id, organization_name, response)
|
||||
|
||||
|
||||
async def get_dashboard_eu_projects(
|
||||
institution_id: str,
|
||||
organization_name: str,
|
||||
) -> DashboardStatisticValue:
|
||||
normalized_id = _normalize_institution_id(institution_id)
|
||||
aliases = await _institution_aliases(normalized_id, organization_name)
|
||||
response = await elasticsearch.search(
|
||||
index=ESIndex.CORDIS_EU_ORGANIZATIONS_WILDCARD,
|
||||
body={
|
||||
"size": 0,
|
||||
"query": _eu_organization_query(aliases),
|
||||
"aggs": {
|
||||
"projects": {
|
||||
"cardinality": {
|
||||
"field": "projectID",
|
||||
}
|
||||
}
|
||||
},
|
||||
},
|
||||
cluster=ESCluster.INSE,
|
||||
)
|
||||
return DashboardStatisticValue(
|
||||
institution_id=normalized_id,
|
||||
organization_name=organization_name,
|
||||
value=int(
|
||||
response.get("aggregations", {})
|
||||
.get("projects", {})
|
||||
.get("value", 0)
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
async def get_dashboard_bmbf_projects(
|
||||
institution_id: str,
|
||||
organization_name: str,
|
||||
) -> DashboardStatisticValue:
|
||||
normalized_id = _normalize_institution_id(institution_id)
|
||||
aliases = await _institution_aliases(normalized_id, organization_name)
|
||||
response = await elasticsearch.search(
|
||||
index=ESIndex.PROJECTS_BUND_V1,
|
||||
query=_alias_match_query("Zuwendungsempfänger", aliases),
|
||||
size=0,
|
||||
track_total_hits=True,
|
||||
cluster=ESCluster.INSE,
|
||||
)
|
||||
return _dashboard_statistic_value(normalized_id, organization_name, response)
|
||||
|
||||
|
||||
async def get_dashboard_dfg_projects(
|
||||
institution_id: str,
|
||||
organization_name: str,
|
||||
) -> DashboardStatisticValue:
|
||||
normalized_id = _normalize_institution_id(institution_id)
|
||||
aliases = await _institution_aliases(normalized_id, organization_name)
|
||||
response = await elasticsearch.search(
|
||||
index=ESIndex.PROJECTS_DFG_ALL,
|
||||
query=_dfg_institution_query(aliases),
|
||||
size=0,
|
||||
track_total_hits=True,
|
||||
cluster=ESCluster.INSE,
|
||||
)
|
||||
return _dashboard_statistic_value(normalized_id, organization_name, response)
|
||||
|
||||
|
||||
def _dashboard_statistic_value(
|
||||
institution_id: str,
|
||||
organization_name: str,
|
||||
response: dict[str, Any],
|
||||
) -> DashboardStatisticValue:
|
||||
return DashboardStatisticValue(
|
||||
institution_id=institution_id,
|
||||
organization_name=organization_name,
|
||||
value=_total(response),
|
||||
)
|
||||
|
||||
|
||||
async def _institution_aliases(
|
||||
institution_id: str,
|
||||
organization_name: str,
|
||||
) -> list[str]:
|
||||
aliases = await InstitutionsSearchClient().get_institution_aliases_by_oa_institution_id(
|
||||
_raw_institution_id(institution_id)
|
||||
)
|
||||
return sorted(
|
||||
{
|
||||
alias.strip()
|
||||
for alias in [organization_name, *aliases]
|
||||
if alias and alias.strip()
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
def _eu_organization_query(aliases: list[str]) -> dict[str, Any]:
|
||||
return {
|
||||
"terms": {
|
||||
"name.keyword": [alias.upper() for alias in aliases],
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
def _alias_match_query(field: str, aliases: list[str]) -> dict[str, Any]:
|
||||
return {
|
||||
"bool": {
|
||||
"should": [
|
||||
{
|
||||
"match": {
|
||||
field: {
|
||||
"query": alias,
|
||||
"operator": "and",
|
||||
}
|
||||
}
|
||||
}
|
||||
for alias in aliases
|
||||
],
|
||||
"minimum_should_match": 1,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
def _dfg_institution_query(aliases: list[str]) -> dict[str, Any]:
|
||||
return {
|
||||
"bool": {
|
||||
"should": [
|
||||
_alias_match_query(field, aliases)
|
||||
for field in DFG_INSTITUTION_FIELDS
|
||||
],
|
||||
"minimum_should_match": 1,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
async def get_top_authors(
|
||||
institution_id: str,
|
||||
organization_name: str,
|
||||
works_period: WorksPeriod = "all_time",
|
||||
) -> TopAuthorStatistics:
|
||||
normalized_id = _normalize_institution_id(institution_id)
|
||||
authors = await _safe_institution_authors(normalized_id)
|
||||
works = _top_work_authors(authors, works_period)
|
||||
aliases = await _safe_institution_aliases(normalized_id, organization_name)
|
||||
projects = await _safe_top_authors(
|
||||
"projects",
|
||||
_top_project_authors(authors, aliases),
|
||||
)
|
||||
patents = await _safe_top_authors(
|
||||
"patents",
|
||||
_top_patent_authors(normalized_id),
|
||||
)
|
||||
news = await _safe_top_authors(
|
||||
"news",
|
||||
_top_news_authors(authors),
|
||||
)
|
||||
return TopAuthorStatistics(
|
||||
institution_id=normalized_id,
|
||||
works=works,
|
||||
projects=projects,
|
||||
patents=patents,
|
||||
news=news,
|
||||
)
|
||||
|
||||
|
||||
async def get_topic_heatmap(
|
||||
institution_id: str,
|
||||
organization_name: str,
|
||||
from_year: int | None = None,
|
||||
to_year: int | None = None,
|
||||
limit: int = TOPIC_HEATMAP_LIMIT,
|
||||
) -> TopicHeatmap:
|
||||
normalized_id = _normalize_institution_id(institution_id)
|
||||
current_year = datetime.now().year
|
||||
effective_to_year = to_year or current_year
|
||||
effective_from_year = from_year or (effective_to_year - TOPIC_HEATMAP_YEARS + 1)
|
||||
if effective_from_year > effective_to_year:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
||||
detail="from_year must be less than or equal to to_year.",
|
||||
)
|
||||
years = list(range(effective_from_year, effective_to_year + 1))
|
||||
|
||||
response = await elasticsearch.search(
|
||||
index=config.settings.openalex_works_search_index,
|
||||
body={
|
||||
"size": 0,
|
||||
"query": {
|
||||
"bool": {
|
||||
"must": [_institution_works_query(normalized_id)],
|
||||
"filter": [
|
||||
{
|
||||
"range": {
|
||||
"publication_year": {
|
||||
"gte": effective_from_year,
|
||||
"lte": effective_to_year,
|
||||
}
|
||||
}
|
||||
}
|
||||
],
|
||||
}
|
||||
},
|
||||
"aggs": {
|
||||
"publication_years": {
|
||||
"terms": {
|
||||
"field": "publication_year",
|
||||
"size": len(years),
|
||||
"order": {"_key": "asc"},
|
||||
}
|
||||
},
|
||||
"topics_nested": {
|
||||
"nested": {"path": "topics"},
|
||||
"aggs": {
|
||||
"fields": {
|
||||
"terms": {
|
||||
"field": "topics.field.id",
|
||||
"size": limit,
|
||||
"order": [
|
||||
{"works": "desc"},
|
||||
{"_key": "asc"},
|
||||
],
|
||||
},
|
||||
"aggs": {
|
||||
"field_name": {
|
||||
"terms": {
|
||||
"field": "topics.field.display_name.keyword",
|
||||
"size": 1,
|
||||
}
|
||||
},
|
||||
"works": {
|
||||
"reverse_nested": {},
|
||||
"aggs": {
|
||||
"by_year": {
|
||||
"terms": {
|
||||
"field": "publication_year",
|
||||
"size": len(years),
|
||||
"order": {"_key": "asc"},
|
||||
}
|
||||
}
|
||||
},
|
||||
}
|
||||
},
|
||||
}
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
cluster=ESCluster.NES,
|
||||
)
|
||||
year_totals = _year_totals(response)
|
||||
buckets = (
|
||||
response.get("aggregations", {})
|
||||
.get("topics_nested", {})
|
||||
.get("fields", {})
|
||||
.get("buckets", [])
|
||||
)
|
||||
field_names = await _field_names([bucket.get("key") for bucket in buckets])
|
||||
|
||||
return TopicHeatmap(
|
||||
institution_id=normalized_id,
|
||||
organization_name=organization_name,
|
||||
years=years,
|
||||
fields=[
|
||||
_topic_heatmap_field(bucket, years, year_totals, field_names)
|
||||
for bucket in buckets
|
||||
if bucket.get("key")
|
||||
],
|
||||
)
|
||||
|
||||
|
||||
async def _safe_top_authors(
|
||||
source: str, operation: Any
|
||||
) -> list[TopAuthor]:
|
||||
try:
|
||||
return await operation
|
||||
except Exception:
|
||||
logger.exception("Dashboard top-author aggregation failed for %s.", source)
|
||||
return []
|
||||
|
||||
|
||||
def _normalize_institution_id(value: str) -> str:
|
||||
short_id = value.replace("https://openalex.org/", "").strip().upper()
|
||||
return f"https://openalex.org/{short_id}"
|
||||
|
||||
|
||||
def _raw_institution_id(value: str) -> str:
|
||||
return value.replace("https://openalex.org/", "").strip().upper()
|
||||
|
||||
|
||||
def _institution_works_query(institution_id: str) -> dict[str, Any]:
|
||||
return {
|
||||
"nested": {
|
||||
"path": "authorships.institutions",
|
||||
"query": {"term": {"authorships.institutions.id": institution_id}},
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
def _year_totals(response: dict[str, Any]) -> dict[int, int]:
|
||||
buckets = (
|
||||
response.get("aggregations", {})
|
||||
.get("publication_years", {})
|
||||
.get("buckets", [])
|
||||
)
|
||||
return {
|
||||
int(bucket["key"]): int(bucket.get("doc_count", 0))
|
||||
for bucket in buckets
|
||||
if bucket.get("key") is not None
|
||||
}
|
||||
|
||||
|
||||
async def _field_names(field_ids: list[str | None]) -> dict[str, str]:
|
||||
ids = [field_id for field_id in field_ids if field_id]
|
||||
if not ids:
|
||||
return {}
|
||||
try:
|
||||
response = await elasticsearch.search(
|
||||
index="openalex-fields",
|
||||
query={"terms": {"id": ids}},
|
||||
source=["id", "display_name"],
|
||||
size=len(ids),
|
||||
cluster=ESCluster.NES,
|
||||
)
|
||||
except Exception:
|
||||
logger.exception("Could not load dashboard field names.")
|
||||
return {}
|
||||
|
||||
return {
|
||||
source["id"]: source["display_name"]
|
||||
for hit in response.get("hits", {}).get("hits", [])
|
||||
if (source := hit.get("_source", {})).get("id")
|
||||
and source.get("display_name")
|
||||
}
|
||||
|
||||
|
||||
def _topic_heatmap_field(
|
||||
bucket: dict[str, Any],
|
||||
years: list[int],
|
||||
year_totals: dict[int, int],
|
||||
field_names: dict[str, str],
|
||||
) -> TopicHeatmapField:
|
||||
field_id = str(bucket["key"])
|
||||
by_year = {
|
||||
int(year_bucket["key"]): int(year_bucket.get("doc_count", 0))
|
||||
for year_bucket in (
|
||||
bucket.get("works", {}).get("by_year", {}).get("buckets", [])
|
||||
)
|
||||
if year_bucket.get("key") is not None
|
||||
}
|
||||
values = []
|
||||
for year in years:
|
||||
count = by_year.get(year, 0)
|
||||
total = year_totals.get(year, 0)
|
||||
values.append(
|
||||
TopicHeatmapValue(
|
||||
year=year,
|
||||
count=count,
|
||||
share=(count / total) if total else 0,
|
||||
)
|
||||
)
|
||||
|
||||
return TopicHeatmapField(
|
||||
id=field_id,
|
||||
name=_field_name(bucket, field_names.get(field_id, field_id)),
|
||||
total=int(bucket.get("works", {}).get("doc_count", 0)),
|
||||
values=values,
|
||||
)
|
||||
|
||||
|
||||
def _field_name(bucket: dict[str, Any], fallback: str) -> str:
|
||||
name_buckets = bucket.get("field_name", {}).get("buckets", [])
|
||||
if name_buckets and name_buckets[0].get("key"):
|
||||
return str(name_buckets[0]["key"])
|
||||
return fallback
|
||||
|
||||
|
||||
def _short_author_id(value: str) -> str:
|
||||
return value.replace("https://openalex.org/", "").strip().upper()
|
||||
|
||||
|
||||
def _top_work_authors(
|
||||
authors: list[dict[str, Any]],
|
||||
works_period: WorksPeriod,
|
||||
) -> list[TopAuthor]:
|
||||
if works_period == "last_5_years":
|
||||
from_year = datetime.now().year - 4
|
||||
ranked_authors = sorted(
|
||||
(
|
||||
{
|
||||
**author,
|
||||
"selected_works_count": _works_count_since(author, from_year),
|
||||
}
|
||||
for author in authors
|
||||
),
|
||||
key=lambda author: author["selected_works_count"],
|
||||
reverse=True,
|
||||
)
|
||||
else:
|
||||
ranked_authors = [
|
||||
{**author, "selected_works_count": author["works_count"]}
|
||||
for author in authors
|
||||
]
|
||||
|
||||
return [
|
||||
TopAuthor(
|
||||
id=_short_author_id(author["id"]),
|
||||
name=author["name"],
|
||||
count=author["selected_works_count"],
|
||||
)
|
||||
for author in ranked_authors[:TOP_AUTHOR_LIMIT]
|
||||
if author["selected_works_count"] > 0
|
||||
]
|
||||
|
||||
|
||||
def _works_count_since(author: dict[str, Any], from_year: int) -> int:
|
||||
return sum(
|
||||
int(item.get("works_count", 0) or 0)
|
||||
for item in author.get("counts_by_year", [])
|
||||
if int(item.get("year", 0) or 0) >= from_year
|
||||
)
|
||||
|
||||
|
||||
async def _safe_institution_authors(institution_id: str) -> list[dict[str, Any]]:
|
||||
try:
|
||||
return await _institution_authors(institution_id)
|
||||
except Exception:
|
||||
logger.exception("Could not load authors for institution %s.", institution_id)
|
||||
return []
|
||||
|
||||
|
||||
async def _safe_institution_aliases(
|
||||
institution_id: str,
|
||||
organization_name: str,
|
||||
) -> list[str]:
|
||||
try:
|
||||
return await _institution_aliases(institution_id, organization_name)
|
||||
except Exception:
|
||||
logger.exception("Could not load aliases for institution %s.", institution_id)
|
||||
return [organization_name]
|
||||
|
||||
|
||||
async def _institution_authors(institution_id: str) -> list[dict[str, Any]]:
|
||||
response = await elasticsearch.search(
|
||||
index=ESIndex.OPENALEX_AUTHORS,
|
||||
query={
|
||||
"nested": {
|
||||
"path": "last_known_institutions",
|
||||
"query": {"term": {"last_known_institutions.id": institution_id}},
|
||||
}
|
||||
},
|
||||
source=["id", "display_name", "works_count", "counts_by_year"],
|
||||
size=10000,
|
||||
sort=[{"works_count": {"order": "desc", "missing": "_last"}}],
|
||||
cluster=ESCluster.NES,
|
||||
)
|
||||
return [
|
||||
{
|
||||
"id": str(source["id"]),
|
||||
"name": str(source["display_name"]),
|
||||
"works_count": int(source.get("works_count", 0)),
|
||||
"counts_by_year": source.get("counts_by_year", []) or [],
|
||||
}
|
||||
for hit in response.get("hits", {}).get("hits", [])
|
||||
if (source := hit.get("_source", {})).get("id")
|
||||
and source.get("display_name")
|
||||
]
|
||||
|
||||
|
||||
async def _top_project_authors(
|
||||
authors: list[dict[str, Any]],
|
||||
aliases: list[str],
|
||||
) -> list[TopAuthor]:
|
||||
if not aliases:
|
||||
return []
|
||||
counts: dict[str, int] = {}
|
||||
names: dict[str, str] = {}
|
||||
for bucket in await _top_bund_project_author_buckets(aliases):
|
||||
key = str(bucket.get("key", "")).strip()
|
||||
if key:
|
||||
normalized_key = key.casefold()
|
||||
names[normalized_key] = key
|
||||
counts[normalized_key] = counts.get(normalized_key, 0) + int(
|
||||
bucket.get("doc_count", 0)
|
||||
)
|
||||
|
||||
institution_authors = {author["name"].casefold(): author for author in authors}
|
||||
ranked = sorted(
|
||||
(
|
||||
(name, count)
|
||||
for name, count in counts.items()
|
||||
if count > 0
|
||||
),
|
||||
key=lambda item: (-item[1], names[item[0]].casefold()),
|
||||
)
|
||||
return [
|
||||
TopAuthor(
|
||||
id=(
|
||||
_short_author_id(institution_authors[name]["id"])
|
||||
if name in institution_authors
|
||||
else None
|
||||
),
|
||||
name=(
|
||||
institution_authors[name]["name"]
|
||||
if name in institution_authors
|
||||
else names[name]
|
||||
),
|
||||
count=count,
|
||||
)
|
||||
for name, count in ranked[:TOP_AUTHOR_LIMIT]
|
||||
]
|
||||
|
||||
|
||||
async def _top_bund_project_author_buckets(
|
||||
aliases: list[str],
|
||||
) -> list[dict[str, Any]]:
|
||||
response = await elasticsearch.search(
|
||||
index=ESIndex.PROJECTS_BUND_V1,
|
||||
body={
|
||||
"size": 0,
|
||||
"query": _alias_match_query("Zuwendungsempfänger", aliases),
|
||||
"aggs": {
|
||||
"people": {
|
||||
"terms": {
|
||||
"script": {
|
||||
"lang": "painless",
|
||||
"source": _bund_persons_script(),
|
||||
},
|
||||
"size": 10000,
|
||||
}
|
||||
}
|
||||
},
|
||||
},
|
||||
cluster=ESCluster.INSE,
|
||||
)
|
||||
return (
|
||||
response.get("aggregations", {}).get("people", {}).get("buckets", [])
|
||||
)
|
||||
|
||||
|
||||
def _bund_persons_script() -> str:
|
||||
return (
|
||||
"def names = new HashSet(); "
|
||||
"if (params['_source'].containsKey('Arb') && params['_source']['Arb'] != null) { "
|
||||
" for (entry in params['_source']['Arb'].entrySet()) { "
|
||||
" def value = entry.getValue(); "
|
||||
" if (value instanceof String && value.length() > 0) { "
|
||||
" if (value.contains(';')) { "
|
||||
" for (name in value.splitOnToken(';')) { names.add(name.trim()); } "
|
||||
" } else { names.add(value.trim()); } "
|
||||
" } "
|
||||
" } "
|
||||
"} "
|
||||
"return new ArrayList(names);"
|
||||
)
|
||||
|
||||
|
||||
async def _top_patent_authors(institution_id: str) -> list[TopAuthor]:
|
||||
client = OrgPatentsSearchClient()
|
||||
authors = await client.top_authors_by_institution(
|
||||
institution_id=institution_id,
|
||||
size=TOP_AUTHOR_LIMIT,
|
||||
)
|
||||
return [
|
||||
TopAuthor(
|
||||
id=_short_author_id(author["id"]),
|
||||
name=author["name"],
|
||||
count=author["count"],
|
||||
)
|
||||
for author in authors
|
||||
]
|
||||
|
||||
|
||||
async def _top_news_authors(authors: list[dict[str, Any]]) -> list[TopAuthor]:
|
||||
if not authors:
|
||||
return []
|
||||
|
||||
author_names = [author["name"] for author in authors]
|
||||
response = await elasticsearch.search(
|
||||
index="aktuell_postproc",
|
||||
body={
|
||||
"size": 0,
|
||||
"query": {"terms": {"authors.keyword": author_names}},
|
||||
"aggs": {
|
||||
"authors": {
|
||||
"terms": {
|
||||
"field": "authors.keyword",
|
||||
"size": 10000,
|
||||
"order": [
|
||||
{"_count": "desc"},
|
||||
{"_key": "asc"},
|
||||
],
|
||||
}
|
||||
}
|
||||
},
|
||||
},
|
||||
cluster=ESCluster.INSE,
|
||||
)
|
||||
buckets = response.get("aggregations", {}).get("authors", {}).get("buckets", [])
|
||||
institution_authors = {author["name"].casefold(): author for author in authors}
|
||||
|
||||
return [
|
||||
TopAuthor(
|
||||
id=_short_author_id(institution_authors[str(bucket["key"]).casefold()]["id"]),
|
||||
name=institution_authors[str(bucket["key"]).casefold()]["name"],
|
||||
count=int(bucket.get("doc_count", 0)),
|
||||
)
|
||||
for bucket in buckets
|
||||
if str(bucket.get("key", "")).casefold() in institution_authors
|
||||
][:TOP_AUTHOR_LIMIT]
|
||||
@@ -0,0 +1,531 @@
|
||||
from unittest.mock import AsyncMock, patch
|
||||
from datetime import datetime
|
||||
|
||||
import pytest
|
||||
from fastapi import HTTPException
|
||||
from sqlmodel import Session, SQLModel, create_engine
|
||||
|
||||
from inse import config
|
||||
from inse.auth.model import AccessToken, Organization, UserRole
|
||||
from inse.dashboard.service import (
|
||||
get_dashboard_organization,
|
||||
get_dashboard_statistics,
|
||||
get_top_authors,
|
||||
get_topic_heatmap,
|
||||
)
|
||||
from inse.model import ESCluster, ESIndex
|
||||
|
||||
ORG_INSTITUTION_ID = "https://openalex.org/I123"
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def anyio_backend():
|
||||
return "asyncio"
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_dashboard_statistics_counts_organization_data_and_all_projects():
|
||||
async def search(**kwargs):
|
||||
index = kwargs["index"]
|
||||
if index == config.settings.openalex_works_search_index:
|
||||
return {"hits": {"total": {"value": 120}}}
|
||||
if index == ESIndex.OPENALEX_AUTHORS:
|
||||
return {"hits": {"total": {"value": 35}}}
|
||||
if index == ESIndex.CORDIS_EU_ORGANIZATIONS_WILDCARD:
|
||||
return {"aggregations": {"projects": {"value": 10}}}
|
||||
if index == ESIndex.PROJECTS_BUND_V1:
|
||||
return {"hits": {"total": {"value": 5}}}
|
||||
return {"hits": {"total": {"value": 3}}}
|
||||
|
||||
with patch(
|
||||
"inse.dashboard.service.elasticsearch.search",
|
||||
new=AsyncMock(side_effect=search),
|
||||
) as mocked_search, patch(
|
||||
"inse.dashboard.service.InstitutionsSearchClient.get_institution_aliases_by_oa_institution_id",
|
||||
new=AsyncMock(return_value=["Example University", "Example Uni"]),
|
||||
):
|
||||
result = await get_dashboard_statistics(ORG_INSTITUTION_ID, "Example Org")
|
||||
|
||||
assert result.model_dump() == {
|
||||
"institution_id": ORG_INSTITUTION_ID,
|
||||
"organization_name": "Example Org",
|
||||
"publications": 120,
|
||||
"persons": 35,
|
||||
"projects": 18,
|
||||
"dfg_projects": 3,
|
||||
"eu_projects": 10,
|
||||
"bmbf_projects": 5,
|
||||
}
|
||||
calls = mocked_search.await_args_list
|
||||
assert calls[0].kwargs["index"] == config.settings.openalex_works_search_index
|
||||
assert calls[0].kwargs["query"]["nested"]["query"]["term"] == {
|
||||
"authorships.institutions.id": ORG_INSTITUTION_ID
|
||||
}
|
||||
assert calls[1].kwargs["query"]["nested"]["query"]["term"] == {
|
||||
"affiliations.institution.id": ORG_INSTITUTION_ID
|
||||
}
|
||||
assert all(call.kwargs["cluster"] == ESCluster.INSE for call in calls[2:])
|
||||
assert [call.kwargs["index"] for call in calls[2:]] == [
|
||||
ESIndex.CORDIS_EU_ORGANIZATIONS_WILDCARD,
|
||||
ESIndex.PROJECTS_BUND_V1,
|
||||
ESIndex.PROJECTS_DFG_ALL,
|
||||
]
|
||||
assert calls[2].kwargs["body"]["query"] == {
|
||||
"terms": {
|
||||
"name.keyword": [
|
||||
"EXAMPLE ORG",
|
||||
"EXAMPLE UNI",
|
||||
"EXAMPLE UNIVERSITY",
|
||||
]
|
||||
}
|
||||
}
|
||||
assert calls[3].kwargs["query"]["bool"]["minimum_should_match"] == 1
|
||||
assert calls[3].kwargs["query"]["bool"]["should"][0]["match"] == {
|
||||
"Zuwendungsempfänger": {
|
||||
"query": "Example Org",
|
||||
"operator": "and",
|
||||
}
|
||||
}
|
||||
assert calls[4].kwargs["query"]["bool"]["minimum_should_match"] == 1
|
||||
assert calls[4].kwargs["query"]["bool"]["should"][0]["bool"]["should"][0][
|
||||
"match"
|
||||
] == {
|
||||
"Antragstellende Institution": {
|
||||
"query": "Example Org",
|
||||
"operator": "and",
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_top_authors_maps_works_and_bund_project_aggregations():
|
||||
async def search(**kwargs):
|
||||
if kwargs["index"] == ESIndex.OPENALEX_AUTHORS:
|
||||
return {
|
||||
"hits": {
|
||||
"hits": [
|
||||
{
|
||||
"_source": {
|
||||
"id": "https://openalex.org/A1",
|
||||
"display_name": "Ada Example",
|
||||
"works_count": 42,
|
||||
"counts_by_year": [],
|
||||
}
|
||||
},
|
||||
{
|
||||
"_source": {
|
||||
"id": "https://openalex.org/A2",
|
||||
"display_name": "Grace Example",
|
||||
"works_count": 12,
|
||||
"counts_by_year": [],
|
||||
}
|
||||
},
|
||||
]
|
||||
}
|
||||
}
|
||||
if kwargs["index"] == "aktuell_postproc":
|
||||
return {
|
||||
"aggregations": {
|
||||
"authors": {
|
||||
"buckets": [{"key": "Ada Example", "doc_count": 6}]
|
||||
}
|
||||
}
|
||||
}
|
||||
if kwargs["index"] == ESIndex.PROJECTS_BUND_V1:
|
||||
return {
|
||||
"aggregations": {
|
||||
"people": {
|
||||
"buckets": [{"key": "Grace Example", "doc_count": 3}]
|
||||
}
|
||||
}
|
||||
}
|
||||
return {"aggregations": {"people": {"buckets": []}}}
|
||||
|
||||
with patch(
|
||||
"inse.dashboard.service.elasticsearch.search",
|
||||
new=AsyncMock(side_effect=search),
|
||||
) as mocked_search, patch(
|
||||
"inse.dashboard.service.InstitutionsSearchClient.get_institution_aliases_by_oa_institution_id",
|
||||
new=AsyncMock(return_value=["Example University"]),
|
||||
), patch(
|
||||
"inse.dashboard.service.OrgPatentsSearchClient.top_authors_by_institution",
|
||||
new=AsyncMock(
|
||||
return_value=[
|
||||
{"id": "A1", "name": "Ada Example", "count": 4},
|
||||
]
|
||||
),
|
||||
):
|
||||
result = await get_top_authors(ORG_INSTITUTION_ID, "Example Org")
|
||||
|
||||
assert result.works[0].model_dump() == {
|
||||
"id": "A1",
|
||||
"name": "Ada Example",
|
||||
"count": 42,
|
||||
}
|
||||
assert result.projects[0].model_dump() == {
|
||||
"id": "A2",
|
||||
"name": "Grace Example",
|
||||
"count": 3,
|
||||
}
|
||||
assert result.patents[0].model_dump() == {
|
||||
"id": "A1",
|
||||
"name": "Ada Example",
|
||||
"count": 4,
|
||||
}
|
||||
assert result.news[0].model_dump() == {
|
||||
"id": "A1",
|
||||
"name": "Ada Example",
|
||||
"count": 6,
|
||||
}
|
||||
project_calls = [
|
||||
call
|
||||
for call in mocked_search.await_args_list
|
||||
if call.kwargs["index"]
|
||||
in {ESIndex.PROJECTS_DFG_ALL, ESIndex.PROJECTS_BUND_V1}
|
||||
]
|
||||
assert len(project_calls) == 1
|
||||
assert project_calls[0].kwargs["index"] == ESIndex.PROJECTS_BUND_V1
|
||||
assert project_calls[0].kwargs["body"]["query"]["bool"]["should"][0]["match"] == {
|
||||
"Zuwendungsempfänger": {
|
||||
"query": "Example Org",
|
||||
"operator": "and",
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_top_authors_keeps_bund_project_authors_without_openalex_match():
|
||||
async def search(**kwargs):
|
||||
if kwargs["index"] == ESIndex.OPENALEX_AUTHORS:
|
||||
return {"hits": {"hits": []}}
|
||||
if kwargs["index"] == ESIndex.PROJECTS_BUND_V1:
|
||||
return {
|
||||
"aggregations": {
|
||||
"people": {
|
||||
"buckets": [{"key": "Project Person", "doc_count": 9}]
|
||||
}
|
||||
}
|
||||
}
|
||||
return {"aggregations": {"people": {"buckets": []}}}
|
||||
|
||||
with patch(
|
||||
"inse.dashboard.service.elasticsearch.search",
|
||||
new=AsyncMock(side_effect=search),
|
||||
), patch(
|
||||
"inse.dashboard.service.InstitutionsSearchClient.get_institution_aliases_by_oa_institution_id",
|
||||
new=AsyncMock(return_value=["Example University"]),
|
||||
), patch(
|
||||
"inse.dashboard.service.OrgPatentsSearchClient.top_authors_by_institution",
|
||||
new=AsyncMock(return_value=[]),
|
||||
):
|
||||
result = await get_top_authors(ORG_INSTITUTION_ID, "Example Org")
|
||||
|
||||
assert result.projects[0].model_dump() == {
|
||||
"id": None,
|
||||
"name": "Project Person",
|
||||
"count": 9,
|
||||
}
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_top_authors_returns_top_ten_bund_project_people_by_project_count():
|
||||
async def search(**kwargs):
|
||||
if kwargs["index"] == ESIndex.OPENALEX_AUTHORS:
|
||||
return {"hits": {"hits": []}}
|
||||
if kwargs["index"] == ESIndex.PROJECTS_BUND_V1:
|
||||
return {
|
||||
"aggregations": {
|
||||
"people": {
|
||||
"buckets": [
|
||||
{"key": f"Project Person {count}", "doc_count": count}
|
||||
for count in range(1, 12)
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
return {"aggregations": {"people": {"buckets": []}}}
|
||||
|
||||
with patch(
|
||||
"inse.dashboard.service.elasticsearch.search",
|
||||
new=AsyncMock(side_effect=search),
|
||||
), patch(
|
||||
"inse.dashboard.service.InstitutionsSearchClient.get_institution_aliases_by_oa_institution_id",
|
||||
new=AsyncMock(return_value=["Example University"]),
|
||||
), patch(
|
||||
"inse.dashboard.service.OrgPatentsSearchClient.top_authors_by_institution",
|
||||
new=AsyncMock(return_value=[]),
|
||||
):
|
||||
result = await get_top_authors(ORG_INSTITUTION_ID, "Example Org")
|
||||
|
||||
assert [author.count for author in result.projects] == list(range(11, 1, -1))
|
||||
assert result.projects[0].name == "Project Person 11"
|
||||
assert len(result.projects) == 10
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_top_authors_returns_partial_response_when_one_source_fails():
|
||||
async def search(**kwargs):
|
||||
if kwargs["index"] == ESIndex.OPENALEX_AUTHORS:
|
||||
return {
|
||||
"hits": {
|
||||
"hits": [
|
||||
{
|
||||
"_source": {
|
||||
"id": "https://openalex.org/A1",
|
||||
"display_name": "Ada Example",
|
||||
"works_count": 42,
|
||||
"counts_by_year": [],
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
raise RuntimeError("projects unavailable")
|
||||
|
||||
with patch(
|
||||
"inse.dashboard.service.elasticsearch.search",
|
||||
new=AsyncMock(side_effect=search),
|
||||
), patch(
|
||||
"inse.dashboard.service.InstitutionsSearchClient.get_institution_aliases_by_oa_institution_id",
|
||||
new=AsyncMock(return_value=["Example University"]),
|
||||
), patch(
|
||||
"inse.dashboard.service.OrgPatentsSearchClient.top_authors_by_institution",
|
||||
new=AsyncMock(return_value=[]),
|
||||
):
|
||||
result = await get_top_authors(ORG_INSTITUTION_ID, "Example Org")
|
||||
|
||||
assert result.works[0].name == "Ada Example"
|
||||
assert result.projects == []
|
||||
assert result.patents == []
|
||||
assert result.news == []
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_top_authors_can_rank_works_by_last_five_years():
|
||||
current_year = datetime.now().year
|
||||
|
||||
async def search(**kwargs):
|
||||
if kwargs["index"] == ESIndex.OPENALEX_AUTHORS:
|
||||
return {
|
||||
"hits": {
|
||||
"hits": [
|
||||
{
|
||||
"_source": {
|
||||
"id": "https://openalex.org/A1",
|
||||
"display_name": "Ada Example",
|
||||
"works_count": 100,
|
||||
"counts_by_year": [
|
||||
{"year": current_year - 6, "works_count": 90},
|
||||
{"year": current_year - 1, "works_count": 2},
|
||||
],
|
||||
}
|
||||
},
|
||||
{
|
||||
"_source": {
|
||||
"id": "https://openalex.org/A2",
|
||||
"display_name": "Grace Example",
|
||||
"works_count": 50,
|
||||
"counts_by_year": [
|
||||
{"year": current_year - 1, "works_count": 12},
|
||||
{"year": current_year, "works_count": 4},
|
||||
],
|
||||
}
|
||||
},
|
||||
]
|
||||
}
|
||||
}
|
||||
return {"aggregations": {"people": {"buckets": []}}}
|
||||
|
||||
with patch(
|
||||
"inse.dashboard.service.elasticsearch.search",
|
||||
new=AsyncMock(side_effect=search),
|
||||
), patch(
|
||||
"inse.dashboard.service.InstitutionsSearchClient.get_institution_aliases_by_oa_institution_id",
|
||||
new=AsyncMock(return_value=["Example University"]),
|
||||
), patch(
|
||||
"inse.dashboard.service.OrgPatentsSearchClient.top_authors_by_institution",
|
||||
new=AsyncMock(return_value=[]),
|
||||
):
|
||||
result = await get_top_authors(
|
||||
ORG_INSTITUTION_ID,
|
||||
"Example Org",
|
||||
works_period="last_5_years",
|
||||
)
|
||||
|
||||
assert result.works[0].model_dump() == {
|
||||
"id": "A2",
|
||||
"name": "Grace Example",
|
||||
"count": 16,
|
||||
}
|
||||
assert result.works[1].model_dump() == {
|
||||
"id": "A1",
|
||||
"name": "Ada Example",
|
||||
"count": 2,
|
||||
}
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_topic_heatmap_maps_field_year_counts_and_shares():
|
||||
async def search(**kwargs):
|
||||
if kwargs["index"] == config.settings.openalex_works_search_index:
|
||||
return {
|
||||
"aggregations": {
|
||||
"publication_years": {
|
||||
"buckets": [
|
||||
{"key": 2023, "doc_count": 10},
|
||||
{"key": 2024, "doc_count": 20},
|
||||
]
|
||||
},
|
||||
"topics_nested": {
|
||||
"fields": {
|
||||
"buckets": [
|
||||
{
|
||||
"key": "https://openalex.org/fields/17",
|
||||
"field_name": {
|
||||
"buckets": [
|
||||
{
|
||||
"key": "Computer Science",
|
||||
"doc_count": 12,
|
||||
}
|
||||
]
|
||||
},
|
||||
"works": {
|
||||
"doc_count": 12,
|
||||
"by_year": {
|
||||
"buckets": [
|
||||
{"key": 2023, "doc_count": 4},
|
||||
{"key": 2024, "doc_count": 8},
|
||||
]
|
||||
},
|
||||
},
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
return {
|
||||
"hits": {
|
||||
"hits": [
|
||||
{
|
||||
"_source": {
|
||||
"id": "https://openalex.org/fields/17",
|
||||
"display_name": "Computer Science",
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
with patch(
|
||||
"inse.dashboard.service.elasticsearch.search",
|
||||
new=AsyncMock(side_effect=search),
|
||||
) as mocked_search:
|
||||
result = await get_topic_heatmap(
|
||||
institution_id=ORG_INSTITUTION_ID,
|
||||
organization_name="Example Org",
|
||||
from_year=2023,
|
||||
to_year=2024,
|
||||
limit=10,
|
||||
)
|
||||
|
||||
assert result.institution_id == ORG_INSTITUTION_ID
|
||||
assert result.organization_name == "Example Org"
|
||||
assert result.years == [2023, 2024]
|
||||
assert result.fields[0].model_dump() == {
|
||||
"id": "https://openalex.org/fields/17",
|
||||
"name": "Computer Science",
|
||||
"total": 12,
|
||||
"values": [
|
||||
{"year": 2023, "count": 4, "share": 0.4},
|
||||
{"year": 2024, "count": 8, "share": 0.4},
|
||||
],
|
||||
}
|
||||
body = mocked_search.await_args_list[0].kwargs["body"]
|
||||
assert body["query"]["bool"]["must"][0]["nested"]["query"]["term"] == {
|
||||
"authorships.institutions.id": ORG_INSTITUTION_ID
|
||||
}
|
||||
assert (
|
||||
body["aggs"]["topics_nested"]["aggs"]["fields"]["terms"]["field"]
|
||||
== "topics.field.id"
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_topic_heatmap_defaults_to_last_five_years():
|
||||
async def search(**kwargs):
|
||||
if kwargs["index"] == config.settings.openalex_works_search_index:
|
||||
return {
|
||||
"aggregations": {
|
||||
"publication_years": {"buckets": []},
|
||||
"topics_nested": {"fields": {"buckets": []}},
|
||||
}
|
||||
}
|
||||
return {"hits": {"hits": []}}
|
||||
|
||||
with patch(
|
||||
"inse.dashboard.service.elasticsearch.search",
|
||||
new=AsyncMock(side_effect=search),
|
||||
) as mocked_search:
|
||||
result = await get_topic_heatmap(
|
||||
institution_id=ORG_INSTITUTION_ID,
|
||||
organization_name="Example Org",
|
||||
)
|
||||
|
||||
current_year = datetime.now().year
|
||||
assert result.years == list(range(current_year - 4, current_year + 1))
|
||||
body = mocked_search.await_args_list[0].kwargs["body"]
|
||||
assert body["query"]["bool"]["filter"][0]["range"]["publication_year"] == {
|
||||
"gte": current_year - 4,
|
||||
"lte": current_year,
|
||||
}
|
||||
|
||||
|
||||
def test_get_dashboard_organization_uses_effective_organization():
|
||||
engine = create_engine("sqlite://", connect_args={"check_same_thread": False})
|
||||
SQLModel.metadata.create_all(engine)
|
||||
|
||||
with Session(engine) as session:
|
||||
organization = Organization(
|
||||
name="Example University",
|
||||
openalex_institution_id="I456",
|
||||
)
|
||||
session.add(organization)
|
||||
session.commit()
|
||||
session.refresh(organization)
|
||||
|
||||
token = _access_token(organization.id)
|
||||
|
||||
result = get_dashboard_organization(session, token)
|
||||
|
||||
assert result.id == organization.id
|
||||
assert result.openalex_institution_id == "I456"
|
||||
|
||||
|
||||
def test_get_dashboard_organization_rejects_missing_openalex_id():
|
||||
engine = create_engine("sqlite://", connect_args={"check_same_thread": False})
|
||||
SQLModel.metadata.create_all(engine)
|
||||
|
||||
with Session(engine) as session:
|
||||
organization = Organization(name="Example University")
|
||||
session.add(organization)
|
||||
session.commit()
|
||||
session.refresh(organization)
|
||||
|
||||
with pytest.raises(HTTPException) as exc_info:
|
||||
get_dashboard_organization(session, _access_token(organization.id))
|
||||
|
||||
assert exc_info.value.status_code == 422
|
||||
|
||||
|
||||
def _access_token(organization_id):
|
||||
return AccessToken(
|
||||
real_account_id=organization_id,
|
||||
effective_account_id=organization_id,
|
||||
effective_role=UserRole.USER,
|
||||
effective_organization_id=organization_id,
|
||||
expires_at="2099-01-01T00:00:00Z",
|
||||
epoch=0,
|
||||
user_fingerprint_hash="hash",
|
||||
raw_token="token",
|
||||
)
|
||||
@@ -37,6 +37,7 @@ from inse.news.service import router as news_service_router
|
||||
from inse.auth.router import router as auth_router
|
||||
from inse.account_management.router import router as account_management_router
|
||||
from inse.organization_management.router import router as organization_management_router
|
||||
from inse.dashboard.router import router as dashboard_router
|
||||
|
||||
from inse.institutions.router import router as institutions_router
|
||||
from inse.database import create_db_and_tables, get_session
|
||||
@@ -101,6 +102,7 @@ app.include_router(service_router)
|
||||
app.include_router(auth_router)
|
||||
app.include_router(account_management_router)
|
||||
app.include_router(organization_management_router)
|
||||
app.include_router(dashboard_router)
|
||||
|
||||
|
||||
app.add_middleware(
|
||||
|
||||
@@ -300,6 +300,71 @@ class OrgPatentsSearchClient:
|
||||
patents = [_hit_to_org_patent(hit) for hit in data.get("hits", {}).get("hits", [])]
|
||||
return patents, total
|
||||
|
||||
async def top_authors_by_institution(
|
||||
self,
|
||||
institution_id: str,
|
||||
size: int = 10,
|
||||
) -> list[dict[str, Any]]:
|
||||
short_id = institution_id.replace("https://openalex.org/", "").upper()
|
||||
payload = {
|
||||
"size": 0,
|
||||
"query": {"term": {"institution_id": short_id}},
|
||||
"aggs": {
|
||||
"matched_authors_nested": {
|
||||
"nested": {"path": "matched_authors"},
|
||||
"aggs": {
|
||||
"authors": {
|
||||
"terms": {
|
||||
"field": "matched_authors.openalex_author_id",
|
||||
"size": size,
|
||||
"order": [{"_count": "desc"}, {"_key": "asc"}],
|
||||
},
|
||||
"aggs": {
|
||||
"names": {
|
||||
"terms": {
|
||||
"field": "matched_authors.author_name",
|
||||
"size": 1,
|
||||
}
|
||||
},
|
||||
"patents": {"reverse_nested": {}},
|
||||
},
|
||||
}
|
||||
},
|
||||
}
|
||||
},
|
||||
}
|
||||
|
||||
async with httpx.AsyncClient(
|
||||
base_url=self.base_url,
|
||||
timeout=self.timeout,
|
||||
transport=self.transport,
|
||||
) as client:
|
||||
response = await client.post(
|
||||
f"/{ORG_PATENTS_INDEX}/_search",
|
||||
headers=self._headers(),
|
||||
json=payload,
|
||||
)
|
||||
if response.status_code == 404:
|
||||
return []
|
||||
response.raise_for_status()
|
||||
data = response.json()
|
||||
|
||||
buckets = (
|
||||
data.get("aggregations", {})
|
||||
.get("matched_authors_nested", {})
|
||||
.get("authors", {})
|
||||
.get("buckets", [])
|
||||
)
|
||||
return [
|
||||
{
|
||||
"id": bucket.get("key"),
|
||||
"name": _top_author_name(bucket),
|
||||
"count": int(bucket.get("patents", {}).get("doc_count", 0)),
|
||||
}
|
||||
for bucket in buckets
|
||||
if bucket.get("key")
|
||||
]
|
||||
|
||||
|
||||
def _hit_to_org_patent(hit: dict[str, Any]) -> OrgPatentEntry:
|
||||
source = hit.get("_source", {})
|
||||
@@ -327,3 +392,10 @@ def _hit_to_org_patent(hit: dict[str, Any]) -> OrgPatentEntry:
|
||||
country=source.get("country"),
|
||||
matched_authors=source.get("matched_authors") or [],
|
||||
)
|
||||
|
||||
|
||||
def _top_author_name(bucket: dict[str, Any]) -> str:
|
||||
name_buckets = bucket.get("names", {}).get("buckets", [])
|
||||
if name_buckets:
|
||||
return str(name_buckets[0].get("key") or bucket.get("key"))
|
||||
return str(bucket.get("key"))
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
import json
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
|
||||
from inse.patents.org.elastic_search_client import OrgPatentsSearchClient
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_top_authors_by_institution_aggregates_matched_authors():
|
||||
requests: list[httpx.Request] = []
|
||||
|
||||
def handler(request: httpx.Request) -> httpx.Response:
|
||||
requests.append(request)
|
||||
return httpx.Response(
|
||||
200,
|
||||
json={
|
||||
"aggregations": {
|
||||
"matched_authors_nested": {
|
||||
"authors": {
|
||||
"buckets": [
|
||||
{
|
||||
"key": "A1",
|
||||
"patents": {"doc_count": 5},
|
||||
"names": {
|
||||
"buckets": [
|
||||
{"key": "Ada Example", "doc_count": 5}
|
||||
]
|
||||
},
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
)
|
||||
|
||||
client = OrgPatentsSearchClient(
|
||||
base_url="https://example.test",
|
||||
api_key="key",
|
||||
transport=httpx.MockTransport(handler),
|
||||
)
|
||||
|
||||
result = await client.top_authors_by_institution(
|
||||
"https://openalex.org/I123",
|
||||
size=10,
|
||||
)
|
||||
|
||||
assert result == [{"id": "A1", "name": "Ada Example", "count": 5}]
|
||||
payload = json.loads(requests[0].content)
|
||||
assert payload["query"] == {"term": {"institution_id": "I123"}}
|
||||
assert (
|
||||
payload["aggs"]["matched_authors_nested"]["nested"]["path"]
|
||||
== "matched_authors"
|
||||
)
|
||||
@@ -13,3 +13,4 @@ class Tags(StrEnum):
|
||||
ACCOUNT = "Account"
|
||||
ORGANIZATION = "Organization"
|
||||
UNIVERSITY_RANKINGS = "University Rankings"
|
||||
DASHBOARD = "Dashboard"
|
||||
|
||||
@@ -0,0 +1,125 @@
|
||||
import { HttpClient } from '@angular/common/http';
|
||||
import { Injectable, inject } from '@angular/core';
|
||||
import { Observable } from 'rxjs';
|
||||
|
||||
import { Configuration } from '../../api';
|
||||
|
||||
export type TopAuthorsWorksPeriod = 'all_time' | 'last_5_years';
|
||||
|
||||
export interface DashboardStatistics {
|
||||
institution_id: string;
|
||||
organization_name: string;
|
||||
publications: number;
|
||||
persons: number;
|
||||
projects: number;
|
||||
dfg_projects: number;
|
||||
eu_projects: number;
|
||||
bmbf_projects: number;
|
||||
}
|
||||
|
||||
export interface DashboardStatisticValue {
|
||||
institution_id: string;
|
||||
organization_name: string;
|
||||
value: number;
|
||||
}
|
||||
|
||||
export interface TopAuthor {
|
||||
id?: string | null;
|
||||
name: string;
|
||||
count: number;
|
||||
}
|
||||
|
||||
export interface TopAuthorStatistics {
|
||||
institution_id: string;
|
||||
works: TopAuthor[];
|
||||
projects: TopAuthor[];
|
||||
patents: TopAuthor[];
|
||||
news: TopAuthor[];
|
||||
}
|
||||
|
||||
export interface TopicHeatmapValue {
|
||||
year: number;
|
||||
count: number;
|
||||
share: number;
|
||||
}
|
||||
|
||||
export interface TopicHeatmapField {
|
||||
id: string;
|
||||
name: string;
|
||||
total: number;
|
||||
values: TopicHeatmapValue[];
|
||||
}
|
||||
|
||||
export interface TopicHeatmap {
|
||||
institution_id: string;
|
||||
organization_name: string;
|
||||
years: number[];
|
||||
fields: TopicHeatmapField[];
|
||||
}
|
||||
|
||||
@Injectable({ providedIn: 'root' })
|
||||
export class DashboardStatisticsService {
|
||||
private readonly httpClient = inject(HttpClient);
|
||||
private readonly apiConfiguration = inject(Configuration, { optional: true });
|
||||
|
||||
getStatistics(): Observable<DashboardStatistics> {
|
||||
return this.httpClient.get<DashboardStatistics>(
|
||||
`${this.apiConfiguration?.basePath ?? ''}/api/dashboard/statistics`,
|
||||
);
|
||||
}
|
||||
|
||||
getPublicationCount(): Observable<DashboardStatisticValue> {
|
||||
return this.httpClient.get<DashboardStatisticValue>(
|
||||
`${this.apiConfiguration?.basePath ?? ''}/api/dashboard/statistics/publications`,
|
||||
);
|
||||
}
|
||||
|
||||
getPersonCount(): Observable<DashboardStatisticValue> {
|
||||
return this.httpClient.get<DashboardStatisticValue>(
|
||||
`${this.apiConfiguration?.basePath ?? ''}/api/dashboard/statistics/persons`,
|
||||
);
|
||||
}
|
||||
|
||||
getEuProjectCount(): Observable<DashboardStatisticValue> {
|
||||
return this.httpClient.get<DashboardStatisticValue>(
|
||||
`${this.apiConfiguration?.basePath ?? ''}/api/dashboard/statistics/projects/eu`,
|
||||
);
|
||||
}
|
||||
|
||||
getBmbfProjectCount(): Observable<DashboardStatisticValue> {
|
||||
return this.httpClient.get<DashboardStatisticValue>(
|
||||
`${this.apiConfiguration?.basePath ?? ''}/api/dashboard/statistics/projects/bmbf`,
|
||||
);
|
||||
}
|
||||
|
||||
getDfgProjectCount(): Observable<DashboardStatisticValue> {
|
||||
return this.httpClient.get<DashboardStatisticValue>(
|
||||
`${this.apiConfiguration?.basePath ?? ''}/api/dashboard/statistics/projects/dfg`,
|
||||
);
|
||||
}
|
||||
|
||||
getTopAuthors(
|
||||
worksPeriod: TopAuthorsWorksPeriod = 'all_time',
|
||||
): Observable<TopAuthorStatistics> {
|
||||
return this.httpClient.get<TopAuthorStatistics>(
|
||||
`${this.apiConfiguration?.basePath ?? ''}/api/dashboard/top-authors`,
|
||||
{
|
||||
params: { works_period: worksPeriod },
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
getTopicHeatmap(
|
||||
fromYear?: number,
|
||||
toYear?: number,
|
||||
): Observable<TopicHeatmap> {
|
||||
const params: Record<string, number> = {};
|
||||
if (fromYear !== undefined) params['from_year'] = fromYear;
|
||||
if (toYear !== undefined) params['to_year'] = toYear;
|
||||
|
||||
return this.httpClient.get<TopicHeatmap>(
|
||||
`${this.apiConfiguration?.basePath ?? ''}/api/dashboard/topic-heatmap`,
|
||||
{ params },
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,41 +1,253 @@
|
||||
<div class="dashboard-wrapper">
|
||||
<header class="dashboard-header">
|
||||
<h2>University Performance Dashboard</h2>
|
||||
<div class="controls">
|
||||
<select
|
||||
[value]="selectedTopic"
|
||||
(change)="onTopicChange($any($event.target).value)">
|
||||
@for (t of topics; track t) {
|
||||
<option [value]="t">{{ t }}</option>
|
||||
}
|
||||
</select>
|
||||
<section class="statistics-grid" aria-label="Kennzahlen">
|
||||
<a
|
||||
class="statistics-card"
|
||||
[routerLink]="['/institution', institutionRouteId(), 'publications']"
|
||||
[class.disabled]="!institutionRouteId()"
|
||||
[attr.aria-disabled]="!institutionRouteId()"
|
||||
[attr.aria-label]="
|
||||
'Publikationen von ' + organizationName() + ' anzeigen'
|
||||
">
|
||||
<div class="statistics-icon statistics-icon--publications">
|
||||
<mat-icon>menu_book</mat-icon>
|
||||
</div>
|
||||
<div>
|
||||
<span>Publikationen</span>
|
||||
<strong>
|
||||
{{
|
||||
isStatisticLoading('publications')
|
||||
? '…'
|
||||
: ((statistics?.publications | number) ?? '–')
|
||||
}}
|
||||
</strong>
|
||||
</div>
|
||||
</a>
|
||||
|
||||
<div class="toggle-group">
|
||||
<a
|
||||
class="statistics-card"
|
||||
routerLink="/persons"
|
||||
[queryParams]="{ institutionName: organizationName() }"
|
||||
[attr.aria-label]="'Personen von ' + organizationName() + ' anzeigen'">
|
||||
<div class="statistics-icon statistics-icon--persons">
|
||||
<mat-icon>groups</mat-icon>
|
||||
</div>
|
||||
<div>
|
||||
<span>Personen</span>
|
||||
<strong>
|
||||
{{
|
||||
isStatisticLoading('persons')
|
||||
? '…'
|
||||
: ((statistics?.persons | number) ?? '–')
|
||||
}}
|
||||
</strong>
|
||||
</div>
|
||||
</a>
|
||||
|
||||
<a
|
||||
class="statistics-card"
|
||||
routerLink="/projects"
|
||||
[queryParams]="{ selected_project_types: 'eu' }"
|
||||
aria-label="EU-Projekte anzeigen">
|
||||
<div class="statistics-icon statistics-icon--eu-projects">
|
||||
<mat-icon>public</mat-icon>
|
||||
</div>
|
||||
<div>
|
||||
<span>EU-Projekte</span>
|
||||
<strong>
|
||||
{{
|
||||
isStatisticLoading('eu_projects')
|
||||
? '…'
|
||||
: ((statistics?.eu_projects | number) ?? '–')
|
||||
}}
|
||||
</strong>
|
||||
</div>
|
||||
</a>
|
||||
|
||||
<a
|
||||
class="statistics-card"
|
||||
routerLink="/projects"
|
||||
[queryParams]="{ selected_project_types: 'bund' }"
|
||||
aria-label="Bund-Projekte anzeigen">
|
||||
<div class="statistics-icon statistics-icon--bund-projects">
|
||||
<mat-icon>account_balance</mat-icon>
|
||||
</div>
|
||||
<div>
|
||||
<span>Bund-Projekte</span>
|
||||
<strong>
|
||||
{{
|
||||
isStatisticLoading('bmbf_projects')
|
||||
? '…'
|
||||
: ((statistics?.bmbf_projects | number) ?? '–')
|
||||
}}
|
||||
</strong>
|
||||
</div>
|
||||
</a>
|
||||
|
||||
<a
|
||||
class="statistics-card"
|
||||
routerLink="/projects"
|
||||
[queryParams]="{ selected_project_types: 'dfg' }"
|
||||
aria-label="DFG-Projekte anzeigen">
|
||||
<div class="statistics-icon statistics-icon--dfg-projects">
|
||||
<mat-icon>science</mat-icon>
|
||||
</div>
|
||||
<div>
|
||||
<span>DFG-Projekte</span>
|
||||
<strong>
|
||||
{{
|
||||
isStatisticLoading('dfg_projects')
|
||||
? '…'
|
||||
: ((statistics?.dfg_projects | number) ?? '–')
|
||||
}}
|
||||
</strong>
|
||||
</div>
|
||||
</a>
|
||||
</section>
|
||||
|
||||
@if (statisticsError) {
|
||||
<p class="statistics-error">Die Kennzahlen konnten nicht geladen werden.</p>
|
||||
}
|
||||
|
||||
@if (topicHeatmapLoading || topicHeatmapError || hasTopicHeatmapData()) {
|
||||
<section class="topic-heatmap-section">
|
||||
<header class="topic-heatmap-header">
|
||||
<div>
|
||||
<h2>Field Treemap</h2>
|
||||
<p>Publikationen Ihrer Organisation nach Field.</p>
|
||||
</div>
|
||||
<div class="topic-treemap-period-controls" aria-label="Zeitraum">
|
||||
<div class="topic-treemap-period-toggle">
|
||||
<button
|
||||
type="button"
|
||||
[class.active]="topicTreemapPeriod === 'last_5_years'"
|
||||
(click)="setTopicTreemapPeriod('last_5_years')">
|
||||
5 Jahre
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
[class.active]="topicTreemapPeriod === 'last_10_years'"
|
||||
(click)="setTopicTreemapPeriod('last_10_years')">
|
||||
10 Jahre
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
[class.active]="topicTreemapPeriod === 'all_time'"
|
||||
(click)="setTopicTreemapPeriod('all_time')">
|
||||
Alle
|
||||
</button>
|
||||
</div>
|
||||
<label>
|
||||
Von
|
||||
<input
|
||||
type="number"
|
||||
min="1900"
|
||||
max="2100"
|
||||
[value]="topicTreemapFromYear"
|
||||
(change)="onTopicTreemapYearChange('from', $any($event.target).value)" />
|
||||
</label>
|
||||
<label>
|
||||
Bis
|
||||
<input
|
||||
type="number"
|
||||
min="1900"
|
||||
max="2100"
|
||||
[value]="topicTreemapToYear"
|
||||
(change)="onTopicTreemapYearChange('to', $any($event.target).value)" />
|
||||
</label>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
@if (topicHeatmapError) {
|
||||
<p class="statistics-error">
|
||||
Die Field-Treemap konnte nicht geladen werden.
|
||||
</p>
|
||||
} @else {
|
||||
<app-topic-heatmap
|
||||
[heatmap]="topicHeatmap"
|
||||
[loading]="topicHeatmapLoading"></app-topic-heatmap>
|
||||
}
|
||||
</section>
|
||||
}
|
||||
|
||||
@if (topAuthorsLoading || topAuthorsError || hasTopAuthorData()) {
|
||||
<section class="top-authors-section">
|
||||
<header class="top-authors-header">
|
||||
<div>
|
||||
<h2>Top 10 Personen aller Zeiten</h2>
|
||||
<p>Nach Anzahl der Works und Projekte Ihrer Organisation.</p>
|
||||
</div>
|
||||
<div class="top-authors-period-toggle" aria-label="Works-Zeitraum">
|
||||
<button
|
||||
[class.active]="metric === 'publications'"
|
||||
(click)="setMetric('publications')">
|
||||
Publications
|
||||
type="button"
|
||||
[class.active]="topAuthorsWorksPeriod === 'all_time'"
|
||||
(click)="setTopAuthorsWorksPeriod('all_time')">
|
||||
Alle Zeiten
|
||||
</button>
|
||||
<button
|
||||
[class.active]="metric === 'citations'"
|
||||
(click)="setMetric('citations')">
|
||||
Citations
|
||||
type="button"
|
||||
[class.active]="topAuthorsWorksPeriod === 'last_5_years'"
|
||||
(click)="setTopAuthorsWorksPeriod('last_5_years')">
|
||||
Letzte 5 Jahre
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</header>
|
||||
</header>
|
||||
|
||||
<div class="content-grid">
|
||||
<section class="chart-section">
|
||||
<app-university-line-chart
|
||||
[data]="rawDataSource"
|
||||
[metric]="metric"></app-university-line-chart>
|
||||
</section>
|
||||
@if (topAuthorsError) {
|
||||
<p class="statistics-error">
|
||||
Die Autorenstatistiken konnten nicht geladen werden.
|
||||
</p>
|
||||
} @else {
|
||||
<div class="top-authors-grid" [class.loading]="topAuthorsLoading">
|
||||
@for (dataset of visibleTopAuthorDatasets(); track dataset.title) {
|
||||
<article class="top-authors-chart">
|
||||
<h3>
|
||||
<mat-icon>{{ dataset.icon }}</mat-icon
|
||||
>{{ dataset.title }}
|
||||
</h3>
|
||||
@for (
|
||||
entry of dataset.entries;
|
||||
track entry.id || entry.name;
|
||||
let rank = $index
|
||||
) {
|
||||
<div class="author-bar-row">
|
||||
<span class="author-rank">{{ rank + 1 }}</span>
|
||||
<div class="author-bar-content">
|
||||
<div class="author-bar-label">
|
||||
@if (entry.id) {
|
||||
<a
|
||||
class="author-link"
|
||||
[routerLink]="['/person', entry.id, 'overview']"
|
||||
[title]="entry.name">
|
||||
{{ entry.name }}
|
||||
</a>
|
||||
} @else {
|
||||
<span [title]="entry.name">{{ entry.name }}</span>
|
||||
}
|
||||
<strong>{{ entry.count | number }}</strong>
|
||||
</div>
|
||||
<div class="author-bar-track">
|
||||
<span
|
||||
class="author-bar-fill"
|
||||
[style.width.%]="
|
||||
authorBarWidth(dataset.entries, entry.count)
|
||||
"></span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
} @empty {
|
||||
<p class="empty-chart">
|
||||
{{
|
||||
topAuthorsLoading
|
||||
? 'Wird geladen …'
|
||||
: 'Keine Daten vorhanden.'
|
||||
}}
|
||||
</p>
|
||||
}
|
||||
</article>
|
||||
}
|
||||
</div>
|
||||
}
|
||||
</section>
|
||||
}
|
||||
|
||||
<aside class="table-section">
|
||||
<app-university-ranking-table
|
||||
[rankings]="computedRankings"
|
||||
[loading]="isLoading"></app-university-ranking-table>
|
||||
</aside>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -4,92 +4,350 @@
|
||||
font-family: 'Inter', sans-serif;
|
||||
color: #333;
|
||||
|
||||
.dashboard-header {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
.statistics-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
|
||||
gap: 1rem;
|
||||
margin-bottom: 2rem;
|
||||
border-bottom: 1px solid #eee;
|
||||
padding-bottom: 1rem;
|
||||
}
|
||||
|
||||
.content-grid {
|
||||
display: grid;
|
||||
grid-template-columns: 2fr 1fr;
|
||||
gap: 2rem;
|
||||
.statistics-card {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 1rem;
|
||||
min-height: 120px;
|
||||
padding: 1.25rem;
|
||||
border: 1px solid #e2e8f0;
|
||||
border-radius: 12px;
|
||||
background: #fff;
|
||||
box-shadow: 0 4px 14px rgb(15 23 42 / 6%);
|
||||
color: inherit;
|
||||
text-decoration: none;
|
||||
transition:
|
||||
border-color 160ms ease,
|
||||
box-shadow 160ms ease,
|
||||
transform 160ms ease;
|
||||
|
||||
@media (max-width: 1024px) {
|
||||
&:hover {
|
||||
border-color: #93c5fd;
|
||||
box-shadow: 0 8px 24px rgb(15 23 42 / 12%);
|
||||
transform: translateY(-2px);
|
||||
}
|
||||
|
||||
&:focus-visible {
|
||||
outline: 3px solid #93c5fd;
|
||||
outline-offset: 3px;
|
||||
}
|
||||
|
||||
&.disabled {
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
span,
|
||||
small {
|
||||
display: block;
|
||||
color: #64748b;
|
||||
}
|
||||
|
||||
strong {
|
||||
display: block;
|
||||
margin: 0.2rem 0;
|
||||
color: #0f172a;
|
||||
font-size: clamp(1.7rem, 3vw, 2.3rem);
|
||||
line-height: 1.1;
|
||||
}
|
||||
}
|
||||
|
||||
.statistics-icon {
|
||||
display: grid;
|
||||
flex: 0 0 52px;
|
||||
width: 52px;
|
||||
height: 52px;
|
||||
place-items: center;
|
||||
border-radius: 12px;
|
||||
background: #dbeafe;
|
||||
color: #1d4ed8;
|
||||
|
||||
&--persons {
|
||||
background: #dcfce7;
|
||||
color: #15803d;
|
||||
}
|
||||
|
||||
&--eu-projects {
|
||||
background: #e0f2fe;
|
||||
color: #0369a1;
|
||||
}
|
||||
|
||||
&--bund-projects {
|
||||
background: #fef3c7;
|
||||
color: #b45309;
|
||||
}
|
||||
|
||||
&--dfg-projects {
|
||||
background: #f3e8ff;
|
||||
color: #7e22ce;
|
||||
}
|
||||
}
|
||||
|
||||
.statistics-error {
|
||||
margin: -1rem 0 2rem;
|
||||
color: #b91c1c;
|
||||
}
|
||||
|
||||
.top-authors-section {
|
||||
margin-bottom: 2.5rem;
|
||||
}
|
||||
|
||||
.topic-heatmap-section {
|
||||
margin-bottom: 2.5rem;
|
||||
padding: 1.25rem;
|
||||
border: 1px solid #e2e8f0;
|
||||
border-radius: 12px;
|
||||
background: #fff;
|
||||
}
|
||||
|
||||
.topic-heatmap-header {
|
||||
display: flex;
|
||||
align-items: flex-end;
|
||||
justify-content: space-between;
|
||||
gap: 1rem;
|
||||
margin-bottom: 1rem;
|
||||
|
||||
h2,
|
||||
p {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
p {
|
||||
margin-top: 0.35rem;
|
||||
color: #64748b;
|
||||
}
|
||||
|
||||
@media (max-width: 820px) {
|
||||
align-items: flex-start;
|
||||
flex-direction: column;
|
||||
}
|
||||
}
|
||||
|
||||
.topic-treemap-period-controls {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
flex-wrap: wrap;
|
||||
gap: 0.65rem;
|
||||
|
||||
label {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 0.35rem;
|
||||
color: #475569;
|
||||
font-size: 0.9rem;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
input {
|
||||
width: 5.5rem;
|
||||
padding: 0.45rem 0.55rem;
|
||||
border: 1px solid #cbd5e1;
|
||||
border-radius: 6px;
|
||||
color: #0f172a;
|
||||
font: inherit;
|
||||
|
||||
&:focus {
|
||||
border-color: #93c5fd;
|
||||
outline: 3px solid #bfdbfe;
|
||||
outline-offset: 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.topic-treemap-period-toggle {
|
||||
display: inline-flex;
|
||||
overflow: hidden;
|
||||
border: 1px solid #cbd5e1;
|
||||
border-radius: 6px;
|
||||
background: #fff;
|
||||
|
||||
button {
|
||||
padding: 0.5rem 0.7rem;
|
||||
border: 0;
|
||||
border-right: 1px solid #cbd5e1;
|
||||
background: transparent;
|
||||
color: #334155;
|
||||
cursor: pointer;
|
||||
font: inherit;
|
||||
font-weight: 600;
|
||||
|
||||
&:last-child {
|
||||
border-right: 0;
|
||||
}
|
||||
|
||||
&.active {
|
||||
background: #1d4ed8;
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
&:focus-visible {
|
||||
outline: 3px solid #93c5fd;
|
||||
outline-offset: -3px;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.top-authors-header {
|
||||
display: flex;
|
||||
align-items: flex-end;
|
||||
justify-content: space-between;
|
||||
gap: 1rem;
|
||||
margin-bottom: 1rem;
|
||||
|
||||
h2,
|
||||
p {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
p {
|
||||
margin-top: 0.35rem;
|
||||
color: #64748b;
|
||||
}
|
||||
|
||||
@media (max-width: 720px) {
|
||||
align-items: flex-start;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
.top-authors-period-toggle {
|
||||
display: inline-flex;
|
||||
overflow: hidden;
|
||||
border: 1px solid #cbd5e1;
|
||||
border-radius: 6px;
|
||||
background: #fff;
|
||||
|
||||
button {
|
||||
padding: 0.55rem 0.8rem;
|
||||
border: 0;
|
||||
border-right: 1px solid #cbd5e1;
|
||||
background: transparent;
|
||||
color: #334155;
|
||||
cursor: pointer;
|
||||
font: inherit;
|
||||
|
||||
&:last-child {
|
||||
border-right: 0;
|
||||
}
|
||||
|
||||
&.active {
|
||||
background: #1d4ed8;
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
&:focus-visible {
|
||||
outline: 3px solid #93c5fd;
|
||||
outline-offset: -3px;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.top-authors-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
gap: 1rem;
|
||||
|
||||
&.loading {
|
||||
opacity: 0.65;
|
||||
}
|
||||
|
||||
@media (max-width: 900px) {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
}
|
||||
|
||||
.controls {
|
||||
.top-authors-chart {
|
||||
padding: 1.25rem;
|
||||
border: 1px solid #e2e8f0;
|
||||
border-radius: 12px;
|
||||
background: #fff;
|
||||
|
||||
h3 {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
margin: 0 0 1rem;
|
||||
color: #0f172a;
|
||||
}
|
||||
}
|
||||
|
||||
.author-bar-row {
|
||||
display: flex;
|
||||
gap: 1rem;
|
||||
|
||||
select {
|
||||
padding: 0.5rem;
|
||||
border-radius: 4px;
|
||||
border: 1px solid #ccc;
|
||||
}
|
||||
|
||||
.toggle-group {
|
||||
button {
|
||||
padding: 0.5rem 1rem;
|
||||
border: 1px solid #0056b3;
|
||||
background: white;
|
||||
color: #0056b3;
|
||||
cursor: pointer;
|
||||
&:first-child {
|
||||
border-radius: 4px 0 0 4px;
|
||||
}
|
||||
&:last-child {
|
||||
border-radius: 0 4px 4px 0;
|
||||
}
|
||||
&.active {
|
||||
background: #0056b3;
|
||||
color: white;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Table styling
|
||||
.ranking-table {
|
||||
width: 100%;
|
||||
border-collapse: collapse;
|
||||
font-size: 0.9rem;
|
||||
|
||||
th,
|
||||
td {
|
||||
padding: 0.75rem;
|
||||
text-align: left;
|
||||
border-bottom: 1px solid #f0f0f0;
|
||||
align-items: center;
|
||||
gap: 0.65rem;
|
||||
margin-top: 0.7rem;
|
||||
}
|
||||
|
||||
.top-tier {
|
||||
background-color: #f8fbff;
|
||||
font-weight: 600;
|
||||
}
|
||||
.positive {
|
||||
color: #28a745;
|
||||
}
|
||||
.negative {
|
||||
color: #dc3545;
|
||||
}
|
||||
.mover-badge {
|
||||
margin-left: 4px;
|
||||
.author-rank {
|
||||
flex: 0 0 1.4rem;
|
||||
color: #64748b;
|
||||
font-size: 0.8rem;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.trend-col {
|
||||
font-weight: bold;
|
||||
&[data-trend='up'] {
|
||||
color: #28a745;
|
||||
}
|
||||
&[data-trend='down'] {
|
||||
color: #dc3545;
|
||||
.author-bar-content {
|
||||
min-width: 0;
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.author-bar-label {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
gap: 0.75rem;
|
||||
margin-bottom: 0.25rem;
|
||||
font-size: 0.85rem;
|
||||
|
||||
span {
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
}
|
||||
|
||||
.author-link {
|
||||
overflow: hidden;
|
||||
color: #1d4ed8;
|
||||
font-weight: 600;
|
||||
text-decoration: none;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
|
||||
&:hover {
|
||||
text-decoration: underline;
|
||||
}
|
||||
|
||||
&:focus-visible {
|
||||
border-radius: 2px;
|
||||
outline: 2px solid #93c5fd;
|
||||
outline-offset: 2px;
|
||||
}
|
||||
}
|
||||
|
||||
.author-bar-track {
|
||||
overflow: hidden;
|
||||
height: 7px;
|
||||
border-radius: 999px;
|
||||
background: #e2e8f0;
|
||||
}
|
||||
|
||||
.author-bar-fill {
|
||||
display: block;
|
||||
height: 100%;
|
||||
border-radius: inherit;
|
||||
background: linear-gradient(90deg, #2563eb, #60a5fa);
|
||||
transition: width 220ms ease;
|
||||
}
|
||||
|
||||
.empty-chart {
|
||||
margin: 2rem 0;
|
||||
color: #64748b;
|
||||
text-align: center;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,67 +1,280 @@
|
||||
import { Component, inject, OnInit } from '@angular/core';
|
||||
import { UniversityLineChartComponent } from '../university-ranking/uni-line-chart/uni-line-chart.component';
|
||||
import { UniversityRankingTableComponent } from '../university-ranking/uni-ranking-table/uni-ranking-table.component';
|
||||
import { Component, OnInit } from '@angular/core';
|
||||
import { DecimalPipe } from '@angular/common';
|
||||
import { MatIconModule } from '@angular/material/icon';
|
||||
import { Observable, finalize } from 'rxjs';
|
||||
import { RouterLink } from '@angular/router';
|
||||
import { TopicHeatmapComponent } from './topic-heatmap/topic-heatmap.component';
|
||||
import {
|
||||
UniversityTopicData,
|
||||
UniversityRanking,
|
||||
UniversityRankingsService,
|
||||
} from '../../api';
|
||||
|
||||
export type ResearchTopic = string;
|
||||
export type DashboardMetric = 'publications' | 'citations';
|
||||
DashboardStatisticValue,
|
||||
DashboardStatistics,
|
||||
DashboardStatisticsService,
|
||||
TopAuthor,
|
||||
TopAuthorStatistics,
|
||||
TopAuthorsWorksPeriod,
|
||||
TopicHeatmap,
|
||||
} from './dashboard-statistics.service';
|
||||
type DashboardStatisticKey =
|
||||
| 'publications'
|
||||
| 'persons'
|
||||
| 'eu_projects'
|
||||
| 'bmbf_projects'
|
||||
| 'dfg_projects';
|
||||
type TopicTreemapPeriod =
|
||||
| 'last_5_years'
|
||||
| 'last_10_years'
|
||||
| 'all_time'
|
||||
| 'custom';
|
||||
|
||||
@Component({
|
||||
selector: 'dashboard',
|
||||
imports: [UniversityLineChartComponent, UniversityRankingTableComponent],
|
||||
imports: [DecimalPipe, MatIconModule, RouterLink, TopicHeatmapComponent],
|
||||
templateUrl: './dashboard.component.html',
|
||||
styleUrl: './dashboard.component.scss',
|
||||
})
|
||||
export class DashboardComponent implements OnInit {
|
||||
private readonly dataService = inject(UniversityRankingsService);
|
||||
statistics?: Partial<DashboardStatistics>;
|
||||
statisticsLoading = false;
|
||||
statisticsError = false;
|
||||
statisticLoading: Record<DashboardStatisticKey, boolean> = {
|
||||
publications: false,
|
||||
persons: false,
|
||||
eu_projects: false,
|
||||
bmbf_projects: false,
|
||||
dfg_projects: false,
|
||||
};
|
||||
statisticErrors: Record<DashboardStatisticKey, boolean> = {
|
||||
publications: false,
|
||||
persons: false,
|
||||
eu_projects: false,
|
||||
bmbf_projects: false,
|
||||
dfg_projects: false,
|
||||
};
|
||||
private pendingStatisticRequests = 0;
|
||||
topAuthors?: TopAuthorStatistics;
|
||||
topAuthorsLoading = false;
|
||||
topAuthorsError = false;
|
||||
topAuthorsWorksPeriod: TopAuthorsWorksPeriod = 'all_time';
|
||||
topicHeatmap?: TopicHeatmap;
|
||||
topicHeatmapLoading = false;
|
||||
topicHeatmapError = false;
|
||||
topicTreemapPeriod: TopicTreemapPeriod = 'last_5_years';
|
||||
topicTreemapFromYear = new Date().getFullYear() - 4;
|
||||
topicTreemapToYear = new Date().getFullYear();
|
||||
|
||||
topics: ResearchTopic[] = [
|
||||
'Quantum Computing',
|
||||
'Renewable Energy',
|
||||
'Artificial Intelligence and Decision Support Systems',
|
||||
];
|
||||
selectedTopic: ResearchTopic = 'Quantum Computing';
|
||||
metric: DashboardMetric = 'publications';
|
||||
|
||||
rawDataSource: UniversityTopicData[] = [];
|
||||
computedRankings: UniversityRanking[] = [];
|
||||
isLoading = false;
|
||||
constructor(private statisticsService: DashboardStatisticsService) {}
|
||||
|
||||
ngOnInit() {
|
||||
this.loadData();
|
||||
this.loadStatistics();
|
||||
this.loadTopAuthors();
|
||||
this.loadTopicHeatmap();
|
||||
}
|
||||
|
||||
onTopicChange(topic: ResearchTopic) {
|
||||
this.selectedTopic = topic;
|
||||
this.loadData(); // Re-fetch as rankings depend on the topic
|
||||
private loadStatistics(): void {
|
||||
this.statisticsError = false;
|
||||
this.loadStatistic(
|
||||
'publications',
|
||||
this.statisticsService.getPublicationCount(),
|
||||
);
|
||||
this.loadStatistic('persons', this.statisticsService.getPersonCount());
|
||||
this.loadStatistic(
|
||||
'eu_projects',
|
||||
this.statisticsService.getEuProjectCount(),
|
||||
);
|
||||
this.loadStatistic(
|
||||
'bmbf_projects',
|
||||
this.statisticsService.getBmbfProjectCount(),
|
||||
);
|
||||
this.loadStatistic(
|
||||
'dfg_projects',
|
||||
this.statisticsService.getDfgProjectCount(),
|
||||
);
|
||||
}
|
||||
|
||||
setMetric(metric: DashboardMetric) {
|
||||
this.metric = metric;
|
||||
this.loadData(); // Re-fetch as ranking order changes based on metric
|
||||
isStatisticLoading(key: DashboardStatisticKey): boolean {
|
||||
return this.statisticLoading[key];
|
||||
}
|
||||
|
||||
private loadData() {
|
||||
this.isLoading = true;
|
||||
this.dataService
|
||||
.getRankingsApiInseServiceUniversityRankingsGet(
|
||||
this.selectedTopic,
|
||||
this.metric,
|
||||
topAuthorDatasets(): Array<{
|
||||
title: string;
|
||||
icon: string;
|
||||
entries: TopAuthor[];
|
||||
}> {
|
||||
return [
|
||||
{
|
||||
title: 'Publikationen',
|
||||
icon: 'menu_book',
|
||||
entries: this.topAuthors?.works ?? [],
|
||||
},
|
||||
{
|
||||
title: 'Projekte',
|
||||
icon: 'work',
|
||||
entries: this.topAuthors?.projects ?? [],
|
||||
},
|
||||
{
|
||||
title: 'Patente',
|
||||
icon: 'description',
|
||||
entries: this.topAuthors?.patents ?? [],
|
||||
},
|
||||
{ title: 'News', icon: 'article', entries: this.topAuthors?.news ?? [] },
|
||||
];
|
||||
}
|
||||
|
||||
visibleTopAuthorDatasets(): Array<{
|
||||
title: string;
|
||||
icon: string;
|
||||
entries: TopAuthor[];
|
||||
}> {
|
||||
const datasets = this.topAuthorDatasets();
|
||||
return this.topAuthorsLoading
|
||||
? datasets
|
||||
: datasets.filter((dataset) => dataset.entries.length > 0);
|
||||
}
|
||||
|
||||
hasTopAuthorData(): boolean {
|
||||
return this.topAuthorDatasets().some(
|
||||
(dataset) => dataset.entries.length > 0,
|
||||
);
|
||||
}
|
||||
|
||||
hasTopicHeatmapData(): boolean {
|
||||
return (this.topicHeatmap?.fields ?? []).some(
|
||||
(field) =>
|
||||
field.total > 0 || field.values.some((value) => value.count > 0),
|
||||
);
|
||||
}
|
||||
|
||||
setTopAuthorsWorksPeriod(period: TopAuthorsWorksPeriod): void {
|
||||
if (period === this.topAuthorsWorksPeriod) return;
|
||||
this.topAuthorsWorksPeriod = period;
|
||||
this.loadTopAuthors();
|
||||
}
|
||||
|
||||
authorBarWidth(entries: TopAuthor[], count: number): number {
|
||||
const maximum = Math.max(...entries.map((entry) => entry.count), 1);
|
||||
return (count / maximum) * 100;
|
||||
}
|
||||
|
||||
organizationName(): string {
|
||||
return this.statistics?.organization_name ?? 'Ihre Organisation';
|
||||
}
|
||||
|
||||
institutionRouteId(): string {
|
||||
return (
|
||||
this.statistics?.institution_id?.replace('https://openalex.org/', '') ??
|
||||
this.topAuthors?.institution_id?.replace('https://openalex.org/', '') ??
|
||||
''
|
||||
);
|
||||
}
|
||||
|
||||
setTopicTreemapPeriod(period: TopicTreemapPeriod): void {
|
||||
if (period === this.topicTreemapPeriod && period !== 'custom') return;
|
||||
|
||||
const currentYear = new Date().getFullYear();
|
||||
this.topicTreemapPeriod = period;
|
||||
if (period === 'last_5_years') {
|
||||
this.topicTreemapFromYear = currentYear - 4;
|
||||
this.topicTreemapToYear = currentYear;
|
||||
} else if (period === 'last_10_years') {
|
||||
this.topicTreemapFromYear = currentYear - 9;
|
||||
this.topicTreemapToYear = currentYear;
|
||||
} else if (period === 'all_time') {
|
||||
this.topicTreemapFromYear = 1900;
|
||||
this.topicTreemapToYear = currentYear;
|
||||
}
|
||||
this.loadTopicHeatmap();
|
||||
}
|
||||
|
||||
onTopicTreemapYearChange(field: 'from' | 'to', value: string): void {
|
||||
const year = Number(value);
|
||||
if (!Number.isInteger(year)) return;
|
||||
|
||||
if (field === 'from') {
|
||||
this.topicTreemapFromYear = year;
|
||||
} else {
|
||||
this.topicTreemapToYear = year;
|
||||
}
|
||||
this.topicTreemapPeriod = 'custom';
|
||||
this.loadTopicHeatmap();
|
||||
}
|
||||
|
||||
private loadStatistic(
|
||||
key: DashboardStatisticKey,
|
||||
request: Observable<DashboardStatisticValue>,
|
||||
): void {
|
||||
this.statisticLoading[key] = true;
|
||||
this.statisticErrors[key] = false;
|
||||
this.pendingStatisticRequests += 1;
|
||||
this.statisticsLoading = true;
|
||||
|
||||
request
|
||||
.pipe(
|
||||
finalize(() => {
|
||||
this.statisticLoading[key] = false;
|
||||
this.pendingStatisticRequests -= 1;
|
||||
this.statisticsLoading = this.pendingStatisticRequests > 0;
|
||||
}),
|
||||
)
|
||||
.subscribe({
|
||||
next: (response) => {
|
||||
this.rawDataSource = (response.timeseries as any) || [];
|
||||
this.computedRankings = (response.rankings as any) || [];
|
||||
this.isLoading = false;
|
||||
next: (statistic) => {
|
||||
this.applyStatisticValue(key, statistic);
|
||||
},
|
||||
error: () => {
|
||||
this.rawDataSource = [];
|
||||
this.computedRankings = [];
|
||||
this.isLoading = false;
|
||||
this.statisticErrors[key] = true;
|
||||
this.statisticsError = true;
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
private applyStatisticValue(
|
||||
key: DashboardStatisticKey,
|
||||
statistic: DashboardStatisticValue,
|
||||
): void {
|
||||
const nextStatistics = {
|
||||
...(this.statistics ?? {}),
|
||||
institution_id: statistic.institution_id,
|
||||
organization_name: statistic.organization_name,
|
||||
[key]: statistic.value,
|
||||
};
|
||||
nextStatistics.projects =
|
||||
(nextStatistics.eu_projects ?? 0) +
|
||||
(nextStatistics.bmbf_projects ?? 0) +
|
||||
(nextStatistics.dfg_projects ?? 0);
|
||||
this.statistics = nextStatistics;
|
||||
}
|
||||
|
||||
private loadTopAuthors(): void {
|
||||
this.topAuthorsLoading = true;
|
||||
this.topAuthorsError = false;
|
||||
this.statisticsService
|
||||
.getTopAuthors(this.topAuthorsWorksPeriod)
|
||||
.pipe(finalize(() => (this.topAuthorsLoading = false)))
|
||||
.subscribe({
|
||||
next: (statistics) => {
|
||||
this.topAuthors = statistics;
|
||||
},
|
||||
error: () => {
|
||||
this.topAuthorsError = true;
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
private loadTopicHeatmap(): void {
|
||||
if (this.topicTreemapFromYear > this.topicTreemapToYear) {
|
||||
this.topicHeatmapError = true;
|
||||
return;
|
||||
}
|
||||
|
||||
this.topicHeatmapLoading = true;
|
||||
this.topicHeatmapError = false;
|
||||
this.statisticsService
|
||||
.getTopicHeatmap(this.topicTreemapFromYear, this.topicTreemapToYear)
|
||||
.pipe(finalize(() => (this.topicHeatmapLoading = false)))
|
||||
.subscribe({
|
||||
next: (heatmap) => {
|
||||
this.topicHeatmap = heatmap;
|
||||
},
|
||||
error: () => {
|
||||
this.topicHeatmapError = true;
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
@if (heatmap?.fields?.length) {
|
||||
<div echarts [options]="options" class="topic-treemap-chart"></div>
|
||||
} @else {
|
||||
<p class="topic-treemap-empty">
|
||||
{{ loading ? 'Wird geladen ...' : 'Keine Field-Daten vorhanden.' }}
|
||||
</p>
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
.topic-treemap-chart {
|
||||
width: 100%;
|
||||
height: 560px;
|
||||
}
|
||||
|
||||
.topic-treemap-empty {
|
||||
display: grid;
|
||||
min-height: 260px;
|
||||
margin: 0;
|
||||
place-items: center;
|
||||
color: #64748b;
|
||||
}
|
||||
@@ -0,0 +1,212 @@
|
||||
import { Component, Input, OnChanges } from '@angular/core';
|
||||
import { EChartsOption } from 'echarts';
|
||||
import { NgxEchartsDirective } from 'ngx-echarts';
|
||||
|
||||
import { TopicHeatmap } from '../dashboard-statistics.service';
|
||||
|
||||
@Component({
|
||||
selector: 'app-topic-heatmap',
|
||||
imports: [NgxEchartsDirective],
|
||||
templateUrl: './topic-heatmap.component.html',
|
||||
styleUrl: './topic-heatmap.component.scss',
|
||||
})
|
||||
export class TopicHeatmapComponent implements OnChanges {
|
||||
@Input() heatmap?: TopicHeatmap;
|
||||
@Input() loading = false;
|
||||
|
||||
options: EChartsOption = {};
|
||||
private readonly colors = [
|
||||
'#2563eb',
|
||||
'#059669',
|
||||
'#d97706',
|
||||
'#dc2626',
|
||||
'#7c3aed',
|
||||
'#0284c7',
|
||||
'#ea580c',
|
||||
'#4f46e5',
|
||||
'#0f766e',
|
||||
'#be123c',
|
||||
];
|
||||
|
||||
ngOnChanges(): void {
|
||||
this.options = this.buildOptions();
|
||||
}
|
||||
|
||||
private buildOptions(): EChartsOption {
|
||||
const fields = this.heatmap?.fields ?? [];
|
||||
const data = fields.map((field) => ({
|
||||
id: field.id,
|
||||
name: field.name,
|
||||
value: field.total || this.totalCount(field.values),
|
||||
label: {
|
||||
show: true,
|
||||
formatter: (params: any) =>
|
||||
`${params.name}\n${this.formatCount(params.value)}`,
|
||||
color: '#ffffff',
|
||||
fontWeight: 700,
|
||||
lineHeight: 18,
|
||||
overflow: 'truncate' as const,
|
||||
},
|
||||
children: field.values
|
||||
.filter((value) => value.count > 0)
|
||||
.map((value) => ({
|
||||
name: String(value.year),
|
||||
value: value.count,
|
||||
share: value.share,
|
||||
})),
|
||||
}));
|
||||
|
||||
return {
|
||||
tooltip: {
|
||||
formatter: (params: any) => {
|
||||
const count = Number(params.value ?? 0);
|
||||
const share =
|
||||
typeof params.data?.share === 'number'
|
||||
? `<br />Anteil im Jahr: <strong>${(params.data.share * 100).toFixed(1)}%</strong>`
|
||||
: '';
|
||||
return `${params.name}<br /><strong>${count}</strong> Publikationen${share}`;
|
||||
},
|
||||
},
|
||||
series: [
|
||||
{
|
||||
name: 'Fields',
|
||||
type: 'treemap',
|
||||
data,
|
||||
roam: false,
|
||||
nodeClick: 'zoomToNode',
|
||||
sort: 'desc',
|
||||
drillDownIcon: '',
|
||||
breadcrumb: {
|
||||
show: true,
|
||||
bottom: 0,
|
||||
height: 24,
|
||||
left: 8,
|
||||
right: 8,
|
||||
emptyItemWidth: 80,
|
||||
itemStyle: {
|
||||
color: '#f8fafc',
|
||||
borderColor: '#cbd5e1',
|
||||
borderWidth: 1,
|
||||
textStyle: {
|
||||
color: '#334155',
|
||||
fontWeight: 600,
|
||||
},
|
||||
},
|
||||
emphasis: {
|
||||
itemStyle: {
|
||||
color: '#e0f2fe',
|
||||
borderColor: '#93c5fd',
|
||||
textStyle: {
|
||||
color: '#0f172a',
|
||||
fontWeight: 700,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
color: this.colors,
|
||||
colorMappingBy: 'id',
|
||||
label: {
|
||||
show: true,
|
||||
formatter: (params: any) =>
|
||||
`${params.name}\n${this.formatCount(params.value)}`,
|
||||
color: '#ffffff',
|
||||
fontWeight: 600,
|
||||
lineHeight: 18,
|
||||
position: 'inside',
|
||||
align: 'center',
|
||||
verticalAlign: 'middle',
|
||||
overflow: 'truncate',
|
||||
},
|
||||
upperLabel: {
|
||||
show: true,
|
||||
formatter: (params: any) =>
|
||||
`${params.name} · ${this.formatCount(params.value)}`,
|
||||
height: 30,
|
||||
color: '#ffffff',
|
||||
fontWeight: 700,
|
||||
overflow: 'truncate',
|
||||
},
|
||||
levels: [
|
||||
{
|
||||
color: this.colors,
|
||||
label: {
|
||||
show: true,
|
||||
position: 'inside',
|
||||
align: 'center',
|
||||
verticalAlign: 'middle',
|
||||
},
|
||||
upperLabel: { show: false },
|
||||
itemStyle: {
|
||||
borderColor: '#ffffff',
|
||||
borderWidth: 3,
|
||||
gapWidth: 3,
|
||||
},
|
||||
},
|
||||
{
|
||||
color: this.colors,
|
||||
label: {
|
||||
show: true,
|
||||
position: 'inside',
|
||||
align: 'center',
|
||||
verticalAlign: 'middle',
|
||||
},
|
||||
upperLabel: { show: false },
|
||||
itemStyle: {
|
||||
borderColor: '#ffffff',
|
||||
borderWidth: 3,
|
||||
gapWidth: 3,
|
||||
},
|
||||
},
|
||||
{
|
||||
colorSaturation: [0.45, 0.78],
|
||||
label: {
|
||||
show: true,
|
||||
formatter: (params: any) =>
|
||||
`${params.name}\n${this.formatCount(params.value)}`,
|
||||
position: 'inside',
|
||||
align: 'center',
|
||||
verticalAlign: 'middle',
|
||||
color: '#ffffff',
|
||||
fontWeight: 700,
|
||||
lineHeight: 18,
|
||||
overflow: 'truncate',
|
||||
},
|
||||
upperLabel: { show: false },
|
||||
itemStyle: {
|
||||
borderColor: '#ffffff',
|
||||
borderWidth: 2,
|
||||
gapWidth: 2,
|
||||
},
|
||||
},
|
||||
],
|
||||
leafDepth: 1,
|
||||
top: 8,
|
||||
right: 8,
|
||||
bottom: 32,
|
||||
left: 8,
|
||||
animationDurationUpdate: 450,
|
||||
emphasis: {
|
||||
focus: 'self',
|
||||
label: {
|
||||
color: '#ffffff',
|
||||
},
|
||||
},
|
||||
itemStyle: {
|
||||
borderRadius: 4,
|
||||
borderColor: '#ffffff',
|
||||
borderWidth: 3,
|
||||
gapWidth: 3,
|
||||
},
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
private totalCount(values: Array<{ count: number }>): number {
|
||||
return values.reduce((sum, value) => sum + value.count, 0);
|
||||
}
|
||||
|
||||
private formatCount(value: unknown): string {
|
||||
return Number(value ?? 0).toLocaleString('de-DE');
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user