diff --git a/llm_evaluations/basic_applied_experimental/classify_ude_works_to_index.py b/llm_evaluations/basic_applied_experimental/classify_ude_works_to_index.py index 329842c4..d006ed68 100644 --- a/llm_evaluations/basic_applied_experimental/classify_ude_works_to_index.py +++ b/llm_evaluations/basic_applied_experimental/classify_ude_works_to_index.py @@ -2,6 +2,7 @@ from __future__ import annotations import argparse import json +import sys import time from concurrent.futures import FIRST_COMPLETED, ThreadPoolExecutor, wait from datetime import datetime, timezone @@ -12,6 +13,15 @@ import requests from openai import OpenAI ROOT = Path(__file__).resolve().parent +SERVICE_SOURCE_ROOT = ROOT.parents[1] / "service" / "src" / "main" +if str(SERVICE_SOURCE_ROOT) not in sys.path: + sys.path.insert(0, str(SERVICE_SOURCE_ROOT)) + +from inse.authors.institution_membership_query import ( # noqa: E402 + build_institution_membership_query, + current_affiliation_year_cutoff, +) + PROMPT_FILE = ROOT / "prompt_frascati_hard_ranges_v2.txt" REPORTS_DIR = ROOT / "run_reports" @@ -27,11 +37,13 @@ LLM_MODEL = "gemma4-e4b" PROMPT_VERSION = "frascati_hard_ranges_v2" UDE_ID = "https://openalex.org/I62318514" -UDE_ROR = "https://ror.org/04mz5ra38" -UDE_NAME = "University of Duisburg-Essen" -AFFILIATION_YEAR_GTE = 2025 +AFFILIATION_YEAR_GTE = current_affiliation_year_cutoff() WORK_YEAR_GTE = 1950 +SELECTION_AUTHOR_COHORT = "author-cohort" +SELECTION_INSTITUTION_WORKS = "institution-works" +SELECTION_MODES = (SELECTION_AUTHOR_COHORT, SELECTION_INSTITUTION_WORKS) + AUTHOR_PAGE_SIZE = 1000 AUTHOR_BATCH_SIZE = 1000 WORK_PAGE_SIZE = 2000 @@ -201,6 +213,7 @@ TARGET_TOP_LEVEL_FIELDS = { "work_id", "title", "publication_year", + "publication_type", "doi", "authors", "institutions", @@ -209,6 +222,7 @@ TARGET_TOP_LEVEL_FIELDS = { "validation", "classification_meta", } +TARGET_OPTIONAL_TOP_LEVEL_FIELDS = {"publication_type"} TARGET_CLASSIFICATION_FIELDS = { "primary_category", "applied_orientation_score", @@ -398,6 +412,7 @@ def build_work_metadata( "work_id": full_work_id, "title": title, "publication_year": publication_year, + "publication_type": nullable_text(work.get("type")), "doi": nullable_text(work.get("doi")), "authors": target_authors(work), "institutions": target_institutions(work), @@ -409,12 +424,13 @@ def exact_fields( value: Any, expected: set[str], path: str, + optional: set[str] | None = None, ) -> list[str]: if not isinstance(value, dict): return [f"{path}_must_be_object"] actual = set(value) errors: list[str] = [] - missing = expected - actual + missing = expected - (optional or set()) - actual unknown = actual - expected if missing: errors.append(f"{path}_missing_fields:{','.join(sorted(missing))}") @@ -456,7 +472,12 @@ def validate_target_document( short_work_id: str, document: Any, ) -> list[str]: - errors = exact_fields(document, TARGET_TOP_LEVEL_FIELDS, "document") + errors = exact_fields( + document, + TARGET_TOP_LEVEL_FIELDS, + "document", + optional=TARGET_OPTIONAL_TOP_LEVEL_FIELDS, + ) if not isinstance(document, dict): return errors @@ -466,6 +487,12 @@ def validate_target_document( errors.extend(validate_nullable_string(document.get("title"), "title")) errors.extend(validate_nullable_string(document.get("doi"), "doi")) + errors.extend( + validate_nullable_string( + document.get("publication_type"), + "publication_type", + ) + ) year = document.get("publication_year") if year is not None and (isinstance(year, bool) or not isinstance(year, int)): @@ -854,69 +881,20 @@ def validate(result: dict[str, Any]) -> list[str]: return errors -def ude_affiliation_filter() -> dict[str, Any]: - return { - "nested": { - "path": "affiliations", - "query": { - "bool": { - "filter": [ - { - "bool": { - "should": [ - {"term": {"affiliations.institution.id": UDE_ID}}, - {"term": {"affiliations.institution.ror": UDE_ROR}}, - { - "match_phrase": { - "affiliations.institution.display_name": UDE_NAME - } - }, - ], - "minimum_should_match": 1, - } - }, - { - "range": { - "affiliations.years": {"gte": AFFILIATION_YEAR_GTE} - } - }, - ] - } - }, - } - } - - -def author_query(group: str, after: list[Any] | None) -> dict[str, Any]: - last_known = { - "nested": { - "path": "last_known_institutions", - "query": { - "match_phrase": {"last_known_institutions.display_name": UDE_NAME} - }, - } - } - last_known_exists = { - "nested": { - "path": "last_known_institutions", - "query": {"exists": {"field": "last_known_institutions.display_name"}}, - } - } - query = ( - {"bool": {"filter": [last_known, ude_affiliation_filter()]}} - if group == "known" - else { - "bool": { - "filter": [ude_affiliation_filter()], - "must_not": [last_known_exists], - } - } - ) +def author_query( + after: list[Any] | None, + institution_id: str = UDE_ID, + affiliation_year_gte: int = AFFILIATION_YEAR_GTE, +) -> dict[str, Any]: body: dict[str, Any] = { "size": AUTHOR_PAGE_SIZE, "track_total_hits": True, "_source": ["id"], - "query": query, + "query": build_institution_membership_query( + institution_id=institution_id, + year_mode="from", + year=affiliation_year_gte, + ), "sort": [{"id": "asc"}], } if after is not None: @@ -924,7 +902,22 @@ def author_query(group: str, after: list[Any] | None) -> dict[str, Any]: return body -def work_query(author_ids: list[str], after: list[Any] | None) -> dict[str, Any]: +def work_query( + author_ids: list[str], + after: list[Any] | None, + work_year_gte: int | None = WORK_YEAR_GTE, +) -> dict[str, Any]: + filters: list[dict[str, Any]] = [ + { + "nested": { + "path": "authorships", + "query": {"terms": {"authorships.author.id": author_ids}}, + } + } + ] + if work_year_gte is not None: + filters.insert(0, {"range": {"publication_year": {"gte": work_year_gte}}}) + body: dict[str, Any] = { "size": WORK_PAGE_SIZE, "track_total_hits": False, @@ -964,15 +957,7 @@ def work_query(author_ids: list[str], after: list[Any] | None) -> dict[str, Any] ], "query": { "bool": { - "filter": [ - {"range": {"publication_year": {"gte": WORK_YEAR_GTE}}}, - { - "nested": { - "path": "authorships", - "query": {"terms": {"authorships.author.id": author_ids}}, - } - }, - ] + "filter": filters } }, "sort": [{"id": "asc"}], @@ -982,6 +967,36 @@ def work_query(author_ids: list[str], after: list[Any] | None) -> dict[str, Any] return body +def institution_work_query( + institution_id: str, + after: list[Any] | None, +) -> dict[str, Any]: + """Select all works attributed to an institution, like Publikationsliste.""" + body = work_query([], after) + body["query"] = { + "bool": { + "must": [ + { + "nested": { + "path": "authorships", + "query": { + "nested": { + "path": "authorships.institutions", + "query": { + "terms": { + "authorships.institutions.id": [institution_id] + } + }, + } + }, + } + } + ] + } + } + return body + + def choose_work_hit( current: dict[str, Any] | None, candidate: dict[str, Any], @@ -1016,6 +1031,7 @@ EXPECTED_MAPPING_TYPES = { "work_id": "keyword", "title": "text", "publication_year": "integer", + "publication_type": "keyword", "doi": "keyword", "authors": "nested", "authors.id": "keyword", @@ -1510,32 +1526,42 @@ def classify( raise StopPipeline(f"LLM unavailable for {work_id}: {error}") -def collect_authors(es: ES) -> list[str]: +def collect_authors( + es: ES, + institution_id: str = UDE_ID, + affiliation_year_gte: int = AFFILIATION_YEAR_GTE, +) -> list[str]: ids: set[str] = set() - for group in ("known", "empty"): - after = None - total = None - read = 0 - while True: - result = es.search(AUTHORS_INDEX, author_query(group, after)) - hits = result.get("hits", {}).get("hits", []) - if total is None: - value = result.get("hits", {}).get("total", 0) - total = int(value.get("value", 0) if isinstance(value, dict) else value) - print(f"Authors {group}: expected {total}") - if not hits: - break - for hit in hits: - author_id = (hit.get("_source") or {}).get("id") - if isinstance(author_id, str): - ids.add(author_id) - read += len(hits) - after = hits[-1].get("sort") - if not isinstance(after, list): - raise StopPipeline("Missing author search_after") - print(f"Authors {group}: {read}/{total}") + after = None + total = None + read = 0 + while True: + result = es.search( + AUTHORS_INDEX, + author_query( + after, + institution_id, + affiliation_year_gte, + ), + ) + hits = result.get("hits", {}).get("hits", []) + if total is None: + value = result.get("hits", {}).get("total", 0) + total = int(value.get("value", 0) if isinstance(value, dict) else value) + print(f"Authors: expected {total}") + if not hits: + break + for hit in hits: + author_id = (hit.get("_source") or {}).get("id") + if isinstance(author_id, str): + ids.add(author_id) + read += len(hits) + after = hits[-1].get("sort") + if not isinstance(after, list): + raise StopPipeline("Missing author search_after") + print(f"Authors: {read}/{total}") result = sorted(ids) - print(f"Final UDE author count: {len(result)}") + print(f"Final institution author count: {len(result)}") return result @@ -1726,6 +1752,10 @@ def run( limit: int | None, workers: int, report: dict[str, Any], + selection_mode: str = SELECTION_AUTHOR_COHORT, + institution_id: str = UDE_ID, + affiliation_year_gte: int = AFFILIATION_YEAR_GTE, + work_year_gte: int | None = WORK_YEAR_GTE, preflight_only: bool = False, ) -> None: if not ES_API_KEY.strip(): @@ -1749,17 +1779,32 @@ def run( api_key=LLM_API_KEY, timeout=REQUEST_TIMEOUT, ) - authors = collect_authors(es) - count = 0 warm = False - batches = (len(authors) + AUTHOR_BATCH_SIZE - 1) // AUTHOR_BATCH_SIZE - for start in range(0, len(authors), AUTHOR_BATCH_SIZE): + if selection_mode == SELECTION_INSTITUTION_WORKS: + work_batches: list[tuple[str, list[str] | None]] = [ + (f"Institution works: {institution_id}", None) + ] + else: + authors = collect_authors( + es, + institution_id, + affiliation_year_gte, + ) + batch_count = (len(authors) + AUTHOR_BATCH_SIZE - 1) // AUTHOR_BATCH_SIZE + work_batches = [ + ( + f"Author batch {start // AUTHOR_BATCH_SIZE + 1}/{batch_count}", + authors[start : start + AUTHOR_BATCH_SIZE], + ) + for start in range(0, len(authors), AUTHOR_BATCH_SIZE) + ] + + for batch_label, author_ids in work_batches: if limit is not None and count >= limit: break - batch = authors[start : start + AUTHOR_BATCH_SIZE] - print(f"\nAuthor batch {start // AUTHOR_BATCH_SIZE + 1}/{batches}") + print(f"\n{batch_label}") after = None page = 0 @@ -1767,7 +1812,12 @@ def run( if limit is not None and count >= limit: break - result = es.search(WORKS_INDEX, work_query(batch, after)) + query = ( + institution_work_query(institution_id, after) + if author_ids is None + else work_query(author_ids, after, work_year_gte) + ) + result = es.search(WORKS_INDEX, query) hits = result.get("hits", {}).get("hits", []) if not hits: break @@ -1843,15 +1893,58 @@ def main() -> None: parser.add_argument("--limit", type=int) parser.add_argument("--workers", type=int, default=MAX_WORKERS) parser.add_argument("--preflight-only", action="store_true") + parser.add_argument( + "--selection-mode", + choices=SELECTION_MODES, + default=SELECTION_AUTHOR_COHORT, + help=( + "author-cohort selects works by current affiliated authors; " + "institution-works selects every work attributed to --institution-id" + ), + ) + parser.add_argument("--institution-id", default=UDE_ID) + parser.add_argument( + "--affiliation-year-gte", type=int, default=AFFILIATION_YEAR_GTE + ) + parser.add_argument("--work-year-gte", type=int, default=WORK_YEAR_GTE) + parser.add_argument( + "--all-work-years", + action="store_true", + help=( + "disable the publication-year filter in author-cohort mode, " + "including works without publication_year" + ), + ) args = parser.parse_args() if args.limit is not None and args.limit < 1: raise SystemExit("--limit must be at least 1") if args.workers < 1: raise SystemExit("--workers must be at least 1") + if args.affiliation_year_gte < 0: + raise SystemExit("--affiliation-year-gte must not be negative") + if args.work_year_gte < 0: + raise SystemExit("--work-year-gte must not be negative") + + work_year_gte = None if args.all_work_years else args.work_year_gte + + institution_id = args.institution_id.strip() + if not institution_id: + raise SystemExit("--institution-id must not be empty") + if not institution_id.startswith("https://openalex.org/"): + institution_id = f"https://openalex.org/{bare_id(institution_id)}" report = new_run_report(args.limit, args.workers) report["parameters"]["preflight_only"] = args.preflight_only + report["parameters"].update( + { + "selection_mode": args.selection_mode, + "institution_id": institution_id, + "affiliation_year_gte": args.affiliation_year_gte, + "work_year_gte": work_year_gte, + "all_work_years": args.all_work_years, + } + ) exit_code = 0 try: @@ -1859,6 +1952,10 @@ def main() -> None: args.limit, args.workers, report, + selection_mode=args.selection_mode, + institution_id=institution_id, + affiliation_year_gte=args.affiliation_year_gte, + work_year_gte=work_year_gte, preflight_only=args.preflight_only, ) report["status"] = "completed" diff --git a/llm_evaluations/basic_applied_experimental/run_reports/run_20260722_021910_049378.json b/llm_evaluations/basic_applied_experimental/run_reports/run_20260722_021910_049378.json new file mode 100644 index 00000000..169d8c92 --- /dev/null +++ b/llm_evaluations/basic_applied_experimental/run_reports/run_20260722_021910_049378.json @@ -0,0 +1,50 @@ +{ + "run_id": "20260722_021910_049378", + "started_at": "2026-07-22T02:19:10Z", + "finished_at": "2026-07-22T09:26:37Z", + "duration_seconds": 25645.781, + "status": "completed", + "error": null, + "parameters": { + "limit": null, + "workers": 25, + "model": "gemma4-e4b", + "prompt_version": "frascati_hard_ranges_v2", + "target_index": "work-classifications", + "bulk_batch_size": 200, + "state_storage": "memory_only", + "preflight_only": false, + "selection_mode": "institution-works", + "institution_id": "https://openalex.org/I62318514", + "institution_ror": "https://ror.org/04mz5ra38", + "institution_name": "University of Duisburg-Essen", + "affiliation_year_gte": 2025, + "work_year_gte": 1950 + }, + "classification": { + "llm_completed": 32189, + "valid": 32189, + "invalid": 0, + "categories": { + "applied_research": 10001, + "basic_research": 17089, + "experimental_development": 1813, + "non_research": 3286 + }, + "validation_errors": {} + }, + "indexing": { + "newly_indexed": 32189, + "bulk_requests": 183, + "bulk_documents_submitted": 32589, + "bulk_failures": 0 + }, + "token_usage": { + "prompt_tokens": 119788565, + "cached_prompt_tokens": 110500800, + "uncached_prompt_tokens": 9287765, + "completion_tokens": 29352270, + "real_total_usage": 38640035 + }, + "throughput_indexed_per_hour": 4518.5 +} diff --git a/llm_evaluations/basic_applied_experimental/run_reports/run_20260723_154918_847690.json b/llm_evaluations/basic_applied_experimental/run_reports/run_20260723_154918_847690.json new file mode 100644 index 00000000..a2c15e78 --- /dev/null +++ b/llm_evaluations/basic_applied_experimental/run_reports/run_20260723_154918_847690.json @@ -0,0 +1,51 @@ +{ + "run_id": "20260723_154918_847690", + "started_at": "2026-07-23T15:49:18Z", + "finished_at": "2026-07-23T19:49:04Z", + "duration_seconds": 14385.39, + "status": "completed", + "error": null, + "parameters": { + "limit": null, + "workers": 25, + "model": "gemma4-e4b", + "prompt_version": "frascati_hard_ranges_v2", + "target_index": "work-classifications", + "bulk_batch_size": 200, + "state_storage": "memory_only", + "preflight_only": false, + "selection_mode": "author-cohort", + "institution_id": "https://openalex.org/I62318514", + "institution_ror": "https://ror.org/04mz5ra38", + "institution_name": "University of Duisburg-Essen", + "affiliation_year_gte": 2024, + "work_year_gte": 1950, + "all_work_years": false + }, + "classification": { + "llm_completed": 16272, + "valid": 16272, + "invalid": 0, + "categories": { + "basic_research": 8658, + "applied_research": 4889, + "non_research": 1190, + "experimental_development": 1535 + }, + "validation_errors": {} + }, + "indexing": { + "newly_indexed": 16272, + "bulk_requests": 148, + "bulk_documents_submitted": 16472, + "bulk_failures": 0 + }, + "token_usage": { + "prompt_tokens": 60051102, + "cached_prompt_tokens": 55752000, + "uncached_prompt_tokens": 4299102, + "completion_tokens": 14983831, + "real_total_usage": 19282933 + }, + "throughput_indexed_per_hour": 4072.13 +} diff --git a/service/src/main/inse/authors/institution_membership_query.py b/service/src/main/inse/authors/institution_membership_query.py new file mode 100644 index 00000000..8f4906f1 --- /dev/null +++ b/service/src/main/inse/authors/institution_membership_query.py @@ -0,0 +1,231 @@ +from __future__ import annotations + +from collections.abc import Iterable +from datetime import datetime, timezone +from typing import Any, Literal + + +AFFILIATION_LOOKBACK_YEARS = 2 +OPENALEX_ID_PREFIX = "https://openalex.org/" +AffiliationYearMode = Literal["all", "in", "from"] + + +def current_affiliation_year_cutoff( + reference_time: datetime | None = None, +) -> int: + """Return the inclusive first year used for active membership. + + The shared active cohort includes affiliation years greater than or equal + to the current UTC year minus ``AFFILIATION_LOOKBACK_YEARS``. + ``reference_time`` exists so callers can make the cutoff deterministic + when needed. + """ + + current_time = reference_time or datetime.now(timezone.utc) + return current_time.year - AFFILIATION_LOOKBACK_YEARS + + +def build_institution_affiliation_query( + institution_id: str, + year_mode: AffiliationYearMode = "all", + year: int | None = None, +) -> dict[str, Any]: + """Build an affiliation query for an institution and optional year rule. + + ``all`` accepts an affiliation from any year and requires ``year=None``. + ``in`` requires an affiliation in exactly ``year``. + ``from`` requires an affiliation in ``year`` or any later year. + Institution IDs are normalized to their full OpenAlex URL. + """ + + normalized_institution_id = _normalize_openalex_id(institution_id) + _validate_year_mode(year_mode, year) + + affiliation_filters: list[dict[str, Any]] = [ + { + "term": { + "affiliations.institution.id": normalized_institution_id + } + } + ] + if year_mode == "in": + affiliation_filters.append( + {"term": {"affiliations.years": year}} + ) + elif year_mode == "from": + affiliation_filters.append( + {"range": {"affiliations.years": {"gte": year}}} + ) + + return { + "nested": { + "path": "affiliations", + "query": {"bool": {"filter": affiliation_filters}}, + } + } + + +def build_institution_membership_query( + institution_id: str, + year_mode: AffiliationYearMode = "all", + year: int | None = None, + author_ids: Iterable[str] | None = None, +) -> dict[str, Any]: + """Build an institution membership query for the selected year mode. + + Membership is accepted when one of these conditions matches: + + 1. The institution is both last known and present in the selected + affiliation period. + 2. The institution is last known and no affiliation institution IDs are + available. This fallback is used only for ``all`` and ``from``. + 3. The institution is present in the selected affiliation period and no + last-known institution IDs are available. + + ``in`` deliberately excludes condition 2 because an exact year requires + explicit affiliation evidence for that year. When ``author_ids`` are + supplied, the query is restricted to those authors in the same + Elasticsearch request. Empty ``author_ids`` produce ``match_none``. + Institution and author IDs are normalized to full OpenAlex URLs. + """ + + normalized_institution_id = _normalize_openalex_id(institution_id) + affiliation = build_institution_affiliation_query( + normalized_institution_id, + year_mode=year_mode, + year=year, + ) + + author_filters: list[dict[str, Any]] = [] + if author_ids is not None: + normalized_author_ids = list( + dict.fromkeys( + _normalize_openalex_id(author_id) + for author_id in author_ids + if author_id and author_id.strip() + ) + ) + if not normalized_author_ids: + return {"match_none": {}} + author_filters.append({"terms": {"id": normalized_author_ids}}) + + matching_last_known_institution = { + "nested": { + "path": "last_known_institutions", + "query": { + "term": { + "last_known_institutions.id": normalized_institution_id + } + }, + } + } + any_affiliation_id = { + "nested": { + "path": "affiliations", + "query": { + "exists": { + "field": "affiliations.institution.id" + } + }, + } + } + any_last_known_institution_id = { + "nested": { + "path": "last_known_institutions", + "query": { + "exists": { + "field": "last_known_institutions.id" + } + }, + } + } + + # Confirmed by both last-known and affiliation evidence. + membership_branches: list[dict[str, Any]] = [ + { + "bool": { + "filter": [ + matching_last_known_institution, + affiliation, + ] + } + }, + # Affiliation evidence is accepted when last-known data is unavailable. + { + "bool": { + "filter": [affiliation], + "must_not": [any_last_known_institution_id], + } + }, + ] + if year_mode != "in": + # Last-known is the fallback only when affiliation IDs are unavailable. + membership_branches.insert( + 1, + { + "bool": { + "filter": [matching_last_known_institution], + "must_not": [any_affiliation_id], + } + }, + ) + + membership_query = { + "bool": { + "should": membership_branches, + "minimum_should_match": 1, + } + } + + if not author_filters: + return membership_query + + return { + "bool": { + "filter": [ + *author_filters, + membership_query, + ], + } + } + + +def build_active_institution_membership_query( + institution_id: str, + author_ids: Iterable[str] | None = None, + reference_time: datetime | None = None, +) -> dict[str, Any]: + """Build the shared active-cohort query. + + Active membership uses ``from`` with the inclusive cutoff returned by + ``current_affiliation_year_cutoff``. It therefore applies the same + membership and fallback rules everywhere that consumes this helper. + """ + + return build_institution_membership_query( + institution_id=institution_id, + year_mode="from", + year=current_affiliation_year_cutoff(reference_time), + author_ids=author_ids, + ) + + +def _validate_year_mode( + year_mode: AffiliationYearMode, + year: int | None, +) -> None: + if year_mode not in {"all", "in", "from"}: + raise ValueError(f"Unsupported affiliation year mode: {year_mode}") + if year_mode == "all": + if year is not None: + raise ValueError("year must be omitted when year_mode is 'all'") + return + if isinstance(year, bool) or not isinstance(year, int): + raise ValueError(f"year is required when year_mode is '{year_mode}'") + + +def _normalize_openalex_id(raw_id: str) -> str: + normalized_id = raw_id.strip() + if normalized_id.startswith(OPENALEX_ID_PREFIX): + return normalized_id + return f"{OPENALEX_ID_PREFIX}{normalized_id}" diff --git a/service/src/main/inse/authors/v2/service.py b/service/src/main/inse/authors/v2/service.py index e0347314..b4b8b928 100644 --- a/service/src/main/inse/authors/v2/service.py +++ b/service/src/main/inse/authors/v2/service.py @@ -1,11 +1,12 @@ from typing import Dict, List, Optional, Set +from inse.authors.institution_membership_query import ( + build_active_institution_membership_query, +) from inse.authors.v2.model import AuthorPage from inse.integrations import elasticsearch -from inse.institutions.v2 import service as institution_service from inse.model import ESIndex from inse.models.openalex.author import Author -from inse.models.openalex.institution import Institution async def search_authors( @@ -117,177 +118,40 @@ async def get_authors_by_ids(author_ids: List[str]) -> AuthorPage: async def author_currently_belongs_to_institution( raw_oa_author_id: str, raw_oa_institution_id: str, - current_years: List[int] = [2025, 2026], ) -> bool: - """Checks if an author currently belongs to a specific institution based on their affiliations and the provided years. + """Return whether one author belongs to the institution's active cohort. Args: raw_oa_author_id (str): The ID of the author to check. raw_oa_institution_id (str): The ID of the institution to check. - current_years (List[int], optional): The years to check for affiliation. Defaults to [2025, 2026]. Returns: - bool: True if the author belongs to the institution in any of the specified years, False otherwise. + bool: True if the author matches the shared active-membership query. """ - if not current_years: - return False - - matching_author_ids = await _authors_belong_to_institution( + matching_author_ids = await authors_currently_belong_to_institution( [raw_oa_author_id], raw_oa_institution_id, - affiliation_year_filter={"terms": {"affiliations.years": current_years}}, ) return bool(matching_author_ids) -def _prefix_openalex_id(raw_id: str) -> str: - if raw_id.startswith("https://openalex.org/"): - return raw_id - return f"https://openalex.org/{raw_id}" - - -async def _get_institution_identity( - raw_oa_institution_id: str, -) -> Optional[Institution]: - page = await institution_service.get_institutions_by_ids( - [_prefix_openalex_id(raw_oa_institution_id)] - ) - return page.elements[0] if page.elements else None - - -def _current_institution_cohort_query( - author_ids: List[str], - institution_id: str, - institution_ror: Optional[str], - institution_display_name: str, - affiliation_year_filter: Dict, -) -> Dict: - """Build the author cohort query used by work classification access.""" - - affiliation_identifiers = [ - {"term": {"affiliations.institution.id": institution_id}}, - ] - if institution_ror: - affiliation_identifiers.append( - {"term": {"affiliations.institution.ror": institution_ror}} - ) - affiliation_identifiers.append( - { - "match_phrase": { - "affiliations.institution.display_name": institution_display_name - } - } - ) - - recent_affiliation = { - "nested": { - "path": "affiliations", - "query": { - "bool": { - "filter": [ - { - "bool": { - "should": affiliation_identifiers, - "minimum_should_match": 1, - } - }, - affiliation_year_filter, - ] - } - }, - } - } - matching_last_known_institution = { - "nested": { - "path": "last_known_institutions", - "query": { - "match_phrase": { - "last_known_institutions.display_name": institution_display_name - } - }, - } - } - missing_last_known_institutions = { - "bool": { - "must_not": [ - { - "nested": { - "path": "last_known_institutions", - "query": { - "exists": { - "field": "last_known_institutions.display_name" - } - }, - } - } - ] - } - } - - return { - "bool": { - "filter": [ - { - "terms": { - "id": [_prefix_openalex_id(author_id) for author_id in author_ids] - } - }, - recent_affiliation, - { - "bool": { - "should": [ - matching_last_known_institution, - missing_last_known_institutions, - ], - "minimum_should_match": 1, - } - }, - ] - } - } - - async def authors_currently_belong_to_institution( raw_oa_author_ids: List[str], raw_oa_institution_id: str, ) -> Set[str]: - """Return current cohort members using one query for all author IDs.""" - - return await _authors_belong_to_institution( - raw_oa_author_ids, - raw_oa_institution_id, - affiliation_year_filter={ - "range": {"affiliations.years": {"gte": 2025}} - }, - ) - - -async def _authors_belong_to_institution( - raw_oa_author_ids: List[str], - raw_oa_institution_id: str, - affiliation_year_filter: Dict, -) -> Set[str]: - """Return matching author IDs for the supplied affiliation-year filter.""" + """Return active cohort members using one query for all supplied authors.""" author_ids = list(dict.fromkeys(filter(None, raw_oa_author_ids))) if not author_ids: return set() - institution = await _get_institution_identity(raw_oa_institution_id) - if not institution or not institution.display_name: - return set() - authors = await search_authors( page=0, size=len(author_ids), - query=_current_institution_cohort_query( + query=build_active_institution_membership_query( + institution_id=raw_oa_institution_id, author_ids=author_ids, - institution_id=institution.id - or _prefix_openalex_id(raw_oa_institution_id), - institution_ror=institution.ror, - institution_display_name=institution.display_name, - affiliation_year_filter=affiliation_year_filter, ), source=["id"], ) diff --git a/service/src/main/inse/company_connections/logic.py b/service/src/main/inse/company_connections/logic.py index ceb39e06..14ccae33 100644 --- a/service/src/main/inse/company_connections/logic.py +++ b/service/src/main/inse/company_connections/logic.py @@ -2,18 +2,30 @@ import logging from typing import Any from . import model -from inse.exceptions import MissingApiKeyError, ElasticsearchException, NotFoundException +from inse.authors.v2.service import author_currently_belongs_to_institution +from inse.exceptions import NotFoundException from .search_client import CompanyConnectionsSearchClient logger = logging.getLogger(__name__) -UDE_OPENALEX_ID = "https://openalex.org/I62318514" -UDE_ROR = "https://ror.org/04mz5ra38" -UDE_DISPLAY_NAME = "University of Duisburg-Essen" - MATCHING_METHOD = "exact_openalex_display_name_to_handelsregister_officer_name" +async def author_has_company_connections_access( + author_id: str, + institution_id: str | None, +) -> bool: + """Return whether the author belongs to the account institution's active cohort.""" + + if not institution_id: + return False + + return await author_currently_belongs_to_institution( + raw_oa_author_id=author_id, + raw_oa_institution_id=institution_id, + ) + + async def get_company_connections_by_author_id( author_id: str, client: CompanyConnectionsSearchClient | None = None, @@ -27,16 +39,11 @@ async def get_company_connections_by_author_id( source = author_hit.get("_source", {}) display_name = _clean(source.get("display_name")) - institution_scope, matching_institutions = _get_ude_institution_scope(source) - is_ude_author = institution_scope is not None - if not is_ude_author or not display_name: + if not display_name: return model.CompanyConnectionsResponse( author_id=author_id, display_name=display_name or None, - is_ude_author=is_ude_author, - institution_scope=institution_scope, - matching_institutions=matching_institutions, matching_method=None, company_count=0, has_more_results=False, @@ -62,9 +69,6 @@ async def get_company_connections_by_author_id( return model.CompanyConnectionsResponse( author_id=author_id, display_name=display_name, - is_ude_author=True, - institution_scope=institution_scope, - matching_institutions=matching_institutions, matching_method=MATCHING_METHOD, company_count=company_count, has_more_results=has_more_results, @@ -95,44 +99,6 @@ async def get_company_counts_by_names( ) -def _get_ude_institution_scope(source: dict[str, Any]) -> tuple[str | None, list[str]]: - institutions = source.get("last_known_institutions") or [] - - direct_matches: list[str] = [] - child_matches: list[str] = [] - - for institution in institutions: - if not isinstance(institution, dict): - continue - - institution_id = _clean(institution.get("id")) - ror = _clean(institution.get("ror")) - name = _clean(institution.get("display_name")) - lineage = institution.get("lineage") or [] - - label = name or institution_id or ror - - is_direct = ( - institution_id == UDE_OPENALEX_ID - or ror == UDE_ROR - or name == UDE_DISPLAY_NAME - ) - is_child = UDE_OPENALEX_ID in lineage and not is_direct - - if is_direct: - direct_matches.append(label) - elif is_child: - child_matches.append(label) - - if direct_matches: - return "direct_ude", sorted(set(direct_matches)) - - if child_matches: - return "child_of_ude", sorted(set(child_matches)) - - return None, [] - - def _parse_total(response: dict[str, Any]) -> tuple[int, str]: total = response.get("hits", {}).get("total", 0) diff --git a/service/src/main/inse/company_connections/model.py b/service/src/main/inse/company_connections/model.py index dd7d28c0..bb7c567e 100644 --- a/service/src/main/inse/company_connections/model.py +++ b/service/src/main/inse/company_connections/model.py @@ -28,12 +28,13 @@ class CompanyConnection(BaseModel): officers: list[MatchedOfficer] = Field(default_factory=list) +class CompanyConnectionsAvailability(BaseModel): + available: bool + + class CompanyConnectionsResponse(BaseModel): author_id: str display_name: str | None = None - is_ude_author: bool - institution_scope: str | None = None - matching_institutions: list[str] = Field(default_factory=list) matching_method: str | None = None diff --git a/service/src/main/inse/company_connections/service.py b/service/src/main/inse/company_connections/service.py index a739aa1c..19bef518 100644 --- a/service/src/main/inse/company_connections/service.py +++ b/service/src/main/inse/company_connections/service.py @@ -4,7 +4,12 @@ REST API for possible company connections of OpenAlex authors. """ -from fastapi import APIRouter +from typing import Annotated + +from fastapi import APIRouter, HTTPException, status + +from inse.auth.model import AccessTokenMetadata +from inse.auth.service import CurrentUserAccessTokenPayloadDep from . import logic, model @@ -14,6 +19,25 @@ router = APIRouter( ) +@router.get( + "/{author_id}/company-connections/availability", + operation_id="getCompanyConnectionsAvailability", + response_model=model.CompanyConnectionsAvailability, + summary="Check whether company connections are available for an author.", +) +async def get_company_connections_availability( + access_token_metadata: Annotated[ + AccessTokenMetadata, CurrentUserAccessTokenPayloadDep + ], + author_id: str, +) -> model.CompanyConnectionsAvailability: + available = await logic.author_has_company_connections_access( + author_id=author_id, + institution_id=access_token_metadata.effective_institution_id, + ) + return model.CompanyConnectionsAvailability(available=available) + + @router.get( "/{author_id}/company-connections", operation_id="getCompanyConnectionsByAuthor", @@ -21,5 +45,23 @@ router = APIRouter( response_model_exclude_none=True, summary="Get possible company connections by OpenAlex author ID.", ) -async def get_company_connections_by_author(author_id: str): +async def get_company_connections_by_author( + access_token_metadata: Annotated[ + AccessTokenMetadata, CurrentUserAccessTokenPayloadDep + ], + author_id: str, +): + available = await logic.author_has_company_connections_access( + author_id=author_id, + institution_id=access_token_metadata.effective_institution_id, + ) + if not available: + raise HTTPException( + status_code=status.HTTP_403_FORBIDDEN, + detail=( + "Company connections are only available for active members " + "of the account institution." + ), + ) + return await logic.get_company_connections_by_author_id(author_id) diff --git a/service/src/main/inse/institutions/institutions_search_client.py b/service/src/main/inse/institutions/institutions_search_client.py index 1c3a060f..af18216e 100644 --- a/service/src/main/inse/institutions/institutions_search_client.py +++ b/service/src/main/inse/institutions/institutions_search_client.py @@ -157,49 +157,6 @@ class InstitutionsSearchClient: total=total, ) - async def get_authors_by_institution_id(self, raw_institution_id: str) -> List[str]: - """ - Fetches authors associated with an institution. - Note: This query is specifically looking for current affiliations (2026). - """ - query = { - "nested": { - "path": "affiliations", - "query": { - "bool": { - "must": [ - { - "term": { - "affiliations.institution.id": f"https://openalex.org/{raw_institution_id.upper()}" - } - }, - { - "range": { - "affiliations.years": {"gte": 2026, "lte": 2026} - } - }, - ] - } - }, - } - } - logger.debug( - "Fetching authors for institution_id=%s with query: %s", - raw_institution_id, - query, - ) - - res = await elasticsearch.search(index="openalex-authors", query=query) - hits = res.get("hits", {}).get("hits", []) - - # Extracting display_name directly from the author document source - authors = { - hit["_source"].get("display_name") - for hit in hits - if hit["_source"].get("display_name") - } - return list(authors) - async def search_institutions( self, query_text: str, diff --git a/service/src/main/inse/integrations/llm.py b/service/src/main/inse/integrations/llm.py index 180edfbc..101ce92c 100644 --- a/service/src/main/inse/integrations/llm.py +++ b/service/src/main/inse/integrations/llm.py @@ -1,9 +1,9 @@ -from openai import OpenAI, APIConnectionError +from openai import APIConnectionError from openai import AsyncOpenAI from .. import config from typing import Optional, Dict, Any import asyncio -def call( +async def call( system_prompt: str, user_prompt: str, model: str = None, @@ -16,18 +16,18 @@ def call( if model is None: model = config.settings.llm_model - + response_format = None if json_schema is not None: response_format = _get_response_format(schema = json_schema,schema_name=schema_name) - - client = OpenAI( + + client = AsyncOpenAI( base_url=config.settings.llm_api_url, api_key=config.settings.llm_api_key, timeout=timeout, ) try: - response = client.chat.completions.create( + response = await client.chat.completions.create( model=model, messages=[ {"role": "system", "content": system_prompt}, diff --git a/service/src/main/inse/keywords/logic.py b/service/src/main/inse/keywords/logic.py index 964c5364..b2bdcb2e 100644 --- a/service/src/main/inse/keywords/logic.py +++ b/service/src/main/inse/keywords/logic.py @@ -82,7 +82,7 @@ async def extract_keywords(query: str, mode: str, limit: int) -> ExtractedKeywor user_prompt += f"""Input:{text}""" - keywords = llm.call( + keywords = await llm.call( system_prompt=system_prompt, user_prompt=user_prompt, json_schema = ExtractedKeywordsLLM.model_json_schema(), diff --git a/service/src/main/inse/main.py b/service/src/main/inse/main.py index bb55e148..65f076d7 100644 --- a/service/src/main/inse/main.py +++ b/service/src/main/inse/main.py @@ -61,6 +61,9 @@ from inse.topics.v2.router import router as topics_v2_router from inse.projects.dfg_institutions.router import router as dfg_institutions_router from inse.projects.dfg_persons.router import router as dfg_persons_router + +from inse.projects.eu_organizations.router import router as eu_organizations_router + logger = logging.getLogger(__name__) ### startup @@ -120,6 +123,7 @@ app.include_router(dfg_institutions_router) app.include_router(dfg_persons_router) app.include_router(bookmarks_router) +app.include_router(eu_organizations_router) app.add_middleware( ETagCacheMiddleware, ttl=120, # 2 minutes expiration time diff --git a/service/src/main/inse/middleware/etag_cache.py b/service/src/main/inse/middleware/etag_cache.py index 3f36e483..47076a63 100644 --- a/service/src/main/inse/middleware/etag_cache.py +++ b/service/src/main/inse/middleware/etag_cache.py @@ -8,14 +8,23 @@ from starlette.middleware.base import BaseHTTPMiddleware from starlette.requests import Request from starlette.responses import Response -# Paths excluded from caching entirely (everything concerning auth/identity/mutations) -EXCLUDED_PATHS = ( - "/api/auth/v2", - "/api/accounts", - "/api/bookmarks", - "/api/organizations", -) - +# Responses whose contents depend on the current account or effective +# organization must never be reused by the browser. +NO_STORE_PATH_PREFIXES = ( + "/api/auth/v2", + "/api/accounts", + "/api/bookmarks", + "/api/organizations", + "/api/dashboard", + "/api/rank/rank-author", + "/api/v2/works/classification/", +) + +NO_STORE_PATH_FRAGMENTS = ( + "/company-connections", + "/primary-category-aggregations", +) + # POST is opt-out. Add any endpoint here that MUTATES state (create/update/delete/ # trigger side effects), even if it "usually" returns 200. EXCLUDED_POST_PATHS = ( @@ -82,21 +91,61 @@ class ETagCacheMiddleware(BaseHTTPMiddleware): return f"{user_id}:{base}" return base - def _content_type(self, response: Response) -> str | None: - return response.headers.get("content-type") - - def _is_cacheable_request(self, request: Request) -> bool: - if request.url.path.startswith(EXCLUDED_PATHS): - return False + def _content_type(self, response: Response) -> str | None: + return response.headers.get("content-type") + + def _requires_no_store(self, request: Request) -> bool: + path = request.url.path + return path.startswith(NO_STORE_PATH_PREFIXES) or any( + fragment in path for fragment in NO_STORE_PATH_FRAGMENTS + ) + + def _set_no_store_headers(self, response: Response) -> None: + response.headers["Cache-Control"] = "private, no-store, max-age=0" + response.headers["Pragma"] = "no-cache" + response.headers["Expires"] = "0" + self._append_vary_authorization(response.headers) + + @staticmethod + def _append_vary_authorization(headers) -> None: + vary_values = [ + value.strip() + for value in headers.get("Vary", "").split(",") + if value.strip() + ] + if not any(value.lower() == "authorization" for value in vary_values): + vary_values.append("Authorization") + headers["Vary"] = ", ".join(vary_values) + + def _cache_response_headers( + self, request: Request, etag: str, content_type: str | None + ) -> dict[str, str]: + cache_control = f"max-age={self.ttl}" + headers = {"ETag": etag, "Cache-Control": cache_control} + if request.headers.get("authorization"): + headers["Cache-Control"] = f"private, {cache_control}" + headers["Vary"] = "Authorization" + if content_type: + headers["Content-Type"] = content_type + return headers + + def _is_cacheable_request(self, request: Request) -> bool: + if self._requires_no_store(request): + return False if request.method == "GET": return True if request.method == "POST": return not request.url.path.startswith(EXCLUDED_POST_PATHS) return False - async def dispatch(self, request: Request, call_next): - if not self._is_cacheable_request(request): - return await call_next(request) + async def dispatch(self, request: Request, call_next): + if self._requires_no_store(request): + response = await call_next(request) + self._set_no_store_headers(response) + return response + + if not self._is_cacheable_request(request): + return await call_next(request) body_bytes = b"" if request.method == "POST": @@ -116,17 +165,21 @@ class ETagCacheMiddleware(BaseHTTPMiddleware): client_etag = request.headers.get("if-none-match") # Cache hit + not expired - if entry: - if client_etag == entry["etag"]: - headers = {"ETag": entry["etag"]} - if entry.get("content_type"): - headers["Content-Type"] = entry["content_type"] - return Response(status_code=304, headers=headers) - - headers = {"ETag": entry["etag"], "Cache-Control": f"max-age={self.ttl}"} - if entry.get("content_type"): - headers["Content-Type"] = entry["content_type"] - return Response( + if entry: + if client_etag == entry["etag"]: + headers = self._cache_response_headers( + request, + entry["etag"], + entry.get("content_type"), + ) + return Response(status_code=304, headers=headers) + + headers = self._cache_response_headers( + request, + entry["etag"], + entry.get("content_type"), + ) + return Response( content=entry["body"], status_code=entry["status_code"], headers=headers, @@ -151,11 +204,9 @@ class ETagCacheMiddleware(BaseHTTPMiddleware): }, ) - headers = {"ETag": etag, "Cache-Control": f"max-age={self.ttl}"} - if content_type: - headers["Content-Type"] = content_type - return Response( + headers = self._cache_response_headers(request, etag, content_type) + return Response( content=body, status_code=response.status_code, headers=headers, - ) \ No newline at end of file + ) diff --git a/service/src/main/inse/news/logic.py b/service/src/main/inse/news/logic.py index 3ced9bf5..bb423948 100644 --- a/service/src/main/inse/news/logic.py +++ b/service/src/main/inse/news/logic.py @@ -292,7 +292,7 @@ async def _get_article_keywords( if not text: return [] - raw = llm.call( + raw = await llm.call( system_prompt=KEYWORD_SYSTEM_PROMPT, user_prompt=f"Artikel:\n{text}", temperature=0.3, diff --git a/service/src/main/inse/persons/logic.py b/service/src/main/inse/persons/logic.py index 43db5add..c8c7a157 100644 --- a/service/src/main/inse/persons/logic.py +++ b/service/src/main/inse/persons/logic.py @@ -444,7 +444,7 @@ async def generate_person_bio( user_prompt = f"Daten zur Person:\n{person_json}" - bio = llm.call( + bio = await llm.call( system_prompt=system_prompt, user_prompt=user_prompt, temperature=0.8, @@ -608,100 +608,6 @@ async def search_persons_autocomplete( return AuthorsListResponse(results=persons) -async def search_persons_by_institution( - institution_name: str, - limit: Optional[int] = 10, - page_offset: Optional[int] = 0, - include: Optional[str] = None, -) -> AuthorsListResponse: - if not institution_name: - raise BadRequestException("institution_name must be provided") - - target_year = datetime.now().year - 1 - - recent_affiliation_query = { - "nested": { - "path": "affiliations", - "query": { - "bool": { - "filter": [ - { - "match_phrase": { - "affiliations.institution.display_name": institution_name - } - }, - {"range": {"affiliations.years": {"gte": target_year}}}, - ] - } - }, - } - } - matching_last_known_institution_query = { - "nested": { - "path": "last_known_institutions", - "query": { - "match_phrase": { - "last_known_institutions.display_name": institution_name - } - }, - } - } - missing_last_known_institutions_query = { - "bool": { - "must_not": [ - { - "nested": { - "path": "last_known_institutions", - "query": {"exists": {"field": "last_known_institutions.id"}}, - } - } - ] - } - } - search_query = { - "bool": { - "should": [ - { - "bool": { - "filter": [ - matching_last_known_institution_query, - recent_affiliation_query, - ] - } - }, - { - "bool": { - "filter": [ - missing_last_known_institutions_query, - recent_affiliation_query, - ] - } - }, - ], - "minimum_should_match": 1, - } - } - try: - response = await elasticsearch.search( - index="openalex-authors", - query=search_query, - source=include.split(",") if include else True, - size=limit, - offset=page_offset, - sort=[{"works_count": {"order": "desc"}}], - track_total_hits=True, - ) - - except ElasticsearchException as e: - raise ElasticsearchException(f"Elasticsearch search failed: {str(e)}") from e - total_count = response.get("hits", {}).get("total", {}).get("value", 0) - hits = response.get("hits", {}).get("hits", []) - persons = [util.get_persons_data(hit) for hit in hits] - return AuthorsListResponse( - results=persons, meta=Meta(count=total_count, page=page_offset) - ) - - def _enrich_author_data(author_data) -> Optional[CustomAuthor]: if not author_data: return None @@ -747,28 +653,28 @@ def _enrich_author_data(author_data) -> Optional[CustomAuthor]: async def advanced_search_persons( query: Optional[str] = None, - institution_name: Optional[str] = None, + institution_id: Optional[str] = None, sort_by: Optional[str] = None, sort_order: Optional[str] = None, topics: Optional[List[str]] = None, page: int = 1, page_size: int = 10, include: Optional[set[str]] = None, - strict: Optional[bool] = False, + year_filter_enabled: bool = True, filter_mode: Optional[str] = "from", filter_year: Optional[int] = None, ) -> CustomAuthorsListResponse: try: query_body = build_authors_search_rescored( query=query, - institution_name=institution_name, + institution_id=institution_id, sort_by=sort_by, sort_order=sort_order, topics=topics, page=page, page_size=page_size, include=include, - strict=strict, + year_filter_enabled=year_filter_enabled, track_total_hits=True, filter_mode=filter_mode, filter_year=filter_year, diff --git a/service/src/main/inse/persons/query_builder.py b/service/src/main/inse/persons/query_builder.py index a45a492f..788ea3ac 100644 --- a/service/src/main/inse/persons/query_builder.py +++ b/service/src/main/inse/persons/query_builder.py @@ -1,10 +1,15 @@ from typing import Any, List, Optional, Set +from inse.authors.institution_membership_query import ( + build_institution_membership_query, + current_affiliation_year_cutoff, +) + def build_author_filter_clauses( - institution_name: Optional[str] = None, + institution_id: Optional[str] = None, topics: Optional[List[str]] = None, - strict: Optional[bool] = False, + year_filter_enabled: bool = True, filter_mode: Optional[str] = "from", filter_year: Optional[int] = None, ) -> List[dict]: @@ -46,109 +51,25 @@ def build_author_filter_clauses( } } ) - # Institution filter with optional year-based filtering - if institution_name: - if filter_year is not None: - target_year = filter_year - mode = filter_mode or "from" - else: - from datetime import datetime - - current_year = datetime.now().year - target_year = current_year - 1 - mode = "from" - - range_query = {"gte": target_year} - if mode == "in": - range_query["lte"] = target_year - - if strict: - filter_clauses.append( - { - "nested": { - "path": "affiliations", - "query": { - "bool": { - "filter": [ - { - "match_phrase": { - "affiliations.institution.display_name": institution_name - } - }, - {"range": {"affiliations.years": range_query}}, - ] - } - }, - } - } + if institution_id: + if year_filter_enabled: + membership_mode = "in" if filter_mode == "in" else "from" + membership_year = ( + filter_year + if filter_year is not None + else current_affiliation_year_cutoff() ) else: - recent_affiliation_query = { - "nested": { - "path": "affiliations", - "query": { - "bool": { - "filter": [ - { - "match_phrase": { - "affiliations.institution.display_name": institution_name - } - }, - {"range": {"affiliations.years": range_query}}, - ] - } - }, - } - } - matching_last_known_institution_query = { - "nested": { - "path": "last_known_institutions", - "query": { - "match_phrase": { - "last_known_institutions.display_name": institution_name - } - }, - } - } - missing_last_known_institutions_query = { - "bool": { - "must_not": [ - { - "nested": { - "path": "last_known_institutions", - "query": { - "exists": {"field": "last_known_institutions.id"} - }, - } - } - ] - } - } - filter_clauses.append( - { - "bool": { - "should": [ - { - "bool": { - "filter": [ - matching_last_known_institution_query, - recent_affiliation_query, - ] - } - }, - { - "bool": { - "filter": [ - missing_last_known_institutions_query, - recent_affiliation_query, - ] - } - }, - ], - "minimum_should_match": 1, - } - } + membership_mode = "all" + membership_year = None + + filter_clauses.append( + build_institution_membership_query( + institution_id=institution_id, + year_mode=membership_mode, + year=membership_year, ) + ) if topics: for t in topics: @@ -169,14 +90,14 @@ def build_authors_search_rescored( using: Any = None, index: Optional[str] = None, query: Optional[str] = None, - institution_name: Optional[str] = None, + institution_id: Optional[str] = None, sort_by: Optional[str] = None, sort_order: Optional[str] = None, topics: Optional[List[str]] = None, page: int = 1, page_size: int = 10, include: Optional[Set[str]] = None, - strict: Optional[bool] = False, + year_filter_enabled: bool = True, track_total_hits: Optional[bool] = False, filter_mode: Optional[str] = "from", filter_year: Optional[int] = None, @@ -209,9 +130,9 @@ def build_authors_search_rescored( # 2. Build Filters filter_clauses = build_author_filter_clauses( - institution_name=institution_name, + institution_id=institution_id, topics=topics, - strict=strict, + year_filter_enabled=year_filter_enabled, filter_mode=filter_mode, filter_year=filter_year, ) diff --git a/service/src/main/inse/persons/service.py b/service/src/main/inse/persons/service.py index dfdf7fd7..51fb1c5c 100644 --- a/service/src/main/inse/persons/service.py +++ b/service/src/main/inse/persons/service.py @@ -150,33 +150,6 @@ async def search_persons_autocomplete( return await logic.search_persons_autocomplete(author_name=author_name, include=include) -@router.get( - "/persons/searchByInstitution", - operation_id="searchPersonsByInstitution", - response_model=AuthorsListResponse, - summary="Searches for persons by institution name.", - tags=["Persons"], -) -async def search_persons_by_institution( - institution_name: Annotated[ - str, Query(description="Institution name (e.g., MIT, Oxford University)") - ], - include: Annotated[ - Optional[str], - Query( - description=( - "Which data do we require? include tags: topics_full, topic_share, summary_stats, ids, " - "last_known_institutions, ..." - ), - example="topics_full,topic_share", - ), - ], - limit:Annotated[Optional[int], Query(description=("Limit of search page results"),example ="2")]= None, - page_offset : Annotated[Optional[int], Query(description=("Offset of the result page"),example="2")] = None, -): - return await logic.search_persons_by_institution(institution_name, include=include, page_offset=page_offset, limit=limit) - - @router.get( "/persons/search-list", operation_id="searchPersonsList", @@ -189,8 +162,9 @@ async def search_persons_list( query: Annotated[ Optional[str], Query(description="Search query (e.g., Arman AND Arzani)") ] = None, - institution_name: Annotated[ - Optional[str], Query(alias="institutionName", description="Filter by institution name") + institution_id: Annotated[ + Optional[str], + Query(alias="institutionId", description="Filter by OpenAlex institution ID"), ] = None, sort_by: Annotated[ Optional[str], Query(alias="sortBy", description="Value to sort by") @@ -214,9 +188,13 @@ async def search_persons_list( example="topics_full,topic_share", ), ] = None, - strict: Annotated[ - Optional[bool], Query(description="Strict institution search by target year") - ] = False, + year_filter_enabled: Annotated[ + bool, + Query( + alias="yearFilterEnabled", + description="Apply the selected affiliation year rule", + ), + ] = True, filter_mode: Annotated[ Optional[str], Query(alias="filterMode", description="Filter mode: 'in' or 'from'") ] = "from", @@ -231,14 +209,14 @@ async def search_persons_list( ) return await logic.advanced_search_persons( query=query, - institution_name=institution_name, + institution_id=institution_id, sort_by=sort_by, sort_order=sort_order, topics=topic, page=page, page_size=page_size, include=include_set, - strict=strict, + year_filter_enabled=year_filter_enabled, filter_mode=filter_mode, filter_year=filter_year, ) diff --git a/service/src/main/inse/projects/eu_cordis_projects_client.py b/service/src/main/inse/projects/eu_cordis_projects_client.py new file mode 100644 index 00000000..8efd3813 --- /dev/null +++ b/service/src/main/inse/projects/eu_cordis_projects_client.py @@ -0,0 +1,1027 @@ +import logging +import asyncio +from typing import Any, Dict, List, Optional, Union, Tuple, Set +from collections import defaultdict +from inse.config import get_settings +from inse.integrations import elasticsearch +from inse.model import ESCluster, ESIndex +from inse.authors.v2.model import AuthorPage +from inse.authors.v2.service import get_authors_by_ids +# Import base models +from inse.models.cordis_eu_project import CordisEuProject + +# Import FP7 models +from inse.models.projects_eu_cordis.fp7.fp7_project import Fp7Project +from inse.models.projects_eu_cordis.fp7.fp7_organization import Fp7Organization +from inse.models.projects_eu_cordis.fp7.fp7_publication import Fp7Publication +from inse.models.projects_eu_cordis.fp7.fp7_project_ipr import Fp7ProjectIPR +from inse.models.projects_eu_cordis.fp7.fp7_report_summary import Fp7ReportSummary +from inse.models.projects_eu_cordis.fp7.fp7_topic import Fp7Topic +from inse.models.projects_eu_cordis.fp7.fp7_web_link import Fp7WebLink +from inse.models.projects_eu_cordis.fp7.fp7_eurosci_voc import Fp7EurosciVoc +from inse.models.projects_eu_cordis.fp7.fp7_legal_basis import Fp7LegalBasis +from inse.models.projects_eu_cordis.fp7.fp7_project_details import Fp7ProjectDetails + +# Import H2020 models +from inse.models.projects_eu_cordis.horizon2020.h2020_project import H2020Project +from inse.models.projects_eu_cordis.horizon2020.h2020_organization import H2020Organization +from inse.models.projects_eu_cordis.horizon2020.h2020_publication import H2020Publication +from inse.models.projects_eu_cordis.horizon2020.h2020_deliverable import H2020Deliverable +from inse.models.projects_eu_cordis.horizon2020.h2020_report_summary import H2020ReportSummary +from inse.models.projects_eu_cordis.horizon2020.h2020_topic import H2020Topic +from inse.models.projects_eu_cordis.horizon2020.h2020_web_link import H2020WebLink +from inse.models.projects_eu_cordis.horizon2020.h2020_eurosci_voc import H2020EurosciVoc +from inse.models.projects_eu_cordis.horizon2020.h2020_legal_basis import H2020LegalBasis +from inse.models.projects_eu_cordis.horizon2020.h2020_erc_pi import H2020ErcPI +from inse.models.projects_eu_cordis.horizon2020.h2020_project_details import H2020ProjectDetails + +# Import Horizon Europe models +from inse.models.projects_eu_cordis.horizon_europe.heu_project import HEUProject +from inse.models.projects_eu_cordis.horizon_europe.heu_organization import HEUOrganization +from inse.models.projects_eu_cordis.horizon_europe.heu_publication import HEUPublication +from inse.models.projects_eu_cordis.horizon_europe.heu_deliverable import HEUDeliverable +from inse.models.projects_eu_cordis.horizon_europe.heu_report_summary import HEUReportSummary +from inse.models.projects_eu_cordis.horizon_europe.heu_topic import HEUTopic +from inse.models.projects_eu_cordis.horizon_europe.heu_web_link import HEUWebLink +from inse.models.projects_eu_cordis.horizon_europe.heu_eurosci_voc import HEUEurosciVoc +from inse.models.projects_eu_cordis.horizon_europe.heu_legal_basis import HEULegalBasis +from inse.models.projects_eu_cordis.horizon_europe.heu_project_details import HEUProjectDetails + +settings = get_settings() +logger = logging.getLogger(__name__) +logger.setLevel(settings.logging_level) + +# Entity config +_FP7_ENTITY_CONFIGS = [ + {"key": "organizations", "index_pattern": ESIndex.CORDIS_EU_FP7_ORGANIZATIONS, "model_class": Fp7Organization}, + {"key": "publications", "index_pattern": ESIndex.CORDIS_EU_FP7_PUBLICATIONS, "model_class": Fp7Publication}, + {"key": "iprs", "index_pattern": ESIndex.CORDIS_EU_FP7_PROJECT_IPRS, "model_class": Fp7ProjectIPR}, + {"key": "report_summaries", "index_pattern": ESIndex.CORDIS_EU_FP7_REPORT_SUMMARIES, "model_class": Fp7ReportSummary}, + {"key": "topics_list", "index_pattern": ESIndex.CORDIS_EU_FP7_TOPICS, "model_class": Fp7Topic}, + {"key": "web_links", "index_pattern": ESIndex.CORDIS_EU_FP7_WEB_LINKS, "model_class": Fp7WebLink}, + {"key": "eurosci_voc", "index_pattern": ESIndex.CORDIS_EU_FP7_EUROSCIVOC, "model_class": Fp7EurosciVoc}, + {"key": "legal_basis_list", "index_pattern": ESIndex.CORDIS_EU_FP7_LEGAL_BASIS, "model_class": Fp7LegalBasis}, +] + +_H2020_ENTITY_CONFIGS = [ + {"key": "organizations", "index_pattern": ESIndex.CORDIS_EU_HORIZON_2020_ORGANIZATIONS, "model_class": H2020Organization}, + {"key": "publications", "index_pattern": ESIndex.CORDIS_EU_HORIZON_2020_PUBLICATIONS, "model_class": H2020Publication}, + {"key": "deliverables", "index_pattern": ESIndex.CORDIS_EU_HORIZON_2020_DELIVERABLES, "model_class": H2020Deliverable}, + {"key": "report_summaries", "index_pattern": ESIndex.CORDIS_EU_HORIZON_2020_REPORT_SUMMARIES, "model_class": H2020ReportSummary}, + {"key": "topics_list", "index_pattern": ESIndex.CORDIS_EU_HORIZON_2020_TOPICS, "model_class": H2020Topic}, + {"key": "web_links", "index_pattern": ESIndex.CORDIS_EU_HORIZON_2020_WEB_LINKS, "model_class": H2020WebLink}, + {"key": "eurosci_voc", "index_pattern": ESIndex.CORDIS_EU_HORIZON_2020_EUROSCIVOC, "model_class": H2020EurosciVoc}, + {"key": "legal_basis_list", "index_pattern": ESIndex.CORDIS_EU_HORIZON_2020_LEGAL_BASIS, "model_class": H2020LegalBasis}, + {"key": "erc_principal_investigators", "index_pattern": ESIndex.CORDIS_EU_HORIZON_2020_ERC_PIS, "model_class": H2020ErcPI}, +] + +_HEU_ENTITY_CONFIGS = [ + {"key": "organizations", "index_pattern": ESIndex.CORDIS_EU_HORIZON_EUROPE_ORGANIZATIONS, "model_class": HEUOrganization}, + {"key": "publications", "index_pattern": ESIndex.CORDIS_EU_HORIZON_EUROPE_PUBLICATIONS, "model_class": HEUPublication}, + {"key": "deliverables", "index_pattern": ESIndex.CORDIS_EU_HORIZON_EUROPE_DELIVERABLES, "model_class": HEUDeliverable}, + {"key": "report_summaries", "index_pattern": ESIndex.CORDIS_EU_HORIZON_EUROPE_REPORT_SUMMARIES, "model_class": HEUReportSummary}, + {"key": "topics_list", "index_pattern": ESIndex.CORDIS_EU_HORIZON_EUROPE_TOPICS, "model_class": HEUTopic}, + {"key": "web_links", "index_pattern": ESIndex.CORDIS_EU_HORIZON_EUROPE_WEB_LINKS, "model_class": HEUWebLink}, + {"key": "eurosci_voc", "index_pattern": ESIndex.CORDIS_EU_HORIZON_EUROPE_EUROSCIVOC, "model_class": HEUEurosciVoc}, + {"key": "legal_basis_list", "index_pattern": ESIndex.CORDIS_EU_HORIZON_EUROPE_LEGAL_BASIS, "model_class": HEULegalBasis}, +] + +async def get_enriched_cordis_project_by_id( + project_id: str, +) -> Optional[Union[Fp7ProjectDetails, H2020ProjectDetails, HEUProjectDetails]]: + """ + Fetches and enriches a single Cordis EU project by its ID across all programme types. + + Args: + project_id: The project ID to fetch. + + Returns: + The enriched detailed project model, or None if not found. + """ + if not project_id: + return None + + query = {"bool": {"filter": [{"term": {"id": project_id}}]}} + + response = await elasticsearch.search( + query=query, + index=ESIndex.CORDIS_EU_PROJECTS_WILDCARD, + cluster=ESCluster.INSE, + size=1, + ) + + hits = response.get("hits", {}).get("hits", []) + if not hits: + logger.info(f"No project found with ID: {project_id}") + return None + + hit = hits[0] + index = hit.get("_index", "") + source = hit.get("_source", {}) + + program_type = _determine_program_type_from_index(index) + + enrichers = { + "fp7": _enrich_fp7_project, + "h2020": _enrich_h2020_project, + "heu": _enrich_heu_project, + } + + enricher = enrichers.get(program_type) + if enricher is None: + logger.warning(f"Unknown programme type for index: {index}") + return CordisEuProject.model_validate(source) + + return await enricher(project_id, source) + +# helpers +def _determine_program_type_from_index(index: str) -> str: + """Determines the programme type from the Elasticsearch index name.""" + index_lower = index.lower() + if "fp7" in index_lower: + return "fp7" + if "horizon_2020" in index_lower: + return "h2020" + if "heu" in index_lower or "horizon_europe" in index_lower: + return "heu" + return "unknown" + + +async def _fetch_related_entities_parallel( + project_id: str, + entity_configs: List[Dict[str, Any]], +) -> Dict[str, List[Any]]: + """ + Fetches all related entity types for a project in parallel. + + Args: + project_id: The project ID to fetch entities for. + entity_configs: List of dicts with keys 'key', 'index_pattern', 'model_class'. + + Returns: + Dictionary mapping each config 'key' to a list of validated entities. + """ + async def _fetch_one(config: Dict[str, Any]): + entities = await _fetch_related_entities( + project_ids=[project_id], + index_pattern=config["index_pattern"], + model_class=config["model_class"], + ) + return config["key"], entities.get(project_id, []) + + tasks = [_fetch_one(cfg) for cfg in entity_configs] + completed = await asyncio.gather(*tasks, return_exceptions=True) + + results: Dict[str, List[Any]] = {} + for cfg, res in zip(entity_configs, completed): + key = cfg["key"] + if isinstance(res, Exception): + logger.error(f"Parallel fetch failed for '{key}': {res}") + results[key] = [] + else: + key_name, data = res + results[key_name] = data + + return results + + +async def _fetch_related_entities( + project_ids: List[str], + index_pattern: str, + model_class: Any, +) -> Dict[str, List[Any]]: + """ + Fetches and groups related entities from Elasticsearch by project ID. + + Args: + project_ids: List of project IDs to fetch entities for. + index_pattern: The index pattern to search (supports wildcards). + model_class: The Pydantic model class to validate against. + + Returns: + Dictionary mapping project IDs to lists of validated entities. + """ + query = {"bool": {"filter": [{"terms": {"projectID": project_ids}}]}} + + try: + response = await elasticsearch.search( + query=query, + index=index_pattern, + cluster=ESCluster.INSE, + size=10000, + ) + except Exception as e: + logger.warning(f"Failed to fetch from {index_pattern}: {e}") + return {} + + grouped: Dict[str, List[Any]] = {} + + for hit in response.get("hits", {}).get("hits", []): + source = hit.get("_source", {}) + project_id = source.get("projectID") + + if not project_id: + continue + + grouped.setdefault(project_id, []) + + try: + entity = model_class.model_validate(source) + grouped[project_id].append(entity) + except Exception as e: + logger.warning(f"Failed to validate {model_class.__name__} for project {project_id}: {e}") + + return grouped + + +async def _enrich_fp7_project( + project_id: str, + project_source: Dict[str, Any], +) -> Optional[Fp7ProjectDetails]: + """Enriches a single FP7 project with all related data.""" + try: + project = Fp7Project.model_validate(project_source) + except Exception as e: + logger.error(f"Failed to validate FP7 project {project_id}: {e}") + return None + + related = await _fetch_related_entities_parallel(project_id, _FP7_ENTITY_CONFIGS) + + return Fp7ProjectDetails.from_project_with_relations(project=project, **related) + + +async def _enrich_h2020_project( + project_id: str, + project_source: Dict[str, Any], +) -> Optional[H2020ProjectDetails]: + """Enriches a single H2020 project with all related data.""" + try: + project = H2020Project.model_validate(project_source) + except Exception as e: + logger.error(f"Failed to validate H2020 project {project_id}: {e}") + return None + + related = await _fetch_related_entities_parallel(project_id, _H2020_ENTITY_CONFIGS) + + return H2020ProjectDetails.from_project_with_relations(project=project, **related) + + +async def _enrich_heu_project( + project_id: str, + project_source: Dict[str, Any], +) -> Optional[HEUProjectDetails]: + """Enriches a single Horizon Europe project with all related data.""" + try: + project = HEUProject.model_validate(project_source) + except Exception as e: + logger.error(f"Failed to validate Horizon Europe project {project_id}: {e}") + return None + + related = await _fetch_related_entities_parallel(project_id, _HEU_ENTITY_CONFIGS) + + return HEUProjectDetails.from_project_with_relations(project=project, **related) + + + + +from inse.projects.model import ( + EuCordisProjectType, + EuCordisProjectSearchPage, + EuCordisProjectSummary, + EuCordisOrganizationSummary, + EuCordisTopicSummary, + EuCordisEurosciVocSummary, +) +from inse.projects.logic import ( + get_eu_project_ids_by_openalex_topic_ids, + get_openalex_topics_for_eu_projects, +) + +def _eu_project_type_index_filter( + project_ids_by_type: Dict[EuCordisProjectType, List[str]], +) -> Optional[Dict[str, Any]]: + should_clauses = [] + + for project_type, project_ids in project_ids_by_type.items(): + if not project_ids: + continue + + should_clauses.append( + { + "bool": { + "filter": [ + {"term": {"_index": project_type.to_project_index().value}}, + {"terms": {"id": project_ids}}, + ] + } + } + ) + + if not should_clauses: + return None + + return { + "bool": { + "should": should_clauses, + "minimum_should_match": 1, + } + } + + +def _eu_year_filters(field: str, years: List[str]) -> Dict[str, Any]: + should = [] + + for year in years: + year = str(year).strip() + if not year: + continue + + should.append( + { + "range": { + field: { + "gte": f"{year}-01-01", + "lte": f"{year}-12-31", + } + } + } + ) + + return { + "bool": { + "should": should, + "minimum_should_match": 1, + } + } + + +def _eu_sort_field(sort_by: str) -> str: + mapping = { + "title": "title.keyword", + "funding_start": "startDate", + "funding_end": "endDate", + "funding_amount": "ecMaxContribution", + "id": "id", + "project_type": "_index", + } + return mapping.get(sort_by, "title.keyword") + + +async def get_eu_project_ids_by_organization_filters( + project_types: List[EuCordisProjectType], + organization_ids: Optional[List[str]] = None, + organization_names: Optional[List[str]] = None, +) -> Dict[EuCordisProjectType, List[str]]: + """ + Returns project IDs matching ALL selected organizations. + If organization_ids=[A,B], a project must have both A and B. + Same semantics requested as DFG topic filters. + """ + organization_ids = [x for x in (organization_ids or []) if str(x).strip()] + organization_names = [x for x in (organization_names or []) if str(x).strip()] + + if not organization_ids and not organization_names: + return {} + + result: Dict[EuCordisProjectType, List[str]] = {} + + for project_type in project_types: + project_org_matches: Dict[str, Set[str]] = defaultdict(set) + + should = [] + + if organization_ids: + should.append({"terms": {"organisationID": organization_ids}}) + + for name in organization_names: + should.append( + { + "match": { + "name": { + "query": name, + "operator": "and", + } + } + } + ) + + response = await elasticsearch.search( + index=project_type.to_organization_index(), + cluster=ESCluster.INSE, + body={ + "size": 10000, + "_source": ["projectID", "organisationID", "name"], + "query": { + "bool": { + "should": should, + "minimum_should_match": 1, + } + }, + }, + ) + + hits = response.get("hits", {}).get("hits", []) + + for hit in hits: + source = hit.get("_source", {}) + project_id = source.get("projectID") + if not project_id: + continue + + organisation_id = source.get("organisationID") + name = source.get("name") + + if organisation_id in organization_ids: + project_org_matches[project_id].add(f"id:{organisation_id}") + + for org_name in organization_names: + if name and org_name.lower() in name.lower(): + project_org_matches[project_id].add(f"name:{org_name.lower()}") + + required = {f"id:{x}" for x in organization_ids} + required.update({f"name:{x.lower()}" for x in organization_names}) + + result[project_type] = [ + project_id + for project_id, found in project_org_matches.items() + if required.issubset(found) + ] + + return result + +async def get_eu_organizations_for_projects( + project_ids_by_type: Dict[EuCordisProjectType, List[str]], +) -> Dict[Tuple[EuCordisProjectType, str], List[EuCordisOrganizationSummary]]: + lookup: Dict[Tuple[EuCordisProjectType, str], List[EuCordisOrganizationSummary]] = {} + + for project_type, project_ids in project_ids_by_type.items(): + if not project_ids: + continue + + response = await elasticsearch.search( + index=project_type.to_organization_index(), + cluster=ESCluster.INSE, + body={ + "size": 10000, + "_source": [ + "id", + "organisationID", + "name", + "shortName", + "country", + "city", + "role", + "activityType", + "projectID", + "ecContribution", + "totalCost", + ], + "query": { + "terms": { + "projectID": project_ids + } + }, + "sort": [ + {"order": {"order": "asc", "unmapped_type": "integer"}} + ], + }, + ) + + for hit in response.get("hits", {}).get("hits", []): + source = hit.get("_source", {}) + project_id = source.get("projectID") + if not project_id: + continue + + lookup.setdefault((project_type, project_id), []).append( + EuCordisOrganizationSummary.from_es_source(source) + ) + + return lookup + + +async def get_eu_cordis_topics_for_projects( + project_ids_by_type: Dict[EuCordisProjectType, List[str]], +) -> Dict[Tuple[EuCordisProjectType, str], List[EuCordisTopicSummary]]: + lookup: Dict[Tuple[EuCordisProjectType, str], List[EuCordisTopicSummary]] = {} + + for project_type, project_ids in project_ids_by_type.items(): + if not project_ids: + continue + + response = await elasticsearch.search( + index=project_type.to_cordis_topic_index(), + cluster=ESCluster.INSE, + body={ + "size": 10000, + "_source": ["id", "projectID", "title", "topic"], + "query": { + "terms": { + "projectID": project_ids + } + }, + }, + ) + + for hit in response.get("hits", {}).get("hits", []): + source = hit.get("_source", {}) + project_id = source.get("projectID") + if not project_id: + continue + + lookup.setdefault((project_type, project_id), []).append( + EuCordisTopicSummary.from_es_source(source) + ) + + return lookup + + +async def get_eu_euroscivoc_for_projects( + project_ids_by_type: Dict[EuCordisProjectType, List[str]], +) -> Dict[Tuple[EuCordisProjectType, str], List[EuCordisEurosciVocSummary]]: + lookup: Dict[Tuple[EuCordisProjectType, str], List[EuCordisEurosciVocSummary]] = {} + + for project_type, project_ids in project_ids_by_type.items(): + if not project_ids: + continue + + response = await elasticsearch.search( + index=project_type.to_euroscivoc_index(), + cluster=ESCluster.INSE, + body={ + "size": 10000, + "_source": ["id", "projectID", "code", "title", "description", "path"], + "query": { + "terms": { + "projectID": project_ids + } + }, + }, + ) + + for hit in response.get("hits", {}).get("hits", []): + source = hit.get("_source", {}) + project_id = source.get("projectID") + if not project_id: + continue + + lookup.setdefault((project_type, project_id), []).append( + EuCordisEurosciVocSummary.from_es_source(source) + ) + + return lookup + + +async def search_eu_cordis_projects( + page: int, + size: int, + project_types: Optional[List[EuCordisProjectType]] = None, + organization_ids: Optional[List[str]] = None, + organization_names: Optional[List[str]] = None, + author_project_ids: Optional[List[str]] = None, + keywords: Optional[List[str]] = None, + topic_ids: Optional[List[str]] = None, + filter_topic_ids: Optional[List[str]] = None, + title: Optional[str] = None, + funding_start_years: Optional[List[str]] = None, + funding_end_years: Optional[List[str]] = None, + countries: Optional[List[str]] = None, + framework_programmes: Optional[List[str]] = None, + funding_schemes: Optional[List[str]] = None, + statuses: Optional[List[str]] = None, + sort_by: str = "title", + sort_direction: str = "asc", + fuzzy: bool = False, +) -> EuCordisProjectSearchPage: + """ + Generic EU CORDIS project search across FP7, H2020 and Horizon Europe. + Mirrors DFG behavior: + - fuzzy=True + topic_ids => OpenAlex topic mapping lookup + - filter_topic_ids are always applied independently + - selected organizations/topics must ALL match + """ + if not project_types: + project_types = [ + EuCordisProjectType.FP7, + EuCordisProjectType.H2020, + EuCordisProjectType.HEU, + ] + + indices = [project_type.to_project_index() for project_type in project_types] + + must_clauses: List[Dict[str, Any]] = [] + + # === Author filter resolved in service layer === + if author_project_ids is not None: + if not author_project_ids: + return EuCordisProjectSearchPage(elements=[], total=0, page=page, size=size) + + must_clauses.append({"terms": {"id": author_project_ids}}) + + # === Primary search: fuzzy OpenAlex topics or raw keywords === + if fuzzy and topic_ids: + topic_project_ids_by_type = await get_eu_project_ids_by_openalex_topic_ids( + project_types=project_types, + topic_ids=topic_ids, + ) + + topic_filter = _eu_project_type_index_filter(topic_project_ids_by_type) + if not topic_filter: + return EuCordisProjectSearchPage(elements=[], total=0, page=page, size=size) + + must_clauses.append(topic_filter) + + elif keywords: + keyword_clauses = [] + + for keyword in keywords: + keyword = keyword.strip() + if not keyword: + continue + + keyword_clauses.append( + { + "bool": { + "should": [ + { + "multi_match": { + "query": keyword, + "fields": [ + "title^4", + "acronym^3", + "objective^2", + "keywords^2", + ], + "type": "phrase_prefix", + "max_expansions": 100, + } + }, + { + "wildcard": { + "topics": { + "value": f"*{keyword}*", + "case_insensitive": True, + } + } + }, + ], + "minimum_should_match": 1, + } + } + ) + + if keyword_clauses: + must_clauses.append({"bool": {"must": keyword_clauses}}) + + # === Independent OpenAlex topic filters === + if filter_topic_ids: + filter_topic_project_ids_by_type = await get_eu_project_ids_by_openalex_topic_ids( + project_types=project_types, + topic_ids=filter_topic_ids, + ) + + topic_filter = _eu_project_type_index_filter(filter_topic_project_ids_by_type) + if not topic_filter: + return EuCordisProjectSearchPage(elements=[], total=0, page=page, size=size) + + must_clauses.append(topic_filter) + + # === Organization filters: all selected organizations must match === + if organization_ids or organization_names: + org_project_ids_by_type = await get_eu_project_ids_by_organization_filters( + project_types=project_types, + organization_ids=organization_ids, + organization_names=organization_names, + ) + + org_filter = _eu_project_type_index_filter(org_project_ids_by_type) + if not org_filter: + return EuCordisProjectSearchPage(elements=[], total=0, page=page, size=size) + + must_clauses.append(org_filter) + + # === Title === + if title: + must_clauses.append( + { + "multi_match": { + "query": title, + "fields": ["title^4", "acronym^2"], + "type": "phrase_prefix", + "max_expansions": 100, + } + } + ) + + # === Funding dates === + if funding_start_years: + must_clauses.append(_eu_year_filters("startDate", funding_start_years)) + + if funding_end_years: + must_clauses.append(_eu_year_filters("endDate", funding_end_years)) + + # === Project core filters === + if framework_programmes: + must_clauses.append({"terms": {"frameworkProgramme": framework_programmes}}) + + if funding_schemes: + must_clauses.append({"terms": {"fundingScheme": funding_schemes}}) + + if statuses: + must_clauses.append({"terms": {"status": statuses}}) + + # === Country filter requires organization lookup === + if countries: + country_project_ids_by_type: Dict[EuCordisProjectType, List[str]] = {} + + for project_type in project_types: + response = await elasticsearch.search( + index=project_type.to_organization_index(), + cluster=ESCluster.INSE, + body={ + "size": 10000, + "_source": ["projectID"], + "query": { + "terms": { + "country": countries + } + }, + }, + ) + + country_project_ids_by_type[project_type] = list( + { + hit.get("_source", {}).get("projectID") + for hit in response.get("hits", {}).get("hits", []) + if hit.get("_source", {}).get("projectID") + } + ) + + country_filter = _eu_project_type_index_filter(country_project_ids_by_type) + if not country_filter: + return EuCordisProjectSearchPage(elements=[], total=0, page=page, size=size) + + must_clauses.append(country_filter) + + query = {"bool": {"must": must_clauses}} if must_clauses else {"match_all": {}} + + sort_direction = sort_direction.lower() + if sort_direction not in ["asc", "desc"]: + sort_direction = "asc" + + sort_field = _eu_sort_field(sort_by.strip().lower()) + response = await elasticsearch.search( + index=indices, + cluster=ESCluster.INSE, + body={ + "size": size, + "from": page * size, + "track_total_hits": True, + "_source": [ + "id", + "title", + "acronym", + "objective", + "keywords", + "frameworkProgramme", + "fundingScheme", + "status", + "startDate", + "endDate", + "ecMaxContribution", + "totalCost", + ], + "query": query, + "sort": [ + { + sort_field: { + "order": sort_direction, + "missing": "_last", + "unmapped_type": "keyword" if sort_field.endswith(".keyword") else "date", + } + } + ], + }, + ) + + hits = response.get("hits", {}).get("hits", []) + total = response.get("hits", {}).get("total", {}).get("value", 0) + + project_ids_by_type: Dict[EuCordisProjectType, List[str]] = defaultdict(list) + + for hit in hits: + project_type = EuCordisProjectType.from_index_name(hit.get("_index", "")) + project_id = hit.get("_source", {}).get("id") + if project_id: + project_ids_by_type[project_type].append(project_id) + authors_lookup = await get_openalex_authors_for_projects_ids(project_ids_by_type) + organizations_lookup = await get_eu_organizations_for_projects(project_ids_by_type) + cordis_topics_lookup = await get_eu_cordis_topics_for_projects(project_ids_by_type) + euroscivoc_lookup = await get_eu_euroscivoc_for_projects(project_ids_by_type) + openalex_topics_lookup = await get_openalex_topics_for_eu_projects(project_ids_by_type) + + elements: List[EuCordisProjectSummary] = [] + + for hit in hits: + source = hit.get("_source", {}) + project_type = EuCordisProjectType.from_index_name(hit.get("_index", "")) + project_id = source.get("id") + + raw_topic_matches = openalex_topics_lookup.get((project_type, project_id), []) + raw_topic_matches = sorted( + raw_topic_matches, + key=lambda t: t.get("rank") if t.get("rank") is not None else float("inf"), + ) + + topics = [ + EuCordisProjectSummary.topic_from_match(match) + for match in raw_topic_matches + if isinstance(match, dict) + ] + elements.append( + EuCordisProjectSummary.from_hit( + hit=hit, + authors=authors_lookup.get((project_type, project_id), AuthorPage(elements=[], total=0, page=0, size=0)), + organizations=organizations_lookup.get((project_type, project_id), []), + cordis_topics=cordis_topics_lookup.get((project_type, project_id), []), + eurosci_voc=euroscivoc_lookup.get((project_type, project_id), []), + topics=topics, + ) + ) + return EuCordisProjectSearchPage( + elements=elements, + total=total, + page=page, + size=size, + ) + +def _to_openalex_doi_url(raw_doi: str) -> str: + """CORDIS stores bare DOIs (e.g. '10.1093/toxsci/kfs018'); + OpenAlex works index stores full URLs ('https://doi.org/10.1093/toxsci/kfs018').""" + raw_doi = raw_doi.strip() + if raw_doi.startswith("http://") or raw_doi.startswith("https://"): + return raw_doi + return f"https://doi.org/{raw_doi}" + +async def get_dois_by_cordis_eu_project_id(project_id: str) -> List[str]: + """Retrieves the raw DOIs of publications associated with a given CORDIS EU project ID.""" + query = {"bool": {"filter": [{"term": {"projectID": project_id}}]}} + + response = await elasticsearch.search( + query=query, + index=ESIndex.CORDIS_EU_PUBLICATIONS_WILDCARD, + cluster=ESCluster.INSE, + source=["doi","qaProcessedDoi"], + size=10000, + ) + + dois = [] + for hit in response.get("hits", {}).get("hits", []): + doi = hit.get("_source", {}).get("doi") + qa_processed_doi = hit.get("_source", {}).get("qaProcessedDoi") + if doi: + dois.append(doi) + if qa_processed_doi: + dois.append(qa_processed_doi) + return list(set(dois)) # Remove duplicates + +async def get_openalex_author_ids_by_dois( + dois: List[str], +) -> Dict[str, List[str]]: + """Retrieves the OpenAlex author IDs (full URL form) authoring works for each + given (raw, non-prefixed) DOI. Returns a mapping of the *original raw DOI* + (as passed in) -> list of author_ids, so callers can trace authors back to + whatever the DOI was associated with (e.g. a project).""" + if not dois: + return {} + + url_to_raw = { + _to_openalex_doi_url(doi.lower()): doi + for doi in dois + } + + doi_urls = list(url_to_raw.keys()) + + query = { + "bool": { + "filter": [ + { + "terms": { + "doi": doi_urls + } + } + ] + } + } + + response = await elasticsearch.search( + index=ESIndex.OPENALEX_WORKS_WILDCARD, + source=["doi", "authorships.author.id"], + query=query, + size=10000, + cluster=ESCluster.NES, + ) + result: Dict[str, List[str]] = {} + for hit in response.get("hits", {}).get("hits", []): + source = hit.get("_source", {}) + doi_url = source.get("doi") + raw_doi = url_to_raw.get(doi_url) + if not raw_doi: + continue + author_ids = [ + authorship.get("author", {}).get("id") + for authorship in source.get("authorships", []) + if authorship.get("author", {}).get("id") + ] + result.setdefault(raw_doi, []).extend(author_ids) + + 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]], +) -> Dict[Tuple[EuCordisProjectType, str], AuthorPage]: + """Adapts get_openalex_authors_for_cordis_project_ids to the + (project_type, project_id)-keyed lookup convention used across this module.""" + all_project_ids = [ + pid for pids in project_ids_by_type.values() for pid in pids + ] + if not all_project_ids: + return {} + + # NOTE: get_openalex_authors_for_cordis_project_ids is keyed purely by project_id, + # not (type, id). This assumes project_id is globally unique across FP7/H2020/HEU. + author_pages_by_project_id = await get_openalex_authors_for_cordis_project_ids( + project_ids=all_project_ids + ) + + result: Dict[Tuple[EuCordisProjectType, str], AuthorPage] = {} + for project_type, project_ids in project_ids_by_type.items(): + for pid in project_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 diff --git a/service/src/main/inse/projects/eu_cordis_projects_enrichment_client.py b/service/src/main/inse/projects/eu_cordis_projects_enrichment_client.py deleted file mode 100644 index cb120418..00000000 --- a/service/src/main/inse/projects/eu_cordis_projects_enrichment_client.py +++ /dev/null @@ -1,281 +0,0 @@ -import logging -import asyncio -from typing import Any, Dict, List, Optional, Union - -from inse.config import get_settings -from inse.integrations import elasticsearch -from inse.model import ESCluster, ESIndex - -# Import base models -from inse.models.cordis_eu_project import CordisEuProject - -# Import FP7 models -from inse.models.projects_eu_cordis.fp7.fp7_project import Fp7Project -from inse.models.projects_eu_cordis.fp7.fp7_organization import Fp7Organization -from inse.models.projects_eu_cordis.fp7.fp7_publication import Fp7Publication -from inse.models.projects_eu_cordis.fp7.fp7_project_ipr import Fp7ProjectIPR -from inse.models.projects_eu_cordis.fp7.fp7_report_summary import Fp7ReportSummary -from inse.models.projects_eu_cordis.fp7.fp7_topic import Fp7Topic -from inse.models.projects_eu_cordis.fp7.fp7_web_link import Fp7WebLink -from inse.models.projects_eu_cordis.fp7.fp7_eurosci_voc import Fp7EurosciVoc -from inse.models.projects_eu_cordis.fp7.fp7_legal_basis import Fp7LegalBasis -from inse.models.projects_eu_cordis.fp7.fp7_project_details import Fp7ProjectDetails - -# Import H2020 models -from inse.models.projects_eu_cordis.horizon2020.h2020_project import H2020Project -from inse.models.projects_eu_cordis.horizon2020.h2020_organization import H2020Organization -from inse.models.projects_eu_cordis.horizon2020.h2020_publication import H2020Publication -from inse.models.projects_eu_cordis.horizon2020.h2020_deliverable import H2020Deliverable -from inse.models.projects_eu_cordis.horizon2020.h2020_report_summary import H2020ReportSummary -from inse.models.projects_eu_cordis.horizon2020.h2020_topic import H2020Topic -from inse.models.projects_eu_cordis.horizon2020.h2020_web_link import H2020WebLink -from inse.models.projects_eu_cordis.horizon2020.h2020_eurosci_voc import H2020EurosciVoc -from inse.models.projects_eu_cordis.horizon2020.h2020_legal_basis import H2020LegalBasis -from inse.models.projects_eu_cordis.horizon2020.h2020_erc_pi import H2020ErcPI -from inse.models.projects_eu_cordis.horizon2020.h2020_project_details import H2020ProjectDetails - -# Import Horizon Europe models -from inse.models.projects_eu_cordis.horizon_europe.heu_project import HEUProject -from inse.models.projects_eu_cordis.horizon_europe.heu_organization import HEUOrganization -from inse.models.projects_eu_cordis.horizon_europe.heu_publication import HEUPublication -from inse.models.projects_eu_cordis.horizon_europe.heu_deliverable import HEUDeliverable -from inse.models.projects_eu_cordis.horizon_europe.heu_report_summary import HEUReportSummary -from inse.models.projects_eu_cordis.horizon_europe.heu_topic import HEUTopic -from inse.models.projects_eu_cordis.horizon_europe.heu_web_link import HEUWebLink -from inse.models.projects_eu_cordis.horizon_europe.heu_eurosci_voc import HEUEurosciVoc -from inse.models.projects_eu_cordis.horizon_europe.heu_legal_basis import HEULegalBasis -from inse.models.projects_eu_cordis.horizon_europe.heu_project_details import HEUProjectDetails - -settings = get_settings() -logger = logging.getLogger(__name__) -logger.setLevel(settings.logging_level) - -# Entity config -_FP7_ENTITY_CONFIGS = [ - {"key": "organizations", "index_pattern": ESIndex.CORDIS_EU_FP7_ORGANIZATIONS, "model_class": Fp7Organization}, - {"key": "publications", "index_pattern": ESIndex.CORDIS_EU_FP7_PUBLICATIONS, "model_class": Fp7Publication}, - {"key": "iprs", "index_pattern": ESIndex.CORDIS_EU_FP7_PROJECT_IPRS, "model_class": Fp7ProjectIPR}, - {"key": "report_summaries", "index_pattern": ESIndex.CORDIS_EU_FP7_REPORT_SUMMARIES, "model_class": Fp7ReportSummary}, - {"key": "topics_list", "index_pattern": ESIndex.CORDIS_EU_FP7_TOPICS, "model_class": Fp7Topic}, - {"key": "web_links", "index_pattern": ESIndex.CORDIS_EU_FP7_WEB_LINKS, "model_class": Fp7WebLink}, - {"key": "eurosci_voc", "index_pattern": ESIndex.CORDIS_EU_FP7_EUROSCIVOC, "model_class": Fp7EurosciVoc}, - {"key": "legal_basis_list", "index_pattern": ESIndex.CORDIS_EU_FP7_LEGAL_BASIS, "model_class": Fp7LegalBasis}, -] - -_H2020_ENTITY_CONFIGS = [ - {"key": "organizations", "index_pattern": ESIndex.CORDIS_EU_HORIZON_2020_ORGANIZATIONS, "model_class": H2020Organization}, - {"key": "publications", "index_pattern": ESIndex.CORDIS_EU_HORIZON_2020_PUBLICATIONS, "model_class": H2020Publication}, - {"key": "deliverables", "index_pattern": ESIndex.CORDIS_EU_HORIZON_2020_DELIVERABLES, "model_class": H2020Deliverable}, - {"key": "report_summaries", "index_pattern": ESIndex.CORDIS_EU_HORIZON_2020_REPORT_SUMMARIES, "model_class": H2020ReportSummary}, - {"key": "topics_list", "index_pattern": ESIndex.CORDIS_EU_HORIZON_2020_TOPICS, "model_class": H2020Topic}, - {"key": "web_links", "index_pattern": ESIndex.CORDIS_EU_HORIZON_2020_WEB_LINKS, "model_class": H2020WebLink}, - {"key": "eurosci_voc", "index_pattern": ESIndex.CORDIS_EU_HORIZON_2020_EUROSCIVOC, "model_class": H2020EurosciVoc}, - {"key": "legal_basis_list", "index_pattern": ESIndex.CORDIS_EU_HORIZON_2020_LEGAL_BASIS, "model_class": H2020LegalBasis}, - {"key": "erc_principal_investigators", "index_pattern": ESIndex.CORDIS_EU_HORIZON_2020_ERC_PIS, "model_class": H2020ErcPI}, -] - -_HEU_ENTITY_CONFIGS = [ - {"key": "organizations", "index_pattern": ESIndex.CORDIS_EU_HORIZON_EUROPE_ORGANIZATIONS, "model_class": HEUOrganization}, - {"key": "publications", "index_pattern": ESIndex.CORDIS_EU_HORIZON_EUROPE_PUBLICATIONS, "model_class": HEUPublication}, - {"key": "deliverables", "index_pattern": ESIndex.CORDIS_EU_HORIZON_EUROPE_DELIVERABLES, "model_class": HEUDeliverable}, - {"key": "report_summaries", "index_pattern": ESIndex.CORDIS_EU_HORIZON_EUROPE_REPORT_SUMMARIES, "model_class": HEUReportSummary}, - {"key": "topics_list", "index_pattern": ESIndex.CORDIS_EU_HORIZON_EUROPE_TOPICS, "model_class": HEUTopic}, - {"key": "web_links", "index_pattern": ESIndex.CORDIS_EU_HORIZON_EUROPE_WEB_LINKS, "model_class": HEUWebLink}, - {"key": "eurosci_voc", "index_pattern": ESIndex.CORDIS_EU_HORIZON_EUROPE_EUROSCIVOC, "model_class": HEUEurosciVoc}, - {"key": "legal_basis_list", "index_pattern": ESIndex.CORDIS_EU_HORIZON_EUROPE_LEGAL_BASIS, "model_class": HEULegalBasis}, -] - -async def get_enriched_cordis_project_by_id( - project_id: str, -) -> Optional[Union[Fp7ProjectDetails, H2020ProjectDetails, HEUProjectDetails]]: - """ - Fetches and enriches a single Cordis EU project by its ID across all programme types. - - Args: - project_id: The project ID to fetch. - - Returns: - The enriched detailed project model, or None if not found. - """ - if not project_id: - return None - - query = {"bool": {"filter": [{"term": {"id": project_id}}]}} - - response = await elasticsearch.search( - query=query, - index=ESIndex.CORDIS_EU_PROJECTS_WILDCARD, - cluster=ESCluster.INSE, - size=1, - ) - - hits = response.get("hits", {}).get("hits", []) - if not hits: - logger.info(f"No project found with ID: {project_id}") - return None - - hit = hits[0] - index = hit.get("_index", "") - source = hit.get("_source", {}) - - program_type = _determine_program_type_from_index(index) - - enrichers = { - "fp7": _enrich_fp7_project, - "h2020": _enrich_h2020_project, - "heu": _enrich_heu_project, - } - - enricher = enrichers.get(program_type) - if enricher is None: - logger.warning(f"Unknown programme type for index: {index}") - return CordisEuProject.model_validate(source) - - return await enricher(project_id, source) - -# helpers -def _determine_program_type_from_index(index: str) -> str: - """Determines the programme type from the Elasticsearch index name.""" - index_lower = index.lower() - if "fp7" in index_lower: - return "fp7" - if "horizon_2020" in index_lower: - return "h2020" - if "heu" in index_lower or "horizon_europe" in index_lower: - return "heu" - return "unknown" - - -async def _fetch_related_entities_parallel( - project_id: str, - entity_configs: List[Dict[str, Any]], -) -> Dict[str, List[Any]]: - """ - Fetches all related entity types for a project in parallel. - - Args: - project_id: The project ID to fetch entities for. - entity_configs: List of dicts with keys 'key', 'index_pattern', 'model_class'. - - Returns: - Dictionary mapping each config 'key' to a list of validated entities. - """ - async def _fetch_one(config: Dict[str, Any]): - entities = await _fetch_related_entities( - project_ids=[project_id], - index_pattern=config["index_pattern"], - model_class=config["model_class"], - ) - return config["key"], entities.get(project_id, []) - - tasks = [_fetch_one(cfg) for cfg in entity_configs] - completed = await asyncio.gather(*tasks, return_exceptions=True) - - results: Dict[str, List[Any]] = {} - for cfg, res in zip(entity_configs, completed): - key = cfg["key"] - if isinstance(res, Exception): - logger.error(f"Parallel fetch failed for '{key}': {res}") - results[key] = [] - else: - key_name, data = res - results[key_name] = data - - return results - - -async def _fetch_related_entities( - project_ids: List[str], - index_pattern: str, - model_class: Any, -) -> Dict[str, List[Any]]: - """ - Fetches and groups related entities from Elasticsearch by project ID. - - Args: - project_ids: List of project IDs to fetch entities for. - index_pattern: The index pattern to search (supports wildcards). - model_class: The Pydantic model class to validate against. - - Returns: - Dictionary mapping project IDs to lists of validated entities. - """ - query = {"bool": {"filter": [{"terms": {"projectID": project_ids}}]}} - - try: - response = await elasticsearch.search( - query=query, - index=index_pattern, - cluster=ESCluster.INSE, - size=10000, - ) - except Exception as e: - logger.warning(f"Failed to fetch from {index_pattern}: {e}") - return {} - - grouped: Dict[str, List[Any]] = {} - - for hit in response.get("hits", {}).get("hits", []): - source = hit.get("_source", {}) - project_id = source.get("projectID") - - if not project_id: - continue - - grouped.setdefault(project_id, []) - - try: - entity = model_class.model_validate(source) - grouped[project_id].append(entity) - except Exception as e: - logger.warning(f"Failed to validate {model_class.__name__} for project {project_id}: {e}") - - return grouped - - -async def _enrich_fp7_project( - project_id: str, - project_source: Dict[str, Any], -) -> Optional[Fp7ProjectDetails]: - """Enriches a single FP7 project with all related data.""" - try: - project = Fp7Project.model_validate(project_source) - except Exception as e: - logger.error(f"Failed to validate FP7 project {project_id}: {e}") - return None - - related = await _fetch_related_entities_parallel(project_id, _FP7_ENTITY_CONFIGS) - - return Fp7ProjectDetails.from_project_with_relations(project=project, **related) - - -async def _enrich_h2020_project( - project_id: str, - project_source: Dict[str, Any], -) -> Optional[H2020ProjectDetails]: - """Enriches a single H2020 project with all related data.""" - try: - project = H2020Project.model_validate(project_source) - except Exception as e: - logger.error(f"Failed to validate H2020 project {project_id}: {e}") - return None - - related = await _fetch_related_entities_parallel(project_id, _H2020_ENTITY_CONFIGS) - - return H2020ProjectDetails.from_project_with_relations(project=project, **related) - - -async def _enrich_heu_project( - project_id: str, - project_source: Dict[str, Any], -) -> Optional[HEUProjectDetails]: - """Enriches a single Horizon Europe project with all related data.""" - try: - project = HEUProject.model_validate(project_source) - except Exception as e: - logger.error(f"Failed to validate Horizon Europe project {project_id}: {e}") - return None - - related = await _fetch_related_entities_parallel(project_id, _HEU_ENTITY_CONFIGS) - - return HEUProjectDetails.from_project_with_relations(project=project, **related) \ No newline at end of file diff --git a/service/src/main/inse/projects/eu_organizations/model.py b/service/src/main/inse/projects/eu_organizations/model.py new file mode 100644 index 00000000..e69de29b diff --git a/service/src/main/inse/projects/eu_organizations/router.py b/service/src/main/inse/projects/eu_organizations/router.py new file mode 100644 index 00000000..263587c4 --- /dev/null +++ b/service/src/main/inse/projects/eu_organizations/router.py @@ -0,0 +1,51 @@ +import logging +from typing import Annotated, List + +from fastapi import APIRouter, Query + +from inse.projects.eu_organizations.service import autocomplete_organizations_for_selector, get_organizations_by_ids + +from inse.projects.model import EuCordisOrganizationSelectorPage +from inse.tags import Tags + +logger = logging.getLogger(__name__) + +EU_ORGANIZATIONS_PREFIX = "/api/eu/organizations" + +router = APIRouter(prefix=EU_ORGANIZATIONS_PREFIX, tags=[Tags.PROJECTS]) + + +@router.get( + "/ids", + operation_id="getEuOrganizationsByIds", + summary="Returns EU CORDIS organizations by organisation IDs.", + response_model=EuCordisOrganizationSelectorPage, +) +async def get_eu_organizations_by_ids( + organization_ids: Annotated[ + List[str], + Query(description="CORDIS organisation IDs to retrieve."), + ] = [], +) -> EuCordisOrganizationSelectorPage: + return await get_organizations_by_ids(organization_ids=organization_ids or []) + + +@router.get( + "/autocomplete/selector", + operation_id="getEuOrganizationAutocompleteForSelector", + summary="Returns EU CORDIS organizations based on a search term.", + response_model=EuCordisOrganizationSelectorPage, +) +async def get_eu_organization_autocomplete( + query: Annotated[ + str, + Query(description="Search term for organization autocomplete."), + ] = "", + page: Annotated[int, Query(ge=0)] = 0, + size: Annotated[int, Query(ge=1)] = 10, +) -> EuCordisOrganizationSelectorPage: + return await autocomplete_organizations_for_selector( + query=query, + page=page, + size=size, + ) \ No newline at end of file diff --git a/service/src/main/inse/projects/eu_organizations/service.py b/service/src/main/inse/projects/eu_organizations/service.py new file mode 100644 index 00000000..376cb592 --- /dev/null +++ b/service/src/main/inse/projects/eu_organizations/service.py @@ -0,0 +1,160 @@ +import logging +from typing import Dict, List, Optional + +from inse.integrations import elasticsearch +from inse.model import ESCluster, ESIndex +from inse.projects.model import ( + EuCordisOrganizationSelectorPage, + EuCordisOrganizationSelectorSummary, + EuCordisProjectType, +) + +logger = logging.getLogger(__name__) + + +def _project_type_from_org_index(index_name: str) -> Optional[EuCordisProjectType]: + if index_name == ESIndex.CORDIS_EU_FP7_ORGANIZATIONS.value: + return EuCordisProjectType.FP7 + if index_name == ESIndex.CORDIS_EU_HORIZON_2020_ORGANIZATIONS.value: + return EuCordisProjectType.H2020 + if index_name == ESIndex.CORDIS_EU_HORIZON_EUROPE_ORGANIZATIONS.value: + return EuCordisProjectType.HEU + return None + + +async def get_organizations_by_ids( + organization_ids: List[str], +) -> EuCordisOrganizationSelectorPage: + if not organization_ids: + return EuCordisOrganizationSelectorPage(elements=[], total=0, page=0, size=0) + + response = await elasticsearch.search( + index=ESIndex.CORDIS_EU_ORGANIZATIONS_WILDCARD, + cluster=ESCluster.INSE, + body={ + "size": len(organization_ids) * 3, + "_source": [ + "id", + "organisationID", + "name", + "shortName", + "country", + "city", + ], + "query": { + "terms": { + "organisationID": organization_ids + } + }, + "collapse": { + "field": "organisationID" + }, + }, + ) + + elements: List[EuCordisOrganizationSelectorSummary] = [] + + for hit in response.get("hits", {}).get("hits", []): + source = hit.get("_source", {}) + source["project_type"] = _project_type_from_org_index(hit.get("_index", "")) + elements.append(EuCordisOrganizationSelectorSummary.from_es_source(source)) + + return EuCordisOrganizationSelectorPage( + elements=elements, + total=response.get("hits", {}).get("total", {}).get("value", len(elements)), + page=0, + size=len(elements), + ) + + +async def autocomplete_organizations_for_selector( + query: str, + page: int = 0, + size: int = 10, +) -> EuCordisOrganizationSelectorPage: + if not query or not query.strip(): + return EuCordisOrganizationSelectorPage( + elements=[], + total=0, + page=page, + size=size, + ) + + query = query.strip() + + response = await elasticsearch.search( + index=ESIndex.CORDIS_EU_ORGANIZATIONS_WILDCARD, + cluster=ESCluster.INSE, + body={ + "size": size, + "from": page * size, + "_source": [ + "id", + "organisationID", + "name", + "shortName", + "country", + "city", + ], + "query": { + "bool": { + "should": [ + { + "match_phrase_prefix": { + "name": { + "query": query, + "max_expansions": 50, + } + } + }, + { + "wildcard": { + "shortName": { + "value": f"*{query}*", + "case_insensitive": True, + } + } + }, + { + "term": { + "organisationID": query, + } + }, + ], + "minimum_should_match": 1, + } + }, + "collapse": { + "field": "organisationID", + }, + "sort": [ + { + "name.keyword": { + "order": "asc", + "missing": "_last", + "unmapped_type": "keyword", + } + } + ], + }, + ) + + elements: List[EuCordisOrganizationSelectorSummary] = [] + + for hit in response.get("hits", {}).get("hits", []): + source = hit.get("_source", {}) + source["project_type"] = _project_type_from_org_index(hit.get("_index", "")) + + elements.append( + EuCordisOrganizationSelectorSummary.from_es_source( + source=source, + project_type=source["project_type"], + ) + ) + + return EuCordisOrganizationSelectorPage( + elements=elements, + total=response.get("hits", {}).get("total", {}).get("value", len(elements)), + page=page, + size=size, + ) \ No newline at end of file diff --git a/service/src/main/inse/projects/logic.py b/service/src/main/inse/projects/logic.py index 2a01e5ca..01b3fa7a 100644 --- a/service/src/main/inse/projects/logic.py +++ b/service/src/main/inse/projects/logic.py @@ -3,11 +3,11 @@ import logging from typing import Any, Dict, List, Optional, Set, Tuple from collections import defaultdict -from inse.projects.eu_cordis_projects_enrichment_client import get_enriched_cordis_project_by_id +from inse.projects.eu_cordis_projects_client import get_enriched_cordis_project_by_id from inse.integrations import elasticsearch from inse.model import ESCluster, ESIndex - +from inse.projects.model import EuCordisProjectType logger = logging.getLogger(__name__) @@ -244,3 +244,133 @@ async def get_person_institutes( "address_country_en": source.get("address_country_en"), } return result + + +#EU Cordis Projects + + + +async def get_eu_project_ids_by_openalex_topic_ids( + project_types: List[EuCordisProjectType], + topic_ids: List[str], +) -> Dict[EuCordisProjectType, List[str]]: + """ + Returns EU CORDIS project IDs whose mapped OpenAlex topic_matches contain + EVERY given topic ID. Same semantics as DFG topic filtering. + """ + if not topic_ids: + return {project_type: [] for project_type in project_types} + + required_topics = set(topic_ids) + result: Dict[EuCordisProjectType, List[str]] = {} + + for project_type in project_types: + project_topics: Dict[str, Set[str]] = defaultdict(set) + + page_size = 1000 + from_ = 0 + + while True: + body = { + "size": page_size, + "from": from_, + "_source": ["project_id", "topic_matches"], + "query": { + "terms": { + "topic_matches.topic_id.keyword": topic_ids + } + }, + } + + response = await elasticsearch.search( + index=project_type.to_openalex_topics_index(), + cluster=ESCluster.INSE, + body=body, + ) + + hits = response.get("hits", {}).get("hits", []) + if not hits: + break + + for hit in hits: + source = hit.get("_source", {}) + project_id = source.get("project_id") + if not project_id: + continue + + topic_matches = source.get("topic_matches") or [] + if isinstance(topic_matches, dict): + topic_matches = [topic_matches] + + for match in topic_matches: + topic_id = match.get("topic_id") + if topic_id in required_topics: + project_topics[project_id].add(topic_id) + + if len(hits) < page_size: + break + + from_ += page_size + + result[project_type] = [ + project_id + for project_id, found_topics in project_topics.items() + if required_topics.issubset(found_topics) + ] + + return result + + +async def get_openalex_topics_for_eu_projects( + project_ids_by_type: Dict[EuCordisProjectType, List[str]], +) -> Dict[Tuple[EuCordisProjectType, str], List[Dict[str, Any]]]: + """ + Fetches mapped OpenAlex topic matches for EU CORDIS projects. + """ + topic_lookup: Dict[Tuple[EuCordisProjectType, str], List[Dict[str, Any]]] = {} + + for project_type, project_ids in project_ids_by_type.items(): + if not project_ids: + continue + + page_size = 1000 + from_ = 0 + + while True: + response = await elasticsearch.search( + index=project_type.to_openalex_topics_index(), + cluster=ESCluster.INSE, + body={ + "size": page_size, + "from": from_, + "_source": ["project_id", "topic_matches"], + "query": { + "terms": { + "project_id.keyword": project_ids + } + }, + }, + ) + + hits = response.get("hits", {}).get("hits", []) + if not hits: + break + + for hit in hits: + source = hit.get("_source", {}) + project_id = source.get("project_id") + if not project_id: + continue + + topic_matches = source.get("topic_matches") or [] + if isinstance(topic_matches, dict): + topic_matches = [topic_matches] + + topic_lookup.setdefault((project_type, project_id), []).extend(topic_matches) + + if len(hits) < page_size: + break + + from_ += page_size + + return topic_lookup \ No newline at end of file diff --git a/service/src/main/inse/projects/model.py b/service/src/main/inse/projects/model.py index 8284b33a..558cdadb 100644 --- a/service/src/main/inse/projects/model.py +++ b/service/src/main/inse/projects/model.py @@ -14,6 +14,7 @@ from inse.models.projects_eu_cordis.horizon_europe.heu_project_details import HE from inse.models.projects_eu_cordis.fp7.fp7_project_details import Fp7ProjectDetails from inse.models.projects_dfg_v2.project.dfg_project_fachgebiete_inner import DFGProjectFachgebieteInner from inse.models.openalex.topic import Topic, TopicDomain, TopicField, TopicSubfield +from inse.authors.v2.model import AuthorPage from typing import Union class ProjectType(StrEnum): @@ -81,11 +82,6 @@ class BundProjectList(BaseModel): ) total: int = Field(default=0, description="The total number of bund projects.") - -class EuProjectPage(Page): - elements: List[EuProject] = Field( - default_factory=list, description="The EU projects on this page." - ) class DfgInstitutionSummary(BaseModel): """A summary of a DFG institution.""" @@ -443,6 +439,12 @@ class FundingProjectPage(Page): ) +#EU CORDIS PROJECTS +class EuProjectPage(Page): + elements: List[EuProject] = Field( + default_factory=list, description="The EU projects on this page." + ) + class EuOrganizationShort(BaseModel): project_id: str = Field(description="The unique identifier of the project.") organization_id: str = Field( @@ -496,3 +498,258 @@ class EuOrganizationProjectSummaryPage(Page): default_factory=list, description="The organization project summaries on this page.", ) + + + +################ +class EuCordisProjectType(StrEnum): + FP7 = "fp7" + H2020 = "h2020" + HEU = "heu" + + def to_project_index(self) -> ESIndex: + mapping = { + self.FP7: ESIndex.CORDIS_EU_FP7_PROJECTS, + self.H2020: ESIndex.CORDIS_EU_HORIZON_2020_PROJECTS, + self.HEU: ESIndex.CORDIS_EU_HORIZON_EUROPE_PROJECTS, + } + return mapping[self] + + def to_organization_index(self) -> ESIndex: + mapping = { + self.FP7: ESIndex.CORDIS_EU_FP7_ORGANIZATIONS, + self.H2020: ESIndex.CORDIS_EU_HORIZON_2020_ORGANIZATIONS, + self.HEU: ESIndex.CORDIS_EU_HORIZON_EUROPE_ORGANIZATIONS, + } + return mapping[self] + + def to_cordis_topic_index(self) -> ESIndex: + mapping = { + self.FP7: ESIndex.CORDIS_EU_FP7_TOPICS, + self.H2020: ESIndex.CORDIS_EU_HORIZON_2020_TOPICS, + self.HEU: ESIndex.CORDIS_EU_HORIZON_EUROPE_TOPICS, + } + return mapping[self] + def to_cordis_publications_index(self) -> ESIndex: + mapping = { + self.FP7: ESIndex.CORDIS_EU_FP7_PUBLICATIONS, + self.H2020: ESIndex.CORDIS_EU_HORIZON_2020_PUBLICATIONS, + self.HEU: ESIndex.CORDIS_EU_HORIZON_EUROPE_PUBLICATIONS, + } + return mapping[self] + + def to_euroscivoc_index(self) -> ESIndex: + mapping = { + self.FP7: ESIndex.CORDIS_EU_FP7_EUROSCIVOC, + self.H2020: ESIndex.CORDIS_EU_HORIZON_2020_EUROSCIVOC, + self.HEU: ESIndex.CORDIS_EU_HORIZON_EUROPE_EUROSCIVOC, + } + return mapping[self] + + def to_openalex_topics_index(self) -> ESIndex: + mapping = { + self.FP7: ESIndex.PROJECTS_CORDIS_EU_FP7_TOPICS_MAPPING, + self.H2020: ESIndex.PROJECTS_CORDIS_EU_H2020_TOPICS, + self.HEU: ESIndex.PROJECTS_CORDIS_EU_HEUROPE_TOPICS, + } + return mapping[self] + + + @classmethod + def from_index_name(cls, index_name: str) -> "EuCordisProjectType": + if index_name == ESIndex.CORDIS_EU_FP7_PROJECTS.value: + return cls.FP7 + if index_name == ESIndex.CORDIS_EU_HORIZON_2020_PROJECTS.value: + return cls.H2020 + if index_name == ESIndex.CORDIS_EU_HORIZON_EUROPE_PROJECTS.value: + return cls.HEU + + raise ValueError(f"Unsupported EU CORDIS project index: {index_name}") + + +class EuCordisOrganizationSummary(BaseModel): + id: Optional[str] = None + organisation_id: Optional[str] = None + name: Optional[str] = None + short_name: Optional[str] = None + country: Optional[str] = None + city: Optional[str] = None + role: Optional[str] = None + activity_type: Optional[str] = None + project_id: Optional[str] = None + ec_contribution: Optional[float] = None + total_cost: Optional[float] = None + + @classmethod + def from_es_source(cls, source: Dict[str, Any]) -> "EuCordisOrganizationSummary": + return cls( + id=source.get("id"), + organisation_id=source.get("organisationID"), + name=source.get("name"), + short_name=source.get("shortName"), + country=source.get("country"), + city=source.get("city"), + role=source.get("role"), + activity_type=source.get("activityType"), + project_id=source.get("projectID"), + ec_contribution=source.get("ecContribution"), + total_cost=source.get("totalCost"), + ) + + + +class EuCordisTopicSummary(BaseModel): + id: Optional[str] = None + project_id: Optional[str] = None + title: Optional[str] = None + topic: Optional[str] = None + + @classmethod + def from_es_source(cls, source: Dict[str, Any]) -> "EuCordisTopicSummary": + return cls( + id=source.get("id"), + project_id=source.get("projectID"), + title=source.get("title"), + topic=source.get("topic"), + ) + + + +class EuCordisEurosciVocSummary(BaseModel): + id: Optional[str] = None + project_id: Optional[str] = None + code: Optional[str] = None + title: Optional[str] = None + description: Optional[str] = None + path: Optional[str] = None + + @classmethod + def from_es_source(cls, source: Dict[str, Any]) -> "EuCordisEurosciVocSummary": + return cls( + id=source.get("id"), + project_id=source.get("projectID"), + code=source.get("code"), + title=source.get("title"), + description=source.get("description"), + path=source.get("path"), + ) + + +class EuCordisProjectSummary(BaseModel): + id: str + project_type: EuCordisProjectType + + title: Optional[str] = None + acronym: Optional[str] = None + objective: Optional[str] = None + keywords: Optional[str] = None + + framework_programme: Optional[str] = None + funding_scheme: Optional[str] = None + status: Optional[str] = None + + start_date: Optional[date] = None + end_date: Optional[date] = None + + ec_max_contribution: Optional[float] = None + total_cost: Optional[float] = None + authors: Optional[AuthorPage] = None + organizations: List[EuCordisOrganizationSummary] = Field(default_factory=list) + cordis_topics: List[EuCordisTopicSummary] = Field(default_factory=list) + eurosci_voc: List[EuCordisEurosciVocSummary] = Field(default_factory=list) + topics: List[Topic] = Field(default_factory=list, description="Mapped OpenAlex topics.") + + @classmethod + def from_hit( + cls, + hit: Dict[str, Any], + authors: Optional[AuthorPage] = None, + organizations: Optional[List[EuCordisOrganizationSummary]] = None, + cordis_topics: Optional[List[EuCordisTopicSummary]] = None, + eurosci_voc: Optional[List[EuCordisEurosciVocSummary]] = None, + topics: Optional[List[Topic]] = None, + ) -> "EuCordisProjectSummary": + source = hit.get("_source", {}) + project_type = EuCordisProjectType.from_index_name(hit.get("_index", "")) + + return cls( + id=source.get("id") or hit.get("_id", ""), + project_type=project_type, + + title=source.get("title"), + acronym=source.get("acronym"), + objective=source.get("objective"), + keywords=source.get("keywords"), + + framework_programme=source.get("frameworkProgramme"), + funding_scheme=source.get("fundingScheme"), + status=source.get("status"), + + start_date=source.get("startDate"), + end_date=source.get("endDate"), + + ec_max_contribution=source.get("ecMaxContribution"), + total_cost=source.get("totalCost"), + + authors=authors or None, + organizations=organizations or [], + cordis_topics=cordis_topics or [], + eurosci_voc=eurosci_voc or [], + topics=topics or [], + ) + + @staticmethod + def topic_from_match(match: Dict[str, Any]) -> Topic: + domain_name = match.get("domain") + field_name = match.get("field") + subfield_name = match.get("subfield") + + domain = TopicDomain(display_name=domain_name) if domain_name else None + field = TopicField(display_name=field_name) if field_name else None + subfield = TopicSubfield(display_name=subfield_name) if subfield_name else None + + return Topic( + id=match.get("topic_id"), + display_name=match.get("topic_display_name"), + domain=domain, + field=field, + subfield=subfield, + ) + + +class EuCordisProjectSearchPage(Page): + elements: List[EuCordisProjectSummary] = Field( + default_factory=list, + description="The EU CORDIS project summaries on this page.", + ) + + +class EuCordisOrganizationSelectorSummary(BaseModel): + id: Optional[str] = None + organisation_id: Optional[str] = None + name: Optional[str] = None + short_name: Optional[str] = None + country: Optional[str] = None + city: Optional[str] = None + project_type: Optional[EuCordisProjectType] = None + + @classmethod + def from_es_source( + cls, + source: Dict[str, Any], + project_type: Optional[EuCordisProjectType] = None, + ) -> "EuCordisOrganizationSelectorSummary": + return cls( + id=source.get("id"), + organisation_id=source.get("organisationID"), + name=source.get("name"), + short_name=source.get("shortName"), + country=source.get("country"), + city=source.get("city"), + project_type=project_type, + ) + + + +class EuCordisOrganizationSelectorPage(Page): + elements: List[EuCordisOrganizationSelectorSummary] = Field(default_factory=list) \ No newline at end of file diff --git a/service/src/main/inse/projects/projects_search_client.py b/service/src/main/inse/projects/projects_search_client.py index 3a0a7557..7404421a 100644 --- a/service/src/main/inse/projects/projects_search_client.py +++ b/service/src/main/inse/projects/projects_search_client.py @@ -21,7 +21,7 @@ from inse.projects.model import ( ProjectsSortBy, SortDirection, ) -from inse.projects.eu_cordis_projects_enrichment_client import get_enriched_cordis_project_by_id +from inse.projects.eu_cordis_projects_client import get_enriched_cordis_project_by_id from inse.models.dfg_project_details import DfgProjectDetails from inse.models.bund_project_details import BundProjectDetails from inse.models.cordis_eu_project import CordisEuProject @@ -505,8 +505,32 @@ async def get_cordis_eu_publications_by_dois(dois: List[str]): Returns: _type_: The retrieved publications. """ - raw_dois = [_get_raw_doi(doi) for doi in dois] - query = {"bool": {"filter": [{"terms": {"qaProcessedDoi": raw_dois}}]}} + + query_dois = list({ + variant + for doi in dois + for variant in ( + _get_raw_doi(doi), + _get_raw_doi(doi).lower(), + _get_raw_doi(doi).upper(), + ) + }) + + query = { + "bool": { + "filter": [ + { + "bool": { + "should": [ + {"terms": {"doi": query_dois}}, + {"terms": {"qaProcessedDoi": query_dois}}, + ], + "minimum_should_match": 1, + } + } + ] + } + } response = await elasticsearch.search( query=query, diff --git a/service/src/main/inse/projects/router.py b/service/src/main/inse/projects/router.py index 699b4d22..8fbc5f70 100644 --- a/service/src/main/inse/projects/router.py +++ b/service/src/main/inse/projects/router.py @@ -134,7 +134,148 @@ async def get_single_bund_project( return await projects_service.get_single_bund_project( project_id=id, ) + + +######## +from inse.projects.model import EuCordisProjectSearchPage, EuCordisProjectType +from inse.projects.service import search_eu_cordis_projects_summary_impl +@router.get( + "/eu/search", + summary="Search EU CORDIS projects.", + description="Returns a page of EU CORDIS project summaries across FP7, Horizon 2020 and Horizon Europe.", + operation_id="searchEuCordisProjectsSummary", + responses={ + status.HTTP_200_OK: { + "description": "Successful Response", + "model": EuCordisProjectSearchPage, + }, + }, + response_model_by_alias=False, +) +async def search_eu_cordis_projects_summary( + author_id: Annotated[ + Optional[str], + Query(description="OpenAlex author ID to filter by."), + ] = None, + author_ids: Annotated[ + Optional[List[str]], + Query(description="Additional OpenAlex author IDs to filter by. All selected authors must match."), + ] = None, + organization_ids: Annotated[ + Optional[List[str]], + Query(description="CORDIS organisation IDs. All selected organizations must match."), + ] = None, + organization_names: Annotated[ + Optional[List[str]], + Query(description="CORDIS organization names. All selected organizations must match."), + ] = None, + project_types: Annotated[ + Optional[List[EuCordisProjectType]], + Query(description="Project types to include: fp7, h2020, heu."), + ] = None, + title: Annotated[ + Optional[str], + Query(description="Project title/acronym search."), + ] = None, + keywords: Annotated[ + Optional[List[str]], + Query(description="Raw keywords to search in title/objective/keywords/topics."), + ] = None, + topic_ids: Annotated[ + Optional[List[str]], + Query(description="OpenAlex topic IDs used for fuzzy topic resolution."), + ] = None, + filter_topic_ids: Annotated[ + Optional[List[str]], + Query(description="Additional OpenAlex topic IDs used as mandatory filters."), + ] = None, + funding_start_years: Annotated[ + Optional[List[str]], + Query(description="Funding start years."), + ] = None, + funding_end_years: Annotated[ + Optional[List[str]], + Query(description="Funding end years."), + ] = None, + countries: Annotated[ + Optional[List[str]], + Query(description="Organization countries."), + ] = None, + framework_programmes: Annotated[ + Optional[List[str]], + Query(description="Framework programme filters."), + ] = None, + funding_schemes: Annotated[ + Optional[List[str]], + Query(description="Funding scheme filters."), + ] = None, + statuses: Annotated[ + Optional[List[str]], + Query(description="Project status filters."), + ] = 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="Sort field.")] = "title", + sort_direction: Annotated[ + str, + Query(description="Sort direction: asc or desc."), + ] = "asc", + fuzzy: Annotated[ + bool, + Query(description="Use OpenAlex topic-id resolution if true, otherwise raw keyword search."), + ] = False, +) -> EuCordisProjectSearchPage: + logger.debug( + "Received EU CORDIS search request: author_id=%s, author_ids=%s, " + "organization_ids=%s, organization_names=%s, project_types=%s, " + "title=%s, keywords=%s, topic_ids=%s, filter_topic_ids=%s, " + "funding_start_years=%s, funding_end_years=%s, countries=%s, " + "framework_programmes=%s, funding_schemes=%s, statuses=%s, " + "page=%s, size=%s, sort_by=%s, sort_direction=%s, fuzzy=%s", + author_id, + author_ids, + organization_ids, + organization_names, + project_types, + title, + keywords, + topic_ids, + filter_topic_ids, + funding_start_years, + funding_end_years, + countries, + framework_programmes, + funding_schemes, + statuses, + page, + size, + sort_by, + sort_direction, + fuzzy, + ) + return await search_eu_cordis_projects_summary_impl( + author_id=author_id, + author_ids=author_ids, + organization_ids=organization_ids, + organization_names=organization_names, + project_types=project_types, + title=title, + keywords=keywords, + topic_ids=topic_ids, + filter_topic_ids=filter_topic_ids, + funding_start_years=funding_start_years, + funding_end_years=funding_end_years, + countries=countries, + framework_programmes=framework_programmes, + funding_schemes=funding_schemes, + statuses=statuses, + page=page, + size=size, + sort_by=sort_by, + sort_direction=sort_direction, + fuzzy=fuzzy, + ) @router.get( "/eu/{id}", @@ -209,7 +350,7 @@ async def get_single_eu_cordis_project( return EuCordisProjectResponse( success=False, project_type=None, - data=None, + eu_project_data=None, error=f"Internal server error: {str(e)}" ) diff --git a/service/src/main/inse/projects/service.py b/service/src/main/inse/projects/service.py index 86637a6f..65a7ded5 100644 --- a/service/src/main/inse/projects/service.py +++ b/service/src/main/inse/projects/service.py @@ -385,7 +385,7 @@ async def get_single_eu_cordis_project( project = await projects_search_client.get_eu_cordis_projects_by_id(project_id) if not project: - raise NotFoundException(f"EU project with id {project_id} not found") + return None return project @@ -414,3 +414,98 @@ async def search_cordis_eu_projects_for_author_id( return funding_project_page + + +################ +from inse.projects.eu_cordis_projects_client import search_eu_cordis_projects +from inse.projects.model import EuCordisProjectType, EuCordisProjectSearchPage +from inse.works.logic import get_publication_dois_of_author + +async def _get_eu_project_ids_for_openalex_authors( + author_ids: List[str], +) -> Optional[List[str]]: + """ + Resolves OpenAlex authors to CORDIS EU project IDs via publication DOIs. + + Multiple authors use AND semantics: + project must be connected to publications from every selected author. + """ + author_ids = [author_id for author_id in author_ids if author_id and author_id.strip()] + if not author_ids: + return None + + project_sets: List[Set[str]] = [] + + for author_id in author_ids: + dois = await get_publication_dois_of_author(raw_oa_author_id=author_id) + if not dois: + return [] + + project_ids = await projects_search_client.get_cordis_eu_project_ids_by_dois( + dois=dois + ) + + if not project_ids: + return [] + + project_sets.append(set(project_ids)) + + if not project_sets: + return None + + return list(set.intersection(*project_sets)) + + +async def search_eu_cordis_projects_summary_impl( + page: int, + size: int, + project_types: Optional[List[EuCordisProjectType]] = None, + author_id: Optional[str] = None, + author_ids: Optional[List[str]] = None, + organization_ids: Optional[List[str]] = None, + organization_names: Optional[List[str]] = None, + keywords: Optional[List[str]] = None, + topic_ids: Optional[List[str]] = None, + filter_topic_ids: Optional[List[str]] = None, + title: Optional[str] = None, + funding_start_years: Optional[List[str]] = None, + funding_end_years: Optional[List[str]] = None, + countries: Optional[List[str]] = None, + framework_programmes: Optional[List[str]] = None, + funding_schemes: Optional[List[str]] = None, + statuses: Optional[List[str]] = None, + sort_by: str = "title", + sort_direction: str = "asc", + fuzzy: bool = False, +) -> EuCordisProjectSearchPage: + + all_author_ids: List[str] = [] + + if author_id: + all_author_ids.append(author_id) + all_author_ids.extend(author_ids or []) + author_project_ids = await _get_eu_project_ids_for_openalex_authors( + author_ids=all_author_ids + ) + + return await search_eu_cordis_projects( + page=page, + size=size, + project_types=project_types, + organization_ids=organization_ids, + organization_names=organization_names, + author_project_ids=author_project_ids, + keywords=keywords, + topic_ids=topic_ids, + filter_topic_ids=filter_topic_ids, + title=title, + funding_start_years=funding_start_years, + funding_end_years=funding_end_years, + countries=countries, + framework_programmes=framework_programmes, + funding_schemes=funding_schemes, + statuses=statuses, + sort_by=sort_by, + sort_direction=sort_direction, + fuzzy=fuzzy, + ) \ No newline at end of file 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 new file mode 100644 index 00000000..b9bc7aa1 --- /dev/null +++ b/service/src/main/inse/projects/test_eu_cordis_search_client.py @@ -0,0 +1,364 @@ +import pytest +from inse.projects import eu_cordis_projects_client as eu_cordis_search_client + +@pytest.mark.anyio +async def test_search_eu_cordis_projects_by_title(): + """Test searching EU CORDIS projects by title.""" + res = await eu_cordis_search_client.search_eu_cordis_projects( + page=0, + size=5, + title="Artificial Intelligence", + ) + assert res is not None + assert res.total > 0 + assert len(res.elements) > 0 + for element in res.elements: + assert element.id is not None + assert element.title is not None + assert "artificial" in element.title.lower() or "intelligence" in element.title.lower() + + +@pytest.mark.anyio +async def test_search_eu_cordis_projects_by_keywords(): + """Test searching EU CORDIS projects by keywords.""" + res = await eu_cordis_search_client.search_eu_cordis_projects( + page=0, + size=5, + keywords=["machine learning", "deep learning"], + ) + assert res is not None + assert res.total > 0 + assert len(res.elements) > 0 + for element in res.elements: + assert element.id is not None + assert element.title is not None + + +@pytest.mark.anyio +async def test_search_eu_cordis_projects_by_framework_programme(): + """Test filtering EU CORDIS projects by framework programme.""" + res = await eu_cordis_search_client.search_eu_cordis_projects( + page=0, + size=5, + framework_programmes=["H2020"], + ) + assert res is not None + assert res.total > 0 + assert len(res.elements) > 0 + for element in res.elements: + assert element.id is not None + assert element.framework_programme == "H2020" + + +@pytest.mark.anyio +async def test_search_eu_cordis_projects_by_status(): + """Test filtering EU CORDIS projects by status.""" + res = await eu_cordis_search_client.search_eu_cordis_projects( + page=0, + size=5, + statuses=["SIGNED"], + ) + assert res is not None + assert res.total > 0 + assert len(res.elements) > 0 + for element in res.elements: + assert element.id is not None + assert element.status == "SIGNED" + + +@pytest.mark.anyio +async def test_search_eu_cordis_projects_by_funding_years(): + """Test filtering EU CORDIS projects by funding start years.""" + res = await eu_cordis_search_client.search_eu_cordis_projects( + page=0, + size=5, + funding_start_years=["2020"], + ) + + assert res is not None + assert res.total > 0 + assert len(res.elements) > 0 + for element in res.elements: + assert element.id is not None + assert element.start_date is not None + assert element.start_date.year == 2020 + + +@pytest.mark.anyio +async def test_search_eu_cordis_projects_by_country(): + """Test filtering EU CORDIS projects by country.""" + res = await eu_cordis_search_client.search_eu_cordis_projects( + page=0, + size=5, + countries=["DE"], + ) + assert res is not None + assert res.total > 0 + assert len(res.elements) > 0 + for element in res.elements: + assert element.id is not None + # Verify at least one organization is from Germany + assert any( + org.country == "DE" for org in element.organizations + ) + + +@pytest.mark.anyio +async def test_search_eu_cordis_projects_by_organization_name(): + """Test filtering EU CORDIS projects by organization name.""" + res = await eu_cordis_search_client.search_eu_cordis_projects( + page=0, + size=5, + organization_names=["Max Planck"], + ) + assert res is not None + assert res.total > 0 + assert len(res.elements) > 0 + for element in res.elements: + assert element.id is not None + # Verify at least one organization matches the name + assert any( + "max planck" in org.name.lower() for org in element.organizations + ) + + +@pytest.mark.anyio +async def test_search_eu_cordis_projects_by_organization_id(): + """Test filtering EU CORDIS projects by organization ID.""" + # Use a known organization ID (e.g., Max Planck Society) + known_org_id = "999990267" + res = await eu_cordis_search_client.search_eu_cordis_projects( + page=0, + size=5, + organization_ids=[known_org_id], + ) + assert res is not None + assert res.total > 0 + assert len(res.elements) > 0 + for element in res.elements: + assert element.id is not None + # Verify the organization is present in the project + assert any( + org.organisation_id == known_org_id for org in element.organizations + ) + + +@pytest.mark.anyio +async def test_search_eu_cordis_projects_by_project_type(): + """Test filtering EU CORDIS projects by project type (FP7, H2020, HEU).""" + from inse.projects.model import EuCordisProjectType + + # Test FP7 projects + res_fp7 = await eu_cordis_search_client.search_eu_cordis_projects( + page=0, + size=5, + project_types=[EuCordisProjectType.FP7], + ) + assert res_fp7 is not None + assert res_fp7.total > 0 + assert len(res_fp7.elements) > 0 + for element in res_fp7.elements: + assert element.id is not None + assert element.project_type == EuCordisProjectType.FP7 + + # Test H2020 projects + res_h2020 = await eu_cordis_search_client.search_eu_cordis_projects( + page=0, + size=5, + project_types=[EuCordisProjectType.H2020], + ) + assert res_h2020 is not None + assert res_h2020.total > 0 + assert len(res_h2020.elements) > 0 + for element in res_h2020.elements: + assert element.id is not None + assert element.project_type == EuCordisProjectType.H2020 + + +@pytest.mark.anyio +async def test_search_eu_cordis_projects_with_sorting(): + """Test sorting EU CORDIS projects.""" + # Test ascending sort by title + res_asc = await eu_cordis_search_client.search_eu_cordis_projects( + page=0, + size=5, + sort_by="title", + sort_direction="asc", + ) + assert res_asc is not None + assert len(res_asc.elements) > 0 + + titles_asc = [element.title for element in res_asc.elements] + assert titles_asc == sorted(titles_asc) + + # Test descending sort by title + res_desc = await eu_cordis_search_client.search_eu_cordis_projects( + page=0, + size=5, + sort_by="title", + sort_direction="desc", + ) + assert res_desc is not None + assert len(res_desc.elements) > 0 + + titles_desc = [element.title for element in res_desc.elements] + assert titles_desc == sorted(titles_desc, reverse=True) + + +@pytest.mark.anyio +async def test_search_eu_cordis_projects_pagination(): + """Test pagination of EU CORDIS project search results.""" + # Get first page + page1 = await eu_cordis_search_client.search_eu_cordis_projects( + page=0, + size=3, + ) + assert page1 is not None + assert len(page1.elements) <= 3 + assert page1.page == 0 + assert page1.size == 3 + + # Get second page + page2 = await eu_cordis_search_client.search_eu_cordis_projects( + page=1, + size=3, + ) + assert page2 is not None + assert len(page2.elements) <= 3 + assert page2.page == 1 + assert page2.size == 3 + + # Ensure pages don't overlap + page1_ids = {element.id for element in page1.elements} + page2_ids = {element.id for element in page2.elements} + assert page1_ids.isdisjoint(page2_ids) + + +@pytest.mark.anyio +async def test_get_enriched_cordis_project_by_id(): + """Test fetching an enriched EU CORDIS project by ID.""" + # Use a known project ID (e.g., an H2020 project) + known_id = "101016442" # Example H2020 project ID + project = await eu_cordis_search_client.get_enriched_cordis_project_by_id(known_id) + assert project is not None + assert project.id == known_id + assert project.title is not None + assert project.objective is not None + + # Verify enriched data + assert hasattr(project, 'organizations') + assert hasattr(project, 'publications') + assert hasattr(project, 'report_summaries') + assert hasattr(project, 'topics_list') + + +@pytest.mark.anyio +async def test_get_enriched_cordis_project_by_id_not_found(): + """Test fetching a non-existent EU CORDIS project.""" + project = await eu_cordis_search_client.get_enriched_cordis_project_by_id("nonexistent_id") + assert project is None + + +@pytest.mark.anyio +async def test_get_enriched_cordis_project_by_id_empty(): + """Test fetching with empty project ID.""" + project = await eu_cordis_search_client.get_enriched_cordis_project_by_id("") + assert project is None + + project = await eu_cordis_search_client.get_enriched_cordis_project_by_id(None) + assert project is None + + +@pytest.mark.anyio +async def test_get_dois_by_cordis_eu_project_id(): + """Test retrieving DOIs for a CORDIS EU project.""" + known_id = "101016442" # Example H2020 project ID + dois = await eu_cordis_search_client.get_dois_by_cordis_eu_project_id(known_id) + assert dois is not None + assert len(dois) > 0 + + +@pytest.mark.anyio +async def test_get_openalex_authors_for_cordis_project_ids(): + """Test retrieving OpenAlex authors for CORDIS project IDs.""" + project_ids = ["101016442"] # Example H2020 project ID + authors_by_project = await eu_cordis_search_client.get_openalex_authors_for_cordis_project_ids(project_ids) + assert authors_by_project is not None + assert len(authors_by_project) > 0 + + for project_id, author_page in authors_by_project.items(): + assert project_id in project_ids + assert author_page is not None + if author_page.total > 0: + for author in author_page.elements: + assert author.id is not None + assert author.display_name is not None + + +@pytest.mark.anyio +async def test_search_eu_cordis_projects_with_multiple_filters(): + """Test combining multiple filters in EU CORDIS project search.""" + res = await eu_cordis_search_client.search_eu_cordis_projects( + page=0, + size=5, + framework_programmes=["H2020"], + funding_start_years=["2020"], + countries=["US"], + statuses=["SIGNED"], + ) + assert res is not None + assert res.total > 0 + assert len(res.elements) > 0 + for element in res.elements: + assert element.id is not None + assert element.framework_programme == "H2020" + assert element.status == "SIGNED" + assert element.start_date.year == 2020 + assert any(org.country == "US" for org in element.organizations) + + +@pytest.mark.anyio +async def test_search_eu_cordis_projects_empty_results(): + """Test search that should return no results.""" + res = await eu_cordis_search_client.search_eu_cordis_projects( + page=0, + size=5, + title="ThisProjectDoesNotExistXYZ123", + ) + assert res is not None + assert res.total == 0 + assert len(res.elements) == 0 + + +@pytest.mark.anyio +async def test_search_eu_cordis_projects_by_funding_scheme(): + """Test filtering EU CORDIS projects by funding scheme.""" + res = await eu_cordis_search_client.search_eu_cordis_projects( + page=0, + size=5, + funding_schemes=["ERC-ADG"], # ERC Advanced Grant + ) + assert res is not None + assert res.total > 0 + assert len(res.elements) > 0 + for element in res.elements: + assert element.id is not None + assert element.funding_scheme == "ERC-ADG" + + +@pytest.mark.anyio +async def test_search_eu_cordis_projects_with_fuzzy_topic_search(): + """Test fuzzy search with OpenAlex topic IDs.""" + # This test requires known OpenAlex topic IDs + topic_ids = ["https://openalex.org/T12345"] # Example topic ID + res = await eu_cordis_search_client.search_eu_cordis_projects( + page=0, + size=5, + topic_ids=topic_ids, + fuzzy=True, + ) + assert res is not None + # 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 diff --git a/service/src/main/inse/ranking/logic.py b/service/src/main/inse/ranking/logic.py index c4997cb8..dc842f4c 100644 --- a/service/src/main/inse/ranking/logic.py +++ b/service/src/main/inse/ranking/logic.py @@ -9,11 +9,14 @@ from typing import Any, List, Optional import pandas as pd +from inse.authors.institution_membership_query import ( + current_affiliation_year_cutoff, +) +from inse.company_connections.logic import get_company_counts_by_names from inse.integrations import elasticsearch from inse.model import ESCluster -from inse.persons.logic import _classify_career_stage from inse.persons.query_builder import build_author_filter_clauses -from inse.company_connections.logic import get_company_counts_by_names + from .. import config from .model import ( AuthorStaticStats, @@ -39,19 +42,23 @@ logger = logging.getLogger(__name__) # terms size: gather all matching authors as candidates before the score is # computed, so a strong citation weight can still lift a low-works author. CANDIDATE_POOL_SIZE = 10000 -UNI_AUTHOR_LIMIT = 20000 +INSTITUTION_AUTHOR_LIMIT = 20000 -async def _get_author_ids_from_uni(institution_name: str) -> List[str]: - """Returns the ids of all authors of the given institution. +async def _get_author_ids_from_institution(institution_id: str) -> List[str]: + """Returns the IDs of active authors of the given institution. - Uses the same author selection as the persons search endpoint (by institution - display name, see ``build_author_filter_clauses``), but scrolls over the whole - result set instead of paginating so that *all* matching author ids are returned. + Uses the same author selection as the persons search endpoint, but scrolls + over the result set instead of paginating it. """ query = { "bool": { - "filter": build_author_filter_clauses(institution_name=institution_name), + "filter": build_author_filter_clauses( + institution_id=institution_id, + year_filter_enabled=True, + filter_mode="from", + filter_year=current_affiliation_year_cutoff(), + ), }, } @@ -67,7 +74,7 @@ async def _get_author_ids_from_uni(institution_name: str) -> List[str]: author_id = source.get("id") or hit.get("_id", "") if author_id: author_ids.append(author_id) - if len(author_ids) >= UNI_AUTHOR_LIMIT: + if len(author_ids) >= INSTITUTION_AUTHOR_LIMIT: break return author_ids @@ -376,7 +383,7 @@ async def topic_stats_for_authors( ) results = [] - + for author_bucket in author_buckets: to_work = author_bucket.get("to_work", {}) avg_value = to_work.get("avg_percentile", {}).get("value") @@ -690,7 +697,7 @@ async def static_stats_for_authors( ) results = [] - + for author_id in author_ids: name = names_by_id.get(author_id, "") results.append( @@ -837,7 +844,7 @@ def _min_max_normalize(values: pd.Series) -> pd.Series: # 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 (values - minimum) / (maximum - minimum) @@ -1091,7 +1098,7 @@ async def _filter_author_ids_by_career_stage( async def rank_authors_by_keywords( keywords: List[str], operator: KeywordOperator, - institution_name: str, + institution_id: str, weights: RankingWeights, career_stages: List[CareerStage], publication_types: List[PublicationType], @@ -1106,11 +1113,11 @@ async def rank_authors_by_keywords( """ query_start_time = time() - author_ids = await _get_author_ids_from_uni(institution_name) - + author_ids = await _get_author_ids_from_institution(institution_id) + if not author_ids: return [] - + if career_stages: author_ids = await _filter_author_ids_by_career_stage(author_ids, career_stages) diff --git a/service/src/main/inse/ranking/model.py b/service/src/main/inse/ranking/model.py index 8fce11ef..b6557415 100644 --- a/service/src/main/inse/ranking/model.py +++ b/service/src/main/inse/ranking/model.py @@ -114,10 +114,6 @@ class KeywordToAuthorRequest(BaseModel): description="What the 'keywords' values match against: 'keyword' (OpenAlex " "keyword display names) or 'topic' (OpenAlex topic display names). Defaults to 'keyword'.", ) - institution_name: str = Field( - default="University of Duisburg-Essen", - description="The selected institution display name. (Default Uni-Due)", - ) weights: RankingWeights = Field( description="Weights for the ranking metrics. Required.", ) diff --git a/service/src/main/inse/ranking/router.py b/service/src/main/inse/ranking/router.py index 6f00eca7..df0c227d 100644 --- a/service/src/main/inse/ranking/router.py +++ b/service/src/main/inse/ranking/router.py @@ -1,8 +1,10 @@ import logging -from typing import List +from typing import Annotated, List -from fastapi import APIRouter +from fastapi import APIRouter, HTTPException, status +from inse.auth.model import AccessTokenMetadata +from inse.auth.service import CurrentUserAccessTokenPayloadDep from inse.tags import Tags from . import logic from .model import ( @@ -24,28 +26,40 @@ router = APIRouter( # Author ranking @router.post("/rank-author", response_model=List[RankedAuthor]) -async def rank_author(request: KeywordToAuthorRequest): +async def rank_author( + request: KeywordToAuthorRequest, + access_token_metadata: Annotated[ + AccessTokenMetadata, CurrentUserAccessTokenPayloadDep + ], +): + institution_id = access_token_metadata.effective_institution_id + if not institution_id: + raise HTTPException( + status_code=status.HTTP_403_FORBIDDEN, + detail="No OpenAlex institution is assigned to the current organization.", + ) + logger.info( - "rank-author keywords=%s operator=%s filter_type=%s institution_name=%s career_stages=%s " + "rank-author keywords=%s operator=%s filter_type=%s institution_id=%s career_stages=%s " "publication_types=%s timespan=%s", request.keywords, request.operator, request.filter_type, - request.institution_name, + institution_id, request.career_stages, request.publication_types, request.timespan, ) return await logic.rank_authors_by_keywords( - request.keywords, - request.operator, - request.institution_name, - request.weights, - request.career_stages, - request.publication_types, - request.timespan, - request.company_status, - request.filter_type, + keywords=request.keywords, + operator=request.operator, + institution_id=institution_id, + weights=request.weights, + career_stages=request.career_stages, + publication_types=request.publication_types, + timespan=request.timespan, + company_status=request.company_status, + filter_type=request.filter_type, ) # Compare authors table 1 (topic stats) diff --git a/service/src/main/inse/university_ranking/trend_logic.py b/service/src/main/inse/university_ranking/trend_logic.py index e77225e6..d6314793 100644 --- a/service/src/main/inse/university_ranking/trend_logic.py +++ b/service/src/main/inse/university_ranking/trend_logic.py @@ -942,9 +942,6 @@ async def get_top_topics_for_entity( except Exception as e: logger.error("Failed to query top project topics for entity: %s", e) return {"items": []} - -# Default fallback institution: University of Duisburg-Essen -DEFAULT_INSTITUTION_ID = "https://openalex.org/I62318514" DEFAULT_INSTITUTION_NAME = "University of Duisburg-Essen" DEFAULT_TOP_TOPICS_SIZE = 20 @@ -995,18 +992,34 @@ async def get_top_topics_for_entity( from inse.patents.search_client import PatentSearchClient patent_client = PatentSearchClient() short_id = entity_id.split("/")[-1] + full_id = f"https://openalex.org/{short_id}" - aliases = [short_id, entity_id] + aliases = [short_id, entity_id, full_id] if entity_type == "institution": try: from inse.institutions.institutions_search_client import InstitutionsSearchClient client = InstitutionsSearchClient() resolved_aliases = await client.get_institution_aliases_by_oa_institution_id(short_id) if resolved_aliases: - aliases = list(resolved_aliases) + aliases.extend(resolved_aliases) + + inst_res = await elasticsearch.search( + index=str(ESIndex.OPENALEX_INSTITUTIONS), + query={"terms": {"id": [full_id, short_id]}}, + size=1, + source=["display_name"], + cluster="nes" + ) + hits = inst_res.get("hits", {}).get("hits", []) + if hits: + d_name = hits[0]["_source"].get("display_name") + if d_name: + aliases.append(d_name) except Exception as e: logger.warning("Failed to resolve institution aliases in get_top_topics_for_entity: %s", e) - + + aliases = list(set([a for a in aliases if a])) + include_german = True if entity_type == "country" and entity_id.strip().upper() != "DE": include_german = False @@ -1100,22 +1113,35 @@ async def get_top_topics_for_entity( for topic_idx, p_ids in project_ids_by_index.items(): if not p_ids: continue - for i in range(0, len(p_ids), 500): - chunk = p_ids[i:i+500] + for i in range(0, len(p_ids), 1000): + chunk = p_ids[i:i+1000] payload = { - "query": {"terms": {"project_id": chunk}}, - "size": 10000, - "_source": ["topic_matches"] + "query": { + "bool": { + "should": [ + {"terms": {"project_id": chunk}}, + {"terms": {"project_id.keyword": chunk}} + ], + "minimum_should_match": 1 + } + }, + "size": 0, + "aggs": { + "topics": { + "terms": { + "field": "topic_matches.topic_display_name.keyword", + "size": 100 + } + } + } } try: res = await patent_client._search(index=topic_idx, payload=payload) - hits = res.get("hits", {}).get("hits", []) - for hit in hits: - matches = hit.get("_source", {}).get("topic_matches", []) - for m in matches: - t_name = m.get("topic_display_name") - if t_name: - topic_counts[t_name] = topic_counts.get(t_name, 0) + 1 + buckets = res.get("aggregations", {}).get("topics", {}).get("buckets", []) + for b in buckets: + t_name = b["key"] + cnt = b["doc_count"] + topic_counts[t_name] = topic_counts.get(t_name, 0) + cnt except Exception as e: logger.warning("Failed to aggregate topics from %s: %s", topic_idx, e) @@ -1134,6 +1160,37 @@ async def get_top_topics_for_entity( logger.error("Failed to query top project topics for entity: %s", e) return {"items": []} + if search_type == "news": + try: + res = await elasticsearch.search( + index="aktuell_postproc", + body={ + "query": {"match_all": {}}, + "size": 0, + "aggs": { + "top_topics": { + "terms": { + "field": "topics.display_name.keyword", + "size": DEFAULT_TOP_TOPICS_SIZE + } + } + } + }, + cluster="inse" + ) + buckets = res.get("aggregations", {}).get("top_topics", {}).get("buckets", []) + items = [{"name": b["key"], "count": b["doc_count"]} for b in buckets] + total_hits = res.get("hits", {}).get("total", {}) + total_val = total_hits.get("value", 0) if isinstance(total_hits, dict) else int(total_hits or 0) + sum_top = sum(b["count"] for b in items) + other_count = max(0, total_val - sum_top) + if other_count > 0: + items.append({"name": "Andere Themen", "count": other_count}) + return {"items": items} + except Exception as e: + logger.error("Failed to query top news topics for entity: %s", e) + return {"items": []} + # Default fallback: openalex-works* query for publications/authors # 1. Normalize ID and prepare filter clause if entity_type == "institution": diff --git a/service/src/main/inse/university_ranking/trend_strategies.py b/service/src/main/inse/university_ranking/trend_strategies.py index 4a93704a..4cf56e6e 100644 --- a/service/src/main/inse/university_ranking/trend_strategies.py +++ b/service/src/main/inse/university_ranking/trend_strategies.py @@ -1448,33 +1448,67 @@ class NewsTrendStrategy(TrendStrategy): end_year = datetime.datetime.now().year - 1 years_range = list(range(start_year, end_year + 1)) - search_terms = keywords if keywords else topics - - # Each series will map all topic keys to its data. + # Each series entity represents one topic/keyword. accumulated_data = { f"news_topic_{t}": {top: {yr: (0, 1) for yr in years_range} for top in topics} for t in topics } - # Query UDE news postprocessed index to get matching news IDs + AKTUELLES_SEARCH_FIELDS = ["main_content", "full_content", "maintitle", "subtitle", "intro_content"] + STOP_WORDS = {"in", "and", "or", "und", "oder", "der", "die", "das", "von", "mit", "zu", "at", "by", "on", "for", "to", "a", "an", "the"} + + # Query UDE news postprocessed index to get matching news IDs without 10k capping async def fetch_news_ids_for_term(idx: int, t_name: str) -> List[str]: - term = search_terms[idx] if idx < len(search_terms) else t_name + if fuzzy: + term = t_name + es_query = {"match": {"topics.display_name": term}} + 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 + es_query = {"match": {"keywords": term}} + + news_ids = set() try: - res = await elasticsearch.search( + async for hit in elasticsearch.scan( index="aktuell_postproc", - query={"match": {"keywords": term}}, - size=10000, + query=es_query, source=["news_id"], cluster="inse" - ) - return [ - hit["_source"]["news_id"] - for hit in res.get("hits", {}).get("hits", []) - if hit.get("_source", {}).get("news_id") - ] + ): + nid = hit.get("_source", {}).get("news_id") + if nid: + news_ids.add(nid) except Exception as e: - logger.warning("Failed to search UDE news postproc keywords: %s", e) - return [] + logger.warning("Failed to scan UDE news postproc: %s", e) + + # If non-fuzzy keyword search, also search article content fields in 'aktuell' index + if not fuzzy and term and term.lower() not in STOP_WORDS and len(term.strip()) > 1: + try: + content_query = { + "query_string": { + "query": term, + "fields": AKTUELLES_SEARCH_FIELDS, + "default_operator": "AND" + } + } + async for hit in elasticsearch.scan( + index="aktuell", + query=content_query, + source=["news_id"], + cluster="inse" + ): + nid = hit.get("_id") or hit.get("_source", {}).get("news_id") + if nid: + news_ids.add(nid) + except Exception as e: + logger.warning("Failed to scan UDE news content in aktuell: %s", e) + + return list(news_ids) # Find all matching news IDs concurrently matching_ids_list = await asyncio.gather(*[ @@ -1484,36 +1518,36 @@ class NewsTrendStrategy(TrendStrategy): async def count_by_year(t_name: str, news_ids: List[str]): if not news_ids: return - try: - # Query aktuell index using matching news IDs and aggregate by date_year - res = await elasticsearch.search( - index="aktuell", - body={ - "query": {"bool": {"filter": [ - {"ids": {"values": news_ids}}, - {"range": {"date_year": {"gte": start_year, "lte": end_year}}} - ]}}, - "aggs": { - "by_year": { - "terms": {"field": "date_year", "size": len(years_range) * 2} + entity_key = f"news_topic_{t_name}" + # Batch news_ids in chunks of 2000 to avoid ES query clause limits + for i in range(0, len(news_ids), 2000): + chunk = news_ids[i:i+2000] + try: + res = await elasticsearch.search( + index="aktuell", + body={ + "query": {"bool": {"filter": [ + {"ids": {"values": chunk}}, + {"range": {"date_year": {"gte": start_year, "lte": end_year}}} + ]}}, + "aggs": { + "by_year": { + "terms": {"field": "date_year", "size": len(years_range) * 2} + } } - } - }, - size=0, - cluster="inse" - ) - buckets = res.get("aggregations", {}).get("by_year", {}).get("buckets", []) - for b in buckets: - yr = int(b.get("key")) - count = int(b.get("doc_count", 0)) - if yr in years_range: - entity_key = f"news_topic_{t_name}" - # Set this count for all topic keys in this topic's series - for top in topics: - accumulated_data[entity_key][top] = dict(accumulated_data[entity_key][top]) - accumulated_data[entity_key][top][yr] = (count, 1) - except Exception as e: - logger.warning("Failed to aggregate news years from ES: %s", e) + }, + size=0, + cluster="inse" + ) + buckets = res.get("aggregations", {}).get("by_year", {}).get("buckets", []) + for b in buckets: + yr = int(b.get("key")) + count = int(b.get("doc_count", 0)) + if yr in years_range: + prev_count, _ = accumulated_data[entity_key][t_name][yr] + accumulated_data[entity_key][t_name][yr] = (prev_count + count, 1) + except Exception as e: + logger.warning("Failed to aggregate news years from ES for chunk: %s", e) # Aggregate news publication years concurrently await asyncio.gather(*[ @@ -1526,21 +1560,27 @@ class NewsTrendStrategy(TrendStrategy): for t_name in topics: entity_key = f"news_topic_{t_name}" topic_data_map = {} - for topic in topics: - yearly_data_items = [] - lookup = normalized_lookup.get((entity_key, topic), {}) - norm_vals = lookup.get("normalized", [0.0] * len(years_range)) - cum_vals = lookup.get("cumulative", [0.0] * len(years_range)) - for idx, yr in enumerate(years_range): - count, _ = accumulated_data[entity_key][topic][yr] - yearly_data_items.append(TopicYearlyData( - year=yr, - raw=count, - normalized=norm_vals[idx], - cumulative=cum_vals[idx], - institutions_count=1 - )) + # Extract yearly data items for t_name from accumulated_data[entity_key][t_name] + 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)) + + yearly_data_items = [] + for idx, yr in enumerate(years_range): + count, _ = accumulated_data[entity_key][t_name][yr] + yearly_data_items.append(TopicYearlyData( + year=yr, + raw=count, + normalized=norm_vals[idx], + cumulative=cum_vals[idx], + institutions_count=1 + )) + + # Populate topic_data_map for ALL topic keys in topics with t_name's yearly items. + # This ensures uni-trend-chart accessing topic_data[selectedTopic] for any selected topic + # always gets t_name's true data items for series t_name. + for topic in topics: topic_data_map[topic] = yearly_data_items series_list.append(TrendSeries( diff --git a/service/src/main/inse/works/logic.py b/service/src/main/inse/works/logic.py index ec4f16af..6384b39b 100644 --- a/service/src/main/inse/works/logic.py +++ b/service/src/main/inse/works/logic.py @@ -22,7 +22,7 @@ from inse.models.openalex.topics_by_year import TopicsByYear from inse.models.openalex.topics_by_time import TopicsByTime from inse.exceptions import MissingApiKeyError, ElasticsearchException, UpstreamAPIException from .search_client import OpenAlexWorksSearchClient - +from inse.model import ESCluster, ESIndex logger = logging.getLogger(__name__) TOPIC_DETAIL_SOURCE_FIELDS = [ @@ -183,7 +183,8 @@ async def _get_primary_topic_counts_from_es(author_id: str) -> list[dict]: try: response = await elasticsearch.search( - index=config.settings.openalex_works_search_index, + index=ESIndex.OPENALEX_WORKS_WILDCARD, + cluster=ESCluster.NES, body=body, ) except ElasticsearchException as exc: @@ -273,7 +274,8 @@ async def _get_topic_details(topic_ids: List[str]) -> dict[str, dict]: try: response = await elasticsearch.search( - index="openalex-topics", + index=ESIndex.OPENALEX_TOPICS, + cluster=ESCluster.NES, query={"terms": {"id": topic_ids}}, source=TOPIC_DETAIL_SOURCE_FIELDS, size=len(topic_ids), @@ -698,7 +700,8 @@ async def _get_publication_year_counts_from_es(author_id: str) -> tuple[list[dic try: response = await elasticsearch.search( - index=config.settings.openalex_works_search_index, + index=ESIndex.OPENALEX_WORKS_WILDCARD, + cluster=ESCluster.NES, body=body, ) except ElasticsearchException as exc: @@ -766,7 +769,8 @@ async def _get_timeline_topic_counts_from_es( try: response = await elasticsearch.search( - index=config.settings.openalex_works_search_index, + index=ESIndex.OPENALEX_WORKS_WILDCARD, + cluster=ESCluster.NES, body=body, ) except ElasticsearchException as exc: @@ -1015,11 +1019,11 @@ async def get_publication_dois_of_author( try: response = await elasticsearch.search( - index="openalex-works", + index=ESIndex.OPENALEX_WORKS_WILDCARD, source=["doi"], size=10000, query=query, - cluster="nes", + cluster=ESCluster.NES, ) except ElasticsearchException as exc: logger.exception("Request for publication DOIs of author failed.") diff --git a/service/src/main/inse/works/v2/model.py b/service/src/main/inse/works/v2/model.py index 5cde6e77..121ea2cc 100644 --- a/service/src/main/inse/works/v2/model.py +++ b/service/src/main/inse/works/v2/model.py @@ -149,6 +149,9 @@ class WorkClassification(BaseModel): publication_year: Optional[int] = Field( default=None, description="The publication year of the work." ) + publication_type: Optional[str] = Field( + default=None, description="The OpenAlex publication type of the work." + ) authors: List[WorkClassificationAuthor] = Field( default_factory=list, description="The authors of the work." ) diff --git a/service/src/main/inse/works/v2/service.py b/service/src/main/inse/works/v2/service.py index b7941d11..9c86b65e 100644 --- a/service/src/main/inse/works/v2/service.py +++ b/service/src/main/inse/works/v2/service.py @@ -1,8 +1,13 @@ import logging from typing import Dict, List, Optional + +import inse.authors.v2.service as author_service from fastapi import Query +from inse.auth.model import AccessTokenMetadata +from inse.exceptions import ElasticsearchNotFoundException from inse.integrations import elasticsearch -from inse.model import ESIndex, SortDirection, ESCluster +from inse.model import ESCluster, ESIndex, SortDirection +from inse.models.openalex.work import Work from inse.works.v2.model import ( PrimaryCategoryYearAggregation, PrimaryCategoryYearAggregationPage, @@ -11,10 +16,6 @@ from inse.works.v2.model import ( WorkPageV2, WorkSortBy, ) -from inse.models.openalex.work import Work -from inse.auth.model import AccessTokenMetadata -import inse.authors.v2.service as author_service - logger = logging.getLogger(__name__) logger.setLevel(logging.DEBUG) @@ -357,7 +358,7 @@ async def get_works_by_keywords( sort = [{"title.keyword": sort_order.value}] else: sort = [{sort_by.value: sort_order.value}] - print(f"Final query:", must) + print("Final query:", must) # search response = await elasticsearch.search( index=ESIndex.OPENALEX_WORKS_WILDCARD, @@ -698,6 +699,7 @@ async def _get_work_classifications_by_work_ids( "doi", "title", "publication_year", + "publication_type", "authors", "institutions", "topics", @@ -755,11 +757,14 @@ async def _get_work_classification_by_work_id( Optional[WorkClassification]: The work classification if found, otherwise None. """ - response = await elasticsearch.get( - ESIndex.WORK_CLASSIFICATIONS, - doc_id=raw_oa_work_id, - source=source, - ) + try: + response = await elasticsearch.get( + ESIndex.WORK_CLASSIFICATIONS, + doc_id=raw_oa_work_id, + source=source, + ) + except ElasticsearchNotFoundException: + return None _source = response.get("_source") if _source: diff --git a/webapp/src/app/api/.openapi-generator/FILES b/webapp/src/app/api/.openapi-generator/FILES index bcaf568d..9122548b 100644 --- a/webapp/src/app/api/.openapi-generator/FILES +++ b/webapp/src/app/api/.openapi-generator/FILES @@ -22,6 +22,7 @@ api/patents.service.ts api/personNetwork.service.ts api/persons.service.ts api/projects.service.ts +api/ranking.service.ts api/topics.service.ts api/topicsV2.service.ts api/universityRankings.service.ts @@ -40,11 +41,15 @@ model/author.ts model/authorAffiliationsInner.ts model/authorCountsByYearInner.ts model/authorIds.ts +model/authorMetricsRequest.ts model/authorNetworkNode.ts model/authorPage.ts model/authorParsedLongestName.ts model/authorPositionCount.ts +model/authorStaticStats.ts model/authorSummaryStats.ts +model/authorTopicProfile.ts +model/authorTopicStats.ts model/authorsFilterProperties.ts model/authorsListResponse.ts model/authorship.ts @@ -63,11 +68,13 @@ model/bundProject.ts model/bundProjectDetails.ts model/bundProjectPage.ts model/careerMetrics.ts +model/careerStage.ts model/collaborationNetwork.ts model/collaborationNetworkEdge.ts model/collaborationNetworkNodeType.ts model/companyConnection.ts model/companyConnectionsResponse.ts +model/companyStatusFilter.ts model/cordisEuProject.ts model/cordisEuProjectPage.ts model/costUsd.ts @@ -90,7 +97,15 @@ model/dfgPersonSummaryPage.ts model/dfgProjectDetails.ts model/dfgProjectPage.ts model/dfgProjectSummary.ts +model/euCordisEurosciVocSummary.ts +model/euCordisOrganizationSelectorPage.ts +model/euCordisOrganizationSelectorSummary.ts +model/euCordisOrganizationSummary.ts model/euCordisProjectResponse.ts +model/euCordisProjectSearchPage.ts +model/euCordisProjectSummary.ts +model/euCordisProjectType.ts +model/euCordisTopicSummary.ts model/euOrganizationProjectSummary.ts model/euOrganizationProjectSummaryPage.ts model/euProjectData.ts @@ -100,6 +115,7 @@ model/extractedKeywordsResponse.ts model/fileUpload.ts model/filterInformation.ts model/filterProperties.ts +model/filterType.ts model/fp7EurosciVoc.ts model/fp7LegalBasis.ts model/fp7Organization.ts @@ -151,11 +167,13 @@ model/ipcClassification.ts model/keywordEntry.ts model/keywordEntryWithTopic.ts model/keywordEvidence.ts +model/keywordOperator.ts model/keywordPatentLevel.ts model/keywordPatentMappingStatus.ts model/keywordPatentMatch.ts model/keywordPatentSearchDiagnostics.ts model/keywordPatentSearchItem.ts +model/keywordToAuthorRequest.ts model/keywordTopicMatch.ts model/keywords.ts model/keywordsRequest.ts @@ -195,11 +213,17 @@ model/projectsFilteringProperties.ts model/projectsSortBy.ts model/publicationDetailByFunder.ts model/publicationIdsByAuthorPosition.ts +model/publicationType.ts model/publicationsByAuthorResponse.ts +model/rankedAuthor.ts model/rankingResponse.ts +model/rankingWeights.ts model/rebuildResponse.ts model/score.ts +model/selectedAuthorsRequest.ts model/sortDirection.ts +model/subfieldShare.ts +model/timespan.ts model/tokenType.ts model/topAuthor.ts model/topAuthorStatistics.ts diff --git a/webapp/src/app/api/api/companyConnections.service.ts b/webapp/src/app/api/api/companyConnections.service.ts index cbc5f803..59c13e2a 100644 --- a/webapp/src/app/api/api/companyConnections.service.ts +++ b/webapp/src/app/api/api/companyConnections.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,87 +9,244 @@ */ /* 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 { CompanyConnectionsAvailability } from '../model/companyConnectionsAvailability'; // @ts-ignore import { CompanyConnectionsResponse } from '../model/companyConnectionsResponse'; // @ts-ignore import { HTTPValidationError } from '../model/hTTPValidationError'; // @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 CompanyConnectionsService 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 whether company connections are available for an author. + * @endpoint get /api/inse-service/authors/{author_id}/company-connections/availability + * @param authorId + * @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 getCompanyConnectionsAvailability( + authorId: string, + observe?: 'body', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable; + public getCompanyConnectionsAvailability( + authorId: string, + observe?: 'response', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public getCompanyConnectionsAvailability( + authorId: string, + observe?: 'events', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public getCompanyConnectionsAvailability( + authorId: 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 getCompanyConnectionsAvailability.', + ); } - /** - * Get possible company connections by OpenAlex author ID. - * @endpoint get /api/inse-service/authors/{author_id}/company-connections - * @param authorId - * @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 getCompanyConnectionsByAuthor(authorId: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; - public getCompanyConnectionsByAuthor(authorId: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public getCompanyConnectionsByAuthor(authorId: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public getCompanyConnectionsByAuthor(authorId: 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 getCompanyConnectionsByAuthor.'); - } + 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/inse-service/authors/${this.configuration.encodeParam({name: "authorId", value: authorId, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: undefined})}/company-connections`; - 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, + ); } + const localVarHttpContext: HttpContext = + options?.context ?? new HttpContext(); + + const localVarTransferCache: boolean = options?.transferCache ?? true; + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if ( + this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected) + ) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/api/inse-service/authors/${this.configuration.encodeParam({ name: 'authorId', value: authorId, in: 'path', style: 'simple', explode: false, dataType: 'string', dataFormat: undefined })}/company-connections/availability`; + 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, + }, + ); + } + + /** + * Get possible company connections by OpenAlex author ID. + * @endpoint get /api/inse-service/authors/{author_id}/company-connections + * @param authorId + * @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 getCompanyConnectionsByAuthor( + authorId: string, + observe?: 'body', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable; + public getCompanyConnectionsByAuthor( + authorId: string, + observe?: 'response', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public getCompanyConnectionsByAuthor( + authorId: string, + observe?: 'events', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public getCompanyConnectionsByAuthor( + authorId: 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 getCompanyConnectionsByAuthor.', + ); + } + + let localVarHeaders = this.defaultHeaders; + + const localVarHttpHeaderAcceptSelected: string | undefined = + options?.httpHeaderAccept ?? + this.configuration.selectHeaderAccept(['application/json']); + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set( + 'Accept', + localVarHttpHeaderAcceptSelected, + ); + } + + const localVarHttpContext: HttpContext = + options?.context ?? new HttpContext(); + + const localVarTransferCache: boolean = options?.transferCache ?? true; + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if ( + this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected) + ) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/api/inse-service/authors/${this.configuration.encodeParam({ name: 'authorId', value: authorId, in: 'path', style: 'simple', explode: false, dataType: 'string', dataFormat: undefined })}/company-connections`; + 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, + }, + ); + } } diff --git a/webapp/src/app/api/api/persons.service.ts b/webapp/src/app/api/api/persons.service.ts index 03222a4c..2dd47272 100644 --- a/webapp/src/app/api/api/persons.service.ts +++ b/webapp/src/app/api/api/persons.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 { AuthorsListResponse } from '../model/authorsListResponse'; @@ -26,869 +32,1449 @@ import { HTTPValidationError } from '../model/hTTPValidationError'; import { PersonBio } from '../model/personBio'; // @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 PersonsService 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); + /** + * Generates a bio for a person by author ID. + * @endpoint get /api/inse-service/persons/bio + * @param authorId OpenAlex author ID (e.g., A5093075883) + * @param include Comma-separated list to include tags + * @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 generatePersonBio( + authorId: string, + include?: string, + observe?: 'body', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable; + public generatePersonBio( + authorId: string, + include?: string, + observe?: 'response', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public generatePersonBio( + authorId: string, + include?: string, + observe?: 'events', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public generatePersonBio( + authorId: string, + include?: 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 generatePersonBio.', + ); } - /** - * Generates a bio for a person by author ID. - * @endpoint get /api/inse-service/persons/bio - * @param authorId OpenAlex author ID (e.g., A5093075883) - * @param include Comma-separated list to include tags - * @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 generatePersonBio(authorId: string, include?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; - public generatePersonBio(authorId: string, include?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public generatePersonBio(authorId: string, include?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public generatePersonBio(authorId: string, include?: 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 generatePersonBio.'); - } + let localVarQueryParameters = new HttpParams({ encoder: this.encoder }); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + authorId, + 'author_id', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + include, + 'include', + ); - let localVarQueryParameters = new HttpParams({encoder: this.encoder}); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - authorId, 'author_id'); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - include, 'include'); + 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/inse-service/persons/bio`; + 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 for person by ID. + * @endpoint get /api/inse-service/person/{id} + * @param id OpenAlex author ID + * @param include Which data do we require? include tags: topics_full, topic_share, summary_stats, ids, last_known_institutions, ... + * @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 getPersonByID( + id: string, + include?: string, + observe?: 'body', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable; + public getPersonByID( + id: string, + include?: string, + observe?: 'response', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public getPersonByID( + id: string, + include?: string, + observe?: 'events', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public getPersonByID( + id: string, + include?: string, + observe: any = 'body', + reportProgress: boolean = false, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable { + if (id === null || id === undefined) { + throw new Error( + 'Required parameter id was null or undefined when calling getPersonByID.', + ); + } - let localVarPath = `/api/inse-service/persons/bio`; - 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, + include, + 'include', + ); + + let localVarHeaders = this.defaultHeaders; + + const localVarHttpHeaderAcceptSelected: string | undefined = + options?.httpHeaderAccept ?? + this.configuration.selectHeaderAccept(['application/json']); + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set( + 'Accept', + localVarHttpHeaderAcceptSelected, + ); + } + + const localVarHttpContext: HttpContext = + options?.context ?? new HttpContext(); + + const localVarTransferCache: boolean = options?.transferCache ?? true; + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if ( + this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected) + ) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/api/inse-service/person/${this.configuration.encodeParam({ name: 'id', value: id, in: 'path', style: 'simple', explode: false, dataType: 'string', dataFormat: undefined })}`; + 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 for person by ID. + * @endpoint get /api/inse-service/person/{id} + * @param id OpenAlex author ID + * @param include Which data do we require? include tags: topics_full, topic_share, summary_stats, ids, last_known_institutions, ... + * @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 getPersonByID_1( + id: string, + include?: string, + observe?: 'body', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable; + public getPersonByID_1( + id: string, + include?: string, + observe?: 'response', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public getPersonByID_1( + id: string, + include?: string, + observe?: 'events', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public getPersonByID_1( + id: string, + include?: string, + observe: any = 'body', + reportProgress: boolean = false, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable { + if (id === null || id === undefined) { + throw new Error( + 'Required parameter id was null or undefined when calling getPersonByID_1.', + ); + } + + let localVarQueryParameters = new HttpParams({ encoder: this.encoder }); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + include, + 'include', + ); + + let localVarHeaders = this.defaultHeaders; + + const localVarHttpHeaderAcceptSelected: string | undefined = + options?.httpHeaderAccept ?? + this.configuration.selectHeaderAccept(['application/json']); + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set( + 'Accept', + localVarHttpHeaderAcceptSelected, + ); + } + + const localVarHttpContext: HttpContext = + options?.context ?? new HttpContext(); + + const localVarTransferCache: boolean = options?.transferCache ?? true; + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if ( + this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected) + ) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/api/inse-service/person/${this.configuration.encodeParam({ name: 'id', value: id, in: 'path', style: 'simple', explode: false, dataType: 'string', dataFormat: undefined })}`; + 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 for persons by ID or name. + * @endpoint get /api/inse-service/persons/search + * @param authorId OpenAlex author ID (e.g., A5093075883) + * @param query Search query (e.g., Arman AND Arzani) + * @param include Comma-separated include tags: topics_full, topic_share, summary_stats, ids, last_known_institutions, sources, counts_by_year, works_api_url, dates, cited_by_count_boost + * @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 searchPersons( + authorId?: string, + query?: string, + include?: string, + observe?: 'body', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable; + public searchPersons( + authorId?: string, + query?: string, + include?: string, + observe?: 'response', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public searchPersons( + authorId?: string, + query?: string, + include?: string, + observe?: 'events', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public searchPersons( + authorId?: string, + query?: string, + include?: 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, + authorId, + 'author_id', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + query, + 'query', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + include, + 'include', + ); + + let localVarHeaders = this.defaultHeaders; + + const localVarHttpHeaderAcceptSelected: string | undefined = + options?.httpHeaderAccept ?? + this.configuration.selectHeaderAccept(['application/json']); + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set( + 'Accept', + localVarHttpHeaderAcceptSelected, + ); + } + + const localVarHttpContext: HttpContext = + options?.context ?? new HttpContext(); + + const localVarTransferCache: boolean = options?.transferCache ?? true; + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if ( + this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected) + ) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/api/inse-service/persons/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 for person by name. + * @endpoint get /api/inse-service/persons/autocomplete + * @param authorName Authors name (e.g., Arman Arzani) + * @param include Which data do we require? include tags: topics_full, topic_share, summary_stats, ids, last_known_institutions, ... + * @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 searchPersonsAutocomplete( + authorName: string, + include: string, + observe?: 'body', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable; + public searchPersonsAutocomplete( + authorName: string, + include: string, + observe?: 'response', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public searchPersonsAutocomplete( + authorName: string, + include: string, + observe?: 'events', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public searchPersonsAutocomplete( + authorName: string, + include: string, + observe: any = 'body', + reportProgress: boolean = false, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable { + if (authorName === null || authorName === undefined) { + throw new Error( + 'Required parameter authorName was null or undefined when calling searchPersonsAutocomplete.', + ); + } + if (include === null || include === undefined) { + throw new Error( + 'Required parameter include was null or undefined when calling searchPersonsAutocomplete.', + ); + } + + let localVarQueryParameters = new HttpParams({ encoder: this.encoder }); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + authorName, + 'author_name', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + include, + 'include', + ); + + let localVarHeaders = this.defaultHeaders; + + const localVarHttpHeaderAcceptSelected: string | undefined = + options?.httpHeaderAccept ?? + this.configuration.selectHeaderAccept(['application/json']); + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set( + 'Accept', + localVarHttpHeaderAcceptSelected, + ); + } + + const localVarHttpContext: HttpContext = + options?.context ?? new HttpContext(); + + const localVarTransferCache: boolean = options?.transferCache ?? true; + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if ( + this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected) + ) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/api/inse-service/persons/autocomplete`; + 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 for person by name. + * @endpoint get /api/inse-service/persons/autocomplete + * @param authorName Authors name (e.g., Arman Arzani) + * @param include Which data do we require? include tags: topics_full, topic_share, summary_stats, ids, last_known_institutions, ... + * @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 searchPersonsAutocomplete_2( + authorName: string, + include: string, + observe?: 'body', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable; + public searchPersonsAutocomplete_2( + authorName: string, + include: string, + observe?: 'response', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public searchPersonsAutocomplete_2( + authorName: string, + include: string, + observe?: 'events', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public searchPersonsAutocomplete_2( + authorName: string, + include: string, + observe: any = 'body', + reportProgress: boolean = false, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable { + if (authorName === null || authorName === undefined) { + throw new Error( + 'Required parameter authorName was null or undefined when calling searchPersonsAutocomplete_2.', + ); + } + if (include === null || include === undefined) { + throw new Error( + 'Required parameter include was null or undefined when calling searchPersonsAutocomplete_2.', + ); + } + + let localVarQueryParameters = new HttpParams({ encoder: this.encoder }); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + authorName, + 'author_name', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + include, + 'include', + ); + + let localVarHeaders = this.defaultHeaders; + + const localVarHttpHeaderAcceptSelected: string | undefined = + options?.httpHeaderAccept ?? + this.configuration.selectHeaderAccept(['application/json']); + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set( + 'Accept', + localVarHttpHeaderAcceptSelected, + ); + } + + const localVarHttpContext: HttpContext = + options?.context ?? new HttpContext(); + + const localVarTransferCache: boolean = options?.transferCache ?? true; + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if ( + this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected) + ) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/api/inse-service/persons/autocomplete`; + 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 for person by name. + * @endpoint get /api/inse-service/persons/searchByName + * @param authorName Authors name (e.g., Arman Arzani) + * @param include Which data do we require? include tags: topics_full, topic_share, summary_stats, ids, last_known_institutions, ... + * @param limit Limit of search page results + * @param pageOffset Offset of the result page + * @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 searchPersonsByName( + authorName: string, + include: string, + limit?: number, + pageOffset?: number, + observe?: 'body', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable; + public searchPersonsByName( + authorName: string, + include: string, + limit?: number, + pageOffset?: number, + observe?: 'response', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public searchPersonsByName( + authorName: string, + include: string, + limit?: number, + pageOffset?: number, + observe?: 'events', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public searchPersonsByName( + authorName: string, + include: string, + limit?: number, + pageOffset?: number, + observe: any = 'body', + reportProgress: boolean = false, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable { + if (authorName === null || authorName === undefined) { + throw new Error( + 'Required parameter authorName was null or undefined when calling searchPersonsByName.', + ); + } + if (include === null || include === undefined) { + throw new Error( + 'Required parameter include was null or undefined when calling searchPersonsByName.', + ); + } + + let localVarQueryParameters = new HttpParams({ encoder: this.encoder }); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + authorName, + 'author_name', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + include, + 'include', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + limit, + 'limit', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + pageOffset, + 'page_offset', + ); + + let localVarHeaders = this.defaultHeaders; + + const localVarHttpHeaderAcceptSelected: string | undefined = + options?.httpHeaderAccept ?? + this.configuration.selectHeaderAccept(['application/json']); + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set( + 'Accept', + localVarHttpHeaderAcceptSelected, + ); + } + + const localVarHttpContext: HttpContext = + options?.context ?? new HttpContext(); + + const localVarTransferCache: boolean = options?.transferCache ?? true; + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if ( + this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected) + ) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/api/inse-service/persons/searchByName`; + 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 for person by name. + * @endpoint get /api/inse-service/persons/searchByName + * @param authorName Authors name (e.g., Arman Arzani) + * @param include Which data do we require? include tags: topics_full, topic_share, summary_stats, ids, last_known_institutions, ... + * @param limit Limit of search page results + * @param pageOffset Offset of the result page + * @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 searchPersonsByName_3( + authorName: string, + include: string, + limit?: number, + pageOffset?: number, + observe?: 'body', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable; + public searchPersonsByName_3( + authorName: string, + include: string, + limit?: number, + pageOffset?: number, + observe?: 'response', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public searchPersonsByName_3( + authorName: string, + include: string, + limit?: number, + pageOffset?: number, + observe?: 'events', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public searchPersonsByName_3( + authorName: string, + include: string, + limit?: number, + pageOffset?: number, + observe: any = 'body', + reportProgress: boolean = false, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable { + if (authorName === null || authorName === undefined) { + throw new Error( + 'Required parameter authorName was null or undefined when calling searchPersonsByName_3.', + ); + } + if (include === null || include === undefined) { + throw new Error( + 'Required parameter include was null or undefined when calling searchPersonsByName_3.', + ); + } + + let localVarQueryParameters = new HttpParams({ encoder: this.encoder }); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + authorName, + 'author_name', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + include, + 'include', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + limit, + 'limit', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + pageOffset, + 'page_offset', + ); + + let localVarHeaders = this.defaultHeaders; + + const localVarHttpHeaderAcceptSelected: string | undefined = + options?.httpHeaderAccept ?? + this.configuration.selectHeaderAccept(['application/json']); + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set( + 'Accept', + localVarHttpHeaderAcceptSelected, + ); + } + + const localVarHttpContext: HttpContext = + options?.context ?? new HttpContext(); + + const localVarTransferCache: boolean = options?.transferCache ?? true; + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if ( + this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected) + ) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/api/inse-service/persons/searchByName`; + 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 for persons with advanced filters (Topic & Institution) and pagination. + * @endpoint get /api/inse-service/persons/search-list + * @param query Search query (e.g., Arman AND Arzani) + * @param institutionId Filter by OpenAlex institution ID + * @param sortBy Value to sort by + * @param sortOrder asc or desc? + * @param topic Filter by topic display names + * @param page Page number (1-indexed) + * @param pageSize Results per page + * @param include Comma-separated include tags + * @param yearFilterEnabled Apply the selected affiliation year rule + * @param filterMode Filter mode: \'in\' or \'from\' + * @param filterYear Filter year + * @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 searchPersonsList( + query?: string, + institutionId?: string, + sortBy?: string, + sortOrder?: string, + topic?: Array, + page?: number, + pageSize?: number, + include?: string, + yearFilterEnabled?: boolean, + filterMode?: string, + filterYear?: number, + observe?: 'body', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable; + public searchPersonsList( + query?: string, + institutionId?: string, + sortBy?: string, + sortOrder?: string, + topic?: Array, + page?: number, + pageSize?: number, + include?: string, + yearFilterEnabled?: boolean, + filterMode?: string, + filterYear?: number, + observe?: 'response', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public searchPersonsList( + query?: string, + institutionId?: string, + sortBy?: string, + sortOrder?: string, + topic?: Array, + page?: number, + pageSize?: number, + include?: string, + yearFilterEnabled?: boolean, + filterMode?: string, + filterYear?: number, + observe?: 'events', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public searchPersonsList( + query?: string, + institutionId?: string, + sortBy?: string, + sortOrder?: string, + topic?: Array, + page?: number, + pageSize?: number, + include?: string, + yearFilterEnabled?: boolean, + filterMode?: string, + filterYear?: 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, + query, + 'query', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + institutionId, + 'institutionId', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + sortBy, + 'sortBy', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + sortOrder, + 'sortOrder', + ); + if (topic) { + topic.forEach((element) => { + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + element, + 'topic', ); + }); + } + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + page, + 'page', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + pageSize, + 'pageSize', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + include, + 'include', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + yearFilterEnabled, + 'yearFilterEnabled', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + filterMode, + 'filterMode', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + filterYear, + 'filterYear', + ); + + let localVarHeaders = this.defaultHeaders; + + const localVarHttpHeaderAcceptSelected: string | undefined = + options?.httpHeaderAccept ?? + this.configuration.selectHeaderAccept(['application/json']); + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set( + 'Accept', + localVarHttpHeaderAcceptSelected, + ); } - /** - * Searches for person by ID. - * @endpoint get /api/inse-service/person/{id} - * @param id OpenAlex author ID - * @param include Which data do we require? include tags: topics_full, topic_share, summary_stats, ids, last_known_institutions, ... - * @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 getPersonByID(id: string, include?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; - public getPersonByID(id: string, include?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public getPersonByID(id: string, include?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public getPersonByID(id: string, include?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { - if (id === null || id === undefined) { - throw new Error('Required parameter id was null or undefined when calling getPersonByID.'); - } + const localVarHttpContext: HttpContext = + options?.context ?? new HttpContext(); - let localVarQueryParameters = new HttpParams({encoder: this.encoder}); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - include, 'include'); + const localVarTransferCache: boolean = options?.transferCache ?? true; - let localVarHeaders = this.defaultHeaders; + 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 localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([ - 'application/json' - ]); - if (localVarHttpHeaderAcceptSelected !== undefined) { - localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); - } + let localVarPath = `/api/inse-service/persons/search-list`; + 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 localVarHttpContext: HttpContext = options?.context ?? new HttpContext(); - - const localVarTransferCache: boolean = options?.transferCache ?? true; - - - let responseType_: 'text' | 'json' | 'blob' = 'json'; - if (localVarHttpHeaderAcceptSelected) { - if (localVarHttpHeaderAcceptSelected.startsWith('text')) { - responseType_ = 'text'; - } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { - responseType_ = 'json'; - } else { - responseType_ = 'blob'; - } - } - - let localVarPath = `/api/inse-service/person/${this.configuration.encodeParam({name: "id", value: id, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: undefined})}`; - 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 for persons with advanced filters (Topic & Institution) and pagination. + * @endpoint get /api/inse-service/persons/search-list + * @param query Search query (e.g., Arman AND Arzani) + * @param institutionId Filter by OpenAlex institution ID + * @param sortBy Value to sort by + * @param sortOrder asc or desc? + * @param topic Filter by topic display names + * @param page Page number (1-indexed) + * @param pageSize Results per page + * @param include Comma-separated include tags + * @param yearFilterEnabled Apply the selected affiliation year rule + * @param filterMode Filter mode: \'in\' or \'from\' + * @param filterYear Filter year + * @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 searchPersonsList_4( + query?: string, + institutionId?: string, + sortBy?: string, + sortOrder?: string, + topic?: Array, + page?: number, + pageSize?: number, + include?: string, + yearFilterEnabled?: boolean, + filterMode?: string, + filterYear?: number, + observe?: 'body', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable; + public searchPersonsList_4( + query?: string, + institutionId?: string, + sortBy?: string, + sortOrder?: string, + topic?: Array, + page?: number, + pageSize?: number, + include?: string, + yearFilterEnabled?: boolean, + filterMode?: string, + filterYear?: number, + observe?: 'response', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public searchPersonsList_4( + query?: string, + institutionId?: string, + sortBy?: string, + sortOrder?: string, + topic?: Array, + page?: number, + pageSize?: number, + include?: string, + yearFilterEnabled?: boolean, + filterMode?: string, + filterYear?: number, + observe?: 'events', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public searchPersonsList_4( + query?: string, + institutionId?: string, + sortBy?: string, + sortOrder?: string, + topic?: Array, + page?: number, + pageSize?: number, + include?: string, + yearFilterEnabled?: boolean, + filterMode?: string, + filterYear?: 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, + query, + 'query', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + institutionId, + 'institutionId', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + sortBy, + 'sortBy', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + sortOrder, + 'sortOrder', + ); + if (topic) { + topic.forEach((element) => { + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + element, + 'topic', ); + }); + } + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + page, + 'page', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + pageSize, + 'pageSize', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + include, + 'include', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + yearFilterEnabled, + 'yearFilterEnabled', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + filterMode, + 'filterMode', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + filterYear, + 'filterYear', + ); + + let localVarHeaders = this.defaultHeaders; + + const localVarHttpHeaderAcceptSelected: string | undefined = + options?.httpHeaderAccept ?? + this.configuration.selectHeaderAccept(['application/json']); + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set( + 'Accept', + localVarHttpHeaderAcceptSelected, + ); } - /** - * Searches for person by ID. - * @endpoint get /api/inse-service/person/{id} - * @param id OpenAlex author ID - * @param include Which data do we require? include tags: topics_full, topic_share, summary_stats, ids, last_known_institutions, ... - * @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 getPersonByID_1(id: string, include?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; - public getPersonByID_1(id: string, include?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public getPersonByID_1(id: string, include?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public getPersonByID_1(id: string, include?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { - if (id === null || id === undefined) { - throw new Error('Required parameter id was null or undefined when calling getPersonByID_1.'); - } + const localVarHttpContext: HttpContext = + options?.context ?? new HttpContext(); - let localVarQueryParameters = new HttpParams({encoder: this.encoder}); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - include, 'include'); + 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/inse-service/person/${this.configuration.encodeParam({name: "id", value: id, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: undefined})}`; - 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 for persons by ID or name. - * @endpoint get /api/inse-service/persons/search - * @param authorId OpenAlex author ID (e.g., A5093075883) - * @param query Search query (e.g., Arman AND Arzani) - * @param include Comma-separated include tags: topics_full, topic_share, summary_stats, ids, last_known_institutions, sources, counts_by_year, works_api_url, dates, cited_by_count_boost - * @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 searchPersons(authorId?: string, query?: string, include?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; - public searchPersons(authorId?: string, query?: string, include?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public searchPersons(authorId?: string, query?: string, include?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public searchPersons(authorId?: string, query?: string, include?: 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, - authorId, 'author_id'); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - query, 'query'); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - include, 'include'); - - let localVarHeaders = this.defaultHeaders; - - const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([ - 'application/json' - ]); - if (localVarHttpHeaderAcceptSelected !== undefined) { - localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); - } - - const localVarHttpContext: HttpContext = options?.context ?? new HttpContext(); - - const localVarTransferCache: boolean = options?.transferCache ?? true; - - - let responseType_: 'text' | 'json' | 'blob' = 'json'; - if (localVarHttpHeaderAcceptSelected) { - if (localVarHttpHeaderAcceptSelected.startsWith('text')) { - responseType_ = 'text'; - } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { - responseType_ = 'json'; - } else { - responseType_ = 'blob'; - } - } - - let localVarPath = `/api/inse-service/persons/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 for person by name. - * @endpoint get /api/inse-service/persons/autocomplete - * @param authorName Authors name (e.g., Arman Arzani) - * @param include Which data do we require? include tags: topics_full, topic_share, summary_stats, ids, last_known_institutions, ... - * @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 searchPersonsAutocomplete(authorName: string, include: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; - public searchPersonsAutocomplete(authorName: string, include: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public searchPersonsAutocomplete(authorName: string, include: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public searchPersonsAutocomplete(authorName: string, include: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { - if (authorName === null || authorName === undefined) { - throw new Error('Required parameter authorName was null or undefined when calling searchPersonsAutocomplete.'); - } - if (include === null || include === undefined) { - throw new Error('Required parameter include was null or undefined when calling searchPersonsAutocomplete.'); - } - - let localVarQueryParameters = new HttpParams({encoder: this.encoder}); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - authorName, 'author_name'); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - include, 'include'); - - let localVarHeaders = this.defaultHeaders; - - const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([ - 'application/json' - ]); - if (localVarHttpHeaderAcceptSelected !== undefined) { - localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); - } - - const localVarHttpContext: HttpContext = options?.context ?? new HttpContext(); - - const localVarTransferCache: boolean = options?.transferCache ?? true; - - - let responseType_: 'text' | 'json' | 'blob' = 'json'; - if (localVarHttpHeaderAcceptSelected) { - if (localVarHttpHeaderAcceptSelected.startsWith('text')) { - responseType_ = 'text'; - } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { - responseType_ = 'json'; - } else { - responseType_ = 'blob'; - } - } - - let localVarPath = `/api/inse-service/persons/autocomplete`; - 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 for person by name. - * @endpoint get /api/inse-service/persons/autocomplete - * @param authorName Authors name (e.g., Arman Arzani) - * @param include Which data do we require? include tags: topics_full, topic_share, summary_stats, ids, last_known_institutions, ... - * @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 searchPersonsAutocomplete_2(authorName: string, include: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; - public searchPersonsAutocomplete_2(authorName: string, include: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public searchPersonsAutocomplete_2(authorName: string, include: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public searchPersonsAutocomplete_2(authorName: string, include: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { - if (authorName === null || authorName === undefined) { - throw new Error('Required parameter authorName was null or undefined when calling searchPersonsAutocomplete_2.'); - } - if (include === null || include === undefined) { - throw new Error('Required parameter include was null or undefined when calling searchPersonsAutocomplete_2.'); - } - - let localVarQueryParameters = new HttpParams({encoder: this.encoder}); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - authorName, 'author_name'); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - include, 'include'); - - let localVarHeaders = this.defaultHeaders; - - const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([ - 'application/json' - ]); - if (localVarHttpHeaderAcceptSelected !== undefined) { - localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); - } - - const localVarHttpContext: HttpContext = options?.context ?? new HttpContext(); - - const localVarTransferCache: boolean = options?.transferCache ?? true; - - - let responseType_: 'text' | 'json' | 'blob' = 'json'; - if (localVarHttpHeaderAcceptSelected) { - if (localVarHttpHeaderAcceptSelected.startsWith('text')) { - responseType_ = 'text'; - } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { - responseType_ = 'json'; - } else { - responseType_ = 'blob'; - } - } - - let localVarPath = `/api/inse-service/persons/autocomplete`; - 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 for persons by institution name. - * @endpoint get /api/inse-service/persons/searchByInstitution - * @param institutionName Institution name (e.g., MIT, Oxford University) - * @param include Which data do we require? include tags: topics_full, topic_share, summary_stats, ids, last_known_institutions, ... - * @param limit Limit of search page results - * @param pageOffset Offset of the result page - * @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 searchPersonsByInstitution(institutionName: string, include: string, limit?: number, pageOffset?: number, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; - public searchPersonsByInstitution(institutionName: string, include: string, limit?: number, pageOffset?: number, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public searchPersonsByInstitution(institutionName: string, include: string, limit?: number, pageOffset?: number, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public searchPersonsByInstitution(institutionName: string, include: string, limit?: number, pageOffset?: number, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { - if (institutionName === null || institutionName === undefined) { - throw new Error('Required parameter institutionName was null or undefined when calling searchPersonsByInstitution.'); - } - if (include === null || include === undefined) { - throw new Error('Required parameter include was null or undefined when calling searchPersonsByInstitution.'); - } - - let localVarQueryParameters = new HttpParams({encoder: this.encoder}); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - institutionName, 'institution_name'); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - include, 'include'); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - limit, 'limit'); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - pageOffset, 'page_offset'); - - let localVarHeaders = this.defaultHeaders; - - const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([ - 'application/json' - ]); - if (localVarHttpHeaderAcceptSelected !== undefined) { - localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); - } - - const localVarHttpContext: HttpContext = options?.context ?? new HttpContext(); - - const localVarTransferCache: boolean = options?.transferCache ?? true; - - - let responseType_: 'text' | 'json' | 'blob' = 'json'; - if (localVarHttpHeaderAcceptSelected) { - if (localVarHttpHeaderAcceptSelected.startsWith('text')) { - responseType_ = 'text'; - } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { - responseType_ = 'json'; - } else { - responseType_ = 'blob'; - } - } - - let localVarPath = `/api/inse-service/persons/searchByInstitution`; - 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 for persons by institution name. - * @endpoint get /api/inse-service/persons/searchByInstitution - * @param institutionName Institution name (e.g., MIT, Oxford University) - * @param include Which data do we require? include tags: topics_full, topic_share, summary_stats, ids, last_known_institutions, ... - * @param limit Limit of search page results - * @param pageOffset Offset of the result page - * @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 searchPersonsByInstitution_3(institutionName: string, include: string, limit?: number, pageOffset?: number, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; - public searchPersonsByInstitution_3(institutionName: string, include: string, limit?: number, pageOffset?: number, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public searchPersonsByInstitution_3(institutionName: string, include: string, limit?: number, pageOffset?: number, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public searchPersonsByInstitution_3(institutionName: string, include: string, limit?: number, pageOffset?: number, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { - if (institutionName === null || institutionName === undefined) { - throw new Error('Required parameter institutionName was null or undefined when calling searchPersonsByInstitution_3.'); - } - if (include === null || include === undefined) { - throw new Error('Required parameter include was null or undefined when calling searchPersonsByInstitution_3.'); - } - - let localVarQueryParameters = new HttpParams({encoder: this.encoder}); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - institutionName, 'institution_name'); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - include, 'include'); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - limit, 'limit'); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - pageOffset, 'page_offset'); - - let localVarHeaders = this.defaultHeaders; - - const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([ - 'application/json' - ]); - if (localVarHttpHeaderAcceptSelected !== undefined) { - localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); - } - - const localVarHttpContext: HttpContext = options?.context ?? new HttpContext(); - - const localVarTransferCache: boolean = options?.transferCache ?? true; - - - let responseType_: 'text' | 'json' | 'blob' = 'json'; - if (localVarHttpHeaderAcceptSelected) { - if (localVarHttpHeaderAcceptSelected.startsWith('text')) { - responseType_ = 'text'; - } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { - responseType_ = 'json'; - } else { - responseType_ = 'blob'; - } - } - - let localVarPath = `/api/inse-service/persons/searchByInstitution`; - 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 for person by name. - * @endpoint get /api/inse-service/persons/searchByName - * @param authorName Authors name (e.g., Arman Arzani) - * @param include Which data do we require? include tags: topics_full, topic_share, summary_stats, ids, last_known_institutions, ... - * @param limit Limit of search page results - * @param pageOffset Offset of the result page - * @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 searchPersonsByName(authorName: string, include: string, limit?: number, pageOffset?: number, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; - public searchPersonsByName(authorName: string, include: string, limit?: number, pageOffset?: number, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public searchPersonsByName(authorName: string, include: string, limit?: number, pageOffset?: number, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public searchPersonsByName(authorName: string, include: string, limit?: number, pageOffset?: number, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { - if (authorName === null || authorName === undefined) { - throw new Error('Required parameter authorName was null or undefined when calling searchPersonsByName.'); - } - if (include === null || include === undefined) { - throw new Error('Required parameter include was null or undefined when calling searchPersonsByName.'); - } - - let localVarQueryParameters = new HttpParams({encoder: this.encoder}); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - authorName, 'author_name'); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - include, 'include'); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - limit, 'limit'); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - pageOffset, 'page_offset'); - - let localVarHeaders = this.defaultHeaders; - - const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([ - 'application/json' - ]); - if (localVarHttpHeaderAcceptSelected !== undefined) { - localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); - } - - const localVarHttpContext: HttpContext = options?.context ?? new HttpContext(); - - const localVarTransferCache: boolean = options?.transferCache ?? true; - - - let responseType_: 'text' | 'json' | 'blob' = 'json'; - if (localVarHttpHeaderAcceptSelected) { - if (localVarHttpHeaderAcceptSelected.startsWith('text')) { - responseType_ = 'text'; - } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { - responseType_ = 'json'; - } else { - responseType_ = 'blob'; - } - } - - let localVarPath = `/api/inse-service/persons/searchByName`; - 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 for person by name. - * @endpoint get /api/inse-service/persons/searchByName - * @param authorName Authors name (e.g., Arman Arzani) - * @param include Which data do we require? include tags: topics_full, topic_share, summary_stats, ids, last_known_institutions, ... - * @param limit Limit of search page results - * @param pageOffset Offset of the result page - * @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 searchPersonsByName_4(authorName: string, include: string, limit?: number, pageOffset?: number, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; - public searchPersonsByName_4(authorName: string, include: string, limit?: number, pageOffset?: number, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public searchPersonsByName_4(authorName: string, include: string, limit?: number, pageOffset?: number, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public searchPersonsByName_4(authorName: string, include: string, limit?: number, pageOffset?: number, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { - if (authorName === null || authorName === undefined) { - throw new Error('Required parameter authorName was null or undefined when calling searchPersonsByName_4.'); - } - if (include === null || include === undefined) { - throw new Error('Required parameter include was null or undefined when calling searchPersonsByName_4.'); - } - - let localVarQueryParameters = new HttpParams({encoder: this.encoder}); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - authorName, 'author_name'); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - include, 'include'); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - limit, 'limit'); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - pageOffset, 'page_offset'); - - let localVarHeaders = this.defaultHeaders; - - const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([ - 'application/json' - ]); - if (localVarHttpHeaderAcceptSelected !== undefined) { - localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); - } - - const localVarHttpContext: HttpContext = options?.context ?? new HttpContext(); - - const localVarTransferCache: boolean = options?.transferCache ?? true; - - - let responseType_: 'text' | 'json' | 'blob' = 'json'; - if (localVarHttpHeaderAcceptSelected) { - if (localVarHttpHeaderAcceptSelected.startsWith('text')) { - responseType_ = 'text'; - } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { - responseType_ = 'json'; - } else { - responseType_ = 'blob'; - } - } - - let localVarPath = `/api/inse-service/persons/searchByName`; - 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 for persons with advanced filters (Topic & Institution) and pagination. - * @endpoint get /api/inse-service/persons/search-list - * @param query Search query (e.g., Arman AND Arzani) - * @param institutionName Filter by institution name - * @param sortBy Value to sort by - * @param sortOrder asc or desc? - * @param topic Filter by topic display names - * @param page Page number (1-indexed) - * @param pageSize Results per page - * @param include Comma-separated include tags - * @param strict Strict institution search by target year - * @param filterMode Filter mode: \'in\' or \'from\' - * @param filterYear Filter year - * @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 searchPersonsList(query?: string, institutionName?: string, sortBy?: string, sortOrder?: string, topic?: Array, page?: number, pageSize?: number, include?: string, strict?: boolean, filterMode?: string, filterYear?: number, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; - public searchPersonsList(query?: string, institutionName?: string, sortBy?: string, sortOrder?: string, topic?: Array, page?: number, pageSize?: number, include?: string, strict?: boolean, filterMode?: string, filterYear?: number, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public searchPersonsList(query?: string, institutionName?: string, sortBy?: string, sortOrder?: string, topic?: Array, page?: number, pageSize?: number, include?: string, strict?: boolean, filterMode?: string, filterYear?: number, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public searchPersonsList(query?: string, institutionName?: string, sortBy?: string, sortOrder?: string, topic?: Array, page?: number, pageSize?: number, include?: string, strict?: boolean, filterMode?: string, filterYear?: 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, - query, 'query'); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - institutionName, 'institutionName'); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - sortBy, 'sortBy'); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - sortOrder, 'sortOrder'); - if (topic) { - topic.forEach((element) => { - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - element, 'topic'); - }) - } - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - page, 'page'); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - pageSize, 'pageSize'); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - include, 'include'); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - strict, 'strict'); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - filterMode, 'filterMode'); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - filterYear, 'filterYear'); - - let localVarHeaders = this.defaultHeaders; - - const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([ - 'application/json' - ]); - if (localVarHttpHeaderAcceptSelected !== undefined) { - localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); - } - - const localVarHttpContext: HttpContext = options?.context ?? new HttpContext(); - - const localVarTransferCache: boolean = options?.transferCache ?? true; - - - let responseType_: 'text' | 'json' | 'blob' = 'json'; - if (localVarHttpHeaderAcceptSelected) { - if (localVarHttpHeaderAcceptSelected.startsWith('text')) { - responseType_ = 'text'; - } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { - responseType_ = 'json'; - } else { - responseType_ = 'blob'; - } - } - - let localVarPath = `/api/inse-service/persons/search-list`; - 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 for persons with advanced filters (Topic & Institution) and pagination. - * @endpoint get /api/inse-service/persons/search-list - * @param query Search query (e.g., Arman AND Arzani) - * @param institutionName Filter by institution name - * @param sortBy Value to sort by - * @param sortOrder asc or desc? - * @param topic Filter by topic display names - * @param page Page number (1-indexed) - * @param pageSize Results per page - * @param include Comma-separated include tags - * @param strict Strict institution search by target year - * @param filterMode Filter mode: \'in\' or \'from\' - * @param filterYear Filter year - * @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 searchPersonsList_5(query?: string, institutionName?: string, sortBy?: string, sortOrder?: string, topic?: Array, page?: number, pageSize?: number, include?: string, strict?: boolean, filterMode?: string, filterYear?: number, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; - public searchPersonsList_5(query?: string, institutionName?: string, sortBy?: string, sortOrder?: string, topic?: Array, page?: number, pageSize?: number, include?: string, strict?: boolean, filterMode?: string, filterYear?: number, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public searchPersonsList_5(query?: string, institutionName?: string, sortBy?: string, sortOrder?: string, topic?: Array, page?: number, pageSize?: number, include?: string, strict?: boolean, filterMode?: string, filterYear?: number, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public searchPersonsList_5(query?: string, institutionName?: string, sortBy?: string, sortOrder?: string, topic?: Array, page?: number, pageSize?: number, include?: string, strict?: boolean, filterMode?: string, filterYear?: 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, - query, 'query'); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - institutionName, 'institutionName'); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - sortBy, 'sortBy'); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - sortOrder, 'sortOrder'); - if (topic) { - topic.forEach((element) => { - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - element, 'topic'); - }) - } - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - page, 'page'); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - pageSize, 'pageSize'); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - include, 'include'); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - strict, 'strict'); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - filterMode, 'filterMode'); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - filterYear, 'filterYear'); - - let localVarHeaders = this.defaultHeaders; - - const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([ - 'application/json' - ]); - if (localVarHttpHeaderAcceptSelected !== undefined) { - localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); - } - - const localVarHttpContext: HttpContext = options?.context ?? new HttpContext(); - - const localVarTransferCache: boolean = options?.transferCache ?? true; - - - let responseType_: 'text' | 'json' | 'blob' = 'json'; - if (localVarHttpHeaderAcceptSelected) { - if (localVarHttpHeaderAcceptSelected.startsWith('text')) { - responseType_ = 'text'; - } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { - responseType_ = 'json'; - } else { - responseType_ = 'blob'; - } - } - - let localVarPath = `/api/inse-service/persons/search-list`; - 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'; + } } + let localVarPath = `/api/inse-service/persons/search-list`; + 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/projects.service.ts b/webapp/src/app/api/api/projects.service.ts index 57111cb9..a63fc5bc 100644 --- a/webapp/src/app/api/api/projects.service.ts +++ b/webapp/src/app/api/api/projects.service.ts @@ -33,8 +33,14 @@ import { DfgProjectDetails } from '../model/dfgProjectDetails'; // @ts-ignore import { DfgProjectPage } from '../model/dfgProjectPage'; // @ts-ignore +import { EuCordisOrganizationSelectorPage } from '../model/euCordisOrganizationSelectorPage'; +// @ts-ignore import { EuCordisProjectResponse } from '../model/euCordisProjectResponse'; // @ts-ignore +import { EuCordisProjectSearchPage } from '../model/euCordisProjectSearchPage'; +// @ts-ignore +import { EuCordisProjectType } from '../model/euCordisProjectType'; +// @ts-ignore import { EuOrganizationProjectSummaryPage } from '../model/euOrganizationProjectSummaryPage'; // @ts-ignore import { FundingProjectPage } from '../model/fundingProjectPage'; @@ -331,6 +337,238 @@ export class ProjectsService extends BaseService { ); } + /** + * Returns EU CORDIS organizations based on a search term. + * @endpoint get /api/eu/organizations/autocomplete/selector + * @param query Search term for organization autocomplete. + * @param page + * @param size + * @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 getEuOrganizationAutocompleteForSelector( + query?: string, + page?: number, + size?: number, + observe?: 'body', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable; + public getEuOrganizationAutocompleteForSelector( + query?: string, + page?: number, + size?: number, + observe?: 'response', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public getEuOrganizationAutocompleteForSelector( + query?: string, + page?: number, + size?: number, + observe?: 'events', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public getEuOrganizationAutocompleteForSelector( + query?: string, + page?: number, + size?: 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, + query, + 'query', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + page, + 'page', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + size, + 'size', + ); + + 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/eu/organizations/autocomplete/selector`; + 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 EU CORDIS organizations by organisation IDs. + * @endpoint get /api/eu/organizations/ids + * @param organizationIds CORDIS organisation IDs 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 getEuOrganizationsByIds( + organizationIds?: Array, + observe?: 'body', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable; + public getEuOrganizationsByIds( + organizationIds?: Array, + observe?: 'response', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public getEuOrganizationsByIds( + organizationIds?: Array, + observe?: 'events', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public getEuOrganizationsByIds( + organizationIds?: Array, + observe: any = 'body', + reportProgress: boolean = false, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable { + let localVarQueryParameters = new HttpParams({ encoder: this.encoder }); + if (organizationIds) { + organizationIds.forEach((element) => { + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + element, + 'organization_ids', + ); + }); + } + + 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/eu/organizations/ids`; + 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 EU projects for an author. * Returns a list of EU projects associated with the specified author ID. @@ -1201,6 +1439,353 @@ export class ProjectsService extends BaseService { ); } + /** + * Search EU CORDIS projects. + * Returns a page of EU CORDIS project summaries across FP7, Horizon 2020 and Horizon Europe. + * @endpoint get /api/projects/eu/search + * @param authorId OpenAlex author ID to filter by. + * @param authorIds Additional OpenAlex author IDs to filter by. All selected authors must match. + * @param organizationIds CORDIS organisation IDs. All selected organizations must match. + * @param organizationNames CORDIS organization names. All selected organizations must match. + * @param projectTypes Project types to include: fp7, h2020, heu. + * @param title Project title/acronym search. + * @param keywords Raw keywords to search in title/objective/keywords/topics. + * @param topicIds OpenAlex topic IDs used for fuzzy topic resolution. + * @param filterTopicIds Additional OpenAlex topic IDs used as mandatory filters. + * @param fundingStartYears Funding start years. + * @param fundingEndYears Funding end years. + * @param countries Organization countries. + * @param frameworkProgrammes Framework programme filters. + * @param fundingSchemes Funding scheme filters. + * @param statuses Project status filters. + * @param page The page number. + * @param size The page size. + * @param sortBy Sort field. + * @param sortDirection Sort direction: asc or desc. + * @param fuzzy Use OpenAlex topic-id resolution if true, otherwise raw keyword search. + * @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 searchEuCordisProjectsSummary( + authorId?: string, + authorIds?: Array, + organizationIds?: Array, + organizationNames?: Array, + projectTypes?: Array, + title?: string, + keywords?: Array, + topicIds?: Array, + filterTopicIds?: Array, + fundingStartYears?: Array, + fundingEndYears?: Array, + countries?: Array, + frameworkProgrammes?: Array, + fundingSchemes?: Array, + statuses?: Array, + page?: number, + size?: number, + sortBy?: string, + sortDirection?: string, + fuzzy?: boolean, + observe?: 'body', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable; + public searchEuCordisProjectsSummary( + authorId?: string, + authorIds?: Array, + organizationIds?: Array, + organizationNames?: Array, + projectTypes?: Array, + title?: string, + keywords?: Array, + topicIds?: Array, + filterTopicIds?: Array, + fundingStartYears?: Array, + fundingEndYears?: Array, + countries?: Array, + frameworkProgrammes?: Array, + fundingSchemes?: Array, + statuses?: Array, + page?: number, + size?: number, + sortBy?: string, + sortDirection?: string, + fuzzy?: boolean, + observe?: 'response', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public searchEuCordisProjectsSummary( + authorId?: string, + authorIds?: Array, + organizationIds?: Array, + organizationNames?: Array, + projectTypes?: Array, + title?: string, + keywords?: Array, + topicIds?: Array, + filterTopicIds?: Array, + fundingStartYears?: Array, + fundingEndYears?: Array, + countries?: Array, + frameworkProgrammes?: Array, + fundingSchemes?: Array, + statuses?: Array, + page?: number, + size?: number, + sortBy?: string, + sortDirection?: string, + fuzzy?: boolean, + observe?: 'events', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public searchEuCordisProjectsSummary( + authorId?: string, + authorIds?: Array, + organizationIds?: Array, + organizationNames?: Array, + projectTypes?: Array, + title?: string, + keywords?: Array, + topicIds?: Array, + filterTopicIds?: Array, + fundingStartYears?: Array, + fundingEndYears?: Array, + countries?: Array, + frameworkProgrammes?: Array, + fundingSchemes?: Array, + statuses?: Array, + page?: number, + size?: number, + sortBy?: string, + sortDirection?: string, + fuzzy?: boolean, + 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, + authorId, + 'author_id', + ); + if (authorIds) { + authorIds.forEach((element) => { + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + element, + 'author_ids', + ); + }); + } + if (organizationIds) { + organizationIds.forEach((element) => { + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + element, + 'organization_ids', + ); + }); + } + if (organizationNames) { + organizationNames.forEach((element) => { + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + element, + 'organization_names', + ); + }); + } + if (projectTypes) { + projectTypes.forEach((element) => { + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + element, + 'project_types', + ); + }); + } + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + title, + 'title', + ); + if (keywords) { + keywords.forEach((element) => { + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + element, + 'keywords', + ); + }); + } + if (topicIds) { + topicIds.forEach((element) => { + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + element, + 'topic_ids', + ); + }); + } + if (filterTopicIds) { + filterTopicIds.forEach((element) => { + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + element, + 'filter_topic_ids', + ); + }); + } + if (fundingStartYears) { + fundingStartYears.forEach((element) => { + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + element, + 'funding_start_years', + ); + }); + } + if (fundingEndYears) { + fundingEndYears.forEach((element) => { + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + element, + 'funding_end_years', + ); + }); + } + if (countries) { + countries.forEach((element) => { + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + element, + 'countries', + ); + }); + } + if (frameworkProgrammes) { + frameworkProgrammes.forEach((element) => { + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + element, + 'framework_programmes', + ); + }); + } + if (fundingSchemes) { + fundingSchemes.forEach((element) => { + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + element, + 'funding_schemes', + ); + }); + } + if (statuses) { + statuses.forEach((element) => { + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + element, + 'statuses', + ); + }); + } + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + page, + 'page', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + size, + 'size', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + sortBy, + 'sort_by', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + sortDirection, + 'sort_direction', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + fuzzy, + 'fuzzy', + ); + + 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/projects/eu/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, + }, + ); + } + /** * Search projects across all funders. * Returns a page of projects across all funders based on the provided pagination parameters and optional institution filter. diff --git a/webapp/src/app/api/model/careerStage.ts b/webapp/src/app/api/model/careerStage.ts new file mode 100644 index 00000000..d2a4e844 --- /dev/null +++ b/webapp/src/app/api/model/careerStage.ts @@ -0,0 +1,20 @@ +/** + * 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 const CareerStage = { + Unknown: 'unknown', + Early: 'Early', + Emerging: 'Emerging', + Established: 'Established', + Senior: 'Senior' +} as const; +export type CareerStage = typeof CareerStage[keyof typeof CareerStage]; + diff --git a/webapp/src/app/api/model/companyConnectionsAvailability.ts b/webapp/src/app/api/model/companyConnectionsAvailability.ts new file mode 100644 index 00000000..cefa8680 --- /dev/null +++ b/webapp/src/app/api/model/companyConnectionsAvailability.ts @@ -0,0 +1,13 @@ +/** + * 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 CompanyConnectionsAvailability { + available: boolean; +} diff --git a/webapp/src/app/api/model/companyConnectionsResponse.ts b/webapp/src/app/api/model/companyConnectionsResponse.ts index 9beabd1e..9b86a710 100644 --- a/webapp/src/app/api/model/companyConnectionsResponse.ts +++ b/webapp/src/app/api/model/companyConnectionsResponse.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,17 +9,12 @@ */ import { CompanyConnection } from './companyConnection'; - -export interface CompanyConnectionsResponse { - author_id: string; - display_name?: string | null; - is_ude_author: boolean; - institution_scope?: string | null; - matching_institutions?: Array; - matching_method?: string | null; - company_count: number; - has_more_results: boolean; - common_name_warning: boolean; - connections?: Array; +export interface CompanyConnectionsResponse { + author_id: string; + display_name?: string | null; + matching_method?: string | null; + company_count: number; + has_more_results: boolean; + common_name_warning: boolean; + connections?: Array; } - diff --git a/webapp/src/app/api/model/companyStatusFilter.ts b/webapp/src/app/api/model/companyStatusFilter.ts new file mode 100644 index 00000000..7d4355e7 --- /dev/null +++ b/webapp/src/app/api/model/companyStatusFilter.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. + */ + + +export const CompanyStatusFilter = { + All: 'all', + Active: 'active', + Deleted: 'deleted' +} as const; +export type CompanyStatusFilter = typeof CompanyStatusFilter[keyof typeof CompanyStatusFilter]; + diff --git a/webapp/src/app/api/model/dfgProjectSummary.ts b/webapp/src/app/api/model/dfgProjectSummary.ts index cc1d2b59..c68e8926 100644 --- a/webapp/src/app/api/model/dfgProjectSummary.ts +++ b/webapp/src/app/api/model/dfgProjectSummary.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 @@ -12,28 +12,30 @@ import { DFGProjectFachgebieteInner } from './dFGProjectFachgebieteInner'; import { Topic } from './topic'; import { DfgPersonSummary } from './dfgPersonSummary'; -export interface DfgProjectSummary { - /** - * The unique identifier of the DFG project. - */ - id: string; - link?: string | null; - title?: string | null; - professional_classification?: string | null; - funding_start?: string | null; - funding_end?: string | null; - /** - * Institutions associated with the project. - */ - institutions?: Array; - /** - * The names of the persons involved in the DFG project. - */ - names?: Array; - /** - * The persons involved in the DFG project. - */ - persons?: Array; - subject_classifications?: Array | null; - topics?: Array | null; + +export interface DfgProjectSummary { + /** + * The unique identifier of the DFG project. + */ + id: string; + link?: string | null; + title?: string | null; + professional_classification?: string | null; + funding_start?: string | null; + funding_end?: string | null; + /** + * Institutions associated with the project. + */ + institutions?: Array; + /** + * The names of the persons involved in the DFG project. + */ + names?: Array; + /** + * The persons involved in the DFG project. + */ + persons?: Array; + subject_classifications?: Array | null; + topics?: Array | null; } + diff --git a/webapp/src/app/api/model/euCordisEurosciVocSummary.ts b/webapp/src/app/api/model/euCordisEurosciVocSummary.ts new file mode 100644 index 00000000..c45f9b09 --- /dev/null +++ b/webapp/src/app/api/model/euCordisEurosciVocSummary.ts @@ -0,0 +1,20 @@ +/** + * 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 EuCordisEurosciVocSummary { + id?: string | null; + project_id?: string | null; + code?: string | null; + title?: string | null; + description?: string | null; + path?: string | null; +} + diff --git a/webapp/src/app/api/model/euCordisOrganizationSelectorPage.ts b/webapp/src/app/api/model/euCordisOrganizationSelectorPage.ts new file mode 100644 index 00000000..824bf430 --- /dev/null +++ b/webapp/src/app/api/model/euCordisOrganizationSelectorPage.ts @@ -0,0 +1,28 @@ +/** + * 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 { EuCordisOrganizationSelectorSummary } from './euCordisOrganizationSelectorSummary'; + + +export interface EuCordisOrganizationSelectorPage { + /** + * The current page number. + */ + page?: number; + /** + * The requested page size. + */ + size?: number; + /** + * The total number of items. + */ + total?: number; + elements?: Array; +} + diff --git a/webapp/src/app/api/model/euCordisOrganizationSelectorSummary.ts b/webapp/src/app/api/model/euCordisOrganizationSelectorSummary.ts new file mode 100644 index 00000000..647c7a90 --- /dev/null +++ b/webapp/src/app/api/model/euCordisOrganizationSelectorSummary.ts @@ -0,0 +1,25 @@ +/** + * 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 { EuCordisProjectType } from './euCordisProjectType'; + + +export interface EuCordisOrganizationSelectorSummary { + id?: string | null; + organisation_id?: string | null; + name?: string | null; + short_name?: string | null; + country?: string | null; + city?: string | null; + project_type?: EuCordisProjectType | null; +} +export namespace EuCordisOrganizationSelectorSummary { +} + + diff --git a/webapp/src/app/api/model/euCordisOrganizationSummary.ts b/webapp/src/app/api/model/euCordisOrganizationSummary.ts new file mode 100644 index 00000000..7fe70356 --- /dev/null +++ b/webapp/src/app/api/model/euCordisOrganizationSummary.ts @@ -0,0 +1,25 @@ +/** + * 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 EuCordisOrganizationSummary { + id?: string | null; + organisation_id?: string | null; + name?: string | null; + short_name?: string | null; + country?: string | null; + city?: string | null; + role?: string | null; + activity_type?: string | null; + project_id?: string | null; + ec_contribution?: number | null; + total_cost?: number | null; +} + diff --git a/webapp/src/app/api/model/euCordisProjectSearchPage.ts b/webapp/src/app/api/model/euCordisProjectSearchPage.ts new file mode 100644 index 00000000..c78066c6 --- /dev/null +++ b/webapp/src/app/api/model/euCordisProjectSearchPage.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 { EuCordisProjectSummary } from './euCordisProjectSummary'; + + +export interface EuCordisProjectSearchPage { + /** + * The current page number. + */ + page?: number; + /** + * The requested page size. + */ + size?: number; + /** + * The total number of items. + */ + total?: number; + /** + * The EU CORDIS project summaries on this page. + */ + elements?: Array; +} + diff --git a/webapp/src/app/api/model/euCordisProjectSummary.ts b/webapp/src/app/api/model/euCordisProjectSummary.ts new file mode 100644 index 00000000..41197749 --- /dev/null +++ b/webapp/src/app/api/model/euCordisProjectSummary.ts @@ -0,0 +1,44 @@ +/** + * 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 { EuCordisTopicSummary } from './euCordisTopicSummary'; +import { AuthorPage } from './authorPage'; +import { EuCordisEurosciVocSummary } from './euCordisEurosciVocSummary'; +import { Topic } from './topic'; +import { EuCordisOrganizationSummary } from './euCordisOrganizationSummary'; +import { EuCordisProjectType } from './euCordisProjectType'; + + +export interface EuCordisProjectSummary { + id: string; + project_type: EuCordisProjectType; + title?: string | null; + acronym?: string | null; + objective?: string | null; + keywords?: string | null; + framework_programme?: string | null; + funding_scheme?: string | null; + status?: string | null; + start_date?: string | null; + end_date?: string | null; + ec_max_contribution?: number | null; + total_cost?: number | null; + authors?: AuthorPage | null; + organizations?: Array; + cordis_topics?: Array; + eurosci_voc?: Array; + /** + * Mapped OpenAlex topics. + */ + topics?: Array; +} +export namespace EuCordisProjectSummary { +} + + diff --git a/webapp/src/app/api/model/euCordisProjectType.ts b/webapp/src/app/api/model/euCordisProjectType.ts new file mode 100644 index 00000000..7720922b --- /dev/null +++ b/webapp/src/app/api/model/euCordisProjectType.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. + */ + + +export const EuCordisProjectType = { + Fp7: 'fp7', + H2020: 'h2020', + Heu: 'heu' +} as const; +export type EuCordisProjectType = typeof EuCordisProjectType[keyof typeof EuCordisProjectType]; + diff --git a/webapp/src/app/api/model/euCordisTopicSummary.ts b/webapp/src/app/api/model/euCordisTopicSummary.ts new file mode 100644 index 00000000..c13fbb8b --- /dev/null +++ b/webapp/src/app/api/model/euCordisTopicSummary.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. + */ + + +export interface EuCordisTopicSummary { + id?: string | null; + project_id?: string | null; + title?: string | null; + topic?: string | null; +} + diff --git a/webapp/src/app/api/model/filterType.ts b/webapp/src/app/api/model/filterType.ts new file mode 100644 index 00000000..bee9d0d7 --- /dev/null +++ b/webapp/src/app/api/model/filterType.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. + */ + + +export const FilterType = { + Keyword: 'keyword', + Topic: 'topic' +} as const; +export type FilterType = typeof FilterType[keyof typeof FilterType]; + diff --git a/webapp/src/app/api/model/keywordOperator.ts b/webapp/src/app/api/model/keywordOperator.ts new file mode 100644 index 00000000..d4d4bf1f --- /dev/null +++ b/webapp/src/app/api/model/keywordOperator.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. + */ + + +export const KeywordOperator = { + And: 'and', + Or: 'or' +} as const; +export type KeywordOperator = typeof KeywordOperator[keyof typeof KeywordOperator]; + diff --git a/webapp/src/app/api/model/keywordToAuthorRequest.ts b/webapp/src/app/api/model/keywordToAuthorRequest.ts index 9d34e1d9..97edef03 100644 --- a/webapp/src/app/api/model/keywordToAuthorRequest.ts +++ b/webapp/src/app/api/model/keywordToAuthorRequest.ts @@ -26,10 +26,6 @@ export interface KeywordToAuthorRequest { * What the \'keywords\' values match against: \'keyword\' or \'topic\'. Defaults to \'keyword\'. */ filter_type?: string; - /** - * The selected institution display name. (Default Uni-Due) - */ - institution_name?: string; /** * Optional filter: only keep authors in one of these career stages. */ diff --git a/webapp/src/app/api/model/models.ts b/webapp/src/app/api/model/models.ts index 6eefd7b1..d85f7041 100644 --- a/webapp/src/app/api/model/models.ts +++ b/webapp/src/app/api/model/models.ts @@ -34,6 +34,7 @@ export * from './collaborationNetwork'; export * from './collaborationNetworkEdge'; export * from './collaborationNetworkNodeType'; export * from './companyConnection'; +export * from './companyConnectionsAvailability'; export * from './companyConnectionsResponse'; export * from './cordisEuProject'; export * from './cordisEuProjectPage'; @@ -57,7 +58,15 @@ export * from './dfgPersonSummaryPage'; export * from './dfgProjectDetails'; export * from './dfgProjectPage'; export * from './dfgProjectSummary'; +export * from './euCordisEurosciVocSummary'; +export * from './euCordisOrganizationSelectorPage'; +export * from './euCordisOrganizationSelectorSummary'; +export * from './euCordisOrganizationSummary'; export * from './euCordisProjectResponse'; +export * from './euCordisProjectSearchPage'; +export * from './euCordisProjectSummary'; +export * from './euCordisProjectType'; +export * from './euCordisTopicSummary'; export * from './euOrganizationProjectSummary'; export * from './euOrganizationProjectSummaryPage'; export * from './euProjectData'; diff --git a/webapp/src/app/api/model/publicationType.ts b/webapp/src/app/api/model/publicationType.ts new file mode 100644 index 00000000..753c47e8 --- /dev/null +++ b/webapp/src/app/api/model/publicationType.ts @@ -0,0 +1,39 @@ +/** + * 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 const PublicationType = { + Article: 'article', + Other: 'other', + Dataset: 'dataset', + BookChapter: 'book-chapter', + Book: 'book', + Dissertation: 'dissertation', + Preprint: 'preprint', + Paratext: 'paratext', + Libguides: 'libguides', + Review: 'review', + Letter: 'letter', + ReferenceEntry: 'reference-entry', + Editorial: 'editorial', + PeerReview: 'peer-review', + Report: 'report', + Standard: 'standard', + Erratum: 'erratum', + Retraction: 'retraction', + SupplementaryMaterials: 'supplementary-materials', + BookSection: 'book-section', + Database: 'database', + Software: 'software', + ReportComponent: 'report-component', + Grant: 'grant' +} as const; +export type PublicationType = typeof PublicationType[keyof typeof PublicationType]; + diff --git a/webapp/src/app/api/model/selectedAuthorsRequest.ts b/webapp/src/app/api/model/selectedAuthorsRequest.ts new file mode 100644 index 00000000..79f008fe --- /dev/null +++ b/webapp/src/app/api/model/selectedAuthorsRequest.ts @@ -0,0 +1,42 @@ +/** + * 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 { Timespan } from './timespan'; +import { FilterType } from './filterType'; +import { KeywordOperator } from './keywordOperator'; +import { PublicationType } from './publicationType'; + + +export interface SelectedAuthorsRequest { + /** + * OpenAlex IDs of the authors to rank. + */ + author_ids: Array; + /** + * One or more keywords defining the topic. + */ + keywords: Array; + /** + * How to combine the keywords: \'and\' or \'or\'. Defaults to \'and\'. + */ + operator?: KeywordOperator; + /** + * What the \'keywords\' values match against: \'keyword\' (OpenAlex keyword display names) or \'topic\' (OpenAlex topic ids). Defaults to \'keyword\'. + */ + filter_type?: FilterType; + /** + * Optional filter: only count works of these publication types. Empty = no filter. + */ + publication_types?: Array; + timespan?: Timespan | null; +} +export namespace SelectedAuthorsRequest { +} + + diff --git a/webapp/src/app/api/model/subfieldShare.ts b/webapp/src/app/api/model/subfieldShare.ts new file mode 100644 index 00000000..83185941 --- /dev/null +++ b/webapp/src/app/api/model/subfieldShare.ts @@ -0,0 +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. + */ + + +export interface SubfieldShare { + /** + * The subfield display name. + */ + name: string; + /** + * Number of works whose primary topic belongs to this subfield. + */ + count: number; +} + diff --git a/webapp/src/app/api/model/timespan.ts b/webapp/src/app/api/model/timespan.ts new file mode 100644 index 00000000..c44eee8a --- /dev/null +++ b/webapp/src/app/api/model/timespan.ts @@ -0,0 +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. + */ + + +export interface Timespan { + /** + * Start year (inclusive). + */ + from: number; + /** + * End year (inclusive). + */ + to: number; +} + diff --git a/webapp/src/app/app.routes.ts b/webapp/src/app/app.routes.ts index 5afe8de7..3ac157fe 100644 --- a/webapp/src/app/app.routes.ts +++ b/webapp/src/app/app.routes.ts @@ -41,11 +41,16 @@ import { SearchResultsStateService } from './modules/keywords-search/search-resu import { roleGuard } from './shared/guards/role.guard'; import { UserRole } from './api'; import { personCordisEuProjectPageResolver } from './resolvers/person-cordis-eu-project-page.resolver'; +import { euCordisProjectsResolver } from './resolvers/eu-cordis-projects.resolver'; import { selectedAuthorsResolver } from './resolvers/selected-authors.resolver'; import { workClassificationResolver } from './resolvers/work-classification.resolver'; import { selectedDfgAuthorsResolver } from './resolvers/selected-dfg-authors.resolver'; import { selectedDfgInstitutionsResolver } from './resolvers/selected-dfg-institutions.resolver'; import { primaryCategoryYearAggregationPageResolver } from './resolvers/primary-category-year-aggregation-page.resolver'; +import { selectedEuInstitutionsResolver } from './resolvers/selected-eu-institutions.resolver'; +import { uniTrendResolver } from './resolvers/uni-trend.resolver'; +import { EuProjectsComponent } from './shared/ui/eu-projects/eu-projects.component'; +import { DfgProjectsComponent } from './shared/ui/dfg-projects/dfg-projects.component'; export const routes: Routes = [ { path: '', @@ -142,6 +147,7 @@ export const routes: Routes = [ 'query', 'page', 'pageSize', + 'institutionId', 'institutionName', 'sortBy', 'sortOrder', @@ -188,19 +194,41 @@ export const routes: Routes = [ { path: 'projects', component: KeywordsToProjectsResultsComponent, - runGuardsAndResolvers: 'always', - resolve: { - dfgProjectPage: dfgProjectsResolver, - personCordisEuProjectPage: personCordisEuProjectPageResolver, - selectedDfgInstitutionsPage: selectedDfgInstitutionsResolver, - selectedDfgAuthorsPage: selectedDfgAuthorsResolver, - selectedTopicsPage: selectedTopicsResolver, - selectedEuInstitutionsPage: selectedInstitutionsResolver, - selectedEuAuthorsPage: selectedAuthorsResolver, - }, - data: { - resolvingFor: RESOLVING_PROJECT_PAGE_FOR.KEYWORDS_SEARCH, - }, + children: [ + { + path: '', + pathMatch: 'full', + redirectTo: 'dfg', + }, + { + path: 'dfg', + component: DfgProjectsComponent, + resolve: { + dfgProjectPage: dfgProjectsResolver, + selectedDfgInstitutionsPage: selectedDfgInstitutionsResolver, + selectedDfgAuthorsPage: selectedDfgAuthorsResolver, + selectedTopicsPage: selectedTopicsResolver, + }, + runGuardsAndResolvers: 'always', + data: { + resolvingFor: RESOLVING_PROJECT_PAGE_FOR.KEYWORDS_SEARCH, + }, + }, + { + path: 'eu', + component: EuProjectsComponent, + resolve: { + euCordisProjectPage: euCordisProjectsResolver, + selectedEuInstitutionsPage: selectedEuInstitutionsResolver, + selectedEuAuthorsPage: selectedAuthorsResolver, + selectedTopicsPage: selectedTopicsResolver, + }, + runGuardsAndResolvers: 'always', + data: { + resolvingFor: RESOLVING_PROJECT_PAGE_FOR.KEYWORDS_SEARCH, + }, + }, + ], }, { path: 'patents', component: KeywordsToPatentsResultsComponent }, { @@ -218,7 +246,30 @@ export const routes: Routes = [ }, }, { path: 'news', component: KeywordsToNewsResultsComponent }, - { path: 'trends', component: UniTrendParentComponent }, + { + path: 'trends', + component: UniTrendParentComponent, + resolve: { + trendData: uniTrendResolver, + }, + runGuardsAndResolvers: (from, to) => { + const keys = [ + 'search_type', + 'topic', + 'topics', + 'keyword', + 'keywords', + 'institutions', + 'countries', + 'regions', + 'authors', + 'fuzzy', + ]; + return keys.some( + (key) => from.queryParamMap.get(key) !== to.queryParamMap.get(key), + ); + }, + }, ], }, { @@ -417,19 +468,41 @@ export const routes: Routes = [ import('./modules/person-projects/person-projects.component').then( (mod) => mod.PersonProjectsComponent, ), - resolve: { - dfgProjectPage: dfgProjectsResolver, - personCordisEuProjectPage: personCordisEuProjectPageResolver, - selectedDfgInstitutionsPage: selectedDfgInstitutionsResolver, - selectedDfgAuthorsPage: selectedDfgAuthorsResolver, - selectedTopicsPage: selectedTopicsResolver, - selectedEuInstitutionsPage: selectedInstitutionsResolver, - selectedEuAuthorsPage: selectedAuthorsResolver, - }, - runGuardsAndResolvers: 'always', - data: { - resolvingFor: RESOLVING_PROJECT_PAGE_FOR.PERSON, - }, + children: [ + { + path: '', + pathMatch: 'full', + redirectTo: 'dfg', + }, + { + path: 'dfg', + component: DfgProjectsComponent, + resolve: { + dfgProjectPage: dfgProjectsResolver, + selectedDfgInstitutionsPage: selectedDfgInstitutionsResolver, + selectedDfgAuthorsPage: selectedDfgAuthorsResolver, + selectedTopicsPage: selectedTopicsResolver, + }, + runGuardsAndResolvers: 'always', + data: { + resolvingFor: RESOLVING_PROJECT_PAGE_FOR.PERSON, + }, + }, + { + path: 'eu', + component: EuProjectsComponent, + resolve: { + euCordisProjectPage: euCordisProjectsResolver, + selectedEuInstitutionsPage: selectedEuInstitutionsResolver, + selectedEuAuthorsPage: selectedAuthorsResolver, + selectedTopicsPage: selectedTopicsResolver, + }, + runGuardsAndResolvers: 'always', + data: { + resolvingFor: RESOLVING_PROJECT_PAGE_FOR.PERSON, + }, + }, + ], }, { path: 'publications', diff --git a/webapp/src/app/modules/dashboard/dashboard.component.html b/webapp/src/app/modules/dashboard/dashboard.component.html index 4b827cb2..e7479263 100644 --- a/webapp/src/app/modules/dashboard/dashboard.component.html +++ b/webapp/src/app/modules/dashboard/dashboard.component.html @@ -26,7 +26,7 @@
groups diff --git a/webapp/src/app/modules/dashboard/dashboard.component.ts b/webapp/src/app/modules/dashboard/dashboard.component.ts index ea16ab26..171c3d6f 100644 --- a/webapp/src/app/modules/dashboard/dashboard.component.ts +++ b/webapp/src/app/modules/dashboard/dashboard.component.ts @@ -13,6 +13,10 @@ import { TopAuthorsWorksPeriod, TopicHeatmap, } from './dashboard-statistics.service'; +import { + activeInstitutionPersonListQueryParams, + PersonListQueryParams, +} from '../../shared/person-list-query-params'; type DashboardStatisticKey = | 'publications' | 'persons' @@ -161,6 +165,13 @@ export class DashboardComponent implements OnInit { ); } + personListQueryParams(): PersonListQueryParams { + return activeInstitutionPersonListQueryParams( + this.institutionRouteId(), + this.organizationName(), + ); + } + setTopicTreemapPeriod(period: TopicTreemapPeriod): void { if (period === this.topicTreemapPeriod && period !== 'custom') return; diff --git a/webapp/src/app/modules/keywords-search/keywords-search.component.ts b/webapp/src/app/modules/keywords-search/keywords-search.component.ts index b698ea4e..1e30196d 100644 --- a/webapp/src/app/modules/keywords-search/keywords-search.component.ts +++ b/webapp/src/app/modules/keywords-search/keywords-search.component.ts @@ -962,8 +962,8 @@ export class KeywordsSearchComponent { const selected = this.parseKeywordList(queryParams.get('selected')); const source = queryParams.get('source') ?? ''; const view = queryParams.get('view') ?? 'llm'; - const legend = queryParams.get('legend') ?? 'on'; - const legendExpanded = queryParams.get('legendExpanded') ?? 'off'; + const legend = queryParams.get('legend') === 'true'; + const legendExpanded = queryParams.get('legendExpanded') === 'true'; const fuzzy = queryParams.get('fuzzy') === 'true'; this.isRestoringState = true; this.form.patchValue( @@ -975,8 +975,8 @@ export class KeywordsSearchComponent { { emitEvent: false }, ); this.keywordView.set(view as KeywordView); - this.subfieldLegendVisible.set(legend === 'on'); - this.subfieldLegendExpanded.set(legendExpanded === 'on'); + this.subfieldLegendVisible.set(legend); + this.subfieldLegendExpanded.set(legendExpanded); this.extractionSource.set(source as InputMode); this.topicMappingSearch.set(fuzzy); this.restoreStateFromSession(); @@ -1036,8 +1036,8 @@ export class KeywordsSearchComponent { url: this.toNullableParam(this.form.controls.urlInput.value), text: this.toNullableParam(this.form.controls.textInput.value), view: this.keywordView(), - legend: this.subfieldLegendVisible() ? 'on' : 'off', - legendExpanded: this.subfieldLegendExpanded() ? 'on' : 'off', + legend: this.subfieldLegendVisible() ? 'true' : 'false', + legendExpanded: this.subfieldLegendExpanded() ? 'true' : 'false', broad: this.serializeKeywords( this.getKeywordLabels(this.broadKeywords()), ), diff --git a/webapp/src/app/modules/keywords-search/search-results/projects-results/projects-results.component.html b/webapp/src/app/modules/keywords-search/search-results/projects-results/projects-results.component.html index dd9481b3..3d42eb98 100644 --- a/webapp/src/app/modules/keywords-search/search-results/projects-results/projects-results.component.html +++ b/webapp/src/app/modules/keywords-search/search-results/projects-results/projects-results.component.html @@ -3,34 +3,22 @@
Projekte

Übersicht der durchgeführten Projekte.

- - - - - - - - - - - - - - + +
+ + + + diff --git a/webapp/src/app/modules/keywords-search/search-results/projects-results/projects-results.component.ts b/webapp/src/app/modules/keywords-search/search-results/projects-results/projects-results.component.ts index aec16222..c58a9776 100644 --- a/webapp/src/app/modules/keywords-search/search-results/projects-results/projects-results.component.ts +++ b/webapp/src/app/modules/keywords-search/search-results/projects-results/projects-results.component.ts @@ -1,73 +1,45 @@ -import { Component, computed, input, signal } from '@angular/core'; -import { ActivatedRoute, Router } from '@angular/router'; -import { toSignal } from '@angular/core/rxjs-interop'; -import { DfgInstitutionSummaryPage } from '../../../../api/model/dfgInstitutionSummaryPage'; -import { - CordisEuProjectPage, - DfgProjectPage, - AuthorPage, - InstitutionPageV2, - DfgPersonSummaryPage, - TopicPageV2, -} from '../../../../api'; +import { Component } from '@angular/core'; +import { RouterLink, RouterLinkActive, RouterOutlet } from '@angular/router'; + import { MatCardModule } from '@angular/material/card'; import { MatTabsModule } from '@angular/material/tabs'; -import { ProjectFilterComponent } from '../../../../shared/ui/project-filters/project-filters.component'; -import { DfgProjectTableComponent } from '../../../../shared/ui/dfg-project-table/dfg-project-table.component'; -import { EuProjectTableComponent } from '../../../../shared/ui/eu-project-table/eu-project-table.component'; -import { projectQueryParamKeys } from '../../../../resolvers/dfg-projects.resolver'; -import { euProjectQueryParamKeys } from '../../../../resolvers/person-cordis-eu-project-page.resolver'; +import { OnInit, computed } from '@angular/core'; +import { ActivatedRoute, Router } from '@angular/router'; +import { toSignal } from '@angular/core/rxjs-interop'; -const PROJECT_TAB_QUERY_PARAM_KEY = 'project_type'; - -import { SearchResultsStateService } from '../search-results-state.service'; @Component({ selector: 'app-projects-results', imports: [ MatCardModule, MatTabsModule, - ProjectFilterComponent, - DfgProjectTableComponent, - EuProjectTableComponent, + RouterLink, + RouterLinkActive, + RouterOutlet, ], templateUrl: './projects-results.component.html', styleUrl: './projects-results.component.scss', }) export class KeywordsToProjectsResultsComponent { - dfgProjectPage = input.required(); - personCordisEuProjectPage = input.required(); - - selectedDfgInstitutionsPage = input.required(); - selectedDfgAuthorsPage = input.required(); - selectedTopicsPage = input.required(); - - selectedEuInstitutionsPage = input.required(); - selectedEuAuthorsPage = input.required(); - - readonly dfgQueryParamKeys = projectQueryParamKeys; - readonly euQueryParamKeys = euProjectQueryParamKeys; - constructor( private readonly router: Router, private readonly activatedRoute: ActivatedRoute, ) {} - loading = signal(false); + queryParamMap = toSignal(this.activatedRoute.queryParamMap, { initialValue: this.activatedRoute.snapshot.queryParamMap, }); readonly fuzzySearch = computed( () => this.queryParamMap().get('fuzzy') === 'true', ); - selectedTabIndex = computed(() => { - const type = this.queryParamMap().get(PROJECT_TAB_QUERY_PARAM_KEY); - return type === 'eu' ? 1 : 0; - }); - onTabChange(index: number): void { - const type = index === 1 ? 'eu' : 'dfg'; - this.router.navigate([], { - queryParams: { [PROJECT_TAB_QUERY_PARAM_KEY]: type }, - queryParamsHandling: 'merge', - }); - } + readonly childRoutes = [ + { + path: 'dfg', + label: 'DFG-Projekte', + }, + { + path: 'eu', + label: 'EU-Projekte', + }, + ]; } diff --git a/webapp/src/app/modules/keywords-search/search-results/search-results.component.html b/webapp/src/app/modules/keywords-search/search-results/search-results.component.html index 94c091e4..ddc28113 100644 --- a/webapp/src/app/modules/keywords-search/search-results/search-results.component.html +++ b/webapp/src/app/modules/keywords-search/search-results/search-results.component.html @@ -69,7 +69,8 @@ keywords: state.payload()?.keywords?.join(','), fuzzy: state.payload()?.options?.fuzzy, topics: state.payload()?.options?.fuzzy ? state.topicIds() : null, - }"> + }" + queryParamsHandling="replace"> {{ route.icon }} {{ route.label }} diff --git a/webapp/src/app/modules/keywords-search/search-results/search-results.component.ts b/webapp/src/app/modules/keywords-search/search-results/search-results.component.ts index 6cb4c2ab..176100ec 100644 --- a/webapp/src/app/modules/keywords-search/search-results/search-results.component.ts +++ b/webapp/src/app/modules/keywords-search/search-results/search-results.component.ts @@ -217,6 +217,7 @@ export class KeywordsSearchResultsComponent { const queryParams = { fuzzy: fuzzy, topics: fuzzy ? this.state.topicIds() : null, + topicId: null, }; this.router.navigate([], { diff --git a/webapp/src/app/modules/person-card/person-card.component.html b/webapp/src/app/modules/person-card/person-card.component.html index 9f7bf142..1231d2a5 100644 --- a/webapp/src/app/modules/person-card/person-card.component.html +++ b/webapp/src/app/modules/person-card/person-card.component.html @@ -68,10 +68,7 @@ [matTooltip]="inst.display_name || ''" [matTooltipDisabled]="loading()" matTooltipPosition="above" - (click)=" - institutionClick.emit(inst.display_name || ''); - $event.stopPropagation() - "> + (click)="institutionClick.emit(inst); $event.stopPropagation()"> Verbindungen zu Unternehmen konnten nicht geladen werden. -} @else if (data && !data.is_ude_author) { -
-

Keine Unternehmenssuche verfügbar

-

Für diese Person wird aktuell keine Suche nach Unternehmen angezeigt.

-
} @else if (data && connections.length === 0) {

Keine Treffer im Handelsregister

diff --git a/webapp/src/app/modules/person-company-connections/person-company-connections.component.ts b/webapp/src/app/modules/person-company-connections/person-company-connections.component.ts index 742349e8..0194c0a6 100644 --- a/webapp/src/app/modules/person-company-connections/person-company-connections.component.ts +++ b/webapp/src/app/modules/person-company-connections/person-company-connections.component.ts @@ -1,12 +1,14 @@ import { CommonModule, LocationStrategy } from '@angular/common'; import { Component, + DestroyRef, ElementRef, OnInit, QueryList, ViewChildren, inject, } from '@angular/core'; +import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; import { MatButtonModule } from '@angular/material/button'; import { MatCardModule } from '@angular/material/card'; import { MatIconModule } from '@angular/material/icon'; @@ -22,6 +24,7 @@ import { CompanyConnectionsService, MatchedOfficer, } from '../../api'; +import { PersonDataResolved } from '../../resolvers/person.resolver'; interface RoleLegendItem { role: string; @@ -47,6 +50,7 @@ interface RoleLegendItem { export class PersonCompanyConnectionsComponent implements OnInit { private readonly route = inject(ActivatedRoute); private readonly router = inject(Router); + private readonly destroyRef = inject(DestroyRef); private readonly locationStrategy = inject(LocationStrategy); private readonly companyConnectionsApi = inject(CompanyConnectionsService); @@ -115,17 +119,31 @@ export class PersonCompanyConnectionsComponent implements OnInit { } ngOnInit(): void { - this.route.parent?.paramMap.subscribe((params) => { - const authorId = params.get('id'); + const parentRoute = this.route.parent; + const authorId = parentRoute?.snapshot.paramMap.get('id'); + const resolved = parentRoute?.snapshot.data['personData'] as + | PersonDataResolved + | undefined; - if (!authorId) { - this.loading = false; - this.error = true; - return; - } + if (!authorId || !resolved) { + this.loading = false; + this.error = true; + return; + } - this.loadCompanyConnections(authorId); - }); + resolved.companyConnectionsAvailable$ + .pipe(takeUntilDestroyed(this.destroyRef)) + .subscribe((available) => { + if (!available) { + void this.router.navigate(['overview'], { + relativeTo: parentRoute, + replaceUrl: true, + }); + return; + } + + this.loadCompanyConnections(authorId); + }); } getPrimaryOfficer(connection: CompanyConnection): MatchedOfficer | null { @@ -329,7 +347,7 @@ export class PersonCompanyConnectionsComponent implements OnInit { ): EChartsOption | null { const connections = response.connections ?? []; - if (!response.is_ude_author || connections.length === 0) { + if (connections.length === 0) { return null; } diff --git a/webapp/src/app/modules/person-list/person-list.component.html b/webapp/src/app/modules/person-list/person-list.component.html index 9647b24a..9dc0f676 100644 --- a/webapp/src/app/modules/person-list/person-list.component.html +++ b/webapp/src/app/modules/person-list/person-list.component.html @@ -59,7 +59,7 @@ close - } @else if (filter.category === 'institutionName') { + } @else if (filter.category === 'institutionId') { } - @if (findInstitutionPageIdByName(filter.value)) { + @if (filter.value) { @@ -246,9 +246,10 @@ (keyup.enter)="applySidebarFilters()" /> @for (institution of institutionOptions(); track institution.id) { - + {{ institution.display_name }} @if (institution.hint) { {{ institution.hint }} @@ -259,7 +260,7 @@ !institutionLookupLoading() && institutionOptions().length === 0 && institutionControl.value && - institutionControl.value.trim().length >= 2 + displayInstitution(institutionControl.value).trim().length >= 2 ) { Keine Institution gefunden } @@ -284,11 +285,11 @@ + aria-label="Institutionszugehörigkeit nach Jahr filtern"> Zusammenarbeit nach Jahr filtern + style="font-size: 12px; font-weight: 500; color: var(--sg-text)"> + Institutionszugehörigkeit nach Jahr filtern + @if (yearFilterEnabledControl.value) { @@ -305,16 +306,16 @@ (change)="applySidebarFilters()" style="display: flex; gap: 16px" aria-label="Modus für Jahresfilter"> - Genau in - Seit + + + Genau im Jahr + + + + + Seit + + ([]); readonly institutionLookupLoading = signal(false); + readonly selectedInstitution = signal(null); + readonly defaultMembershipYear = new Date().getUTCFullYear() - 2; defaultOrderValue = 'desc'; @@ -95,10 +97,11 @@ export class PersonListComponent { readonly topicSearchType = signal<'hybrid' | 'semantic'>('hybrid'); // Applied filter states (reflecting actual URL query params) - appliedInstitutionName = ''; - appliedYearFilterEnabled = false; - appliedFilterMode: 'in' | 'from' = 'from'; - appliedFilterYear = new Date().getFullYear() - 1; + public appliedInstitutionId = ''; + public appliedInstitutionName = ''; + public appliedYearFilterEnabled = false; + public appliedFilterMode: 'in' | 'from' = 'from'; + public appliedFilterYear = this.defaultMembershipYear; // Forms sortValueControl = new FormControl(null, { @@ -109,12 +112,14 @@ export class PersonListComponent { { nonNullable: true }, ); topicSearchControl = new FormControl('', { nonNullable: true }); - institutionControl = new FormControl('', { nonNullable: true }); + institutionControl = new FormControl('', { + nonNullable: true, + }); yearFilterEnabledControl = new FormControl(false, { nonNullable: true }); filterModeControl = new FormControl<'in' | 'from'>('from', { nonNullable: true, }); - filterYearControl = new FormControl(new Date().getFullYear() - 1, { + filterYearControl = new FormControl(this.defaultMembershipYear, { nonNullable: true, validators: [ Validators.min(1900), @@ -134,11 +139,14 @@ export class PersonListComponent { this.setupInstitutionAutocomplete(); // Enable/disable the year filter checkbox based on the presence of an institution value - this.updateYearFilterState(this.institutionControl.value); + this.updateYearFilterState(this.selectedInstitution()); this.institutionControl.valueChanges .pipe(takeUntilDestroyed(this.destroyRef)) .subscribe((val) => { - this.updateYearFilterState(val); + if (typeof val === 'string') { + this.selectedInstitution.set(null); + this.updateYearFilterState(null); + } }); this.route.queryParams @@ -149,17 +157,19 @@ export class PersonListComponent { const pageSize = params['pageSize'] ? Number.parseInt(params['pageSize'], 10) : 10; + const institutionId = params['institutionId'] || ''; const institutionName = params['institutionName'] || ''; const sortBy = params['sortBy'] || null; const sortOrder = params['sortOrder'] || this.defaultOrderValue; - const yearFilterEnabled = params['yearFilterEnabled'] === 'true'; + const yearFilterEnabled = + !!institutionId && params['yearFilterEnabled'] !== 'false'; const filterMode = params['filterMode'] === 'in' || params['filterMode'] === 'from' ? params['filterMode'] : 'from'; const filterYear = params['filterYear'] ? Number.parseInt(params['filterYear'], 10) - : new Date().getFullYear() - 1; + : this.defaultMembershipYear; const topicSearch = params['topicSearch'] || ''; const topicSearchType = params['topicSearchType'] === 'semantic' ? 'semantic' : 'hybrid'; @@ -181,12 +191,23 @@ export class PersonListComponent { if (this.searchValue() !== query) { this.searchValue.set(query || null); } - if (this.institutionControl.value !== institutionName) { - this.institutionControl.setValue(institutionName, { + const institution = + institutionId && institutionName + ? ({ + id: institutionId, + display_name: institutionName, + } satisfies DehydratedInstitution) + : null; + this.selectedInstitution.set(institution); + if ( + this.displayInstitution(this.institutionControl.value) !== + institutionName + ) { + this.institutionControl.setValue(institution ?? '', { emitEvent: false, }); - this.updateYearFilterState(institutionName); } + this.updateYearFilterState(institution); if (this.yearFilterEnabledControl.value !== yearFilterEnabled) { this.yearFilterEnabledControl.setValue(yearFilterEnabled); } @@ -202,6 +223,7 @@ export class PersonListComponent { this.topicSearchType.set(topicSearchType); // Update applied filter states + this.appliedInstitutionId = institutionId; this.appliedInstitutionName = institutionName; this.appliedYearFilterEnabled = yearFilterEnabled; this.appliedFilterMode = filterMode; @@ -311,15 +333,18 @@ export class PersonListComponent { this.selectedTopics().forEach((t) => { list.push({ category: 'topic', value: t, label: `Thema: ${t}` }); }); - if (this.appliedInstitutionName) { + if (this.appliedInstitutionId && this.appliedInstitutionName) { let label = `Institution: ${this.appliedInstitutionName}`; if (this.appliedYearFilterEnabled) { - const modeLabel = this.appliedFilterMode === 'in' ? 'in' : 'from'; - label += ` (${modeLabel} ${this.appliedFilterYear})`; + const periodLabel = + this.appliedFilterMode === 'in' + ? `im Jahr ${this.appliedFilterYear}` + : `seit ${this.appliedFilterYear}`; + label += ` (${periodLabel})`; } list.push({ - category: 'institutionName', - value: this.appliedInstitutionName, + category: 'institutionId', + value: this.appliedInstitutionId, label: label, countryCode: this.findInstitutionCountryCode( this.appliedInstitutionName, @@ -333,36 +358,11 @@ export class PersonListComponent { return filter.label.replace(/^Institution:\s*/, ''); } - findInstitutionPageIdByName(institutionName: string): string | null { - const normalized = institutionName.trim().toLowerCase(); - if (!normalized) { - return null; - } - - for (const person of this.persons) { - const candidates: Array = [ - ...(person.last_known_institutions ?? []), - ...(person.affiliations ?? []).map((a) => a.institution ?? undefined), - ]; - - for (const inst of candidates) { - if ( - inst?.id && - (inst.display_name ?? '').trim().toLowerCase() === normalized - ) { - return inst.id.split('/').pop() ?? null; - } - } - } - - return null; - } - - openInstitutionPage(institutionName: string, event: Event): void { + openInstitutionPage(institutionId: string, event: Event): void { event.stopPropagation(); event.preventDefault(); - const id = this.findInstitutionPageIdByName(institutionName); + const id = institutionId.split('/').pop(); if (!id) return; void this.router.navigate(['/institution', id]); @@ -400,13 +400,14 @@ export class PersonListComponent { next.delete(filter.value); return next; }); - } else if (filter.category === 'institutionName') { + } else if (filter.category === 'institutionId') { this.institutionControl.setValue('', { emitEvent: false }); - this.updateYearFilterState(''); + this.selectedInstitution.set(null); + this.updateYearFilterState(null); this.institutionOptions.set([]); this.yearFilterEnabledControl.setValue(false); this.filterModeControl.setValue('from'); - this.filterYearControl.setValue(new Date().getFullYear() - 1); + this.filterYearControl.setValue(this.defaultMembershipYear); } this.applySidebarFilters(); } @@ -453,11 +454,12 @@ export class PersonListComponent { clearAllFilters(): void { this.selectedTopics.set(new Set()); this.institutionControl.setValue('', { emitEvent: false }); - this.updateYearFilterState(''); + this.selectedInstitution.set(null); + this.updateYearFilterState(null); this.institutionOptions.set([]); this.yearFilterEnabledControl.setValue(false); this.filterModeControl.setValue('from'); - this.filterYearControl.setValue(new Date().getFullYear() - 1); + this.filterYearControl.setValue(this.defaultMembershipYear); this.applySidebarFilters(); } @@ -465,6 +467,7 @@ export class PersonListComponent { if (this.yearFilterEnabledControl.value && this.filterYearControl.invalid) { return; } + const institution = this.selectedInstitution(); this.router.navigate([], { queryParams: { topic: this.selectedTopics().size @@ -473,22 +476,23 @@ export class PersonListComponent { topicSearch: this.topicSearchControl.value || null, topicSearchType: this.topicSearchType() === 'semantic' ? 'semantic' : null, - institutionName: this.institutionControl.value || null, + institutionId: institution?.id || null, + institutionName: institution?.display_name || null, sortBy: this.sortValueControl.value || null, sortOrder: this.sortOrderControl.value || null, - yearFilterEnabled: - this.institutionControl.value && this.yearFilterEnabledControl.value + yearFilterEnabled: institution + ? this.yearFilterEnabledControl.value ? 'true' - : null, + : 'false' + : null, filterMode: - this.institutionControl.value && this.yearFilterEnabledControl.value + institution && this.yearFilterEnabledControl.value ? this.filterModeControl.value : null, filterYear: - this.institutionControl.value && this.yearFilterEnabledControl.value + institution && this.yearFilterEnabledControl.value ? this.filterYearControl.value : null, - strict: null, page: 1, }, queryParamsHandling: 'merge', @@ -535,9 +539,14 @@ export class PersonListComponent { this.toggleTopic(topic); } - onCardInstitutionClick(institutionName: string): void { - this.institutionControl.setValue(institutionName, { emitEvent: false }); - this.updateYearFilterState(institutionName); + onCardInstitutionClick(institution: DehydratedInstitution): void { + if (!institution.id || !institution.display_name) { + return; + } + this.selectedInstitution.set(institution); + this.institutionControl.setValue(institution, { emitEvent: false }); + this.resetActiveMembershipFilter(); + this.updateYearFilterState(institution); this.institutionOptions.set([]); this.applySidebarFilters(); } @@ -604,8 +613,8 @@ export class PersonListComponent { .pipe(map((response) => response.results ?? [])); } - updateYearFilterState(val: string): void { - if (!val) { + updateYearFilterState(institution: DehydratedInstitution | null): void { + if (!institution?.id) { this.yearFilterEnabledControl.disable(); this.yearFilterEnabledControl.setValue(false); } else { @@ -615,19 +624,40 @@ export class PersonListComponent { clearInstitutionFilter(): void { this.institutionControl.setValue('', { emitEvent: false }); - this.updateYearFilterState(''); + this.selectedInstitution.set(null); + this.updateYearFilterState(null); this.institutionOptions.set([]); this.applySidebarFilters(); } onInstitutionSelected(event: MatAutocompleteSelectedEvent): void { - const val = event.option.value; - this.institutionControl.setValue(val, { emitEvent: false }); - this.updateYearFilterState(val); + const institution = event.option.value as DehydratedInstitution; + if (!institution.id || !institution.display_name) { + return; + } + this.selectedInstitution.set(institution); + this.institutionControl.setValue(institution, { emitEvent: false }); + this.resetActiveMembershipFilter(); + this.updateYearFilterState(institution); this.institutionOptions.set([]); this.applySidebarFilters(); } + public readonly displayInstitution = ( + institution: string | DehydratedInstitution | null, + ): string => + typeof institution === 'string' + ? institution + : (institution?.display_name ?? ''); + + private resetActiveMembershipFilter(): void { + this.yearFilterEnabledControl.setValue(true, { emitEvent: false }); + this.filterModeControl.setValue('from', { emitEvent: false }); + this.filterYearControl.setValue(this.defaultMembershipYear, { + emitEvent: false, + }); + } + private parseQueryParamArray(val: any): string[] { if (!val) return []; if (Array.isArray(val)) return val; diff --git a/webapp/src/app/modules/person-projects/person-projects.component.html b/webapp/src/app/modules/person-projects/person-projects.component.html index 5372cfb4..3d42eb98 100644 --- a/webapp/src/app/modules/person-projects/person-projects.component.html +++ b/webapp/src/app/modules/person-projects/person-projects.component.html @@ -3,34 +3,22 @@
Projekte

Übersicht der durchgeführten Projekte.

- - - - - - - - - - - - - - + + + + + + diff --git a/webapp/src/app/modules/person-projects/person-projects.component.ts b/webapp/src/app/modules/person-projects/person-projects.component.ts index 91dda724..359a9d9c 100644 --- a/webapp/src/app/modules/person-projects/person-projects.component.ts +++ b/webapp/src/app/modules/person-projects/person-projects.component.ts @@ -1,69 +1,31 @@ -import { Component, computed, input } from '@angular/core'; -import { ActivatedRoute, Router } from '@angular/router'; -import { toSignal } from '@angular/core/rxjs-interop'; -import { DfgInstitutionSummaryPage } from '../../api/model/dfgInstitutionSummaryPage'; -import { - CordisEuProjectPage, - DfgProjectPage, - AuthorPage, - InstitutionPageV2, - TopicPageV2, - DfgPersonSummaryPage, -} from '../../api'; +import { Component } from '@angular/core'; +import { RouterLink, RouterLinkActive, RouterOutlet } from '@angular/router'; + import { MatCardModule } from '@angular/material/card'; import { MatTabsModule } from '@angular/material/tabs'; -import { ProjectFilterComponent } from '../../shared/ui/project-filters/project-filters.component'; -import { DfgProjectTableComponent } from '../../shared/ui/dfg-project-table/dfg-project-table.component'; -import { EuProjectTableComponent } from '../../shared/ui/eu-project-table/eu-project-table.component'; -import { projectQueryParamKeys } from '../../resolvers/dfg-projects.resolver'; -import { euProjectQueryParamKeys } from '../../resolvers/person-cordis-eu-project-page.resolver'; - -const PROJECT_TAB_QUERY_PARAM_KEY = 'project_type'; @Component({ selector: 'app-person-projects', + standalone: true, imports: [ MatCardModule, MatTabsModule, - ProjectFilterComponent, - DfgProjectTableComponent, - EuProjectTableComponent, + RouterOutlet, + RouterLink, + RouterLinkActive, ], templateUrl: './person-projects.component.html', styleUrl: './person-projects.component.scss', }) export class PersonProjectsComponent { - dfgProjectPage = input.required(); - personCordisEuProjectPage = input.required(); - - selectedDfgInstitutionsPage = input.required(); - selectedDfgAuthorsPage = input.required(); - selectedEuInstitutionsPage = input.required(); - selectedEuAuthorsPage = input.required(); - selectedTopicsPage = input.required(); - - readonly dfgQueryParamKeys = projectQueryParamKeys; - readonly euQueryParamKeys = euProjectQueryParamKeys; - - constructor( - private readonly router: Router, - private readonly activatedRoute: ActivatedRoute, - ) {} - - queryParamMap = toSignal(this.activatedRoute.queryParamMap, { - initialValue: this.activatedRoute.snapshot.queryParamMap, - }); - - selectedTabIndex = computed(() => { - const type = this.queryParamMap().get(PROJECT_TAB_QUERY_PARAM_KEY); - return type === 'eu' ? 1 : 0; - }); - - onTabChange(index: number): void { - const type = index === 1 ? 'eu' : 'dfg'; - this.router.navigate([], { - queryParams: { [PROJECT_TAB_QUERY_PARAM_KEY]: type }, - queryParamsHandling: 'merge', - }); - } + readonly childRoutes = [ + { + path: 'dfg', + label: 'DFG-Projekte', + }, + { + path: 'eu', + label: 'EU-Projekte', + }, + ]; } diff --git a/webapp/src/app/modules/person/person.component.html b/webapp/src/app/modules/person/person.component.html index 316c07be..37b613aa 100644 --- a/webapp/src/app/modules/person/person.component.html +++ b/webapp/src/app/modules/person/person.component.html @@ -149,7 +149,7 @@ (tagClick)="onInterestingTagClick($event)">