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/router.py b/service/src/main/inse/auth/router.py index 9bf5d85a..4bb2ab31 100644 --- a/service/src/main/inse/auth/router.py +++ b/service/src/main/inse/auth/router.py @@ -2,7 +2,7 @@ import logging import uuid from typing import Annotated -from fastapi import APIRouter, Body, Depends, Response, status +from fastapi import APIRouter, Body, Depends, Query, Response, status from sqlmodel import Session import inse.auth.service as auth_service @@ -204,3 +204,30 @@ async def change_password( current_password=current_password, new_password=new_password, ) + + +@router.get( + "/can-fetch-gdpr-relevant-data", + summary="Check if user can fetch GDPR-relevant data", + description="Check if the authenticated user can fetch GDPR-relevant data for a given author and institution.", + operation_id="canFetchGdprRelevantData", +) +async def can_fetch_gdpr_relevant_data( + access_token: Annotated[ + AccessTokenMetadata, + auth_service.CurrentUserAccessTokenPayloadDep, + ], + raw_oa_author_id: Annotated[ + str | None, + Query(description="OpenAlex author ID to check access for"), + ] = None, + raw_oa_institution_id: Annotated[ + str | None, + Query(description="OpenAlex institution ID to check access for"), + ] = None, +) -> bool: + return await auth_service.can_fetch_gdpr_relevant_data( + access_token=access_token, + raw_oa_author_id=raw_oa_author_id, + raw_oa_institution_id=raw_oa_institution_id, + ) diff --git a/service/src/main/inse/auth/service.py b/service/src/main/inse/auth/service.py index 9ce83f9c..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, @@ -31,6 +32,7 @@ from inse.auth.model import ( effective_role_for_roles, normalize_roles, ) +from inse.authors.v2 import service as authors_service from inse.config import get_settings from inse.database import get_session @@ -97,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" @@ -112,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( @@ -1451,3 +1464,69 @@ def change_password( logger.info("Password changed successfully for account %s", account.id) return {"status": "ok"} + + +async def can_fetch_gdpr_relevant_data( + access_token: AccessTokenMetadata, + raw_oa_author_id: str | None = None, + raw_oa_institution_id: str | None = None, +) -> bool: + """Returns True if the user associated with the provided access token is allowed to fetch GDPR-relevant data for the specified OpenAlex author ID and institution ID, based on their effective institution ID. + + Args: + access_token (AccessTokenMetadata): The access token for the user. + raw_oa_author_id (str | None, optional): The OpenAlex author ID for which to check access. Defaults to None. + raw_oa_institution_id (str | None, optional): The OpenAlex institution ID for which to check access. Defaults to None. + + Returns: + bool: True if the user is allowed to fetch GDPR-relevant data for the specified IDs, False otherwise. + """ + + logger.debug( + "Checking if user with effective institution ID %s can fetch GDPR-relevant data for author ID %s and institution ID %s", + access_token.effective_institution_id, + raw_oa_author_id, + raw_oa_institution_id, + ) + + if not raw_oa_author_id and not raw_oa_institution_id: + logger.debug("No OpenAlex author ID or institution ID provided") + return False + + effective_institution_id = access_token.effective_institution_id + # Current user does not belong to any institution + if not effective_institution_id: + logger.debug( + "Current user does not belong to any institution, cannot fetch GDPR-relevant data" + ) + return False + + # Current user belongs to an institution, but the request is for a different institution + if ( + raw_oa_institution_id + and effective_institution_id + and raw_oa_institution_id != effective_institution_id + ): + logger.debug( + "Current user belongs to institution %s, but request is for institution %s, cannot fetch GDPR-relevant data", + effective_institution_id, + raw_oa_institution_id, + ) + return False + + # Current user belongs to an institution, but request is for author not belonging to that institution + if raw_oa_author_id: + author_belongs_to_institution = ( + await authors_service.author_currently_belongs_to_institution( + raw_oa_author_id or "", effective_institution_id + ) + ) + logger.debug( + "Author %s belongs to institution %s: %s", + raw_oa_author_id, + effective_institution_id, + author_belongs_to_institution, + ) + return author_belongs_to_institution + + return True 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 d2056d48..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.authors.institution_membership_query import ( - build_institution_membership_query, -) -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.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.persons import service as persons_service +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,20 +111,23 @@ async def get_dashboard_publications( ) -> DashboardStatisticValue: normalized_id = _normalize_institution_id(institution_id) period = _dashboard_period(from_year, to_year) - filters = [] - if year_filter := _publication_year_filter(period): - filters.append(year_filter) - query = _institution_works_query(normalized_id) - if filters: - query = {"bool": {"must": [query], "filter": filters}} - response = await elasticsearch.search( - index=config.settings.openalex_works_search_index, - query=query, - size=0, - track_total_hits=True, - cluster=ESCluster.NES, + 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, + ) + return DashboardStatisticValue( + institution_id=normalized_id, + organization_name=organization_name, + value=works.total, ) - return _dashboard_statistic_value(normalized_id, organization_name, response) async def get_dashboard_persons( @@ -270,20 +143,25 @@ async def get_dashboard_persons( status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, detail="from_year and to_year must either both be provided or both omitted.", ) - membership_query = build_institution_membership_query( + persons = await persons_service.search_persons_list( + query=None, institution_id=normalized_id, - year_mode="between" if period[0] is not None else "all", - year=period[0], - year_to=period[1], + sort_by=None, + sort_order=None, + topic=None, + page=1, + page_size=1, + include="", + year_filter_enabled=period[0] is not None, + filter_mode="between" if period[0] is not None else None, + filter_year=period[0], + filter_year_to=period[1], ) - response = await elasticsearch.search( - index=ESIndex.OPENALEX_AUTHORS, - query=membership_query, - size=0, - track_total_hits=True, - cluster=ESCluster.NES, + return DashboardStatisticValue( + institution_id=normalized_id, + organization_name=organization_name, + value=int(persons.meta.count or 0) if persons.meta else 0, ) - return _dashboard_statistic_value(normalized_id, organization_name, response) async def get_dashboard_patents( @@ -308,750 +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) - aliases = await _institution_aliases(normalized_id, organization_name) - period = _dashboard_period(from_year, to_year) - period_filter = _project_overlap_filter( - "startDate", - "endDate", - _date_period(period, "iso"), - ) - if period_filter: - project_ids = await _eu_project_ids_for_aliases(aliases) - value = await _count_eu_projects_in_period(project_ids, period_filter) - return DashboardStatisticValue( - institution_id=normalized_id, - organization_name=organization_name, - value=value, - ) - - response = await elasticsearch.search( - index=ESIndex.CORDIS_EU_ORGANIZATIONS_WILDCARD, - body={ - "size": 0, - "query": _eu_organization_query(aliases), - "aggs": { - "projects": { - "cardinality": { - "field": "projectID", - } - } - }, - }, - cluster=ESCluster.INSE, - ) - return DashboardStatisticValue( - institution_id=normalized_id, - organization_name=organization_name, - value=int( - response.get("aggregations", {}) - .get("projects", {}) - .get("value", 0) - ), - ) - - -async def get_dashboard_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: - return EuProjectStatusStatistics( - institution_id=normalized_id, - organization_name=organization_name, - ongoing=0, - 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", {}) - return EuProjectStatusStatistics( - institution_id=normalized_id, - organization_name=organization_name, - ongoing=_project_status_count(aggregations, "ongoing"), - upcoming=_project_status_count(aggregations, "upcoming"), - completed=_project_status_count(aggregations, "completed"), - ) - - -def _project_status_count(aggregations: dict[str, Any], status_name: str) -> int: - return int( - aggregations.get(status_name, {}).get("projects", {}).get("value", 0) - ) - - -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) - 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) - response = await elasticsearch.search( - index=ESIndex.PROJECTS_BUND_V1, - query=filters[0] if len(filters) == 1 else {"bool": {"filter": filters}}, - size=0, - track_total_hits=True, - cluster=ESCluster.INSE, - ) - return _dashboard_statistic_value(normalized_id, organization_name, response) - - -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", {}) - return BmbfProjectStatusStatistics( - institution_id=normalized_id, - organization_name=organization_name, - ongoing=int(aggregations.get("ongoing", {}).get("doc_count", 0)), - upcoming=int(aggregations.get("upcoming", {}).get("doc_count", 0)), - completed=int(aggregations.get("completed", {}).get("doc_count", 0)), - ) - - -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) - project_ids = await _get_dfg_project_ids_for_institution( - normalized_id, - from_year=from_year, - to_year=to_year, - ) - return DashboardStatisticValue( - institution_id=normalized_id, - organization_name=organization_name, - value=len(project_ids), - ) - - -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: - return DfgProjectStatusStatistics( - institution_id=normalized_id, - organization_name=organization_name, - ongoing=0, - 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", {}) - ) - return DfgProjectStatusStatistics( - institution_id=normalized_id, - organization_name=organization_name, - ongoing=_project_status_count(aggregations, "ongoing"), - upcoming=0, - completed=_project_status_count(aggregations, "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_for_institution( - normalized_id, - from_year=from_year, - to_year=to_year, - ) - print( - "Dashboard DFG project topics " - f"for institution {normalized_id}: " - f"{len(project_ids)} project IDs={project_ids}", - flush=True, - ) - 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_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) - aliases = await _institution_aliases(normalized_id, organization_name) - 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, aliases, authors), - ) - - 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, @@ -1270,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)) @@ -1330,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") } @@ -1407,793 +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, - organization_names: list[str], - institution_authors: list[dict[str, Any]], -) -> 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_page = await get_eu_organization_project_contributions( - organization_names=organization_names, - projects_filtering_properties=ProjectsFilteringProperties( - project_type=ProjectType.EU, - page=0, - size=10000, - ), - ) - - project_ids = [project.project_id for project in project_page.elements] - - 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, - ) - - return _openalex_work_authors_by_eu_projects( - works_response, - doi_project_ids, - institution_id, - institution_author_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], -) -> 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]), - ) - - return [ - TopAuthor( - id=_short_author_id(author_id), - name=author_names[author_id], - count=len(project_ids), - ) - for author_id, project_ids in ranked_authors[:TOP_AUTHOR_LIMIT] - ] - - -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 2e58db2e..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,31 +10,377 @@ 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_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.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_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 +async def test_dfg_topic_project_ids_use_paginated_projects_service(): + pages = [ + DfgProjectPage( + elements=[DfgProjectSummary(id="101"), DfgProjectSummary(id="102")], + total=3, + page=0, + size=1000, + ), + DfgProjectPage( + elements=[DfgProjectSummary(id="103")], + total=3, + page=1, + size=1000, + ), + ] + + with patch( + "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( + ORG_INSTITUTION_ID, + from_year=2020, + to_year=2022, + ) + + assert project_ids == ["101", "102", "103"] + assert mocked_get_projects.await_count == 2 + first_call = mocked_get_projects.await_args_list[0] + assert first_call.kwargs["raw_oa_institution_id"] == "I123" + assert first_call.kwargs["skip_enrichment"] is True + assert first_call.kwargs["funding_start_years"][-1] == "2022" + 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}}} @@ -47,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": { @@ -69,20 +414,58 @@ 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.institutions.institutions_search_client.InstitutionsSearchClient.get_institution_aliases_by_oa_institution_id", + new=AsyncMock(return_value=["Example University", "Example Uni"]), + ), + 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.projects.service.get_dfg_projects", + new=AsyncMock( + return_value=DfgProjectPage(elements=[], total=3, page=0, size=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) + ), ), ): result = await get_dashboard_statistics( @@ -101,64 +484,153 @@ async def test_dashboard_statistics_counts_organization_data_and_all_projects(): "bmbf_projects": 5, } - publication_call = next( - call - for call in mocked_search.await_args_list - if call.kwargs["index"] == config.settings.openalex_works_search_index - ) - assert publication_call.kwargs["query"]["nested"]["query"]["term"] == { - "authorships.institutions.id": ORG_INSTITUTION_ID - } - person_call = next( - call - for call in mocked_search.await_args_list - if call.kwargs["index"] == ESIndex.OPENALEX_AUTHORS - ) - person_query = person_call.kwargs["query"] - affiliation = person_query["bool"]["should"][0]["bool"]["filter"][1] - - assert affiliation["nested"]["path"] == "affiliations" - assert affiliation["nested"]["query"]["bool"]["filter"][0] == { - "term": {"affiliations.institution.id": ORG_INSTITUTION_ID} - } - eu_call = next( - call - for call in mocked_search.await_args_list - if call.kwargs["index"] == ESIndex.CORDIS_EU_ORGANIZATIONS_WILDCARD - ) - assert eu_call.kwargs["cluster"] == ESCluster.INSE - assert eu_call.kwargs["body"]["query"] == { - "terms": { - "name.keyword": [ - "EXAMPLE ORG", - "EXAMPLE UNI", - "EXAMPLE UNIVERSITY", +@pytest.mark.anyio +async def test_dashboard_publications_uses_institution_publications_logic(): + with patch( + "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", + ) + selected_period = await get_dashboard_publications( + ORG_INSTITUTION_ID, + "Example Org", + from_year=2021, + to_year=2022, + ) + + assert all_time.value == 250 + assert selected_period.value == 22 + 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], } - bund_call = next( - call - for call in mocked_search.await_args_list - if call.kwargs["index"] == ESIndex.PROJECTS_BUND_V1 + +@pytest.mark.anyio +async def test_dashboard_persons_uses_persons_service_for_organization(): + response = CustomAuthorsListResponse( + results=[], meta=Meta(count=64, page=1, per_page=1) ) - assert bund_call.kwargs["cluster"] == ESCluster.INSE - assert bund_call.kwargs["query"]["bool"]["minimum_should_match"] == 1 - assert bund_call.kwargs["query"]["bool"]["should"][0]["match"] == { - "Zuwendungsempfänger": { - "query": "Example Org", - "operator": "and", - } - } - dfg_calls = [ - call - for call in mocked_search.await_args_list - if call.kwargs["index"] == ESIndex.DFG_INSTITUTES_V2 - ] - assert len(dfg_calls) == 2 - assert all(call.kwargs["cluster"] == ESCluster.INSE for call in dfg_calls) + with patch( + "inse.dashboard.service.persons_service.search_persons_list", + new=AsyncMock(return_value=response), + ) as mocked_search_persons: + result = await get_dashboard_persons( + ORG_INSTITUTION_ID, + "Example Org", + from_year=2020, + to_year=2023, + ) + + assert result.value == 64 + call = mocked_search_persons.await_args + assert call.kwargs["institution_id"] == ORG_INSTITUTION_ID + assert call.kwargs["filter_mode"] == "between" + assert call.kwargs["filter_year"] == 2020 + assert call.kwargs["filter_year_to"] == 2023 + assert call.kwargs["page"] == 1 + assert call.kwargs["page_size"] == 1 + + +@pytest.mark.anyio +async def test_dashboard_dfg_projects_uses_projects_service_total(): + project_page = DfgProjectPage(elements=[], total=42, page=0, size=1) + + with patch( + "inse.projects.service.get_dfg_projects", + new=AsyncMock(return_value=project_page), + ) as mocked_get_projects: + result = await get_dashboard_dfg_projects( + ORG_INSTITUTION_ID, + "Example Org", + from_year=2020, + to_year=2022, + ) + + assert result.value == 42 + 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"] 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 + + +@pytest.mark.anyio +async def test_dashboard_bmbf_projects_uses_projects_service_total(): + project_page = BundProjectPage(elements=[], total=29, page=0, size=1) + + with patch( + "inse.projects.service.search_bund_projects_with_filters", + new=AsyncMock(return_value=project_page), + ) as mocked_get_projects: + result = await get_dashboard_bmbf_projects( + ORG_INSTITUTION_ID, + "Example Org", + from_year=2018, + to_year=2020, + ) + + assert result.value == 29 + 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"] 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) + + with patch( + "inse.projects.service.search_eu_cordis_projects", + new=AsyncMock(return_value=project_page), + ) as mocked_get_projects: + result = await get_dashboard_eu_projects( + ORG_INSTITUTION_ID, + "Example Org", + from_year=2019, + to_year=2021, + ) + + assert result.value == 37 + 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"] 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 @pytest.mark.anyio @@ -191,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: @@ -221,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}]} } } @@ -272,29 +738,94 @@ async def test_top_authors_maps_works_patents_news_and_eu_projects(): return {"aggregations": {"people": {"buckets": []}}} - with patch( - "inse.dashboard.service.elasticsearch.search", - new=AsyncMock(side_effect=search), - ) as mocked_search, patch( - "inse.dashboard.service.InstitutionsSearchClient.get_institution_aliases_by_oa_institution_id", - new=AsyncMock(return_value=["Example University"]), - ), patch( - "inse.dashboard.service.get_eu_organization_project_contributions", - new=AsyncMock( - return_value=SimpleNamespace( - elements=[ - SimpleNamespace(project_id="P1"), - SimpleNamespace(project_id="P2"), - SimpleNamespace(project_id="P3"), + 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 + ), + ], + total=3, + page=0, + size=1000, ) + return EuCordisProjectSearchPage( + elements=[], + total={"A1": 3, "A2": 4}[kwargs["author_id"]], + page=0, + size=1, + ) + + with ( + patch( + "inse.integrations.elasticsearch.search", + new=AsyncMock(side_effect=search), + ) as mocked_search, + patch( + "inse.integrations.elasticsearch.scan", + new=scan, ), - ), patch( - "inse.dashboard.service.OrgPatentsSearchClient.top_authors_by_institution", - new=AsyncMock( - return_value=[ - {"id": "A1", "name": "Ada Example", "count": 4}, - ] + 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( @@ -305,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", @@ -313,8 +844,8 @@ async def test_top_authors_maps_works_patents_news_and_eu_projects(): "count": 4, } assert [author.model_dump() for author in result.eu_projects] == [ - {"id": "A2", "name": "Grace Example", "count": 2}, - {"id": "A1", "name": "Ada Example", "count": 1}, + {"id": "A2", "name": "Grace Example", "count": 4}, + {"id": "A1", "name": "Ada Example", "count": 3}, ] assert result.news[0].model_dump() == { "id": "A1", @@ -325,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 == [] @@ -346,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", @@ -451,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": [ @@ -573,34 +1126,61 @@ async def test_top_eu_project_authors_count_filtered_projects_by_stable_author_i } return {"aggregations": {"authors": {"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( + 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=[ - SimpleNamespace(project_id="P1"), - SimpleNamespace(project_id="P2"), + 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": 0}[kwargs["author_id"]], + page=0, + size=1, + ) + + 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=[]), ), - ), 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": 2}, - {"id": "A2", "name": "Grace Example", "count": 1}, + {"id": "A1", "name": "Ada Example", "count": 4}, ] @@ -625,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, @@ -691,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, @@ -721,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(): @@ -812,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( @@ -866,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 @@ -892,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( @@ -928,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/institutions/institutions_search_client.py b/service/src/main/inse/institutions/institutions_search_client.py index 482194d9..7896a01d 100644 --- a/service/src/main/inse/institutions/institutions_search_client.py +++ b/service/src/main/inse/institutions/institutions_search_client.py @@ -361,6 +361,7 @@ class InstitutionsSearchClient: "government", "facility", "other", + "funder", } cleaned_source = {} diff --git a/service/src/main/inse/institutions/logic.py b/service/src/main/inse/institutions/logic.py index 9e7eeb2e..4437c6c9 100644 --- a/service/src/main/inse/institutions/logic.py +++ b/service/src/main/inse/institutions/logic.py @@ -33,6 +33,7 @@ _VALID_INSTITUTION_TYPES = { "government", "facility", "other", + "funder", } diff --git a/service/src/main/inse/institutions/test_logic.py b/service/src/main/inse/institutions/test_logic.py index cca61dc9..d19b6ba7 100644 --- a/service/src/main/inse/institutions/test_logic.py +++ b/service/src/main/inse/institutions/test_logic.py @@ -174,3 +174,34 @@ async def test_list_institutions_accepts_practical_openalex_type_variants(): assert result.results[0].counts_by_year[0].cited_by_count is None assert result.group_by[0].key == "true" + +@pytest.mark.anyio +async def test_list_institutions_accepts_funder_institution_type(): + def handler(_: httpx.Request) -> httpx.Response: + return httpx.Response( + 200, + json={ + "meta": {"count": 1, "page": 1, "per_page": 25}, + "results": [ + { + "id": "https://openalex.org/I4210119759", + "display_name": "Essen University Hospital", + "country_code": "DE", + "type": "funder", + } + ], + }, + ) + + client = OpenAlexInstitutionsClient( + api_key="test-key", + transport=httpx.MockTransport(handler), + ) + + result = await logic.list_institutions(client=client) + + assert result.results[0].id == "https://openalex.org/I4210119759" + assert result.results[0].display_name == "Essen University Hospital" + assert result.results[0].type == "funder" + + diff --git a/service/src/main/inse/institutions/v2/service.py b/service/src/main/inse/institutions/v2/service.py index 7b6876d0..860815d3 100644 --- a/service/src/main/inse/institutions/v2/service.py +++ b/service/src/main/inse/institutions/v2/service.py @@ -142,20 +142,55 @@ async def autocomplete_institutions( if not query: return InstitutionPageV2(elements=[], total=0, page=0, size=0) + stripped = query.strip() + fields = [("display_name", 1.0), ("display_name_alternatives", 0.8)] + should_clauses = [] + for field, weight in fields: + should_clauses.extend([ + { + "prefix": { + f"{field}.keyword": { + "value": stripped, + "case_insensitive": True, + "boost": 10.0 * weight, + } + } + }, + {"match_phrase_prefix": {field: {"query": stripped, "boost": 5.0 * weight, "slop": 3}}}, + {"match_bool_prefix": {field: {"query": stripped, "boost": 2.0 * weight}}}, + { + "constant_score": { + "filter": { + "wildcard": { + f"{field}.keyword": { + "value": f"*{stripped}*", + "case_insensitive": True, + } + } + }, + "boost": 1.0 * weight, + } + }, + ]) + return await search_institutions( page=page, size=size, query={ - "bool": { - "should": [ - {"match_phrase_prefix": {"display_name": query}}, - {"match_phrase_prefix": {"display_name_alternatives": query}}, - ] + "function_score": { + "query": {"bool": {"should": should_clauses, "minimum_should_match": 1}}, + "field_value_factor": { + "field": "works_count", + "modifier": "log1p", + "factor": 0.05, + "missing": 1.0, + }, + "boost_mode": "multiply", } }, source=source, ) - + async def autocomplete_institutions_for_selector( query: str, page: int = 0, size: int = 10 diff --git a/service/src/main/inse/integrations/elasticsearch.py b/service/src/main/inse/integrations/elasticsearch.py index 0ad63956..b48e6c78 100644 --- a/service/src/main/inse/integrations/elasticsearch.py +++ b/service/src/main/inse/integrations/elasticsearch.py @@ -96,6 +96,7 @@ def _index_to_cluster(index: ESIndex) -> ESCluster | None: ESIndex.OPENALEX_INSTITUTIONS, ESIndex.OPENALEX_PUBLICATIONS, ESIndex.WORK_CLASSIFICATIONS, + ESIndex.CC_NEWS_WILDCARD, }: return ESCluster.NES elif index in { @@ -260,11 +261,10 @@ async def search( payload["sort"] = sort if aggs is not None: payload["aggs"] = aggs - if track_total_hits: - payload["track_total_hits"] = True if highlight is not None: payload["highlight"] = highlight - + + payload["track_total_hits"] = True # always track total hits for accurate pagination and counts if len(payload) == 0: raise ValueError( "At least one of 'query', 'body', 'source', 'size', 'offset', 'sort', 'aggs' must be provided" @@ -439,12 +439,16 @@ async def count( async def msearch( searches: list[tuple[ESIndex | str | list[str], dict[str, Any]]], cluster: ESCluster = ESCluster.NES, + request_cache: bool = False, ) -> list[dict[str, Any]]: """Performs a multi-search request (_msearch) on Elasticsearch. Args: searches: A list of tuples, each containing (index, payload_dict). cluster: The Elasticsearch cluster to execute searches on. + request_cache: Whether to enable the shard request cache for each search. + Elasticsearch rejects `request_cache` as an _msearch URL parameter, so + it goes into the per-search header line instead. Returns: List[Dict[str, Any]]: List of response dictionaries for each search in order. @@ -464,7 +468,9 @@ async def msearch( idx_str = ",".join(str(i) for i in idx) else: idx_str = str(idx) - header_obj = {"index": idx_str} + header_obj: dict[str, Any] = {"index": idx_str} + if request_cache: + header_obj["request_cache"] = True lines.append(json.dumps(header_obj)) lines.append(json.dumps(body)) diff --git a/service/src/main/inse/model.py b/service/src/main/inse/model.py index e1f0d3aa..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" @@ -65,6 +68,7 @@ class ESIndex(StrEnum): AKTUELLES = "aktuell" AKTUELLES_POSTPROC = "aktuell_postproc" AKTUELLES_OPENALEX_TOPICS = "aktuell_openalex_topics" + CC_NEWS_WILDCARD = "cc-news-*" CORDIS_EU_ORGANIZATIONS_WILDCARD = "cordis_eu_*_organizations" diff --git a/service/src/main/inse/models/dfg_project_details.py b/service/src/main/inse/models/dfg_project_details.py index fe914373..a5a704f9 100644 --- a/service/src/main/inse/models/dfg_project_details.py +++ b/service/src/main/inse/models/dfg_project_details.py @@ -170,25 +170,6 @@ class DfgProjectPublicationSummary(BaseModel): ) -class DfgProjectSubjectArea(BaseModel): - """A single subject-area classification entry (DFG 'Fachsystematik').""" - - model_config = ConfigDict(populate_by_name=True) - - fach: str | None = None - fachgebiet: str | None = None - fachkollegium: str | None = None - wissenschaftsbereich: str | None = None - - @classmethod - def from_inner(cls, f: DFGProjectFachgebieteInner) -> "DfgProjectSubjectArea": - return cls( - fach=f.fach, - fachgebiet=f.fachgebiet, - fachkollegium=f.fachkollegium, - wissenschaftsbereich=f.wissenschaftsbereich, - ) - class DfgProjectDetails(BaseModel): """ @@ -253,7 +234,7 @@ class DfgProjectDetails(BaseModel): subject_area_de: str | None = Field(default=None, description="Subject area, summary text (German)") subject_area_en: str | None = Field(default=None, description="Subject area, summary text (English)") - subject_classifications: list[DfgProjectSubjectArea] = Field( + subject_classifications: list[DFGProjectFachgebieteInner] = Field( default_factory=list, description="Detailed DFG subject-area classification entries (Fachsystematik)", ) @@ -319,7 +300,7 @@ class DfgProjectDetails(BaseModel): DfgProjectPublicationSummary.from_inner(p) for p in (project.publications or []) ] subject_classifications = [ - DfgProjectSubjectArea.from_inner(f) for f in (project.fachgebiete or []) + DFGProjectFachgebieteInner.from_dict(f) for f in (project.subject_classifications or []) ] # De-duplicated flat views, order-preserving @@ -383,8 +364,6 @@ class DfgProjectDetails(BaseModel): @classmethod def from_dict(cls, obj: dict) -> "DfgProjectDetails": - """Convenience constructor from a raw dict (e.g. a JSON API response body).""" - obj = cls._sanitize_raw_project_dict(obj) return cls.from_dfg_project(DFGProject.from_dict(obj)) @staticmethod diff --git a/service/src/main/inse/models/openalex/institution.py b/service/src/main/inse/models/openalex/institution.py index deede4f7..089013ba 100644 --- a/service/src/main/inse/models/openalex/institution.py +++ b/service/src/main/inse/models/openalex/institution.py @@ -37,7 +37,7 @@ class Institution(BaseModel): ror: StrictStr | None = Field(default=None, description="The ROR ID for this institution. This is the Canonical External ID for institutions.") display_name: StrictStr | None = Field(default=None, description="The primary name of the institution.") country_code: StrictStr | None = Field(default=None, description="ISO two-letter country code where this institution is located.") - type: StrictStr | None = Field(default=None, description="The institution's primary type (ROR vocabulary): `Education`, `Healthcare`, `Company`, `Archive`, `Nonprofit`, `Government`, `Facility`, `Other`.") + type: StrictStr | None = Field(default=None, description="The institution's primary type (ROR vocabulary): `Education`, `Healthcare`, `Company`, `Archive`, `Nonprofit`, `Government`, `Facility`, `Other`, `Funder`.") homepage_url: StrictStr | None = Field(default=None, description="URL for the institution's primary homepage.") image_url: StrictStr | None = Field(default=None, description="URL for an image representing this institution (usually from Wikimedia).") image_thumbnail_url: StrictStr | None = Field(default=None, description="Smaller version of `image_url`.") @@ -61,8 +61,9 @@ class Institution(BaseModel): if value is None: return value - if value not in set(['education', 'healthcare', 'company', 'archive', 'nonprofit', 'government', 'facility', 'other']): - raise ValueError("must be one of enum values ('education', 'healthcare', 'company', 'archive', 'nonprofit', 'government', 'facility', 'other')") + valid_types = {'education', 'healthcare', 'company', 'archive', 'nonprofit', 'government', 'facility', 'other', 'funder'} + if value not in valid_types: + return 'other' return value model_config = ConfigDict( diff --git a/service/src/main/inse/models/projects_dfg_v2/project/dfg_project.py b/service/src/main/inse/models/projects_dfg_v2/project/dfg_project.py index 8ae70f97..8d874a7e 100644 --- a/service/src/main/inse/models/projects_dfg_v2/project/dfg_project.py +++ b/service/src/main/inse/models/projects_dfg_v2/project/dfg_project.py @@ -49,7 +49,6 @@ class DFGProject(BaseModel): equipment_group: StrictStr | None = None equipment_name: StrictStr | None = None external_link: StrictStr | None = None - fachgebiete: list[DFGProjectFachgebieteInner] | None = None fetched_at: datetime | None = None final_report_abstract_de: StrictStr | None = None final_report_abstract_en: StrictStr | None = None @@ -81,7 +80,7 @@ class DFGProject(BaseModel): publications: list[DFGProjectPublicationsInner] | None = None subject_area_de: StrictStr | None = None subject_area_en: StrictStr | None = None - subject_classifications: DFGProjectFachgebieteInner | None = None + subject_classifications: list[DFGProjectFachgebieteInner] | None = None subproject_order: list[StrictStr] | None = None subprojects: list[DFGProjectSubprojectsInner] | None = None template_type: StrictStr | None = None @@ -90,7 +89,7 @@ class DFGProject(BaseModel): website_html_de: StrictStr | None = None website_html_en: StrictStr | None = None topics: list[Topic] | None = None - __properties: ClassVar[list[str]] = ["abstract_de", "abstract_en", "equipment_group", "equipment_name", "external_link", "fachgebiete", "fetched_at", "final_report_abstract_de", "final_report_abstract_en", "funding_end", "funding_period_de", "funding_period_en", "funding_start", "funding_type_de", "funding_type_en", "funding_type_key", "funding_type_sort", "id", "institution_roles_order", "institutions", "international_relation_de", "international_relation_en", "is_transfer_project", "link", "page_url", "parent_project_id", "parent_title_de", "parent_title_en", "person_roles_order", "persons", "project", "project_id", "project_identifier_de", "project_identifier_en", "publications", "subject_area_de", "subject_area_en", "subject_classifications", "subproject_order", "subprojects", "template_type", "title_de", "title_en", "website_html_de", "website_html_en"] + __properties: ClassVar[list[str]] = ["abstract_de", "abstract_en", "equipment_group", "equipment_name", "external_link","fetched_at", "final_report_abstract_de", "final_report_abstract_en", "funding_end", "funding_period_de", "funding_period_en", "funding_start", "funding_type_de", "funding_type_en", "funding_type_key", "funding_type_sort", "id", "institution_roles_order", "institutions", "international_relation_de", "international_relation_en", "is_transfer_project", "link", "page_url", "parent_project_id", "parent_title_de", "parent_title_en", "person_roles_order", "persons", "project", "project_id", "project_identifier_de", "project_identifier_en", "publications", "subject_area_de", "subject_area_en", "subject_classifications", "subproject_order", "subprojects", "template_type", "title_de", "title_en", "website_html_de", "website_html_en"] model_config = ConfigDict( validate_by_name=True, @@ -131,13 +130,6 @@ class DFGProject(BaseModel): exclude=excluded_fields, exclude_none=True, ) - # override the default output from pydantic by calling `to_dict()` of each item in fachgebiete (list) - _items = [] - if self.fachgebiete: - for _item_fachgebiete in self.fachgebiete: - if _item_fachgebiete: - _items.append(_item_fachgebiete.to_dict()) - _dict['fachgebiete'] = _items # override the default output from pydantic by calling `to_dict()` of each item in institutions (list) _items = [] if self.institutions: @@ -164,7 +156,7 @@ class DFGProject(BaseModel): _dict['publications'] = _items # override the default output from pydantic by calling `to_dict()` of subject_classifications if self.subject_classifications: - _dict['subject_classifications'] = self.subject_classifications.to_dict() + _dict['subject_classifications'] = [f.to_dict() for f in self.subject_classifications] # override the default output from pydantic by calling `to_dict()` of each item in subprojects (list) _items = [] if self.subprojects: @@ -191,14 +183,12 @@ class DFGProject(BaseModel): key=lambda t: t.get("rank") if t.get("rank") is not None else float("inf"), ) topics = [cls._topic_from_match(t) for t in sorted_topics_raw] - _obj = cls.model_validate({ "abstract_de": obj.get("abstract_de"), "abstract_en": obj.get("abstract_en"), "equipment_group": obj.get("equipment_group"), "equipment_name": obj.get("equipment_name"), "external_link": obj.get("external_link"), - "fachgebiete": [DFGProjectFachgebieteInner.from_dict(_item) for _item in obj["fachgebiete"]] if obj.get("fachgebiete") is not None else None, "fetched_at": obj.get("fetched_at"), "final_report_abstract_de": obj.get("final_report_abstract_de"), "final_report_abstract_en": obj.get("final_report_abstract_en"), @@ -230,7 +220,7 @@ class DFGProject(BaseModel): "publications": [DFGProjectPublicationsInner.from_dict(_item) for _item in obj["publications"]] if obj.get("publications") is not None else None, "subject_area_de": obj.get("subject_area_de"), "subject_area_en": obj.get("subject_area_en"), - "subject_classifications": DFGProjectFachgebieteInner.from_dict(obj["subject_classifications"]) if obj.get("subject_classifications") is not None else None, + "subject_classifications": [DFGProjectFachgebieteInner.from_dict(f) for f in (obj.get("subject_classifications") or [])], "subproject_order": obj.get("subproject_order"), "subprojects": [DFGProjectSubprojectsInner.from_dict(_item) for _item in obj["subprojects"]] if obj.get("subprojects") is not None else None, "template_type": obj.get("template_type"), diff --git a/service/src/main/inse/news/logic.py b/service/src/main/inse/news/logic.py index 9e07315b..da4ca3eb 100644 --- a/service/src/main/inse/news/logic.py +++ b/service/src/main/inse/news/logic.py @@ -27,7 +27,6 @@ TOPIC_NUM_CANDIDATES = 100 TOPIC_SIMILARITY = 0.5 TOPICS_INDEX = "aktuell_openalex_topics" -TOPICS_INDEX_MAX_PAIRS = 100 _SESSION_TOPIC_CACHE: dict[str, list] = {} @@ -48,6 +47,11 @@ RELATED_BLOCK_SIZE = 5 RELATED_TOPIC_K = 1 EXACT_ID_CAP = 1000 +KEYWORD_SEARCH_FIELDS = ["maintitle^3", "intro_content^2", "tags^2", "full_content"] +KEYWORD_SEARCH_SCAN_CAP = 50000 +KEYWORD_SEARCH_ID_CAP = 2000 +TOPIC_DOCS_PER_ARTICLE = 25 + async def get_news_page( page: int, @@ -127,6 +131,206 @@ async def search_news( return news_page +async def search_news_by_keywords( + keywords: list | None = None, + topic_ids: list | None = None, + filter_topic_ids: list | None = None, + fuzzy: bool = False, + page: int = 1, + page_size: int = 10, + year_from: int | None = None, + year_to: int | None = None, + relevance_values: list | None = None, + sort_order: str | None = None, +) -> NewsPage: + """Searches the news for the keywords of a keywords-search run. + + `fuzzy` resolves the keywords to OpenAlex topics (via the aktuell_openalex_topics index), + otherwise the raw keywords are matched as phrases against the article + text. The individual keywords are OR-ed rather than AND-ed. + An article carries at most KEYWORD_LIMIT keywords, so requiring all of them + would leave every multi-keyword search empty. + Articles matching more of them simply rank higher. + + A fuzzy search without any resolved topic ids falls back to the raw + keywords. Once there are topic ids the fallback is off: a topic search that matches no article + stays empty instead of silently returning keyword hits. + + By default results stay ranked by match strength (Elasticsearch's + `_score`). Passing `sort_order` ('asc'/'desc') overrides that with a + plain date sort, same as the plain news list. + """ + wanted_topic_ids: set = set() + if fuzzy: + wanted_topic_ids = { + topic_id + for topic_id in (topic_ids or []) + (filter_topic_ids or []) + if topic_id + } + + if wanted_topic_ids: + should = await _topic_id_should_clauses(wanted_topic_ids) + else: + should = _keyword_should_clauses(keywords) + + if not should: + return _empty_page(page, page_size) + + clauses = await _filter_clauses(year_from, year_to, relevance_values) + query = { + "bool": { + "should": should, + "minimum_should_match": 1, + "filter": clauses, + } + } + + highlight = { + "fields": {"full_content": {"fragment_size": 200, "number_of_fragments": 1}}, + "pre_tags": [""], + "post_tags": [""], + "encoder": "html", + } + + sort = [{"date_full": sort_order}] if sort_order in ("asc", "desc") else None + + response = await _run_search( + query=query, + source=["date", "maintitle", "author", "url", "intro_content", "full_content"], + size=page_size, + offset=(page - 1) * page_size, + sort=sort, + highlight=None if wanted_topic_ids else highlight, + ) + + news_page = await _build_page(response, page, page_size) + await _attach_topics(news_page.results) + + return news_page + + +def _keyword_should_clauses(keywords: list | None) -> list: + return [ + { + "multi_match": { + "query": keyword.strip(), + "fields": KEYWORD_SEARCH_FIELDS, + "type": "phrase", + } + } + for keyword in (keywords or []) + if keyword and keyword.strip() + ] + + +async def _topic_id_should_clauses(topic_ids: set) -> list: + """Turns matched OpenAlex topics into id clauses, boosted by hit count. + + Articles that match several of the searched topics get a higher boost, so + Elasticsearch ranks them above articles that only match one. + """ + topics_per_article = await _news_ids_by_topic_ids(topic_ids) + if not topics_per_article: + return [] + + ranked = sorted(topics_per_article.items(), key=lambda item: -len(item[1])) + ids_by_hit_count: dict[int, list] = {} + for news_id, matched_topics in ranked[:KEYWORD_SEARCH_ID_CAP]: + ids_by_hit_count.setdefault(len(matched_topics), []).append(news_id) + + return [ + {"ids": {"values": news_ids, "boost": float(hit_count)}} + for hit_count, news_ids in ids_by_hit_count.items() + ] + + +async def _news_ids_by_topic_ids(topic_ids: set) -> dict: + """Returns news_id -> set of searched topic ids the article was mapped to.""" + query = {"terms": {"topic_matches.topic_id.keyword": sorted(topic_ids)}} + + topics_per_article: dict[str, set] = {} + scanned = 0 + try: + async for hit in elasticsearch.scan( + index=TOPICS_INDEX, + query=query, + source=["news_id", "topic_matches.topic_id"], + cluster="inse", + ): + scanned += 1 + source = hit.get("_source", {}) + news_id = source.get("news_id") + if news_id: + matched = topics_per_article.setdefault(news_id, set()) + for match in source.get("topic_matches") or []: + topic_id = match.get("topic_id") + if topic_id in topic_ids: + matched.add(topic_id) + if scanned >= KEYWORD_SEARCH_SCAN_CAP: + logger.warning( + f"Topic lookup hit the scan cap of {KEYWORD_SEARCH_SCAN_CAP} documents." + ) + break + except Exception: + logger.exception("Topic lookup for the keyword news search failed.") + return {} + + return {news_id: matched for news_id, matched in topics_per_article.items() if matched} + + +async def _attach_topics(articles: list) -> None: + news_ids = [article.id for article in articles if article.id] + if not news_ids: + return + + topics_per_article = await _topics_for_news_ids(news_ids) + for article in articles: + article.topics = topics_per_article.get(article.id, []) + + +async def _topics_for_news_ids(news_ids: list) -> dict[str, list[MatchedTopic]]: + """Reads the indexed OpenAlex topic matches for the given articles.""" + try: + response = await elasticsearch.search( + index=TOPICS_INDEX, + query={"terms": {"news_id.keyword": news_ids}}, + source=["news_id", "keyword", "topic_matches"], + size=min(len(news_ids) * TOPIC_DOCS_PER_ARTICLE, 10000), + cluster="inse", + ) + except Exception: + logger.exception("Batched topic lookup for the news result page failed.") + return {} + + topics_per_article: dict[str, list[MatchedTopic]] = {} + seen_per_article: dict[str, set] = {} + for hit in response.get("hits", {}).get("hits", []): + source = hit.get("_source", {}) + news_id = source.get("news_id") + if not news_id: + continue + keyword = source.get("keyword") + matched = topics_per_article.setdefault(news_id, []) + seen_ids = seen_per_article.setdefault(news_id, set()) + for match in source.get("topic_matches") or []: + topic_id = match.get("topic_id") + if not topic_id or topic_id in seen_ids: + continue + seen_ids.add(topic_id) + matched.append( + MatchedTopic( + id=topic_id, + display_name=match.get("topic_display_name"), + subfield_name=match.get("subfield"), + field_name=match.get("field"), + domain_name=match.get("domain"), + source_keyword=keyword, + ) + ) + + return topics_per_article + + async def get_news_by_author( author_id: str, page: int = 1, @@ -321,7 +525,7 @@ async def _get_article_keywords( async def _get_article_topics(news_id: str, keywords: list) -> list: - indexed = await get_article_topics_from_index(news_id) + indexed = (await _topics_for_news_ids([news_id])).get(news_id, []) if indexed: return indexed @@ -336,42 +540,6 @@ async def _get_article_topics(news_id: str, keywords: list) -> list: return topics -async def get_article_topics_from_index(news_id: str) -> list: - try: - response = await elasticsearch.search( - index=TOPICS_INDEX, - query={"term": {"news_id.keyword": news_id}}, - source=["keyword", "topic_matches"], - size=TOPICS_INDEX_MAX_PAIRS, - cluster="inse", - ) - except Exception: - logger.exception(f"Topic-index lookup for {news_id} failed.") - return [] - - matched = [] - seen_ids = set() - for hit in response.get("hits", {}).get("hits", []): - source = hit.get("_source", {}) - keyword = source.get("keyword") - for match in source.get("topic_matches") or []: - topic_id = match.get("topic_id") - if not topic_id or topic_id in seen_ids: - continue - seen_ids.add(topic_id) - matched.append( - MatchedTopic( - id=topic_id, - display_name=match.get("topic_display_name"), - subfield_name=match.get("subfield"), - field_name=match.get("field"), - domain_name=match.get("domain"), - source_keyword=keyword, - ) - ) - return matched - - def _normalize_keywords(candidates: list) -> list: """Trims, dedups (case-insensitive) and caps the keywords from the LLM.""" seen = set() @@ -516,7 +684,7 @@ async def _get_postproc_labels(news_id: str) -> tuple[bool | None, list, list, s return relevant, authors, keywords, hit.get("_id") -async def _run_search(query: dict, source: list, size: int, offset: int, sort, highlight: dict = None) -> dict: +async def _run_search(query: dict, source: list, size: int, offset: int, sort, highlight: dict | None = None) -> dict: try: return await elasticsearch.search( index="aktuell", diff --git a/service/src/main/inse/news/model.py b/service/src/main/inse/news/model.py index 8ce160de..dd688444 100644 --- a/service/src/main/inse/news/model.py +++ b/service/src/main/inse/news/model.py @@ -8,17 +8,6 @@ class NewsKeywords(BaseModel): keywords: list[str] = Field(description="The extracted keywords from the article.") -class NewsArticle(BaseModel): - id: str - date: str | None = None - maintitle: str | None = None - author: str | None = None - url: str | None = None - relevant: bool | None = None - snippet: str | None = None - related: bool | None = None - - class MentionedPerson(BaseModel): name: str is_ude: bool = False @@ -34,6 +23,18 @@ class MatchedTopic(BaseModel): source_keyword: str | None = None +class NewsArticle(BaseModel): + id: str + date: str | None = None + maintitle: str | None = None + author: str | None = None + url: str | None = None + relevant: bool | None = None + snippet: str | None = None + related: bool | None = None + topics: list[MatchedTopic] | None = None + + class NewsArticleDetail(NewsArticle): full_content: str | None = None relevant: bool | None = None diff --git a/service/src/main/inse/news/service.py b/service/src/main/inse/news/service.py index 74f300b9..eeeeb564 100644 --- a/service/src/main/inse/news/service.py +++ b/service/src/main/inse/news/service.py @@ -100,6 +100,68 @@ async def search_news( ) +@router.get( + "/keyword/search", + operation_id="getNewsByKeywords", + response_model=NewsPage, + response_model_exclude_none=True, + summary="Searches news articles by the keywords or matched topics of a keywords search.", + tags=[Tags.NEWS], +) +async def search_news_by_keywords( + keywords: Annotated[ + list[str] | None, Query(description="Raw keywords to match against title/content.") + ] = None, + topic_ids: Annotated[ + list[str] | None, + Query(alias="topicIds", description="OpenAlex topic ids the keywords resolved to."), + ] = None, + filter_topic_ids: Annotated[ + list[str] | None, + Query(alias="filterTopicIds", description="Additional topic ids to narrow the results by."), + ] = None, + fuzzy: Annotated[ + bool, + Query(description="Search by resolved topics if True, otherwise by raw keywords."), + ] = False, + page: Annotated[ + int, Query(description="Page number (1-based).", ge=1) + ] = 1, + page_size: Annotated[ + int, Query(alias="pageSize", description="Articles per page.", ge=1, le=100) + ] = 10, + relevance: Annotated[ + str | None, Query(description="Comma-separated relevance filter: 'relevant', 'not_relevant'.") + ] = None, + year_from: Annotated[ + int | None, Query(alias="yearFrom", description="Earliest publication year (inclusive).", ge=0) + ] = None, + year_to: Annotated[ + int | None, Query(alias="yearTo", description="Latest publication year (inclusive).", ge=0) + ] = None, + sort_order: Annotated[ + str | None, + Query( + alias="sortOrder", + description="Overrides relevance ranking with a date sort: 'desc' (newest first) or 'asc' (oldest first).", + pattern="^(asc|desc)$", + ), + ] = None, +): + return await logic.search_news_by_keywords( + keywords=keywords or [], + topic_ids=topic_ids or [], + filter_topic_ids=filter_topic_ids or [], + fuzzy=fuzzy, + page=page, + page_size=page_size, + sort_order=sort_order, + year_from=year_from, + year_to=year_to, + relevance_values=_parse_relevance(relevance), + ) + + @router.get( "/by-author", operation_id="getNewsByAuthor", 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/patents/keywords/logic.py b/service/src/main/inse/patents/keywords/logic.py index 01e06de2..138602cb 100644 --- a/service/src/main/inse/patents/keywords/logic.py +++ b/service/src/main/inse/patents/keywords/logic.py @@ -1,4 +1,4 @@ -"""Find patents for extracted OpenAlex keywords via patents_openalex_keywords index.""" +"""Find patents for extracted OpenAlex keywords via IPC/CPC reverse lookup.""" from __future__ import annotations import asyncio @@ -31,7 +31,6 @@ from inse.patents.ipc_lookup import ( ) from inse.patents.ipc_search_client import IpcSearchClient from inse.patents.keywords.model import ( - KeywordEvidence, KeywordPatentMappingStatus, KeywordPatentMatch, KeywordPatentSearchDiagnostics, @@ -76,13 +75,7 @@ _MIN_LEADER_RELATIVE_MASS = 0.20 _MIN_LEADER_MASS_RATIO = 1.5 _TARGET_CUMULATIVE_CLUSTER_MASS = 0.75 _MIN_PATENT_MATCH_SCORE = 0.50 -_MIN_TEXT_PATENT_MATCH_SCORE = 0.30 _DEFAULT_SCORE_WEIGHTS = {"ipc": 0.60, "topic": 0.25, "text": 0.15} -# When IPC mapping is abstained, score only topic + text evidence. -_TEXT_SCORE_WEIGHTS = {"ipc": 0.0, "topic": 0.45, "text": 0.55} -# Also try title/abstract search when IPC mapping produced terms but scoring -# returned no patents (empty retrieval or over-filtering). -_TEXT_SEARCH_AFTER_EMPTY_IPC = True _TOPIC_SCORE_TOPIC_ID = 1.0 _TOPIC_SCORE_SUBFIELD = 0.7 _TOPIC_SCORE_COMPATIBLE_FIELD = 0.3 @@ -618,12 +611,6 @@ class TopicEvidence: score: float -@dataclass(frozen=True) -class TextGateDecision: - accepted: bool - reason: str - - def _compute_topic_evidence( patent_topics: list[MappedOpenAlexTopic], keyword_topic_ids: frozenset[str], @@ -702,16 +689,6 @@ def _tokenize_words(text: str) -> list[str]: return re.findall(r"[a-z0-9äöüß]+", (text or "").casefold()) -def _contains_token_sequence(haystack: list[str], needle: list[str]) -> bool: - if not needle or len(needle) > len(haystack): - return False - width = len(needle) - for index in range(len(haystack) - width + 1): - if haystack[index : index + width] == needle: - return True - return False - - def _token_set(tokens: list[str]) -> set[str]: return set(tokens) @@ -735,23 +712,6 @@ def _text_search_terms(items: list[KeywordPatentSearchItem]) -> list[str]: return terms -def _text_search_phrases(items: list[KeywordPatentSearchItem]) -> list[str]: - """Full phrases for ES title/abstract retrieval (text path).""" - phrases: list[str] = [] - seen: set[str] = set() - for item in items: - for value in (item.keyword, item.topic_display_name): - cleaned = " ".join((value or "").strip().split()) - if len(cleaned) < 3: - continue - key = cleaned.casefold() - if key in seen: - continue - seen.add(key) - phrases.append(cleaned) - return phrases - - def _text_overlap_score( patent: model.PatentEntry, search_terms: list[str], @@ -772,173 +732,6 @@ def _text_overlap_score( return min(hits / 3, 1.0) -def _text_match_kind( - *, - phrase_in_title: bool, - phrase_in_abstract: bool, - full_token_match: bool, - partial_token_match: bool, -) -> str: - if phrase_in_title: - return "phrase_title" - if phrase_in_abstract: - return "phrase_abstract" - if full_token_match: - return "full_token" - if partial_token_match: - return "partial_token" - return "none" - - -def _collect_keyword_text_evidence( - patent: model.PatentEntry, - phrases: list[str], - search_terms: list[str], -) -> KeywordEvidence: - """Record phrase / full-token / partial-token evidence separately.""" - title_tokens = _tokenize_words(patent.title or "") - abstract_tokens = _tokenize_words(patent.abstract or "") - combined_tokens = _token_set(title_tokens + abstract_tokens) - - phrase_in_title = False - phrase_in_abstract = False - full_token_match = False - partial_token_match = False - matched_phrases: list[str] = [] - - for phrase in phrases: - phrase_tokens = _tokenize_words(phrase) - if not phrase_tokens: - continue - if _contains_token_sequence(title_tokens, phrase_tokens): - phrase_in_title = True - matched_phrases.append(phrase) - elif _contains_token_sequence(abstract_tokens, phrase_tokens): - phrase_in_abstract = True - matched_phrases.append(phrase) - - present = [token for token in phrase_tokens if token in combined_tokens] - if present and len(present) == len(phrase_tokens): - full_token_match = True - elif present: - partial_token_match = True - - matched_words = [term for term in search_terms if term in combined_tokens] - if matched_words and not full_token_match and not partial_token_match: - # Lone search-term hits without a covering phrase count as partial. - partial_token_match = True - - word_match_score = ( - min(len(matched_words) / 3, 1.0) if search_terms and matched_words else 0.0 - ) - kind = _text_match_kind( - phrase_in_title=phrase_in_title, - phrase_in_abstract=phrase_in_abstract, - full_token_match=full_token_match, - partial_token_match=partial_token_match, - ) - - return KeywordEvidence( - phrase_in_title=phrase_in_title, - phrase_in_abstract=phrase_in_abstract, - full_token_match=full_token_match, - partial_token_match=partial_token_match, - word_match_score=round(word_match_score, 4), - matched_phrases=list(dict.fromkeys(matched_phrases)), - matched_words=matched_words, - text_match_kind=kind, - ) - - -def _keyword_text_score(evidence: KeywordEvidence) -> float: - if evidence.phrase_in_title: - return 1.0 - if evidence.phrase_in_abstract: - return 0.85 - if evidence.full_token_match: - return 0.55 - if evidence.partial_token_match: - return 0.25 - return 0.0 - - -def _exact_topic_or_subfield_match( - patent_topics: list[MappedOpenAlexTopic], - keyword_topic_ids: frozenset[str], - keyword_subfield_names: frozenset[str], -) -> bool: - evidence = _compute_topic_evidence( - patent_topics, - keyword_topic_ids, - keyword_subfield_names, - frozenset(), - ) - return evidence.match_kind in {"topic_id", "subfield"} - - -def _keyword_text_passes_relevance_gate( - evidence: KeywordEvidence, - *, - topic_evidence: TopicEvidence, -) -> TextGateDecision: - """Keyword text acceptance policy (no domain hardcoding). - - Accept: - - phrase in title (strong) - - phrase in abstract (medium) - - exact topic/subfield together with full token text evidence - Reject: - - partial/general words alone - - compatible field alone - - exact topic/subfield without text evidence - """ - exact = topic_evidence.match_kind in {"topic_id", "subfield"} - - if evidence.phrase_in_title: - return TextGateDecision(True, "phrase_in_title") - if evidence.phrase_in_abstract: - return TextGateDecision(True, "phrase_in_abstract") - if exact and evidence.full_token_match: - return TextGateDecision( - True, - f"{topic_evidence.match_kind}_with_full_token_match", - ) - if exact and evidence.partial_token_match: - return TextGateDecision(False, "exact_topic_with_partial_tokens_only") - if exact: - return TextGateDecision(False, "exact_topic_without_text") - if topic_evidence.match_kind == "compatible_field": - return TextGateDecision(False, "compatible_field_only") - if evidence.partial_token_match or evidence.matched_words: - return TextGateDecision(False, "partial_or_loose_words_only") - return TextGateDecision(False, "insufficient_evidence") - - -def _matched_keyword_labels_from_evidence( - items: list[KeywordPatentSearchItem], - evidence: KeywordEvidence, -) -> list[str]: - matched: list[str] = [] - seen: set[str] = set() - phrase_keys = {phrase.casefold() for phrase in evidence.matched_phrases} - word_keys = set(evidence.matched_words) - - for item in items: - for value in (item.keyword, item.topic_display_name): - label = (value or "").strip() - if not label: - continue - key = label.casefold() - if key in seen: - continue - label_tokens = _tokenize_words(label) - if key in phrase_keys or any(token in word_keys for token in label_tokens): - seen.add(key) - matched.append(label) - break - return matched - - def _patent_passes_relevance_gate( patent_topics: list[MappedOpenAlexTopic], *, @@ -1261,210 +1054,6 @@ async def _score_patents_with_ipc( } -async def _score_patents_text_search( - *, - raw_patents: list[model.PatentEntry], - search_keywords: list[KeywordPatentSearchItem], - phrases: list[str], - text_search_terms: list[str], - keyword_topic_ids: frozenset[str], - keyword_subfield_names: frozenset[str], - keyword_soft_field_names: frozenset[str], - resolver: PatentOpenAlexMappingResolver, -) -> tuple[list[KeywordPatentMatch], dict[str, int]]: - """Score patents without IPC using graded topic + structured text evidence.""" - patent_topics_by_key = await resolver.resolve_topics_for_patents(raw_patents) - scored: list[KeywordPatentMatch] = [] - filtered_by_relevance_gate = 0 - filtered_by_min_score = 0 - passed_relevance_gate = 0 - - for patent in raw_patents: - patent_topics = patent_topics_by_key.get(patent_map_key(patent), []) - evidence = _collect_keyword_text_evidence(patent, phrases, text_search_terms) - topic_evidence = _compute_topic_evidence( - patent_topics, - keyword_topic_ids, - keyword_subfield_names, - keyword_soft_field_names, - ) - decision = _keyword_text_passes_relevance_gate( - evidence, - topic_evidence=topic_evidence, - ) - if not decision.accepted: - filtered_by_relevance_gate += 1 - logger.info( - "Text reject: id=%s title=%s topic_kind=%s topic_score=%.2f " - "text_kind=%s phrase_title=%s phrase_abstract=%s " - "full_token=%s partial_token=%s reason=%s", - patent.patent_id, - patent.title, - topic_evidence.match_kind, - topic_evidence.score, - evidence.text_match_kind, - evidence.phrase_in_title, - evidence.phrase_in_abstract, - evidence.full_token_match, - evidence.partial_token_match, - decision.reason, - ) - continue - - passed_relevance_gate += 1 - text_score = _keyword_text_score(evidence) - # Field-only remains a weak ranking signal when already accepted via phrase. - score = _compute_final_score( - 0.0, - topic_evidence.score, - text_score, - weights=_TEXT_SCORE_WEIGHTS, - ) - if score < _MIN_TEXT_PATENT_MATCH_SCORE: - filtered_by_min_score += 1 - logger.info( - "Text reject: id=%s reason=below_min_score score=%.4f", - patent.patent_id, - score, - ) - continue - - logger.info( - "Text accept: id=%s title=%s topic_kind=%s topic_score=%.2f " - "text_kind=%s text_score=%.2f final_score=%.4f reason=%s", - patent.patent_id, - patent.title, - topic_evidence.match_kind, - topic_evidence.score, - evidence.text_match_kind, - text_score, - score, - decision.reason, - ) - scored.append( - KeywordPatentMatch( - patent=patent, - match_score=score, - ipc_score=0.0, - topic_score=topic_evidence.score, - text_score=text_score, - matched_keywords=_matched_keyword_labels_from_evidence( - search_keywords, - evidence, - ), - matched_ipc_symbols=[], - text_retrieval=True, - keyword_evidence=evidence, - topic_match_kind=topic_evidence.match_kind, - ) - ) - - logger.info( - "Keyword patent text search: filtered_by_relevance_gate=%d " - "filtered_by_min_score=%d passed_relevance_gate=%d scored=%d", - filtered_by_relevance_gate, - filtered_by_min_score, - passed_relevance_gate, - len(scored), - ) - return scored, { - "filtered_by_relevance_gate": filtered_by_relevance_gate, - "filtered_by_min_score": filtered_by_min_score, - "passed_relevance_gate": passed_relevance_gate, - } - - -async def _search_patents_text_search( - *, - client: BasePatentSearchClient, - queries: IpcPatentSearchQueries, - ipc_search: IpcSearchClient, - resolver: PatentOpenAlexMappingResolver, - search_keywords: list[KeywordPatentSearchItem], - keyword_topic_ids: frozenset[str], - keyword_subfield_names: frozenset[str], - keyword_soft_field_names: frozenset[str], - mapping_status: KeywordPatentMappingStatus, - ipc_cluster_selections: list[dict] | None = None, -) -> PatentsByKeywordsResponse: - cluster_dicts = list(ipc_cluster_selections or []) - phrases = _text_search_phrases(search_keywords) - text_search_terms = _text_search_terms(search_keywords) - if not phrases: - logger.info( - "Keyword patent text search: no phrases for keywords %s", - [item.keyword for item in search_keywords], - ) - return PatentsByKeywordsResponse( - patent_count=0, - patents=[], - mapping_status="no_patents_found", - diagnostics=_empty_diagnostics( - search_path="text", - ipc_cluster_selections=cluster_dicts, - ), - ) - - logger.info( - "Keyword patent text search: mapping_status=%s phrases=%s", - mapping_status, - phrases, - ) - raw_patents = await _fetch_patents_for_queries( - client, - queries.epo_query_by_text_phrases(phrases, size=_MAX_PATENTS), - queries.uspto_query_by_text_phrases(phrases, size=_MAX_PATENTS), - ) - if raw_patents is None: - return PatentsByKeywordsResponse( - patent_count=0, - patents=[], - mapping_status="search_error", - diagnostics=_empty_diagnostics( - search_path="text", - ipc_cluster_selections=cluster_dicts, - ), - ) - - logger.info("Keyword patent text search: raw_patents=%d", len(raw_patents)) - scored, filter_counts = await _score_patents_text_search( - raw_patents=raw_patents, - search_keywords=search_keywords, - phrases=phrases, - text_search_terms=text_search_terms, - keyword_topic_ids=keyword_topic_ids, - keyword_subfield_names=keyword_subfield_names, - keyword_soft_field_names=keyword_soft_field_names, - resolver=resolver, - ) - scored, diagnostics = _finalize_scored_patents( - scored, - raw_count=len(raw_patents), - filtered_by_ipc=0, - filtered_by_relevance_gate=filter_counts["filtered_by_relevance_gate"], - filtered_by_min_score=filter_counts["filtered_by_min_score"], - passed_relevance_gate=filter_counts["passed_relevance_gate"], - search_path="text", - ipc_cluster_selections=cluster_dicts, - ) - await enrich_patents_classifications([item.patent for item in scored], ipc_search) - - if not scored: - return PatentsByKeywordsResponse( - patent_count=0, - patents=[], - mapping_status="no_patents_found", - diagnostics=diagnostics, - ) - - return PatentsByKeywordsResponse( - patent_count=len(scored), - patents=scored, - mapping_status=mapping_status, - diagnostics=diagnostics, - ) - - async def get_patents_by_keywords( request: PatentsByKeywordsRequest, *, @@ -1528,21 +1117,18 @@ async def get_patents_by_keywords( ) logger.info( "Keyword patent search: no IPC search terms for keywords %s " - "(mapping_status=%s) — trying keyword text search", + "(mapping_status=%s)", [item.keyword for item in search_keywords], mapping_status, ) - return await _search_patents_text_search( - client=client, - queries=queries, - ipc_search=ipc_search, - resolver=resolver, - search_keywords=search_keywords, - keyword_topic_ids=keyword_topic_ids, - keyword_subfield_names=keyword_subfield_names, - keyword_soft_field_names=keyword_soft_field_names, + return PatentsByKeywordsResponse( + patent_count=0, + patents=[], mapping_status=mapping_status, - ipc_cluster_selections=cluster_dicts, + diagnostics=_empty_diagnostics( + search_path="none", + ipc_cluster_selections=cluster_dicts, + ), ) text_search_terms = _text_search_terms(search_keywords) @@ -1594,31 +1180,11 @@ async def get_patents_by_keywords( diagnostics=diagnostics, ) - if not _TEXT_SEARCH_AFTER_EMPTY_IPC: - return PatentsByKeywordsResponse( - patent_count=0, - patents=[], - mapping_status="no_patents_found", - diagnostics=diagnostics, - ) - - logger.info( - "Keyword patent search: IPC path yielded no scored patents — " - "trying keyword text search (policy=_TEXT_SEARCH_AFTER_EMPTY_IPC)" - ) - return await _search_patents_text_search( - client=client, - queries=queries, - ipc_search=ipc_search, - resolver=resolver, - search_keywords=search_keywords, - keyword_topic_ids=keyword_topic_ids, - keyword_subfield_names=keyword_subfield_names, - keyword_soft_field_names=keyword_soft_field_names, - # IPC was selected but produced no usable hits; UI treats this like - # uncertain IPC evidence and labels patents via text_retrieval. - mapping_status="uncertain", - ipc_cluster_selections=cluster_dicts, + return PatentsByKeywordsResponse( + patent_count=0, + patents=[], + mapping_status="no_patents_found", + diagnostics=diagnostics, ) diff --git a/service/src/main/inse/patents/keywords/search_queries.py b/service/src/main/inse/patents/keywords/search_queries.py index c24570f6..780e3903 100644 --- a/service/src/main/inse/patents/keywords/search_queries.py +++ b/service/src/main/inse/patents/keywords/search_queries.py @@ -46,19 +46,12 @@ _USPTO_SOURCE_FIELDS = [ ] _MIN_MATCH_TERM_LEN = 4 -_MIN_TEXT_PHRASE_LEN = 3 # Prefer concrete group/subgroup hits over broad subclass prefixes. _BOOST_SUBGROUP = 4.0 _BOOST_MAIN_GROUP = 2.5 _BOOST_SUBCLASS = 1.0 -# Text search: prefer exact phrases in title over abstract / loose match. -_BOOST_TEXT_PHRASE_TITLE = 5.0 -_BOOST_TEXT_PHRASE_ABSTRACT = 3.0 -_BOOST_TEXT_MATCH_TITLE = 1.5 -_BOOST_TEXT_MATCH_ABSTRACT = 1.0 - def _add_term_boost(weights: dict[str, float], term: str, boost: float) -> None: cleaned = term.strip() @@ -157,76 +150,6 @@ def _ipc_match_clauses(field: str, term_boosts: dict[str, float]) -> list[dict[s return clauses -def _normalize_text_phrases(phrases: list[str]) -> list[str]: - cleaned: list[str] = [] - seen: set[str] = set() - for phrase in phrases: - value = " ".join((phrase or "").strip().split()) - if len(value) < _MIN_TEXT_PHRASE_LEN: - continue - key = value.casefold() - if key in seen: - continue - seen.add(key) - cleaned.append(value) - return cleaned - - -def _text_match_clauses( - phrases: list[str], - *, - title_fields: tuple[str, ...], - abstract_field: str, -) -> list[dict[str, Any]]: - """Build title/abstract should-clauses with phrase boosts over loose match.""" - clauses: list[dict[str, Any]] = [] - for phrase in _normalize_text_phrases(phrases): - for field in title_fields: - clauses.append( - { - "match_phrase": { - field: { - "query": phrase, - "boost": _BOOST_TEXT_PHRASE_TITLE, - } - } - } - ) - clauses.append( - { - "match": { - field: { - "query": phrase, - "operator": "and", - "boost": _BOOST_TEXT_MATCH_TITLE, - } - } - } - ) - clauses.append( - { - "match_phrase": { - abstract_field: { - "query": phrase, - "boost": _BOOST_TEXT_PHRASE_ABSTRACT, - } - } - } - ) - clauses.append( - { - "match": { - abstract_field: { - "query": phrase, - "operator": "and", - "boost": _BOOST_TEXT_MATCH_ABSTRACT, - } - } - } - ) - return clauses - - class IpcPatentSearchQueries: def epo_query_by_ipc_terms( self, @@ -299,55 +222,3 @@ class IpcPatentSearchQueries: size: int = DEFAULT_SEARCH_SIZE, ) -> dict[str, Any]: return self.uspto_query_by_ipc_terms(_merge_term_boosts(symbols), size=size) - - def epo_query_by_text_phrases( - self, - phrases: list[str], - size: int = DEFAULT_SEARCH_SIZE, - ) -> dict[str, Any]: - should = _text_match_clauses( - phrases, - title_fields=("title_en", "title_de"), - abstract_field="abstract", - ) - query: dict[str, Any] = ( - {"match_none": {}} - if not should - else {"bool": {"should": should, "minimum_should_match": 1}} - ) - return { - "size": size, - "track_total_hits": True, - "sort": [ - {"_score": {"order": "desc"}}, - {"date_publication": {"order": "desc", "missing": "_last"}}, - ], - "_source": _PATENT_SOURCE_FIELDS, - "query": query, - } - - def uspto_query_by_text_phrases( - self, - phrases: list[str], - size: int = DEFAULT_SEARCH_SIZE, - ) -> dict[str, Any]: - should = _text_match_clauses( - phrases, - title_fields=("title",), - abstract_field="abstract", - ) - query: dict[str, Any] = ( - {"match_none": {}} - if not should - else {"bool": {"should": should, "minimum_should_match": 1}} - ) - return { - "size": size, - "track_total_hits": True, - "sort": [ - {"_score": {"order": "desc"}}, - {"publication_date": {"order": "desc", "missing": "_last"}}, - ], - "_source": _USPTO_SOURCE_FIELDS, - "query": query, - } diff --git a/service/src/main/inse/patents/keywords/test_logic.py b/service/src/main/inse/patents/keywords/test_logic.py index 4b48aaa4..5bcb3ffd 100644 --- a/service/src/main/inse/patents/keywords/test_logic.py +++ b/service/src/main/inse/patents/keywords/test_logic.py @@ -10,21 +10,17 @@ from inse.patents.authors.ipc_openalex_mapping import MappedOpenAlexTopic from inse.patents.common import model from inse.patents.keywords.logic import ( TopicEvidence, - _aggregate_subclass_clusters, - _collect_keyword_text_evidence, _compute_final_score, _compute_topic_evidence, - _exact_topic_or_subfield_match, _filter_keywords_for_patent_search, _ipc_hierarchy_quality, _keyword_is_patent_searchable, - _keyword_text_passes_relevance_gate, - _keyword_text_score, _patent_passes_relevance_gate, _patent_search_terms, _score_ipc_match, _score_patent, _select_dominant_clusters, + _aggregate_subclass_clusters, _term_from_ipc_match, _text_overlap_score, _text_search_terms, @@ -34,10 +30,6 @@ from inse.patents.keywords.logic import ( get_patents_by_keywords, select_ipc_matches_by_cluster_mass, ) -from inse.patents.keywords.model import ( - KeywordPatentSearchItem, - PatentsByKeywordsRequest, -) from inse.patents.keywords.reverse_lookup import ( IpcCodeMatch, _dedupe_ipc_matches, @@ -45,6 +37,7 @@ from inse.patents.keywords.reverse_lookup import ( _weighted_score, clear_reverse_lookup_caches, ) +from inse.patents.keywords.model import KeywordPatentSearchItem, PatentsByKeywordsRequest from inse.patents.keywords.search_queries import ( IpcPatentSearchQueries, _search_terms_for_symbol, @@ -646,132 +639,6 @@ def test_text_overlap_score_uses_word_boundaries_not_substrings() -> None: assert _text_overlap_score(patent, ["chemistry", "organic"]) == 0.0 -def test_fallback_rejects_mechanical_patent_for_organic_chemistry() -> None: - """Soft field / loose words must not accept a mechanical separator patent.""" - patent = model.PatentEntry( - patent_id="EP-MECH", - source="EPO", - title=( - "Rotating machine for separating materials in different " - "states of aggregation" - ), - abstract="Apparatus for mechanical separation of materials.", - ipc=["B01D45/12"], - ) - phrases = ["Organic Chemistry", "organische Chemie"] - terms = ["organic", "chemistry", "organische", "chemie"] - evidence = _collect_keyword_text_evidence(patent, phrases, terms) - - assert evidence.phrase_in_title is False - assert evidence.phrase_in_abstract is False - assert evidence.full_token_match is False - assert evidence.matched_phrases == [] - assert evidence.matched_words == [] - - field_only = TopicEvidence(match_kind="compatible_field", score=0.3) - assert not _keyword_text_passes_relevance_gate( - evidence, - topic_evidence=field_only, - ).accepted - exact = TopicEvidence(match_kind="topic_id", score=1.0) - assert not _keyword_text_passes_relevance_gate( - evidence, - topic_evidence=exact, - ).accepted - - -def test_fallback_accepts_strong_phrase_or_exact_topic_with_full_tokens() -> None: - phrase_patent = model.PatentEntry( - patent_id="EP-PHRASE", - source="EPO", - title="Process for organic chemistry synthesis", - abstract="Catalytic reactions.", - ) - phrases = ["organic chemistry"] - terms = ["organic", "chemistry"] - evidence = _collect_keyword_text_evidence(phrase_patent, phrases, terms) - assert evidence.phrase_in_title is True - assert evidence.text_match_kind == "phrase_title" - assert _keyword_text_score(evidence) == 1.0 - assert _keyword_text_passes_relevance_gate( - evidence, - topic_evidence=TopicEvidence(match_kind="none", score=0.0), - ).accepted - - full_token_patent = model.PatentEntry( - patent_id="EP-WORDS", - source="EPO", - title="Catalytic organic synthesis method", - abstract="Uses chemistry laboratory techniques.", - ) - full_evidence = _collect_keyword_text_evidence( - full_token_patent, - phrases, - terms, - ) - assert full_evidence.phrase_in_title is False - assert full_evidence.phrase_in_abstract is False - assert full_evidence.full_token_match is True - assert not _keyword_text_passes_relevance_gate( - full_evidence, - topic_evidence=TopicEvidence(match_kind="none", score=0.0), - ).accepted - assert _keyword_text_passes_relevance_gate( - full_evidence, - topic_evidence=TopicEvidence(match_kind="topic_id", score=1.0), - ).accepted - - partial_patent = model.PatentEntry( - patent_id="EP-PARTIAL", - source="EPO", - title="Organic polymer blend", - abstract="Industrial materials processing.", - ) - partial_evidence = _collect_keyword_text_evidence( - partial_patent, - phrases, - terms, - ) - assert partial_evidence.partial_token_match is True - assert partial_evidence.full_token_match is False - decision = _keyword_text_passes_relevance_gate( - partial_evidence, - topic_evidence=TopicEvidence(match_kind="topic_id", score=1.0), - ) - assert not decision.accepted - assert decision.reason == "exact_topic_with_partial_tokens_only" - - assert _exact_topic_or_subfield_match( - [ - MappedOpenAlexTopic( - topic_id="https://openalex.org/TORG", - topic_display_name="Organic Chemistry", - subfield_name="Organic Chemistry", - field_name="Chemistry", - ) - ], - frozenset({"TORG"}), - frozenset({"organic chemistry"}), - ) - - -def test_token_match_rejects_machine_inside_micromachined() -> None: - patent = model.PatentEntry( - patent_id="EP-MICRO", - source="EPO", - title="Micromachined sensor device", - abstract="Fabrication of micromachined structures.", - ) - assert _text_overlap_score(patent, ["machine", "learning"]) == 0.0 - evidence = _collect_keyword_text_evidence( - patent, - ["Machine Learning"], - ["machine", "learning"], - ) - assert evidence.matched_words == [] - assert evidence.full_token_match is False - - def test_patent_passes_relevance_gate_with_text_but_no_topics() -> None: patent = model.PatentEntry( patent_id="EP1", @@ -914,8 +781,7 @@ def test_get_patents_by_keywords_uses_symbol_queries() -> None: uspto_symbols.assert_called_once() assert epo_symbols.call_args.args[0][0] == "C07C243/08" assert "C07C" in epo_symbols.call_args.args[0] - # IPC search returns empty → text fallback also queries EPO/USPTO. - assert captured == ["epo", "uspto", "epo", "uspto"] + assert captured == ["epo", "uspto"] def test_text_search_terms_include_topic_metadata() -> None: @@ -993,64 +859,84 @@ def test_epo_and_uspto_queries_boost_specific_symbols_over_subclass() -> None: assert uspto["sort"][0] == {"_score": {"order": "desc"}} -def test_text_queries_prefer_phrase_match_in_title() -> None: - queries = IpcPatentSearchQueries() - epo = queries.epo_query_by_text_phrases(["organic chemistry"]) - uspto = queries.uspto_query_by_text_phrases(["organic chemistry"]) - - epo_should = epo["query"]["bool"]["should"] - uspto_should = uspto["query"]["bool"]["should"] - - def clause_boost(clauses: list[dict], kind: str, field: str) -> float | None: - for clause in clauses: - payload = clause.get(kind, {}).get(field) - if isinstance(payload, dict) and payload.get("query") == "organic chemistry": - return float(payload.get("boost", 1.0)) - return None - - assert clause_boost(epo_should, "match_phrase", "title_en") == 5.0 - assert clause_boost(epo_should, "match_phrase", "abstract") == 3.0 - assert clause_boost(epo_should, "match", "title_en") == 1.5 - assert clause_boost(uspto_should, "match_phrase", "title") == 5.0 - assert epo["sort"][0] == {"_score": {"order": "desc"}} - - -def test_uncertain_mapping_uses_text_fallback_not_empty_list() -> None: - """Fragmented IPC abstention must fall back to title/abstract search.""" - patent = model.PatentEntry( - patent_id="EP123", - source="EPO", - title="Process for organic chemistry synthesis", - abstract="A catalytic method in organic chemistry.", - publication_date="20240101", - ipc=["C07C243/08"], - cpc=[], +def test_technical_search_failure_returns_search_error_not_no_patents_found() -> None: + request = PatentsByKeywordsRequest( + keywords=[ + KeywordPatentSearchItem( + keyword="organische Chemie", + keyword_level="coarse", + topic_id="https://openalex.org/TORG", + topic_display_name="Organic Chemistry", + field_name="Chemistry", + relevance_score=1.0, + ) + ] ) + ipc_matches = [ + IpcCodeMatch( + "subgroup", + "C07C243/08", + 0.90, + "organische Chemie", + "topic", + "TORG", + ) + ] - async def fake_search_epo(query): - assert "match_phrase" in str(query) or "title_en" in str(query) - return { - "hits": { - "hits": [ - { - "_source": { - "doc_number": "123", - "country": "EP", - "kind": "A1", - "date_publication": "20240101", - "title_en": patent.title, - "abstract": patent.abstract, - "ipc": patent.ipc, - "cpc": [], - } - } - ] - } - } + with patch( + "inse.patents.keywords.logic.KeywordIpcReverseLookup.lookup_ipc_codes", + new=AsyncMock(return_value=ipc_matches), + ), patch( + "inse.patents.keywords.logic.BasePatentSearchClient.search_epo", + new=AsyncMock(side_effect=httpx.HTTPError("boom")), + ), patch( + "inse.patents.keywords.logic.BasePatentSearchClient.search_uspto", + new=AsyncMock(return_value={"hits": {"hits": []}}), + ): + response = asyncio.run(get_patents_by_keywords(request)) - async def fake_search_uspto(query): - return {"hits": {"hits": []}} + assert response.mapping_status == "search_error" + assert response.patent_count == 0 + +def test_no_ipc_search_terms_returns_without_text_fallback() -> None: + """Without usable IPC symbols the search abstains — no title/abstract path.""" + request = PatentsByKeywordsRequest( + keywords=[ + KeywordPatentSearchItem( + keyword="organische Chemie", + keyword_level="coarse", + topic_id="https://openalex.org/TORG", + topic_display_name="Organic Chemistry", + field_name="Chemistry", + relevance_score=1.0, + ) + ] + ) + search_epo = AsyncMock(return_value={"hits": {"hits": []}}) + search_uspto = AsyncMock(return_value={"hits": {"hits": []}}) + + with patch( + "inse.patents.keywords.logic.KeywordIpcReverseLookup.lookup_ipc_codes", + new=AsyncMock(return_value=[]), + ), patch( + "inse.patents.keywords.logic.BasePatentSearchClient.search_epo", + new=search_epo, + ), patch( + "inse.patents.keywords.logic.BasePatentSearchClient.search_uspto", + new=search_uspto, + ): + response = asyncio.run(get_patents_by_keywords(request)) + + assert response.mapping_status == "no_mapping" + assert response.patent_count == 0 + assert response.patents == [] + search_epo.assert_not_called() + search_uspto.assert_not_called() + + +def test_uncertain_ipc_cluster_abstention_returns_without_text_fallback() -> None: + """Fragmented IPC mapping abstains without falling back to text retrieval.""" fragmented = [ IpcCodeMatch( "subgroup", @@ -1074,113 +960,31 @@ def test_uncertain_mapping_uses_text_fallback_not_empty_list() -> None: ) ] ) + search_epo = AsyncMock(return_value={"hits": {"hits": []}}) with patch( "inse.patents.keywords.logic.KeywordIpcReverseLookup.lookup_ipc_codes", new=AsyncMock(return_value=fragmented), ), patch( "inse.patents.keywords.logic.BasePatentSearchClient.search_epo", - new=AsyncMock(side_effect=fake_search_epo), - ), patch( - "inse.patents.keywords.logic.BasePatentSearchClient.search_uspto", - new=AsyncMock(side_effect=fake_search_uspto), - ), patch( - "inse.patents.keywords.logic.PatentOpenAlexMappingResolver.resolve_topics_for_patents", - new=AsyncMock(return_value={}), - ), patch( - "inse.patents.keywords.logic.enrich_patents_classifications", - new=AsyncMock(), - ), patch.object( - IpcPatentSearchQueries, - "epo_query_by_text_phrases", - wraps=IpcPatentSearchQueries().epo_query_by_text_phrases, - ) as epo_text: - response = asyncio.run(get_patents_by_keywords(request)) - - epo_text.assert_called_once() - assert response.mapping_status == "uncertain" - assert response.patent_count == 1 - assert response.patents[0].text_retrieval is True - assert response.patents[0].ipc_score == 0.0 - assert response.patents[0].text_score > 0.0 - assert response.patents[0].matched_ipc_symbols == [] - assert response.patents[0].keyword_evidence is not None - assert response.patents[0].keyword_evidence.phrase_in_title is True - assert response.patents[0].keyword_evidence.text_match_kind == "phrase_title" - - -def test_text_fallback_empty_yields_no_patents_found() -> None: - request = PatentsByKeywordsRequest( - keywords=[ - KeywordPatentSearchItem( - keyword="organische Chemie", - keyword_level="coarse", - topic_id="https://openalex.org/TORG", - topic_display_name="Organic Chemistry", - field_name="Chemistry", - relevance_score=1.0, - ) - ] - ) - - with patch( - "inse.patents.keywords.logic.KeywordIpcReverseLookup.lookup_ipc_codes", - new=AsyncMock(return_value=[]), - ), patch( - "inse.patents.keywords.logic.BasePatentSearchClient.search_epo", - new=AsyncMock(return_value={"hits": {"hits": []}}), + new=search_epo, ), patch( "inse.patents.keywords.logic.BasePatentSearchClient.search_uspto", new=AsyncMock(return_value={"hits": {"hits": []}}), - ), patch( - "inse.patents.keywords.logic.PatentOpenAlexMappingResolver.resolve_topics_for_patents", - new=AsyncMock(return_value={}), - ), patch( - "inse.patents.keywords.logic.enrich_patents_classifications", - new=AsyncMock(), ): response = asyncio.run(get_patents_by_keywords(request)) - assert response.mapping_status == "no_patents_found" + assert response.mapping_status == "uncertain" assert response.patent_count == 0 assert response.patents == [] - - -def test_technical_search_failure_returns_search_error_not_no_patents_found() -> None: - request = PatentsByKeywordsRequest( - keywords=[ - KeywordPatentSearchItem( - keyword="organische Chemie", - keyword_level="coarse", - topic_id="https://openalex.org/TORG", - topic_display_name="Organic Chemistry", - field_name="Chemistry", - relevance_score=1.0, - ) - ] - ) - - with patch( - "inse.patents.keywords.logic.KeywordIpcReverseLookup.lookup_ipc_codes", - new=AsyncMock(return_value=[]), - ), patch( - "inse.patents.keywords.logic.BasePatentSearchClient.search_epo", - new=AsyncMock(side_effect=httpx.HTTPError("boom")), - ), patch( - "inse.patents.keywords.logic.BasePatentSearchClient.search_uspto", - new=AsyncMock(return_value={"hits": {"hits": []}}), - ): - response = asyncio.run(get_patents_by_keywords(request)) - - assert response.mapping_status == "search_error" - assert response.patent_count == 0 + search_epo.assert_not_called() def test_json_lookup_returns_empty_without_mapping(monkeypatch) -> None: clear_reverse_lookup_caches() monkeypatch.setattr( "inse.patents.keywords.reverse_lookup.load_patents_openalex_keywords_json", - dict, + lambda: {}, ) clear_reverse_lookup_caches() 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 c0df87bb..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, @@ -944,6 +960,7 @@ async def search_eu_cordis_projects( sort_by: str = "title", sort_direction: str = "asc", fuzzy: bool = False, + skip_enrichment: bool = False, ) -> EuCordisProjectSearchPage: """ Generic EU CORDIS project search across FP7, H2020 and Horizon Europe. @@ -964,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, @@ -1015,6 +1034,14 @@ async def search_eu_cordis_projects( hits = response.get("hits", {}).get("hits", []) total = response.get("hits", {}).get("total", {}).get("value", 0) + if skip_enrichment: + return EuCordisProjectSearchPage( + elements=[EuCordisProjectSummary.from_hit(hit) for hit in hits], + total=total, + page=page, + size=size, + ) + project_ids_by_type: dict[EuCordisProjectType, list[str]] = defaultdict(list) for hit in hits: @@ -1124,10 +1151,6 @@ async def get_eu_cordis_projects_funding_data( "track_total_hits": False, "_source": ["id", "startDate", "endDate", "ecMaxContribution"], "query": query, - # "id" is unique per project and used elsewhere as a term-filter - # field, so it's mapped as keyword - safe + deterministic sort - # key for search_after pagination across an arbitrarily large - # result set. "sort": [{"id": {"order": "asc", "unmapped_type": "keyword"}}], } if search_after is not None: @@ -1247,68 +1270,6 @@ async def get_openalex_author_ids_by_dois( return result -async def get_openalex_authors_for_cordis_project_ids( - project_ids: list[str], -) -> dict[str, AuthorPage]: - """Returns a mapping of project_id -> AuthorPage for a batch of projects.""" - if not project_ids: - return {} - - query = {"bool": {"filter": [{"terms": {"projectID": project_ids}}]}} - response = await elasticsearch.search( - query=query, - index=ESIndex.CORDIS_EU_PUBLICATIONS_WILDCARD, - cluster=ESCluster.INSE, - source=["projectID", "doi","qaProcessedDoi"], - size=10000, - ) - dois_by_project: dict[str, set[str]] = {} - for hit in response.get("hits", {}).get("hits", []): - source = hit.get("_source", {}) - pid = source.get("projectID") - doi = source.get("doi") - qa_processed_doi = source.get("qaProcessedDoi") - if pid: - dois_by_project.setdefault(pid, set()) - if doi: - dois_by_project[pid].add(doi) - elif qa_processed_doi: - dois_by_project[pid].add(qa_processed_doi) - - all_dois = list({doi for dois in dois_by_project.values() for doi in dois}) - - # single ES call for the whole batch, keyed by raw DOI - author_ids_by_doi = await get_openalex_author_ids_by_dois(dois=all_dois) - - # aggregate per project, dedupe author_ids within a project - author_ids_by_project: dict[str, list[str]] = {} - for pid, dois in dois_by_project.items(): - project_author_ids: set[str] = set() - for doi in dois: - project_author_ids.update(author_ids_by_doi.get(doi, [])) - author_ids_by_project[pid] = list(project_author_ids) - - # single ES call to fetch all Author objects across every project - all_author_ids = list({aid for ids in author_ids_by_project.values() for aid in ids}) - - author_page = await get_authors_by_ids(author_ids=all_author_ids) - authors_by_id = {author.id: author for author in author_page.elements} - - # split the fetched authors back out per project - result: dict[str, AuthorPage] = {} - for pid in project_ids: - ids_for_project = author_ids_by_project.get(pid, []) - authors_for_project = [ - authors_by_id[aid] for aid in ids_for_project if aid in authors_by_id - ] - result[pid] = AuthorPage( - elements=authors_for_project, - total=len(authors_for_project), - page=0, - size=len(authors_for_project), - ) - - return result async def get_openalex_authors_for_projects_ids( project_ids_by_type: dict[EuCordisProjectType, list[str]], @@ -1333,4 +1294,4 @@ async def get_openalex_authors_for_projects_ids( result[(project_type, pid)] = author_pages_by_project_id.get( pid, AuthorPage(elements=[], total=0, page=0, size=0) ) - return result \ No newline at end of file + return result diff --git a/service/src/main/inse/projects/logic.py b/service/src/main/inse/projects/logic.py index 7a37ce66..69c99c61 100644 --- a/service/src/main/inse/projects/logic.py +++ b/service/src/main/inse/projects/logic.py @@ -1,7 +1,8 @@ import logging from collections import defaultdict from typing import Any - +import inse.authors.v2.service as author_service +from inse.auth.model import AccessTokenMetadata from inse.integrations import elasticsearch from inse.model import ESCluster, ESIndex from inse.projects.model import EuCordisProjectType @@ -359,6 +360,53 @@ async def get_person_institutes( } return result +async def get_dfg_institutes_by_ids( + institute_ids: list[int], + ) -> dict[str, dict]: + + if not institute_ids: + return {} + + response = await elasticsearch.search( + index=ESIndex.DFG_INSTITUTES, + cluster=ESCluster.INSE, + body={ + "size": len(institute_ids), + "_source": [ + "institute_id", + "root_id", + "root_name_de", + "root_name_en", + "institute_name_de", + "institute_name_en", + "address_country_de", + "address_country_en", + ], + "query": { + "terms": { + "_id": institute_ids, + } + }, + }, + ) + + result = {} + + for hit in response["hits"]["hits"]: + source = hit["_source"] + + result[source["institute_id"]] = { + "institute_id": source["institute_id"], + "root_id": source.get("root_id"), + "root_name_de": source.get("root_name_de"), + "root_name_en": source.get("root_name_en"), + "institute_name_de": source.get("institute_name_de"), + "institute_name_en": source.get("institute_name_en"), + "address_country_de": source.get("address_country_de"), + "address_country_en": source.get("address_country_en"), + } + return result + #EU Cordis Projects diff --git a/service/src/main/inse/projects/model.py b/service/src/main/inse/projects/model.py index 64dbf6d5..64bfff41 100644 --- a/service/src/main/inse/projects/model.py +++ b/service/src/main/inse/projects/model.py @@ -250,12 +250,41 @@ class DfgProjectSummary(BaseModel): def from_hit(cls, hit: dict) -> "DfgProjectSummary": source = hit.get("_source", {}) fields = hit.get("fields", {}) - + names = [] institutions = {} project_persons = [] - persons = source.get("persons", []) + institutions_raw= source.get("institutions", []) + if isinstance(institutions_raw, list): + for institution in institutions_raw: + if not isinstance(institution, dict): + continue + + institute_id = institution.get("institute_id") + if institute_id is not None: + institutions[f"institute:{institute_id}"] = DfgInstitutionSummary( + id=institute_id, + institute_name_de=institution.get("institute_name_de"), + institute_name_en=institution.get("institute_name_en"), + address_country_de=institution.get("address_country_de"), + address_country_en=institution.get("address_country_en"), + root_id=institution.get("root_id"), + root_name_de=institution.get("root_name_de"), + root_name_en=institution.get("root_name_en"), + ) + root_id = institution.get("root_id") + if root_id is not None: + institutions[f"root:{root_id}"] = DfgInstitutionSummary( + id=root_id, + institute_name_de=institution.get("root_name_de"), + institute_name_en=institution.get("root_name_en"), + address_country_de=institution.get("address_country_de"), + address_country_en=institution.get("address_country_en"), + root_id=None, + root_name_de=None, + root_name_en=None, + ) if isinstance(persons, list): for person in persons: @@ -266,35 +295,35 @@ class DfgProjectSummary(BaseModel): if full_name: names.append(full_name.strip()) + # previously we were creating institution objects for each person, but now we are using the institutions from the institutions_raw list + #institution = None + # if person.get("institute_id") is not None: + # institute = DfgInstitutionSummary( + # id=person["institute_id"], + # institute_name_de=person.get("institute_name_de"), + # institute_name_en=person.get("institute_name_en"), + # address_country_de=person.get("address_country_de"), + # address_country_en=person.get("address_country_en"), + # root_id=None, + # root_name_de=None, + # root_name_en=None, + # ) - institution = None - if person.get("institute_id") is not None: - institute = DfgInstitutionSummary( - id=person["institute_id"], - institute_name_de=person.get("institute_name_de"), - institute_name_en=person.get("institute_name_en"), - address_country_de=person.get("address_country_de"), - address_country_en=person.get("address_country_en"), - root_id=None, - root_name_de=None, - root_name_en=None, - ) + # institutions[f"institute:{person['institute_id']}"] = institute - institutions[f"institute:{person['institute_id']}"] = institute + # if person.get("root_id") is not None: + # root_institution = DfgInstitutionSummary( + # id=person["root_id"], + # institute_name_de=person.get("root_name_de"), + # institute_name_en=person.get("root_name_en"), + # address_country_de=person.get("address_country_de"), + # address_country_en=person.get("address_country_en"), + # root_id=None, + # root_name_de=None, + # root_name_en=None, + # ) - if person.get("root_id") is not None: - root_institution = DfgInstitutionSummary( - id=person["root_id"], - institute_name_de=person.get("root_name_de"), - institute_name_en=person.get("root_name_en"), - address_country_de=person.get("address_country_de"), - address_country_en=person.get("address_country_en"), - root_id=None, - root_name_de=None, - root_name_en=None, - ) - - institutions[f"root:{person['root_id']}"] = root_institution + # institutions[f"root:{person['root_id']}"] = root_institution if person.get("person_id") is not None: project_persons.append( @@ -305,7 +334,7 @@ class DfgProjectSummary(BaseModel): full_name=full_name, role_label_en=person.get("role_label_en"), role_label_de=person.get("role_label_de"), - institution=institution, + institution=None, ) ) topics_raw = source.get("topics") or [] diff --git a/service/src/main/inse/projects/projects_search_client.py b/service/src/main/inse/projects/projects_search_client.py index b6b0a041..924e1e41 100644 --- a/service/src/main/inse/projects/projects_search_client.py +++ b/service/src/main/inse/projects/projects_search_client.py @@ -15,6 +15,7 @@ from inse.projects.logic import ( get_openalex_topics_for_bund_projects, get_openalex_topics_for_dfg_projects, get_person_ids_by_institution_ids, + get_dfg_institutes_by_ids, get_person_institutes, ) from inse.projects.model import ( @@ -194,7 +195,7 @@ async def get_cordis_eu_publications_by_dois(dois: list[str]): _type_: The retrieved publications. """ - query_dois = list({ + query_dois = set({ variant for doi in dois for variant in ( @@ -210,8 +211,8 @@ async def get_cordis_eu_publications_by_dois(dois: list[str]): { "bool": { "should": [ - {"terms": {"doi": query_dois}}, - {"terms": {"qaProcessedDoi": query_dois}}, + {"terms": {"doi": list(query_dois)}}, + {"terms": {"qaProcessedDoi": list(query_dois)}}, ], "minimum_should_match": 1, } @@ -222,6 +223,7 @@ async def get_cordis_eu_publications_by_dois(dois: list[str]): response = await elasticsearch.search( query=query, + size=10000, index=ESIndex.CORDIS_EU_PUBLICATIONS_WILDCARD, cluster=ESCluster.INSE, ) @@ -263,7 +265,7 @@ async def get_dfg_publications_by_dois(dois: list[str]): _type_: The retrieved publications. """ - query_dois = list({ + query_dois = set({ variant for doi in dois for variant in ( @@ -280,7 +282,7 @@ async def get_dfg_publications_by_dois(dois: list[str]): "query": { "terms": { "publications.doi": - query_dois + list(query_dois) } } } @@ -290,7 +292,7 @@ async def get_dfg_publications_by_dois(dois: list[str]): } response = await elasticsearch.search( - size=1000, + size=10000, query=query, index=ESIndex.DFG_PROJECTS, cluster=ESCluster.INSE, @@ -317,7 +319,7 @@ async def get_dfg_project_ids_by_names(names: list[str]) -> list[str]: response = await elasticsearch.search( source=["projects.project_id"], - size=1000, + size=10000, query=query, index=ESIndex.DFG_PERSONS, cluster=ESCluster.INSE, @@ -366,6 +368,9 @@ async def search_dfg_projects( sort_by: str = "id", 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. @@ -411,6 +416,7 @@ async def search_dfg_projects( "subject_area_en", "persons", "subject_classifications", + "institutions", ], "query": {}, } @@ -485,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: @@ -522,34 +533,54 @@ async def search_dfg_projects( ) if not matching_institution_ids: return DfgProjectPage(elements=[], total=0, page=page, size=size) - matching_person_ids = await get_person_ids_by_institution_ids( - institution_ids=matching_institution_ids - ) + #previously we were filtering by person_ids, but now we are filtering by institution_ids directly + # matching_person_ids = await get_person_ids_by_institution_ids( + # institution_ids=matching_institution_ids + # ) + # must_clauses.append( + # { + # "nested": { + # "path": "persons", + # "query": {"terms": {"persons.person_id": matching_person_ids}}, + # } + # } + # ) must_clauses.append( { "nested": { - "path": "persons", - "query": {"terms": {"persons.person_id": matching_person_ids}}, + "path": "institutions", + "query": {"terms": {"institutions.institute_id": matching_institution_ids}}, } } ) + print("MATCHING_INSTITUTION_IDS", matching_institution_ids) if institution_ids: - matching_person_ids = await get_person_ids_by_institution_ids( - institution_ids=institution_ids - ) + #prevously we were filtering by person_ids, but now we are filtering by institution_ids directly + # matching_person_ids = await get_person_ids_by_institution_ids( + # institution_ids=institution_ids + # ) - if not matching_person_ids: - return DfgProjectPage(elements=[], total=0, page=page, size=size) + # if not matching_person_ids: + # return DfgProjectPage(elements=[], total=0, page=page, size=size) + # must_clauses.append( + # { + # "nested": { + # "path": "persons", + # "query": {"terms": {"persons.person_id": matching_person_ids}}, + # } + # } + # ) must_clauses.append( { "nested": { - "path": "persons", - "query": {"terms": {"persons.person_id": matching_person_ids}}, + "path": "institutions", + "query": {"terms": {"institutions.institute_id": institution_ids}}, } } ) + body["query"] = ( {"bool": {"must": must_clauses}} if must_clauses else {"match_all": {}} @@ -584,6 +615,12 @@ async def search_dfg_projects( hits = response.get("hits", {}).get("hits", []) + 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) @@ -599,21 +636,28 @@ async def search_dfg_projects( source = hit["_source"] project_id = source["id"] source["topics"] = topic_lookup.get(str(project_id), []) + institutions = source.get("institutions", []) + for institution in institutions: + institute_id = institution.get("institute_id") + if institute_id is not None: + institute_info = await get_dfg_institutes_by_ids(institute_ids=[institute_id]) + if institute_info: + institution.update(institute_info[institute_id]) persons = source.get("persons", []) for person in persons: person_id = person.get("person_id") institute = person_lookup.get(person_id) - if institute: - person["root_id"] = institute.get("root_id") - person["institute_id"] = institute.get("institute_id") - person["root_name_de"] = institute.get("root_name_de") - person["root_name_en"] = institute.get("root_name_en") - person["institute_name_de"] = institute.get("institute_name_de") - person["institute_name_en"] = institute.get("institute_name_en") - person["address_country_de"] = institute.get("address_country_de") - person["address_country_en"] = institute.get("address_country_en") - + # if institute: + # person["root_id"] = institute.get("root_id") + # person["institute_id"] = institute.get("institute_id") + # person["root_name_de"] = institute.get("root_name_de") + # person["root_name_en"] = institute.get("root_name_en") + # person["institute_name_de"] = institute.get("institute_name_de") + # person["institute_name_en"] = institute.get("institute_name_en") + # person["address_country_de"] = institute.get("address_country_de") + # person["address_country_en"] = institute.get("address_country_en") + return _complete_response_to_dfg_project_page(response, page, size) def _complete_response_to_dfg_project_page( @@ -654,12 +698,128 @@ async def get_dfg_project_by_id(project_id: str) -> DfgProjectDetails | None: ) hits = response.get("hits", {}).get("hits", []) - if hits: - hit = hits[0] - hit["_source"]["topics"] = topic_lookup.get(project_id, []) - details = DfgProjectDetails.from_elastic_hit(hit=hit) - return details - return None + if not hits: + return None + + hit = hits[0] + source = hit["_source"] + source["topics"] = topic_lookup.get(project_id, []) + + persons = source.get("persons", []) + + # --- Enrich persons with institute/root info (mirrors search_dfg_projects) --- + person_ids = { + person["person_id"] + for person in persons + if isinstance(person, dict) and person.get("person_id") is not None + } + person_lookup = await get_person_institutes(person_ids=list(person_ids)) + + institutions: dict[str, dict] = {} + + for person in persons: + person_id = person.get("person_id") + institute = person_lookup.get(person_id) + if not institute: + continue + + person["root_id"] = institute.get("root_id") + person["institute_id"] = institute.get("institute_id") + person["root_name_de"] = institute.get("root_name_de") + person["root_name_en"] = institute.get("root_name_en") + person["institute_name_de"] = institute.get("institute_name_de") + person["institute_name_en"] = institute.get("institute_name_en") + person["address_country_de"] = institute.get("address_country_de") + person["address_country_en"] = institute.get("address_country_en") + + if institute.get("institute_id") is not None: + institutions[f"institute:{institute['institute_id']}"] = { + "institute_id": institute["institute_id"], + "institute_name_de": institute.get("institute_name_de"), + "institute_name_en": institute.get("institute_name_en"), + } + + if institute.get("root_id") is not None: + institutions[f"root:{institute['root_id']}"] = { + "institute_id": institute["root_id"], + "institute_name_de": institute.get("root_name_de"), + "institute_name_en": institute.get("root_name_en"), + } + + source["institutions"] = list(institutions.values()) + + return DfgProjectDetails.from_elastic_hit(hit=hit) + +async def get_dfg_project_by_id(project_id: str) -> DfgProjectDetails | None: + """Fetches the details of a single DFG project based on its project ID. + + Args: + project_id (str): The project ID to fetch. + + Returns: + Optional[DfgProjectDetails]: The project details or None if not found. + """ + topic_lookup = await get_openalex_topics_for_dfg_projects(project_ids=[project_id]) + query = {"ids": {"values": [project_id]}} + + response = await elasticsearch.search( + index=ESIndex.DFG_PROJECTS, + query=query, + size=1, + ) + hits = response.get("hits", {}).get("hits", []) + + if not hits: + return None + + hit = hits[0] + source = hit["_source"] + source["topics"] = topic_lookup.get(project_id, []) + + persons = source.get("persons", []) + + #Enrich persons with institute/root info + person_ids = { + person["person_id"] + for person in persons + if isinstance(person, dict) and person.get("person_id") is not None + } + person_lookup = await get_person_institutes(person_ids=list(person_ids)) + + institutions: dict[str, dict] = {} + + for person in persons: + person_id = person.get("person_id") + institute = person_lookup.get(person_id) + if not institute: + continue + + person["root_id"] = institute.get("root_id") + person["institute_id"] = institute.get("institute_id") + person["root_name_de"] = institute.get("root_name_de") + person["root_name_en"] = institute.get("root_name_en") + person["institute_name_de"] = institute.get("institute_name_de") + person["institute_name_en"] = institute.get("institute_name_en") + person["address_country_de"] = institute.get("address_country_de") + person["address_country_en"] = institute.get("address_country_en") + + if institute.get("institute_id") is not None: + institutions[f"institute:{institute['institute_id']}"] = { + "institute_id": institute["institute_id"], + "institute_name_de": institute.get("institute_name_de"), + "institute_name_en": institute.get("institute_name_en"), + } + + if institute.get("root_id") is not None: + institutions[f"root:{institute['root_id']}"] = { + "institute_id": institute["root_id"], + "institute_name_de": institute.get("root_name_de"), + "institute_name_en": institute.get("root_name_en"), + } + + source["institutions"] = list(institutions.values()) + + return DfgProjectDetails.from_elastic_hit(hit=hit) #BUND @@ -707,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. @@ -848,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() @@ -1000,11 +1171,13 @@ async def search_all_projects( page = projects_filtering_properties.page offset = page * size response = await elasticsearch.search( + index=index, size=size, offset=offset, query=query, sort=sort, + track_total_hits=True, ) return _response_to_funding_project_page(response=response, page=page, size=size) @@ -1051,4 +1224,4 @@ def _hit_to_funding_project(hit: dict[str, Any]) -> FundingProject: else: raise ValueError( "The provided hit does not belong to a recognized project index." - ) \ No newline at end of file + ) diff --git a/service/src/main/inse/projects/router.py b/service/src/main/inse/projects/router.py index 5c7c426f..3c3f2c97 100644 --- a/service/src/main/inse/projects/router.py +++ b/service/src/main/inse/projects/router.py @@ -2,6 +2,8 @@ import logging from typing import Annotated from fastapi import APIRouter, Body, Depends, Path, Query, status +from inse.auth.model import AccessTokenMetadata +from inse.auth.service import CurrentUserAccessTokenPayloadDep from inse.institutions.institutions_search_client import ( InstitutionsSearchClient, ) @@ -28,6 +30,8 @@ from inse.projects.model import ( SortDirection, ) from inse.tags import Tags +from inse.auth.service import can_fetch_gdpr_relevant_data +from fastapi import HTTPException as HttpException logger = logging.getLogger(__name__) @@ -63,6 +67,109 @@ async def search_bund_projects( ) +@router.get( + "/dfg/search", + summary="Get DFG projects.", + description="Returns a page of DFG projects based on the provided pagination parameters and optional institution filter.", + operation_id="getDfgProjects", + responses={ + status.HTTP_200_OK: { + "description": "Successful Response", + "model": DfgProjectPage, + }, + status.HTTP_404_NOT_FOUND: {"description": "Institution not found"}, + status.HTTP_403_FORBIDDEN: {"description": "Access denied for the provided institution ID"}, + }, + response_model_by_alias=False, +) +async def get_dfg_projects( + access_token_metadata: Annotated[AccessTokenMetadata, CurrentUserAccessTokenPayloadDep], + institutions_search_client: Annotated[ + InstitutionsSearchClient, Depends(get_institutions_search_client) + ], + raw_oa_institution_id: Annotated[ + str | None, Query(description="The openalex institution ID to filter by.") + ] = None, + author_id: Annotated[str | None, Query(description="The openalex author ID to filter by.")] = None, + author_filter_ids: Annotated[list[str] | None, Query(description="The dfg author IDs to filter by.")] = None, + institution_ids: Annotated[list[str] | None, Query(description="The institution IDs to filter by.")] = None, + title: Annotated[ + str | None, Query(description="The title to filter by.") + ] = None, + keywords: Annotated[ + list[str] | None, Query(description="Raw keywords to search in title/abstract/subject fields.") + ] = None, + topic_ids: Annotated[ + list[str] | None, Query(description="The openalex topic IDs to filter by.") + ] = None, + filter_topic_ids: Annotated[ + list[str] | None, + Query( + description="Additional topic IDs to merge into the fuzzy topic-id resolution " + "(union with topic_ids). Only used when fuzzy=True." + ), + ] = None, + funding_start_years: Annotated[list[str] | None, Query(description="The funding start years to filter by.")] = None, + funding_end_years: Annotated[list[str] | None, Query(description="The funding end years to filter by.")] = None, + + page: Annotated[int, Query(description="The page number.", ge=0)] = 0, + size: Annotated[int, Query(description="The page size.", ge=1)] = 20, + sort_by: Annotated[str, Query(description="The field to sort by.")] = "title", + sort_direction: Annotated[ + str, Query(description="The sort direction (asc or desc).") + ] = "asc", + fuzzy: Annotated[ + bool, + Query(description="Use topic_id resolution if True, otherwise use raw keyword search."), + ] = False, + +) -> DfgProjectPage: + logger.debug( + "Received request to get DFG projects for author_id=%s, author_filter_ids=%s, " + "institution_ids=%s, keywords=%s, topic_ids=%s, filter_topic_ids=%s, title=%s, " + "funding_start_years=%s, funding_end_years=%s, page=%d, size=%d, sort_by=%s, " + "sort_direction=%s, fuzzy=%s", + author_id, + author_filter_ids, + institution_ids, + keywords, + topic_ids, + filter_topic_ids, + title, + funding_start_years, + funding_end_years, + page, + size, + sort_by, + sort_direction, + fuzzy, + ) + if (author_id or raw_oa_institution_id): + is_allowed = await can_fetch_gdpr_relevant_data(access_token = access_token_metadata, raw_oa_author_id = author_id, raw_oa_institution_id = raw_oa_institution_id) + if not is_allowed: + raise HttpException( + status_code=403, + detail="Access denied for the provided author ID or institution ID", + ) + return await projects_service.get_dfg_projects( + institutions_search_client=institutions_search_client, + raw_oa_institution_id=raw_oa_institution_id, + author_id=author_id, + author_filter_ids=author_filter_ids, + institution_ids=institution_ids, + funding_start_years=funding_start_years, + funding_end_years=funding_end_years, + title=title, + keywords=keywords, + topic_ids=topic_ids, + filter_topic_ids=filter_topic_ids, + page=page, + size=size, + sort_by=sort_by, + sort_direction=sort_direction, + fuzzy=fuzzy, + ) + @router.get( "/dfg/{id}", summary="Get a single DFG project.", @@ -96,10 +203,13 @@ async def get_single_dfg_project( "description": "Successful Response", "model": BundProjectPage, }, + status.HTTP_404_NOT_FOUND: {"description": "Institution not found"}, + status.HTTP_403_FORBIDDEN: {"description": "Access denied for the provided institution ID"}, }, response_model_by_alias=False, ) async def search_bund_projects( + access_token_metadata: Annotated[AccessTokenMetadata, CurrentUserAccessTokenPayloadDep], institutions_search_client: Annotated[ InstitutionsSearchClient, Depends(get_institutions_search_client) ], @@ -155,6 +265,13 @@ async def search_bund_projects( Query(description="Use OpenAlex topic-id resolution if true, otherwise raw keyword search."), ] = False, ) -> BundProjectPage: + if (raw_oa_institution_id): + is_allowed = await can_fetch_gdpr_relevant_data(access_token = access_token_metadata, raw_oa_author_id = None, raw_oa_institution_id = raw_oa_institution_id) + if not is_allowed: + raise HttpException( + status_code=403, + detail="Access denied for the provided author ID or institution ID", + ) return await projects_service.search_bund_projects_with_filters( institutions_search_client=institutions_search_client, executing_agency=executing_agency, @@ -217,10 +334,12 @@ from inse.projects.service import search_eu_cordis_projects "model": EuCordisProjectSearchPage, }, status.HTTP_404_NOT_FOUND: {"description": "Institution not found"}, + status.HTTP_403_FORBIDDEN: {"description": "Access denied for the provided institution ID"}, }, response_model_by_alias=False, ) async def search_eu_cordis_projects_endpoint( + access_token_metadata: Annotated[AccessTokenMetadata, CurrentUserAccessTokenPayloadDep], institutions_search_client: Annotated[ InstitutionsSearchClient, Depends(get_institutions_search_client) ], @@ -299,6 +418,7 @@ async def search_eu_cordis_projects_endpoint( bool, Query(description="Use OpenAlex topic-id resolution if true, otherwise raw keyword search."), ] = False, + ) -> EuCordisProjectSearchPage: logger.debug( "Received EU CORDIS search request: raw_oa_institution_id=%s, " @@ -330,7 +450,13 @@ async def search_eu_cordis_projects_endpoint( sort_direction, fuzzy, ) - + if (author_id or raw_oa_institution_id): + is_allowed = await can_fetch_gdpr_relevant_data(access_token = access_token_metadata, raw_oa_author_id = author_id, raw_oa_institution_id = raw_oa_institution_id) + if not is_allowed: + raise HttpException( + status_code=403, + detail="Access denied for the provided author ID or institution ID", + ) return await search_eu_cordis_projects( institutions_search_client=institutions_search_client, raw_oa_institution_id=raw_oa_institution_id, @@ -629,102 +755,6 @@ async def get_institution_cordis_eu_projects_funding_over_time( ) -@router.get( - "/person/dfg/search", - summary="Get DFG projects.", - description="Returns a page of DFG projects based on the provided pagination parameters and optional institution filter.", - operation_id="getDfgProjects", - responses={ - status.HTTP_200_OK: { - "description": "Successful Response", - "model": DfgProjectPage, - }, - status.HTTP_404_NOT_FOUND: {"description": "Institution not found"}, - }, - response_model_by_alias=False, -) -async def get_dfg_projects( - institutions_search_client: Annotated[ - InstitutionsSearchClient, Depends(get_institutions_search_client) - ], - raw_oa_institution_id: Annotated[ - str | None, Query(description="The openalex institution ID to filter by.") - ] = None, - author_id: Annotated[str | None, Query(description="The openalex author ID to filter by.")] = None, - author_filter_ids: Annotated[list[int] | None, Query(description="The dfg author IDs to filter by.")] = None, - institution_ids: Annotated[ - list[int] | None, Query(description="The institution IDs to filter by.") - ] = None, - title: Annotated[ - str | None, Query(description="The title to filter by.") - ] = None, - keywords: Annotated[ - list[str] | None, Query(description="Raw keywords to search in title/abstract/subject fields.") - ] = None, - topic_ids: Annotated[ - list[str] | None, Query(description="The openalex topic IDs to filter by.") - ] = None, - filter_topic_ids: Annotated[ - list[str] | None, - Query( - description="Additional topic IDs to merge into the fuzzy topic-id resolution " - "(union with topic_ids). Only used when fuzzy=True." - ), - ] = None, - funding_start_years: Annotated[list[str] | None, Query(description="The funding start years to filter by.")] = None, - funding_end_years: Annotated[list[str] | None, Query(description="The funding end years to filter by.")] = None, - - page: Annotated[int, Query(description="The page number.", ge=0)] = 0, - size: Annotated[int, Query(description="The page size.", ge=1)] = 20, - sort_by: Annotated[str, Query(description="The field to sort by.")] = "title", - sort_direction: Annotated[ - str, Query(description="The sort direction (asc or desc).") - ] = "asc", - fuzzy: Annotated[ - bool, - Query(description="Use topic_id resolution if True, otherwise use raw keyword search."), - ] = False, - -) -> DfgProjectPage: - logger.debug( - "Received request to get DFG projects for author_id=%s, author_filter_ids=%s, " - "institution_ids=%s, keywords=%s, topic_ids=%s, filter_topic_ids=%s, title=%s, " - "funding_start_years=%s, funding_end_years=%s, page=%d, size=%d, sort_by=%s, " - "sort_direction=%s, fuzzy=%s", - author_id, - author_filter_ids, - institution_ids, - keywords, - topic_ids, - filter_topic_ids, - title, - funding_start_years, - funding_end_years, - page, - size, - sort_by, - sort_direction, - fuzzy, - ) - return await projects_service.get_dfg_projects_by_author_id( - institutions_search_client=institutions_search_client, - raw_oa_institution_id=raw_oa_institution_id, - author_id=author_id, - author_filter_ids=author_filter_ids, - institution_ids=institution_ids, - funding_start_years=funding_start_years, - funding_end_years=funding_end_years, - title=title, - keywords=keywords, - topic_ids=topic_ids, - filter_topic_ids=filter_topic_ids, - page=page, - size=size, - sort_by=sort_by, - sort_direction=sort_direction, - fuzzy=fuzzy, - ) - @router.get( "/search", summary="Search projects across all funders.", diff --git a/service/src/main/inse/projects/service.py b/service/src/main/inse/projects/service.py index 4666c640..eabd2228 100644 --- a/service/src/main/inse/projects/service.py +++ b/service/src/main/inse/projects/service.py @@ -3,6 +3,7 @@ import logging from typing import Any from inse.exceptions import NotFoundException +from inse.auth.model import AccessTokenMetadata from inse.institutions.institutions_search_client import ( InstitutionsSearchClient, ) @@ -26,9 +27,7 @@ from inse.projects.eu_cordis_projects_client import ( from inse.projects.eu_cordis_projects_client import ( search_eu_cordis_projects as _search_eu_cordis_projects_es, ) -from inse.projects.logic import ( - get_dfg_author_names_by_ids, -) + from inse.projects.model import ( BundProjectPage, DfgProjectPage, @@ -41,8 +40,9 @@ from inse.projects.model import ( ProjectType, SortDirection, ) +from inse.projects.logic import get_dfg_author_names_by_ids from inse.works.logic import get_publication_dois_of_author - +from fastapi import HTTPException as HttpException logger = logging.getLogger(__name__) @@ -157,12 +157,25 @@ async def _get_dfg_project_ids_for_openalex_authors( return list(set.intersection(*project_sets)) -async def get_dfg_projects_by_author_id( +def _is_number_list(values: list[str] | None) -> bool: + if not values: + return True # nothing to validate, treat as valid/empty + for value in values: + if value is None or value == "": + return False + try: + float(value) + except (TypeError, ValueError): + return False + return True + + +async def get_dfg_projects( institutions_search_client: InstitutionsSearchClient, raw_oa_institution_id: str | None, author_id: str | None, - author_filter_ids: list[int] | None, - institution_ids: list[int] | None, + author_filter_ids: list[str] | None, + institution_ids: list[str] | None, keywords: list[str] | None, topic_ids: list[str] | None, filter_topic_ids: list[str] | None, @@ -174,6 +187,9 @@ async def get_dfg_projects_by_author_id( sort_by: str = "topic", 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, " @@ -195,6 +211,23 @@ async def get_dfg_projects_by_author_id( sort_direction, fuzzy, ) + + # Validate author_filter_ids / institution_ids. Return an empty page + if not _is_number_list(author_filter_ids) or not _is_number_list(institution_ids): + logger.debug( + "Invalid author_filter_ids=%s or institution_ids=%s, returning empty page", + author_filter_ids, + institution_ids, + ) + return DfgProjectPage(elements=[], page=page, size=size, total=0) + + author_filter_ids_int = ( + [int(float(v)) for v in author_filter_ids] if author_filter_ids else None + ) + institution_ids_int = ( + [int(float(v)) for v in institution_ids] if institution_ids else None + ) + filter_names = [] author_project_ids = [] if author_id: @@ -207,19 +240,23 @@ async def get_dfg_projects_by_author_id( size=size, total=0) - if author_filter_ids: + if author_filter_ids_int: filter_names = ( - await get_dfg_author_names_by_ids(author_ids=author_filter_ids) - if author_filter_ids + await get_dfg_author_names_by_ids(author_ids=author_filter_ids_int) + if author_filter_ids_int else [] ) - if author_filter_ids and not filter_names: + if author_filter_ids_int and not filter_names: logger.debug( "No author names found for author_filter_ids=%s", - author_filter_ids, + author_filter_ids_int, ) institution_aliases = [] if raw_oa_institution_id: + if institutions_search_client is None: + raise ValueError( + "institutions_search_client must be provided when raw_oa_institution_id is set" + ) institution_aliases = ( await institutions_search_client.get_institution_aliases_by_oa_institution_id( raw_oa_institution_id @@ -238,7 +275,7 @@ async def get_dfg_projects_by_author_id( institution_aliases=institution_aliases, project_ids=author_project_ids, names=filter_names or [], - institution_ids=institution_ids, + institution_ids=institution_ids_int, keywords=keywords, topic_ids=topic_ids, filter_topic_ids=filter_topic_ids, @@ -248,6 +285,9 @@ async def get_dfg_projects_by_author_id( sort_by=sort_by, 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( @@ -423,9 +463,15 @@ 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: + if institutions_search_client is None: + raise ValueError( + "institutions_search_client must be provided when raw_oa_institution_id is set" + ) institution_aliases = ( await institutions_search_client.get_institution_aliases_by_oa_institution_id( raw_oa_institution_id @@ -454,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( @@ -616,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, @@ -623,6 +673,7 @@ async def search_eu_cordis_projects( sort_by: str = "title", sort_direction: str = "asc", fuzzy: bool = False, + skip_enrichment: bool = False, ) -> EuCordisProjectSearchPage: """Single entry point for EU CORDIS project search. @@ -639,7 +690,6 @@ async def search_eu_cordis_projects( eu_cordis_projects_client.search_eu_cordis_projects. """ resolved_organization_names: list[str] = list(organization_names or []) - if raw_oa_institution_id: if institutions_search_client is None: raise ValueError( @@ -676,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, @@ -683,4 +735,5 @@ async def search_eu_cordis_projects( sort_by=sort_by, sort_direction=sort_direction, fuzzy=fuzzy, - ) \ No newline at end of file + skip_enrichment=skip_enrichment, + ) 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/ranking/logic.py b/service/src/main/inse/ranking/logic.py index f37df621..e8aacfd5 100644 --- a/service/src/main/inse/ranking/logic.py +++ b/service/src/main/inse/ranking/logic.py @@ -3,11 +3,10 @@ import asyncio import logging from dataclasses import dataclass +from math import floor from time import time from typing import Any -import pandas as pd - from inse.authors.institution_membership_query import ( build_active_institution_membership_query, ) @@ -825,15 +824,29 @@ def _bucket_to_ranked_author(author_bucket: dict) -> RankedAuthor: ) -def _min_max_normalize(values: pd.Series) -> pd.Series: +def _quantile(values: list[float], quantile: float) -> float: + """Returns a linearly interpolated quantile (the former pandas default).""" + ordered = sorted(values) + if not ordered: + return 0.0 + position = (len(ordered) - 1) * quantile + lower_index = floor(position) + upper_index = min(lower_index + 1, len(ordered) - 1) + fraction = position - lower_index + return ordered[lower_index] + ( + ordered[upper_index] - ordered[lower_index] + ) * fraction + + +def _min_max_normalize(values: list[float]) -> list[float]: """Scales a numeric column to the range [0, 1] via min-max normalization.""" - minimum = values.min() - maximum = values.max() + minimum = min(values) + maximum = max(values) # if all values are the same, return a series of 1.0 to avoid division by zero. if maximum == minimum: - return pd.Series([1.0] * len(values)) + return [1.0] * len(values) - return (values - minimum) / (maximum - minimum) + return [(value - minimum) / (maximum - minimum) for value in values] def _apply_scores(authors: list[RankedAuthor], weights: RankingWeights) -> None: @@ -854,38 +867,29 @@ def _apply_scores(authors: list[RankedAuthor], weights: RankingWeights) -> None: news_counts.append(author.news_count) patents_counts.append(author.patents_count) - frame = pd.DataFrame({ - "works": works_counts, - "citations": citations_counts, - "companies": companies_counts, - "news": news_counts, - "patents": patents_counts, - }) - quantile_value = 0.95 - - frame["works"] = frame["works"].clip(upper=frame["works"].quantile(quantile_value)) - frame["citations"] = frame["citations"].clip(upper=frame["citations"].quantile(quantile_value)) - frame["companies"] = frame["companies"].clip(upper=frame["companies"].quantile(quantile_value)) - frame["news"] = frame["news"].clip(upper=frame["news"].quantile(quantile_value)) - frame["patents"] = frame["patents"].clip(upper=frame["patents"].quantile(quantile_value)) - - works_normalized = _min_max_normalize(frame["works"]) - citations_normalized = _min_max_normalize(frame["citations"]) - companies_normalized = _min_max_normalize(frame["companies"]) - news_normalized = _min_max_normalize(frame["news"]) - patents_normalized = _min_max_normalize(frame["patents"]) - - scores = ( - works_normalized * weights.works - + citations_normalized * weights.citation - + companies_normalized * weights.companies - + news_normalized * weights.news - + patents_normalized * weights.patents - ) + metrics = [ + works_counts, + citations_counts, + companies_counts, + news_counts, + patents_counts, + ] + normalized_metrics = [ + _min_max_normalize( + [min(value, _quantile(values, quantile_value)) for value in values] + ) + for values in metrics + ] for index, author in enumerate(authors): - author.score = float(scores.iloc[index]) + author.score = float( + normalized_metrics[0][index] * weights.works + + normalized_metrics[1][index] * weights.citation + + normalized_metrics[2][index] * weights.companies + + normalized_metrics[3][index] * weights.news + + normalized_metrics[4][index] * weights.patents + ) def _author_score(author: RankedAuthor) -> float: 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/service/src/main/inse/university_ranking/trend_query_builder.py b/service/src/main/inse/university_ranking/trend_query_builder.py index dc639132..10e4b805 100644 --- a/service/src/main/inse/university_ranking/trend_query_builder.py +++ b/service/src/main/inse/university_ranking/trend_query_builder.py @@ -1,5 +1,6 @@ import asyncio import logging +import re from typing import Any from inse.integrations import elasticsearch @@ -11,6 +12,17 @@ logger = logging.getLogger(__name__) DEFAULT_INSTITUTION_ID = "https://openalex.org/I62318514" DEFAULT_INSTITUTION_NAME = "University of Duisburg-Essen" +# Reserved characters and boolean operators of the Lucene query_string syntax +_LUCENE_SPECIAL_CHARS = re.compile(r'([+\-=&|> str: + """Escapes a free-text search term so it is safe inside a ``query_string`` query.""" + if not term: + return "" + escaped = _LUCENE_SPECIAL_CHARS.sub(r"\\\1", term) + return _LUCENE_BOOL_OPERATORS.sub(lambda m: f'"{m.group(1)}"', escaped) def clean_inst_id(id_str: str) -> str: @@ -407,6 +419,56 @@ class TrendQueryBuilder: } } + @staticmethod + def build_cc_news_year_agg_body( + term: str, + start_year: int, + end_year: int, + languages: list[str] | None = None, + ) -> dict[str, Any]: + """Builds a size=0 yearly-count aggregation over the Common Crawl News indices. Buckets + by year with a `date_histogram`, since cc-news has a real `content_date` date field rather than + the integer `date_year` of `aktuell`. + """ + return { + "size": 0, + "track_total_hits": False, + "_source": False, + "query": { + "bool": { + "filter": [ + { + "query_string": { + "query": escape_lucene_query(term), + "fields": CC_NEWS_SEARCH_FIELDS, + "default_operator": "AND", + } + }, + {"terms": {"language_code": languages or CC_NEWS_LANGUAGES}}, + { + "range": { + "content_date": { + "gte": f"{start_year}-01-01", + "lte": f"{end_year}-12-31", + "format": "yyyy-MM-dd", + } + } + }, + ] + } + }, + "aggs": { + "by_year": { + "date_histogram": { + "field": "content_date", + "calendar_interval": "year", + "format": "yyyy", + "min_doc_count": 0, + } + } + }, + } + @staticmethod def build_bund_receiver_clause(aliases: list[str]) -> dict[str, Any]: """Builds Zuwendungsempfänger matching clause for BUND projects.""" @@ -443,4 +505,7 @@ DFG_PROJECT_TEXT_FIELDS = [ CORDIS_PROJECT_TEXT_FIELDS = ["title", "objective"] AKTUELLES_SEARCH_FIELDS = ["main_content", "full_content", "maintitle", "subtitle", "intro_content"] +CC_NEWS_SEARCH_FIELDS = ["title", "body"] +CC_NEWS_LANGUAGES = ["de", "en"] +CC_NEWS_START_YEAR = 2017 diff --git a/service/src/main/inse/university_ranking/trend_strategies.py b/service/src/main/inse/university_ranking/trend_strategies.py index f46c6be2..c0badec6 100644 --- a/service/src/main/inse/university_ranking/trend_strategies.py +++ b/service/src/main/inse/university_ranking/trend_strategies.py @@ -16,11 +16,13 @@ from .model import ( ) from .trend_query_builder import ( AKTUELLES_SEARCH_FIELDS, + CC_NEWS_START_YEAR, DEFAULT_INSTITUTION_ID, DEFAULT_INSTITUTION_NAME, TrendMetadataResolver, TrendQueryBuilder, clean_inst_id, + escape_lucene_query, to_full_inst_url, ) @@ -47,6 +49,13 @@ EPO_PATENT_FIELDS = [ "openalex_topics.topic_id", ] +# Synthetic entity id prefixes for the news trend series. The webapp keys colouring, chip +# visibility and pie filtering off these, so keep them in sync with uni-trend-parent.component.ts. +NEWS_ENTITY_PREFIX = "news_topic_" +CC_NEWS_ENTITY_PREFIX = "ccnews_topic_" +# Entity id of the collapsed CC-News series in the cross-domain ("all") view. +CC_NEWS_COMPOSITE_ID = "ccnews" + DFG_INSTITUTION_FIELDS = [ "Antragstellende Institution", "Mitantragstellende Institution", @@ -1042,6 +1051,18 @@ class ProjectsTrendStrategy(TrendStrategy): class NewsTrendStrategy(TrendStrategy): + """Yearly news counts per topic. + + Produces one series per topic from the UDE-internal `aktuell` index (entity id + ``news_topic_``). When keyword matching is active (``fuzzy=False``) it additionally + produces an external Common Crawl News baseline per topic (``ccnews_topic_``) so the + internal coverage can be compared against the wider web. CC-News has no OpenAlex topic + mapping, so it is skipped entirely in topic-mapping mode. + """ + + def __init__(self, include_cc_news: bool = True): + self.include_cc_news = include_cc_news + async def get_trend( self, topics: list[str], @@ -1054,20 +1075,40 @@ class NewsTrendStrategy(TrendStrategy): ) -> TrendResponse: years_range = self._get_years_range() start_year, end_year = years_range[0], years_range[-1] + years_set = set(years_range) + + cc_news_enabled = self.include_cc_news and not fuzzy accumulated_data = { - f"news_topic_{t}": {top: {yr: (0, 1) for yr in years_range} for top in topics} + f"{NEWS_ENTITY_PREFIX}{t}": {top: {yr: (0, 1) for yr in years_range} for top in topics} for t in topics } + if cc_news_enabled: + accumulated_data.update({ + f"{CC_NEWS_ENTITY_PREFIX}{t}": {top: {yr: (0, 1) for yr in years_range} for top in topics} + for t in topics + }) STOP_WORDS = {"in", "and", "or", "und", "oder", "der", "die", "das", "von", "mit", "zu", "at", "by", "on", "for", "to", "a", "an", "the"} + def resolve_keyword_term(idx: int, t_name: str) -> str: + """Picks the raw keyword for a topic, falling back to the topic name itself.""" + if keywords and idx < len(keywords) and keywords[idx]: + raw_kw = keywords[idx] + term = raw_kw.split(",")[0].strip() if isinstance(raw_kw, str) else raw_kw + if term: + return term + return t_name + + def is_searchable_term(term: str) -> bool: + return bool(term) and term.lower() not in STOP_WORDS and len(term.strip()) > 1 + # Scan UDE news OpenAlex topics index to get matching news IDs without size limit cutoffs async def fetch_news_ids_for_term(idx: int, t_name: str) -> list[str]: news_ids: Set[str] = set() if fuzzy: term = t_name - es_query = {"term": {"topic_matches.topic_display_name.keyword": term}} + es_query = {"match_phrase": {"topic_matches.topic_display_name": term}} try: async for hit in elasticsearch.scan( index=ESIndex.AKTUELLES_OPENALEX_TOPICS.value, @@ -1081,20 +1122,14 @@ class NewsTrendStrategy(TrendStrategy): except Exception as e: logger.warning("Failed to scan UDE news OpenAlex topics index %s: %s", ESIndex.AKTUELLES_OPENALEX_TOPICS.value, e) else: - if keywords and idx < len(keywords) and keywords[idx]: - raw_kw = keywords[idx] - term = raw_kw.split(",")[0].strip() if isinstance(raw_kw, str) else raw_kw - if not term: - term = t_name - else: - term = t_name + term = resolve_keyword_term(idx, t_name) # If non-fuzzy keyword search, search article content fields in 'aktuell' index - if term and term.lower() not in STOP_WORDS and len(term.strip()) > 1: + if is_searchable_term(term): try: content_query = { "query_string": { - "query": term, + "query": escape_lucene_query(term), "fields": AKTUELLES_SEARCH_FIELDS, "default_operator": "AND", } @@ -1113,12 +1148,59 @@ class NewsTrendStrategy(TrendStrategy): return list(news_ids) - matching_ids_list = await asyncio.gather(*(fetch_news_ids_for_term(idx, t) for idx, t in enumerate(topics))) + async def fetch_cc_news_counts() -> dict[int, dict[int, int]]: + """Yearly CC-News counts per topic index, from a single _msearch over cc-news-*. + The year buckets are read straight off a size=0 date_histogram instead. + """ + searchable = [ + (idx, term) + for idx, t_name in enumerate(topics) + if is_searchable_term(term := resolve_keyword_term(idx, t_name)) + ] + if not searchable: + return {} + + searches = [ + ( + ESIndex.CC_NEWS_WILDCARD.value, + TrendQueryBuilder.build_cc_news_year_agg_body(term, CC_NEWS_START_YEAR, end_year), + ) + for _, term in searchable + ] + try: + responses = await elasticsearch.msearch( + searches, cluster=ESCluster.NES, request_cache=True + ) + except Exception as e: + logger.warning("Failed to aggregate CC-News years via msearch: %s", e) + return {} + + counts: dict[int, dict[int, int]] = {} + for (topic_idx, term), res in zip(searchable, responses): + if not isinstance(res, dict) or "error" in res: + logger.warning("CC-News msearch entry for %r failed: %s", term, (res or {}).get("error")) + continue + by_year: dict[int, int] = {} + for b in res.get("aggregations", {}).get("by_year", {}).get("buckets", []): + try: + yr = int(b.get("key_as_string")) + except (TypeError, ValueError): + continue + if yr in years_set: + by_year[yr] = int(b.get("doc_count", 0)) + counts[topic_idx] = by_year + return counts + + news_ids_future = asyncio.gather(*(fetch_news_ids_for_term(idx, t) for idx, t in enumerate(topics))) + if cc_news_enabled: + matching_ids_list, cc_news_counts = await asyncio.gather(news_ids_future, fetch_cc_news_counts()) + else: + matching_ids_list, cc_news_counts = await news_ids_future, {} async def count_by_year(t_name: str, news_ids: list[str]): if not news_ids: return - entity_key = f"news_topic_{t_name}" + entity_key = f"{NEWS_ENTITY_PREFIX}{t_name}" # Prepare multi-search payloads for chunks of news_ids to avoid payload limits chunk_queries = [] @@ -1164,13 +1246,15 @@ class NewsTrendStrategy(TrendStrategy): await asyncio.gather(*(count_by_year(t, ids) for t, ids in zip(topics, matching_ids_list))) + for topic_idx, t_name in enumerate(topics): + entity_key = f"{CC_NEWS_ENTITY_PREFIX}{t_name}" + for yr, count in cc_news_counts.get(topic_idx, {}).items(): + prev_count, _ = accumulated_data[entity_key][t_name][yr] + accumulated_data[entity_key][t_name][yr] = (prev_count + count, 1) + normalized_lookup = self._normalize_series(years_range, accumulated_data, topics) - series_list: list[TrendSeries] = [] - for t_name in topics: - entity_key = f"news_topic_{t_name}" - topic_data_map: dict[str, list[TopicYearlyData]] = {} - + def build_series(entity_key: str, t_name: str, entity_name: str) -> TrendSeries: lookup = normalized_lookup.get((entity_key, t_name), {}) norm_vals = lookup.get("normalized", [0.0] * len(years_range)) cum_vals = lookup.get("cumulative", [0.0] * len(years_range)) @@ -1188,16 +1272,22 @@ class NewsTrendStrategy(TrendStrategy): ) ) - for topic in topics: - topic_data_map[topic] = yearly_data_items + topic_data_map: dict[str, list[TopicYearlyData]] = {topic: yearly_data_items for topic in topics} - series_list.append( - TrendSeries( - entity_id=entity_key, - entity_name=t_name, - entity_type="institution", - topic_data=topic_data_map, - ) + return TrendSeries( + entity_id=entity_key, + entity_name=entity_name, + entity_type="institution", + topic_data=topic_data_map, + ) + + series_list: list[TrendSeries] = [ + build_series(f"{NEWS_ENTITY_PREFIX}{t_name}", t_name, t_name) for t_name in topics + ] + if cc_news_enabled: + series_list.extend( + build_series(f"{CC_NEWS_ENTITY_PREFIX}{t_name}", t_name, f"{t_name} (CC-News)") + for t_name in topics ) return TrendResponse(series=series_list, years=years_range) @@ -1269,25 +1359,40 @@ class AllTrendStrategy(TrendStrategy): add_composite(pat_series, "patents", "Patentanmeldungen") add_composite(proj_series, "projects", "Drittmittelförderung") - if is_ude and news_res: - merged_news_topic_data: dict[str, list[TopicYearlyData]] = {} + def merge_news_composite(prefix: str, c_id: str, c_name: str) -> bool: + """Collapses the per-topic news series of one source into a single composite. + + Returns False when the source produced no series at all. + """ + if not news_res or not any(s.entity_id.startswith(prefix) for s in news_res.series): + return False + + merged_topic_data: dict[str, list[TopicYearlyData]] = {} for topic in topics: - term_key = f"news_topic_{topic}" + term_key = f"{prefix}{topic}" matching_series = next((s for s in news_res.series if s.entity_id == term_key), None) if matching_series and topic in matching_series.topic_data: - merged_news_topic_data[topic] = matching_series.topic_data[topic] + merged_topic_data[topic] = matching_series.topic_data[topic] else: - merged_news_topic_data[topic] = [ + merged_topic_data[topic] = [ TopicYearlyData(year=yr, raw=0, normalized=0.0, cumulative=0.0, institutions_count=1) for yr in years_range ] - news_series = TrendSeries( - entity_id="news", - entity_name="UDE Campus Aktuell Beiträge", - entity_type="institution", - topic_data=merged_news_topic_data, + add_composite( + TrendSeries( + entity_id=c_id, + entity_name=c_name, + entity_type="institution", + topic_data=merged_topic_data, + ), + c_id, + c_name, ) - add_composite(news_series, "news", "UDE Campus Aktuell Beiträge") + return True + + if is_ude: + merge_news_composite(NEWS_ENTITY_PREFIX, "news", "UDE Campus Aktuell Beiträge") + merge_news_composite(CC_NEWS_ENTITY_PREFIX, CC_NEWS_COMPOSITE_ID, "Web-Nachrichten (CC-News)") return TrendResponse(series=composite_series, years=years_range) diff --git a/service/src/main/inse/works/v2/router.py b/service/src/main/inse/works/v2/router.py index 87596cdd..13446ecd 100644 --- a/service/src/main/inse/works/v2/router.py +++ b/service/src/main/inse/works/v2/router.py @@ -24,7 +24,7 @@ router = APIRouter(prefix=RouterPrefixes.WORKS_V2, tags=[Tags.WORKS_V2]) @router.get( - "/{raw_oa_work_id}", + "/single/{raw_oa_work_id}", operation_id="getWorkById", summary="Returns a work based on its ID.", ) diff --git a/service/src/main/inse/works/v2/service.py b/service/src/main/inse/works/v2/service.py index f1fa10d2..20e139a8 100644 --- a/service/src/main/inse/works/v2/service.py +++ b/service/src/main/inse/works/v2/service.py @@ -654,6 +654,7 @@ async def _search_works( size=size, offset=page * size, sort=sort, + track_total_hits=True ) hits_block = response.get("hits", {}) diff --git a/webapp/src/app/api/.openapi-generator/FILES b/webapp/src/app/api/.openapi-generator/FILES index e751f4aa..d1763419 100644 --- a/webapp/src/app/api/.openapi-generator/FILES +++ b/webapp/src/app/api/.openapi-generator/FILES @@ -103,11 +103,11 @@ model/dfgPersonSummary.ts model/dfgPersonSummaryPage.ts model/dfgProjectDetails.ts model/dfgProjectInstitutionRole.ts +model/dfgProjectKeyword.ts model/dfgProjectPage.ts model/dfgProjectPersonRole.ts model/dfgProjectPublicationSummary.ts model/dfgProjectStatusStatistics.ts -model/dfgProjectSubjectArea.ts model/dfgProjectSubprojectSummary.ts model/dfgProjectSummary.ts model/dfgProjectTopic.ts @@ -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/auth.service.ts b/webapp/src/app/api/api/auth.service.ts index a906d12f..535c7da5 100644 --- a/webapp/src/app/api/api/auth.service.ts +++ b/webapp/src/app/api/api/auth.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 { AccessResponse } from '../model/accessResponse'; @@ -50,964 +56,1877 @@ import { OtkResponse } from '../model/otkResponse'; import { UpdateAccountRequest } from '../model/updateAccountRequest'; // @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 AuthService 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); + /** + * Check if user can fetch GDPR-relevant data + * Check if the authenticated user can fetch GDPR-relevant data for a given author and institution. + * @endpoint get /api/auth/v2/can-fetch-gdpr-relevant-data + * @param rawOaAuthorId OpenAlex author ID to check access for + * @param rawOaInstitutionId OpenAlex institution ID to check access for + * @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 canFetchGdprRelevantData( + rawOaAuthorId?: string, + rawOaInstitutionId?: string, + secureFgpAcc?: string, + observe?: 'body', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable; + public canFetchGdprRelevantData( + rawOaAuthorId?: string, + rawOaInstitutionId?: string, + secureFgpAcc?: string, + observe?: 'response', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public canFetchGdprRelevantData( + rawOaAuthorId?: string, + rawOaInstitutionId?: string, + secureFgpAcc?: string, + observe?: 'events', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public canFetchGdprRelevantData( + rawOaAuthorId?: string, + rawOaInstitutionId?: string, + secureFgpAcc?: string, + observe: any = 'body', + reportProgress: boolean = false, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable { + let localVarQueryParameters = new HttpParams({ encoder: this.encoder }); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + rawOaAuthorId, + 'raw_oa_author_id', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + rawOaInstitutionId, + 'raw_oa_institution_id', + ); + + let localVarHeaders = this.defaultHeaders; + + // authentication (HTTPBearer) required + localVarHeaders = this.configuration.addCredentialToHeaders( + 'HTTPBearer', + 'Authorization', + localVarHeaders, + 'Bearer ', + ); + + const localVarHttpHeaderAcceptSelected: string | undefined = + options?.httpHeaderAccept ?? + this.configuration.selectHeaderAccept(['application/json']); + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set( + 'Accept', + localVarHttpHeaderAcceptSelected, + ); } - /** - * Change Password - * Change the user\'s password and invalidate existing tokens. - * @endpoint post /api/auth/v2/change-password - * @param bodyChangePassword - * @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 changePassword(bodyChangePassword: BodyChangePassword, secureFgpAcc?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; - public changePassword(bodyChangePassword: BodyChangePassword, secureFgpAcc?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public changePassword(bodyChangePassword: BodyChangePassword, secureFgpAcc?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public changePassword(bodyChangePassword: BodyChangePassword, secureFgpAcc?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { - if (bodyChangePassword === null || bodyChangePassword === undefined) { - throw new Error('Required parameter bodyChangePassword was null or undefined when calling changePassword.'); - } + const localVarHttpContext: HttpContext = + options?.context ?? new HttpContext(); - let localVarHeaders = this.defaultHeaders; + const localVarTransferCache: boolean = options?.transferCache ?? true; - // authentication (HTTPBearer) required - localVarHeaders = this.configuration.addCredentialToHeaders('HTTPBearer', 'Authorization', localVarHeaders, 'Bearer '); - - const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([ - 'application/json' - ]); - if (localVarHttpHeaderAcceptSelected !== undefined) { - localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); - } - - const localVarHttpContext: HttpContext = options?.context ?? new HttpContext(); - - const localVarTransferCache: boolean = options?.transferCache ?? true; - - - // to determine the Content-Type header - const consumes: string[] = [ - 'application/json' - ]; - const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes); - if (httpContentTypeSelected !== undefined) { - localVarHeaders = localVarHeaders.set('Content-Type', httpContentTypeSelected); - } - - let responseType_: 'text' | 'json' | 'blob' = 'json'; - if (localVarHttpHeaderAcceptSelected) { - if (localVarHttpHeaderAcceptSelected.startsWith('text')) { - responseType_ = 'text'; - } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { - responseType_ = 'json'; - } else { - responseType_ = 'blob'; - } - } - - let localVarPath = `/api/auth/v2/change-password`; - const { basePath, withCredentials } = this.configuration; - return this.httpClient.request('post', `${basePath}${localVarPath}`, - { - context: localVarHttpContext, - body: bodyChangePassword, - responseType: responseType_, - ...(withCredentials ? { withCredentials } : {}), - headers: localVarHeaders, - observe: observe, - ...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}), - reportProgress: reportProgress - } - ); + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if ( + this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected) + ) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } } - /** - * Create Account - * @endpoint post /api/accounts - * @param createAccountRequest - * @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 createAccount(createAccountRequest: CreateAccountRequest, secureFgpAcc?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; - public createAccount(createAccountRequest: CreateAccountRequest, secureFgpAcc?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public createAccount(createAccountRequest: CreateAccountRequest, secureFgpAcc?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public createAccount(createAccountRequest: CreateAccountRequest, secureFgpAcc?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { - if (createAccountRequest === null || createAccountRequest === undefined) { - throw new Error('Required parameter createAccountRequest was null or undefined when calling createAccount.'); - } + let localVarPath = `/api/auth/v2/can-fetch-gdpr-relevant-data`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request( + 'get', + `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + params: localVarQueryParameters, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined + ? { transferCache: localVarTransferCache } + : {}), + reportProgress: reportProgress, + }, + ); + } - let localVarHeaders = this.defaultHeaders; - - // authentication (HTTPBearer) required - localVarHeaders = this.configuration.addCredentialToHeaders('HTTPBearer', 'Authorization', localVarHeaders, 'Bearer '); - - const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([ - 'application/json' - ]); - if (localVarHttpHeaderAcceptSelected !== undefined) { - localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); - } - - const localVarHttpContext: HttpContext = options?.context ?? new HttpContext(); - - const localVarTransferCache: boolean = options?.transferCache ?? true; - - - // to determine the Content-Type header - const consumes: string[] = [ - 'application/json' - ]; - const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes); - if (httpContentTypeSelected !== undefined) { - localVarHeaders = localVarHeaders.set('Content-Type', httpContentTypeSelected); - } - - let responseType_: 'text' | 'json' | 'blob' = 'json'; - if (localVarHttpHeaderAcceptSelected) { - if (localVarHttpHeaderAcceptSelected.startsWith('text')) { - responseType_ = 'text'; - } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { - responseType_ = 'json'; - } else { - responseType_ = 'blob'; - } - } - - let localVarPath = `/api/accounts`; - const { basePath, withCredentials } = this.configuration; - return this.httpClient.request('post', `${basePath}${localVarPath}`, - { - context: localVarHttpContext, - body: createAccountRequest, - responseType: responseType_, - ...(withCredentials ? { withCredentials } : {}), - headers: localVarHeaders, - observe: observe, - ...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}), - reportProgress: reportProgress - } - ); + /** + * Change Password + * Change the user\'s password and invalidate existing tokens. + * @endpoint post /api/auth/v2/change-password + * @param bodyChangePassword + * @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 changePassword( + bodyChangePassword: BodyChangePassword, + secureFgpAcc?: string, + observe?: 'body', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable; + public changePassword( + bodyChangePassword: BodyChangePassword, + secureFgpAcc?: string, + observe?: 'response', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public changePassword( + bodyChangePassword: BodyChangePassword, + secureFgpAcc?: string, + observe?: 'events', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public changePassword( + bodyChangePassword: BodyChangePassword, + secureFgpAcc?: string, + observe: any = 'body', + reportProgress: boolean = false, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable { + if (bodyChangePassword === null || bodyChangePassword === undefined) { + throw new Error( + 'Required parameter bodyChangePassword was null or undefined when calling changePassword.', + ); } - /** - * Delete Account - * @endpoint delete /api/accounts/{account_id} - * @param accountId - * @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 deleteAccount(accountId: string, secureFgpAcc?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; - public deleteAccount(accountId: string, secureFgpAcc?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public deleteAccount(accountId: string, secureFgpAcc?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public deleteAccount(accountId: string, secureFgpAcc?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { - if (accountId === null || accountId === undefined) { - throw new Error('Required parameter accountId was null or undefined when calling deleteAccount.'); - } + let localVarHeaders = this.defaultHeaders; - let localVarHeaders = this.defaultHeaders; + // authentication (HTTPBearer) required + localVarHeaders = this.configuration.addCredentialToHeaders( + 'HTTPBearer', + 'Authorization', + localVarHeaders, + 'Bearer ', + ); - // authentication (HTTPBearer) required - localVarHeaders = this.configuration.addCredentialToHeaders('HTTPBearer', 'Authorization', localVarHeaders, 'Bearer '); - - const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([ - 'application/json' - ]); - if (localVarHttpHeaderAcceptSelected !== undefined) { - localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); - } - - const localVarHttpContext: HttpContext = options?.context ?? new HttpContext(); - - const localVarTransferCache: boolean = options?.transferCache ?? true; - - - let responseType_: 'text' | 'json' | 'blob' = 'json'; - if (localVarHttpHeaderAcceptSelected) { - if (localVarHttpHeaderAcceptSelected.startsWith('text')) { - responseType_ = 'text'; - } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { - responseType_ = 'json'; - } else { - responseType_ = 'blob'; - } - } - - let localVarPath = `/api/accounts/${this.configuration.encodeParam({name: "accountId", value: accountId, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: "uuid"})}`; - const { basePath, withCredentials } = this.configuration; - return this.httpClient.request('delete', `${basePath}${localVarPath}`, - { - context: localVarHttpContext, - responseType: responseType_, - ...(withCredentials ? { withCredentials } : {}), - headers: localVarHeaders, - observe: observe, - ...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}), - reportProgress: reportProgress - } - ); + const localVarHttpHeaderAcceptSelected: string | undefined = + options?.httpHeaderAccept ?? + this.configuration.selectHeaderAccept(['application/json']); + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set( + 'Accept', + localVarHttpHeaderAcceptSelected, + ); } - /** - * Get Access Token - * Retrieve an access token for the authenticated user. - * @endpoint post /api/auth/v2/access - * @param bodyGetAccessToken - * @param idToken - * @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 getAccessToken(bodyGetAccessToken: BodyGetAccessToken, idToken?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; - public getAccessToken(bodyGetAccessToken: BodyGetAccessToken, idToken?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public getAccessToken(bodyGetAccessToken: BodyGetAccessToken, idToken?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public getAccessToken(bodyGetAccessToken: BodyGetAccessToken, idToken?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { - if (bodyGetAccessToken === null || bodyGetAccessToken === undefined) { - throw new Error('Required parameter bodyGetAccessToken was null or undefined when calling getAccessToken.'); - } + const localVarHttpContext: HttpContext = + options?.context ?? new HttpContext(); - let localVarHeaders = this.defaultHeaders; + const localVarTransferCache: boolean = options?.transferCache ?? true; - const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([ - 'application/json' - ]); - if (localVarHttpHeaderAcceptSelected !== undefined) { - localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); - } - - const localVarHttpContext: HttpContext = options?.context ?? new HttpContext(); - - const localVarTransferCache: boolean = options?.transferCache ?? true; - - - // to determine the Content-Type header - const consumes: string[] = [ - 'application/json' - ]; - const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes); - if (httpContentTypeSelected !== undefined) { - localVarHeaders = localVarHeaders.set('Content-Type', httpContentTypeSelected); - } - - let responseType_: 'text' | 'json' | 'blob' = 'json'; - if (localVarHttpHeaderAcceptSelected) { - if (localVarHttpHeaderAcceptSelected.startsWith('text')) { - responseType_ = 'text'; - } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { - responseType_ = 'json'; - } else { - responseType_ = 'blob'; - } - } - - let localVarPath = `/api/auth/v2/access`; - const { basePath, withCredentials } = this.configuration; - return this.httpClient.request('post', `${basePath}${localVarPath}`, - { - context: localVarHttpContext, - body: bodyGetAccessToken, - responseType: responseType_, - ...(withCredentials ? { withCredentials } : {}), - headers: localVarHeaders, - observe: observe, - ...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}), - reportProgress: reportProgress - } - ); + // to determine the Content-Type header + const consumes: string[] = ['application/json']; + const httpContentTypeSelected: string | undefined = + this.configuration.selectHeaderContentType(consumes); + if (httpContentTypeSelected !== undefined) { + localVarHeaders = localVarHeaders.set( + 'Content-Type', + httpContentTypeSelected, + ); } - /** - * Get Current Account - * @endpoint get /api/accounts/me - * @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 getCurrentAccount(secureFgpAcc?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; - public getCurrentAccount(secureFgpAcc?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public getCurrentAccount(secureFgpAcc?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public getCurrentAccount(secureFgpAcc?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { - - let localVarHeaders = this.defaultHeaders; - - // authentication (HTTPBearer) required - localVarHeaders = this.configuration.addCredentialToHeaders('HTTPBearer', 'Authorization', localVarHeaders, 'Bearer '); - - const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([ - 'application/json' - ]); - if (localVarHttpHeaderAcceptSelected !== undefined) { - localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); - } - - const localVarHttpContext: HttpContext = options?.context ?? new HttpContext(); - - const localVarTransferCache: boolean = options?.transferCache ?? true; - - - let responseType_: 'text' | 'json' | 'blob' = 'json'; - if (localVarHttpHeaderAcceptSelected) { - if (localVarHttpHeaderAcceptSelected.startsWith('text')) { - responseType_ = 'text'; - } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { - responseType_ = 'json'; - } else { - responseType_ = 'blob'; - } - } - - let localVarPath = `/api/accounts/me`; - const { basePath, withCredentials } = this.configuration; - return this.httpClient.request('get', `${basePath}${localVarPath}`, - { - context: localVarHttpContext, - responseType: responseType_, - ...(withCredentials ? { withCredentials } : {}), - headers: localVarHeaders, - observe: observe, - ...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}), - reportProgress: reportProgress - } - ); + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if ( + this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected) + ) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } } - /** - * Health Check - * @endpoint get /api/auth/v2/health - * @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 healthCheckApiAuthV2HealthGet(observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; - public healthCheckApiAuthV2HealthGet(observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public healthCheckApiAuthV2HealthGet(observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public healthCheckApiAuthV2HealthGet(observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + let localVarPath = `/api/auth/v2/change-password`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request('post', `${basePath}${localVarPath}`, { + context: localVarHttpContext, + body: bodyChangePassword, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined + ? { transferCache: localVarTransferCache } + : {}), + reportProgress: reportProgress, + }); + } - let localVarHeaders = this.defaultHeaders; - - const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([ - 'application/json' - ]); - if (localVarHttpHeaderAcceptSelected !== undefined) { - localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); - } - - const localVarHttpContext: HttpContext = options?.context ?? new HttpContext(); - - const localVarTransferCache: boolean = options?.transferCache ?? true; - - - let responseType_: 'text' | 'json' | 'blob' = 'json'; - if (localVarHttpHeaderAcceptSelected) { - if (localVarHttpHeaderAcceptSelected.startsWith('text')) { - responseType_ = 'text'; - } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { - responseType_ = 'json'; - } else { - responseType_ = 'blob'; - } - } - - let localVarPath = `/api/auth/v2/health`; - const { basePath, withCredentials } = this.configuration; - return this.httpClient.request('get', `${basePath}${localVarPath}`, - { - context: localVarHttpContext, - responseType: responseType_, - ...(withCredentials ? { withCredentials } : {}), - headers: localVarHeaders, - observe: observe, - ...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}), - reportProgress: reportProgress - } - ); + /** + * Create Account + * @endpoint post /api/accounts + * @param createAccountRequest + * @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 createAccount( + createAccountRequest: CreateAccountRequest, + secureFgpAcc?: string, + observe?: 'body', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable; + public createAccount( + createAccountRequest: CreateAccountRequest, + secureFgpAcc?: string, + observe?: 'response', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public createAccount( + createAccountRequest: CreateAccountRequest, + secureFgpAcc?: string, + observe?: 'events', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public createAccount( + createAccountRequest: CreateAccountRequest, + secureFgpAcc?: string, + observe: any = 'body', + reportProgress: boolean = false, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable { + if (createAccountRequest === null || createAccountRequest === undefined) { + throw new Error( + 'Required parameter createAccountRequest was null or undefined when calling createAccount.', + ); } - /** - * List Organizations - * @endpoint get /api/accounts/organizations - * @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 listAccountOrganizations(secureFgpAcc?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public listAccountOrganizations(secureFgpAcc?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>>; - public listAccountOrganizations(secureFgpAcc?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>>; - public listAccountOrganizations(secureFgpAcc?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + let localVarHeaders = this.defaultHeaders; - let localVarHeaders = this.defaultHeaders; + // authentication (HTTPBearer) required + localVarHeaders = this.configuration.addCredentialToHeaders( + 'HTTPBearer', + 'Authorization', + localVarHeaders, + 'Bearer ', + ); - // authentication (HTTPBearer) required - localVarHeaders = this.configuration.addCredentialToHeaders('HTTPBearer', 'Authorization', localVarHeaders, 'Bearer '); - - const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([ - 'application/json' - ]); - if (localVarHttpHeaderAcceptSelected !== undefined) { - localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); - } - - const localVarHttpContext: HttpContext = options?.context ?? new HttpContext(); - - const localVarTransferCache: boolean = options?.transferCache ?? true; - - - let responseType_: 'text' | 'json' | 'blob' = 'json'; - if (localVarHttpHeaderAcceptSelected) { - if (localVarHttpHeaderAcceptSelected.startsWith('text')) { - responseType_ = 'text'; - } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { - responseType_ = 'json'; - } else { - responseType_ = 'blob'; - } - } - - let localVarPath = `/api/accounts/organizations`; - const { basePath, withCredentials } = this.configuration; - return this.httpClient.request>('get', `${basePath}${localVarPath}`, - { - context: localVarHttpContext, - responseType: responseType_, - ...(withCredentials ? { withCredentials } : {}), - headers: localVarHeaders, - observe: observe, - ...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}), - reportProgress: reportProgress - } - ); + const localVarHttpHeaderAcceptSelected: string | undefined = + options?.httpHeaderAccept ?? + this.configuration.selectHeaderAccept(['application/json']); + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set( + 'Accept', + localVarHttpHeaderAcceptSelected, + ); } - /** - * List Accounts - * @endpoint get /api/accounts - * @param page - * @param pageSize - * @param offset - * @param search - * @param organizationId - * @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 listAccounts(page?: number, pageSize?: number, offset?: number, search?: string, organizationId?: string, secureFgpAcc?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; - public listAccounts(page?: number, pageSize?: number, offset?: number, search?: string, organizationId?: string, secureFgpAcc?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public listAccounts(page?: number, pageSize?: number, offset?: number, search?: string, organizationId?: string, secureFgpAcc?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public listAccounts(page?: number, pageSize?: number, offset?: number, search?: string, organizationId?: string, secureFgpAcc?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + const localVarHttpContext: HttpContext = + options?.context ?? new HttpContext(); - let localVarQueryParameters = new HttpParams({encoder: this.encoder}); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - page, 'page'); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - pageSize, 'page_size'); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - offset, 'offset'); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - search, 'search'); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - organizationId, 'organization_id'); + const localVarTransferCache: boolean = options?.transferCache ?? true; - let localVarHeaders = this.defaultHeaders; - - // authentication (HTTPBearer) required - localVarHeaders = this.configuration.addCredentialToHeaders('HTTPBearer', 'Authorization', localVarHeaders, 'Bearer '); - - const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([ - 'application/json' - ]); - if (localVarHttpHeaderAcceptSelected !== undefined) { - localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); - } - - const localVarHttpContext: HttpContext = options?.context ?? new HttpContext(); - - const localVarTransferCache: boolean = options?.transferCache ?? true; - - - let responseType_: 'text' | 'json' | 'blob' = 'json'; - if (localVarHttpHeaderAcceptSelected) { - if (localVarHttpHeaderAcceptSelected.startsWith('text')) { - responseType_ = 'text'; - } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { - responseType_ = 'json'; - } else { - responseType_ = 'blob'; - } - } - - let localVarPath = `/api/accounts`; - const { basePath, withCredentials } = this.configuration; - return this.httpClient.request('get', `${basePath}${localVarPath}`, - { - context: localVarHttpContext, - params: localVarQueryParameters, - responseType: responseType_, - ...(withCredentials ? { withCredentials } : {}), - headers: localVarHeaders, - observe: observe, - ...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}), - reportProgress: reportProgress - } - ); + // to determine the Content-Type header + const consumes: string[] = ['application/json']; + const httpContentTypeSelected: string | undefined = + this.configuration.selectHeaderContentType(consumes); + if (httpContentTypeSelected !== undefined) { + localVarHeaders = localVarHeaders.set( + 'Content-Type', + httpContentTypeSelected, + ); } - /** - * Login with One-Time Key - * Login using a one-time key (OTK) sent to the user\'s email. - * @endpoint post /api/auth/v2/login - * @param bodyLogin - * @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 login(bodyLogin: BodyLogin, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; - public login(bodyLogin: BodyLogin, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public login(bodyLogin: BodyLogin, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public login(bodyLogin: BodyLogin, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { - if (bodyLogin === null || bodyLogin === undefined) { - throw new Error('Required parameter bodyLogin was null or undefined when calling login.'); - } - - let localVarHeaders = this.defaultHeaders; - - const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([ - 'application/json' - ]); - if (localVarHttpHeaderAcceptSelected !== undefined) { - localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); - } - - const localVarHttpContext: HttpContext = options?.context ?? new HttpContext(); - - const localVarTransferCache: boolean = options?.transferCache ?? true; - - - // to determine the Content-Type header - const consumes: string[] = [ - 'application/json' - ]; - const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes); - if (httpContentTypeSelected !== undefined) { - localVarHeaders = localVarHeaders.set('Content-Type', httpContentTypeSelected); - } - - let responseType_: 'text' | 'json' | 'blob' = 'json'; - if (localVarHttpHeaderAcceptSelected) { - if (localVarHttpHeaderAcceptSelected.startsWith('text')) { - responseType_ = 'text'; - } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { - responseType_ = 'json'; - } else { - responseType_ = 'blob'; - } - } - - let localVarPath = `/api/auth/v2/login`; - const { basePath, withCredentials } = this.configuration; - return this.httpClient.request('post', `${basePath}${localVarPath}`, - { - context: localVarHttpContext, - body: bodyLogin, - responseType: responseType_, - ...(withCredentials ? { withCredentials } : {}), - headers: localVarHeaders, - observe: observe, - ...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}), - reportProgress: reportProgress - } - ); + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if ( + this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected) + ) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } } - /** - * Logout - * Logout the authenticated user. - * @endpoint post /api/auth/v2/logout - * @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 logout(secureFgpAcc?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; - public logout(secureFgpAcc?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public logout(secureFgpAcc?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public logout(secureFgpAcc?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + let localVarPath = `/api/accounts`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request( + 'post', + `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + body: createAccountRequest, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined + ? { transferCache: localVarTransferCache } + : {}), + reportProgress: reportProgress, + }, + ); + } - let localVarHeaders = this.defaultHeaders; - - // authentication (HTTPBearer) required - localVarHeaders = this.configuration.addCredentialToHeaders('HTTPBearer', 'Authorization', localVarHeaders, 'Bearer '); - - const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([ - 'application/json' - ]); - if (localVarHttpHeaderAcceptSelected !== undefined) { - localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); - } - - const localVarHttpContext: HttpContext = options?.context ?? new HttpContext(); - - const localVarTransferCache: boolean = options?.transferCache ?? true; - - - let responseType_: 'text' | 'json' | 'blob' = 'json'; - if (localVarHttpHeaderAcceptSelected) { - if (localVarHttpHeaderAcceptSelected.startsWith('text')) { - responseType_ = 'text'; - } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { - responseType_ = 'json'; - } else { - responseType_ = 'blob'; - } - } - - let localVarPath = `/api/auth/v2/logout`; - const { basePath, withCredentials } = this.configuration; - return this.httpClient.request('post', `${basePath}${localVarPath}`, - { - context: localVarHttpContext, - responseType: responseType_, - ...(withCredentials ? { withCredentials } : {}), - headers: localVarHeaders, - observe: observe, - ...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}), - reportProgress: reportProgress - } - ); + /** + * Delete Account + * @endpoint delete /api/accounts/{account_id} + * @param accountId + * @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 deleteAccount( + accountId: string, + secureFgpAcc?: string, + observe?: 'body', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable; + public deleteAccount( + accountId: string, + secureFgpAcc?: string, + observe?: 'response', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public deleteAccount( + accountId: string, + secureFgpAcc?: string, + observe?: 'events', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public deleteAccount( + accountId: string, + secureFgpAcc?: string, + observe: any = 'body', + reportProgress: boolean = false, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable { + if (accountId === null || accountId === undefined) { + throw new Error( + 'Required parameter accountId was null or undefined when calling deleteAccount.', + ); } - /** - * Refresh Access Token - * Refresh the access token using a valid refresh token. - * @endpoint post /api/auth/v2/refresh - * @param refreshToken - * @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 refreshAccessToken(refreshToken?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; - public refreshAccessToken(refreshToken?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public refreshAccessToken(refreshToken?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public refreshAccessToken(refreshToken?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + let localVarHeaders = this.defaultHeaders; - let localVarHeaders = this.defaultHeaders; + // authentication (HTTPBearer) required + localVarHeaders = this.configuration.addCredentialToHeaders( + 'HTTPBearer', + 'Authorization', + localVarHeaders, + 'Bearer ', + ); - const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([ - 'application/json' - ]); - if (localVarHttpHeaderAcceptSelected !== undefined) { - localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); - } - - const localVarHttpContext: HttpContext = options?.context ?? new HttpContext(); - - const localVarTransferCache: boolean = options?.transferCache ?? true; - - - let responseType_: 'text' | 'json' | 'blob' = 'json'; - if (localVarHttpHeaderAcceptSelected) { - if (localVarHttpHeaderAcceptSelected.startsWith('text')) { - responseType_ = 'text'; - } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { - responseType_ = 'json'; - } else { - responseType_ = 'blob'; - } - } - - let localVarPath = `/api/auth/v2/refresh`; - const { basePath, withCredentials } = this.configuration; - return this.httpClient.request('post', `${basePath}${localVarPath}`, - { - context: localVarHttpContext, - responseType: responseType_, - ...(withCredentials ? { withCredentials } : {}), - headers: localVarHeaders, - observe: observe, - ...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}), - reportProgress: reportProgress - } - ); + const localVarHttpHeaderAcceptSelected: string | undefined = + options?.httpHeaderAccept ?? + this.configuration.selectHeaderAccept(['application/json']); + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set( + 'Accept', + localVarHttpHeaderAcceptSelected, + ); } - /** - * Request One-Time Key - * Request a one-time key (OTK) for authentication using email and password. - * @endpoint post /api/auth/v2/request-otk - * @param bodyRequestOtk - * @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 requestOtk(bodyRequestOtk: BodyRequestOtk, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; - public requestOtk(bodyRequestOtk: BodyRequestOtk, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public requestOtk(bodyRequestOtk: BodyRequestOtk, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public requestOtk(bodyRequestOtk: BodyRequestOtk, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { - if (bodyRequestOtk === null || bodyRequestOtk === undefined) { - throw new Error('Required parameter bodyRequestOtk was null or undefined when calling requestOtk.'); - } + const localVarHttpContext: HttpContext = + options?.context ?? new HttpContext(); - let localVarHeaders = this.defaultHeaders; + const localVarTransferCache: boolean = options?.transferCache ?? true; - const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([ - 'application/json' - ]); - if (localVarHttpHeaderAcceptSelected !== undefined) { - localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); - } - - const localVarHttpContext: HttpContext = options?.context ?? new HttpContext(); - - const localVarTransferCache: boolean = options?.transferCache ?? true; - - - // to determine the Content-Type header - const consumes: string[] = [ - 'application/json' - ]; - const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes); - if (httpContentTypeSelected !== undefined) { - localVarHeaders = localVarHeaders.set('Content-Type', httpContentTypeSelected); - } - - let responseType_: 'text' | 'json' | 'blob' = 'json'; - if (localVarHttpHeaderAcceptSelected) { - if (localVarHttpHeaderAcceptSelected.startsWith('text')) { - responseType_ = 'text'; - } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { - responseType_ = 'json'; - } else { - responseType_ = 'blob'; - } - } - - let localVarPath = `/api/auth/v2/request-otk`; - const { basePath, withCredentials } = this.configuration; - return this.httpClient.request('post', `${basePath}${localVarPath}`, - { - context: localVarHttpContext, - body: bodyRequestOtk, - responseType: responseType_, - ...(withCredentials ? { withCredentials } : {}), - headers: localVarHeaders, - observe: observe, - ...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}), - reportProgress: reportProgress - } - ); + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if ( + this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected) + ) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } } - /** - * Request Password Reset - * Request a one-time password reset link for the given email address. - * @endpoint post /api/auth/v2/request-password-reset - * @param bodyRequestPasswordReset - * @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 requestPasswordReset(bodyRequestPasswordReset: BodyRequestPasswordReset, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; - public requestPasswordReset(bodyRequestPasswordReset: BodyRequestPasswordReset, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public requestPasswordReset(bodyRequestPasswordReset: BodyRequestPasswordReset, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public requestPasswordReset(bodyRequestPasswordReset: BodyRequestPasswordReset, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { - if (bodyRequestPasswordReset === null || bodyRequestPasswordReset === undefined) { - throw new Error('Required parameter bodyRequestPasswordReset was null or undefined when calling requestPasswordReset.'); - } + let localVarPath = `/api/accounts/${this.configuration.encodeParam({ name: 'accountId', value: accountId, in: 'path', style: 'simple', explode: false, dataType: 'string', dataFormat: 'uuid' })}`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request( + 'delete', + `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined + ? { transferCache: localVarTransferCache } + : {}), + reportProgress: reportProgress, + }, + ); + } - let localVarHeaders = this.defaultHeaders; - - const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([ - 'application/json' - ]); - if (localVarHttpHeaderAcceptSelected !== undefined) { - localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); - } - - const localVarHttpContext: HttpContext = options?.context ?? new HttpContext(); - - const localVarTransferCache: boolean = options?.transferCache ?? true; - - - // to determine the Content-Type header - const consumes: string[] = [ - 'application/json' - ]; - const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes); - if (httpContentTypeSelected !== undefined) { - localVarHeaders = localVarHeaders.set('Content-Type', httpContentTypeSelected); - } - - let responseType_: 'text' | 'json' | 'blob' = 'json'; - if (localVarHttpHeaderAcceptSelected) { - if (localVarHttpHeaderAcceptSelected.startsWith('text')) { - responseType_ = 'text'; - } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { - responseType_ = 'json'; - } else { - responseType_ = 'blob'; - } - } - - let localVarPath = `/api/auth/v2/request-password-reset`; - const { basePath, withCredentials } = this.configuration; - return this.httpClient.request('post', `${basePath}${localVarPath}`, - { - context: localVarHttpContext, - body: bodyRequestPasswordReset, - responseType: responseType_, - ...(withCredentials ? { withCredentials } : {}), - headers: localVarHeaders, - observe: observe, - ...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}), - reportProgress: reportProgress - } - ); + /** + * Get Access Token + * Retrieve an access token for the authenticated user. + * @endpoint post /api/auth/v2/access + * @param bodyGetAccessToken + * @param idToken + * @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 getAccessToken( + bodyGetAccessToken: BodyGetAccessToken, + idToken?: string, + observe?: 'body', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable; + public getAccessToken( + bodyGetAccessToken: BodyGetAccessToken, + idToken?: string, + observe?: 'response', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public getAccessToken( + bodyGetAccessToken: BodyGetAccessToken, + idToken?: string, + observe?: 'events', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public getAccessToken( + bodyGetAccessToken: BodyGetAccessToken, + idToken?: string, + observe: any = 'body', + reportProgress: boolean = false, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable { + if (bodyGetAccessToken === null || bodyGetAccessToken === undefined) { + throw new Error( + 'Required parameter bodyGetAccessToken was null or undefined when calling getAccessToken.', + ); } - /** - * Reset Password - * Reset the user\'s password using a one-time password reset token. - * @endpoint post /api/auth/v2/reset-password - * @param bodyResetPassword - * @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 resetPassword(bodyResetPassword: BodyResetPassword, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; - public resetPassword(bodyResetPassword: BodyResetPassword, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public resetPassword(bodyResetPassword: BodyResetPassword, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public resetPassword(bodyResetPassword: BodyResetPassword, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { - if (bodyResetPassword === null || bodyResetPassword === undefined) { - throw new Error('Required parameter bodyResetPassword was null or undefined when calling resetPassword.'); - } + let localVarHeaders = this.defaultHeaders; - let localVarHeaders = this.defaultHeaders; - - const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([ - 'application/json' - ]); - if (localVarHttpHeaderAcceptSelected !== undefined) { - localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); - } - - const localVarHttpContext: HttpContext = options?.context ?? new HttpContext(); - - const localVarTransferCache: boolean = options?.transferCache ?? true; - - - // to determine the Content-Type header - const consumes: string[] = [ - 'application/json' - ]; - const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes); - if (httpContentTypeSelected !== undefined) { - localVarHeaders = localVarHeaders.set('Content-Type', httpContentTypeSelected); - } - - let responseType_: 'text' | 'json' | 'blob' = 'json'; - if (localVarHttpHeaderAcceptSelected) { - if (localVarHttpHeaderAcceptSelected.startsWith('text')) { - responseType_ = 'text'; - } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { - responseType_ = 'json'; - } else { - responseType_ = 'blob'; - } - } - - let localVarPath = `/api/auth/v2/reset-password`; - const { basePath, withCredentials } = this.configuration; - return this.httpClient.request('post', `${basePath}${localVarPath}`, - { - context: localVarHttpContext, - body: bodyResetPassword, - responseType: responseType_, - ...(withCredentials ? { withCredentials } : {}), - headers: localVarHeaders, - observe: observe, - ...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}), - reportProgress: reportProgress - } - ); + const localVarHttpHeaderAcceptSelected: string | undefined = + options?.httpHeaderAccept ?? + this.configuration.selectHeaderAccept(['application/json']); + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set( + 'Accept', + localVarHttpHeaderAcceptSelected, + ); } - /** - * Update Account - * @endpoint put /api/accounts/{account_id} - * @param accountId - * @param updateAccountRequest - * @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 updateAccount(accountId: string, updateAccountRequest: UpdateAccountRequest, secureFgpAcc?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; - public updateAccount(accountId: string, updateAccountRequest: UpdateAccountRequest, secureFgpAcc?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public updateAccount(accountId: string, updateAccountRequest: UpdateAccountRequest, secureFgpAcc?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public updateAccount(accountId: string, updateAccountRequest: UpdateAccountRequest, secureFgpAcc?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { - if (accountId === null || accountId === undefined) { - throw new Error('Required parameter accountId was null or undefined when calling updateAccount.'); - } - if (updateAccountRequest === null || updateAccountRequest === undefined) { - throw new Error('Required parameter updateAccountRequest was null or undefined when calling updateAccount.'); - } + const localVarHttpContext: HttpContext = + options?.context ?? new HttpContext(); - let localVarHeaders = this.defaultHeaders; + const localVarTransferCache: boolean = options?.transferCache ?? true; - // authentication (HTTPBearer) required - localVarHeaders = this.configuration.addCredentialToHeaders('HTTPBearer', 'Authorization', localVarHeaders, 'Bearer '); - - const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([ - 'application/json' - ]); - if (localVarHttpHeaderAcceptSelected !== undefined) { - localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); - } - - const localVarHttpContext: HttpContext = options?.context ?? new HttpContext(); - - const localVarTransferCache: boolean = options?.transferCache ?? true; - - - // to determine the Content-Type header - const consumes: string[] = [ - 'application/json' - ]; - const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes); - if (httpContentTypeSelected !== undefined) { - localVarHeaders = localVarHeaders.set('Content-Type', httpContentTypeSelected); - } - - let responseType_: 'text' | 'json' | 'blob' = 'json'; - if (localVarHttpHeaderAcceptSelected) { - if (localVarHttpHeaderAcceptSelected.startsWith('text')) { - responseType_ = 'text'; - } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { - responseType_ = 'json'; - } else { - responseType_ = 'blob'; - } - } - - let localVarPath = `/api/accounts/${this.configuration.encodeParam({name: "accountId", value: accountId, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: "uuid"})}`; - const { basePath, withCredentials } = this.configuration; - return this.httpClient.request('put', `${basePath}${localVarPath}`, - { - context: localVarHttpContext, - body: updateAccountRequest, - responseType: responseType_, - ...(withCredentials ? { withCredentials } : {}), - headers: localVarHeaders, - observe: observe, - ...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}), - reportProgress: reportProgress - } - ); + // to determine the Content-Type header + const consumes: string[] = ['application/json']; + const httpContentTypeSelected: string | undefined = + this.configuration.selectHeaderContentType(consumes); + if (httpContentTypeSelected !== undefined) { + localVarHeaders = localVarHeaders.set( + 'Content-Type', + httpContentTypeSelected, + ); } + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if ( + this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected) + ) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/api/auth/v2/access`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request( + 'post', + `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + body: bodyGetAccessToken, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined + ? { transferCache: localVarTransferCache } + : {}), + reportProgress: reportProgress, + }, + ); + } + + /** + * Get Current Account + * @endpoint get /api/accounts/me + * @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 getCurrentAccount( + secureFgpAcc?: string, + observe?: 'body', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable; + public getCurrentAccount( + secureFgpAcc?: string, + observe?: 'response', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public getCurrentAccount( + secureFgpAcc?: string, + observe?: 'events', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public getCurrentAccount( + secureFgpAcc?: string, + observe: any = 'body', + reportProgress: boolean = false, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable { + let localVarHeaders = this.defaultHeaders; + + // authentication (HTTPBearer) required + localVarHeaders = this.configuration.addCredentialToHeaders( + 'HTTPBearer', + 'Authorization', + localVarHeaders, + 'Bearer ', + ); + + const localVarHttpHeaderAcceptSelected: string | undefined = + options?.httpHeaderAccept ?? + this.configuration.selectHeaderAccept(['application/json']); + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set( + 'Accept', + localVarHttpHeaderAcceptSelected, + ); + } + + const localVarHttpContext: HttpContext = + options?.context ?? new HttpContext(); + + const localVarTransferCache: boolean = options?.transferCache ?? true; + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if ( + this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected) + ) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/api/accounts/me`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request( + 'get', + `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined + ? { transferCache: localVarTransferCache } + : {}), + reportProgress: reportProgress, + }, + ); + } + + /** + * Health Check + * @endpoint get /api/auth/v2/health + * @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 healthCheckApiAuthV2HealthGet( + observe?: 'body', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable; + public healthCheckApiAuthV2HealthGet( + observe?: 'response', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public healthCheckApiAuthV2HealthGet( + observe?: 'events', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public healthCheckApiAuthV2HealthGet( + observe: any = 'body', + reportProgress: boolean = false, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable { + let localVarHeaders = this.defaultHeaders; + + const localVarHttpHeaderAcceptSelected: string | undefined = + options?.httpHeaderAccept ?? + this.configuration.selectHeaderAccept(['application/json']); + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set( + 'Accept', + localVarHttpHeaderAcceptSelected, + ); + } + + const localVarHttpContext: HttpContext = + options?.context ?? new HttpContext(); + + const localVarTransferCache: boolean = options?.transferCache ?? true; + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if ( + this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected) + ) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/api/auth/v2/health`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request('get', `${basePath}${localVarPath}`, { + context: localVarHttpContext, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined + ? { transferCache: localVarTransferCache } + : {}), + reportProgress: reportProgress, + }); + } + + /** + * List Organizations + * @endpoint get /api/accounts/organizations + * @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 listAccountOrganizations( + secureFgpAcc?: string, + observe?: 'body', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public listAccountOrganizations( + secureFgpAcc?: string, + observe?: 'response', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable< + HttpResponse> + >; + public listAccountOrganizations( + secureFgpAcc?: string, + observe?: 'events', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable< + HttpEvent> + >; + public listAccountOrganizations( + secureFgpAcc?: string, + observe: any = 'body', + reportProgress: boolean = false, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable { + let localVarHeaders = this.defaultHeaders; + + // authentication (HTTPBearer) required + localVarHeaders = this.configuration.addCredentialToHeaders( + 'HTTPBearer', + 'Authorization', + localVarHeaders, + 'Bearer ', + ); + + const localVarHttpHeaderAcceptSelected: string | undefined = + options?.httpHeaderAccept ?? + this.configuration.selectHeaderAccept(['application/json']); + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set( + 'Accept', + localVarHttpHeaderAcceptSelected, + ); + } + + const localVarHttpContext: HttpContext = + options?.context ?? new HttpContext(); + + const localVarTransferCache: boolean = options?.transferCache ?? true; + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if ( + this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected) + ) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/api/accounts/organizations`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request< + Array + >('get', `${basePath}${localVarPath}`, { + context: localVarHttpContext, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined + ? { transferCache: localVarTransferCache } + : {}), + reportProgress: reportProgress, + }); + } + + /** + * List Accounts + * @endpoint get /api/accounts + * @param page + * @param pageSize + * @param offset + * @param search + * @param organizationId + * @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 listAccounts( + page?: number, + pageSize?: number, + offset?: number, + search?: string, + organizationId?: string, + secureFgpAcc?: string, + observe?: 'body', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable; + public listAccounts( + page?: number, + pageSize?: number, + offset?: number, + search?: string, + organizationId?: string, + secureFgpAcc?: string, + observe?: 'response', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public listAccounts( + page?: number, + pageSize?: number, + offset?: number, + search?: string, + organizationId?: string, + secureFgpAcc?: string, + observe?: 'events', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public listAccounts( + page?: number, + pageSize?: number, + offset?: number, + search?: string, + organizationId?: string, + secureFgpAcc?: string, + observe: any = 'body', + reportProgress: boolean = false, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable { + let localVarQueryParameters = new HttpParams({ encoder: this.encoder }); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + page, + 'page', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + pageSize, + 'page_size', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + offset, + 'offset', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + search, + 'search', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + organizationId, + 'organization_id', + ); + + let localVarHeaders = this.defaultHeaders; + + // authentication (HTTPBearer) required + localVarHeaders = this.configuration.addCredentialToHeaders( + 'HTTPBearer', + 'Authorization', + localVarHeaders, + 'Bearer ', + ); + + const localVarHttpHeaderAcceptSelected: string | undefined = + options?.httpHeaderAccept ?? + this.configuration.selectHeaderAccept(['application/json']); + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set( + 'Accept', + localVarHttpHeaderAcceptSelected, + ); + } + + const localVarHttpContext: HttpContext = + options?.context ?? new HttpContext(); + + const localVarTransferCache: boolean = options?.transferCache ?? true; + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if ( + this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected) + ) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/api/accounts`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request( + 'get', + `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + params: localVarQueryParameters, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined + ? { transferCache: localVarTransferCache } + : {}), + reportProgress: reportProgress, + }, + ); + } + + /** + * Login with One-Time Key + * Login using a one-time key (OTK) sent to the user\'s email. + * @endpoint post /api/auth/v2/login + * @param bodyLogin + * @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 login( + bodyLogin: BodyLogin, + observe?: 'body', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable; + public login( + bodyLogin: BodyLogin, + observe?: 'response', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public login( + bodyLogin: BodyLogin, + observe?: 'events', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public login( + bodyLogin: BodyLogin, + observe: any = 'body', + reportProgress: boolean = false, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable { + if (bodyLogin === null || bodyLogin === undefined) { + throw new Error( + 'Required parameter bodyLogin was null or undefined when calling login.', + ); + } + + let localVarHeaders = this.defaultHeaders; + + const localVarHttpHeaderAcceptSelected: string | undefined = + options?.httpHeaderAccept ?? + this.configuration.selectHeaderAccept(['application/json']); + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set( + 'Accept', + localVarHttpHeaderAcceptSelected, + ); + } + + const localVarHttpContext: HttpContext = + options?.context ?? new HttpContext(); + + const localVarTransferCache: boolean = options?.transferCache ?? true; + + // to determine the Content-Type header + const consumes: string[] = ['application/json']; + const httpContentTypeSelected: string | undefined = + this.configuration.selectHeaderContentType(consumes); + if (httpContentTypeSelected !== undefined) { + localVarHeaders = localVarHeaders.set( + 'Content-Type', + httpContentTypeSelected, + ); + } + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if ( + this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected) + ) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/api/auth/v2/login`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request( + 'post', + `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + body: bodyLogin, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined + ? { transferCache: localVarTransferCache } + : {}), + reportProgress: reportProgress, + }, + ); + } + + /** + * Logout + * Logout the authenticated user. + * @endpoint post /api/auth/v2/logout + * @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 logout( + secureFgpAcc?: string, + observe?: 'body', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable; + public logout( + secureFgpAcc?: string, + observe?: 'response', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public logout( + secureFgpAcc?: string, + observe?: 'events', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public logout( + secureFgpAcc?: string, + observe: any = 'body', + reportProgress: boolean = false, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable { + let localVarHeaders = this.defaultHeaders; + + // authentication (HTTPBearer) required + localVarHeaders = this.configuration.addCredentialToHeaders( + 'HTTPBearer', + 'Authorization', + localVarHeaders, + 'Bearer ', + ); + + const localVarHttpHeaderAcceptSelected: string | undefined = + options?.httpHeaderAccept ?? + this.configuration.selectHeaderAccept(['application/json']); + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set( + 'Accept', + localVarHttpHeaderAcceptSelected, + ); + } + + const localVarHttpContext: HttpContext = + options?.context ?? new HttpContext(); + + const localVarTransferCache: boolean = options?.transferCache ?? true; + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if ( + this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected) + ) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/api/auth/v2/logout`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request('post', `${basePath}${localVarPath}`, { + context: localVarHttpContext, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined + ? { transferCache: localVarTransferCache } + : {}), + reportProgress: reportProgress, + }); + } + + /** + * Refresh Access Token + * Refresh the access token using a valid refresh token. + * @endpoint post /api/auth/v2/refresh + * @param refreshToken + * @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 refreshAccessToken( + refreshToken?: string, + observe?: 'body', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable; + public refreshAccessToken( + refreshToken?: string, + observe?: 'response', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public refreshAccessToken( + refreshToken?: string, + observe?: 'events', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public refreshAccessToken( + refreshToken?: string, + observe: any = 'body', + reportProgress: boolean = false, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable { + let localVarHeaders = this.defaultHeaders; + + const localVarHttpHeaderAcceptSelected: string | undefined = + options?.httpHeaderAccept ?? + this.configuration.selectHeaderAccept(['application/json']); + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set( + 'Accept', + localVarHttpHeaderAcceptSelected, + ); + } + + const localVarHttpContext: HttpContext = + options?.context ?? new HttpContext(); + + const localVarTransferCache: boolean = options?.transferCache ?? true; + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if ( + this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected) + ) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/api/auth/v2/refresh`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request( + 'post', + `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined + ? { transferCache: localVarTransferCache } + : {}), + reportProgress: reportProgress, + }, + ); + } + + /** + * Request One-Time Key + * Request a one-time key (OTK) for authentication using email and password. + * @endpoint post /api/auth/v2/request-otk + * @param bodyRequestOtk + * @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 requestOtk( + bodyRequestOtk: BodyRequestOtk, + observe?: 'body', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable; + public requestOtk( + bodyRequestOtk: BodyRequestOtk, + observe?: 'response', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public requestOtk( + bodyRequestOtk: BodyRequestOtk, + observe?: 'events', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public requestOtk( + bodyRequestOtk: BodyRequestOtk, + observe: any = 'body', + reportProgress: boolean = false, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable { + if (bodyRequestOtk === null || bodyRequestOtk === undefined) { + throw new Error( + 'Required parameter bodyRequestOtk was null or undefined when calling requestOtk.', + ); + } + + let localVarHeaders = this.defaultHeaders; + + const localVarHttpHeaderAcceptSelected: string | undefined = + options?.httpHeaderAccept ?? + this.configuration.selectHeaderAccept(['application/json']); + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set( + 'Accept', + localVarHttpHeaderAcceptSelected, + ); + } + + const localVarHttpContext: HttpContext = + options?.context ?? new HttpContext(); + + const localVarTransferCache: boolean = options?.transferCache ?? true; + + // to determine the Content-Type header + const consumes: string[] = ['application/json']; + const httpContentTypeSelected: string | undefined = + this.configuration.selectHeaderContentType(consumes); + if (httpContentTypeSelected !== undefined) { + localVarHeaders = localVarHeaders.set( + 'Content-Type', + httpContentTypeSelected, + ); + } + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if ( + this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected) + ) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/api/auth/v2/request-otk`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request( + 'post', + `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + body: bodyRequestOtk, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined + ? { transferCache: localVarTransferCache } + : {}), + reportProgress: reportProgress, + }, + ); + } + + /** + * Request Password Reset + * Request a one-time password reset link for the given email address. + * @endpoint post /api/auth/v2/request-password-reset + * @param bodyRequestPasswordReset + * @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 requestPasswordReset( + bodyRequestPasswordReset: BodyRequestPasswordReset, + observe?: 'body', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable; + public requestPasswordReset( + bodyRequestPasswordReset: BodyRequestPasswordReset, + observe?: 'response', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public requestPasswordReset( + bodyRequestPasswordReset: BodyRequestPasswordReset, + observe?: 'events', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public requestPasswordReset( + bodyRequestPasswordReset: BodyRequestPasswordReset, + observe: any = 'body', + reportProgress: boolean = false, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable { + if ( + bodyRequestPasswordReset === null || + bodyRequestPasswordReset === undefined + ) { + throw new Error( + 'Required parameter bodyRequestPasswordReset was null or undefined when calling requestPasswordReset.', + ); + } + + let localVarHeaders = this.defaultHeaders; + + const localVarHttpHeaderAcceptSelected: string | undefined = + options?.httpHeaderAccept ?? + this.configuration.selectHeaderAccept(['application/json']); + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set( + 'Accept', + localVarHttpHeaderAcceptSelected, + ); + } + + const localVarHttpContext: HttpContext = + options?.context ?? new HttpContext(); + + const localVarTransferCache: boolean = options?.transferCache ?? true; + + // to determine the Content-Type header + const consumes: string[] = ['application/json']; + const httpContentTypeSelected: string | undefined = + this.configuration.selectHeaderContentType(consumes); + if (httpContentTypeSelected !== undefined) { + localVarHeaders = localVarHeaders.set( + 'Content-Type', + httpContentTypeSelected, + ); + } + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if ( + this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected) + ) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/api/auth/v2/request-password-reset`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request('post', `${basePath}${localVarPath}`, { + context: localVarHttpContext, + body: bodyRequestPasswordReset, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined + ? { transferCache: localVarTransferCache } + : {}), + reportProgress: reportProgress, + }); + } + + /** + * Reset Password + * Reset the user\'s password using a one-time password reset token. + * @endpoint post /api/auth/v2/reset-password + * @param bodyResetPassword + * @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 resetPassword( + bodyResetPassword: BodyResetPassword, + observe?: 'body', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable; + public resetPassword( + bodyResetPassword: BodyResetPassword, + observe?: 'response', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public resetPassword( + bodyResetPassword: BodyResetPassword, + observe?: 'events', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public resetPassword( + bodyResetPassword: BodyResetPassword, + observe: any = 'body', + reportProgress: boolean = false, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable { + if (bodyResetPassword === null || bodyResetPassword === undefined) { + throw new Error( + 'Required parameter bodyResetPassword was null or undefined when calling resetPassword.', + ); + } + + let localVarHeaders = this.defaultHeaders; + + const localVarHttpHeaderAcceptSelected: string | undefined = + options?.httpHeaderAccept ?? + this.configuration.selectHeaderAccept(['application/json']); + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set( + 'Accept', + localVarHttpHeaderAcceptSelected, + ); + } + + const localVarHttpContext: HttpContext = + options?.context ?? new HttpContext(); + + const localVarTransferCache: boolean = options?.transferCache ?? true; + + // to determine the Content-Type header + const consumes: string[] = ['application/json']; + const httpContentTypeSelected: string | undefined = + this.configuration.selectHeaderContentType(consumes); + if (httpContentTypeSelected !== undefined) { + localVarHeaders = localVarHeaders.set( + 'Content-Type', + httpContentTypeSelected, + ); + } + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if ( + this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected) + ) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/api/auth/v2/reset-password`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request('post', `${basePath}${localVarPath}`, { + context: localVarHttpContext, + body: bodyResetPassword, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined + ? { transferCache: localVarTransferCache } + : {}), + reportProgress: reportProgress, + }); + } + + /** + * Update Account + * @endpoint put /api/accounts/{account_id} + * @param accountId + * @param updateAccountRequest + * @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 updateAccount( + accountId: string, + updateAccountRequest: UpdateAccountRequest, + secureFgpAcc?: string, + observe?: 'body', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable; + public updateAccount( + accountId: string, + updateAccountRequest: UpdateAccountRequest, + secureFgpAcc?: string, + observe?: 'response', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public updateAccount( + accountId: string, + updateAccountRequest: UpdateAccountRequest, + secureFgpAcc?: string, + observe?: 'events', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public updateAccount( + accountId: string, + updateAccountRequest: UpdateAccountRequest, + secureFgpAcc?: string, + observe: any = 'body', + reportProgress: boolean = false, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable { + if (accountId === null || accountId === undefined) { + throw new Error( + 'Required parameter accountId was null or undefined when calling updateAccount.', + ); + } + if (updateAccountRequest === null || updateAccountRequest === undefined) { + throw new Error( + 'Required parameter updateAccountRequest was null or undefined when calling updateAccount.', + ); + } + + let localVarHeaders = this.defaultHeaders; + + // authentication (HTTPBearer) required + localVarHeaders = this.configuration.addCredentialToHeaders( + 'HTTPBearer', + 'Authorization', + localVarHeaders, + 'Bearer ', + ); + + const localVarHttpHeaderAcceptSelected: string | undefined = + options?.httpHeaderAccept ?? + this.configuration.selectHeaderAccept(['application/json']); + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set( + 'Accept', + localVarHttpHeaderAcceptSelected, + ); + } + + const localVarHttpContext: HttpContext = + options?.context ?? new HttpContext(); + + const localVarTransferCache: boolean = options?.transferCache ?? true; + + // to determine the Content-Type header + const consumes: string[] = ['application/json']; + const httpContentTypeSelected: string | undefined = + this.configuration.selectHeaderContentType(consumes); + if (httpContentTypeSelected !== undefined) { + localVarHeaders = localVarHeaders.set( + 'Content-Type', + httpContentTypeSelected, + ); + } + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if ( + this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected) + ) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/api/accounts/${this.configuration.encodeParam({ name: 'accountId', value: accountId, in: 'path', style: 'simple', explode: false, dataType: 'string', dataFormat: 'uuid' })}`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request( + 'put', + `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + body: updateAccountRequest, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined + ? { transferCache: localVarTransferCache } + : {}), + reportProgress: reportProgress, + }, + ); + } } diff --git a/webapp/src/app/api/api/news.service.ts b/webapp/src/app/api/api/news.service.ts index 8ff477cf..6d7a4c53 100644 --- a/webapp/src/app/api/api/news.service.ts +++ b/webapp/src/app/api/api/news.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 { HTTPValidationError } from '../model/hTTPValidationError'; @@ -24,567 +30,1563 @@ import { NewsArticleDetail } from '../model/newsArticleDetail'; import { NewsPage } from '../model/newsPage'; // @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 NewsService 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); + /** + * Returns news articles in which the given person is mentioned. + * @endpoint get /api/news/by-author + * @param authorId OpenAlex author id, e.g. A5034365278. + * @param page Page number (1-based). + * @param pageSize Articles per page. + * @param sortOrder Sort order: \'desc\' (newest first) or \'asc\' (oldest first). + * @param query Optional search term, matched against title/author. + * @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 getNewsByAuthor( + authorId: string, + page?: number, + pageSize?: number, + sortOrder?: string, + query?: string, + observe?: 'body', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable; + public getNewsByAuthor( + authorId: string, + page?: number, + pageSize?: number, + sortOrder?: string, + query?: string, + observe?: 'response', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public getNewsByAuthor( + authorId: string, + page?: number, + pageSize?: number, + sortOrder?: string, + query?: string, + observe?: 'events', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public getNewsByAuthor( + authorId: string, + page?: number, + pageSize?: number, + sortOrder?: string, + query?: string, + observe: any = 'body', + reportProgress: boolean = false, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable { + if (authorId === null || authorId === undefined) { + throw new Error( + 'Required parameter authorId was null or undefined when calling getNewsByAuthor.', + ); } - /** - * Returns news articles in which the given person is mentioned. - * @endpoint get /api/news/by-author - * @param authorId OpenAlex author id, e.g. A5034365278. - * @param page Page number (1-based). - * @param pageSize Articles per page. - * @param sortOrder Sort order: \'desc\' (newest first) or \'asc\' (oldest first). - * @param query Optional search term, matched against title/author. - * @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 getNewsByAuthor(authorId: string, page?: number, pageSize?: number, sortOrder?: string, query?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; - public getNewsByAuthor(authorId: string, page?: number, pageSize?: number, sortOrder?: string, query?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public getNewsByAuthor(authorId: string, page?: number, pageSize?: number, sortOrder?: string, query?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public getNewsByAuthor(authorId: string, page?: number, pageSize?: number, sortOrder?: string, query?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { - if (authorId === null || authorId === undefined) { - throw new Error('Required parameter authorId was null or undefined when calling getNewsByAuthor.'); - } + let localVarQueryParameters = new HttpParams({ encoder: this.encoder }); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + authorId, + 'authorId', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + page, + 'page', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + pageSize, + 'pageSize', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + sortOrder, + 'sortOrder', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + query, + 'query', + ); - let localVarQueryParameters = new HttpParams({encoder: this.encoder}); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - authorId, 'authorId'); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - page, 'page'); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - pageSize, 'pageSize'); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - sortOrder, 'sortOrder'); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - query, 'query'); + let localVarHeaders = this.defaultHeaders; - let localVarHeaders = this.defaultHeaders; + const localVarHttpHeaderAcceptSelected: string | undefined = + options?.httpHeaderAccept ?? + this.configuration.selectHeaderAccept(['application/json']); + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set( + 'Accept', + localVarHttpHeaderAcceptSelected, + ); + } - const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([ - 'application/json' - ]); - if (localVarHttpHeaderAcceptSelected !== undefined) { - localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); - } + const localVarHttpContext: HttpContext = + options?.context ?? new HttpContext(); - const localVarHttpContext: HttpContext = options?.context ?? new HttpContext(); + const localVarTransferCache: boolean = options?.transferCache ?? true; - const localVarTransferCache: boolean = options?.transferCache ?? true; + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if ( + this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected) + ) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + let localVarPath = `/api/news/by-author`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request( + 'get', + `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + params: localVarQueryParameters, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined + ? { transferCache: localVarTransferCache } + : {}), + reportProgress: reportProgress, + }, + ); + } - let responseType_: 'text' | 'json' | 'blob' = 'json'; - if (localVarHttpHeaderAcceptSelected) { - if (localVarHttpHeaderAcceptSelected.startsWith('text')) { - responseType_ = 'text'; - } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { - responseType_ = 'json'; - } else { - responseType_ = 'blob'; - } - } + /** + * Returns news articles in which the given person is mentioned. + * @endpoint get /api/news/by-author + * @param authorId OpenAlex author id, e.g. A5034365278. + * @param page Page number (1-based). + * @param pageSize Articles per page. + * @param sortOrder Sort order: \'desc\' (newest first) or \'asc\' (oldest first). + * @param query Optional search term, matched against title/author. + * @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 getNewsByAuthor_1( + authorId: string, + page?: number, + pageSize?: number, + sortOrder?: string, + query?: string, + observe?: 'body', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable; + public getNewsByAuthor_1( + authorId: string, + page?: number, + pageSize?: number, + sortOrder?: string, + query?: string, + observe?: 'response', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public getNewsByAuthor_1( + authorId: string, + page?: number, + pageSize?: number, + sortOrder?: string, + query?: string, + observe?: 'events', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public getNewsByAuthor_1( + authorId: string, + page?: number, + pageSize?: number, + sortOrder?: string, + query?: string, + observe: any = 'body', + reportProgress: boolean = false, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable { + if (authorId === null || authorId === undefined) { + throw new Error( + 'Required parameter authorId was null or undefined when calling getNewsByAuthor_1.', + ); + } - let localVarPath = `/api/news/by-author`; - const { basePath, withCredentials } = this.configuration; - return this.httpClient.request('get', `${basePath}${localVarPath}`, - { - context: localVarHttpContext, - params: localVarQueryParameters, - responseType: responseType_, - ...(withCredentials ? { withCredentials } : {}), - headers: localVarHeaders, - observe: observe, - ...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}), - reportProgress: reportProgress - } + let localVarQueryParameters = new HttpParams({ encoder: this.encoder }); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + authorId, + 'authorId', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + page, + 'page', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + pageSize, + 'pageSize', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + sortOrder, + 'sortOrder', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + query, + 'query', + ); + + let localVarHeaders = this.defaultHeaders; + + const localVarHttpHeaderAcceptSelected: string | undefined = + options?.httpHeaderAccept ?? + this.configuration.selectHeaderAccept(['application/json']); + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set( + 'Accept', + localVarHttpHeaderAcceptSelected, + ); + } + + const localVarHttpContext: HttpContext = + options?.context ?? new HttpContext(); + + const localVarTransferCache: boolean = options?.transferCache ?? true; + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if ( + this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected) + ) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/api/news/by-author`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request( + 'get', + `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + params: localVarQueryParameters, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined + ? { transferCache: localVarTransferCache } + : {}), + reportProgress: reportProgress, + }, + ); + } + + /** + * Returns a single news article including its full content. + * @endpoint get /api/news/{news_id} + * @param newsId The unique id of the news article (Elasticsearch _id). + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public getNewsById( + newsId: string, + observe?: 'body', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable; + public getNewsById( + newsId: string, + observe?: 'response', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public getNewsById( + newsId: string, + observe?: 'events', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public getNewsById( + newsId: string, + observe: any = 'body', + reportProgress: boolean = false, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable { + if (newsId === null || newsId === undefined) { + throw new Error( + 'Required parameter newsId was null or undefined when calling getNewsById.', + ); + } + + let localVarHeaders = this.defaultHeaders; + + const localVarHttpHeaderAcceptSelected: string | undefined = + options?.httpHeaderAccept ?? + this.configuration.selectHeaderAccept(['application/json']); + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set( + 'Accept', + localVarHttpHeaderAcceptSelected, + ); + } + + const localVarHttpContext: HttpContext = + options?.context ?? new HttpContext(); + + const localVarTransferCache: boolean = options?.transferCache ?? true; + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if ( + this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected) + ) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/api/news/${this.configuration.encodeParam({ name: 'newsId', value: newsId, in: 'path', style: 'simple', explode: false, dataType: 'string', dataFormat: undefined })}`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request( + 'get', + `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined + ? { transferCache: localVarTransferCache } + : {}), + reportProgress: reportProgress, + }, + ); + } + + /** + * Returns a single news article including its full content. + * @endpoint get /api/news/{news_id} + * @param newsId The unique id of the news article (Elasticsearch _id). + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public getNewsById_2( + newsId: string, + observe?: 'body', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable; + public getNewsById_2( + newsId: string, + observe?: 'response', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public getNewsById_2( + newsId: string, + observe?: 'events', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public getNewsById_2( + newsId: string, + observe: any = 'body', + reportProgress: boolean = false, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable { + if (newsId === null || newsId === undefined) { + throw new Error( + 'Required parameter newsId was null or undefined when calling getNewsById_2.', + ); + } + + let localVarHeaders = this.defaultHeaders; + + const localVarHttpHeaderAcceptSelected: string | undefined = + options?.httpHeaderAccept ?? + this.configuration.selectHeaderAccept(['application/json']); + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set( + 'Accept', + localVarHttpHeaderAcceptSelected, + ); + } + + const localVarHttpContext: HttpContext = + options?.context ?? new HttpContext(); + + const localVarTransferCache: boolean = options?.transferCache ?? true; + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if ( + this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected) + ) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/api/news/${this.configuration.encodeParam({ name: 'newsId', value: newsId, in: 'path', style: 'simple', explode: false, dataType: 'string', dataFormat: undefined })}`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request( + 'get', + `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined + ? { transferCache: localVarTransferCache } + : {}), + reportProgress: reportProgress, + }, + ); + } + + /** + * Searches news articles by the keywords or matched topics of a keywords search. + * @endpoint get /api/news/keyword/search + * @param keywords Raw keywords to match against title/content. + * @param topicIds OpenAlex topic ids the keywords resolved to. + * @param filterTopicIds Additional topic ids to narrow the results by. + * @param fuzzy Search by resolved topics if True, otherwise by raw keywords. + * @param page Page number (1-based). + * @param pageSize Articles per page. + * @param relevance Comma-separated relevance filter: \'relevant\', \'not_relevant\'. + * @param yearFrom Earliest publication year (inclusive). + * @param yearTo Latest publication year (inclusive). + * @param sortOrder Overrides relevance ranking with a date sort: \'desc\' (newest first) or \'asc\' (oldest first). + * @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 getNewsByKeywords( + keywords?: Array, + topicIds?: Array, + filterTopicIds?: Array, + fuzzy?: boolean, + page?: number, + pageSize?: number, + relevance?: string, + yearFrom?: number, + yearTo?: number, + sortOrder?: string, + observe?: 'body', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable; + public getNewsByKeywords( + keywords?: Array, + topicIds?: Array, + filterTopicIds?: Array, + fuzzy?: boolean, + page?: number, + pageSize?: number, + relevance?: string, + yearFrom?: number, + yearTo?: number, + sortOrder?: string, + observe?: 'response', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public getNewsByKeywords( + keywords?: Array, + topicIds?: Array, + filterTopicIds?: Array, + fuzzy?: boolean, + page?: number, + pageSize?: number, + relevance?: string, + yearFrom?: number, + yearTo?: number, + sortOrder?: string, + observe?: 'events', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public getNewsByKeywords( + keywords?: Array, + topicIds?: Array, + filterTopicIds?: Array, + fuzzy?: boolean, + page?: number, + pageSize?: number, + relevance?: string, + yearFrom?: number, + yearTo?: number, + sortOrder?: string, + observe: any = 'body', + reportProgress: boolean = false, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable { + let localVarQueryParameters = new HttpParams({ encoder: this.encoder }); + if (keywords) { + keywords.forEach((element) => { + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + element, + 'keywords', ); + }); } - - /** - * Returns news articles in which the given person is mentioned. - * @endpoint get /api/news/by-author - * @param authorId OpenAlex author id, e.g. A5034365278. - * @param page Page number (1-based). - * @param pageSize Articles per page. - * @param sortOrder Sort order: \'desc\' (newest first) or \'asc\' (oldest first). - * @param query Optional search term, matched against title/author. - * @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 getNewsByAuthor_1(authorId: string, page?: number, pageSize?: number, sortOrder?: string, query?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; - public getNewsByAuthor_1(authorId: string, page?: number, pageSize?: number, sortOrder?: string, query?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public getNewsByAuthor_1(authorId: string, page?: number, pageSize?: number, sortOrder?: string, query?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public getNewsByAuthor_1(authorId: string, page?: number, pageSize?: number, sortOrder?: string, query?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { - if (authorId === null || authorId === undefined) { - throw new Error('Required parameter authorId was null or undefined when calling getNewsByAuthor_1.'); - } - - let localVarQueryParameters = new HttpParams({encoder: this.encoder}); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - authorId, 'authorId'); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - page, 'page'); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - pageSize, 'pageSize'); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - sortOrder, 'sortOrder'); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - query, 'query'); - - let localVarHeaders = this.defaultHeaders; - - const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([ - 'application/json' - ]); - if (localVarHttpHeaderAcceptSelected !== undefined) { - localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); - } - - const localVarHttpContext: HttpContext = options?.context ?? new HttpContext(); - - const localVarTransferCache: boolean = options?.transferCache ?? true; - - - let responseType_: 'text' | 'json' | 'blob' = 'json'; - if (localVarHttpHeaderAcceptSelected) { - if (localVarHttpHeaderAcceptSelected.startsWith('text')) { - responseType_ = 'text'; - } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { - responseType_ = 'json'; - } else { - responseType_ = 'blob'; - } - } - - let localVarPath = `/api/news/by-author`; - const { basePath, withCredentials } = this.configuration; - return this.httpClient.request('get', `${basePath}${localVarPath}`, - { - context: localVarHttpContext, - params: localVarQueryParameters, - responseType: responseType_, - ...(withCredentials ? { withCredentials } : {}), - headers: localVarHeaders, - observe: observe, - ...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}), - reportProgress: reportProgress - } + if (topicIds) { + topicIds.forEach((element) => { + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + element, + 'topicIds', ); + }); } - - /** - * Returns a single news article including its full content. - * @endpoint get /api/news/{news_id} - * @param newsId The unique id of the news article (Elasticsearch _id). - * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. - * @param reportProgress flag to report request and response progress. - */ - public getNewsById(newsId: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; - public getNewsById(newsId: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public getNewsById(newsId: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public getNewsById(newsId: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { - if (newsId === null || newsId === undefined) { - throw new Error('Required parameter newsId was null or undefined when calling getNewsById.'); - } - - let localVarHeaders = this.defaultHeaders; - - const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([ - 'application/json' - ]); - if (localVarHttpHeaderAcceptSelected !== undefined) { - localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); - } - - const localVarHttpContext: HttpContext = options?.context ?? new HttpContext(); - - const localVarTransferCache: boolean = options?.transferCache ?? true; - - - let responseType_: 'text' | 'json' | 'blob' = 'json'; - if (localVarHttpHeaderAcceptSelected) { - if (localVarHttpHeaderAcceptSelected.startsWith('text')) { - responseType_ = 'text'; - } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { - responseType_ = 'json'; - } else { - responseType_ = 'blob'; - } - } - - let localVarPath = `/api/news/${this.configuration.encodeParam({name: "newsId", value: newsId, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: undefined})}`; - const { basePath, withCredentials } = this.configuration; - return this.httpClient.request('get', `${basePath}${localVarPath}`, - { - context: localVarHttpContext, - responseType: responseType_, - ...(withCredentials ? { withCredentials } : {}), - headers: localVarHeaders, - observe: observe, - ...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}), - reportProgress: reportProgress - } + if (filterTopicIds) { + filterTopicIds.forEach((element) => { + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + element, + 'filterTopicIds', ); + }); + } + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + fuzzy, + 'fuzzy', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + page, + 'page', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + pageSize, + 'pageSize', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + relevance, + 'relevance', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + yearFrom, + 'yearFrom', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + yearTo, + 'yearTo', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + sortOrder, + 'sortOrder', + ); + + let localVarHeaders = this.defaultHeaders; + + const localVarHttpHeaderAcceptSelected: string | undefined = + options?.httpHeaderAccept ?? + this.configuration.selectHeaderAccept(['application/json']); + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set( + 'Accept', + localVarHttpHeaderAcceptSelected, + ); } - /** - * Returns a single news article including its full content. - * @endpoint get /api/news/{news_id} - * @param newsId The unique id of the news article (Elasticsearch _id). - * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. - * @param reportProgress flag to report request and response progress. - */ - public getNewsById_2(newsId: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; - public getNewsById_2(newsId: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public getNewsById_2(newsId: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public getNewsById_2(newsId: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { - if (newsId === null || newsId === undefined) { - throw new Error('Required parameter newsId was null or undefined when calling getNewsById_2.'); - } + const localVarHttpContext: HttpContext = + options?.context ?? new HttpContext(); - let localVarHeaders = this.defaultHeaders; + const localVarTransferCache: boolean = options?.transferCache ?? true; - const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([ - 'application/json' - ]); - if (localVarHttpHeaderAcceptSelected !== undefined) { - localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); - } + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if ( + this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected) + ) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } - const localVarHttpContext: HttpContext = options?.context ?? new HttpContext(); + let localVarPath = `/api/news/keyword/search`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request( + 'get', + `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + params: localVarQueryParameters, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined + ? { transferCache: localVarTransferCache } + : {}), + reportProgress: reportProgress, + }, + ); + } - const localVarTransferCache: boolean = options?.transferCache ?? true; - - - let responseType_: 'text' | 'json' | 'blob' = 'json'; - if (localVarHttpHeaderAcceptSelected) { - if (localVarHttpHeaderAcceptSelected.startsWith('text')) { - responseType_ = 'text'; - } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { - responseType_ = 'json'; - } else { - responseType_ = 'blob'; - } - } - - let localVarPath = `/api/news/${this.configuration.encodeParam({name: "newsId", value: newsId, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: undefined})}`; - const { basePath, withCredentials } = this.configuration; - return this.httpClient.request('get', `${basePath}${localVarPath}`, - { - context: localVarHttpContext, - responseType: responseType_, - ...(withCredentials ? { withCredentials } : {}), - headers: localVarHeaders, - observe: observe, - ...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}), - reportProgress: reportProgress - } + /** + * Searches news articles by the keywords or matched topics of a keywords search. + * @endpoint get /api/news/keyword/search + * @param keywords Raw keywords to match against title/content. + * @param topicIds OpenAlex topic ids the keywords resolved to. + * @param filterTopicIds Additional topic ids to narrow the results by. + * @param fuzzy Search by resolved topics if True, otherwise by raw keywords. + * @param page Page number (1-based). + * @param pageSize Articles per page. + * @param relevance Comma-separated relevance filter: \'relevant\', \'not_relevant\'. + * @param yearFrom Earliest publication year (inclusive). + * @param yearTo Latest publication year (inclusive). + * @param sortOrder Overrides relevance ranking with a date sort: \'desc\' (newest first) or \'asc\' (oldest first). + * @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 getNewsByKeywords_3( + keywords?: Array, + topicIds?: Array, + filterTopicIds?: Array, + fuzzy?: boolean, + page?: number, + pageSize?: number, + relevance?: string, + yearFrom?: number, + yearTo?: number, + sortOrder?: string, + observe?: 'body', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable; + public getNewsByKeywords_3( + keywords?: Array, + topicIds?: Array, + filterTopicIds?: Array, + fuzzy?: boolean, + page?: number, + pageSize?: number, + relevance?: string, + yearFrom?: number, + yearTo?: number, + sortOrder?: string, + observe?: 'response', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public getNewsByKeywords_3( + keywords?: Array, + topicIds?: Array, + filterTopicIds?: Array, + fuzzy?: boolean, + page?: number, + pageSize?: number, + relevance?: string, + yearFrom?: number, + yearTo?: number, + sortOrder?: string, + observe?: 'events', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public getNewsByKeywords_3( + keywords?: Array, + topicIds?: Array, + filterTopicIds?: Array, + fuzzy?: boolean, + page?: number, + pageSize?: number, + relevance?: string, + yearFrom?: number, + yearTo?: number, + sortOrder?: string, + observe: any = 'body', + reportProgress: boolean = false, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable { + let localVarQueryParameters = new HttpParams({ encoder: this.encoder }); + if (keywords) { + keywords.forEach((element) => { + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + element, + 'keywords', ); + }); } - - /** - * Returns a page of news articles, newest first. - * @endpoint get /api/news - * @param page Page number (1-based). - * @param pageSize Articles per page. - * @param sortOrder Sort order: \'desc\' (newest first) or \'asc\' (oldest first). - * @param relevance Comma-separated relevance filter: \'relevant\', \'not_relevant\'. - * @param yearFrom Earliest publication year (inclusive). - * @param yearTo Latest publication year (inclusive). - * @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 listNews(page?: number, pageSize?: number, sortOrder?: string, relevance?: string, yearFrom?: number, yearTo?: number, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; - public listNews(page?: number, pageSize?: number, sortOrder?: string, relevance?: string, yearFrom?: number, yearTo?: number, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public listNews(page?: number, pageSize?: number, sortOrder?: string, relevance?: string, yearFrom?: number, yearTo?: number, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public listNews(page?: number, pageSize?: number, sortOrder?: string, relevance?: string, yearFrom?: number, yearTo?: number, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { - - let localVarQueryParameters = new HttpParams({encoder: this.encoder}); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - page, 'page'); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - pageSize, 'pageSize'); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - sortOrder, 'sortOrder'); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - relevance, 'relevance'); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - yearFrom, 'yearFrom'); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - yearTo, 'yearTo'); - - let localVarHeaders = this.defaultHeaders; - - const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([ - 'application/json' - ]); - if (localVarHttpHeaderAcceptSelected !== undefined) { - localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); - } - - const localVarHttpContext: HttpContext = options?.context ?? new HttpContext(); - - const localVarTransferCache: boolean = options?.transferCache ?? true; - - - let responseType_: 'text' | 'json' | 'blob' = 'json'; - if (localVarHttpHeaderAcceptSelected) { - if (localVarHttpHeaderAcceptSelected.startsWith('text')) { - responseType_ = 'text'; - } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { - responseType_ = 'json'; - } else { - responseType_ = 'blob'; - } - } - - let localVarPath = `/api/news`; - const { basePath, withCredentials } = this.configuration; - return this.httpClient.request('get', `${basePath}${localVarPath}`, - { - context: localVarHttpContext, - params: localVarQueryParameters, - responseType: responseType_, - ...(withCredentials ? { withCredentials } : {}), - headers: localVarHeaders, - observe: observe, - ...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}), - reportProgress: reportProgress - } + if (topicIds) { + topicIds.forEach((element) => { + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + element, + 'topicIds', ); + }); } - - /** - * Returns a page of news articles, newest first. - * @endpoint get /api/news - * @param page Page number (1-based). - * @param pageSize Articles per page. - * @param sortOrder Sort order: \'desc\' (newest first) or \'asc\' (oldest first). - * @param relevance Comma-separated relevance filter: \'relevant\', \'not_relevant\'. - * @param yearFrom Earliest publication year (inclusive). - * @param yearTo Latest publication year (inclusive). - * @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 listNews_3(page?: number, pageSize?: number, sortOrder?: string, relevance?: string, yearFrom?: number, yearTo?: number, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; - public listNews_3(page?: number, pageSize?: number, sortOrder?: string, relevance?: string, yearFrom?: number, yearTo?: number, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public listNews_3(page?: number, pageSize?: number, sortOrder?: string, relevance?: string, yearFrom?: number, yearTo?: number, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public listNews_3(page?: number, pageSize?: number, sortOrder?: string, relevance?: string, yearFrom?: number, yearTo?: number, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { - - let localVarQueryParameters = new HttpParams({encoder: this.encoder}); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - page, 'page'); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - pageSize, 'pageSize'); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - sortOrder, 'sortOrder'); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - relevance, 'relevance'); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - yearFrom, 'yearFrom'); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - yearTo, 'yearTo'); - - let localVarHeaders = this.defaultHeaders; - - const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([ - 'application/json' - ]); - if (localVarHttpHeaderAcceptSelected !== undefined) { - localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); - } - - const localVarHttpContext: HttpContext = options?.context ?? new HttpContext(); - - const localVarTransferCache: boolean = options?.transferCache ?? true; - - - let responseType_: 'text' | 'json' | 'blob' = 'json'; - if (localVarHttpHeaderAcceptSelected) { - if (localVarHttpHeaderAcceptSelected.startsWith('text')) { - responseType_ = 'text'; - } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { - responseType_ = 'json'; - } else { - responseType_ = 'blob'; - } - } - - let localVarPath = `/api/news`; - const { basePath, withCredentials } = this.configuration; - return this.httpClient.request('get', `${basePath}${localVarPath}`, - { - context: localVarHttpContext, - params: localVarQueryParameters, - responseType: responseType_, - ...(withCredentials ? { withCredentials } : {}), - headers: localVarHeaders, - observe: observe, - ...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}), - reportProgress: reportProgress - } + if (filterTopicIds) { + filterTopicIds.forEach((element) => { + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + element, + 'filterTopicIds', ); + }); + } + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + fuzzy, + 'fuzzy', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + page, + 'page', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + pageSize, + 'pageSize', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + relevance, + 'relevance', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + yearFrom, + 'yearFrom', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + yearTo, + 'yearTo', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + sortOrder, + 'sortOrder', + ); + + let localVarHeaders = this.defaultHeaders; + + const localVarHttpHeaderAcceptSelected: string | undefined = + options?.httpHeaderAccept ?? + this.configuration.selectHeaderAccept(['application/json']); + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set( + 'Accept', + localVarHttpHeaderAcceptSelected, + ); } - /** - * Searches news articles by full text (full_content). - * @endpoint get /api/news/search - * @param query Search term, matched against the full text (full_content). - * @param page Page number (1-based). - * @param pageSize Articles per page. - * @param relevance Comma-separated relevance filter: \'relevant\', \'not_relevant\'. - * @param yearFrom Earliest publication year (inclusive). - * @param yearTo Latest publication year (inclusive). - * @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 searchNews(query: string, page?: number, pageSize?: number, relevance?: string, yearFrom?: number, yearTo?: number, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; - public searchNews(query: string, page?: number, pageSize?: number, relevance?: string, yearFrom?: number, yearTo?: number, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public searchNews(query: string, page?: number, pageSize?: number, relevance?: string, yearFrom?: number, yearTo?: number, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public searchNews(query: string, page?: number, pageSize?: number, relevance?: string, yearFrom?: number, yearTo?: number, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { - if (query === null || query === undefined) { - throw new Error('Required parameter query was null or undefined when calling searchNews.'); - } + const localVarHttpContext: HttpContext = + options?.context ?? new HttpContext(); - let localVarQueryParameters = new HttpParams({encoder: this.encoder}); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - query, 'query'); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - page, 'page'); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - pageSize, 'pageSize'); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - relevance, 'relevance'); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - yearFrom, 'yearFrom'); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - yearTo, 'yearTo'); + const localVarTransferCache: boolean = options?.transferCache ?? true; - let localVarHeaders = this.defaultHeaders; - - const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([ - 'application/json' - ]); - if (localVarHttpHeaderAcceptSelected !== undefined) { - localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); - } - - const localVarHttpContext: HttpContext = options?.context ?? new HttpContext(); - - const localVarTransferCache: boolean = options?.transferCache ?? true; - - - let responseType_: 'text' | 'json' | 'blob' = 'json'; - if (localVarHttpHeaderAcceptSelected) { - if (localVarHttpHeaderAcceptSelected.startsWith('text')) { - responseType_ = 'text'; - } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { - responseType_ = 'json'; - } else { - responseType_ = 'blob'; - } - } - - let localVarPath = `/api/news/search`; - const { basePath, withCredentials } = this.configuration; - return this.httpClient.request('get', `${basePath}${localVarPath}`, - { - context: localVarHttpContext, - params: localVarQueryParameters, - responseType: responseType_, - ...(withCredentials ? { withCredentials } : {}), - headers: localVarHeaders, - observe: observe, - ...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}), - reportProgress: reportProgress - } - ); + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if ( + this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected) + ) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } } - /** - * Searches news articles by full text (full_content). - * @endpoint get /api/news/search - * @param query Search term, matched against the full text (full_content). - * @param page Page number (1-based). - * @param pageSize Articles per page. - * @param relevance Comma-separated relevance filter: \'relevant\', \'not_relevant\'. - * @param yearFrom Earliest publication year (inclusive). - * @param yearTo Latest publication year (inclusive). - * @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 searchNews_4(query: string, page?: number, pageSize?: number, relevance?: string, yearFrom?: number, yearTo?: number, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; - public searchNews_4(query: string, page?: number, pageSize?: number, relevance?: string, yearFrom?: number, yearTo?: number, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public searchNews_4(query: string, page?: number, pageSize?: number, relevance?: string, yearFrom?: number, yearTo?: number, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public searchNews_4(query: string, page?: number, pageSize?: number, relevance?: string, yearFrom?: number, yearTo?: number, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { - if (query === null || query === undefined) { - throw new Error('Required parameter query was null or undefined when calling searchNews_4.'); - } + let localVarPath = `/api/news/keyword/search`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request( + 'get', + `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + params: localVarQueryParameters, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined + ? { transferCache: localVarTransferCache } + : {}), + reportProgress: reportProgress, + }, + ); + } - let localVarQueryParameters = new HttpParams({encoder: this.encoder}); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - query, 'query'); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - page, 'page'); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - pageSize, 'pageSize'); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - relevance, 'relevance'); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - yearFrom, 'yearFrom'); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - yearTo, 'yearTo'); + /** + * Returns a page of news articles, newest first. + * @endpoint get /api/news + * @param page Page number (1-based). + * @param pageSize Articles per page. + * @param sortOrder Sort order: \'desc\' (newest first) or \'asc\' (oldest first). + * @param relevance Comma-separated relevance filter: \'relevant\', \'not_relevant\'. + * @param yearFrom Earliest publication year (inclusive). + * @param yearTo Latest publication year (inclusive). + * @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 listNews( + page?: number, + pageSize?: number, + sortOrder?: string, + relevance?: string, + yearFrom?: number, + yearTo?: number, + observe?: 'body', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable; + public listNews( + page?: number, + pageSize?: number, + sortOrder?: string, + relevance?: string, + yearFrom?: number, + yearTo?: number, + observe?: 'response', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public listNews( + page?: number, + pageSize?: number, + sortOrder?: string, + relevance?: string, + yearFrom?: number, + yearTo?: number, + observe?: 'events', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public listNews( + page?: number, + pageSize?: number, + sortOrder?: string, + relevance?: string, + yearFrom?: number, + yearTo?: number, + observe: any = 'body', + reportProgress: boolean = false, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable { + let localVarQueryParameters = new HttpParams({ encoder: this.encoder }); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + page, + 'page', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + pageSize, + 'pageSize', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + sortOrder, + 'sortOrder', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + relevance, + 'relevance', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + yearFrom, + 'yearFrom', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + yearTo, + 'yearTo', + ); - let localVarHeaders = this.defaultHeaders; + let localVarHeaders = this.defaultHeaders; - const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([ - 'application/json' - ]); - if (localVarHttpHeaderAcceptSelected !== undefined) { - localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); - } - - const localVarHttpContext: HttpContext = options?.context ?? new HttpContext(); - - const localVarTransferCache: boolean = options?.transferCache ?? true; - - - let responseType_: 'text' | 'json' | 'blob' = 'json'; - if (localVarHttpHeaderAcceptSelected) { - if (localVarHttpHeaderAcceptSelected.startsWith('text')) { - responseType_ = 'text'; - } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { - responseType_ = 'json'; - } else { - responseType_ = 'blob'; - } - } - - let localVarPath = `/api/news/search`; - const { basePath, withCredentials } = this.configuration; - return this.httpClient.request('get', `${basePath}${localVarPath}`, - { - context: localVarHttpContext, - params: localVarQueryParameters, - responseType: responseType_, - ...(withCredentials ? { withCredentials } : {}), - headers: localVarHeaders, - observe: observe, - ...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}), - reportProgress: reportProgress - } - ); + const localVarHttpHeaderAcceptSelected: string | undefined = + options?.httpHeaderAccept ?? + this.configuration.selectHeaderAccept(['application/json']); + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set( + 'Accept', + localVarHttpHeaderAcceptSelected, + ); } + const localVarHttpContext: HttpContext = + options?.context ?? new HttpContext(); + + const localVarTransferCache: boolean = options?.transferCache ?? true; + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if ( + this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected) + ) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/api/news`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request( + 'get', + `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + params: localVarQueryParameters, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined + ? { transferCache: localVarTransferCache } + : {}), + reportProgress: reportProgress, + }, + ); + } + + /** + * Returns a page of news articles, newest first. + * @endpoint get /api/news + * @param page Page number (1-based). + * @param pageSize Articles per page. + * @param sortOrder Sort order: \'desc\' (newest first) or \'asc\' (oldest first). + * @param relevance Comma-separated relevance filter: \'relevant\', \'not_relevant\'. + * @param yearFrom Earliest publication year (inclusive). + * @param yearTo Latest publication year (inclusive). + * @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 listNews_4( + page?: number, + pageSize?: number, + sortOrder?: string, + relevance?: string, + yearFrom?: number, + yearTo?: number, + observe?: 'body', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable; + public listNews_4( + page?: number, + pageSize?: number, + sortOrder?: string, + relevance?: string, + yearFrom?: number, + yearTo?: number, + observe?: 'response', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public listNews_4( + page?: number, + pageSize?: number, + sortOrder?: string, + relevance?: string, + yearFrom?: number, + yearTo?: number, + observe?: 'events', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public listNews_4( + page?: number, + pageSize?: number, + sortOrder?: string, + relevance?: string, + yearFrom?: number, + yearTo?: number, + observe: any = 'body', + reportProgress: boolean = false, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable { + let localVarQueryParameters = new HttpParams({ encoder: this.encoder }); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + page, + 'page', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + pageSize, + 'pageSize', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + sortOrder, + 'sortOrder', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + relevance, + 'relevance', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + yearFrom, + 'yearFrom', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + yearTo, + 'yearTo', + ); + + let localVarHeaders = this.defaultHeaders; + + const localVarHttpHeaderAcceptSelected: string | undefined = + options?.httpHeaderAccept ?? + this.configuration.selectHeaderAccept(['application/json']); + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set( + 'Accept', + localVarHttpHeaderAcceptSelected, + ); + } + + const localVarHttpContext: HttpContext = + options?.context ?? new HttpContext(); + + const localVarTransferCache: boolean = options?.transferCache ?? true; + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if ( + this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected) + ) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/api/news`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request( + 'get', + `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + params: localVarQueryParameters, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined + ? { transferCache: localVarTransferCache } + : {}), + reportProgress: reportProgress, + }, + ); + } + + /** + * Searches news articles by full text (full_content). + * @endpoint get /api/news/search + * @param query Search term, matched against the full text (full_content). + * @param page Page number (1-based). + * @param pageSize Articles per page. + * @param relevance Comma-separated relevance filter: \'relevant\', \'not_relevant\'. + * @param yearFrom Earliest publication year (inclusive). + * @param yearTo Latest publication year (inclusive). + * @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 searchNews( + query: string, + page?: number, + pageSize?: number, + relevance?: string, + yearFrom?: number, + yearTo?: number, + observe?: 'body', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable; + public searchNews( + query: string, + page?: number, + pageSize?: number, + relevance?: string, + yearFrom?: number, + yearTo?: number, + observe?: 'response', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public searchNews( + query: string, + page?: number, + pageSize?: number, + relevance?: string, + yearFrom?: number, + yearTo?: number, + observe?: 'events', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public searchNews( + query: string, + page?: number, + pageSize?: number, + relevance?: string, + yearFrom?: number, + yearTo?: number, + observe: any = 'body', + reportProgress: boolean = false, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable { + if (query === null || query === undefined) { + throw new Error( + 'Required parameter query was null or undefined when calling searchNews.', + ); + } + + let localVarQueryParameters = new HttpParams({ encoder: this.encoder }); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + query, + 'query', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + page, + 'page', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + pageSize, + 'pageSize', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + relevance, + 'relevance', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + yearFrom, + 'yearFrom', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + yearTo, + 'yearTo', + ); + + let localVarHeaders = this.defaultHeaders; + + const localVarHttpHeaderAcceptSelected: string | undefined = + options?.httpHeaderAccept ?? + this.configuration.selectHeaderAccept(['application/json']); + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set( + 'Accept', + localVarHttpHeaderAcceptSelected, + ); + } + + const localVarHttpContext: HttpContext = + options?.context ?? new HttpContext(); + + const localVarTransferCache: boolean = options?.transferCache ?? true; + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if ( + this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected) + ) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/api/news/search`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request( + 'get', + `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + params: localVarQueryParameters, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined + ? { transferCache: localVarTransferCache } + : {}), + reportProgress: reportProgress, + }, + ); + } + + /** + * Searches news articles by full text (full_content). + * @endpoint get /api/news/search + * @param query Search term, matched against the full text (full_content). + * @param page Page number (1-based). + * @param pageSize Articles per page. + * @param relevance Comma-separated relevance filter: \'relevant\', \'not_relevant\'. + * @param yearFrom Earliest publication year (inclusive). + * @param yearTo Latest publication year (inclusive). + * @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 searchNews_5( + query: string, + page?: number, + pageSize?: number, + relevance?: string, + yearFrom?: number, + yearTo?: number, + observe?: 'body', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable; + public searchNews_5( + query: string, + page?: number, + pageSize?: number, + relevance?: string, + yearFrom?: number, + yearTo?: number, + observe?: 'response', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public searchNews_5( + query: string, + page?: number, + pageSize?: number, + relevance?: string, + yearFrom?: number, + yearTo?: number, + observe?: 'events', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public searchNews_5( + query: string, + page?: number, + pageSize?: number, + relevance?: string, + yearFrom?: number, + yearTo?: number, + observe: any = 'body', + reportProgress: boolean = false, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable { + if (query === null || query === undefined) { + throw new Error( + 'Required parameter query was null or undefined when calling searchNews_5.', + ); + } + + let localVarQueryParameters = new HttpParams({ encoder: this.encoder }); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + query, + 'query', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + page, + 'page', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + pageSize, + 'pageSize', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + relevance, + 'relevance', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + yearFrom, + 'yearFrom', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + yearTo, + 'yearTo', + ); + + let localVarHeaders = this.defaultHeaders; + + const localVarHttpHeaderAcceptSelected: string | undefined = + options?.httpHeaderAccept ?? + this.configuration.selectHeaderAccept(['application/json']); + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set( + 'Accept', + localVarHttpHeaderAcceptSelected, + ); + } + + const localVarHttpContext: HttpContext = + options?.context ?? new HttpContext(); + + const localVarTransferCache: boolean = options?.transferCache ?? true; + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if ( + this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected) + ) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/api/news/search`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request( + 'get', + `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + params: localVarQueryParameters, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined + ? { transferCache: localVarTransferCache } + : {}), + reportProgress: reportProgress, + }, + ); + } } 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; + public createOrganisation( + createOrganizationRequest: CreateOrganizationRequest, + secureFgpAcc?: string, + observe?: 'response', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable< + HttpResponse + >; + public createOrganisation( + createOrganizationRequest: CreateOrganizationRequest, + secureFgpAcc?: string, + observe?: 'events', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public createOrganisation( + createOrganizationRequest: CreateOrganizationRequest, + secureFgpAcc?: string, + observe: any = 'body', + reportProgress: boolean = false, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable { + if ( + createOrganizationRequest === null || + createOrganizationRequest === undefined + ) { + throw new Error( + 'Required parameter createOrganizationRequest was null or undefined when calling createOrganisation.', + ); } - /** - * 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; - public createOrganisation(createOrganizationRequest: CreateOrganizationRequest, secureFgpAcc?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public createOrganisation(createOrganizationRequest: CreateOrganizationRequest, secureFgpAcc?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public createOrganisation(createOrganizationRequest: CreateOrganizationRequest, secureFgpAcc?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { - if (createOrganizationRequest === null || createOrganizationRequest === undefined) { - throw new Error('Required parameter createOrganizationRequest was null or undefined when calling createOrganisation.'); - } + let localVarHeaders = this.defaultHeaders; - let localVarHeaders = this.defaultHeaders; + // authentication (HTTPBearer) required + localVarHeaders = this.configuration.addCredentialToHeaders( + 'HTTPBearer', + 'Authorization', + localVarHeaders, + 'Bearer ', + ); - // authentication (HTTPBearer) required - localVarHeaders = this.configuration.addCredentialToHeaders('HTTPBearer', 'Authorization', localVarHeaders, 'Bearer '); + const localVarHttpHeaderAcceptSelected: string | undefined = + options?.httpHeaderAccept ?? + this.configuration.selectHeaderAccept(['application/json']); + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set( + 'Accept', + localVarHttpHeaderAcceptSelected, + ); + } - const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([ - 'application/json' - ]); - if (localVarHttpHeaderAcceptSelected !== undefined) { - localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); - } + const localVarHttpContext: HttpContext = + options?.context ?? new HttpContext(); - const localVarHttpContext: HttpContext = options?.context ?? new HttpContext(); + const localVarTransferCache: boolean = options?.transferCache ?? true; - const localVarTransferCache: boolean = options?.transferCache ?? true; + // to determine the Content-Type header + const consumes: string[] = ['application/json']; + const httpContentTypeSelected: string | undefined = + this.configuration.selectHeaderContentType(consumes); + if (httpContentTypeSelected !== undefined) { + localVarHeaders = localVarHeaders.set( + 'Content-Type', + httpContentTypeSelected, + ); + } + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if ( + this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected) + ) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } - // to determine the Content-Type header - const consumes: string[] = [ - 'application/json' - ]; - const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes); - if (httpContentTypeSelected !== undefined) { - localVarHeaders = localVarHeaders.set('Content-Type', httpContentTypeSelected); - } + let localVarPath = `/api/organizations`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request( + 'post', + `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + body: createOrganizationRequest, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined + ? { transferCache: localVarTransferCache } + : {}), + reportProgress: reportProgress, + }, + ); + } - let responseType_: 'text' | 'json' | 'blob' = 'json'; - if (localVarHttpHeaderAcceptSelected) { - if (localVarHttpHeaderAcceptSelected.startsWith('text')) { - responseType_ = 'text'; - } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { - responseType_ = 'json'; - } else { - responseType_ = 'blob'; - } - } + /** + * Delete Organization + * @endpoint delete /api/organizations/{organization_id} + * @param organizationId + * @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 deleteOrganisation( + organizationId: string, + secureFgpAcc?: string, + observe?: 'body', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable; + public deleteOrganisation( + organizationId: string, + secureFgpAcc?: string, + observe?: 'response', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public deleteOrganisation( + organizationId: string, + secureFgpAcc?: string, + observe?: 'events', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public deleteOrganisation( + organizationId: string, + secureFgpAcc?: string, + observe: any = 'body', + reportProgress: boolean = false, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable { + if (organizationId === null || organizationId === undefined) { + throw new Error( + 'Required parameter organizationId was null or undefined when calling deleteOrganisation.', + ); + } - let localVarPath = `/api/organizations`; - const { basePath, withCredentials } = this.configuration; - return this.httpClient.request('post', `${basePath}${localVarPath}`, - { - context: localVarHttpContext, - body: createOrganizationRequest, - responseType: responseType_, - ...(withCredentials ? { withCredentials } : {}), - headers: localVarHeaders, - observe: observe, - ...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}), - reportProgress: reportProgress - } + let localVarHeaders = this.defaultHeaders; + + // authentication (HTTPBearer) required + localVarHeaders = this.configuration.addCredentialToHeaders( + 'HTTPBearer', + 'Authorization', + localVarHeaders, + 'Bearer ', + ); + + const localVarHttpHeaderAcceptSelected: string | undefined = + options?.httpHeaderAccept ?? + this.configuration.selectHeaderAccept(['application/json']); + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set( + 'Accept', + localVarHttpHeaderAcceptSelected, + ); + } + + const localVarHttpContext: HttpContext = + options?.context ?? new HttpContext(); + + const localVarTransferCache: boolean = options?.transferCache ?? true; + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if ( + this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected) + ) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/api/organizations/${this.configuration.encodeParam({ name: 'organizationId', value: organizationId, in: 'path', style: 'simple', explode: false, dataType: 'string', dataFormat: 'uuid' })}`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request( + 'delete', + `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined + ? { transferCache: localVarTransferCache } + : {}), + reportProgress: reportProgress, + }, + ); + } + + /** + * Get Organizations + * @endpoint get /api/organizations + * @param page + * @param pageSize + * @param offset + * @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 getOrganisations( + page?: number, + pageSize?: number, + offset?: number, + secureFgpAcc?: string, + observe?: 'body', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable; + public getOrganisations( + page?: number, + pageSize?: number, + offset?: number, + secureFgpAcc?: string, + observe?: 'response', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public getOrganisations( + page?: number, + pageSize?: number, + offset?: number, + secureFgpAcc?: string, + observe?: 'events', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public getOrganisations( + page?: number, + pageSize?: number, + offset?: number, + secureFgpAcc?: string, + observe: any = 'body', + reportProgress: boolean = false, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable { + let localVarQueryParameters = new HttpParams({ encoder: this.encoder }); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + page, + 'page', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + pageSize, + 'page_size', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + offset, + 'offset', + ); + + let localVarHeaders = this.defaultHeaders; + + // authentication (HTTPBearer) required + localVarHeaders = this.configuration.addCredentialToHeaders( + 'HTTPBearer', + 'Authorization', + localVarHeaders, + 'Bearer ', + ); + + const localVarHttpHeaderAcceptSelected: string | undefined = + options?.httpHeaderAccept ?? + this.configuration.selectHeaderAccept(['application/json']); + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set( + 'Accept', + localVarHttpHeaderAcceptSelected, + ); + } + + const localVarHttpContext: HttpContext = + options?.context ?? new HttpContext(); + + const localVarTransferCache: boolean = options?.transferCache ?? true; + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if ( + this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected) + ) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/api/organizations`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request( + 'get', + `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + params: localVarQueryParameters, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined + ? { transferCache: localVarTransferCache } + : {}), + reportProgress: reportProgress, + }, + ); + } + + /** + * Get Organization Institution Associations + * @endpoint get /api/organizations/institutions/associations + * @param institutionIds + * @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 getOrganizationInstitutionAssociations( + institutionIds: Array, + secureFgpAcc?: string, + observe?: 'body', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public getOrganizationInstitutionAssociations( + institutionIds: Array, + secureFgpAcc?: string, + observe?: 'response', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>>; + public getOrganizationInstitutionAssociations( + institutionIds: Array, + secureFgpAcc?: string, + observe?: 'events', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>>; + public getOrganizationInstitutionAssociations( + institutionIds: Array, + secureFgpAcc?: string, + observe: any = 'body', + reportProgress: boolean = false, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable { + if (institutionIds === null || institutionIds === undefined) { + throw new Error( + 'Required parameter institutionIds was null or undefined when calling getOrganizationInstitutionAssociations.', + ); + } + + let localVarQueryParameters = new HttpParams({ encoder: this.encoder }); + if (institutionIds) { + institutionIds.forEach((element) => { + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + element, + 'institution_ids', ); + }); } - /** - * Delete Organization - * @endpoint delete /api/organizations/{organization_id} - * @param organizationId - * @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 deleteOrganisation(organizationId: string, secureFgpAcc?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; - public deleteOrganisation(organizationId: string, secureFgpAcc?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public deleteOrganisation(organizationId: string, secureFgpAcc?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public deleteOrganisation(organizationId: string, secureFgpAcc?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { - if (organizationId === null || organizationId === undefined) { - throw new Error('Required parameter organizationId was null or undefined when calling deleteOrganisation.'); - } + let localVarHeaders = this.defaultHeaders; - let localVarHeaders = this.defaultHeaders; + // authentication (HTTPBearer) required + localVarHeaders = this.configuration.addCredentialToHeaders( + 'HTTPBearer', + 'Authorization', + localVarHeaders, + 'Bearer ', + ); - // authentication (HTTPBearer) required - localVarHeaders = this.configuration.addCredentialToHeaders('HTTPBearer', 'Authorization', localVarHeaders, 'Bearer '); - - const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([ - 'application/json' - ]); - if (localVarHttpHeaderAcceptSelected !== undefined) { - localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); - } - - const localVarHttpContext: HttpContext = options?.context ?? new HttpContext(); - - const localVarTransferCache: boolean = options?.transferCache ?? true; - - - let responseType_: 'text' | 'json' | 'blob' = 'json'; - if (localVarHttpHeaderAcceptSelected) { - if (localVarHttpHeaderAcceptSelected.startsWith('text')) { - responseType_ = 'text'; - } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { - responseType_ = 'json'; - } else { - responseType_ = 'blob'; - } - } - - let localVarPath = `/api/organizations/${this.configuration.encodeParam({name: "organizationId", value: organizationId, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: "uuid"})}`; - const { basePath, withCredentials } = this.configuration; - return this.httpClient.request('delete', `${basePath}${localVarPath}`, - { - context: localVarHttpContext, - responseType: responseType_, - ...(withCredentials ? { withCredentials } : {}), - headers: localVarHeaders, - observe: observe, - ...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}), - reportProgress: reportProgress - } - ); + const localVarHttpHeaderAcceptSelected: string | undefined = + options?.httpHeaderAccept ?? + this.configuration.selectHeaderAccept(['application/json']); + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set( + 'Accept', + localVarHttpHeaderAcceptSelected, + ); } - /** - * Get Organizations - * @endpoint get /api/organizations - * @param page - * @param pageSize - * @param offset - * @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 getOrganisations(page?: number, pageSize?: number, offset?: number, secureFgpAcc?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; - public getOrganisations(page?: number, pageSize?: number, offset?: number, secureFgpAcc?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public getOrganisations(page?: number, pageSize?: number, offset?: number, secureFgpAcc?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public getOrganisations(page?: number, pageSize?: number, offset?: number, secureFgpAcc?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + const localVarHttpContext: HttpContext = + options?.context ?? new HttpContext(); - let localVarQueryParameters = new HttpParams({encoder: this.encoder}); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - page, 'page'); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - pageSize, 'page_size'); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - offset, 'offset'); + const localVarTransferCache: boolean = options?.transferCache ?? true; - let localVarHeaders = this.defaultHeaders; - - // authentication (HTTPBearer) required - localVarHeaders = this.configuration.addCredentialToHeaders('HTTPBearer', 'Authorization', localVarHeaders, 'Bearer '); - - const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([ - 'application/json' - ]); - if (localVarHttpHeaderAcceptSelected !== undefined) { - localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); - } - - const localVarHttpContext: HttpContext = options?.context ?? new HttpContext(); - - const localVarTransferCache: boolean = options?.transferCache ?? true; - - - let responseType_: 'text' | 'json' | 'blob' = 'json'; - if (localVarHttpHeaderAcceptSelected) { - if (localVarHttpHeaderAcceptSelected.startsWith('text')) { - responseType_ = 'text'; - } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { - responseType_ = 'json'; - } else { - responseType_ = 'blob'; - } - } - - let localVarPath = `/api/organizations`; - const { basePath, withCredentials } = this.configuration; - return this.httpClient.request('get', `${basePath}${localVarPath}`, - { - context: localVarHttpContext, - params: localVarQueryParameters, - responseType: responseType_, - ...(withCredentials ? { withCredentials } : {}), - headers: localVarHeaders, - observe: observe, - ...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}), - reportProgress: reportProgress - } - ); + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if ( + this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected) + ) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } } - /** - * Update Organization - * @endpoint put /api/organizations/{organization_id} - * @param organizationId - * @param updateOrganizationRequest - * @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 updateOrganisation(organizationId: string, updateOrganizationRequest: UpdateOrganizationRequest, secureFgpAcc?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; - public updateOrganisation(organizationId: string, updateOrganizationRequest: UpdateOrganizationRequest, secureFgpAcc?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public updateOrganisation(organizationId: string, updateOrganizationRequest: UpdateOrganizationRequest, secureFgpAcc?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public updateOrganisation(organizationId: string, updateOrganizationRequest: UpdateOrganizationRequest, secureFgpAcc?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { - if (organizationId === null || organizationId === undefined) { - throw new Error('Required parameter organizationId was null or undefined when calling updateOrganisation.'); - } - if (updateOrganizationRequest === null || updateOrganizationRequest === undefined) { - throw new Error('Required parameter updateOrganizationRequest was null or undefined when calling updateOrganisation.'); - } + let localVarPath = `/api/organizations/institutions/associations`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request>( + 'get', + `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + params: localVarQueryParameters, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined + ? { transferCache: localVarTransferCache } + : {}), + reportProgress: reportProgress, + }, + ); + } - let localVarHeaders = this.defaultHeaders; - - // authentication (HTTPBearer) required - localVarHeaders = this.configuration.addCredentialToHeaders('HTTPBearer', 'Authorization', localVarHeaders, 'Bearer '); - - const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([ - 'application/json' - ]); - if (localVarHttpHeaderAcceptSelected !== undefined) { - localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); - } - - const localVarHttpContext: HttpContext = options?.context ?? new HttpContext(); - - const localVarTransferCache: boolean = options?.transferCache ?? true; - - - // to determine the Content-Type header - const consumes: string[] = [ - 'application/json' - ]; - const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes); - if (httpContentTypeSelected !== undefined) { - localVarHeaders = localVarHeaders.set('Content-Type', httpContentTypeSelected); - } - - let responseType_: 'text' | 'json' | 'blob' = 'json'; - if (localVarHttpHeaderAcceptSelected) { - if (localVarHttpHeaderAcceptSelected.startsWith('text')) { - responseType_ = 'text'; - } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { - responseType_ = 'json'; - } else { - responseType_ = 'blob'; - } - } - - let localVarPath = `/api/organizations/${this.configuration.encodeParam({name: "organizationId", value: organizationId, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: "uuid"})}`; - const { basePath, withCredentials } = this.configuration; - return this.httpClient.request('put', `${basePath}${localVarPath}`, - { - context: localVarHttpContext, - body: updateOrganizationRequest, - responseType: responseType_, - ...(withCredentials ? { withCredentials } : {}), - headers: localVarHeaders, - observe: observe, - ...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}), - reportProgress: reportProgress - } - ); + /** + * Update Organization + * @endpoint put /api/organizations/{organization_id} + * @param organizationId + * @param updateOrganizationRequest + * @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 updateOrganisation( + organizationId: string, + updateOrganizationRequest: UpdateOrganizationRequest, + secureFgpAcc?: string, + observe?: 'body', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable; + public updateOrganisation( + organizationId: string, + updateOrganizationRequest: UpdateOrganizationRequest, + secureFgpAcc?: string, + observe?: 'response', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable< + HttpResponse + >; + public updateOrganisation( + organizationId: string, + updateOrganizationRequest: UpdateOrganizationRequest, + secureFgpAcc?: string, + observe?: 'events', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public updateOrganisation( + organizationId: string, + updateOrganizationRequest: UpdateOrganizationRequest, + secureFgpAcc?: string, + observe: any = 'body', + reportProgress: boolean = false, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable { + if (organizationId === null || organizationId === undefined) { + throw new Error( + 'Required parameter organizationId was null or undefined when calling updateOrganisation.', + ); + } + if ( + updateOrganizationRequest === null || + updateOrganizationRequest === undefined + ) { + throw new Error( + 'Required parameter updateOrganizationRequest was null or undefined when calling updateOrganisation.', + ); } + let localVarHeaders = this.defaultHeaders; + + // authentication (HTTPBearer) required + localVarHeaders = this.configuration.addCredentialToHeaders( + 'HTTPBearer', + 'Authorization', + localVarHeaders, + 'Bearer ', + ); + + const localVarHttpHeaderAcceptSelected: string | undefined = + options?.httpHeaderAccept ?? + this.configuration.selectHeaderAccept(['application/json']); + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set( + 'Accept', + localVarHttpHeaderAcceptSelected, + ); + } + + const localVarHttpContext: HttpContext = + options?.context ?? new HttpContext(); + + const localVarTransferCache: boolean = options?.transferCache ?? true; + + // to determine the Content-Type header + const consumes: string[] = ['application/json']; + const httpContentTypeSelected: string | undefined = + this.configuration.selectHeaderContentType(consumes); + if (httpContentTypeSelected !== undefined) { + localVarHeaders = localVarHeaders.set( + 'Content-Type', + httpContentTypeSelected, + ); + } + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if ( + this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected) + ) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/api/organizations/${this.configuration.encodeParam({ name: 'organizationId', value: organizationId, in: 'path', style: 'simple', explode: false, dataType: 'string', dataFormat: 'uuid' })}`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request( + 'put', + `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + body: updateOrganizationRequest, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined + ? { transferCache: localVarTransferCache } + : {}), + reportProgress: reportProgress, + }, + ); + } } diff --git a/webapp/src/app/api/api/projects.service.ts b/webapp/src/app/api/api/projects.service.ts index dfa4eed4..ac2d9b1e 100644 --- a/webapp/src/app/api/api/projects.service.ts +++ b/webapp/src/app/api/api/projects.service.ts @@ -73,7 +73,7 @@ export class ProjectsService extends BaseService { /** * Get DFG projects. * Returns a page of DFG projects based on the provided pagination parameters and optional institution filter. - * @endpoint get /api/projects/person/dfg/search + * @endpoint get /api/projects/dfg/search * @param rawOaInstitutionId The openalex institution ID to filter by. * @param authorId The openalex author ID to filter by. * @param authorFilterIds The dfg author IDs to filter by. @@ -95,8 +95,8 @@ export class ProjectsService extends BaseService { public getDfgProjects( rawOaInstitutionId?: string, authorId?: string, - authorFilterIds?: Array, - institutionIds?: Array, + authorFilterIds?: Array, + institutionIds?: Array, title?: string, keywords?: Array, topicIds?: Array, @@ -119,8 +119,8 @@ export class ProjectsService extends BaseService { public getDfgProjects( rawOaInstitutionId?: string, authorId?: string, - authorFilterIds?: Array, - institutionIds?: Array, + authorFilterIds?: Array, + institutionIds?: Array, title?: string, keywords?: Array, topicIds?: Array, @@ -143,8 +143,8 @@ export class ProjectsService extends BaseService { public getDfgProjects( rawOaInstitutionId?: string, authorId?: string, - authorFilterIds?: Array, - institutionIds?: Array, + authorFilterIds?: Array, + institutionIds?: Array, title?: string, keywords?: Array, topicIds?: Array, @@ -167,8 +167,8 @@ export class ProjectsService extends BaseService { public getDfgProjects( rawOaInstitutionId?: string, authorId?: string, - authorFilterIds?: Array, - institutionIds?: Array, + authorFilterIds?: Array, + institutionIds?: Array, title?: string, keywords?: Array, topicIds?: Array, @@ -323,7 +323,7 @@ export class ProjectsService extends BaseService { } } - let localVarPath = `/api/projects/person/dfg/search`; + let localVarPath = `/api/projects/dfg/search`; const { basePath, withCredentials } = this.configuration; return this.httpClient.request( 'get', diff --git a/webapp/src/app/api/api/topicsV2.service.ts b/webapp/src/app/api/api/topicsV2.service.ts index 9424b9b6..4f378585 100644 --- a/webapp/src/app/api/api/topicsV2.service.ts +++ b/webapp/src/app/api/api/topicsV2.service.ts @@ -22,11 +22,17 @@ import { import { CustomHttpParameterCodec } from '../encoder'; import { Observable } from 'rxjs'; +// @ts-ignore +import { Domain } from '../model/domain'; // @ts-ignore import { HTTPValidationError } from '../model/hTTPValidationError'; // @ts-ignore +import { ModelField } from '../model/modelField'; +// @ts-ignore import { SortDirection } from '../model/sortDirection'; // @ts-ignore +import { Subfield } from '../model/subfield'; +// @ts-ignore import { Topic } from '../model/topic'; // @ts-ignore import { TopicPageV2 } from '../model/topicPageV2'; @@ -154,6 +160,312 @@ export class TopicsV2Service extends BaseService { ); } + /** + * Returns a domain for a given domain ID. + * @endpoint get /api/topics/v2/domains/single/{domain_id} + * @param domainId The ID of the domain to retrieve. + * @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 getDomainById( + domainId: string, + observe?: 'body', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable; + public getDomainById( + domainId: string, + observe?: 'response', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public getDomainById( + domainId: string, + observe?: 'events', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public getDomainById( + domainId: string, + observe: any = 'body', + reportProgress: boolean = false, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable { + if (domainId === null || domainId === undefined) { + throw new Error( + 'Required parameter domainId was null or undefined when calling getDomainById.', + ); + } + + let localVarHeaders = this.defaultHeaders; + + const localVarHttpHeaderAcceptSelected: string | undefined = + options?.httpHeaderAccept ?? + this.configuration.selectHeaderAccept(['application/json']); + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set( + 'Accept', + localVarHttpHeaderAcceptSelected, + ); + } + + const localVarHttpContext: HttpContext = + options?.context ?? new HttpContext(); + + const localVarTransferCache: boolean = options?.transferCache ?? true; + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if ( + this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected) + ) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/api/topics/v2/domains/single/${this.configuration.encodeParam({ name: 'domainId', value: domainId, in: 'path', style: 'simple', explode: false, dataType: 'string', dataFormat: undefined })}`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request( + 'get', + `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined + ? { transferCache: localVarTransferCache } + : {}), + reportProgress: reportProgress, + }, + ); + } + + /** + * Returns a field for a given field ID. + * @endpoint get /api/topics/v2/fields/single/{field_id} + * @param fieldId The ID of the field to retrieve. + * @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 getFieldById( + fieldId: string, + observe?: 'body', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable; + public getFieldById( + fieldId: string, + observe?: 'response', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public getFieldById( + fieldId: string, + observe?: 'events', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public getFieldById( + fieldId: string, + observe: any = 'body', + reportProgress: boolean = false, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable { + if (fieldId === null || fieldId === undefined) { + throw new Error( + 'Required parameter fieldId was null or undefined when calling getFieldById.', + ); + } + + let localVarHeaders = this.defaultHeaders; + + const localVarHttpHeaderAcceptSelected: string | undefined = + options?.httpHeaderAccept ?? + this.configuration.selectHeaderAccept(['application/json']); + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set( + 'Accept', + localVarHttpHeaderAcceptSelected, + ); + } + + const localVarHttpContext: HttpContext = + options?.context ?? new HttpContext(); + + const localVarTransferCache: boolean = options?.transferCache ?? true; + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if ( + this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected) + ) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/api/topics/v2/fields/single/${this.configuration.encodeParam({ name: 'fieldId', value: fieldId, in: 'path', style: 'simple', explode: false, dataType: 'string', dataFormat: undefined })}`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request( + 'get', + `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined + ? { transferCache: localVarTransferCache } + : {}), + reportProgress: reportProgress, + }, + ); + } + + /** + * Returns a subfield for a given subfield ID. + * @endpoint get /api/topics/v2/subfields/single/{subfield_id} + * @param subfieldId The ID of the subfield to retrieve. + * @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 getSubfieldById( + subfieldId: string, + observe?: 'body', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable; + public getSubfieldById( + subfieldId: string, + observe?: 'response', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public getSubfieldById( + subfieldId: string, + observe?: 'events', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public getSubfieldById( + subfieldId: string, + observe: any = 'body', + reportProgress: boolean = false, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable { + if (subfieldId === null || subfieldId === undefined) { + throw new Error( + 'Required parameter subfieldId was null or undefined when calling getSubfieldById.', + ); + } + + let localVarHeaders = this.defaultHeaders; + + const localVarHttpHeaderAcceptSelected: string | undefined = + options?.httpHeaderAccept ?? + this.configuration.selectHeaderAccept(['application/json']); + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set( + 'Accept', + localVarHttpHeaderAcceptSelected, + ); + } + + const localVarHttpContext: HttpContext = + options?.context ?? new HttpContext(); + + const localVarTransferCache: boolean = options?.transferCache ?? true; + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if ( + this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected) + ) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/api/topics/v2/subfields/single/${this.configuration.encodeParam({ name: 'subfieldId', value: subfieldId, in: 'path', style: 'simple', explode: false, dataType: 'string', dataFormat: undefined })}`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request( + 'get', + `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined + ? { transferCache: localVarTransferCache } + : {}), + reportProgress: reportProgress, + }, + ); + } + /** * Returns a topic for a given topic ID. * @endpoint get /api/topics/v2/single/{raw_oa_topic_id} diff --git a/webapp/src/app/api/api/worksV2.service.ts b/webapp/src/app/api/api/worksV2.service.ts index f51e5116..fce3739a 100644 --- a/webapp/src/app/api/api/worksV2.service.ts +++ b/webapp/src/app/api/api/worksV2.service.ts @@ -1009,7 +1009,7 @@ export class WorksV2Service extends BaseService { /** * Returns a work based on its ID. - * @endpoint get /api/works/v2/{raw_oa_work_id} + * @endpoint get /api/works/v2/single/{raw_oa_work_id} * @param rawOaWorkId The raw OpenAlex work id. * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. @@ -1090,7 +1090,7 @@ export class WorksV2Service extends BaseService { } } - let localVarPath = `/api/works/v2/${this.configuration.encodeParam({ name: 'rawOaWorkId', value: rawOaWorkId, in: 'path', style: 'simple', explode: false, dataType: 'string', dataFormat: undefined })}`; + let localVarPath = `/api/works/v2/single/${this.configuration.encodeParam({ name: 'rawOaWorkId', value: rawOaWorkId, in: 'path', style: 'simple', explode: false, dataType: 'string', dataFormat: undefined })}`; const { basePath, withCredentials } = this.configuration; return this.httpClient.request('get', `${basePath}${localVarPath}`, { context: localVarHttpContext, diff --git a/webapp/src/app/api/model/createOrganizationRequest.ts b/webapp/src/app/api/model/createOrganizationRequest.ts index fffb5457..d59b0c3f 100644 --- a/webapp/src/app/api/model/createOrganizationRequest.ts +++ b/webapp/src/app/api/model/createOrganizationRequest.ts @@ -1,16 +1,15 @@ /** * Innovation Search Engine API * - * + * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ - -export interface CreateOrganizationRequest { - name: string; - other_inst_id?: string | null; +export interface CreateOrganizationRequest { + name: string; + other_inst_id?: string | null; + selected_openalex_institution_ids?: Array | null; } - diff --git a/webapp/src/app/api/model/dfgProjectDetails.ts b/webapp/src/app/api/model/dfgProjectDetails.ts index 3c70950a..f3846507 100644 --- a/webapp/src/app/api/model/dfgProjectDetails.ts +++ b/webapp/src/app/api/model/dfgProjectDetails.ts @@ -10,7 +10,7 @@ import { DfgProjectPersonRole } from './dfgProjectPersonRole'; import { DfgProjectSubprojectSummary } from './dfgProjectSubprojectSummary'; import { DfgProjectInstitutionRole } from './dfgProjectInstitutionRole'; -import { DfgProjectSubjectArea } from './dfgProjectSubjectArea'; +import { DFGProjectFachgebieteInner } from './dFGProjectFachgebieteInner'; import { Topic } from './topic'; import { DfgProjectPublicationSummary } from './dfgProjectPublicationSummary'; @@ -48,7 +48,7 @@ export interface DfgProjectDetails { /** * Detailed DFG subject-area classification entries (Fachsystematik) */ - subject_classifications?: Array; + subject_classifications?: Array; international_relation_de?: string | null; international_relation_en?: string | null; /** diff --git a/webapp/src/app/api/model/dfgProjectKeyword.ts b/webapp/src/app/api/model/dfgProjectKeyword.ts new file mode 100644 index 00000000..f81b6ad4 --- /dev/null +++ b/webapp/src/app/api/model/dfgProjectKeyword.ts @@ -0,0 +1,14 @@ +/** + * Innovation Search Engine API + * + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +export interface DfgProjectKeyword { + name: string; + project_count: number; +} diff --git a/webapp/src/app/api/model/dfgProjectSubjectArea.ts b/webapp/src/app/api/model/dfgProjectSubjectArea.ts deleted file mode 100644 index 653aedb7..00000000 --- a/webapp/src/app/api/model/dfgProjectSubjectArea.ts +++ /dev/null @@ -1,19 +0,0 @@ -/** - * Innovation Search Engine API - * - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - -/** - * A single subject-area classification entry (DFG \'Fachsystematik\'). - */ -export interface DfgProjectSubjectArea { - fach?: string | null; - fachgebiet?: string | null; - fachkollegium?: string | null; - wissenschaftsbereich?: string | null; -} diff --git a/webapp/src/app/api/model/dfgProjectTopic.ts b/webapp/src/app/api/model/dfgProjectTopic.ts index 94e4ff16..ca22eb28 100644 --- a/webapp/src/app/api/model/dfgProjectTopic.ts +++ b/webapp/src/app/api/model/dfgProjectTopic.ts @@ -7,6 +7,7 @@ * https://openapi-generator.tech * Do not edit the class manually. */ +import { DfgProjectKeyword } from './dfgProjectKeyword'; export interface DfgProjectTopic { id: string; @@ -15,4 +16,5 @@ export interface DfgProjectTopic { field?: string | null; domain?: string | null; project_count: number; + keywords: Array; } diff --git a/webapp/src/app/api/model/domain.ts b/webapp/src/app/api/model/domain.ts new file mode 100644 index 00000000..3a6c6b03 --- /dev/null +++ b/webapp/src/app/api/model/domain.ts @@ -0,0 +1,29 @@ +/** + * Innovation Search Engine API + * + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ +import { DomainFieldsInner } from './domainFieldsInner'; +import { DomainIds } from './domainIds'; + +/** + * Top-level category in the topic hierarchy (4 total) + */ +export interface Domain { + id?: string | null; + display_name?: string | null; + description?: string | null; + display_name_alternatives?: Array | null; + fields?: Array | null; + siblings?: Array | null; + ids?: DomainIds | null; + works_count?: number | null; + cited_by_count?: number | null; + works_api_url?: string | null; + created_date?: string | null; + updated_date?: string | null; +} diff --git a/webapp/src/app/api/model/domainFieldsInner.ts b/webapp/src/app/api/model/domainFieldsInner.ts new file mode 100644 index 00000000..302feae8 --- /dev/null +++ b/webapp/src/app/api/model/domainFieldsInner.ts @@ -0,0 +1,17 @@ +/** + * Innovation Search Engine API + * + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +/** + * DomainFieldsInner + */ +export interface DomainFieldsInner { + id?: string | null; + display_name?: string | null; +} diff --git a/webapp/src/app/api/model/domainIds.ts b/webapp/src/app/api/model/domainIds.ts new file mode 100644 index 00000000..da44d258 --- /dev/null +++ b/webapp/src/app/api/model/domainIds.ts @@ -0,0 +1,18 @@ +/** + * Innovation Search Engine API + * + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +/** + * External identifiers: + */ +export interface DomainIds { + openalex?: string | null; + wikidata?: string | null; + wikipedia?: string | null; +} diff --git a/webapp/src/app/api/model/inseOrganizationManagementModelOrganizationProfile.ts b/webapp/src/app/api/model/inseOrganizationManagementModelOrganizationProfile.ts index 404df0f9..2b6e1e7c 100644 --- a/webapp/src/app/api/model/inseOrganizationManagementModelOrganizationProfile.ts +++ b/webapp/src/app/api/model/inseOrganizationManagementModelOrganizationProfile.ts @@ -1,19 +1,18 @@ /** * Innovation Search Engine API * - * + * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ - -export interface InseOrganizationManagementModelOrganizationProfile { - id: string; - name: string; - other_inst_id?: string | null; - deleted: boolean; - member_count: number; +export interface InseOrganizationManagementModelOrganizationProfile { + id: string; + name: string; + other_inst_id?: string | null; + selected_openalex_institution_ids?: Array; + deleted: boolean; + member_count: number; } - diff --git a/webapp/src/app/api/model/institutionAssociation.ts b/webapp/src/app/api/model/institutionAssociation.ts new file mode 100644 index 00000000..11b0b37e --- /dev/null +++ b/webapp/src/app/api/model/institutionAssociation.ts @@ -0,0 +1,23 @@ +/** + * Innovation Search Engine API + * + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +export interface InstitutionAssociation { + id: string; + display_name: string; + relationship: InstitutionAssociation.RelationshipEnum; +} +export namespace InstitutionAssociation { + export const RelationshipEnum = { + Child: 'child', + Related: 'related', + } as const; + export type RelationshipEnum = + (typeof RelationshipEnum)[keyof typeof RelationshipEnum]; +} diff --git a/webapp/src/app/api/model/institutionAssociationsResponse.ts b/webapp/src/app/api/model/institutionAssociationsResponse.ts new file mode 100644 index 00000000..6bcd3c56 --- /dev/null +++ b/webapp/src/app/api/model/institutionAssociationsResponse.ts @@ -0,0 +1,16 @@ +/** + * Innovation Search Engine API + * + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ +import { InstitutionAssociation } from './institutionAssociation'; + +export interface InstitutionAssociationsResponse { + id: string; + display_name: string; + associated_institutions?: Array; +} diff --git a/webapp/src/app/api/model/modelField.ts b/webapp/src/app/api/model/modelField.ts new file mode 100644 index 00000000..f0aa2203 --- /dev/null +++ b/webapp/src/app/api/model/modelField.ts @@ -0,0 +1,31 @@ +/** + * Innovation Search Engine API + * + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ +import { DomainFieldsInner } from './domainFieldsInner'; +import { DomainIds } from './domainIds'; +import { WorkTopicDomain } from './workTopicDomain'; + +/** + * Second-level category in the topic hierarchy (26 total) + */ +export interface ModelField { + id?: string | null; + display_name?: string | null; + description?: string | null; + display_name_alternatives?: Array | null; + domain?: WorkTopicDomain | null; + subfields?: Array | null; + siblings?: Array | null; + ids?: DomainIds | null; + works_count?: number | null; + cited_by_count?: number | null; + works_api_url?: string | null; + created_date?: string | null; + updated_date?: string | null; +} diff --git a/webapp/src/app/api/model/models.ts b/webapp/src/app/api/model/models.ts index c16ec742..d6da3737 100644 --- a/webapp/src/app/api/model/models.ts +++ b/webapp/src/app/api/model/models.ts @@ -68,16 +68,19 @@ export * from './dfgPersonSummary'; export * from './dfgPersonSummaryPage'; export * from './dfgProjectDetails'; export * from './dfgProjectInstitutionRole'; +export * from './dfgProjectKeyword'; export * from './dfgProjectPage'; export * from './dfgProjectPersonRole'; export * from './dfgProjectPublicationSummary'; export * from './dfgProjectStatusStatistics'; -export * from './dfgProjectSubjectArea'; export * from './dfgProjectSubprojectSummary'; export * from './dfgProjectSummary'; export * from './dfgProjectTopic'; export * from './dfgProjectTopics'; export * from './dockerHealth'; +export * from './domain'; +export * from './domainFieldsInner'; +export * from './domainIds'; export * from './edge'; export * from './euCordisEurosciVocSummary'; export * from './euCordisOrganizationSelectorPage'; @@ -134,6 +137,8 @@ export * from './idTokenMetadata'; export * from './inseAccountManagementModelOrganizationProfile'; export * from './inseOrganizationManagementModelOrganizationProfile'; export * from './institution'; +export * from './institutionAssociation'; +export * from './institutionAssociationsResponse'; export * from './institutionFunderSummary'; export * from './institutionGeo'; export * from './institutionIds'; @@ -172,6 +177,7 @@ export * from './matchedTopic'; export * from './mentionedPerson'; export * from './meta'; export * from './model2YrMeanCitedness'; +export * from './modelField'; export * from './newsArticle'; export * from './newsArticleDetail'; export * from './newsPage'; @@ -206,6 +212,9 @@ export * from './score'; export * from './selectedAuthorsRequest'; export * from './sortDirection'; export * from './startCollaborationGraphResponse'; +export * from './subfield'; +export * from './subfieldDomain'; +export * from './subfieldField'; export * from './subfieldShare'; export * from './timespan'; export * from './tokenType'; diff --git a/webapp/src/app/api/model/newsArticle.ts b/webapp/src/app/api/model/newsArticle.ts index ab48810d..2ed72b5b 100644 --- a/webapp/src/app/api/model/newsArticle.ts +++ b/webapp/src/app/api/model/newsArticle.ts @@ -1,22 +1,22 @@ /** * Innovation Search Engine API * - * + * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ +import { MatchedTopic } from './matchedTopic'; - -export interface NewsArticle { - id: string; - date?: string | null; - maintitle?: string | null; - author?: string | null; - url?: string | null; - relevant?: boolean | null; - snippet?: string | null; - related?: boolean | null; +export interface NewsArticle { + id: string; + date?: string | null; + maintitle?: string | null; + author?: string | null; + url?: string | null; + relevant?: boolean | null; + snippet?: string | null; + related?: boolean | null; + topics?: Array | null; } - diff --git a/webapp/src/app/api/model/newsArticleDetail.ts b/webapp/src/app/api/model/newsArticleDetail.ts index 171a14ff..0e1ffe47 100644 --- a/webapp/src/app/api/model/newsArticleDetail.ts +++ b/webapp/src/app/api/model/newsArticleDetail.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 @@ -10,19 +10,17 @@ import { MatchedTopic } from './matchedTopic'; import { MentionedPerson } from './mentionedPerson'; - -export interface NewsArticleDetail { - id: string; - date?: string | null; - maintitle?: string | null; - author?: string | null; - url?: string | null; - relevant?: boolean | null; - snippet?: string | null; - related?: boolean | null; - full_content?: string | null; - authors?: Array; - keywords?: Array; - topics?: Array; +export interface NewsArticleDetail { + id: string; + date?: string | null; + maintitle?: string | null; + author?: string | null; + url?: string | null; + relevant?: boolean | null; + snippet?: string | null; + related?: boolean | null; + topics?: Array; + full_content?: string | null; + authors?: Array; + keywords?: Array; } - diff --git a/webapp/src/app/api/model/subfield.ts b/webapp/src/app/api/model/subfield.ts new file mode 100644 index 00000000..ef678f6a --- /dev/null +++ b/webapp/src/app/api/model/subfield.ts @@ -0,0 +1,33 @@ +/** + * Innovation Search Engine API + * + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ +import { DomainFieldsInner } from './domainFieldsInner'; +import { DomainIds } from './domainIds'; +import { SubfieldDomain } from './subfieldDomain'; +import { SubfieldField } from './subfieldField'; + +/** + * Third-level category in the topic hierarchy (254 total) + */ +export interface Subfield { + id?: string | null; + display_name?: string | null; + description?: string | null; + display_name_alternatives?: Array | null; + field?: SubfieldField | null; + domain?: SubfieldDomain | null; + topics?: Array | null; + siblings?: Array | null; + ids?: DomainIds | null; + works_count?: number | null; + cited_by_count?: number | null; + works_api_url?: string | null; + created_date?: string | null; + updated_date?: string | null; +} diff --git a/webapp/src/app/api/model/subfieldDomain.ts b/webapp/src/app/api/model/subfieldDomain.ts new file mode 100644 index 00000000..b2228d75 --- /dev/null +++ b/webapp/src/app/api/model/subfieldDomain.ts @@ -0,0 +1,17 @@ +/** + * Innovation Search Engine API + * + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +/** + * The domain containing this subfield (top level of hierarchy). + */ +export interface SubfieldDomain { + id?: string | null; + display_name?: string | null; +} diff --git a/webapp/src/app/api/model/subfieldField.ts b/webapp/src/app/api/model/subfieldField.ts new file mode 100644 index 00000000..8aff75ea --- /dev/null +++ b/webapp/src/app/api/model/subfieldField.ts @@ -0,0 +1,17 @@ +/** + * Innovation Search Engine API + * + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +/** + * The field containing this subfield (parent level). + */ +export interface SubfieldField { + id?: string | null; + display_name?: string | null; +} diff --git a/webapp/src/app/api/model/updateOrganizationRequest.ts b/webapp/src/app/api/model/updateOrganizationRequest.ts index e12063b6..eede4ba0 100644 --- a/webapp/src/app/api/model/updateOrganizationRequest.ts +++ b/webapp/src/app/api/model/updateOrganizationRequest.ts @@ -1,17 +1,16 @@ /** * Innovation Search Engine API * - * + * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ - -export interface UpdateOrganizationRequest { - name?: string | null; - other_inst_id?: string | null; - deleted?: boolean | null; +export interface UpdateOrganizationRequest { + name?: string | null; + other_inst_id?: string | null; + selected_openalex_institution_ids?: Array | null; + deleted?: boolean | null; } - diff --git a/webapp/src/app/app.config.ts b/webapp/src/app/app.config.ts index 0d7f746c..d3f941bf 100644 --- a/webapp/src/app/app.config.ts +++ b/webapp/src/app/app.config.ts @@ -42,11 +42,10 @@ export const appConfig: ApplicationConfig = { withNavigationErrorHandler((navigationError: NavigationError) => { const router = inject(Router); const errorService = inject(ErrorService); + const targetUrl = navigationError.url; - if ( - router.url.includes('/error') || - router.currentNavigation()?.extractedUrl.toString().includes('/error') - ) { + // Prevent an endless loop if navigation to /error itself fails. + if (targetUrl.startsWith('/error')) { console.error( 'Kritischer Fehler beim Laden der Fehlerseite selbst:', navigationError, @@ -56,21 +55,14 @@ export const appConfig: ApplicationConfig = { console.error('Fehler beim Navigieren:', navigationError); - const error = navigationError.error; - let errorMessage: string = 'Unbekannter Fehler'; - if (error instanceof HttpErrorResponse) { - errorMessage = error.error?.message || 'Unbekannter HTTP-Fehler'; - } - - errorService.setError({ - statusCode: error.status || 500, - title: 'Daten-Fehler', - message: 'Die Daten für diese Ansicht konnten nicht geladen werden.', - errorDetails: errorMessage, + errorService.report(navigationError.error, { + title: 'Daten konnten nicht geladen werden', + message: + 'Die Daten für diese Ansicht konnten nicht geladen werden. Bitte versuchen Sie es später erneut.', }); - setTimeout(() => { - router.navigate(['/error'], { replaceUrl: true }); + void router.navigate(['/error'], { + replaceUrl: true, }); }), ), diff --git a/webapp/src/app/app.routes.ts b/webapp/src/app/app.routes.ts index d193f63e..a69daf52 100644 --- a/webapp/src/app/app.routes.ts +++ b/webapp/src/app/app.routes.ts @@ -6,7 +6,6 @@ import { personPatentsResolver } from './resolvers/person-patents.resolver'; import { personResolver } from './resolvers/person.resolver'; import { personNewsResolver } from './resolvers/person-news.resolver'; import { institutionResolver } from './resolvers/institution.resolver'; -import { bundProjectPageResolver } from './resolvers/bund-project-page.resolver'; import { dfgProjectsResolver, RESOLVING_PROJECT_PAGE_FOR, @@ -37,6 +36,7 @@ import { workPageResolver, workQueryParamKeys, } from './resolvers/work-page.resolver'; +import { keywordsNewsPageResolver } from './resolvers/keywords-news-page.resolver'; import { selectedTopicsResolver } from './resolvers/selected-topics.resolver'; import { selectedInstitutionsResolver } from './resolvers/selected-institutions.resolver'; import { selectedBundInstitutionsResolver } from './resolvers/selected-bund-institutions.resolver'; @@ -65,6 +65,7 @@ import { topicQueryParamKeys, } from './resolvers/topic-page.resolver'; import { topicResolver } from './resolvers/topic.resolver'; +import { canFetchGdprRelevantDataResolver } from './resolvers/can-fetch-gdpr-relevant-data.resolver'; export const routes: Routes = [ { path: '', @@ -273,7 +274,14 @@ export const routes: Routes = [ resolvingFor: RESOLVING_WORK_PAGE_FOR.KEYWORDS_SEARCH, }, }, - { path: 'news', component: KeywordsToNewsResultsComponent }, + { + path: 'news', + component: KeywordsToNewsResultsComponent, + runGuardsAndResolvers: 'always', + resolve: { + newsPage: keywordsNewsPageResolver, + }, + }, { path: 'trends', component: UniTrendParentComponent, @@ -493,6 +501,7 @@ export const routes: Routes = [ personData: personResolver, personBio: personBioResolver, personPatents: personPatentsResolver, + canFetchGdprRelevantData: canFetchGdprRelevantDataResolver, }, runGuardsAndResolvers: (from, to) => from.params['id'] !== to.params['id'], children: [ @@ -658,16 +667,12 @@ export const routes: Routes = [ import('./modules/institution/institution.component').then( (mod) => mod.InstitutionComponent, ), - resolve: { institution: institutionResolver }, + resolve: { + institution: institutionResolver, + canFetchGdprRelevantData: canFetchGdprRelevantDataResolver, + }, children: [ - { path: '', pathMatch: 'full', redirectTo: 'overview' }, - { - path: 'overview', - loadComponent: () => - import('./modules/institution-overview/institution-overview.component').then( - (mod) => mod.InstitutionOverviewComponent, - ), - }, + { path: '', pathMatch: 'full', redirectTo: 'publications' }, { path: 'publications', loadComponent: () => @@ -696,7 +701,9 @@ export const routes: Routes = [ bundProjectsFunding: bundProjectsFundingResolver, cordisEuProjectsFunding: cordisEuProjectsFundingResolver, }, - runGuardsAndResolvers: 'always', + data: { + enableFilters: false, + }, children: [ { path: '', @@ -746,18 +753,6 @@ export const routes: Routes = [ }, }, ], - // resolve: { - // bundProjectPage: bundProjectPageResolver, - // bundProjectsFunding: bundProjectsFundingResolver, - // cordisEuProjectPage: euCordisProjectsResolver, - // cordisEuProjectsFunding: cordisEuProjectsFundingResolver, - // }, - // runGuardsAndResolvers: (from, to) => { - // const keys = ['page', 'size', 'sort_by', 'sort_direction', 'search']; - // return keys.some( - // (key) => from.queryParamMap.get(key) !== to.queryParamMap.get(key), - // ); - // }, }, { path: 'patents', diff --git a/webapp/src/app/custom-directives/sk-text.directive.ts b/webapp/src/app/custom-directives/sk-text.directive.ts index e7173238..07ef9d17 100644 --- a/webapp/src/app/custom-directives/sk-text.directive.ts +++ b/webapp/src/app/custom-directives/sk-text.directive.ts @@ -1,76 +1,80 @@ import { Directive, - OnChanges, - Input, ElementRef, + Input, + OnChanges, Renderer2, + SimpleChanges, + effect, + inject, } from '@angular/core'; -import { SimpleChanges } from '@angular/core'; -@Directive({ selector: '[skText]', standalone: true }) +import { ResolverStateService } from '../../app/shared/services/resolver-state.service'; + +@Directive({ + selector: 'span, [skText]', + standalone: true, +}) export class SkTextDirective implements OnChanges { @Input() skText = false; - private originalText = ''; - private originalColor = ''; + private readonly el = inject(ElementRef); + private readonly renderer = inject(Renderer2); + private readonly resolverStateService = inject(ResolverStateService); - constructor( - private el: ElementRef, - private renderer: Renderer2, - ) {} + constructor() { + effect(() => { + const loading = this.skText || this.resolverStateService.isResolving(); - ngOnChanges(changes: SimpleChanges) { - const change = changes['skText']; - - // skip if value didn't actually change, or is undefined - if (!change) return; - - this.skText ? this.showSkeleton() : this.hideSkeleton(); + if (loading) { + this.showSkeleton(); + } else { + this.hideSkeleton(); + } + }); } - private showSkeleton() { - const el: HTMLElement = this.el.nativeElement; - this.originalText = el.textContent ?? ''; - this.originalColor = el.style.color; + ngOnChanges(changes: SimpleChanges): void { + if (!changes['skText']) { + return; + } - // measure natural width before blanking text - const width = Math.min(Math.max(this.originalText.length * 7.5, 48), 60); - const height = 20; - this.renderer.addClass(el, 'sk-text-loading'); - this.renderer.setStyle(el, 'color', 'transparent'); - this.renderer.setStyle( - el, - 'background', - 'linear-gradient(90deg, #e2e8f0 25%, #f8fafc 50%, #e2e8f0 75%)', - ); - this.renderer.setStyle(el, 'background-size', '600px 100%'); - this.renderer.setStyle(el, 'animation', 'sk-shimmer 1.6s infinite linear'); - this.renderer.setStyle(el, 'border-radius', '4px'); - this.renderer.setStyle(el, 'min-width', `${width}px`); - this.renderer.setStyle(el, 'max-height', `${height}px`); - this.renderer.setStyle(el, 'display', 'inline-block'); - this.renderer.setStyle(el, 'overflow', 'hidden'); - this.renderer.setStyle(el, 'pointer-events', 'none'); + if (this.skText || this.resolverStateService.isResolving()) { + this.showSkeleton(); + } else { + this.hideSkeleton(); + } + } - Array.from(el.children).forEach((child) => { + private showSkeleton(): void { + const element = this.el.nativeElement; + + if (element.classList.contains('sk-text-loading')) { + return; + } + + const text = element.textContent?.trim() ?? ''; + + // For ordinary text elements only. Table cells use CSS width naturally. + if (element.tagName.toLowerCase() !== 'td') { + this.renderer.setStyle(element, 'min-width', `${20}px`); + this.renderer.setStyle(element, 'height', '20px'); + } + + this.renderer.addClass(element, 'sk-text-loading'); + + Array.from(element.children).forEach((child) => { this.renderer.setStyle(child, 'visibility', 'hidden'); }); } - private hideSkeleton() { - const el: HTMLElement = this.el.nativeElement; - this.renderer.removeClass(el, 'sk-text-loading'); - this.renderer.removeStyle(el, 'color'); - this.renderer.removeStyle(el, 'background'); - this.renderer.removeStyle(el, 'background-size'); - this.renderer.removeStyle(el, 'animation'); - this.renderer.removeStyle(el, 'border-radius'); - this.renderer.removeStyle(el, 'min-width'); - this.renderer.removeStyle(el, 'max-height'); - this.renderer.removeStyle(el, 'display'); - this.renderer.removeStyle(el, 'overflow'); - this.renderer.removeStyle(el, 'pointer-events'); + private hideSkeleton(): void { + const element = this.el.nativeElement; - Array.from(el.children).forEach((child) => { + this.renderer.removeClass(element, 'sk-text-loading'); + this.renderer.removeStyle(element, 'min-width'); + this.renderer.removeStyle(element, 'height'); + + Array.from(element.children).forEach((child) => { this.renderer.removeStyle(child, 'visibility'); }); } diff --git a/webapp/src/app/directives/component-tooltip.directive.ts b/webapp/src/app/directives/component-tooltip.directive.ts index 9a945510..daccfa52 100644 --- a/webapp/src/app/directives/component-tooltip.directive.ts +++ b/webapp/src/app/directives/component-tooltip.directive.ts @@ -130,12 +130,14 @@ export class ComponentTooltipDirective implements OnDestroy { .flexibleConnectedTo(this.elementRef) .withPositions(positions) .withFlexibleDimensions(false) + .withViewportMargin(12) .withPush(true); this.overlayRef = this.overlay.create({ positionStrategy, scrollStrategy: this.overlay.scrollStrategies.reposition(), panelClass: 'app-tooltip-panel', + maxWidth: this.tooltipMaxWidth() ?? 'calc(100vw - 24px)', }); const portal = new ComponentPortal(this.component(), null, this.injector); diff --git a/webapp/src/app/modules/accounts/accounts.component.html b/webapp/src/app/modules/accounts/accounts.component.html index 8c88c468..fbab8c8f 100644 --- a/webapp/src/app/modules/accounts/accounts.component.html +++ b/webapp/src/app/modules/accounts/accounts.component.html @@ -10,8 +10,22 @@ }}

+ + +