diff --git a/service/src/main/inse/auth/model.py b/service/src/main/inse/auth/model.py
index d78caf5b..b0b5c346 100644
--- a/service/src/main/inse/auth/model.py
+++ b/service/src/main/inse/auth/model.py
@@ -88,6 +88,25 @@ class Organization(Durable, table=True):
accounts: list["Account"] = Relationship(back_populates="organization")
+class OrganizationInstitution(SQLModel, table=True):
+ __tablename__ = "organization_institution"
+ __table_args__ = (
+ UniqueConstraint(
+ "organization_id",
+ "position",
+ name="uq_organization_institution_position",
+ ),
+ )
+
+ organization_id: uuid.UUID = Field(
+ foreign_key="organization.id",
+ primary_key=True,
+ index=True,
+ )
+ openalex_institution_id: str = Field(primary_key=True, index=True)
+ position: int = Field(nullable=False)
+
+
class Account(Durable, table=True):
@model_validator(mode="before")
@classmethod
diff --git a/service/src/main/inse/auth/service.py b/service/src/main/inse/auth/service.py
index 4898ebef..1b271e67 100644
--- a/service/src/main/inse/auth/service.py
+++ b/service/src/main/inse/auth/service.py
@@ -22,6 +22,7 @@ from inse.auth.model import (
IdTokenMetadata,
LoginResponse,
Organization,
+ OrganizationInstitution,
OtkResponse,
RefreshTokenMetadata,
Secret,
@@ -98,9 +99,12 @@ def create_predefined_accounts(session: Session, file_path: str):
with open(file_path, "r") as file:
data: dict[str, Any] = json.loads(file.read())
for organization_data in data.get("organizations", []):
- organization_id = organization_data.get("id")
- if organization_id is not None:
- organization_id = uuid.UUID(organization_id)
+ organization_id_value = organization_data.get("id")
+ organization_id = (
+ uuid.UUID(organization_id_value)
+ if organization_id_value is not None
+ else uuid.uuid4()
+ )
organization_name = organization_data["name"]
openalex_institution_id = organization_data.get(
"openalex_institution_id"
@@ -113,6 +117,14 @@ def create_predefined_accounts(session: Session, file_path: str):
openalex_institution_id=openalex_institution_id,
)
session.add(organization)
+ if openalex_institution_id:
+ session.add(
+ OrganizationInstitution(
+ organization_id=organization.id,
+ openalex_institution_id=openalex_institution_id,
+ position=0,
+ )
+ )
for account_data in data.get("accounts", []):
organization_id = uuid.UUID(account_data["organization_id"])
roles = normalize_roles(
diff --git a/service/src/main/inse/dashboard/bund_topics_service.py b/service/src/main/inse/dashboard/bund_topics_service.py
new file mode 100644
index 00000000..5a241c49
--- /dev/null
+++ b/service/src/main/inse/dashboard/bund_topics_service.py
@@ -0,0 +1,142 @@
+import hashlib
+from collections import defaultdict
+from typing import Any
+
+from inse.institutions.institutions_search_client import InstitutionsSearchClient
+from inse.integrations import elasticsearch
+from inse.model import ESCluster, ESIndex
+from inse.projects import service as projects_service
+
+from .model import BundProjectTopics, DfgProjectKeyword, DfgProjectTopic
+from .common import (
+ dashboard_period as _dashboard_period,
+ normalize_institution_id as _normalize_institution_id,
+ raw_institution_id as _raw_institution_id,
+)
+
+
+async def get_dashboard_bund_topics(
+ institution_id: str,
+ organization_name: str,
+ from_year: int | None = None,
+ to_year: int | None = None,
+) -> BundProjectTopics:
+ normalized_id = _normalize_institution_id(institution_id)
+ period = _dashboard_period(from_year, to_year)
+ page_size = 1000
+ page_number = 0
+ project_ids: set[str] = set()
+
+ while True:
+ projects = await projects_service.search_bund_projects_with_filters(
+ institutions_search_client=InstitutionsSearchClient(),
+ executing_agency=None,
+ raw_oa_institution_id=_raw_institution_id(normalized_id),
+ title=None,
+ keywords=None,
+ funding_arts=None,
+ topic_ids=None,
+ filter_topic_ids=None,
+ funding_start_years=None,
+ funding_end_years=None,
+ active_from_year=period[0],
+ active_to_year=period[1],
+ countries=None,
+ page=page_number,
+ size=page_size,
+ sort_by="id",
+ sort_direction="asc",
+ fuzzy=False,
+ )
+ project_ids.update(
+ project.funding_code
+ for project in projects.elements
+ if project.funding_code
+ )
+ if len(project_ids) >= projects.total or not projects.elements:
+ break
+ page_number += 1
+
+ topics: dict[str, dict[str, Any]] = {}
+ matched_project_ids: set[str] = set()
+ if project_ids:
+ mapping_project_ids = sorted(
+ hashlib.sha256(project_id.encode("utf-8")).hexdigest()
+ for project_id in project_ids
+ )
+ async for hit in elasticsearch.scan(
+ index=str(ESIndex.PROJECTS_BUND_TOPICS),
+ query={"terms": {"project_id": mapping_project_ids}},
+ source=["project_id", "keyword", "topic_matches"],
+ page_size=1000,
+ cluster=ESCluster.INSE,
+ ):
+ source = hit.get("_source", {})
+ project_id = str(source.get("project_id") or "")
+ if not project_id:
+ continue
+ keyword = str(source.get("keyword") or "").strip()
+ matched_project_ids.add(project_id)
+ for match in source.get("topic_matches", []):
+ topic_id = str(match.get("topic_id") or "")
+ if not topic_id:
+ continue
+ topic = topics.setdefault(
+ topic_id,
+ {
+ "id": topic_id,
+ "name": str(match.get("topic_display_name") or topic_id),
+ "subfield": match.get("subfield"),
+ "field": match.get("field"),
+ "domain": match.get("domain"),
+ "project_ids": set(),
+ "keywords": {},
+ },
+ )
+ topic["project_ids"].add(project_id)
+ if keyword:
+ topic["keywords"].setdefault(keyword, set()).add(project_id)
+
+ field_project_ids: dict[str, set[str]] = defaultdict(set)
+ subfield_project_ids: dict[tuple[str, str], set[str]] = defaultdict(set)
+ for topic in topics.values():
+ field_name = str(topic["field"] or "")
+ subfield_name = str(topic["subfield"] or "")
+ field_project_ids[field_name].update(topic["project_ids"])
+ subfield_project_ids[(field_name, subfield_name)].update(topic["project_ids"])
+
+ topic_list = [
+ DfgProjectTopic(
+ id=topic["id"],
+ name=topic["name"],
+ subfield=topic["subfield"],
+ field=topic["field"],
+ domain=topic["domain"],
+ project_count=len(topic["project_ids"]),
+ field_project_count=len(field_project_ids[str(topic["field"] or "")]),
+ subfield_project_count=len(
+ subfield_project_ids[
+ (str(topic["field"] or ""), str(topic["subfield"] or ""))
+ ]
+ ),
+ keywords=sorted(
+ [
+ DfgProjectKeyword(
+ name=keyword,
+ project_count=len(keyword_project_ids),
+ )
+ for keyword, keyword_project_ids in topic["keywords"].items()
+ ],
+ key=lambda entry: (-entry.project_count, entry.name),
+ ),
+ )
+ for topic in topics.values()
+ ]
+ topic_list.sort(key=lambda topic: (-topic.project_count, topic.name, topic.id))
+ return BundProjectTopics(
+ institution_id=normalized_id,
+ organization_name=organization_name,
+ project_count=len(project_ids),
+ matched_project_count=len(matched_project_ids),
+ topics=topic_list,
+ )
diff --git a/service/src/main/inse/dashboard/common.py b/service/src/main/inse/dashboard/common.py
new file mode 100644
index 00000000..e670b2f7
--- /dev/null
+++ b/service/src/main/inse/dashboard/common.py
@@ -0,0 +1,92 @@
+from typing import Any, Literal
+
+from fastapi import HTTPException, status
+
+DashboardPeriod = tuple[int | None, int | None]
+
+
+def dashboard_period(
+ from_year: int | None = None,
+ to_year: int | None = None,
+) -> DashboardPeriod:
+ if from_year is not None and to_year is not None and from_year > to_year:
+ raise HTTPException(
+ status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
+ detail="from_year must be less than or equal to to_year.",
+ )
+ return from_year, to_year
+
+
+def project_overlap_filter(
+ start_field: str,
+ end_field: str,
+ period: DashboardPeriod,
+ *,
+ missing_end_is_ongoing: bool = False,
+) -> dict[str, Any] | None:
+ from_year, to_year = period
+ filters: list[dict[str, Any]] = []
+ if to_year is not None:
+ filters.append({"range": {start_field: {"lte": to_year}}})
+ if from_year is not None:
+ end_filter: dict[str, Any] = {"range": {end_field: {"gte": from_year}}}
+ if missing_end_is_ongoing:
+ end_filter = {
+ "bool": {
+ "should": [
+ end_filter,
+ {"bool": {"must_not": {"exists": {"field": end_field}}}},
+ ],
+ "minimum_should_match": 1,
+ }
+ }
+ filters.append(end_filter)
+ return {"bool": {"filter": filters}} if filters else None
+
+
+def project_boundary_year_filter(
+ start_field: str,
+ end_field: str,
+ period: DashboardPeriod,
+ date_format: Literal["iso", "de", "year"],
+) -> dict[str, Any] | None:
+ from_year, to_year = period
+ filters: list[dict[str, Any]] = []
+ if to_year is not None:
+ if date_format == "year":
+ filters.append({"range": {start_field: {"lte": to_year}}})
+ else:
+ last_day = (
+ f"{to_year}-12-31" if date_format == "iso" else f"31.12.{to_year}"
+ )
+ filters.append({"range": {start_field: {"lte": last_day}}})
+ if from_year is not None:
+ if date_format == "year":
+ filters.append({"range": {end_field: {"gte": from_year}}})
+ else:
+ first_day = (
+ f"{from_year}-01-01" if date_format == "iso" else f"01.01.{from_year}"
+ )
+ filters.append({"range": {end_field: {"gte": first_day}}})
+ return {"bool": {"filter": filters}} if filters else None
+
+
+def normalize_institution_id(value: str) -> str:
+ return (
+ value
+ if value.startswith("https://openalex.org/")
+ else f"https://openalex.org/{value}"
+ )
+
+
+def raw_institution_id(value: str) -> str:
+ return normalize_institution_id(value).removeprefix("https://openalex.org/")
+
+
+def institution_works_query(institution_id: str) -> dict[str, Any]:
+ return {
+ "nested": {
+ "path": "authorships.institutions",
+ "query": {"term": {"authorships.institutions.id": institution_id}},
+ }
+ }
diff --git a/service/src/main/inse/dashboard/dfg_topics_service.py b/service/src/main/inse/dashboard/dfg_topics_service.py
new file mode 100644
index 00000000..2332c809
--- /dev/null
+++ b/service/src/main/inse/dashboard/dfg_topics_service.py
@@ -0,0 +1,103 @@
+from collections import defaultdict
+from typing import Any
+
+from inse.integrations import elasticsearch
+from inse.model import ESCluster, ESIndex
+
+from .model import DfgProjectKeyword, DfgProjectTopic, DfgProjectTopics
+from .common import normalize_institution_id as _normalize_institution_id
+from .project_ids_service import _get_dfg_project_ids_from_projects_service
+
+
+async def get_dashboard_dfg_topics(
+ institution_id: str,
+ organization_name: str,
+ from_year: int | None = None,
+ to_year: int | None = None,
+) -> DfgProjectTopics:
+ normalized_id = _normalize_institution_id(institution_id)
+ project_ids = await _get_dfg_project_ids_from_projects_service(
+ normalized_id,
+ from_year=from_year,
+ to_year=to_year,
+ )
+ topics: dict[str, dict[str, Any]] = {}
+ matched_project_ids: set[str] = set()
+
+ if project_ids:
+ async for hit in elasticsearch.scan(
+ index=str(ESIndex.PROJECTS_DFG_OPENALEX_TOPICS),
+ query={"terms": {"project_id": project_ids}},
+ source=["project_id", "keyword", "topic_matches"],
+ page_size=1000,
+ cluster=ESCluster.INSE,
+ ):
+ source = hit.get("_source", {})
+ project_id = str(source.get("project_id") or "")
+ if not project_id:
+ continue
+ keyword = str(source.get("keyword") or "").strip()
+ matched_project_ids.add(project_id)
+ for match in source.get("topic_matches", []):
+ topic_id = str(match.get("topic_id") or "")
+ if not topic_id:
+ continue
+ topic = topics.setdefault(
+ topic_id,
+ {
+ "id": topic_id,
+ "name": str(match.get("topic_display_name") or topic_id),
+ "subfield": match.get("subfield"),
+ "field": match.get("field"),
+ "domain": match.get("domain"),
+ "project_ids": set(),
+ "keywords": {},
+ },
+ )
+ topic["project_ids"].add(project_id)
+ if keyword:
+ topic["keywords"].setdefault(keyword, set()).add(project_id)
+
+ field_project_ids: dict[str, set[str]] = defaultdict(set)
+ subfield_project_ids: dict[tuple[str, str], set[str]] = defaultdict(set)
+ for topic in topics.values():
+ field_name = str(topic["field"] or "")
+ subfield_name = str(topic["subfield"] or "")
+ field_project_ids[field_name].update(topic["project_ids"])
+ subfield_project_ids[(field_name, subfield_name)].update(topic["project_ids"])
+
+ topic_list = [
+ DfgProjectTopic(
+ id=topic["id"],
+ name=topic["name"],
+ subfield=topic["subfield"],
+ field=topic["field"],
+ domain=topic["domain"],
+ project_count=len(topic["project_ids"]),
+ field_project_count=len(field_project_ids[str(topic["field"] or "")]),
+ subfield_project_count=len(
+ subfield_project_ids[
+ (str(topic["field"] or ""), str(topic["subfield"] or ""))
+ ]
+ ),
+ keywords=sorted(
+ [
+ DfgProjectKeyword(
+ name=keyword,
+ project_count=len(keyword_project_ids),
+ )
+ for keyword, keyword_project_ids in topic["keywords"].items()
+ ],
+ key=lambda entry: (-entry.project_count, entry.name),
+ ),
+ )
+ for topic in topics.values()
+ ]
+ topic_list.sort(key=lambda topic: (-topic.project_count, topic.name, topic.id))
+ return DfgProjectTopics(
+ institution_id=normalized_id,
+ organization_name=organization_name,
+ project_count=len(project_ids),
+ matched_project_count=len(matched_project_ids),
+ topics=topic_list,
+ )
diff --git a/service/src/main/inse/dashboard/eu_topics_service.py b/service/src/main/inse/dashboard/eu_topics_service.py
new file mode 100644
index 00000000..a4cbeaee
--- /dev/null
+++ b/service/src/main/inse/dashboard/eu_topics_service.py
@@ -0,0 +1,109 @@
+from collections import defaultdict
+from typing import Any
+
+from inse.integrations import elasticsearch
+from inse.model import ESCluster, ESIndex
+
+from .model import DfgProjectKeyword, DfgProjectTopic, EuProjectTopics
+from .common import normalize_institution_id as _normalize_institution_id
+from .project_ids_service import _get_eu_project_ids_from_projects_service
+
+
+async def get_dashboard_eu_topics(
+ institution_id: str,
+ organization_name: str,
+ from_year: int | None = None,
+ to_year: int | None = None,
+) -> EuProjectTopics:
+ normalized_id = _normalize_institution_id(institution_id)
+ project_ids = await _get_eu_project_ids_from_projects_service(
+ normalized_id,
+ from_year=from_year,
+ to_year=to_year,
+ )
+ topics: dict[str, dict[str, Any]] = {}
+ matched_project_ids: set[str] = set()
+
+ if project_ids:
+ mapping_indices = (
+ ESIndex.PROJECTS_CORDIS_EU_FP7_TOPICS_MAPPING,
+ ESIndex.PROJECTS_CORDIS_EU_H2020_TOPICS,
+ ESIndex.PROJECTS_CORDIS_EU_HEUROPE_TOPICS,
+ )
+ for mapping_index in mapping_indices:
+ async for hit in elasticsearch.scan(
+ index=str(mapping_index),
+ query={"terms": {"project_id": project_ids}},
+ source=["project_id", "keyword", "topic_matches"],
+ page_size=1000,
+ cluster=ESCluster.INSE,
+ ):
+ source = hit.get("_source", {})
+ project_id = str(source.get("project_id") or "")
+ if not project_id:
+ continue
+ keyword = str(source.get("keyword") or "").strip()
+ matched_project_ids.add(project_id)
+ for match in source.get("topic_matches", []):
+ topic_id = str(match.get("topic_id") or "")
+ if not topic_id:
+ continue
+ topic = topics.setdefault(
+ topic_id,
+ {
+ "id": topic_id,
+ "name": str(match.get("topic_display_name") or topic_id),
+ "subfield": match.get("subfield"),
+ "field": match.get("field"),
+ "domain": match.get("domain"),
+ "project_ids": set(),
+ "keywords": {},
+ },
+ )
+ topic["project_ids"].add(project_id)
+ if keyword:
+ topic["keywords"].setdefault(keyword, set()).add(project_id)
+
+ field_project_ids: dict[str, set[str]] = defaultdict(set)
+ subfield_project_ids: dict[tuple[str, str], set[str]] = defaultdict(set)
+ for topic in topics.values():
+ field_name = str(topic["field"] or "")
+ subfield_name = str(topic["subfield"] or "")
+ field_project_ids[field_name].update(topic["project_ids"])
+ subfield_project_ids[(field_name, subfield_name)].update(topic["project_ids"])
+
+ topic_list = [
+ DfgProjectTopic(
+ id=topic["id"],
+ name=topic["name"],
+ subfield=topic["subfield"],
+ field=topic["field"],
+ domain=topic["domain"],
+ project_count=len(topic["project_ids"]),
+ field_project_count=len(field_project_ids[str(topic["field"] or "")]),
+ subfield_project_count=len(
+ subfield_project_ids[
+ (str(topic["field"] or ""), str(topic["subfield"] or ""))
+ ]
+ ),
+ keywords=sorted(
+ [
+ DfgProjectKeyword(
+ name=keyword,
+ project_count=len(keyword_project_ids),
+ )
+ for keyword, keyword_project_ids in topic["keywords"].items()
+ ],
+ key=lambda entry: (-entry.project_count, entry.name),
+ ),
+ )
+ for topic in topics.values()
+ ]
+ topic_list.sort(key=lambda topic: (-topic.project_count, topic.name, topic.id))
+ return EuProjectTopics(
+ institution_id=normalized_id,
+ organization_name=organization_name,
+ project_count=len(project_ids),
+ matched_project_count=len(matched_project_ids),
+ topics=topic_list,
+ )
diff --git a/service/src/main/inse/dashboard/model.py b/service/src/main/inse/dashboard/model.py
index eae2251a..bbc047db 100644
--- a/service/src/main/inse/dashboard/model.py
+++ b/service/src/main/inse/dashboard/model.py
@@ -54,6 +54,8 @@ class DfgProjectTopic(BaseModel):
field: str | None = None
domain: str | None = None
project_count: int
+ field_project_count: int
+ subfield_project_count: int
keywords: list[DfgProjectKeyword]
@@ -65,6 +67,22 @@ class DfgProjectTopics(BaseModel):
topics: list[DfgProjectTopic]
+class EuProjectTopics(BaseModel):
+ institution_id: str
+ organization_name: str
+ project_count: int
+ matched_project_count: int
+ topics: list[DfgProjectTopic]
+
+
+class BundProjectTopics(BaseModel):
+ institution_id: str
+ organization_name: str
+ project_count: int
+ matched_project_count: int
+ topics: list[DfgProjectTopic]
+
+
class TopAuthor(BaseModel):
id: str | None = None
name: str
@@ -80,6 +98,11 @@ class TopAuthorStatistics(BaseModel):
news: list[TopAuthor]
+class TopAuthorAnalysis(BaseModel):
+ institution_id: str
+ authors: list[TopAuthor]
+
+
class TopicHeatmapValue(BaseModel):
year: int
count: int
diff --git a/service/src/main/inse/dashboard/project_ids_service.py b/service/src/main/inse/dashboard/project_ids_service.py
new file mode 100644
index 00000000..e5bbb37d
--- /dev/null
+++ b/service/src/main/inse/dashboard/project_ids_service.py
@@ -0,0 +1,102 @@
+from inse.institutions.institutions_search_client import InstitutionsSearchClient
+from inse.projects import service as projects_service
+from inse.projects.model import EuCordisProjectType
+
+from .common import (
+ dashboard_period as _dashboard_period,
+ raw_institution_id as _raw_institution_id,
+)
+
+
+async def _get_dfg_project_ids_from_projects_service(
+ institution_id: str,
+ from_year: int | None = None,
+ to_year: int | None = None,
+) -> list[str]:
+ """Returns every matching DFG project ID through the canonical project service."""
+ period = _dashboard_period(from_year, to_year)
+ page_size = 1000
+ page_number = 0
+ project_ids: set[str] = set()
+
+ while True:
+ projects = await projects_service.get_dfg_projects(
+ institutions_search_client=InstitutionsSearchClient(),
+ raw_oa_institution_id=_raw_institution_id(institution_id),
+ author_id=None,
+ author_filter_ids=None,
+ institution_ids=None,
+ keywords=None,
+ topic_ids=None,
+ filter_topic_ids=None,
+ title=None,
+ funding_start_years=(
+ [str(year) for year in range(1900, period[1] + 1)]
+ if period[1] is not None
+ else None
+ ),
+ funding_end_years=(
+ [str(year) for year in range(period[0], 2101)]
+ if period[0] is not None
+ else None
+ ),
+ page=page_number,
+ size=page_size,
+ sort_by="id",
+ sort_direction="asc",
+ fuzzy=False,
+ skip_enrichment=True,
+ )
+ project_ids.update(project.id for project in projects.elements if project.id)
+ if len(project_ids) >= projects.total or not projects.elements:
+ break
+ page_number += 1
+
+ return sorted(project_ids)
+
+
+async def _get_eu_project_ids_from_projects_service(
+ institution_id: str,
+ from_year: int | None = None,
+ to_year: int | None = None,
+) -> list[str]:
+ """Loads all organization EU project IDs from the canonical project service."""
+ period = _dashboard_period(from_year, to_year)
+ page_size = 1000
+ page_number = 0
+ project_ids: set[str] = set()
+
+ while True:
+ projects = await projects_service.search_eu_cordis_projects(
+ institutions_search_client=InstitutionsSearchClient(),
+ raw_oa_institution_id=_raw_institution_id(institution_id),
+ author_id=None,
+ author_ids=None,
+ organization_ids=None,
+ organization_names=None,
+ project_types=list(EuCordisProjectType),
+ keywords=None,
+ topic_ids=None,
+ filter_topic_ids=None,
+ title=None,
+ funding_start_years=None,
+ funding_end_years=None,
+ active_from_year=period[0],
+ active_to_year=period[1],
+ countries=None,
+ framework_programmes=None,
+ funding_schemes=None,
+ statuses=None,
+ page=page_number,
+ size=page_size,
+ sort_by="id",
+ sort_direction="asc",
+ fuzzy=False,
+ skip_enrichment=True,
+ )
+ project_ids.update(project.id for project in projects.elements if project.id)
+ if len(project_ids) >= projects.total or not projects.elements:
+ break
+ page_number += 1
+
+ return sorted(project_ids)
diff --git a/service/src/main/inse/dashboard/project_statistics_service.py b/service/src/main/inse/dashboard/project_statistics_service.py
new file mode 100644
index 00000000..10f68bde
--- /dev/null
+++ b/service/src/main/inse/dashboard/project_statistics_service.py
@@ -0,0 +1,122 @@
+from inse.institutions.institutions_search_client import InstitutionsSearchClient
+from inse.projects import service as projects_service
+from inse.projects.model import EuCordisProjectType
+
+from .common import (
+ dashboard_period as _dashboard_period,
+ normalize_institution_id as _normalize_institution_id,
+ raw_institution_id as _raw_institution_id,
+)
+from .model import DashboardStatisticValue
+
+
+async def get_dashboard_eu_projects(
+ institution_id: str,
+ organization_name: str,
+ from_year: int | None = None,
+ to_year: int | None = None,
+) -> DashboardStatisticValue:
+ normalized_id = _normalize_institution_id(institution_id)
+ period = _dashboard_period(from_year, to_year)
+ projects = await projects_service.search_eu_cordis_projects(
+ institutions_search_client=InstitutionsSearchClient(),
+ raw_oa_institution_id=_raw_institution_id(normalized_id),
+ author_id=None,
+ author_ids=None,
+ organization_ids=None,
+ organization_names=None,
+ project_types=list(EuCordisProjectType),
+ keywords=None,
+ topic_ids=None,
+ filter_topic_ids=None,
+ title=None,
+ funding_start_years=None,
+ funding_end_years=None,
+ active_from_year=period[0],
+ active_to_year=period[1],
+ countries=None,
+ framework_programmes=None,
+ funding_schemes=None,
+ statuses=None,
+ page=0,
+ size=1,
+ sort_by="id",
+ sort_direction="asc",
+ fuzzy=False,
+ )
+ return DashboardStatisticValue(
+ institution_id=normalized_id,
+ organization_name=organization_name,
+ value=projects.total,
+ )
+
+
+async def get_dashboard_bmbf_projects(
+ institution_id: str,
+ organization_name: str,
+ from_year: int | None = None,
+ to_year: int | None = None,
+) -> DashboardStatisticValue:
+ normalized_id = _normalize_institution_id(institution_id)
+ period = _dashboard_period(from_year, to_year)
+ projects = await projects_service.search_bund_projects_with_filters(
+ institutions_search_client=InstitutionsSearchClient(),
+ executing_agency=None,
+ raw_oa_institution_id=_raw_institution_id(normalized_id),
+ title=None,
+ keywords=None,
+ funding_arts=None,
+ topic_ids=None,
+ filter_topic_ids=None,
+ funding_start_years=None,
+ funding_end_years=None,
+ active_from_year=period[0],
+ active_to_year=period[1],
+ countries=None,
+ page=0,
+ size=1,
+ sort_by="id",
+ sort_direction="asc",
+ fuzzy=False,
+ )
+ return DashboardStatisticValue(
+ institution_id=normalized_id,
+ organization_name=organization_name,
+ value=projects.total,
+ )
+
+
+async def get_dashboard_dfg_projects(
+ institution_id: str,
+ organization_name: str,
+ from_year: int | None = None,
+ to_year: int | None = None,
+) -> DashboardStatisticValue:
+ normalized_id = _normalize_institution_id(institution_id)
+ period = _dashboard_period(from_year, to_year)
+ projects = await projects_service.get_dfg_projects(
+ institutions_search_client=InstitutionsSearchClient(),
+ raw_oa_institution_id=_raw_institution_id(normalized_id),
+ author_id=None,
+ author_filter_ids=None,
+ institution_ids=None,
+ keywords=None,
+ topic_ids=None,
+ filter_topic_ids=None,
+ title=None,
+ funding_start_years=None,
+ funding_end_years=None,
+ active_from_year=period[0],
+ active_to_year=period[1],
+ page=0,
+ size=1,
+ sort_by="id",
+ sort_direction="asc",
+ fuzzy=False,
+ skip_enrichment=True,
+ )
+ return DashboardStatisticValue(
+ institution_id=normalized_id,
+ organization_name=organization_name,
+ value=projects.total,
+ )
diff --git a/service/src/main/inse/dashboard/project_status_service.py b/service/src/main/inse/dashboard/project_status_service.py
new file mode 100644
index 00000000..4c32b94b
--- /dev/null
+++ b/service/src/main/inse/dashboard/project_status_service.py
@@ -0,0 +1,513 @@
+from datetime import datetime
+from typing import Any
+
+from inse.institutions.institutions_search_client import InstitutionsSearchClient
+
+from inse.integrations import elasticsearch
+from inse.model import ESCluster, ESIndex
+
+from .common import (
+ DashboardPeriod,
+ dashboard_period as _dashboard_period,
+ normalize_institution_id as _normalize_institution_id,
+ project_boundary_year_filter as _project_boundary_year_filter,
+ project_overlap_filter as _project_overlap_filter,
+ raw_institution_id as _raw_institution_id,
+)
+from .institute_helper import get_openalex_institution
+from .model import (
+ BmbfProjectStatusStatistics,
+ DfgProjectStatusStatistics,
+ EuProjectStatusStatistics,
+)
+from .project_statistics_service import (
+ get_dashboard_bmbf_projects,
+ get_dashboard_dfg_projects,
+ get_dashboard_eu_projects,
+)
+
+
+def _status_count(aggregations: dict[str, Any], status_name: str) -> int:
+ return int(aggregations.get(status_name, {}).get("projects", {}).get("value", 0))
+
+
+def reconcile_status_counts(
+ total: int, ongoing: int, upcoming: int, completed: int
+) -> tuple[int, int, int]:
+ """Make status buckets add up to the authoritative project-service total."""
+ counts = [max(0, ongoing), max(0, upcoming), max(0, completed)]
+ difference = total - sum(counts)
+ if difference >= 0:
+ counts[0] += difference
+ return counts[0], counts[1], counts[2]
+
+ excess = -difference
+ for index in (0, 1, 2):
+ reduction = min(counts[index], excess)
+ counts[index] -= reduction
+ excess -= reduction
+ if excess == 0:
+ break
+ return counts[0], counts[1], counts[2]
+
+
+def _status_filter_aggregations(
+ start_field: str, end_field: str, today: str
+) -> dict[str, Any]:
+ return {
+ "ongoing": {
+ "filter": {
+ "bool": {
+ "filter": [
+ {"range": {start_field: {"lte": today}}},
+ {"range": {end_field: {"gte": today}}},
+ ]
+ }
+ }
+ },
+ "upcoming": {"filter": {"range": {start_field: {"gt": today}}}},
+ "completed": {"filter": {"range": {end_field: {"lt": today}}}},
+ }
+
+
+async def get_dashboard_eu_project_statuses(
+ institution_id: str,
+ organization_name: str,
+ from_year: int | None = None,
+ to_year: int | None = None,
+) -> EuProjectStatusStatistics:
+ normalized_id = _normalize_institution_id(institution_id)
+ aliases = await _institution_aliases(normalized_id, organization_name)
+ project_ids = await _eu_project_ids_for_aliases(aliases)
+ total = (
+ await get_dashboard_eu_projects(
+ normalized_id, organization_name, from_year=from_year, to_year=to_year
+ )
+ ).value
+ if not project_ids:
+ return EuProjectStatusStatistics(
+ institution_id=normalized_id,
+ organization_name=organization_name,
+ ongoing=total,
+ upcoming=0,
+ completed=0,
+ )
+
+ today = datetime.now().date().isoformat()
+ period = _dashboard_period(from_year, to_year)
+ filters: list[dict[str, Any]] = [{"terms": {"id": sorted(project_ids)}}]
+ if period_filter := _project_boundary_year_filter(
+ "startDate", "endDate", period, "iso"
+ ):
+ filters.append(period_filter)
+ response = await elasticsearch.search(
+ index=ESIndex.CORDIS_EU_PROJECTS_WILDCARD,
+ body={
+ "size": 0,
+ "query": filters[0] if len(filters) == 1 else {"bool": {"filter": filters}},
+ "aggs": {
+ "ongoing": {
+ "filter": {
+ "bool": {
+ "filter": [
+ {"range": {"startDate": {"lte": today}}},
+ {"range": {"endDate": {"gte": today}}},
+ ]
+ }
+ },
+ "aggs": {"projects": {"cardinality": {"field": "id"}}},
+ },
+ "upcoming": {
+ "filter": {"range": {"startDate": {"gt": today}}},
+ "aggs": {"projects": {"cardinality": {"field": "id"}}},
+ },
+ "completed": {
+ "filter": {"range": {"endDate": {"lt": today}}},
+ "aggs": {"projects": {"cardinality": {"field": "id"}}},
+ },
+ },
+ },
+ cluster=ESCluster.INSE,
+ )
+ aggregations = response.get("aggregations", {})
+ ongoing, upcoming, completed = reconcile_status_counts(
+ total,
+ _status_count(aggregations, "ongoing"),
+ _status_count(aggregations, "upcoming"),
+ _status_count(aggregations, "completed"),
+ )
+ return EuProjectStatusStatistics(
+ institution_id=normalized_id,
+ organization_name=organization_name,
+ ongoing=ongoing,
+ upcoming=upcoming,
+ completed=completed,
+ )
+
+
+async def get_dashboard_bmbf_project_statuses(
+ institution_id: str,
+ organization_name: str,
+ from_year: int | None = None,
+ to_year: int | None = None,
+) -> BmbfProjectStatusStatistics:
+ normalized_id = _normalize_institution_id(institution_id)
+ aliases = await _institution_aliases(normalized_id, organization_name)
+ period = _dashboard_period(from_year, to_year)
+ filters = [_alias_match_query("Zuwendungsempfänger", aliases)]
+ if period_filter := _project_boundary_year_filter(
+ "funding_start", "funding_end", period, "de"
+ ):
+ filters.append(period_filter)
+ response = await elasticsearch.search(
+ index=ESIndex.PROJECTS_BUND_V1,
+ body={
+ "size": 0,
+ "query": filters[0] if len(filters) == 1 else {"bool": {"filter": filters}},
+ "aggs": _status_filter_aggregations(
+ "funding_start", "funding_end", datetime.now().strftime("%d.%m.%Y")
+ ),
+ },
+ cluster=ESCluster.INSE,
+ )
+ aggregations = response.get("aggregations", {})
+ total = (
+ await get_dashboard_bmbf_projects(
+ normalized_id, organization_name, from_year=from_year, to_year=to_year
+ )
+ ).value
+ ongoing, upcoming, completed = reconcile_status_counts(
+ total,
+ int(aggregations.get("ongoing", {}).get("doc_count", 0)),
+ int(aggregations.get("upcoming", {}).get("doc_count", 0)),
+ int(aggregations.get("completed", {}).get("doc_count", 0)),
+ )
+ return BmbfProjectStatusStatistics(
+ institution_id=normalized_id,
+ organization_name=organization_name,
+ ongoing=ongoing,
+ upcoming=upcoming,
+ completed=completed,
+ )
+
+
+async def get_dashboard_dfg_project_statuses(
+ institution_id: str,
+ organization_name: str,
+ from_year: int | None = None,
+ to_year: int | None = None,
+) -> DfgProjectStatusStatistics:
+ normalized_id = _normalize_institution_id(institution_id)
+ period = _dashboard_period(from_year, to_year)
+ project_ids = await _get_dfg_project_ids_for_institution(normalized_id)
+ total = (
+ await get_dashboard_dfg_projects(
+ normalized_id, organization_name, from_year=from_year, to_year=to_year
+ )
+ ).value
+ if not project_ids:
+ return DfgProjectStatusStatistics(
+ institution_id=normalized_id,
+ organization_name=organization_name,
+ ongoing=total,
+ upcoming=0,
+ completed=0,
+ )
+
+ filters: list[dict[str, Any]] = [
+ {
+ "terms": {
+ "projects.project_id": [int(project_id) for project_id in project_ids]
+ }
+ }
+ ]
+ if period_filter := _project_boundary_year_filter(
+ "projects.funding_start", "projects.funding_end", period, "year"
+ ):
+ filters.append(period_filter)
+ response = await elasticsearch.search(
+ index=ESIndex.DFG_INSTITUTES_V2,
+ body={
+ "size": 0,
+ "aggs": {
+ "projects_nested": {
+ "nested": {"path": "projects"},
+ "aggs": {
+ "selected_projects": {
+ "filter": filters[0]
+ if len(filters) == 1
+ else {"bool": {"filter": filters}},
+ "aggs": {
+ "ongoing": {
+ "filter": {
+ "match_phrase": {
+ "projects.status_de": "laufend"
+ }
+ },
+ "aggs": {
+ "projects": {
+ "cardinality": {
+ "field": "projects.project_id"
+ }
+ }
+ },
+ },
+ "completed": {
+ "filter": {
+ "match_phrase": {
+ "projects.status_de": "abgeschlossen"
+ }
+ },
+ "aggs": {
+ "projects": {
+ "cardinality": {
+ "field": "projects.project_id"
+ }
+ }
+ },
+ },
+ },
+ }
+ },
+ }
+ },
+ },
+ cluster=ESCluster.INSE,
+ )
+ aggregations = (
+ response.get("aggregations", {})
+ .get("projects_nested", {})
+ .get("selected_projects", {})
+ )
+ ongoing, upcoming, completed = reconcile_status_counts(
+ total,
+ _status_count(aggregations, "ongoing"),
+ 0,
+ _status_count(aggregations, "completed"),
+ )
+ return DfgProjectStatusStatistics(
+ institution_id=normalized_id,
+ organization_name=organization_name,
+ ongoing=ongoing,
+ upcoming=upcoming,
+ completed=completed,
+ )
+
+
+async def _get_dfg_project_ids_for_institution(
+ institution_id: str,
+ from_year: int | None = None,
+ to_year: int | None = None,
+) -> list[str]:
+ period = _dashboard_period(from_year, to_year)
+ institution = await get_openalex_institution(institution_id)
+ institution_names = _openalex_institution_names(institution)
+
+ institutes_response = await elasticsearch.search(
+ index=ESIndex.DFG_INSTITUTES_V2,
+ body={
+ "size": 0,
+ "query": _dfg_institute_name_query(institution_names),
+ "aggs": {
+ "institute_ids": {"terms": {"field": "institute_id", "size": 1000}}
+ },
+ },
+ cluster=ESCluster.INSE,
+ )
+ institute_ids = [
+ bucket["key"]
+ for bucket in (
+ institutes_response.get("aggregations", {})
+ .get("institute_ids", {})
+ .get("buckets", [])
+ )
+ if bucket.get("key") is not None
+ ]
+ if not institute_ids:
+ return []
+
+ projects_response = await elasticsearch.search(
+ index=ESIndex.DFG_INSTITUTES_V2,
+ body={
+ "size": 0,
+ "query": {"terms": {"institute_id": institute_ids}},
+ "aggs": {
+ "projects_nested": {
+ "nested": {"path": "projects"},
+ "aggs": {
+ "project_ids": {
+ "filter": {
+ "terms": {"projects.institute_ref_id": institute_ids}
+ },
+ "aggs": {
+ "values": {
+ "terms": {
+ "field": "projects.project_id",
+ "size": 10000,
+ }
+ }
+ },
+ }
+ },
+ }
+ },
+ },
+ cluster=ESCluster.INSE,
+ )
+ project_ids = [
+ str(bucket["key"])
+ for bucket in (
+ projects_response.get("aggregations", {})
+ .get("projects_nested", {})
+ .get("project_ids", {})
+ .get("values", {})
+ .get("buckets", [])
+ )
+ if bucket.get("key") is not None
+ ]
+ return await _filter_dfg_project_ids_by_period(project_ids, period)
+
+
+async def _eu_project_ids_for_aliases(aliases: list[str]) -> set[str]:
+ project_ids: set[str] = set()
+ async for hit in elasticsearch.scan(
+ index=str(ESIndex.CORDIS_EU_ORGANIZATIONS_WILDCARD),
+ query=_eu_organization_query(aliases),
+ source=["projectID"],
+ page_size=1000,
+ cluster=ESCluster.INSE,
+ ):
+ project_id = hit.get("_source", {}).get("projectID")
+ if project_id is not None:
+ project_ids.add(str(project_id))
+ return project_ids
+
+
+async def _filter_dfg_project_ids_by_period(
+ project_ids: list[str],
+ period: DashboardPeriod,
+) -> list[str]:
+ period_filter = _project_overlap_filter(
+ "funding_start",
+ "funding_end",
+ period,
+ missing_end_is_ongoing=True,
+ )
+ if not project_ids or not period_filter:
+ return project_ids
+
+ numeric_project_ids = [
+ int(project_id) for project_id in project_ids if str(project_id).isdigit()
+ ]
+ if not numeric_project_ids:
+ return []
+
+ response = await elasticsearch.search(
+ index=ESIndex.DFG_PROJECTS,
+ body={
+ "size": 0,
+ "query": {
+ "bool": {
+ "filter": [
+ {"terms": {"id": numeric_project_ids}},
+ period_filter,
+ ]
+ }
+ },
+ "aggs": {
+ "project_ids": {
+ "terms": {
+ "field": "id",
+ "size": len(numeric_project_ids),
+ }
+ }
+ },
+ },
+ cluster=ESCluster.INSE,
+ )
+ return [
+ str(bucket["key"])
+ for bucket in (
+ response.get("aggregations", {}).get("project_ids", {}).get("buckets", [])
+ )
+ if bucket.get("key") is not None
+ ]
+
+
+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 _openalex_institution_names(institution: Any) -> list[str]:
+ return sorted(
+ {
+ name.strip()
+ for name in [
+ institution.display_name,
+ *(institution.display_name_alternatives or []),
+ *(institution.display_name_acronyms or []),
+ ]
+ if name and name.strip()
+ }
+ )
+
+
+def _dfg_institute_name_query(institution_names: list[str]) -> dict[str, Any]:
+ return {
+ "bool": {
+ "should": [
+ {
+ "terms": {
+ "institute_name_de.keyword": institution_names,
+ }
+ },
+ {
+ "terms": {
+ "institute_name_en.keyword": institution_names,
+ }
+ },
+ ],
+ "minimum_should_match": 1,
+ }
+ }
diff --git a/service/src/main/inse/dashboard/router.py b/service/src/main/inse/dashboard/router.py
index bd5ad49b..a0d0de82 100644
--- a/service/src/main/inse/dashboard/router.py
+++ b/service/src/main/inse/dashboard/router.py
@@ -10,32 +10,48 @@ from inse.tags import Tags
from .model import (
BmbfProjectStatusStatistics,
+ BundProjectTopics,
DashboardStatistics,
DashboardStatisticValue,
DfgProjectStatusStatistics,
DfgProjectTopics,
+ EuProjectTopics,
EuProjectStatusStatistics,
TopAuthorStatistics,
+ TopAuthorAnalysis,
TopicHeatmap,
TopicWordCloud,
)
from .service import (
- get_dashboard_bmbf_project_statuses,
- get_dashboard_bmbf_projects,
- get_dashboard_dfg_project_statuses,
- get_dashboard_dfg_projects,
- get_dashboard_dfg_topics,
- get_dashboard_eu_project_statuses,
- get_dashboard_eu_projects,
get_dashboard_organization,
get_dashboard_patents,
get_dashboard_persons,
get_dashboard_publications,
get_dashboard_statistics,
- get_top_authors,
get_topic_heatmap,
get_topic_word_cloud,
)
+from .project_statistics_service import (
+ get_dashboard_bmbf_projects,
+ get_dashboard_dfg_projects,
+ get_dashboard_eu_projects,
+)
+from .bund_topics_service import get_dashboard_bund_topics
+from .dfg_topics_service import get_dashboard_dfg_topics
+from .eu_topics_service import get_dashboard_eu_topics
+from .project_status_service import (
+ get_dashboard_bmbf_project_statuses,
+ get_dashboard_dfg_project_statuses,
+ get_dashboard_eu_project_statuses,
+)
+from .top_authors_service import (
+ get_top_authors,
+ get_top_eu_project_authors,
+ get_top_news_authors,
+ get_top_patent_authors,
+ get_top_project_authors,
+ get_top_work_authors,
+)
router = APIRouter(prefix="/api/dashboard", tags=[Tags.DASHBOARD])
@@ -256,6 +272,46 @@ async def dashboard_dfg_project_topics(
)
+@router.get(
+ "/projects/eu/topics",
+ operation_id="getDashboardEuProjectTopics",
+ response_model=EuProjectTopics,
+)
+async def dashboard_eu_project_topics(
+ from_year: int | None = Query(default=None, ge=1900, le=2100),
+ to_year: int | None = Query(default=None, ge=1900, le=2100),
+ session: Session = Depends(get_session),
+ access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
+) -> EuProjectTopics:
+ organization = get_dashboard_organization(session, access_token)
+ return await get_dashboard_eu_topics(
+ organization.openalex_institution_id,
+ organization.name,
+ from_year=from_year,
+ to_year=to_year,
+ )
+
+
+@router.get(
+ "/projects/bund/topics",
+ operation_id="getDashboardBundProjectTopics",
+ response_model=BundProjectTopics,
+)
+async def dashboard_bund_project_topics(
+ from_year: int | None = Query(default=None, ge=1900, le=2100),
+ to_year: int | None = Query(default=None, ge=1900, le=2100),
+ session: Session = Depends(get_session),
+ access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
+) -> BundProjectTopics:
+ organization = get_dashboard_organization(session, access_token)
+ return await get_dashboard_bund_topics(
+ organization.openalex_institution_id,
+ organization.name,
+ from_year=from_year,
+ to_year=to_year,
+ )
+
+
@router.get(
"/top-authors",
operation_id="getDashboardTopAuthors",
@@ -281,6 +337,94 @@ async def dashboard_top_authors(
)
+@router.get(
+ "/top-authors/works",
+ operation_id="getDashboardTopWorkAuthors",
+ response_model=TopAuthorAnalysis,
+)
+async def dashboard_top_work_authors(
+ works_period: Literal["all_time", "last_5_years"] = Query(
+ default="all_time", pattern="^(all_time|last_5_years)$"
+ ),
+ from_year: int | None = Query(default=None, ge=1900, le=2100),
+ to_year: int | None = Query(default=None, ge=1900, le=2100),
+ session: Session = Depends(get_session),
+ access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
+) -> TopAuthorAnalysis:
+ organization = get_dashboard_organization(session, access_token)
+ return await get_top_work_authors(
+ organization.openalex_institution_id, works_period, from_year, to_year
+ )
+
+
+@router.get(
+ "/top-authors/projects",
+ operation_id="getDashboardTopProjectAuthors",
+ response_model=TopAuthorAnalysis,
+)
+async def dashboard_top_project_authors(
+ from_year: int | None = Query(default=None, ge=1900, le=2100),
+ to_year: int | None = Query(default=None, ge=1900, le=2100),
+ session: Session = Depends(get_session),
+ access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
+) -> TopAuthorAnalysis:
+ organization = get_dashboard_organization(session, access_token)
+ return await get_top_project_authors(
+ organization.openalex_institution_id, organization.name, from_year, to_year
+ )
+
+
+@router.get(
+ "/top-authors/eu-projects",
+ operation_id="getDashboardTopEuProjectAuthors",
+ response_model=TopAuthorAnalysis,
+)
+async def dashboard_top_eu_project_authors(
+ from_year: int | None = Query(default=None, ge=1900, le=2100),
+ to_year: int | None = Query(default=None, ge=1900, le=2100),
+ session: Session = Depends(get_session),
+ access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
+) -> TopAuthorAnalysis:
+ organization = get_dashboard_organization(session, access_token)
+ return await get_top_eu_project_authors(
+ organization.openalex_institution_id, from_year, to_year
+ )
+
+
+@router.get(
+ "/top-authors/patents",
+ operation_id="getDashboardTopPatentAuthors",
+ response_model=TopAuthorAnalysis,
+)
+async def dashboard_top_patent_authors(
+ from_year: int | None = Query(default=None, ge=1900, le=2100),
+ to_year: int | None = Query(default=None, ge=1900, le=2100),
+ session: Session = Depends(get_session),
+ access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
+) -> TopAuthorAnalysis:
+ organization = get_dashboard_organization(session, access_token)
+ return await get_top_patent_authors(
+ organization.openalex_institution_id, from_year, to_year
+ )
+
+
+@router.get(
+ "/top-authors/news",
+ operation_id="getDashboardTopNewsAuthors",
+ response_model=TopAuthorAnalysis,
+)
+async def dashboard_top_news_authors(
+ from_year: int | None = Query(default=None, ge=1900, le=2100),
+ to_year: int | None = Query(default=None, ge=1900, le=2100),
+ session: Session = Depends(get_session),
+ access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
+) -> TopAuthorAnalysis:
+ organization = get_dashboard_organization(session, access_token)
+ return await get_top_news_authors(
+ organization.openalex_institution_id, from_year, to_year
+ )
+
+
@router.get(
"/topic-heatmap",
operation_id="getDashboardTopicHeatmap",
diff --git a/service/src/main/inse/dashboard/service.py b/service/src/main/inse/dashboard/service.py
index ec065b45..873c55f0 100644
--- a/service/src/main/inse/dashboard/service.py
+++ b/service/src/main/inse/dashboard/service.py
@@ -1,48 +1,29 @@
import asyncio
import logging
-import re
-from collections import defaultdict
-from datetime import datetime
-from types import SimpleNamespace
-from typing import Any, Literal
+from typing import Any
from fastapi import HTTPException, status
from sqlmodel import Session
from inse import config
from inse.auth.model import AccessToken, Organization
-from inse.institutions.institutions_search_client import InstitutionsSearchClient
from inse.institutions.v2 import service as institutions_v2_service
from inse.integrations import elasticsearch
from inse.model import ESCluster, ESIndex
from inse.patents.org.elastic_search_client import OrgPatentsSearchClient
from inse.persons import service as persons_service
-from inse.projects import service as projects_service
-from inse.projects.dfg_institutions.service import (
- autocomplete_institutions_for_selector,
-)
-from inse.projects.eu_cordis_projects_client import (
- get_eu_project_ids_by_organization_filters,
-)
-from inse.projects.logic import get_person_ids_by_institution_ids
-from inse.projects.model import (
- EuCordisProjectType,
- ProjectsFilteringProperties,
- ProjectType,
-)
+from inse.works.v2 import service as works_v2_service
-from .institute_helper import get_openalex_institution
+from .common import (
+ DashboardPeriod,
+ dashboard_period as _dashboard_period,
+ institution_works_query as _institution_works_query,
+ normalize_institution_id as _normalize_institution_id,
+ raw_institution_id as _raw_institution_id,
+)
from .model import (
- BmbfProjectStatusStatistics,
DashboardStatistics,
- DfgProjectKeyword,
DashboardStatisticValue,
- DfgProjectStatusStatistics,
- DfgProjectTopic,
- DfgProjectTopics,
- EuProjectStatusStatistics,
- TopAuthor,
- TopAuthorStatistics,
TopicHeatmap,
TopicHeatmapField,
TopicHeatmapSubfield,
@@ -51,94 +32,19 @@ from .model import (
TopicWordCloud,
TopicWordCloudWord,
)
+from .project_statistics_service import (
+ get_dashboard_bmbf_projects,
+ get_dashboard_dfg_projects,
+ get_dashboard_eu_projects,
+)
-TOP_AUTHOR_LIMIT = 10
TOPIC_HEATMAP_LIMIT = 25
TOPIC_HEATMAP_SUBFIELD_LIMIT = 100
TOPIC_HEATMAP_TOPIC_LIMIT = 100
TOPIC_WORD_CLOUD_LIMIT = 30
-WorksPeriod = Literal["all_time", "last_5_years"]
-DashboardPeriod = tuple[int | None, int | None]
logger = logging.getLogger(__name__)
-async def get_eu_organization_project_contributions(
- organization_names: list[str],
- projects_filtering_properties: ProjectsFilteringProperties,
-) -> SimpleNamespace:
- project_ids_by_type = await get_eu_project_ids_by_organization_filters(
- project_types=list(EuCordisProjectType),
- organization_names=organization_names,
- )
- project_ids = {
- str(project_id)
- for ids in project_ids_by_type.values()
- for project_id in ids
- }
- return SimpleNamespace(
- elements=[
- SimpleNamespace(project_id=project_id)
- for project_id in sorted(project_ids)
- ],
- total=len(project_ids),
- page=projects_filtering_properties.page,
- size=projects_filtering_properties.size,
- )
-
-
-ACADEMIC_TITLE_RE = re.compile(
- r"^(?:(?:professor(?:in)?|prof|dr)(?:\.-[a-z]+)?\.?|rer\.|nat\.|med\.|ing\.)\s+",
- re.IGNORECASE,
-)
-
-
-def _normalize_person_name(name: str) -> str:
- normalized = " ".join(name.strip().casefold().split())
- while True:
- without_title = ACADEMIC_TITLE_RE.sub("", normalized).strip()
- if without_title == normalized:
- return without_title
- normalized = without_title
-
-
-def _is_initial_surname_match(full_name: str, initial_name: str) -> bool:
- full_parts = _normalize_person_name(full_name).split()
- initial_parts = _normalize_person_name(initial_name).replace(".", "").split()
- if len(full_parts) < 2 or len(initial_parts) < 2:
- return False
- return (
- len(initial_parts[0]) == 1
- and full_parts[0].startswith(initial_parts[0])
- and full_parts[-1] == initial_parts[-1]
- )
-
-
-def _is_supported_name_variant(full_name: str, candidate_name: str) -> bool:
- return (
- _normalize_person_name(full_name) == _normalize_person_name(candidate_name)
- or _is_initial_surname_match(full_name, candidate_name)
- )
-
-
-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 _dashboard_period(
- from_year: int | None = None,
- to_year: int | None = None,
-) -> DashboardPeriod:
- if from_year is not None and to_year is not None and from_year > to_year:
- raise HTTPException(
- status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
- detail="from_year must be less than or equal to to_year.",
- )
- return from_year, to_year
-
-
def _publication_year_filter(period: DashboardPeriod) -> dict[str, Any] | None:
from_year, to_year = period
year_range: dict[str, int] = {}
@@ -149,46 +55,6 @@ def _publication_year_filter(period: DashboardPeriod) -> dict[str, Any] | None:
return {"range": {"publication_year": year_range}} if year_range else None
-def _project_overlap_filter(
- start_field: str,
- end_field: str,
- period: DashboardPeriod,
- *,
- missing_end_is_ongoing: bool = False,
-) -> dict[str, Any] | None:
- from_year, to_year = period
- filters: list[dict[str, Any]] = []
- if to_year is not None:
- filters.append({"range": {start_field: {"lte": to_year}}})
- if from_year is not None:
- end_filter: dict[str, Any] = {"range": {end_field: {"gte": from_year}}}
- if missing_end_is_ongoing:
- end_filter = {
- "bool": {
- "should": [
- end_filter,
- {"bool": {"must_not": {"exists": {"field": end_field}}}},
- ],
- "minimum_should_match": 1,
- }
- }
- filters.append(end_filter)
- return {"bool": {"filter": filters}} if filters else None
-
-
-def _date_period(period: DashboardPeriod, date_format: str) -> DashboardPeriod:
- from_year, to_year = period
- if date_format == "iso":
- return (
- f"{from_year}-01-01" if from_year is not None else None,
- f"{to_year}-12-31" if to_year is not None else None,
- )
- return (
- f"01.01.{from_year}" if from_year is not None else None,
- f"31.12.{to_year}" if to_year is not None else None,
- )
-
-
def get_dashboard_organization(
session: Session,
access_token: AccessToken,
@@ -212,14 +78,18 @@ async def get_dashboard_statistics(
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),
- )
+ (
+ 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,
@@ -241,25 +111,22 @@ async def get_dashboard_publications(
) -> DashboardStatisticValue:
normalized_id = _normalize_institution_id(institution_id)
period = _dashboard_period(from_year, to_year)
- institution = await institutions_v2_service.get_institution_by_id_or_raise(
- raw_oa_institution_id=_raw_institution_id(normalized_id),
- source=["id", "works_count", "counts_by_year"],
+ publication_years: list[int] = []
+ if period != (None, None):
+ first_year = period[0] if period[0] is not None else 1900
+ last_year = period[1] if period[1] is not None else 2100
+ publication_years = list(range(first_year, last_year + 1))
+
+ works = await works_v2_service.get_works(
+ page=0,
+ size=1,
+ institution_ids=[normalized_id],
+ publication_years=publication_years,
)
- if period == (None, None):
- value = int(institution.works_count or 0)
- else:
- value = sum(
- int(entry.works_count or 0)
- for entry in institution.counts_by_year or []
- if (
- (period[0] is None or int(entry.year or 0) >= period[0])
- and (period[1] is None or int(entry.year or 0) <= period[1])
- )
- )
return DashboardStatisticValue(
institution_id=normalized_id,
organization_name=organization_name,
- value=value,
+ value=works.total,
)
@@ -319,914 +186,6 @@ async def get_dashboard_patents(
)
-async def get_dashboard_eu_projects(
- institution_id: str,
- organization_name: str,
- from_year: int | None = None,
- to_year: int | None = None,
-) -> DashboardStatisticValue:
- normalized_id = _normalize_institution_id(institution_id)
- period = _dashboard_period(from_year, to_year)
- projects = await projects_service.search_eu_cordis_projects(
- institutions_search_client=InstitutionsSearchClient(),
- raw_oa_institution_id=_raw_institution_id(normalized_id),
- author_id=None,
- author_ids=None,
- organization_ids=None,
- organization_names=None,
- project_types=list(EuCordisProjectType),
- keywords=None,
- topic_ids=None,
- filter_topic_ids=None,
- title=None,
- funding_start_years=(
- [str(year) for year in range(1900, period[1] + 1)]
- if period[1] is not None
- else None
- ),
- funding_end_years=(
- [str(year) for year in range(period[0], 2101)]
- if period[0] is not None
- else None
- ),
- countries=None,
- framework_programmes=None,
- funding_schemes=None,
- statuses=None,
- page=0,
- size=1,
- sort_by="id",
- sort_direction="asc",
- fuzzy=False,
- )
- return DashboardStatisticValue(
- institution_id=normalized_id,
- organization_name=organization_name,
- value=projects.total,
- )
-
-
-async def get_dashboard_eu_project_statuses(
- institution_id: str,
- organization_name: str,
- from_year: int | None = None,
- to_year: int | None = None,
-) -> EuProjectStatusStatistics:
- normalized_id = _normalize_institution_id(institution_id)
- aliases = await _institution_aliases(normalized_id, organization_name)
- project_ids = await _eu_project_ids_for_aliases(aliases)
-
- if not project_ids:
- total = (
- await get_dashboard_eu_projects(
- normalized_id,
- organization_name,
- from_year=from_year,
- to_year=to_year,
- )
- ).value
- return EuProjectStatusStatistics(
- institution_id=normalized_id,
- organization_name=organization_name,
- ongoing=total,
- upcoming=0,
- completed=0,
- )
-
- today = datetime.now().date().isoformat()
- period = _dashboard_period(from_year, to_year)
- filters: list[dict[str, Any]] = [{"terms": {"id": sorted(project_ids)}}]
- if period_filter := _project_overlap_filter(
- "startDate",
- "endDate",
- _date_period(period, "iso"),
- ):
- filters.append(period_filter)
- query = (
- {"terms": {"id": sorted(project_ids)}}
- if len(filters) == 1
- else {"bool": {"filter": filters}}
- )
- response = await elasticsearch.search(
- index=ESIndex.CORDIS_EU_PROJECTS_WILDCARD,
- body={
- "size": 0,
- "query": query,
- "aggs": {
- "ongoing": {
- "filter": {
- "bool": {
- "filter": [
- {"range": {"startDate": {"lte": today}}},
- {"range": {"endDate": {"gte": today}}},
- ]
- }
- },
- "aggs": {
- "projects": {"cardinality": {"field": "id"}}
- },
- },
- "upcoming": {
- "filter": {"range": {"startDate": {"gt": today}}},
- "aggs": {
- "projects": {"cardinality": {"field": "id"}}
- },
- },
- "completed": {
- "filter": {"range": {"endDate": {"lt": today}}},
- "aggs": {
- "projects": {"cardinality": {"field": "id"}}
- },
- },
- },
- },
- cluster=ESCluster.INSE,
- )
- aggregations = response.get("aggregations", {})
- total = (
- await get_dashboard_eu_projects(
- normalized_id,
- organization_name,
- from_year=from_year,
- to_year=to_year,
- )
- ).value
- ongoing, upcoming, completed = _reconcile_project_status_counts(
- total,
- _project_status_count(aggregations, "ongoing"),
- _project_status_count(aggregations, "upcoming"),
- _project_status_count(aggregations, "completed"),
- )
- return EuProjectStatusStatistics(
- institution_id=normalized_id,
- organization_name=organization_name,
- ongoing=ongoing,
- upcoming=upcoming,
- completed=completed,
- )
-
-
-def _project_status_count(aggregations: dict[str, Any], status_name: str) -> int:
- return int(
- aggregations.get(status_name, {}).get("projects", {}).get("value", 0)
- )
-
-
-def _reconcile_project_status_counts(
- total: int,
- ongoing: int,
- upcoming: int,
- completed: int,
-) -> tuple[int, int, int]:
- """Makes status buckets add up to the authoritative project-service total."""
- counts = [max(0, ongoing), max(0, upcoming), max(0, completed)]
- difference = total - sum(counts)
- if difference >= 0:
- counts[0] += difference
- return counts[0], counts[1], counts[2]
-
- # Defensive fallback for stale/duplicated status documents: reduce buckets
- # without ever returning negative values, preferring the inferred ongoing
- # bucket before changing explicit upcoming/completed classifications.
- excess = -difference
- for index in (0, 1, 2):
- reduction = min(counts[index], excess)
- counts[index] -= reduction
- excess -= reduction
- if excess == 0:
- break
- return counts[0], counts[1], counts[2]
-
-
-async def get_dashboard_bmbf_projects(
- institution_id: str,
- organization_name: str,
- from_year: int | None = None,
- to_year: int | None = None,
-) -> DashboardStatisticValue:
- normalized_id = _normalize_institution_id(institution_id)
- period = _dashboard_period(from_year, to_year)
- projects = await projects_service.search_bund_projects_with_filters(
- institutions_search_client=InstitutionsSearchClient(),
- executing_agency=None,
- raw_oa_institution_id=_raw_institution_id(normalized_id),
- title=None,
- keywords=None,
- funding_arts=None,
- topic_ids=None,
- filter_topic_ids=None,
- funding_start_years=(
- [str(year) for year in range(1900, period[1] + 1)]
- if period[1] is not None
- else None
- ),
- funding_end_years=(
- [str(year) for year in range(period[0], 2101)]
- if period[0] is not None
- else None
- ),
- countries=None,
- page=0,
- size=1,
- sort_by="id",
- sort_direction="asc",
- fuzzy=False,
- )
- return DashboardStatisticValue(
- institution_id=normalized_id,
- organization_name=organization_name,
- value=projects.total,
- )
-
-
-async def get_dashboard_bmbf_project_statuses(
- institution_id: str,
- organization_name: str,
- from_year: int | None = None,
- to_year: int | None = None,
-) -> BmbfProjectStatusStatistics:
- normalized_id = _normalize_institution_id(institution_id)
- aliases = await _institution_aliases(normalized_id, organization_name)
- period = _dashboard_period(from_year, to_year)
- filters = [_alias_match_query("Zuwendungsempfänger", aliases)]
- if period_filter := _project_overlap_filter(
- "funding_start",
- "funding_end",
- _date_period(period, "de"),
- ):
- filters.append(period_filter)
- today = datetime.now().strftime("%d.%m.%Y")
- response = await elasticsearch.search(
- index=ESIndex.PROJECTS_BUND_V1,
- body={
- "size": 0,
- "query": filters[0] if len(filters) == 1 else {"bool": {"filter": filters}},
- "aggs": _project_status_filter_aggregations(
- start_field="funding_start",
- end_field="funding_end",
- today=today,
- ),
- },
- cluster=ESCluster.INSE,
- )
- aggregations = response.get("aggregations", {})
- total = (
- await get_dashboard_bmbf_projects(
- normalized_id,
- organization_name,
- from_year=from_year,
- to_year=to_year,
- )
- ).value
- ongoing, upcoming, completed = _reconcile_project_status_counts(
- total,
- int(aggregations.get("ongoing", {}).get("doc_count", 0)),
- int(aggregations.get("upcoming", {}).get("doc_count", 0)),
- int(aggregations.get("completed", {}).get("doc_count", 0)),
- )
- return BmbfProjectStatusStatistics(
- institution_id=normalized_id,
- organization_name=organization_name,
- ongoing=ongoing,
- upcoming=upcoming,
- completed=completed,
- )
-
-
-def _project_status_filter_aggregations(
- start_field: str,
- end_field: str,
- today: str,
-) -> dict[str, Any]:
- return {
- "ongoing": {
- "filter": {
- "bool": {
- "filter": [
- {"range": {start_field: {"lte": today}}},
- {"range": {end_field: {"gte": today}}},
- ]
- }
- }
- },
- "upcoming": {"filter": {"range": {start_field: {"gt": today}}}},
- "completed": {"filter": {"range": {end_field: {"lt": today}}}},
- }
-
-
-async def get_dashboard_dfg_projects(
- institution_id: str,
- organization_name: str,
- from_year: int | None = None,
- to_year: int | None = None,
-) -> DashboardStatisticValue:
- normalized_id = _normalize_institution_id(institution_id)
- period = _dashboard_period(from_year, to_year)
- projects = await projects_service.get_dfg_projects(
- institutions_search_client=InstitutionsSearchClient(),
- raw_oa_institution_id=_raw_institution_id(normalized_id),
- author_id=None,
- author_filter_ids=None,
- institution_ids=None,
- keywords=None,
- topic_ids=None,
- filter_topic_ids=None,
- title=None,
- funding_start_years=(
- [str(year) for year in range(1900, period[1] + 1)]
- if period[1] is not None
- else None
- ),
- funding_end_years=(
- [str(year) for year in range(period[0], 2101)]
- if period[0] is not None
- else None
- ),
- page=0,
- size=1,
- sort_by="id",
- sort_direction="asc",
- fuzzy=False,
- )
- return DashboardStatisticValue(
- institution_id=normalized_id,
- organization_name=organization_name,
- value=projects.total,
- )
-
-
-async def get_dashboard_dfg_project_statuses(
- institution_id: str,
- organization_name: str,
- from_year: int | None = None,
- to_year: int | None = None,
-) -> DfgProjectStatusStatistics:
- normalized_id = _normalize_institution_id(institution_id)
- period = _dashboard_period(from_year, to_year)
- project_ids = await _get_dfg_project_ids_for_institution(
- normalized_id,
- )
- if not project_ids:
- total = (
- await get_dashboard_dfg_projects(
- normalized_id,
- organization_name,
- from_year=from_year,
- to_year=to_year,
- )
- ).value
- return DfgProjectStatusStatistics(
- institution_id=normalized_id,
- organization_name=organization_name,
- ongoing=total,
- upcoming=0,
- completed=0,
- )
-
- selected_project_filters: list[dict[str, Any]] = [
- {
- "terms": {
- "projects.project_id": [
- int(project_id) for project_id in project_ids
- ]
- }
- }
- ]
- if period_filter := _project_overlap_filter(
- "projects.funding_start",
- "projects.funding_end",
- period,
- missing_end_is_ongoing=True,
- ):
- selected_project_filters.append(period_filter)
-
- response = await elasticsearch.search(
- index=ESIndex.DFG_INSTITUTES_V2,
- body={
- "size": 0,
- "aggs": {
- "projects_nested": {
- "nested": {"path": "projects"},
- "aggs": {
- "selected_projects": {
- "filter": (
- selected_project_filters[0]
- if len(selected_project_filters) == 1
- else {"bool": {"filter": selected_project_filters}}
- ),
- "aggs": {
- "ongoing": {
- "filter": {
- "match_phrase": {
- "projects.status_de": "laufend"
- }
- },
- "aggs": {
- "projects": {
- "cardinality": {
- "field": "projects.project_id"
- }
- }
- },
- },
- "completed": {
- "filter": {
- "match_phrase": {
- "projects.status_de": "abgeschlossen"
- }
- },
- "aggs": {
- "projects": {
- "cardinality": {
- "field": "projects.project_id"
- }
- }
- },
- },
- },
- }
- },
- }
- },
- },
- cluster=ESCluster.INSE,
- )
- aggregations = (
- response.get("aggregations", {})
- .get("projects_nested", {})
- .get("selected_projects", {})
- )
- total = (
- await get_dashboard_dfg_projects(
- normalized_id,
- organization_name,
- from_year=from_year,
- to_year=to_year,
- )
- ).value
- ongoing, upcoming, completed = _reconcile_project_status_counts(
- total,
- _project_status_count(aggregations, "ongoing"),
- 0,
- _project_status_count(aggregations, "completed"),
- )
- return DfgProjectStatusStatistics(
- institution_id=normalized_id,
- organization_name=organization_name,
- ongoing=ongoing,
- upcoming=upcoming,
- completed=completed,
- )
-
-
-async def get_dashboard_dfg_topics(
- institution_id: str,
- organization_name: str,
- from_year: int | None = None,
- to_year: int | None = None,
-) -> DfgProjectTopics:
- normalized_id = _normalize_institution_id(institution_id)
- project_ids = await _get_dfg_project_ids_from_projects_service(
- normalized_id,
- from_year=from_year,
- to_year=to_year,
- )
- topics: dict[str, dict[str, Any]] = {}
- matched_project_ids: set[str] = set()
-
- if project_ids:
- async for hit in elasticsearch.scan(
- index=str(ESIndex.PROJECTS_DFG_OPENALEX_TOPICS),
- query={"terms": {"project_id": project_ids}},
- source=["project_id", "keyword", "topic_matches"],
- page_size=1000,
- cluster=ESCluster.INSE,
- ):
- source = hit.get("_source", {})
- project_id = str(source.get("project_id") or "")
- if not project_id:
- continue
- keyword = str(source.get("keyword") or "").strip()
- matched_project_ids.add(project_id)
- for match in source.get("topic_matches", []):
- topic_id = str(match.get("topic_id") or "")
- if not topic_id:
- continue
- topic = topics.setdefault(
- topic_id,
- {
- "id": topic_id,
- "name": str(match.get("topic_display_name") or topic_id),
- "subfield": match.get("subfield"),
- "field": match.get("field"),
- "domain": match.get("domain"),
- "project_ids": set(),
- "keywords": {},
- },
- )
- topic["project_ids"].add(project_id)
- if keyword:
- topic["keywords"].setdefault(keyword, set()).add(project_id)
-
- topic_list = [
- DfgProjectTopic(
- id=topic["id"],
- name=topic["name"],
- subfield=topic["subfield"],
- field=topic["field"],
- domain=topic["domain"],
- project_count=len(topic["project_ids"]),
- keywords=sorted(
- [
- DfgProjectKeyword(
- name=keyword,
- project_count=len(keyword_project_ids),
- )
- for keyword, keyword_project_ids in topic["keywords"].items()
- ],
- key=lambda entry: (-entry.project_count, entry.name),
- ),
- )
- for topic in topics.values()
- ]
- topic_list.sort(key=lambda topic: (-topic.project_count, topic.name, topic.id))
- return DfgProjectTopics(
- institution_id=normalized_id,
- organization_name=organization_name,
- project_count=len(project_ids),
- matched_project_count=len(matched_project_ids),
- topics=topic_list,
- )
-
-
-async def _get_dfg_project_ids_from_projects_service(
- institution_id: str,
- from_year: int | None = None,
- to_year: int | None = None,
-) -> list[str]:
- """Returns every matching DFG project ID through the canonical project service."""
- period = _dashboard_period(from_year, to_year)
- page_size = 1000
- page_number = 0
- project_ids: set[str] = set()
-
- while True:
- projects = await projects_service.get_dfg_projects(
- institutions_search_client=InstitutionsSearchClient(),
- raw_oa_institution_id=_raw_institution_id(institution_id),
- author_id=None,
- author_filter_ids=None,
- institution_ids=None,
- keywords=None,
- topic_ids=None,
- filter_topic_ids=None,
- title=None,
- funding_start_years=(
- [str(year) for year in range(1900, period[1] + 1)]
- if period[1] is not None
- else None
- ),
- funding_end_years=(
- [str(year) for year in range(period[0], 2101)]
- if period[0] is not None
- else None
- ),
- page=page_number,
- size=page_size,
- sort_by="id",
- sort_direction="asc",
- fuzzy=False,
- skip_enrichment=True,
- )
- project_ids.update(project.id for project in projects.elements if project.id)
- if len(project_ids) >= projects.total or not projects.elements:
- break
- page_number += 1
-
- return sorted(project_ids)
-
-
-async def _get_dfg_project_ids_for_institution(
- institution_id: str,
- from_year: int | None = None,
- to_year: int | None = None,
-) -> list[str]:
- period = _dashboard_period(from_year, to_year)
- institution = await get_openalex_institution(institution_id)
- institution_names = _openalex_institution_names(institution)
-
- institutes_response = await elasticsearch.search(
- index=ESIndex.DFG_INSTITUTES_V2,
- body={
- "size": 0,
- "query": _dfg_institute_name_query(institution_names),
- "aggs": {
- "institute_ids": {
- "terms": {"field": "institute_id", "size": 1000}
- }
- },
- },
- cluster=ESCluster.INSE,
- )
- institute_ids = [
- bucket["key"]
- for bucket in (
- institutes_response.get("aggregations", {})
- .get("institute_ids", {})
- .get("buckets", [])
- )
- if bucket.get("key") is not None
- ]
- if not institute_ids:
- return []
-
- projects_response = await elasticsearch.search(
- index=ESIndex.DFG_INSTITUTES_V2,
- body={
- "size": 0,
- "query": {"terms": {"institute_id": institute_ids}},
- "aggs": {
- "projects_nested": {
- "nested": {"path": "projects"},
- "aggs": {
- "project_ids": {
- "filter": {
- "terms": {"projects.institute_ref_id": institute_ids}
- },
- "aggs": {
- "values": {
- "terms": {
- "field": "projects.project_id",
- "size": 10000,
- }
- }
- },
- }
- },
- }
- },
- },
- cluster=ESCluster.INSE,
- )
- project_ids = [
- str(bucket["key"])
- for bucket in (
- projects_response.get("aggregations", {})
- .get("projects_nested", {})
- .get("project_ids", {})
- .get("values", {})
- .get("buckets", [])
- )
- if bucket.get("key") is not None
- ]
- return await _filter_dfg_project_ids_by_period(project_ids, period)
-
-
-async def _eu_project_ids_for_aliases(aliases: list[str]) -> set[str]:
- project_ids: set[str] = set()
- async for hit in elasticsearch.scan(
- index=str(ESIndex.CORDIS_EU_ORGANIZATIONS_WILDCARD),
- query=_eu_organization_query(aliases),
- source=["projectID"],
- page_size=1000,
- cluster=ESCluster.INSE,
- ):
- project_id = hit.get("_source", {}).get("projectID")
- if project_id is not None:
- project_ids.add(str(project_id))
- return project_ids
-
-
-async def _count_eu_projects_in_period(
- project_ids: set[str],
- period_filter: dict[str, Any],
-) -> int:
- if not project_ids:
- return 0
- response = await elasticsearch.search(
- index=ESIndex.CORDIS_EU_PROJECTS_WILDCARD,
- body={
- "size": 0,
- "query": {
- "bool": {
- "filter": [
- {"terms": {"id": sorted(project_ids)}},
- period_filter,
- ]
- }
- },
- "aggs": {"projects": {"cardinality": {"field": "id"}}},
- },
- cluster=ESCluster.INSE,
- )
- return int(
- response.get("aggregations", {})
- .get("projects", {})
- .get("value", 0)
- )
-
-
-async def _filter_dfg_project_ids_by_period(
- project_ids: list[str],
- period: DashboardPeriod,
-) -> list[str]:
- period_filter = _project_overlap_filter(
- "funding_start",
- "funding_end",
- period,
- missing_end_is_ongoing=True,
- )
- if not project_ids or not period_filter:
- return project_ids
-
- numeric_project_ids = [
- int(project_id)
- for project_id in project_ids
- if str(project_id).isdigit()
- ]
- if not numeric_project_ids:
- return []
-
- response = await elasticsearch.search(
- index=ESIndex.DFG_PROJECTS,
- body={
- "size": 0,
- "query": {
- "bool": {
- "filter": [
- {"terms": {"id": numeric_project_ids}},
- period_filter,
- ]
- }
- },
- "aggs": {
- "project_ids": {
- "terms": {
- "field": "id",
- "size": len(numeric_project_ids),
- }
- }
- },
- },
- cluster=ESCluster.INSE,
- )
- return [
- str(bucket["key"])
- for bucket in (
- response.get("aggregations", {})
- .get("project_ids", {})
- .get("buckets", [])
- )
- if bucket.get("key") is not None
- ]
-
-
-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 _openalex_institution_names(institution: Any) -> list[str]:
- return sorted(
- {
- name.strip()
- for name in [
- institution.display_name,
- *(institution.display_name_alternatives or []),
- *(institution.display_name_acronyms or []),
- ]
- if name and name.strip()
- }
- )
-
-
-def _dfg_institute_name_query(institution_names: list[str]) -> dict[str, Any]:
- return {
- "bool": {
- "should": [
- {
- "terms": {
- "institute_name_de.keyword": institution_names,
- }
- },
- {
- "terms": {
- "institute_name_en.keyword": institution_names,
- }
- },
- ],
- "minimum_should_match": 1,
- }
- }
-
-
-async def get_top_authors(
- institution_id: str,
- organization_name: str,
- works_period: WorksPeriod = "all_time",
- from_year: int | None = None,
- to_year: int | None = None,
-) -> TopAuthorStatistics:
- normalized_id = _normalize_institution_id(institution_id)
- if from_year is None and to_year is None and works_period == "last_5_years":
- from_year = datetime.now().year - 4
- to_year = datetime.now().year
- period = _dashboard_period(from_year, to_year)
- authors = await _safe_institution_authors(normalized_id)
- works = _top_work_authors(authors, period)
- projects = await _safe_top_authors(
- "projects",
- _top_project_authors(
- authors=authors,
- organization_name=organization_name,
- from_year=period[0],
- to_year=period[1],
- ),
- )
- eu_projects = await _safe_top_authors(
- "eu_projects",
- _top_eu_project_publication_authors(
- normalized_id,
- authors,
- from_year=period[0],
- to_year=period[1],
- ),
- )
-
- patents = await _safe_top_authors(
- "patents",
- _top_patent_authors(
- normalized_id,
- from_year=period[0],
- to_year=period[1],
- ),
- )
-
- news = await _safe_top_authors(
- "news",
- _top_news_authors(authors),
- )
-
- return TopAuthorStatistics(
- institution_id=normalized_id,
- works=works,
- projects=projects,
- eu_projects=eu_projects,
- patents=patents,
- news=news,
- )
-
-
async def get_topic_heatmap(
institution_id: str,
organization_name: str,
@@ -1445,39 +404,9 @@ async def get_topic_word_cloud(
return TopicWordCloud(topic_id=topic_id, words=words)
-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", [])
+ response.get("aggregations", {}).get("publication_years", {}).get("buckets", [])
)
return {
int(bucket["key"]): int(bucket.get("doc_count", 0))
@@ -1505,8 +434,7 @@ async def _field_names(field_ids: list[str | None]) -> dict[str, str]:
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")
+ if (source := hit.get("_source", {})).get("id") and source.get("display_name")
}
@@ -1582,901 +510,8 @@ def _field_name(bucket: dict[str, Any], fallback: str) -> str:
return _aggregation_name(bucket, "field_name", fallback)
-def _aggregation_name(
- bucket: dict[str, Any], aggregation: str, fallback: str
-) -> str:
+def _aggregation_name(bucket: dict[str, Any], aggregation: str, fallback: str) -> str:
name_buckets = bucket.get(aggregation, {}).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]],
- period: DashboardPeriod,
-) -> list[TopAuthor]:
- if period != (None, None):
- ranked_authors = sorted(
- (
- {
- **author,
- "selected_works_count": _works_count_in_period(author, period),
- }
- 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_in_period(author: dict[str, Any], period: DashboardPeriod) -> int:
- from_year, to_year = period
- return sum(
- int(item.get("works_count", 0) or 0)
- for item in author.get("counts_by_year", [])
- if (
- (from_year is None or int(item.get("year", 0) or 0) >= from_year)
- and (to_year is None or int(item.get("year", 0) or 0) <= to_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 _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]],
- organization_name: str,
- from_year: int | None = None,
- to_year: int | None = None,
-) -> list[TopAuthor]:
- period = _dashboard_period(from_year, to_year)
- institution_ids = await _dfg_institution_ids_for_organization(
- organization_name=organization_name,
- )
-
- logger.info(
- "DFG institution IDs for %s: %s",
- organization_name,
- institution_ids,
- )
-
- if not institution_ids:
- logger.warning(
- "No DFG institution IDs found for organization %s.",
- organization_name,
- )
- return []
-
- selected_person_ids = set(
- await get_person_ids_by_institution_ids(institution_ids=institution_ids)
- )
-
- logger.info(
- "Found %s DFG persons for organization %s.",
- len(selected_person_ids),
- organization_name,
- )
-
- if not selected_person_ids:
- return []
-
- project_ids_by_person: dict[int, set[str]] = {}
- names: dict[int, str] = {}
-
- page = 0
- size = 10000
- processed = 0
-
- while True:
- project_hits, total = await _dfg_project_author_hits(
- page=page,
- size=size,
- person_ids=selected_person_ids,
- period=period,
- )
-
- if not project_hits:
- break
-
- for project in project_hits:
- project_id = _dfg_project_id(project)
- if not project_id:
- continue
-
- persons = project.get("persons", [])
- if not isinstance(persons, list):
- continue
-
- for person in persons:
- if not isinstance(person, dict):
- continue
-
- person_id = person.get("person_id")
- full_name = person.get("full_name")
- if person_id is None or not full_name:
- continue
-
- try:
- normalized_person_id = int(person_id)
- except (TypeError, ValueError):
- continue
-
- if normalized_person_id not in selected_person_ids:
- continue
-
- project_ids_by_person.setdefault(normalized_person_id, set()).add(
- project_id
- )
- names[normalized_person_id] = str(full_name).strip()
-
- processed += len(project_hits)
- if processed >= total:
- break
-
- page += 1
-
- institution_authors: dict[str, list[dict[str, Any]]] = {}
- for author in authors:
- if author.get("name"):
- institution_authors.setdefault(
- _normalize_person_name(author["name"]),
- [],
- ).append(author)
-
- ranked = sorted(
- (
- (person_id, project_ids)
- for person_id, project_ids in project_ids_by_person.items()
- if project_ids and names.get(person_id)
- ),
- key=lambda item: (
- -len(item[1]),
- names[item[0]].casefold(),
- ),
- )
-
- ranked_person_ids = [person_id for person_id, _ in ranked[:TOP_AUTHOR_LIMIT]]
- dfg_orcids = await _dfg_person_orcids(ranked_person_ids)
-
- result: list[TopAuthor] = []
-
- for person_id, project_ids in ranked[:TOP_AUTHOR_LIMIT]:
- dfg_name = names[person_id]
- matched_author = _single_author_match(
- institution_authors.get(_normalize_person_name(dfg_name), [])
- )
-
- if matched_author is None and (orcid := dfg_orcids.get(person_id)):
- matched_author = await _openalex_author_by_orcid(orcid)
-
- if matched_author is None:
- matched_author = await _openalex_author_by_dfg_publication_evidence(
- dfg_name=dfg_name,
- project_ids=project_ids,
- )
-
- if matched_author is None:
- logger.info(
- "No exact OpenAlex match for DFG author '%s' (person_id=%s).",
- dfg_name,
- person_id,
- )
-
- result.append(
- TopAuthor(
- id=(
- _short_author_id(matched_author["id"])
- if matched_author
- else None
- ),
- name=matched_author["name"] if matched_author else dfg_name,
- count=len(project_ids),
- )
- )
-
- logger.info(
- "DFG top authors for %s: %s",
- organization_name,
- [
- {
- "name": author.name,
- "count": author.count,
- "id": author.id,
- }
- for author in result
- ],
- )
-
- return result
-
-
-def _single_author_match(authors: list[dict[str, Any]]) -> dict[str, Any] | None:
- return authors[0] if len(authors) == 1 else None
-
-
-async def _dfg_person_orcids(person_ids: list[int]) -> dict[int, str]:
- if not person_ids:
- return {}
-
- try:
- response = await elasticsearch.search(
- index=ESIndex.DFG_PERSONS,
- body={
- "size": len(person_ids),
- "_source": ["person_id", "orcid_id"],
- "query": {"terms": {"person_id": person_ids}},
- },
- cluster=ESCluster.INSE,
- )
- except Exception:
- logger.exception("Could not load DFG ORCIDs for top project authors.")
- return {}
-
- result: dict[int, str] = {}
- for hit in response.get("hits", {}).get("hits", []):
- source = hit.get("_source", {})
- person_id = source.get("person_id")
- orcid = source.get("orcid_id")
- if person_id is None or not orcid:
- continue
- try:
- result[int(person_id)] = str(orcid)
- except (TypeError, ValueError):
- continue
- return result
-
-
-async def _openalex_author_by_orcid(orcid: str) -> dict[str, Any] | None:
- normalized_orcid = orcid.replace("https://orcid.org/", "").strip()
- if not normalized_orcid:
- return None
-
- prefixed_orcid = f"https://orcid.org/{normalized_orcid}"
- try:
- response = await elasticsearch.search(
- index=ESIndex.OPENALEX_AUTHORS,
- body={
- "size": 2,
- "_source": ["id", "display_name"],
- "query": {
- "bool": {
- "should": [
- {"term": {"orcid.keyword": normalized_orcid}},
- {"term": {"orcid.keyword": prefixed_orcid}},
- {"term": {"ids.orcid.keyword": normalized_orcid}},
- {"term": {"ids.orcid.keyword": prefixed_orcid}},
- {"term": {"orcid": normalized_orcid}},
- {"term": {"orcid": prefixed_orcid}},
- {"term": {"ids.orcid": normalized_orcid}},
- {"term": {"ids.orcid": prefixed_orcid}},
- ],
- "minimum_should_match": 1,
- }
- },
- },
- cluster=ESCluster.NES,
- track_total_hits=True,
- )
- except Exception:
- logger.exception("Could not resolve OpenAlex author by ORCID %s.", orcid)
- return None
-
- hits = response.get("hits", {}).get("hits", [])
- if len(hits) != 1:
- logger.info(
- "OpenAlex ORCID lookup for %s returned %s hits.",
- orcid,
- len(hits),
- )
- return None
-
- source = hits[0].get("_source", {})
- if not source.get("id") or not source.get("display_name"):
- return None
- return {
- "id": str(source["id"]),
- "name": str(source["display_name"]),
- }
-
-
-async def _openalex_author_by_dfg_publication_evidence(
- dfg_name: str,
- project_ids: set[str],
-) -> dict[str, Any] | None:
- dois = await _dfg_project_publication_dois(project_ids)
- if not dois:
- return None
-
- try:
- response = await elasticsearch.search(
- index=config.settings.openalex_works_search_index,
- body={
- "size": 10000,
- "_source": [
- "doi",
- "authorships.author.id",
- "authorships.author.display_name",
- ],
- "query": {"terms": {"doi": sorted(_doi_variants(dois))}},
- },
- cluster=ESCluster.NES,
- )
- except Exception:
- logger.exception(
- "Could not resolve OpenAlex author from DFG publication DOIs for %s.",
- dfg_name,
- )
- return None
-
- candidates: dict[str, dict[str, Any]] = {}
- for hit in response.get("hits", {}).get("hits", []):
- source = hit.get("_source", {})
- doi = source.get("doi")
- if not doi:
- continue
- for authorship in source.get("authorships", []) or []:
- author = authorship.get("author", {}) if isinstance(authorship, dict) else {}
- author_id = author.get("id")
- display_name = author.get("display_name")
- if not author_id or not display_name:
- continue
- if not _is_supported_name_variant(dfg_name, str(display_name)):
- continue
- candidate = candidates.setdefault(
- str(author_id),
- {
- "id": str(author_id),
- "name": str(display_name),
- "dois": set(),
- },
- )
- candidate["dois"].add(str(doi))
-
- supported_candidates = [
- candidate
- for candidate in candidates.values()
- if len(candidate["dois"]) >= 2
- ]
- if len(supported_candidates) != 1:
- if supported_candidates:
- logger.info(
- "DFG publication DOI lookup for %s returned %s candidates.",
- dfg_name,
- len(supported_candidates),
- )
- return None
-
- candidate = supported_candidates[0]
- return {
- "id": candidate["id"],
- "name": candidate["name"],
- }
-
-
-async def _dfg_project_publication_dois(project_ids: set[str]) -> set[str]:
- if not project_ids:
- return set()
-
- numeric_project_ids = [
- int(project_id)
- for project_id in project_ids
- if str(project_id).isdigit()
- ]
- if not numeric_project_ids:
- return set()
-
- try:
- response = await elasticsearch.search(
- index=ESIndex.DFG_PROJECTS,
- body={
- "size": len(numeric_project_ids),
- "_source": ["publications.doi"],
- "query": {"terms": {"id": numeric_project_ids}},
- },
- cluster=ESCluster.INSE,
- )
- except Exception:
- logger.exception("Could not load DFG publication DOIs.")
- return set()
-
- dois: set[str] = set()
- for hit in response.get("hits", {}).get("hits", []):
- for publication in hit.get("_source", {}).get("publications", []) or []:
- doi = publication.get("doi") if isinstance(publication, dict) else None
- if doi:
- dois.add(str(doi).strip())
- return {doi for doi in dois if doi}
-
-
-def _doi_variants(dois: set[str]) -> set[str]:
- variants: set[str] = set()
- for doi in dois:
- normalized = doi.strip()
- if not normalized:
- continue
- raw = normalized
- for prefix in ("https://doi.org/", "http://dx.doi.org/"):
- if raw.casefold().startswith(prefix):
- raw = raw[len(prefix):]
- break
- variants.update(
- {
- normalized,
- normalized.lower(),
- f"https://doi.org/{raw}",
- f"https://doi.org/{raw.lower()}",
- }
- )
- return variants
-
-
-async def _dfg_institution_ids_for_organization(organization_name: str) -> list[int]:
- page = await autocomplete_institutions_for_selector(
- query=organization_name,
- page=0,
- size=10000,
- )
- return [institution.id for institution in page.elements if institution.id is not None]
-
-
-async def _dfg_project_author_hits(
- page: int,
- size: int,
- person_ids: set[int],
- period: DashboardPeriod = (None, None),
-) -> tuple[list[dict[str, Any]], int]:
- person_query = {
- "nested": {
- "path": "persons",
- "query": {"terms": {"persons.person_id": sorted(person_ids)}},
- },
- }
- period_filter = _project_overlap_filter(
- "funding_start",
- "funding_end",
- period,
- missing_end_is_ongoing=True,
- )
- query = (
- {"bool": {"filter": [person_query, period_filter]}}
- if period_filter
- else person_query
- )
- response = await elasticsearch.search(
- index=ESIndex.DFG_PROJECTS,
- body={
- "size": size,
- "from": page * size,
- "_source": [
- "id",
- "project_id",
- "persons",
- ],
- "query": query,
- "sort": [
- {
- "id": {
- "order": "asc",
- "missing": "_last",
- }
- }
- ],
- },
- cluster=ESCluster.INSE,
- track_total_hits=True,
- )
-
- hits_block = response.get("hits", {})
- total_value = hits_block.get("total", 0)
-
- if isinstance(total_value, dict):
- total = int(total_value.get("value", 0))
- else:
- total = int(total_value or 0)
-
- hits = [
- hit.get("_source", {})
- for hit in hits_block.get("hits", [])
- if isinstance(hit.get("_source"), dict)
- ]
-
- logger.info(
- "Loaded %s of %s matching DFG projects on page %s.",
- len(hits),
- total,
- page,
- )
-
- return hits, total
-
-
-def _dfg_project_id(project: dict[str, Any]) -> str | None:
- project_id = project.get("id")
- if project_id is None:
- project_id = project.get("project_id")
- return str(project_id) if project_id is not None else None
-
-
-async def _top_patent_authors(
- institution_id: str,
- from_year: int | None = None,
- to_year: int | None = None,
-) -> list[TopAuthor]:
- client = OrgPatentsSearchClient()
- authors = await client.top_authors_by_institution(
- institution_id=institution_id,
- size=TOP_AUTHOR_LIMIT,
- from_year=from_year,
- to_year=to_year,
- )
- return [
- TopAuthor(
- id=_short_author_id(author["id"]),
- name=author["name"],
- count=author["count"],
- )
- for author in authors
- ]
-
-
-async def _top_eu_project_publication_authors(
- institution_id: str,
- institution_authors: list[dict[str, Any]],
- from_year: int | None = None,
- to_year: int | None = None,
-) -> list[TopAuthor]:
- institution_author_ids = {
- author_id
- for author in institution_authors
- if (author_id := _normalize_author_id(author.get("id")))
- }
- if not institution_author_ids:
- return []
-
- project_ids = await _get_eu_project_ids_from_projects_service(
- institution_id,
- from_year=from_year,
- to_year=to_year,
- )
-
- if not project_ids:
- return []
-
- publication_response = await elasticsearch.search(
- index=ESIndex.CORDIS_EU_PUBLICATIONS_WILDCARD,
- body={
- "size": 10000,
- "_source": ["projectID", "qaProcessedDoi"],
- "query": {"terms": {"projectID": project_ids}},
- },
- cluster=ESCluster.INSE,
- )
-
- doi_project_ids = _cordis_publication_doi_project_ids(
- publication_response,
- set(project_ids),
- )
- if not doi_project_ids:
- return []
-
- works_response = await elasticsearch.search(
- index="openalex-works",
- body={
- "size": 10000,
- "_source": [
- "doi",
- "authorships.author.id",
- "authorships.author.display_name",
- "authorships.institutions.id",
- ],
- "query": {
- "bool": {
- "filter": [
- {"terms": {"doi": sorted(doi_project_ids)}},
- _institution_works_query(institution_id),
- ]
- }
- },
- },
- cluster=ESCluster.NES,
- )
-
- candidates = _openalex_work_authors_by_eu_projects(
- works_response,
- doi_project_ids,
- institution_id,
- institution_author_ids,
- limit=None,
- )
- counts = await asyncio.gather(
- *(
- _person_eu_project_count(
- candidate.id,
- from_year=from_year,
- to_year=to_year,
- )
- for candidate in candidates
- if candidate.id
- )
- )
- ranked = [
- TopAuthor(id=candidate.id, name=candidate.name, count=count)
- for candidate, count in zip(candidates, counts, strict=True)
- ]
- ranked.sort(key=lambda author: (-author.count, author.name, author.id or ""))
- return ranked[:TOP_AUTHOR_LIMIT]
-
-
-async def _get_eu_project_ids_from_projects_service(
- institution_id: str,
- from_year: int | None = None,
- to_year: int | None = None,
-) -> list[str]:
- """Loads all organization EU project IDs from the canonical project service."""
- period = _dashboard_period(from_year, to_year)
- page_size = 1000
- page_number = 0
- project_ids: set[str] = set()
-
- while True:
- projects = await projects_service.search_eu_cordis_projects(
- institutions_search_client=InstitutionsSearchClient(),
- raw_oa_institution_id=_raw_institution_id(institution_id),
- author_id=None,
- author_ids=None,
- organization_ids=None,
- organization_names=None,
- project_types=list(EuCordisProjectType),
- keywords=None,
- topic_ids=None,
- filter_topic_ids=None,
- title=None,
- funding_start_years=(
- [str(year) for year in range(1900, period[1] + 1)]
- if period[1] is not None
- else None
- ),
- funding_end_years=(
- [str(year) for year in range(period[0], 2101)]
- if period[0] is not None
- else None
- ),
- countries=None,
- framework_programmes=None,
- funding_schemes=None,
- statuses=None,
- page=page_number,
- size=page_size,
- sort_by="id",
- sort_direction="asc",
- fuzzy=False,
- skip_enrichment=True,
- )
- project_ids.update(project.id for project in projects.elements if project.id)
- if len(project_ids) >= projects.total or not projects.elements:
- break
- page_number += 1
-
- return sorted(project_ids)
-
-
-def _cordis_publication_doi_project_ids(
- response: dict[str, Any],
- allowed_project_ids: set[str],
-) -> dict[str, set[str]]:
- doi_project_ids: dict[str, set[str]] = defaultdict(set)
- for hit in response.get("hits", {}).get("hits", []):
- source = hit.get("_source", {})
- project_id = str(source.get("projectID") or "").strip()
- if not project_id or project_id not in allowed_project_ids:
- continue
- doi = _normalize_doi(source.get("qaProcessedDoi"))
- if doi:
- doi_project_ids[doi].add(project_id)
- return dict(doi_project_ids)
-
-
-def _normalize_doi(value: Any) -> str | None:
- if not isinstance(value, str) or not value.strip():
- return None
- doi = value.strip().lower()
- if doi.startswith("https://doi.org/"):
- return doi
- if doi.startswith("http://doi.org/"):
- return "https://" + doi.removeprefix("http://")
- if doi.startswith("doi.org/"):
- return f"https://{doi}"
- return f"https://doi.org/{doi}"
-
-
-def _openalex_work_authors_by_eu_projects(
- response: dict[str, Any],
- doi_project_ids: dict[str, set[str]],
- institution_id: str,
- institution_author_ids: set[str],
- limit: int | None = TOP_AUTHOR_LIMIT,
-) -> list[TopAuthor]:
- # Count unique CORDIS projects per author, not publications. Multiple works
- # (and therefore multiple DOIs) can belong to the same project ID.
- author_project_ids: dict[str, set[str]] = defaultdict(set)
- author_names: dict[str, str] = {}
-
- for hit in response.get("hits", {}).get("hits", []):
- source = hit.get("_source", {})
- project_ids = doi_project_ids.get(_normalize_doi(source.get("doi")) or "")
- if not project_ids:
- continue
-
- for authorship in source.get("authorships") or []:
- if not any(
- institution.get("id") == institution_id
- for institution in authorship.get("institutions") or []
- ):
- continue
- author = authorship.get("author") or {}
- author_id = _normalize_author_id(author.get("id"))
- author_name = str(author.get("display_name") or "").strip()
- if (
- not author_id
- or author_id not in institution_author_ids
- or not author_name
- ):
- continue
- author_project_ids[author_id].update(project_ids)
- author_names.setdefault(author_id, author_name)
-
- ranked_authors = sorted(
- author_project_ids.items(),
- key=lambda item: (-len(item[1]), author_names.get(item[0], ""), item[0]),
- )
-
- authors = [
- TopAuthor(
- id=_short_author_id(author_id),
- name=author_names[author_id],
- count=len(project_ids),
- )
- for author_id, project_ids in ranked_authors
- ]
- return authors[:limit] if limit is not None else authors
-
-
-async def _person_eu_project_count(
- author_id: str,
- from_year: int | None = None,
- to_year: int | None = None,
-) -> int:
- """Uses the same author-only EU project search as the person detail page."""
- period = _dashboard_period(from_year, to_year)
- projects = await projects_service.search_eu_cordis_projects(
- page=0,
- size=1,
- project_types=None,
- raw_oa_institution_id=None,
- institutions_search_client=None,
- author_id=_short_author_id(author_id),
- author_ids=None,
- organization_ids=None,
- organization_names=None,
- keywords=None,
- topic_ids=None,
- filter_topic_ids=None,
- title=None,
- funding_start_years=(
- [str(year) for year in range(1900, period[1] + 1)]
- if period[1] is not None
- else None
- ),
- funding_end_years=(
- [str(year) for year in range(period[0], 2101)]
- if period[0] is not None
- else None
- ),
- countries=None,
- framework_programmes=None,
- funding_schemes=None,
- statuses=None,
- sort_by="title",
- sort_direction="asc",
- fuzzy=False,
- skip_enrichment=True,
- )
- return projects.total
-
-
-def _normalize_author_id(value: Any) -> str | None:
- if not isinstance(value, str) or not value.strip():
- return None
- short_id = value.replace("https://openalex.org/", "").strip().upper()
- return f"https://openalex.org/{short_id}"
-
-
-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]
diff --git a/service/src/main/inse/dashboard/test_service.py b/service/src/main/inse/dashboard/test_service.py
index 2de2ca6e..4445262a 100644
--- a/service/src/main/inse/dashboard/test_service.py
+++ b/service/src/main/inse/dashboard/test_service.py
@@ -1,5 +1,6 @@
+import asyncio
from datetime import datetime
-from types import SimpleNamespace
+import hashlib
from unittest.mock import AsyncMock, patch
import pytest
@@ -9,45 +10,177 @@ from sqlmodel import Session, SQLModel, create_engine
from inse import config
from inse.auth.model import AccessToken, Organization, UserRole
from inse.dashboard.service import (
- _openalex_work_authors_by_eu_projects,
- _get_dfg_project_ids_from_projects_service,
- _reconcile_project_status_counts,
- 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,
get_topic_word_cloud,
)
-from inse.model import ESCluster, ESIndex
-from inse.models.openalex.author_counts_by_year_inner import AuthorCountsByYearInner
+from inse.dashboard.common import (
+ project_boundary_year_filter as _project_boundary_year_filter,
+)
+from inse.dashboard.bund_topics_service import get_dashboard_bund_topics
+from inse.dashboard.eu_topics_service import get_dashboard_eu_topics
+from inse.dashboard.model import TopAuthor
+from inse.dashboard.project_status_service import reconcile_status_counts
+from inse.dashboard.project_ids_service import (
+ _get_dfg_project_ids_from_projects_service,
+)
+from inse.dashboard.project_statistics_service import (
+ get_dashboard_bmbf_projects,
+ get_dashboard_dfg_projects,
+ get_dashboard_eu_projects,
+)
+from inse.dashboard.top_authors_service import (
+ _count_eu_projects_for_candidates,
+ _openalex_work_authors_by_eu_projects,
+ _top_news_authors,
+ get_top_authors,
+)
+from inse.exceptions import ElasticsearchException
+from inse.model import ESIndex
from inse.models.openalex.institution import Institution
from inse.models.openalex.meta import Meta
from inse.persons.model import CustomAuthorsListResponse
from inse.projects.model import (
BundProjectPage,
+ BundProjectSummary,
DfgProjectPage,
DfgProjectSummary,
EuCordisProjectSearchPage,
EuCordisProjectSummary,
EuCordisProjectType,
)
+from inse.works.v2 import service as works_v2_service
+from inse.works.v2.model import WorkPageV2
ORG_INSTITUTION_ID = "https://openalex.org/I123"
+@pytest.mark.anyio
+async def test_eu_project_counts_are_bounded_retried_and_isolated():
+ attempts: dict[str, int] = {}
+ active_requests = 0
+ maximum_active_requests = 0
+
+ async def count_projects(author_id: str, **kwargs) -> int:
+ nonlocal active_requests, maximum_active_requests
+ attempts[author_id] = attempts.get(author_id, 0) + 1
+ active_requests += 1
+ maximum_active_requests = max(maximum_active_requests, active_requests)
+ await asyncio.sleep(0.001)
+ active_requests -= 1
+ if author_id == "A0" and attempts[author_id] < 3:
+ raise ElasticsearchException("temporary")
+ if author_id == "A1":
+ raise ElasticsearchException("unavailable")
+ return int(author_id.removeprefix("A"))
+
+ candidates = [
+ TopAuthor(id=f"A{index}", name=f"Author {index}", count=0) for index in range(8)
+ ]
+ with (
+ patch(
+ "inse.dashboard.top_authors_service._person_eu_project_count",
+ new=count_projects,
+ ),
+ patch(
+ "inse.dashboard.top_authors_service.EU_PROJECT_COUNT_RETRY_DELAY_SECONDS",
+ 0,
+ ),
+ ):
+ result = await _count_eu_projects_for_candidates(candidates)
+
+ assert maximum_active_requests <= 5
+ assert attempts["A0"] == 3
+ assert attempts["A1"] == 3
+ assert [author.id for author in result] == [
+ "A0",
+ "A2",
+ "A3",
+ "A4",
+ "A5",
+ "A6",
+ "A7",
+ ]
+
+
@pytest.fixture
def anyio_backend():
return "asyncio"
def test_project_status_counts_match_authoritative_total():
- assert _reconcile_project_status_counts(12, 4, 1, 5) == (6, 1, 5)
- assert _reconcile_project_status_counts(7, 4, 2, 3) == (2, 2, 3)
+ assert reconcile_status_counts(12, 4, 1, 5) == (6, 1, 5)
+ assert reconcile_status_counts(7, 4, 2, 3) == (2, 2, 3)
+
+
+def test_project_status_period_uses_interval_overlap():
+ assert _project_boundary_year_filter(
+ "startDate", "endDate", (2022, 2026), "iso"
+ ) == {
+ "bool": {
+ "filter": [
+ {"range": {"startDate": {"lte": "2026-12-31"}}},
+ {"range": {"endDate": {"gte": "2022-01-01"}}},
+ ]
+ }
+ }
+ assert _project_boundary_year_filter(
+ "projects.funding_start",
+ "projects.funding_end",
+ (2022, 2026),
+ "year",
+ ) == {
+ "bool": {
+ "filter": [
+ {"range": {"projects.funding_start": {"lte": 2026}}},
+ {"range": {"projects.funding_end": {"gte": 2022}}},
+ ]
+ }
+ }
+
+
+@pytest.mark.anyio
+async def test_top_news_authors_applies_dashboard_period():
+ response = {
+ "aggregations": {
+ "authors": {"buckets": [{"key": "Ada Example", "doc_count": 3}]}
+ }
+ }
+
+ async def scan(**kwargs):
+ assert kwargs["index"] == str(ESIndex.AKTUELLES)
+ assert kwargs["query"] == {"range": {"date_year": {"gte": 2020, "lte": 2023}}}
+ yield {"_id": "N1"}
+ yield {"_id": "N2"}
+
+ with (
+ patch(
+ "inse.integrations.elasticsearch.search",
+ new=AsyncMock(return_value=response),
+ ) as mocked_search,
+ patch(
+ "inse.integrations.elasticsearch.scan",
+ new=scan,
+ ),
+ ):
+ result = await _top_news_authors(
+ [{"id": "https://openalex.org/A1", "name": "Ada Example"}],
+ from_year=2020,
+ to_year=2023,
+ )
+
+ assert result[0].count == 3
+ assert mocked_search.await_args.kwargs["body"]["query"] == {
+ "bool": {
+ "filter": [
+ {"terms": {"authors.keyword": ["Ada Example"]}},
+ {"terms": {"news_id.keyword": ["N1", "N2"]}},
+ ]
+ }
+ }
@pytest.mark.anyio
@@ -68,7 +201,7 @@ async def test_dfg_topic_project_ids_use_paginated_projects_service():
]
with patch(
- "inse.dashboard.service.projects_service.get_dfg_projects",
+ "inse.projects.service.get_dfg_projects",
new=AsyncMock(side_effect=pages),
) as mocked_get_projects:
project_ids = await _get_dfg_project_ids_from_projects_service(
@@ -86,13 +219,168 @@ async def test_dfg_topic_project_ids_use_paginated_projects_service():
assert first_call.kwargs["funding_end_years"][0] == "2020"
+@pytest.mark.anyio
+async def test_eu_topics_scan_all_programme_indices_and_deduplicate_projects():
+ scanned_indices: list[str] = []
+
+ async def scan(**kwargs):
+ scanned_indices.append(kwargs["index"])
+ if kwargs["index"] == str(ESIndex.PROJECTS_CORDIS_EU_FP7_TOPICS_MAPPING):
+ yield {
+ "_source": {
+ "project_id": "P1",
+ "keyword": "AI",
+ "topic_matches": [
+ {
+ "topic_id": "T1",
+ "topic_display_name": "Artificial Intelligence",
+ "field": "Computer Science",
+ "subfield": "AI",
+ "domain": "Physical Sciences",
+ }
+ ],
+ }
+ }
+ yield {
+ "_source": {
+ "project_id": "P1",
+ "keyword": "Robotics",
+ "topic_matches": [
+ {
+ "topic_id": "T2",
+ "topic_display_name": "Robotics",
+ "field": "Computer Science",
+ "subfield": "Robotics",
+ "domain": "Physical Sciences",
+ }
+ ],
+ }
+ }
+ if kwargs["index"] == str(ESIndex.PROJECTS_CORDIS_EU_H2020_TOPICS):
+ yield {
+ "_source": {
+ "project_id": "P2",
+ "keyword": "AI",
+ "topic_matches": [
+ {
+ "topic_id": "T1",
+ "topic_display_name": "Artificial Intelligence",
+ "field": "Computer Science",
+ "subfield": "AI",
+ "domain": "Physical Sciences",
+ }
+ ],
+ }
+ }
+
+ with (
+ patch(
+ "inse.dashboard.eu_topics_service._get_eu_project_ids_from_projects_service",
+ new=AsyncMock(return_value=["P1", "P2", "P3"]),
+ ),
+ patch("inse.integrations.elasticsearch.scan", new=scan),
+ ):
+ result = await get_dashboard_eu_topics(
+ ORG_INSTITUTION_ID,
+ "Example Org",
+ from_year=2022,
+ to_year=2026,
+ )
+
+ assert scanned_indices == [
+ str(ESIndex.PROJECTS_CORDIS_EU_FP7_TOPICS_MAPPING),
+ str(ESIndex.PROJECTS_CORDIS_EU_H2020_TOPICS),
+ str(ESIndex.PROJECTS_CORDIS_EU_HEUROPE_TOPICS),
+ ]
+ assert result.project_count == 3
+ assert result.matched_project_count == 2
+ assert result.topics[0].project_count == 2
+ assert result.topics[0].keywords[0].project_count == 2
+ assert {topic.field_project_count for topic in result.topics} == {2}
+ assert {topic.name: topic.subfield_project_count for topic in result.topics} == {
+ "Artificial Intelligence": 2,
+ "Robotics": 1,
+ }
+
+
+@pytest.mark.anyio
+async def test_bund_topics_use_mapping_index_and_unique_hierarchy_counts():
+ project_page = BundProjectPage(
+ elements=[
+ BundProjectSummary(funding_code="B1"),
+ BundProjectSummary(funding_code="B2"),
+ ],
+ total=2,
+ page=0,
+ size=1000,
+ )
+
+ async def scan(**kwargs):
+ assert kwargs["index"] == str(ESIndex.PROJECTS_BUND_TOPICS)
+ mapping_ids = {
+ funding_code: hashlib.sha256(funding_code.encode("utf-8")).hexdigest()
+ for funding_code in ("B1", "B2")
+ }
+ assert kwargs["query"] == {
+ "terms": {"project_id": sorted(mapping_ids.values())}
+ }
+ for project_id, topic_id, topic_name, subfield in (
+ (mapping_ids["B1"], "T1", "Artificial Intelligence", "AI"),
+ (mapping_ids["B1"], "T2", "Robotics", "Robotics"),
+ (mapping_ids["B2"], "T1", "Artificial Intelligence", "AI"),
+ ):
+ yield {
+ "_source": {
+ "project_id": project_id,
+ "keyword": topic_name,
+ "topic_matches": [
+ {
+ "topic_id": topic_id,
+ "topic_display_name": topic_name,
+ "field": "Computer Science",
+ "subfield": subfield,
+ "domain": "Physical Sciences",
+ }
+ ],
+ }
+ }
+
+ with (
+ patch(
+ "inse.projects.service.search_bund_projects_with_filters",
+ new=AsyncMock(return_value=project_page),
+ ) as mocked_projects,
+ patch(
+ "inse.integrations.elasticsearch.scan",
+ new=scan,
+ ),
+ ):
+ result = await get_dashboard_bund_topics(
+ ORG_INSTITUTION_ID,
+ "Example Org",
+ from_year=2022,
+ to_year=2026,
+ )
+
+ project_call = mocked_projects.await_args
+ assert project_call.kwargs["active_from_year"] == 2022
+ assert project_call.kwargs["active_to_year"] == 2026
+ assert result.project_count == 2
+ assert result.matched_project_count == 2
+ assert {topic.field_project_count for topic in result.topics} == {2}
+ assert {topic.name: topic.subfield_project_count for topic in result.topics} == {
+ "Artificial Intelligence": 2,
+ "Robotics": 1,
+ }
+
+
@pytest.mark.anyio
async def test_dashboard_statistics_counts_organization_data_and_all_projects():
- async def search(**kwargs):
- index = kwargs["index"]
+ async def search(*args, **kwargs):
+ index = kwargs.get("index", args[0] if args else None)
if index == config.settings.openalex_works_search_index:
- return {"hits": {"total": {"value": 120}}}
+ return {"hits": {"total": {"value": 120}, "hits": []}}
if index == ESIndex.OPENALEX_AUTHORS:
return {"hits": {"total": {"value": 35}}}
@@ -106,9 +394,7 @@ async def test_dashboard_statistics_counts_organization_data_and_all_projects():
if index == ESIndex.DFG_INSTITUTES_V2:
if "institute_ids" in kwargs["body"].get("aggs", {}):
return {
- "aggregations": {
- "institute_ids": {"buckets": [{"key": 10210}]}
- }
+ "aggregations": {"institute_ids": {"buckets": [{"key": 10210}]}}
}
return {
"aggregations": {
@@ -128,48 +414,59 @@ async def test_dashboard_statistics_counts_organization_data_and_all_projects():
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"]),
- ), patch(
- "inse.dashboard.service.get_openalex_institution",
- new=AsyncMock(
- return_value=Institution(
- id=ORG_INSTITUTION_ID,
- display_name="Example University",
- display_name_alternatives=["Example Universität"],
- )
+ with (
+ patch(
+ "inse.integrations.elasticsearch.search",
+ new=AsyncMock(side_effect=search),
),
- ), patch(
- "inse.dashboard.service.projects_service.get_dfg_projects",
- new=AsyncMock(
- return_value=DfgProjectPage(elements=[], total=3, page=0, size=1)
+ patch(
+ "inse.institutions.institutions_search_client.InstitutionsSearchClient.get_institution_aliases_by_oa_institution_id",
+ new=AsyncMock(return_value=["Example University", "Example Uni"]),
),
- ), patch(
- "inse.dashboard.service.projects_service.search_eu_cordis_projects",
- new=AsyncMock(
- return_value=EuCordisProjectSearchPage(
- elements=[], total=10, page=0, size=1
- )
+ patch(
+ "inse.dashboard.project_status_service.get_openalex_institution",
+ new=AsyncMock(
+ return_value=Institution(
+ id=ORG_INSTITUTION_ID,
+ display_name="Example University",
+ display_name_alternatives=["Example Universität"],
+ )
+ ),
),
- ), patch(
- "inse.dashboard.service.projects_service.search_bund_projects_with_filters",
- new=AsyncMock(
- return_value=BundProjectPage(elements=[], total=5, page=0, size=1)
+ patch(
+ "inse.projects.service.get_dfg_projects",
+ new=AsyncMock(
+ return_value=DfgProjectPage(elements=[], total=3, page=0, size=1)
+ ),
),
- ), patch(
- "inse.dashboard.service.persons_service.search_persons_list",
- new=AsyncMock(
- return_value=CustomAuthorsListResponse(
- results=[], meta=Meta(count=35, page=1, per_page=1)
- )
+ patch(
+ "inse.projects.service.search_eu_cordis_projects",
+ new=AsyncMock(
+ return_value=EuCordisProjectSearchPage(
+ elements=[], total=10, page=0, size=1
+ )
+ ),
+ ),
+ patch(
+ "inse.projects.service.search_bund_projects_with_filters",
+ new=AsyncMock(
+ return_value=BundProjectPage(elements=[], total=5, page=0, size=1)
+ ),
+ ),
+ patch(
+ "inse.dashboard.service.persons_service.search_persons_list",
+ new=AsyncMock(
+ return_value=CustomAuthorsListResponse(
+ results=[], meta=Meta(count=35, page=1, per_page=1)
+ )
+ ),
+ ),
+ patch(
+ "inse.dashboard.service.institutions_v2_service.get_institution_by_id_or_raise",
+ new=AsyncMock(
+ return_value=Institution(id=ORG_INSTITUTION_ID, works_count=120)
+ ),
),
- ), patch(
- "inse.dashboard.service.institutions_v2_service.get_institution_by_id_or_raise",
- new=AsyncMock(return_value=Institution(id=ORG_INSTITUTION_ID, works_count=120)),
):
result = await get_dashboard_statistics(
ORG_INSTITUTION_ID,
@@ -187,22 +484,18 @@ async def test_dashboard_statistics_counts_organization_data_and_all_projects():
"bmbf_projects": 5,
}
-@pytest.mark.anyio
-async def test_dashboard_publications_uses_institutions_v2_counts():
- institution = Institution(
- id=ORG_INSTITUTION_ID,
- works_count=250,
- counts_by_year=[
- AuthorCountsByYearInner(year=2021, works_count=10),
- AuthorCountsByYearInner(year=2022, works_count=12),
- AuthorCountsByYearInner(year=2023, works_count=14),
- ],
- )
+@pytest.mark.anyio
+async def test_dashboard_publications_uses_institution_publications_logic():
with patch(
- "inse.dashboard.service.institutions_v2_service.get_institution_by_id_or_raise",
- new=AsyncMock(return_value=institution),
- ) as mocked_get_institution:
+ "inse.dashboard.service.works_v2_service.get_works",
+ new=AsyncMock(
+ side_effect=[
+ WorkPageV2(elements=[], total=250, page=0, size=1),
+ WorkPageV2(elements=[], total=22, page=0, size=1),
+ ]
+ ),
+ ) as mocked_get_works:
all_time = await get_dashboard_publications(
ORG_INSTITUTION_ID,
"Example Org",
@@ -216,9 +509,17 @@ async def test_dashboard_publications_uses_institutions_v2_counts():
assert all_time.value == 250
assert selected_period.value == 22
- assert mocked_get_institution.await_args_list[0].kwargs == {
- "raw_oa_institution_id": "I123",
- "source": ["id", "works_count", "counts_by_year"],
+ assert mocked_get_works.await_args_list[0].kwargs == {
+ "page": 0,
+ "size": 1,
+ "institution_ids": [ORG_INSTITUTION_ID],
+ "publication_years": [],
+ }
+ assert mocked_get_works.await_args_list[1].kwargs == {
+ "page": 0,
+ "size": 1,
+ "institution_ids": [ORG_INSTITUTION_ID],
+ "publication_years": [2021, 2022],
}
@@ -254,7 +555,7 @@ async def test_dashboard_dfg_projects_uses_projects_service_total():
project_page = DfgProjectPage(elements=[], total=42, page=0, size=1)
with patch(
- "inse.dashboard.service.projects_service.get_dfg_projects",
+ "inse.projects.service.get_dfg_projects",
new=AsyncMock(return_value=project_page),
) as mocked_get_projects:
result = await get_dashboard_dfg_projects(
@@ -268,8 +569,11 @@ async def test_dashboard_dfg_projects_uses_projects_service_total():
mocked_get_projects.assert_awaited_once()
call = mocked_get_projects.await_args
assert call.kwargs["raw_oa_institution_id"] == "I123"
- assert call.kwargs["funding_start_years"][-1] == "2022"
- assert call.kwargs["funding_end_years"][0] == "2020"
+ assert call.kwargs["funding_start_years"] is None
+ assert call.kwargs["funding_end_years"] is None
+ assert call.kwargs["active_from_year"] == 2020
+ assert call.kwargs["active_to_year"] == 2022
+ assert call.kwargs["skip_enrichment"] is True
assert call.kwargs["page"] == 0
assert call.kwargs["size"] == 1
@@ -279,7 +583,7 @@ async def test_dashboard_bmbf_projects_uses_projects_service_total():
project_page = BundProjectPage(elements=[], total=29, page=0, size=1)
with patch(
- "inse.dashboard.service.projects_service.search_bund_projects_with_filters",
+ "inse.projects.service.search_bund_projects_with_filters",
new=AsyncMock(return_value=project_page),
) as mocked_get_projects:
result = await get_dashboard_bmbf_projects(
@@ -293,20 +597,20 @@ async def test_dashboard_bmbf_projects_uses_projects_service_total():
mocked_get_projects.assert_awaited_once()
call = mocked_get_projects.await_args
assert call.kwargs["raw_oa_institution_id"] == "I123"
- assert call.kwargs["funding_start_years"][-1] == "2020"
- assert call.kwargs["funding_end_years"][0] == "2018"
+ assert call.kwargs["funding_start_years"] is None
+ assert call.kwargs["funding_end_years"] is None
+ assert call.kwargs["active_from_year"] == 2018
+ assert call.kwargs["active_to_year"] == 2020
assert call.kwargs["page"] == 0
assert call.kwargs["size"] == 1
@pytest.mark.anyio
async def test_dashboard_eu_projects_uses_projects_service_total():
- project_page = EuCordisProjectSearchPage(
- elements=[], total=37, page=0, size=1
- )
+ project_page = EuCordisProjectSearchPage(elements=[], total=37, page=0, size=1)
with patch(
- "inse.dashboard.service.projects_service.search_eu_cordis_projects",
+ "inse.projects.service.search_eu_cordis_projects",
new=AsyncMock(return_value=project_page),
) as mocked_get_projects:
result = await get_dashboard_eu_projects(
@@ -320,8 +624,10 @@ async def test_dashboard_eu_projects_uses_projects_service_total():
mocked_get_projects.assert_awaited_once()
call = mocked_get_projects.await_args
assert call.kwargs["raw_oa_institution_id"] == "I123"
- assert call.kwargs["funding_start_years"][-1] == "2021"
- assert call.kwargs["funding_end_years"][0] == "2019"
+ assert call.kwargs["funding_start_years"] is None
+ assert call.kwargs["funding_end_years"] is None
+ assert call.kwargs["active_from_year"] == 2019
+ assert call.kwargs["active_to_year"] == 2021
assert call.kwargs["project_types"] == list(EuCordisProjectType)
assert call.kwargs["page"] == 0
assert call.kwargs["size"] == 1
@@ -357,11 +663,7 @@ async def test_top_authors_maps_works_patents_news_and_eu_projects():
if kwargs["index"] == "aktuell_postproc":
return {
"aggregations": {
- "authors": {
- "buckets": [
- {"key": "Ada Example", "doc_count": 6}
- ]
- }
+ "authors": {"buckets": [{"key": "Ada Example", "doc_count": 6}]}
}
}
if kwargs["index"] == ESIndex.CORDIS_EU_PUBLICATIONS_WILDCARD:
@@ -387,9 +689,7 @@ async def test_top_authors_maps_works_patents_news_and_eu_projects():
if kwargs["index"] == ESIndex.DFG_PROJECTS:
return {
"aggregations": {
- "people": {
- "buckets": [{"key": "Grace Example", "doc_count": 3}]
- }
+ "people": {"buckets": [{"key": "Grace Example", "doc_count": 3}]}
}
}
@@ -438,13 +738,58 @@ async def test_top_authors_maps_works_patents_news_and_eu_projects():
return {"aggregations": {"people": {"buckets": []}}}
+ scan_calls = []
+
+ async def scan(**kwargs):
+ scan_calls.append(kwargs)
+ yield {
+ "_id": "W1",
+ "_source": {
+ "id": "https://openalex.org/W1",
+ "authorships": [
+ {
+ "author": {
+ "id": "https://openalex.org/A1",
+ "display_name": "Ada Example",
+ },
+ },
+ {
+ "author": {
+ "id": "https://openalex.org/A2",
+ "display_name": "Grace Example",
+ },
+ },
+ ],
+ },
+ }
+ yield {
+ "_id": "W2",
+ "_source": {
+ "id": "https://openalex.org/W2",
+ "authorships": [
+ {
+ "author": {
+ "id": "https://openalex.org/A1",
+ "display_name": "Ada Example",
+ },
+ }
+ ],
+ },
+ }
+
async def eu_projects(**kwargs):
if kwargs.get("raw_oa_institution_id"):
return EuCordisProjectSearchPage(
elements=[
- EuCordisProjectSummary(id="P1", project_type=EuCordisProjectType.FP7),
- EuCordisProjectSummary(id="P2", project_type=EuCordisProjectType.H2020),
- EuCordisProjectSummary(id="P3", project_type=EuCordisProjectType.HEU),
+ EuCordisProjectSummary(
+ id="P1", project_type=EuCordisProjectType.FP7
+ ),
+ EuCordisProjectSummary(
+ id="P2", project_type=EuCordisProjectType.H2020
+ ),
+ EuCordisProjectSummary(
+ id="P3", project_type=EuCordisProjectType.HEU
+ ),
],
total=3,
page=0,
@@ -457,21 +802,30 @@ async def test_top_authors_maps_works_patents_news_and_eu_projects():
size=1,
)
- 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.projects_service.search_eu_cordis_projects",
- new=AsyncMock(side_effect=eu_projects),
- ), patch(
- "inse.dashboard.service.OrgPatentsSearchClient.top_authors_by_institution",
- new=AsyncMock(
- return_value=[
- {"id": "A1", "name": "Ada Example", "count": 4},
- ]
+ with (
+ patch(
+ "inse.integrations.elasticsearch.search",
+ new=AsyncMock(side_effect=search),
+ ) as mocked_search,
+ patch(
+ "inse.integrations.elasticsearch.scan",
+ new=scan,
+ ),
+ patch(
+ "inse.institutions.institutions_search_client.InstitutionsSearchClient.get_institution_aliases_by_oa_institution_id",
+ new=AsyncMock(return_value=["Example University"]),
+ ),
+ patch(
+ "inse.projects.service.search_eu_cordis_projects",
+ new=AsyncMock(side_effect=eu_projects),
+ ),
+ 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(
@@ -482,7 +836,7 @@ async def test_top_authors_maps_works_patents_news_and_eu_projects():
assert result.works[0].model_dump() == {
"id": "A1",
"name": "Ada Example",
- "count": 42,
+ "count": 2,
}
assert result.patents[0].model_dump() == {
"id": "A1",
@@ -502,8 +856,7 @@ async def test_top_authors_maps_works_patents_news_and_eu_projects():
project_calls = [
call
for call in mocked_search.await_args_list
- if call.kwargs["index"]
- in {ESIndex.DFG_PROJECTS, ESIndex.PROJECTS_BUND_V1}
+ if call.kwargs["index"] in {ESIndex.DFG_PROJECTS, ESIndex.PROJECTS_BUND_V1}
]
assert project_calls == []
@@ -523,18 +876,43 @@ async def test_top_authors_maps_works_patents_news_and_eu_projects():
assert eu_body["_source"] == ["projectID", "qaProcessedDoi"]
assert "aggs" not in eu_body
- works_calls = [
+ assert len(scan_calls) == 1
+ assert scan_calls[0]["index"] == str(ESIndex.OPENALEX_WORKS_WILDCARD)
+ assert scan_calls[0]["query"]["bool"]["must"] == [
+ {
+ "nested": {
+ "path": "authorships",
+ "query": {
+ "nested": {
+ "path": "authorships.institutions",
+ "query": {
+ "terms": {
+ "authorships.institutions.id": [ORG_INSTITUTION_ID]
+ }
+ },
+ }
+ },
+ }
+ }
+ ]
+ assert scan_calls[0]["source"] == [
+ "id",
+ "authorships.author.id",
+ "authorships.author.display_name",
+ ]
+
+ eu_work_calls = [
call
for call in mocked_search.await_args_list
if call.kwargs["index"] == "openalex-works"
]
- assert len(works_calls) == 1
- works_body = works_calls[0].kwargs["body"]
- assert works_body["query"]["bool"]["filter"][0]["terms"]["doi"] == [
+ assert len(eu_work_calls) == 1
+ eu_works_body = eu_work_calls[0].kwargs["body"]
+ assert eu_works_body["query"]["bool"]["filter"][0]["terms"]["doi"] == [
"https://doi.org/10.1234/p1",
"https://doi.org/10.1234/p2",
]
- assert works_body["_source"] == [
+ assert eu_works_body["_source"] == [
"doi",
"authorships.author.id",
"authorships.author.display_name",
@@ -628,9 +1006,7 @@ async def test_top_eu_project_authors_count_filtered_projects_by_stable_author_i
}
}
if kwargs["index"] == ESIndex.CORDIS_EU_PUBLICATIONS_WILDCARD:
- assert kwargs["body"]["query"] == {
- "terms": {"projectID": ["P1", "P2"]}
- }
+ assert kwargs["body"]["query"] == {"terms": {"projectID": ["P1", "P2"]}}
return {
"hits": {
"hits": [
@@ -751,44 +1127,60 @@ async def test_top_eu_project_authors_count_filtered_projects_by_stable_author_i
return {"aggregations": {"authors": {"buckets": []}}}
async def eu_projects(**kwargs):
+ assert kwargs["funding_start_years"] is None
+ assert kwargs["funding_end_years"] is None
if kwargs.get("raw_oa_institution_id"):
+ assert kwargs["active_from_year"] is None
+ assert kwargs["active_to_year"] is None
return EuCordisProjectSearchPage(
elements=[
- EuCordisProjectSummary(id="P1", project_type=EuCordisProjectType.FP7),
- EuCordisProjectSummary(id="P2", project_type=EuCordisProjectType.H2020),
+ EuCordisProjectSummary(
+ id="P1", project_type=EuCordisProjectType.FP7
+ ),
+ EuCordisProjectSummary(
+ id="P2", project_type=EuCordisProjectType.H2020
+ ),
],
total=2,
page=0,
size=1000,
)
+ assert kwargs["active_from_year"] == 2020
+ assert kwargs["active_to_year"] == 2022
return EuCordisProjectSearchPage(
elements=[],
- total={"A1": 4, "A2": 1}[kwargs["author_id"]],
+ total={"A1": 4, "A2": 0}[kwargs["author_id"]],
page=0,
size=1,
)
- 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.projects_service.search_eu_cordis_projects",
- new=AsyncMock(side_effect=eu_projects),
- ), patch(
- "inse.dashboard.service.OrgPatentsSearchClient.top_authors_by_institution",
- new=AsyncMock(return_value=[]),
+ with (
+ patch(
+ "inse.integrations.elasticsearch.search",
+ new=AsyncMock(side_effect=search),
+ ),
+ patch(
+ "inse.institutions.institutions_search_client.InstitutionsSearchClient.get_institution_aliases_by_oa_institution_id",
+ new=AsyncMock(return_value=["Example University"]),
+ ),
+ patch(
+ "inse.projects.service.search_eu_cordis_projects",
+ new=AsyncMock(side_effect=eu_projects),
+ ),
+ patch(
+ "inse.dashboard.service.OrgPatentsSearchClient.top_authors_by_institution",
+ new=AsyncMock(return_value=[]),
+ ),
):
result = await get_top_authors(
ORG_INSTITUTION_ID,
"Example Org",
+ from_year=2020,
+ to_year=2022,
)
assert [author.model_dump() for author in result.eu_projects] == [
{"id": "A1", "name": "Ada Example", "count": 4},
- {"id": "A2", "name": "Grace Example", "count": 1},
]
@@ -813,24 +1205,39 @@ async def test_top_authors_returns_partial_response_when_one_source_fails():
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.get_eu_organization_project_contributions",
- new=AsyncMock(
- return_value=SimpleNamespace(
- elements=[
- SimpleNamespace(project_id="P1"),
+ async def scan(**kwargs):
+ yield {
+ "_id": "W1",
+ "_source": {
+ "id": "https://openalex.org/W1",
+ "authorships": [
+ {
+ "author": {
+ "id": "https://openalex.org/A1",
+ "display_name": "Ada Example",
+ }
+ }
],
- )
+ },
+ }
+
+ with (
+ patch(
+ "inse.integrations.elasticsearch.search",
+ new=AsyncMock(side_effect=search),
+ ),
+ patch(
+ "inse.integrations.elasticsearch.scan",
+ new=scan,
+ ),
+ patch(
+ "inse.institutions.institutions_search_client.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=[]),
),
- ), patch(
- "inse.dashboard.service.OrgPatentsSearchClient.top_authors_by_institution",
- new=AsyncMock(return_value=[]),
):
result = await get_top_authors(
ORG_INSTITUTION_ID,
@@ -879,18 +1286,56 @@ async def test_top_authors_can_rank_works_by_last_five_years():
}
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.get_eu_organization_project_contributions",
- new=AsyncMock(return_value=SimpleNamespace(elements=[])),
- ), patch(
- "inse.dashboard.service.OrgPatentsSearchClient.top_authors_by_institution",
- new=AsyncMock(return_value=[]),
+ scan_calls = []
+
+ async def scan(**kwargs):
+ scan_calls.append(kwargs)
+ for index in range(16):
+ yield {
+ "_id": f"W-grace-{index}",
+ "_source": {
+ "authorships": [
+ {
+ "author": {
+ "id": "https://openalex.org/A2",
+ "display_name": "Grace Example",
+ }
+ }
+ ]
+ },
+ }
+ for index in range(2):
+ yield {
+ "_id": f"W-ada-{index}",
+ "_source": {
+ "authorships": [
+ {
+ "author": {
+ "id": "https://openalex.org/A1",
+ "display_name": "Ada Example",
+ }
+ }
+ ]
+ },
+ }
+
+ with (
+ patch(
+ "inse.integrations.elasticsearch.search",
+ new=AsyncMock(side_effect=search),
+ ),
+ patch(
+ "inse.integrations.elasticsearch.scan",
+ new=scan,
+ ),
+ patch(
+ "inse.institutions.institutions_search_client.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,
@@ -909,6 +1354,16 @@ async def test_top_authors_can_rank_works_by_last_five_years():
"count": 2,
}
+ work_scan_calls = [
+ call
+ for call in scan_calls
+ if call["index"] == str(ESIndex.OPENALEX_WORKS_WILDCARD)
+ ]
+ assert len(work_scan_calls) == 1
+ assert work_scan_calls[0]["query"]["bool"]["must"][1] == {
+ "terms": {"publication_year": list(range(current_year - 4, current_year + 1))}
+ }
+
@pytest.mark.anyio
async def test_topic_heatmap_maps_field_year_counts_and_shares():
@@ -1000,7 +1455,7 @@ async def test_topic_heatmap_maps_field_year_counts_and_shares():
}
with patch(
- "inse.dashboard.service.elasticsearch.search",
+ "inse.integrations.elasticsearch.search",
new=AsyncMock(side_effect=search),
) as mocked_search:
result = await get_topic_heatmap(
@@ -1054,17 +1509,14 @@ async def test_topic_heatmap_maps_field_year_counts_and_shares():
== "topics.subfield.id"
)
assert (
- body["aggs"]["topics_nested"]["aggs"]["fields"]["aggs"]["subfields"][
- "aggs"
- ]["topics"]["terms"]["field"]
+ body["aggs"]["topics_nested"]["aggs"]["fields"]["aggs"]["subfields"]["aggs"][
+ "topics"
+ ]["terms"]["field"]
== "topics.id"
)
subfield_aggs = body["aggs"]["topics_nested"]["aggs"]["fields"]["aggs"]
assert "aggs" not in subfield_aggs["subfields"]["aggs"]["works"]
- assert (
- "aggs"
- not in subfield_aggs["subfields"]["aggs"]["topics"]["aggs"]["works"]
- )
+ assert "aggs" not in subfield_aggs["subfields"]["aggs"]["topics"]["aggs"]["works"]
@pytest.mark.anyio
@@ -1080,7 +1532,7 @@ async def test_topic_heatmap_defaults_to_all_time():
return {"hits": {"hits": []}}
with patch(
- "inse.dashboard.service.elasticsearch.search",
+ "inse.integrations.elasticsearch.search",
new=AsyncMock(side_effect=search),
) as mocked_search:
result = await get_topic_heatmap(
@@ -1116,7 +1568,7 @@ async def test_topic_word_cloud_maps_related_topics_and_excludes_selected_topic(
}
}
with patch(
- "inse.dashboard.service.elasticsearch.search",
+ "inse.integrations.elasticsearch.search",
new=AsyncMock(return_value=response),
) as mocked_search:
result = await get_topic_word_cloud(
diff --git a/service/src/main/inse/dashboard/top_authors_service.py b/service/src/main/inse/dashboard/top_authors_service.py
new file mode 100644
index 00000000..72a8c1e2
--- /dev/null
+++ b/service/src/main/inse/dashboard/top_authors_service.py
@@ -0,0 +1,1138 @@
+import asyncio
+import logging
+import re
+from collections import defaultdict
+from datetime import datetime
+from typing import Any, Literal
+
+from fastapi import HTTPException
+
+from inse import config
+from inse.exceptions import ElasticsearchException, UpstreamAPIException
+from inse.integrations import elasticsearch
+from inse.model import ESCluster, ESIndex
+from inse.patents.org.elastic_search_client import OrgPatentsSearchClient
+from inse.projects import service as projects_service
+from inse.projects.dfg_institutions.service import (
+ autocomplete_institutions_for_selector,
+)
+from inse.projects.logic import get_person_ids_by_institution_ids
+from inse.works.v2 import service as works_v2_service
+
+from .common import (
+ DashboardPeriod,
+ dashboard_period as _dashboard_period,
+ institution_works_query as _institution_works_query,
+ normalize_institution_id as _normalize_institution_id,
+ project_overlap_filter as _project_overlap_filter,
+)
+from .model import TopAuthor, TopAuthorAnalysis, TopAuthorStatistics
+from .project_ids_service import _get_eu_project_ids_from_projects_service
+
+TOP_AUTHOR_LIMIT = 10
+EU_PROJECT_COUNT_CONCURRENCY = 5
+EU_PROJECT_COUNT_MAX_ATTEMPTS = 3
+EU_PROJECT_COUNT_RETRY_DELAY_SECONDS = 0.5
+logger = logging.getLogger(__name__)
+ACADEMIC_TITLE_RE = re.compile(
+ r"^(?:(?:professor(?:in)?|prof|dr)(?:\.-[a-z]+)?\.?|rer\.|nat\.|med\.|ing\.)\s+",
+ re.IGNORECASE,
+)
+
+
+WorksPeriod = Literal["all_time", "last_5_years"]
+
+
+def _period(
+ works_period: WorksPeriod = "all_time",
+ from_year: int | None = None,
+ to_year: int | None = None,
+) -> DashboardPeriod:
+ if from_year is None and to_year is None and works_period == "last_5_years":
+ from_year = datetime.now().year - 4
+ to_year = datetime.now().year
+ return _dashboard_period(from_year, to_year)
+
+
+async def get_top_authors(
+ institution_id: str,
+ organization_name: str,
+ works_period: WorksPeriod = "all_time",
+ from_year: int | None = None,
+ to_year: int | None = None,
+) -> TopAuthorStatistics:
+ normalized_id = _normalize_institution_id(institution_id)
+ period = _period(works_period, from_year, to_year)
+ authors = await _safe_institution_authors(normalized_id)
+
+ works = await _safe_top_authors("works", _top_work_authors(normalized_id, period))
+ projects = await _safe_top_authors(
+ "projects",
+ _top_project_authors(
+ authors=authors,
+ organization_name=organization_name,
+ from_year=period[0],
+ to_year=period[1],
+ ),
+ )
+ eu_projects = await _safe_top_authors(
+ "eu_projects",
+ _top_eu_project_publication_authors(
+ normalized_id,
+ authors,
+ from_year=period[0],
+ to_year=period[1],
+ ),
+ )
+ patents = await _safe_top_authors(
+ "patents",
+ _top_patent_authors(
+ normalized_id,
+ from_year=period[0],
+ to_year=period[1],
+ ),
+ )
+ news = await _safe_top_authors(
+ "news",
+ _top_news_authors(
+ authors,
+ from_year=period[0],
+ to_year=period[1],
+ ),
+ )
+
+ return TopAuthorStatistics(
+ institution_id=normalized_id,
+ works=works,
+ projects=projects,
+ eu_projects=eu_projects,
+ patents=patents,
+ news=news,
+ )
+
+
+async def get_top_work_authors(
+ institution_id: str,
+ works_period: WorksPeriod = "all_time",
+ from_year: int | None = None,
+ to_year: int | None = None,
+) -> TopAuthorAnalysis:
+ normalized_id = _normalize_institution_id(institution_id)
+ return TopAuthorAnalysis(
+ institution_id=normalized_id,
+ authors=await _top_work_authors(
+ normalized_id, _period(works_period, from_year, to_year)
+ ),
+ )
+
+
+async def get_top_project_authors(
+ institution_id: str,
+ organization_name: str,
+ from_year: int | None = None,
+ to_year: int | None = None,
+) -> TopAuthorAnalysis:
+ normalized_id = _normalize_institution_id(institution_id)
+ period = _period(from_year=from_year, to_year=to_year)
+ return TopAuthorAnalysis(
+ institution_id=normalized_id,
+ authors=await _top_project_authors(
+ authors=await _safe_institution_authors(normalized_id),
+ organization_name=organization_name,
+ from_year=period[0],
+ to_year=period[1],
+ ),
+ )
+
+
+async def get_top_eu_project_authors(
+ institution_id: str,
+ from_year: int | None = None,
+ to_year: int | None = None,
+) -> TopAuthorAnalysis:
+ normalized_id = _normalize_institution_id(institution_id)
+ period = _period(from_year=from_year, to_year=to_year)
+ authors = await _safe_institution_authors(normalized_id)
+ return TopAuthorAnalysis(
+ institution_id=normalized_id,
+ authors=await _top_eu_project_publication_authors(
+ normalized_id,
+ authors,
+ from_year=period[0],
+ to_year=period[1],
+ ),
+ )
+
+
+async def get_top_patent_authors(
+ institution_id: str,
+ from_year: int | None = None,
+ to_year: int | None = None,
+) -> TopAuthorAnalysis:
+ normalized_id = _normalize_institution_id(institution_id)
+ period = _period(from_year=from_year, to_year=to_year)
+ return TopAuthorAnalysis(
+ institution_id=normalized_id,
+ authors=await _top_patent_authors(
+ normalized_id,
+ from_year=period[0],
+ to_year=period[1],
+ ),
+ )
+
+
+async def get_top_news_authors(
+ institution_id: str,
+ from_year: int | None = None,
+ to_year: int | None = None,
+) -> TopAuthorAnalysis:
+ normalized_id = _normalize_institution_id(institution_id)
+ period = _period(from_year=from_year, to_year=to_year)
+ return TopAuthorAnalysis(
+ institution_id=normalized_id,
+ authors=await _top_news_authors(
+ await _safe_institution_authors(normalized_id),
+ from_year=period[0],
+ to_year=period[1],
+ ),
+ )
+
+
+def _normalize_person_name(name: str) -> str:
+ normalized = " ".join(name.strip().casefold().split())
+ while True:
+ without_title = ACADEMIC_TITLE_RE.sub("", normalized).strip()
+ if without_title == normalized:
+ return without_title
+ normalized = without_title
+
+
+def _is_initial_surname_match(full_name: str, initial_name: str) -> bool:
+ full_parts = _normalize_person_name(full_name).split()
+ initial_parts = _normalize_person_name(initial_name).replace(".", "").split()
+ if len(full_parts) < 2 or len(initial_parts) < 2:
+ return False
+ return (
+ len(initial_parts[0]) == 1
+ and full_parts[0].startswith(initial_parts[0])
+ and full_parts[-1] == initial_parts[-1]
+ )
+
+
+def _is_supported_name_variant(full_name: str, candidate_name: str) -> bool:
+ return _normalize_person_name(full_name) == _normalize_person_name(
+ candidate_name
+ ) or _is_initial_surname_match(full_name, candidate_name)
+
+
+def _dashboard_publication_years(period: DashboardPeriod) -> list[int] | None:
+ from_year, to_year = period
+ if from_year is None and to_year is None:
+ return None
+ return list(range(from_year or 1900, (to_year or 2100) + 1))
+
+
+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 _short_author_id(value: str) -> str:
+ return value.replace("https://openalex.org/", "").strip().upper()
+
+
+async def _top_work_authors(
+ institution_id: str,
+ period: DashboardPeriod,
+) -> list[TopAuthor]:
+ must = [works_v2_service._institutions_nested_query([institution_id])]
+ if publication_years := _dashboard_publication_years(period):
+ must.append({"terms": {"publication_year": publication_years}})
+
+ author_counts: dict[str, int] = defaultdict(int)
+ author_names: dict[str, str] = {}
+ async for hit in elasticsearch.scan(
+ index=str(ESIndex.OPENALEX_WORKS_WILDCARD),
+ query={"bool": {"must": must}},
+ source=["id", "authorships.author.id", "authorships.author.display_name"],
+ page_size=1000,
+ cluster=ESCluster.NES,
+ ):
+ hit_author_ids: set[str] = set()
+ for authorship in hit.get("_source", {}).get("authorships", []):
+ author = authorship.get("author") or {}
+ author_id = author.get("id")
+ if not author_id:
+ continue
+ author_id = str(author_id)
+ hit_author_ids.add(author_id)
+ if author.get("display_name"):
+ author_names.setdefault(author_id, str(author["display_name"]))
+ for author_id in hit_author_ids:
+ author_counts[author_id] += 1
+
+ ranked_authors = sorted(
+ (
+ {
+ "id": author_id,
+ "name": author_names.get(author_id, author_id),
+ "count": count,
+ }
+ for author_id, count in author_counts.items()
+ ),
+ key=lambda author: author["count"],
+ reverse=True,
+ )
+ return [
+ TopAuthor(
+ id=_short_author_id(author["id"]),
+ name=author["name"],
+ count=author["count"],
+ )
+ for author in ranked_authors[:TOP_AUTHOR_LIMIT]
+ if author["count"] > 0
+ ]
+
+
+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 _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]],
+ organization_name: str,
+ from_year: int | None = None,
+ to_year: int | None = None,
+) -> list[TopAuthor]:
+ period = _dashboard_period(from_year, to_year)
+ institution_ids = await _dfg_institution_ids_for_organization(
+ organization_name=organization_name,
+ )
+
+ logger.info(
+ "DFG institution IDs for %s: %s",
+ organization_name,
+ institution_ids,
+ )
+
+ if not institution_ids:
+ logger.warning(
+ "No DFG institution IDs found for organization %s.",
+ organization_name,
+ )
+ return []
+
+ selected_person_ids = set(
+ await get_person_ids_by_institution_ids(institution_ids=institution_ids)
+ )
+
+ logger.info(
+ "Found %s DFG persons for organization %s.",
+ len(selected_person_ids),
+ organization_name,
+ )
+
+ if not selected_person_ids:
+ return []
+
+ project_ids_by_person: dict[int, set[str]] = {}
+ names: dict[int, str] = {}
+
+ page = 0
+ size = 10000
+ processed = 0
+
+ while True:
+ project_hits, total = await _dfg_project_author_hits(
+ page=page,
+ size=size,
+ person_ids=selected_person_ids,
+ period=period,
+ )
+
+ if not project_hits:
+ break
+
+ for project in project_hits:
+ project_id = _dfg_project_id(project)
+ if not project_id:
+ continue
+
+ persons = project.get("persons", [])
+ if not isinstance(persons, list):
+ continue
+
+ for person in persons:
+ if not isinstance(person, dict):
+ continue
+
+ person_id = person.get("person_id")
+ full_name = person.get("full_name")
+ if person_id is None or not full_name:
+ continue
+
+ try:
+ normalized_person_id = int(person_id)
+ except (TypeError, ValueError):
+ continue
+
+ if normalized_person_id not in selected_person_ids:
+ continue
+
+ project_ids_by_person.setdefault(normalized_person_id, set()).add(
+ project_id
+ )
+ names[normalized_person_id] = str(full_name).strip()
+
+ processed += len(project_hits)
+ if processed >= total:
+ break
+
+ page += 1
+
+ institution_authors: dict[str, list[dict[str, Any]]] = {}
+ for author in authors:
+ if author.get("name"):
+ institution_authors.setdefault(
+ _normalize_person_name(author["name"]),
+ [],
+ ).append(author)
+
+ ranked = sorted(
+ (
+ (person_id, project_ids)
+ for person_id, project_ids in project_ids_by_person.items()
+ if project_ids and names.get(person_id)
+ ),
+ key=lambda item: (
+ -len(item[1]),
+ names[item[0]].casefold(),
+ ),
+ )
+
+ ranked_person_ids = [person_id for person_id, _ in ranked[:TOP_AUTHOR_LIMIT]]
+ dfg_orcids = await _dfg_person_orcids(ranked_person_ids)
+
+ result: list[TopAuthor] = []
+
+ for person_id, project_ids in ranked[:TOP_AUTHOR_LIMIT]:
+ dfg_name = names[person_id]
+ matched_author = _single_author_match(
+ institution_authors.get(_normalize_person_name(dfg_name), [])
+ )
+
+ if matched_author is None and (orcid := dfg_orcids.get(person_id)):
+ matched_author = await _openalex_author_by_orcid(orcid)
+
+ if matched_author is None:
+ matched_author = await _openalex_author_by_dfg_publication_evidence(
+ dfg_name=dfg_name,
+ project_ids=project_ids,
+ )
+
+ if matched_author is None:
+ logger.info(
+ "No exact OpenAlex match for DFG author '%s' (person_id=%s).",
+ dfg_name,
+ person_id,
+ )
+
+ result.append(
+ TopAuthor(
+ id=(_short_author_id(matched_author["id"]) if matched_author else None),
+ name=matched_author["name"] if matched_author else dfg_name,
+ count=len(project_ids),
+ )
+ )
+
+ logger.info(
+ "DFG top authors for %s: %s",
+ organization_name,
+ [
+ {
+ "name": author.name,
+ "count": author.count,
+ "id": author.id,
+ }
+ for author in result
+ ],
+ )
+
+ return result
+
+
+def _single_author_match(authors: list[dict[str, Any]]) -> dict[str, Any] | None:
+ return authors[0] if len(authors) == 1 else None
+
+
+async def _dfg_person_orcids(person_ids: list[int]) -> dict[int, str]:
+ if not person_ids:
+ return {}
+
+ try:
+ response = await elasticsearch.search(
+ index=ESIndex.DFG_PERSONS,
+ body={
+ "size": len(person_ids),
+ "_source": ["person_id", "orcid_id"],
+ "query": {"terms": {"person_id": person_ids}},
+ },
+ cluster=ESCluster.INSE,
+ )
+ except Exception:
+ logger.exception("Could not load DFG ORCIDs for top project authors.")
+ return {}
+
+ result: dict[int, str] = {}
+ for hit in response.get("hits", {}).get("hits", []):
+ source = hit.get("_source", {})
+ person_id = source.get("person_id")
+ orcid = source.get("orcid_id")
+ if person_id is None or not orcid:
+ continue
+ try:
+ result[int(person_id)] = str(orcid)
+ except (TypeError, ValueError):
+ continue
+ return result
+
+
+async def _openalex_author_by_orcid(orcid: str) -> dict[str, Any] | None:
+ normalized_orcid = orcid.replace("https://orcid.org/", "").strip()
+ if not normalized_orcid:
+ return None
+
+ prefixed_orcid = f"https://orcid.org/{normalized_orcid}"
+ try:
+ response = await elasticsearch.search(
+ index=ESIndex.OPENALEX_AUTHORS,
+ body={
+ "size": 2,
+ "_source": ["id", "display_name"],
+ "query": {
+ "bool": {
+ "should": [
+ {"term": {"orcid.keyword": normalized_orcid}},
+ {"term": {"orcid.keyword": prefixed_orcid}},
+ {"term": {"ids.orcid.keyword": normalized_orcid}},
+ {"term": {"ids.orcid.keyword": prefixed_orcid}},
+ {"term": {"orcid": normalized_orcid}},
+ {"term": {"orcid": prefixed_orcid}},
+ {"term": {"ids.orcid": normalized_orcid}},
+ {"term": {"ids.orcid": prefixed_orcid}},
+ ],
+ "minimum_should_match": 1,
+ }
+ },
+ },
+ cluster=ESCluster.NES,
+ track_total_hits=True,
+ )
+ except Exception:
+ logger.exception("Could not resolve OpenAlex author by ORCID %s.", orcid)
+ return None
+
+ hits = response.get("hits", {}).get("hits", [])
+ if len(hits) != 1:
+ logger.info(
+ "OpenAlex ORCID lookup for %s returned %s hits.",
+ orcid,
+ len(hits),
+ )
+ return None
+
+ source = hits[0].get("_source", {})
+ if not source.get("id") or not source.get("display_name"):
+ return None
+ return {
+ "id": str(source["id"]),
+ "name": str(source["display_name"]),
+ }
+
+
+async def _openalex_author_by_dfg_publication_evidence(
+ dfg_name: str,
+ project_ids: set[str],
+) -> dict[str, Any] | None:
+ dois = await _dfg_project_publication_dois(project_ids)
+ if not dois:
+ return None
+
+ try:
+ response = await elasticsearch.search(
+ index=config.settings.openalex_works_search_index,
+ body={
+ "size": 10000,
+ "_source": [
+ "doi",
+ "authorships.author.id",
+ "authorships.author.display_name",
+ ],
+ "query": {"terms": {"doi": sorted(_doi_variants(dois))}},
+ },
+ cluster=ESCluster.NES,
+ )
+ except Exception:
+ logger.exception(
+ "Could not resolve OpenAlex author from DFG publication DOIs for %s.",
+ dfg_name,
+ )
+ return None
+
+ candidates: dict[str, dict[str, Any]] = {}
+ for hit in response.get("hits", {}).get("hits", []):
+ source = hit.get("_source", {})
+ doi = source.get("doi")
+ if not doi:
+ continue
+ for authorship in source.get("authorships", []) or []:
+ author = (
+ authorship.get("author", {}) if isinstance(authorship, dict) else {}
+ )
+ author_id = author.get("id")
+ display_name = author.get("display_name")
+ if not author_id or not display_name:
+ continue
+ if not _is_supported_name_variant(dfg_name, str(display_name)):
+ continue
+ candidate = candidates.setdefault(
+ str(author_id),
+ {
+ "id": str(author_id),
+ "name": str(display_name),
+ "dois": set(),
+ },
+ )
+ candidate["dois"].add(str(doi))
+
+ supported_candidates = [
+ candidate for candidate in candidates.values() if len(candidate["dois"]) >= 2
+ ]
+ if len(supported_candidates) != 1:
+ if supported_candidates:
+ logger.info(
+ "DFG publication DOI lookup for %s returned %s candidates.",
+ dfg_name,
+ len(supported_candidates),
+ )
+ return None
+
+ candidate = supported_candidates[0]
+ return {
+ "id": candidate["id"],
+ "name": candidate["name"],
+ }
+
+
+async def _dfg_project_publication_dois(project_ids: set[str]) -> set[str]:
+ if not project_ids:
+ return set()
+
+ numeric_project_ids = [
+ int(project_id) for project_id in project_ids if str(project_id).isdigit()
+ ]
+ if not numeric_project_ids:
+ return set()
+
+ try:
+ response = await elasticsearch.search(
+ index=ESIndex.DFG_PROJECTS,
+ body={
+ "size": len(numeric_project_ids),
+ "_source": ["publications.doi"],
+ "query": {"terms": {"id": numeric_project_ids}},
+ },
+ cluster=ESCluster.INSE,
+ )
+ except Exception:
+ logger.exception("Could not load DFG publication DOIs.")
+ return set()
+
+ dois: set[str] = set()
+ for hit in response.get("hits", {}).get("hits", []):
+ for publication in hit.get("_source", {}).get("publications", []) or []:
+ doi = publication.get("doi") if isinstance(publication, dict) else None
+ if doi:
+ dois.add(str(doi).strip())
+ return {doi for doi in dois if doi}
+
+
+def _doi_variants(dois: set[str]) -> set[str]:
+ variants: set[str] = set()
+ for doi in dois:
+ normalized = doi.strip()
+ if not normalized:
+ continue
+ raw = normalized
+ for prefix in ("https://doi.org/", "http://dx.doi.org/"):
+ if raw.casefold().startswith(prefix):
+ raw = raw[len(prefix) :]
+ break
+ variants.update(
+ {
+ normalized,
+ normalized.lower(),
+ f"https://doi.org/{raw}",
+ f"https://doi.org/{raw.lower()}",
+ }
+ )
+ return variants
+
+
+async def _dfg_institution_ids_for_organization(organization_name: str) -> list[int]:
+ page = await autocomplete_institutions_for_selector(
+ query=organization_name,
+ page=0,
+ size=10000,
+ )
+ return [
+ institution.id for institution in page.elements if institution.id is not None
+ ]
+
+
+async def _dfg_project_author_hits(
+ page: int,
+ size: int,
+ person_ids: set[int],
+ period: DashboardPeriod = (None, None),
+) -> tuple[list[dict[str, Any]], int]:
+ person_query = {
+ "nested": {
+ "path": "persons",
+ "query": {"terms": {"persons.person_id": sorted(person_ids)}},
+ },
+ }
+ period_filter = _project_overlap_filter(
+ "funding_start",
+ "funding_end",
+ period,
+ missing_end_is_ongoing=True,
+ )
+ query = (
+ {"bool": {"filter": [person_query, period_filter]}}
+ if period_filter
+ else person_query
+ )
+ response = await elasticsearch.search(
+ index=ESIndex.DFG_PROJECTS,
+ body={
+ "size": size,
+ "from": page * size,
+ "_source": [
+ "id",
+ "project_id",
+ "persons",
+ ],
+ "query": query,
+ "sort": [
+ {
+ "id": {
+ "order": "asc",
+ "missing": "_last",
+ }
+ }
+ ],
+ },
+ cluster=ESCluster.INSE,
+ track_total_hits=True,
+ )
+
+ hits_block = response.get("hits", {})
+ total_value = hits_block.get("total", 0)
+
+ if isinstance(total_value, dict):
+ total = int(total_value.get("value", 0))
+ else:
+ total = int(total_value or 0)
+
+ hits = [
+ hit.get("_source", {})
+ for hit in hits_block.get("hits", [])
+ if isinstance(hit.get("_source"), dict)
+ ]
+
+ logger.info(
+ "Loaded %s of %s matching DFG projects on page %s.",
+ len(hits),
+ total,
+ page,
+ )
+
+ return hits, total
+
+
+def _dfg_project_id(project: dict[str, Any]) -> str | None:
+ project_id = project.get("id")
+ if project_id is None:
+ project_id = project.get("project_id")
+ return str(project_id) if project_id is not None else None
+
+
+async def _top_patent_authors(
+ institution_id: str,
+ from_year: int | None = None,
+ to_year: int | None = None,
+) -> list[TopAuthor]:
+ client = OrgPatentsSearchClient()
+ authors = await client.top_authors_by_institution(
+ institution_id=institution_id,
+ size=TOP_AUTHOR_LIMIT,
+ from_year=from_year,
+ to_year=to_year,
+ )
+ return [
+ TopAuthor(
+ id=_short_author_id(author["id"]),
+ name=author["name"],
+ count=author["count"],
+ )
+ for author in authors
+ ]
+
+
+async def _top_eu_project_publication_authors(
+ institution_id: str,
+ institution_authors: list[dict[str, Any]],
+ from_year: int | None = None,
+ to_year: int | None = None,
+) -> list[TopAuthor]:
+ institution_author_ids = {
+ author_id
+ for author in institution_authors
+ if (author_id := _normalize_author_id(author.get("id")))
+ }
+ if not institution_author_ids:
+ return []
+
+ # Candidate discovery is deliberately all-time. The selected period is
+ # applied to each person's authoritative project count below. Otherwise a
+ # person can disappear merely because their recent projects have no linked
+ # CORDIS publication/DOI, despite having projects in the selected period.
+ project_ids = await _get_eu_project_ids_from_projects_service(institution_id)
+
+ if not project_ids:
+ return []
+
+ publication_response = await elasticsearch.search(
+ index=ESIndex.CORDIS_EU_PUBLICATIONS_WILDCARD,
+ body={
+ "size": 10000,
+ "_source": ["projectID", "qaProcessedDoi"],
+ "query": {"terms": {"projectID": project_ids}},
+ },
+ cluster=ESCluster.INSE,
+ )
+
+ doi_project_ids = _cordis_publication_doi_project_ids(
+ publication_response,
+ set(project_ids),
+ )
+ if not doi_project_ids:
+ return []
+
+ works_response = await elasticsearch.search(
+ index="openalex-works",
+ body={
+ "size": 10000,
+ "_source": [
+ "doi",
+ "authorships.author.id",
+ "authorships.author.display_name",
+ "authorships.institutions.id",
+ ],
+ "query": {
+ "bool": {
+ "filter": [
+ {"terms": {"doi": sorted(doi_project_ids)}},
+ _institution_works_query(institution_id),
+ ]
+ }
+ },
+ },
+ cluster=ESCluster.NES,
+ )
+
+ candidates = _openalex_work_authors_by_eu_projects(
+ works_response,
+ doi_project_ids,
+ institution_id,
+ institution_author_ids,
+ limit=None,
+ )
+ ranked = await _count_eu_projects_for_candidates(
+ candidates,
+ from_year=from_year,
+ to_year=to_year,
+ )
+ ranked = [author for author in ranked if author.count > 0]
+ ranked.sort(key=lambda author: (-author.count, author.name, author.id or ""))
+ return ranked[:TOP_AUTHOR_LIMIT]
+
+
+async def _count_eu_projects_for_candidates(
+ candidates: list[TopAuthor],
+ from_year: int | None = None,
+ to_year: int | None = None,
+) -> list[TopAuthor]:
+ semaphore = asyncio.Semaphore(EU_PROJECT_COUNT_CONCURRENCY)
+
+ async def load(candidate: TopAuthor) -> TopAuthor | None:
+ if not candidate.id:
+ return None
+
+ for attempt in range(1, EU_PROJECT_COUNT_MAX_ATTEMPTS + 1):
+ try:
+ async with semaphore:
+ count = await _person_eu_project_count(
+ candidate.id,
+ from_year=from_year,
+ to_year=to_year,
+ )
+ return TopAuthor(id=candidate.id, name=candidate.name, count=count)
+ except (ElasticsearchException, UpstreamAPIException, HTTPException) as exc:
+ is_retryable = (
+ not isinstance(exc, (HTTPException, UpstreamAPIException))
+ or exc.status_code >= 500
+ )
+ if not is_retryable or attempt == EU_PROJECT_COUNT_MAX_ATTEMPTS:
+ logger.warning(
+ "Could not load EU project count for author %s after %s attempt(s).",
+ candidate.id,
+ attempt,
+ exc_info=True,
+ )
+ return None
+ await asyncio.sleep(EU_PROJECT_COUNT_RETRY_DELAY_SECONDS * attempt)
+
+ return None
+
+ results = await asyncio.gather(*(load(candidate) for candidate in candidates))
+ return [result for result in results if result is not None]
+
+
+def _cordis_publication_doi_project_ids(
+ response: dict[str, Any],
+ allowed_project_ids: set[str],
+) -> dict[str, set[str]]:
+ doi_project_ids: dict[str, set[str]] = defaultdict(set)
+ for hit in response.get("hits", {}).get("hits", []):
+ source = hit.get("_source", {})
+ project_id = str(source.get("projectID") or "").strip()
+ if not project_id or project_id not in allowed_project_ids:
+ continue
+ doi = _normalize_doi(source.get("qaProcessedDoi"))
+ if doi:
+ doi_project_ids[doi].add(project_id)
+ return dict(doi_project_ids)
+
+
+def _normalize_doi(value: Any) -> str | None:
+ if not isinstance(value, str) or not value.strip():
+ return None
+ doi = value.strip().lower()
+ if doi.startswith("https://doi.org/"):
+ return doi
+ if doi.startswith("http://doi.org/"):
+ return "https://" + doi.removeprefix("http://")
+ if doi.startswith("doi.org/"):
+ return f"https://{doi}"
+ return f"https://doi.org/{doi}"
+
+
+def _openalex_work_authors_by_eu_projects(
+ response: dict[str, Any],
+ doi_project_ids: dict[str, set[str]],
+ institution_id: str,
+ institution_author_ids: set[str],
+ limit: int | None = TOP_AUTHOR_LIMIT,
+) -> list[TopAuthor]:
+ # Count unique CORDIS projects per author, not publications. Multiple works
+ # (and therefore multiple DOIs) can belong to the same project ID.
+ author_project_ids: dict[str, set[str]] = defaultdict(set)
+ author_names: dict[str, str] = {}
+
+ for hit in response.get("hits", {}).get("hits", []):
+ source = hit.get("_source", {})
+ project_ids = doi_project_ids.get(_normalize_doi(source.get("doi")) or "")
+ if not project_ids:
+ continue
+
+ for authorship in source.get("authorships") or []:
+ if not any(
+ institution.get("id") == institution_id
+ for institution in authorship.get("institutions") or []
+ ):
+ continue
+ author = authorship.get("author") or {}
+ author_id = _normalize_author_id(author.get("id"))
+ author_name = str(author.get("display_name") or "").strip()
+ if (
+ not author_id
+ or author_id not in institution_author_ids
+ or not author_name
+ ):
+ continue
+ author_project_ids[author_id].update(project_ids)
+ author_names.setdefault(author_id, author_name)
+
+ ranked_authors = sorted(
+ author_project_ids.items(),
+ key=lambda item: (-len(item[1]), author_names.get(item[0], ""), item[0]),
+ )
+
+ authors = [
+ TopAuthor(
+ id=_short_author_id(author_id),
+ name=author_names[author_id],
+ count=len(project_ids),
+ )
+ for author_id, project_ids in ranked_authors
+ ]
+ return authors[:limit] if limit is not None else authors
+
+
+async def _person_eu_project_count(
+ author_id: str,
+ from_year: int | None = None,
+ to_year: int | None = None,
+) -> int:
+ """Returns the same filtered EU project total as the person projects tab."""
+ period = _dashboard_period(from_year, to_year)
+ projects = await projects_service.search_eu_cordis_projects(
+ page=0,
+ size=1,
+ project_types=None,
+ raw_oa_institution_id=None,
+ institutions_search_client=None,
+ author_id=_short_author_id(author_id),
+ author_ids=None,
+ organization_ids=None,
+ organization_names=None,
+ keywords=None,
+ topic_ids=None,
+ filter_topic_ids=None,
+ title=None,
+ funding_start_years=None,
+ funding_end_years=None,
+ active_from_year=period[0],
+ active_to_year=period[1],
+ countries=None,
+ framework_programmes=None,
+ funding_schemes=None,
+ statuses=None,
+ sort_by="title",
+ sort_direction="asc",
+ fuzzy=False,
+ skip_enrichment=True,
+ )
+ return projects.total
+
+
+def _normalize_author_id(value: Any) -> str | None:
+ if not isinstance(value, str) or not value.strip():
+ return None
+ short_id = value.replace("https://openalex.org/", "").strip().upper()
+ return f"https://openalex.org/{short_id}"
+
+
+async def _top_news_authors(
+ authors: list[dict[str, Any]],
+ from_year: int | None = None,
+ to_year: int | None = None,
+) -> list[TopAuthor]:
+ if not authors:
+ return []
+
+ period = _dashboard_period(from_year, to_year)
+ author_names = [author["name"] for author in authors]
+ filters: list[dict[str, Any]] = [{"terms": {"authors.keyword": author_names}}]
+ if period != (None, None):
+ date_range: dict[str, int] = {}
+ if period[0] is not None:
+ date_range["gte"] = period[0]
+ if period[1] is not None:
+ date_range["lte"] = period[1]
+ news_ids = [
+ str(hit["_id"])
+ async for hit in elasticsearch.scan(
+ index=str(ESIndex.AKTUELLES),
+ query={"range": {"date_year": date_range}},
+ source=False,
+ page_size=1000,
+ cluster=ESCluster.INSE,
+ )
+ if hit.get("_id")
+ ]
+ if not news_ids:
+ return []
+ filters.append({"terms": {"news_id.keyword": news_ids}})
+
+ response = await elasticsearch.search(
+ index="aktuell_postproc",
+ body={
+ "size": 0,
+ "query": (
+ filters[0] if len(filters) == 1 else {"bool": {"filter": filters}}
+ ),
+ "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]
diff --git a/service/src/main/inse/database.py b/service/src/main/inse/database.py
index 4fd5a269..5f4a75c9 100644
--- a/service/src/main/inse/database.py
+++ b/service/src/main/inse/database.py
@@ -107,6 +107,30 @@ def create_db_and_tables():
)
)
+ # Preserve the former single institution as the first manually selected
+ # institution.
+ # The legacy column remains synchronized for portal sections that have not yet
+ # been migrated to organization-wide institution lists.
+ with engine.begin() as connection:
+ connection.execute(
+ text(
+ """
+ INSERT INTO organization_institution (
+ organization_id, openalex_institution_id, position
+ )
+ SELECT id, openalex_institution_id, 0
+ FROM organization
+ WHERE openalex_institution_id IS NOT NULL
+ AND TRIM(openalex_institution_id) != ''
+ AND NOT EXISTS (
+ SELECT 1
+ FROM organization_institution oi
+ WHERE oi.organization_id = organization.id
+ )
+ """
+ )
+ )
+
def get_session():
"""Yields a database session for use in FastAPI endpoints.
diff --git a/service/src/main/inse/model.py b/service/src/main/inse/model.py
index 83c064c3..882338ad 100644
--- a/service/src/main/inse/model.py
+++ b/service/src/main/inse/model.py
@@ -52,6 +52,9 @@ class ESIndex(StrEnum):
OPENALEX_CONTINENTS = "openalex-continents"
OPENALEX_TOPICS = "openalex-topics"
OPENALEX_TOPIC_VECTORS = "topicvectors"
+ OPENALEX_DOMAINS = "openalex-domains"
+ OPENALEX_FIELDS = "openalex-fields"
+ OPENALEX_SUBFIELDS = "openalex-subfields"
EPO_INDEX = "epo_index_1.0"
USPTO_INDEX = "uspto_patents_3.0"
diff --git a/service/src/main/inse/organization_management/model.py b/service/src/main/inse/organization_management/model.py
index 8357daa9..e4de2f2e 100644
--- a/service/src/main/inse/organization_management/model.py
+++ b/service/src/main/inse/organization_management/model.py
@@ -1,4 +1,5 @@
import uuid
+from typing import Literal
from pydantic import BaseModel, Field
@@ -7,6 +8,7 @@ class OrganizationProfile(BaseModel):
id: uuid.UUID
name: str
other_inst_id: str | None = None
+ selected_openalex_institution_ids: list[str] = Field(default_factory=list)
deleted: bool
member_count: int
@@ -21,9 +23,25 @@ class OrganizationPage(BaseModel):
class CreateOrganizationRequest(BaseModel):
name: str = Field(min_length=1)
other_inst_id: str | None = None
+ selected_openalex_institution_ids: list[str] | None = None
class UpdateOrganizationRequest(BaseModel):
name: str | None = Field(default=None, min_length=1)
other_inst_id: str | None = None
+ selected_openalex_institution_ids: list[str] | None = None
deleted: bool | None = None
+
+
+class InstitutionAssociation(BaseModel):
+ id: str
+ display_name: str
+ relationship: Literal["child", "related"]
+
+
+class InstitutionAssociationsResponse(BaseModel):
+ id: str
+ display_name: str
+ associated_institutions: list[InstitutionAssociation] = Field(
+ default_factory=list
+ )
diff --git a/service/src/main/inse/organization_management/router.py b/service/src/main/inse/organization_management/router.py
index 5232ca66..32086e0e 100644
--- a/service/src/main/inse/organization_management/router.py
+++ b/service/src/main/inse/organization_management/router.py
@@ -11,6 +11,7 @@ from inse.tags import Tags
from . import service
from .model import (
CreateOrganizationRequest,
+ InstitutionAssociationsResponse,
OrganizationPage,
OrganizationProfile,
UpdateOrganizationRequest,
@@ -19,6 +20,18 @@ from .model import (
router = APIRouter(prefix="/api/organizations", tags=[Tags.ORGANIZATION])
+@router.get(
+ "/institutions/associations",
+ operation_id="getOrganizationInstitutionAssociations",
+ response_model=list[InstitutionAssociationsResponse],
+)
+async def get_organization_institution_associations(
+ institution_ids: list[str] = Query(),
+ access_token: AccessTokenMetadata = auth_service.CurrentUserAccessTokenPayloadDep,
+) -> list[InstitutionAssociationsResponse]:
+ return await service.get_institution_associations(access_token, institution_ids)
+
+
@router.get("", operation_id="getOrganisations", response_model=OrganizationPage)
async def get_organizations(
page: int = Query(default=0, ge=0),
diff --git a/service/src/main/inse/organization_management/service.py b/service/src/main/inse/organization_management/service.py
index dcb06c30..072db92a 100644
--- a/service/src/main/inse/organization_management/service.py
+++ b/service/src/main/inse/organization_management/service.py
@@ -1,18 +1,43 @@
+import logging
+import re
import uuid
from fastapi import HTTPException, status
from sqlmodel import Session, func, select
-from inse.auth.model import AccessTokenMetadata, Account, Organization, UserRole
+from inse.auth.model import (
+ AccessTokenMetadata,
+ Account,
+ Organization,
+ OrganizationInstitution,
+ UserRole,
+)
+from inse.integrations import elasticsearch
+from inse.model import ESIndex
from .model import (
CreateOrganizationRequest,
+ InstitutionAssociation,
+ InstitutionAssociationsResponse,
OrganizationPage,
OrganizationProfile,
UpdateOrganizationRequest,
)
+logger = logging.getLogger(__name__)
+OPENALEX_INSTITUTION_ID_PATTERN = re.compile(
+ r"^(?:https?://openalex\.org/)?(I\d+)/?$", re.IGNORECASE
+)
+KNOWN_ASSOCIATION_TYPES = {
+ "parent",
+ "child",
+ "related",
+ "predecessor",
+ "successor",
+}
+
+
def _require_super_admin(access_token: AccessTokenMetadata) -> None:
if access_token.effective_role != UserRole.SUPER_ADMIN:
raise HTTPException(
@@ -31,6 +56,27 @@ def _normalize_name(name: str) -> str:
return normalized_name
+def _normalize_institution_id(institution_id: str) -> str:
+ match = OPENALEX_INSTITUTION_ID_PATTERN.fullmatch(institution_id.strip())
+ if match is None:
+ raise HTTPException(
+ status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
+ detail=f"Invalid OpenAlex institution ID: {institution_id}",
+ )
+ return f"I{match.group(1)[1:]}"
+
+
+def _normalize_institution_ids(institution_ids: list[str]) -> list[str]:
+ normalized: list[str] = []
+ seen: set[str] = set()
+ for institution_id in institution_ids:
+ clean_id = _normalize_institution_id(institution_id)
+ if clean_id not in seen:
+ normalized.append(clean_id)
+ seen.add(clean_id)
+ return normalized
+
+
def _ensure_name_available(
session: Session,
name: str,
@@ -79,18 +125,76 @@ def _member_counts(
return {organization_id: count for organization_id, count in rows}
+def _institution_data(
+ session: Session, organization_ids: list[uuid.UUID]
+) -> dict[uuid.UUID, list[str]]:
+ ids_by_organization: dict[uuid.UUID, list[str]] = {
+ organization_id: [] for organization_id in organization_ids
+ }
+ if not organization_ids:
+ return ids_by_organization
+
+ institution_rows = session.exec(
+ select(OrganizationInstitution)
+ .where(OrganizationInstitution.organization_id.in_(organization_ids))
+ .order_by(
+ OrganizationInstitution.organization_id,
+ OrganizationInstitution.position,
+ )
+ ).all()
+ for row in institution_rows:
+ ids_by_organization[row.organization_id].append(
+ row.openalex_institution_id
+ )
+
+ return ids_by_organization
+
+
def _to_profile(
- organization: Organization, member_count: int
+ organization: Organization,
+ member_count: int,
+ institution_ids: list[str],
) -> OrganizationProfile:
+ if not institution_ids and organization.openalex_institution_id:
+ legacy_id = _normalize_institution_id(organization.openalex_institution_id)
+ institution_ids = [legacy_id]
return OrganizationProfile(
id=organization.id,
name=organization.name,
- other_inst_id=organization.openalex_institution_id,
+ other_inst_id=institution_ids[0] if institution_ids else None,
+ selected_openalex_institution_ids=institution_ids,
deleted=organization.deleted,
member_count=member_count,
)
+def _replace_organization_institutions(
+ session: Session,
+ organization: Organization,
+ institution_ids: list[str],
+) -> None:
+ normalized_ids = _normalize_institution_ids(institution_ids)
+ for row in session.exec(
+ select(OrganizationInstitution).where(
+ OrganizationInstitution.organization_id == organization.id
+ )
+ ).all():
+ session.delete(row)
+ session.flush()
+
+ for position, institution_id in enumerate(normalized_ids):
+ session.add(
+ OrganizationInstitution(
+ organization_id=organization.id,
+ openalex_institution_id=institution_id,
+ position=position,
+ )
+ )
+ organization.openalex_institution_id = (
+ normalized_ids[0] if normalized_ids else None
+ )
+
+
def _deactivate_organization_accounts(
session: Session, organization_id: uuid.UUID
) -> None:
@@ -106,6 +210,27 @@ def _deactivate_organization_accounts(
session.add(account)
+def _ensure_not_current_organization(
+ session: Session,
+ access_token: AccessTokenMetadata,
+ organization_id: uuid.UUID,
+) -> None:
+ protected_organization_ids = {access_token.effective_organization_id}
+ if access_token.real_account_id is not None:
+ real_account = session.get(Account, access_token.real_account_id)
+ if real_account is not None:
+ protected_organization_ids.add(real_account.organization_id)
+
+ if organization_id in protected_organization_ids:
+ raise HTTPException(
+ status_code=status.HTTP_409_CONFLICT,
+ detail=(
+ "The organization of the real or effective account "
+ "cannot be deleted."
+ ),
+ )
+
+
def get_organizations(
session: Session,
access_token: AccessTokenMetadata,
@@ -130,10 +255,15 @@ def get_organizations(
).all()
organization_ids = [organization.id for organization in organizations]
counts = _member_counts(session, organization_ids)
+ institution_ids = _institution_data(session, organization_ids)
return OrganizationPage(
items=[
- _to_profile(organization, counts.get(organization.id, 0))
+ _to_profile(
+ organization,
+ counts.get(organization.id, 0),
+ institution_ids.get(organization.id, []),
+ )
for organization in organizations
],
total=total,
@@ -153,12 +283,25 @@ def create_organization(
organization = Organization(
name=name,
- openalex_institution_id=(payload.other_inst_id or '').strip() or None,
)
session.add(organization)
+ session.flush()
+ requested_ids = payload.selected_openalex_institution_ids
+ if requested_ids is None:
+ requested_ids = [payload.other_inst_id] if payload.other_inst_id else []
+ _replace_organization_institutions(
+ session,
+ organization,
+ requested_ids,
+ )
session.commit()
session.refresh(organization)
- return _to_profile(organization, 0)
+ institution_ids = _institution_data(session, [organization.id])
+ return _to_profile(
+ organization,
+ 0,
+ institution_ids[organization.id],
+ )
def update_organization(
@@ -174,10 +317,21 @@ def update_organization(
name = _normalize_name(payload.name)
_ensure_name_available(session, name, organization.id)
organization.name = name
- if payload.other_inst_id is not None:
- organization.openalex_institution_id = payload.other_inst_id.strip() or None
+ if payload.selected_openalex_institution_ids is not None:
+ _replace_organization_institutions(
+ session,
+ organization,
+ payload.selected_openalex_institution_ids,
+ )
+ elif payload.other_inst_id is not None:
+ _replace_organization_institutions(
+ session,
+ organization,
+ [payload.other_inst_id] if payload.other_inst_id.strip() else [],
+ )
if payload.deleted is not None:
if payload.deleted and not organization.deleted:
+ _ensure_not_current_organization(session, access_token, organization.id)
_deactivate_organization_accounts(session, organization.id)
organization.deleted = payload.deleted
@@ -185,7 +339,107 @@ def update_organization(
session.commit()
session.refresh(organization)
counts = _member_counts(session, [organization.id])
- return _to_profile(organization, counts.get(organization.id, 0))
+ institution_ids = _institution_data(session, [organization.id])
+ return _to_profile(
+ organization,
+ counts.get(organization.id, 0),
+ institution_ids[organization.id],
+ )
+
+
+async def get_institution_associations(
+ access_token: AccessTokenMetadata,
+ institution_ids: list[str],
+) -> list[InstitutionAssociationsResponse]:
+ _require_super_admin(access_token)
+ clean_ids = _normalize_institution_ids(institution_ids)
+ if not clean_ids:
+ return []
+
+ response = await elasticsearch.search(
+ index=ESIndex.OPENALEX_INSTITUTIONS,
+ query={
+ "terms": {
+ "id": [
+ f"https://openalex.org/{institution_id}"
+ for institution_id in clean_ids
+ ]
+ }
+ },
+ source=["id", "display_name", "associated_institutions"],
+ size=len(clean_ids),
+ )
+ sources_by_id: dict[str, dict] = {}
+ for hit in response.get("hits", {}).get("hits", []):
+ source = hit.get("_source") or {}
+ raw_id = source.get("id")
+ if isinstance(raw_id, str):
+ sources_by_id[_normalize_institution_id(raw_id)] = source
+
+ missing_id = next(
+ (
+ institution_id
+ for institution_id in clean_ids
+ if institution_id not in sources_by_id
+ ),
+ None,
+ )
+ if missing_id is not None:
+ raise HTTPException(
+ status_code=status.HTTP_404_NOT_FOUND,
+ detail=f"OpenAlex institution {missing_id} not found.",
+ )
+
+ results: list[InstitutionAssociationsResponse] = []
+ for clean_id in clean_ids:
+ source = sources_by_id[clean_id]
+ display_name = source.get("display_name")
+ if not isinstance(display_name, str) or not display_name.strip():
+ raise HTTPException(
+ status_code=status.HTTP_502_BAD_GATEWAY,
+ detail=f"OpenAlex institution {clean_id} has no display name.",
+ )
+
+ associations_by_id: dict[str, InstitutionAssociation] = {}
+ for association in source.get("associated_institutions") or []:
+ if not isinstance(association, dict):
+ continue
+ relationship = str(association.get("relationship") or "").lower()
+ if relationship not in KNOWN_ASSOCIATION_TYPES:
+ logger.warning(
+ "Ignoring unknown OpenAlex institution relationship %r for %s",
+ relationship,
+ clean_id,
+ )
+ continue
+ if relationship not in {"child", "related"}:
+ continue
+ raw_association_id = association.get("id")
+ association_name = association.get("display_name")
+ if not isinstance(raw_association_id, str) or not isinstance(
+ association_name, str
+ ):
+ continue
+ associated_id = _normalize_institution_id(raw_association_id)
+ candidate = InstitutionAssociation(
+ id=associated_id,
+ display_name=association_name,
+ relationship=relationship,
+ )
+ existing = associations_by_id.get(associated_id)
+ if existing is None or (
+ existing.relationship == "related" and relationship == "child"
+ ):
+ associations_by_id[associated_id] = candidate
+
+ results.append(
+ InstitutionAssociationsResponse(
+ id=clean_id,
+ display_name=display_name,
+ associated_institutions=list(associations_by_id.values()),
+ )
+ )
+ return results
def delete_organization(
@@ -196,6 +450,7 @@ def delete_organization(
_require_super_admin(access_token)
organization = _get_organization_or_404(session, organization_id)
if not organization.deleted:
+ _ensure_not_current_organization(session, access_token, organization.id)
_deactivate_organization_accounts(session, organization.id)
organization.deleted = True
session.add(organization)
diff --git a/service/src/main/inse/organization_management/test_service.py b/service/src/main/inse/organization_management/test_service.py
index a7ce6ff6..cd4ccdef 100644
--- a/service/src/main/inse/organization_management/test_service.py
+++ b/service/src/main/inse/organization_management/test_service.py
@@ -1,10 +1,16 @@
+import asyncio
from types import SimpleNamespace
import pytest
from fastapi import HTTPException
-from sqlmodel import Session, SQLModel, create_engine
+from sqlmodel import Session, SQLModel, create_engine, select
-from inse.auth.model import Account, Organization, UserRole
+from inse.auth.model import (
+ Account,
+ Organization,
+ OrganizationInstitution,
+ UserRole,
+)
from inse.organization_management import service
from inse.organization_management.model import (
CreateOrganizationRequest,
@@ -22,10 +28,11 @@ def session():
yield database_session
-def token(role: UserRole, organization_id):
+def token(role: UserRole, organization_id, real_account_id=None):
return SimpleNamespace(
effective_role=role,
effective_organization_id=organization_id,
+ real_account_id=real_account_id,
)
@@ -105,8 +112,115 @@ def test_superadmin_can_create_update_and_soft_delete(session):
assert session.get(Organization, created.id).deleted is True
+def test_organization_stores_ordered_selected_institution_ids(session):
+ scope = Organization(name="Scope")
+ session.add(scope)
+ session.commit()
+
+ created = service.create_organization(
+ session,
+ token(UserRole.SUPER_ADMIN, scope.id),
+ CreateOrganizationRequest(
+ name="Institution list",
+ selected_openalex_institution_ids=[
+ "https://openalex.org/I123",
+ "I456",
+ "I123",
+ ],
+ ),
+ )
+
+ assert created.selected_openalex_institution_ids == ["I123", "I456"]
+ assert created.other_inst_id == "I123"
+ assert session.get(Organization, created.id).openalex_institution_id == "I123"
+ rows = session.exec(
+ select(OrganizationInstitution)
+ .where(OrganizationInstitution.organization_id == created.id)
+ .order_by(OrganizationInstitution.position)
+ ).all()
+ assert [row.openalex_institution_id for row in rows] == ["I123", "I456"]
+
+
+def test_empty_institution_list_clears_legacy_primary_institution(session):
+ organization = Organization(name="Organization", openalex_institution_id="I123")
+ session.add(organization)
+ session.commit()
+
+ updated = service.update_organization(
+ session,
+ token(UserRole.SUPER_ADMIN, organization.id),
+ organization.id,
+ UpdateOrganizationRequest(selected_openalex_institution_ids=[]),
+ )
+
+ assert updated.selected_openalex_institution_ids == []
+ assert updated.other_inst_id is None
+ assert session.get(Organization, organization.id).openalex_institution_id is None
+
+
+def test_association_expansion_adds_only_child_and_related_with_child_priority(
+ monkeypatch,
+):
+ async def fake_search(**kwargs):
+ return {
+ "hits": {
+ "hits": [
+ {
+ "_source": {
+ "id": "https://openalex.org/I100",
+ "display_name": "Selected institution",
+ "associated_institutions": [
+ {
+ "id": "https://openalex.org/I200",
+ "display_name": "Duplicate",
+ "relationship": "related",
+ },
+ {
+ "id": "https://openalex.org/I200",
+ "display_name": "Duplicate",
+ "relationship": "child",
+ },
+ {
+ "id": "https://openalex.org/I300",
+ "display_name": "Related",
+ "relationship": "related",
+ },
+ {
+ "id": "https://openalex.org/I400",
+ "display_name": "Parent",
+ "relationship": "parent",
+ },
+ {
+ "id": "https://openalex.org/I500",
+ "display_name": "Successor",
+ "relationship": "successor",
+ },
+ ],
+ },
+ }
+ ],
+ },
+ }
+
+ monkeypatch.setattr(service.elasticsearch, "search", fake_search)
+
+ result = asyncio.run(
+ service.get_institution_associations(
+ token(UserRole.SUPER_ADMIN, None), ["https://openalex.org/I100"]
+ )
+ )
+
+ assert result[0].id == "I100"
+ assert [
+ (association.id, association.relationship)
+ for association in result[0].associated_institutions
+ ] == [("I200", "child"), ("I300", "related")]
+
+
def test_deleting_organization_deactivates_all_its_accounts(session):
+ admin_scope = Organization(name="Admin scope for delete")
organization = Organization(name="Organization to delete")
+ session.add(admin_scope)
session.add(organization)
session.flush()
active_account = Account(
@@ -129,7 +243,7 @@ def test_deleting_organization_deactivates_all_its_accounts(session):
session.commit()
service.delete_organization(
- session, token(UserRole.SUPER_ADMIN, organization.id), organization.id
+ session, token(UserRole.SUPER_ADMIN, admin_scope.id), organization.id
)
session.refresh(active_account)
@@ -141,7 +255,9 @@ def test_deleting_organization_deactivates_all_its_accounts(session):
def test_marking_organization_deleted_deactivates_its_accounts(session):
+ admin_scope = Organization(name="Admin scope for update")
organization = Organization(name="Organization to update")
+ session.add(admin_scope)
session.add(organization)
session.flush()
account = Account(
@@ -155,7 +271,7 @@ def test_marking_organization_deleted_deactivates_its_accounts(session):
service.update_organization(
session,
- token(UserRole.SUPER_ADMIN, organization.id),
+ token(UserRole.SUPER_ADMIN, admin_scope.id),
organization.id,
UpdateOrganizationRequest(deleted=True),
)
@@ -165,6 +281,61 @@ def test_marking_organization_deleted_deactivates_its_accounts(session):
assert account.epoch == 1
+@pytest.mark.parametrize("delete_via_update", [False, True])
+def test_current_organization_cannot_be_deleted(session, delete_via_update):
+ organization = Organization(name="Current organization")
+ session.add(organization)
+ session.commit()
+ access_token = token(UserRole.SUPER_ADMIN, organization.id)
+
+ with pytest.raises(HTTPException) as error:
+ if delete_via_update:
+ service.update_organization(
+ session,
+ access_token,
+ organization.id,
+ UpdateOrganizationRequest(deleted=True),
+ )
+ else:
+ service.delete_organization(session, access_token, organization.id)
+
+ assert error.value.status_code == 409
+ assert session.get(Organization, organization.id).deleted is False
+
+
+def test_real_account_organization_cannot_be_deleted_while_impersonating(session):
+ real_organization = Organization(name="Real organization")
+ effective_organization = Organization(name="Effective organization")
+ session.add(real_organization)
+ session.add(effective_organization)
+ session.flush()
+ real_account = Account(
+ email="real-superadmin@example.org",
+ name="Real superadmin",
+ password_hash="hash",
+ organization_id=real_organization.id,
+ roles=[UserRole.SUPER_ADMIN],
+ )
+ session.add(real_account)
+ session.commit()
+
+ access_token = token(
+ UserRole.SUPER_ADMIN,
+ effective_organization.id,
+ real_account.id,
+ )
+ with pytest.raises(HTTPException) as error:
+ service.delete_organization(
+ session,
+ access_token,
+ real_organization.id,
+ )
+
+ assert error.value.status_code == 409
+ assert session.get(Organization, real_organization.id).deleted is False
+ assert session.get(Account, real_account.id).activated is True
+
+
@pytest.mark.parametrize("role", [UserRole.ADMIN, UserRole.MANAGER, UserRole.USER])
def test_only_superadmin_can_create_organizations(session, role):
organization = Organization(name="Scope")
diff --git a/service/src/main/inse/projects/eu_cordis_projects_client.py b/service/src/main/inse/projects/eu_cordis_projects_client.py
index 731cd699..be4fd23d 100644
--- a/service/src/main/inse/projects/eu_cordis_projects_client.py
+++ b/service/src/main/inse/projects/eu_cordis_projects_client.py
@@ -741,6 +741,8 @@ async def _build_eu_cordis_search_query(
title: str | None = None,
funding_start_years: list[str] | None = None,
funding_end_years: list[str] | None = None,
+ active_from_year: int | None = None,
+ active_to_year: int | None = None,
countries: list[str] | None = None,
framework_programmes: list[str] | None = None,
funding_schemes: list[str] | None = None,
@@ -876,6 +878,18 @@ async def _build_eu_cordis_search_query(
if funding_end_years:
must_clauses.append(_eu_year_filters("endDate", funding_end_years))
+ # Period-overlap filter: a project was active in the selected interval when
+ # it started no later than the interval end and ended no earlier than the
+ # interval start. This is intentionally separate from exact-year filters.
+ if active_to_year is not None:
+ must_clauses.append(
+ {"range": {"startDate": {"lte": f"{active_to_year}-12-31"}}}
+ )
+ if active_from_year is not None:
+ must_clauses.append(
+ {"range": {"endDate": {"gte": f"{active_from_year}-01-01"}}}
+ )
+
# === Project core filters ===
if framework_programmes:
must_clauses.append({"terms": {"frameworkProgramme": framework_programmes}})
@@ -937,6 +951,8 @@ async def search_eu_cordis_projects(
title: str | None = None,
funding_start_years: list[str] | None = None,
funding_end_years: list[str] | None = None,
+ active_from_year: int | None = None,
+ active_to_year: int | None = None,
countries: list[str] | None = None,
framework_programmes: list[str] | None = None,
funding_schemes: list[str] | None = None,
@@ -965,6 +981,8 @@ async def search_eu_cordis_projects(
title=title,
funding_start_years=funding_start_years,
funding_end_years=funding_end_years,
+ active_from_year=active_from_year,
+ active_to_year=active_to_year,
countries=countries,
framework_programmes=framework_programmes,
funding_schemes=funding_schemes,
diff --git a/service/src/main/inse/projects/projects_search_client.py b/service/src/main/inse/projects/projects_search_client.py
index 0c8d126d..924e1e41 100644
--- a/service/src/main/inse/projects/projects_search_client.py
+++ b/service/src/main/inse/projects/projects_search_client.py
@@ -369,6 +369,8 @@ async def search_dfg_projects(
sort_direction: str = "asc",
fuzzy: bool = False,
skip_enrichment: bool = False,
+ active_from_year: int | None = None,
+ active_to_year: int | None = None,
) -> DfgProjectPage:
"""Searches for DFG projects based on the provided filtering and sorting criteria.
@@ -489,6 +491,11 @@ async def search_dfg_projects(
if funding_end_years:
must_clauses.append({"terms": {"funding_end": funding_end_years}})
+ if active_to_year is not None:
+ must_clauses.append({"range": {"funding_start": {"lte": str(active_to_year)}}})
+ if active_from_year is not None:
+ must_clauses.append({"range": {"funding_end": {"gte": str(active_from_year)}}})
+
if names:
name_must_clauses = []
for full_name in names:
@@ -600,7 +607,6 @@ async def search_dfg_projects(
body["sort"] = [sort_config]
# print(f"Executing DFG project search with body: {json.dumps(body, indent=2)}")
# === Execute Search ===
- print(f"Executing DFG project search with body: {json.dumps(body, indent=2)}")
response = await elasticsearch.search(
index=ESIndex.DFG_PROJECTS,
body=body,
@@ -612,6 +618,9 @@ async def search_dfg_projects(
if skip_enrichment:
return _complete_response_to_dfg_project_page(response, page, size)
+ if not hits:
+ return _complete_response_to_dfg_project_page(response, page, size)
+
project_ids = [hit["_source"]["id"] for hit in hits]
topic_lookup = await get_openalex_topics_for_dfg_projects(project_ids=project_ids)
@@ -858,6 +867,8 @@ async def search_bund_projects_with_filters(
sort_direction: str = "asc",
fuzzy: bool = False,
skip_topic_enrichment: bool = False,
+ active_from_year: int | None = None,
+ active_to_year: int | None = None,
) -> BundProjectPage:
"""
Main search function for BUND projects, analogous to the DFG search.
@@ -999,6 +1010,15 @@ async def search_bund_projects_with_filters(
if funding_end_years:
must_clauses.append(_bund_year_filters("funding_end", funding_end_years))
+ if active_to_year is not None:
+ must_clauses.append(
+ {"range": {"funding_start": {"lte": f"31.12.{active_to_year}"}}}
+ )
+ if active_from_year is not None:
+ must_clauses.append(
+ {"range": {"funding_end": {"gte": f"01.01.{active_from_year}"}}}
+ )
+
body["query"] = {"bool": {"must": must_clauses}} if must_clauses else {"match_all": {}}
# === Sorting ===
sort_by = sort_by.strip().lower()
diff --git a/service/src/main/inse/projects/service.py b/service/src/main/inse/projects/service.py
index f1abccf8..eabd2228 100644
--- a/service/src/main/inse/projects/service.py
+++ b/service/src/main/inse/projects/service.py
@@ -188,6 +188,8 @@ async def get_dfg_projects(
sort_direction: str = "asc",
fuzzy: bool = False,
skip_enrichment: bool = False,
+ active_from_year: int | None = None,
+ active_to_year: int | None = None,
) -> DfgProjectPage:
logger.debug(
"Fetching DFG projects for author_id=%s, author_filter_ids=%s, "
@@ -284,6 +286,8 @@ async def get_dfg_projects(
sort_direction=sort_direction,
fuzzy=fuzzy,
skip_enrichment=skip_enrichment,
+ active_from_year=active_from_year,
+ active_to_year=active_to_year,
)
async def get_institution_cordis_eu_projects_funding_over_time(
@@ -459,6 +463,8 @@ async def search_bund_projects_with_filters(
sort_by: str = "title",
sort_direction: str = "asc",
fuzzy: bool = False,
+ active_from_year: int | None = None,
+ active_to_year: int | None = None,
) -> BundProjectPage:
institution_aliases = []
if raw_oa_institution_id:
@@ -494,7 +500,9 @@ async def search_bund_projects_with_filters(
size=size,
sort_by=sort_by,
sort_direction=sort_direction,
- fuzzy=fuzzy
+ fuzzy=fuzzy,
+ active_from_year=active_from_year,
+ active_to_year=active_to_year,
)
def _calculate_funding_over_time(
@@ -656,6 +664,8 @@ async def search_eu_cordis_projects(
title: str | None = None,
funding_start_years: list[str] | None = None,
funding_end_years: list[str] | None = None,
+ active_from_year: int | None = None,
+ active_to_year: int | None = None,
countries: list[str] | None = None,
framework_programmes: list[str] | None = None,
funding_schemes: list[str] | None = None,
@@ -716,6 +726,8 @@ async def search_eu_cordis_projects(
title=title,
funding_start_years=funding_start_years,
funding_end_years=funding_end_years,
+ active_from_year=active_from_year,
+ active_to_year=active_to_year,
countries=countries,
framework_programmes=framework_programmes,
funding_schemes=funding_schemes,
diff --git a/service/src/main/inse/projects/test_eu_cordis_search_client.py b/service/src/main/inse/projects/test_eu_cordis_search_client.py
index 342f383b..f6e7d5c3 100644
--- a/service/src/main/inse/projects/test_eu_cordis_search_client.py
+++ b/service/src/main/inse/projects/test_eu_cordis_search_client.py
@@ -2,6 +2,21 @@ import pytest
from inse.projects import eu_cordis_projects_client as eu_cordis_search_client
+@pytest.mark.anyio
+async def test_active_period_filter_matches_projects_overlapping_interval():
+ query, _, _ = await eu_cordis_search_client._build_eu_cordis_search_query(
+ active_from_year=2022,
+ active_to_year=2026,
+ )
+
+ assert {"range": {"startDate": {"lte": "2026-12-31"}}} in query["bool"][
+ "must"
+ ]
+ assert {"range": {"endDate": {"gte": "2022-01-01"}}} in query["bool"][
+ "must"
+ ]
+
+
@pytest.mark.anyio
async def test_search_eu_cordis_projects_by_title():
"""Test searching EU CORDIS projects by title."""
@@ -362,4 +377,4 @@ async def test_search_eu_cordis_projects_with_fuzzy_topic_search():
# Note: This may return 0 results if the topic ID doesn't exist
# The important thing is that it doesn't crash
assert isinstance(res.total, int)
- assert isinstance(res.elements, list)
\ No newline at end of file
+ assert isinstance(res.elements, list)
diff --git a/service/src/main/inse/projects/test_projects_dfg.py b/service/src/main/inse/projects/test_projects_dfg.py
index f9eb82b9..bc331c62 100644
--- a/service/src/main/inse/projects/test_projects_dfg.py
+++ b/service/src/main/inse/projects/test_projects_dfg.py
@@ -1,4 +1,7 @@
+from unittest.mock import AsyncMock, patch
+
import pytest
+
from inse.projects import projects_search_client
@@ -20,6 +23,33 @@ async def test_search_dfg_projects():
for name in element.names
)
+
+@pytest.mark.anyio
+async def test_search_dfg_projects_returns_empty_page_without_enrichment_crash():
+ response = {
+ "hits": {
+ "total": {"value": 0},
+ "hits": [],
+ }
+ }
+ with patch(
+ "inse.projects.projects_search_client.elasticsearch.search",
+ new=AsyncMock(return_value=response),
+ ) as mocked_search:
+ result = await projects_search_client.search_dfg_projects(
+ page=0,
+ size=1,
+ funding_start_years=["2022"],
+ funding_end_years=["2026"],
+ )
+
+ assert result.total == 0
+ assert result.elements == []
+ query = mocked_search.await_args.kwargs["body"]["query"]
+ assert {"terms": {"funding_start": ["2022"]}} in query["bool"]["must"]
+ assert {"terms": {"funding_end": ["2026"]}} in query["bool"]["must"]
+
+
@pytest.mark.anyio
async def test_get_dfg_project_by_id():
# Get by ID of the project we found or a known one
diff --git a/service/src/main/inse/topics/v2/router.py b/service/src/main/inse/topics/v2/router.py
index f382d5a0..0a7fe43a 100644
--- a/service/src/main/inse/topics/v2/router.py
+++ b/service/src/main/inse/topics/v2/router.py
@@ -4,6 +4,9 @@ from typing import Annotated
import inse.topics.v2.service as topics_service
from fastapi import APIRouter, Path, Query
from inse.model import SortDirection
+from inse.models.openalex.domain import Domain
+from inse.models.openalex.model_field import ModelField
+from inse.models.openalex.subfield import Subfield
from inse.models.openalex.topic import Topic
from inse.router_prefixes import RouterPrefixes
from inse.tags import Tags
@@ -78,6 +81,48 @@ async def get_topic_by_id(
)
+@router.get(
+ "/domains/single/{domain_id}",
+ operation_id="getDomainById",
+ summary="Returns a domain for a given domain ID.",
+)
+async def get_domain_by_id(
+ domain_id: Annotated[
+ str,
+ Path(description="The ID of the domain to retrieve."),
+ ],
+) -> Domain:
+ return await topics_service.get_domain_by_id_or_raise(domain_id=domain_id)
+
+
+@router.get(
+ "/fields/single/{field_id}",
+ operation_id="getFieldById",
+ summary="Returns a field for a given field ID.",
+)
+async def get_field_by_id(
+ field_id: Annotated[
+ str,
+ Path(description="The ID of the field to retrieve."),
+ ],
+) -> ModelField:
+ return await topics_service.get_field_by_id_or_raise(field_id=field_id)
+
+
+@router.get(
+ "/subfields/single/{subfield_id}",
+ operation_id="getSubfieldById",
+ summary="Returns a subfield for a given subfield ID.",
+)
+async def get_subfield_by_id(
+ subfield_id: Annotated[
+ str,
+ Path(description="The ID of the subfield to retrieve."),
+ ],
+) -> Subfield:
+ return await topics_service.get_subfield_by_id_or_raise(subfield_id=subfield_id)
+
+
@router.get(
"/topics/id",
operation_id="getTopicsByIds",
diff --git a/service/src/main/inse/topics/v2/service.py b/service/src/main/inse/topics/v2/service.py
index b73379d8..b10c7d60 100644
--- a/service/src/main/inse/topics/v2/service.py
+++ b/service/src/main/inse/topics/v2/service.py
@@ -1,6 +1,9 @@
from inse.exceptions import NotFoundException
from inse.integrations import elasticsearch
from inse.model import ESIndex, SortDirection
+from inse.models.openalex.domain import Domain
+from inse.models.openalex.model_field import ModelField
+from inse.models.openalex.subfield import Subfield
from inse.models.openalex.topic import Topic
from inse.topics.v2.model import TopicPageV2, TopicSortBy
@@ -184,6 +187,117 @@ async def get_topic_by_id_or_raise(raw_oa_topic_id: str) -> Topic:
return topic
+async def get_domain_by_id(domain_id: str) -> Domain | None:
+ """Retrieves a domain based on its ID.
+
+ Args:
+ domain_id (str): The numeric OpenAlex ID of the domain to retrieve (e.g. "4").
+
+ Returns:
+ Domain | None: The domain matching the provided ID, or None if not found.
+ """
+ response = await elasticsearch.get(
+ index=ESIndex.OPENALEX_DOMAINS,
+ doc_id=domain_id,
+ source=["id", "display_name", "description"],
+ )
+ if response.get("found"):
+ return Domain.from_dict(response.get("_source", {}))
+ return None
+
+
+async def get_domain_by_id_or_raise(domain_id: str) -> Domain:
+ """Retrieves a domain based on its ID, raising an exception if not found.
+
+ Args:
+ domain_id (str): The ID of the domain to retrieve.
+
+ Raises:
+ NotFoundException: If the domain with the specified ID is not found.
+
+ Returns:
+ Domain: The domain matching the provided ID.
+ """
+ domain = await get_domain_by_id(domain_id)
+ if domain is None:
+ raise NotFoundException(f"Domain with ID {domain_id} not found.")
+ return domain
+
+
+async def get_field_by_id(field_id: str) -> ModelField | None:
+ """Retrieves a field based on its ID.
+
+ Args:
+ field_id (str): The numeric OpenAlex ID of the field to retrieve (e.g. "27").
+
+ Returns:
+ ModelField | None: The field matching the provided ID, or None if not found.
+ """
+ response = await elasticsearch.get(
+ index=ESIndex.OPENALEX_FIELDS,
+ doc_id=field_id,
+ source=["id", "display_name", "description"],
+ )
+ if response.get("found"):
+ return ModelField.from_dict(response.get("_source", {}))
+ return None
+
+
+async def get_field_by_id_or_raise(field_id: str) -> ModelField:
+ """Retrieves a field based on its ID, raising an exception if not found.
+
+ Args:
+ field_id (str): The ID of the field to retrieve.
+
+ Raises:
+ NotFoundException: If the field with the specified ID is not found.
+
+ Returns:
+ ModelField: The field matching the provided ID.
+ """
+ field = await get_field_by_id(field_id)
+ if field is None:
+ raise NotFoundException(f"Field with ID {field_id} not found.")
+ return field
+
+
+async def get_subfield_by_id(subfield_id: str) -> Subfield | None:
+ """Retrieves a subfield based on its ID.
+
+ Args:
+ subfield_id (str): The numeric OpenAlex ID of the subfield to retrieve (e.g. "2743").
+
+ Returns:
+ Subfield | None: The subfield matching the provided ID, or None if not found.
+ """
+ response = await elasticsearch.get(
+ index=ESIndex.OPENALEX_SUBFIELDS,
+ doc_id=subfield_id,
+ source=["id", "display_name", "description"],
+ )
+ if response.get("found"):
+ return Subfield.from_dict(response.get("_source", {}))
+ return None
+
+
+async def get_subfield_by_id_or_raise(subfield_id: str) -> Subfield:
+ """Retrieves a subfield based on its ID, raising an exception if not found.
+
+ Args:
+ subfield_id (str): The ID of the subfield to retrieve.
+
+ Raises:
+ NotFoundException: If the subfield with the specified ID is not found.
+
+ Returns:
+ Subfield: The subfield matching the provided ID.
+ """
+ subfield = await get_subfield_by_id(subfield_id)
+ if subfield is None:
+ raise NotFoundException(f"Subfield with ID {subfield_id} not found.")
+ return subfield
+
+
async def get_topics_by_ids(topic_ids: list[str]) -> TopicPageV2:
"""Retrieves topics based on a list of topic IDs.
diff --git a/webapp/src/app/api/.openapi-generator/FILES b/webapp/src/app/api/.openapi-generator/FILES
index 3c0e087f..d1763419 100644
--- a/webapp/src/app/api/.openapi-generator/FILES
+++ b/webapp/src/app/api/.openapi-generator/FILES
@@ -169,6 +169,8 @@ model/idTokenMetadata.ts
model/inseAccountManagementModelOrganizationProfile.ts
model/inseOrganizationManagementModelOrganizationProfile.ts
model/institution.ts
+model/institutionAssociation.ts
+model/institutionAssociationsResponse.ts
model/institutionFunderSummary.ts
model/institutionGeo.ts
model/institutionIds.ts
diff --git a/webapp/src/app/api/api/organization.service.ts b/webapp/src/app/api/api/organization.service.ts
index 14fb942d..1d3c7319 100644
--- a/webapp/src/app/api/api/organization.service.ts
+++ b/webapp/src/app/api/api/organization.service.ts
@@ -1,7 +1,7 @@
/**
* Innovation Search Engine API
*
- *
+ *
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
@@ -9,12 +9,18 @@
*/
/* tslint:disable:no-unused-variable member-ordering */
-import { Inject, Injectable, Optional } from '@angular/core';
-import { HttpClient, HttpHeaders, HttpParams,
- HttpResponse, HttpEvent, HttpParameterCodec, HttpContext
- } from '@angular/common/http';
-import { CustomHttpParameterCodec } from '../encoder';
-import { Observable } from 'rxjs';
+import { Inject, Injectable, Optional } from '@angular/core';
+import {
+ HttpClient,
+ HttpHeaders,
+ HttpParams,
+ HttpResponse,
+ HttpEvent,
+ HttpParameterCodec,
+ HttpContext,
+} from '@angular/common/http';
+import { CustomHttpParameterCodec } from '../encoder';
+import { Observable } from 'rxjs';
// @ts-ignore
import { CreateOrganizationRequest } from '../model/createOrganizationRequest';
@@ -23,292 +29,679 @@ import { HTTPValidationError } from '../model/hTTPValidationError';
// @ts-ignore
import { InseOrganizationManagementModelOrganizationProfile } from '../model/inseOrganizationManagementModelOrganizationProfile';
// @ts-ignore
+import { InstitutionAssociationsResponse } from '../model/institutionAssociationsResponse';
+// @ts-ignore
import { OrganizationPage } from '../model/organizationPage';
// @ts-ignore
import { UpdateOrganizationRequest } from '../model/updateOrganizationRequest';
// @ts-ignore
-import { BASE_PATH, COLLECTION_FORMATS } from '../variables';
-import { Configuration } from '../configuration';
+import { BASE_PATH, COLLECTION_FORMATS } from '../variables';
+import { Configuration } from '../configuration';
import { BaseService } from '../api.base.service';
-
-
@Injectable({
- providedIn: 'root'
+ providedIn: 'root',
})
export class OrganizationService extends BaseService {
+ constructor(
+ protected httpClient: HttpClient,
+ @Optional() @Inject(BASE_PATH) basePath: string | string[],
+ @Optional() configuration?: Configuration,
+ ) {
+ super(basePath, configuration);
+ }
- constructor(protected httpClient: HttpClient, @Optional() @Inject(BASE_PATH) basePath: string|string[], @Optional() configuration?: Configuration) {
- super(basePath, configuration);
+ /**
+ * Create Organization
+ * @endpoint post /api/organizations
+ * @param createOrganizationRequest
+ * @param secureFgpAcc
+ * @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 createOrganisation(
+ createOrganizationRequest: CreateOrganizationRequest,
+ secureFgpAcc?: string,
+ observe?: 'body',
+ reportProgress?: boolean,
+ options?: {
+ httpHeaderAccept?: 'application/json';
+ context?: HttpContext;
+ transferCache?: boolean;
+ },
+ ): Observable