From 0d19abb29357c90a9219203cdc53133053e61b67 Mon Sep 17 00:00:00 2001 From: genja Date: Thu, 30 Jul 2026 01:19:57 +0200 Subject: [PATCH 01/11] added corresponding oa_authors to each EU publication response --- .../projects_eu_cordis/fp7/fp7_publication.py | 6 +- .../horizon2020/h2020_publication.py | 6 +- .../horizon_europe/heu_publication.py | 5 +- .../projects/eu_cordis_projects_client.py | 174 ++++++++++++------ 4 files changed, 132 insertions(+), 59 deletions(-) diff --git a/service/src/main/inse/models/projects_eu_cordis/fp7/fp7_publication.py b/service/src/main/inse/models/projects_eu_cordis/fp7/fp7_publication.py index 2e9ab1ff..b92f9084 100644 --- a/service/src/main/inse/models/projects_eu_cordis/fp7/fp7_publication.py +++ b/service/src/main/inse/models/projects_eu_cordis/fp7/fp7_publication.py @@ -23,12 +23,14 @@ from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set from typing_extensions import Self from pydantic_core import to_jsonable_python - +from inse.authors.v2.model import Author class Fp7Publication(BaseModel): """ Fp7Publication """ # noqa: E501 authors: Optional[StrictStr] = None + oa_authors: Optional[List[Author]] = Field(default=None, alias="oaAuthors", description="OpenAlex authors matched to this publication's DOI") + collection: Optional[StrictStr] = None content_update_date: Optional[datetime] = Field(default=None, alias="contentUpdateDate") doi: Optional[StrictStr] = None @@ -46,7 +48,7 @@ class Fp7Publication(BaseModel): repository_url: Optional[StrictStr] = Field(default=None, alias="repositoryUrl") title: Optional[StrictStr] = None volume: Optional[StrictStr] = None - __properties: ClassVar[List[str]] = ["authors", "collection", "contentUpdateDate", "doi", "id", "isPublishedAs", "journalNumber", "journalTitle", "projectAcronym", "projectID", "publishedPages", "publishedYear", "publisher", "qaProcessedDoi", "rcn", "repositoryUrl", "title", "volume"] + __properties: ClassVar[List[str]] = ["authors", "collection", "contentUpdateDate", "doi", "id", "isPublishedAs", "journalNumber", "journalTitle", "projectAcronym", "projectID", "publishedPages", "publishedYear", "publisher", "qaProcessedDoi", "rcn", "repositoryUrl", "title", "volume", "oaAuthors"] model_config = ConfigDict( validate_by_name=True, diff --git a/service/src/main/inse/models/projects_eu_cordis/horizon2020/h2020_publication.py b/service/src/main/inse/models/projects_eu_cordis/horizon2020/h2020_publication.py index ffe9a440..a9443e4c 100644 --- a/service/src/main/inse/models/projects_eu_cordis/horizon2020/h2020_publication.py +++ b/service/src/main/inse/models/projects_eu_cordis/horizon2020/h2020_publication.py @@ -23,12 +23,13 @@ from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set from typing_extensions import Self from pydantic_core import to_jsonable_python - +from inse.authors.v2.model import Author class H2020Publication(BaseModel): """ H2020Publication """ # noqa: E501 authors: Optional[StrictStr] = None + oa_authors: Optional[List[Author]] = Field(default=None, alias="oaAuthors", description="OpenAlex authors matched to this publication's DOI") collection: Optional[StrictStr] = None content_update_date: Optional[datetime] = Field(default=None, alias="contentUpdateDate") doi: Optional[StrictStr] = None @@ -46,7 +47,8 @@ class H2020Publication(BaseModel): repository_url: Optional[StrictStr] = Field(default=None, alias="repositoryUrl") title: Optional[StrictStr] = None volume: Optional[StrictStr] = None - __properties: ClassVar[List[str]] = ["authors", "collection", "contentUpdateDate", "doi", "id", "isPublishedAs", "journalNumber", "journalTitle", "projectAcronym", "projectID", "publishedPages", "publishedYear", "publisher", "qaProcessedDoi", "rcn", "repositoryUrl", "title", "volume"] + oa_authors: Optional[List[Author]] = Field(default=None, alias="oaAuthors", description="OpenAlex authors matched to this publication's DOI") + __properties: ClassVar[List[str]] = ["authors", "collection", "contentUpdateDate", "doi", "id", "isPublishedAs", "journalNumber", "journalTitle", "projectAcronym", "projectID", "publishedPages", "publishedYear", "publisher", "qaProcessedDoi", "rcn", "repositoryUrl", "title", "volume", "oaAuthors"] model_config = ConfigDict( validate_by_name=True, diff --git a/service/src/main/inse/models/projects_eu_cordis/horizon_europe/heu_publication.py b/service/src/main/inse/models/projects_eu_cordis/horizon_europe/heu_publication.py index 9d3424df..291542a6 100644 --- a/service/src/main/inse/models/projects_eu_cordis/horizon_europe/heu_publication.py +++ b/service/src/main/inse/models/projects_eu_cordis/horizon_europe/heu_publication.py @@ -23,12 +23,14 @@ from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set from typing_extensions import Self from pydantic_core import to_jsonable_python +from inse.authors.v2.model import Author class HEUPublication(BaseModel): """ HEUPublication """ # noqa: E501 authors: Optional[StrictStr] = None + oa_authors: Optional[List[Author]] = Field(default=None, alias="oaAuthors", description="OpenAlex authors matched to this publication's DOI") collection: Optional[StrictStr] = None content_update_date: Optional[datetime] = Field(default=None, alias="contentUpdateDate") doi: Optional[StrictStr] = None @@ -46,7 +48,8 @@ class HEUPublication(BaseModel): repository_url: Optional[StrictStr] = Field(default=None, alias="repositoryUrl") title: Optional[StrictStr] = None volume: Optional[StrictStr] = None - __properties: ClassVar[List[str]] = ["authors", "collection", "contentUpdateDate", "doi", "id", "isPublishedAs", "journalNumber", "journalTitle", "projectAcronym", "projectID", "publishedPages", "publishedYear", "publisher", "qaProcessedDoi", "rcn", "repositoryUrl", "title", "volume"] + oa_authors: Optional[List[Author]] = Field(default=None, alias="oaAuthors", description="OpenAlex authors matched to this publication's DOI") + __properties: ClassVar[List[str]] = ["authors", "collection", "contentUpdateDate", "doi", "id", "isPublishedAs", "journalNumber", "journalTitle", "projectAcronym", "projectID", "publishedPages", "publishedYear", "publisher", "qaProcessedDoi", "rcn", "repositoryUrl", "title", "volume", "oaAuthors"] model_config = ConfigDict( validate_by_name=True, diff --git a/service/src/main/inse/projects/eu_cordis_projects_client.py b/service/src/main/inse/projects/eu_cordis_projects_client.py index a3ecc475..24a8fc51 100644 --- a/service/src/main/inse/projects/eu_cordis_projects_client.py +++ b/service/src/main/inse/projects/eu_cordis_projects_client.py @@ -5,7 +5,7 @@ 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.model import AuthorPage,Author from inse.authors.v2.service import get_authors_by_ids # Import base models from inse.models.cordis_eu_project import CordisEuProject @@ -136,17 +136,96 @@ async def get_enriched_cordis_project_by_id( # helpers +async def _fetch_openalex_author_data_for_project_ids( + project_ids: List[str], +) -> Tuple[Dict[str, AuthorPage], Dict[str, Dict[str, List[Author]]]]: + """ + Single batched fetch that returns, per project_id: + - an AuthorPage of all OpenAlex authors across all of the project's publications + - a map of raw DOI -> List[Author] for attaching authors to individual publications + """ + 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") + if not pid: + continue + dois_by_project.setdefault(pid, set()) + doi = source.get("doi") + qa_processed_doi = source.get("qaProcessedDoi") + 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) + all_author_ids = list({aid for ids in author_ids_by_doi.values() for aid in ids}) + + # single ES call to fetch all Author objects across every project + author_page = await get_authors_by_ids(author_ids=all_author_ids) + authors_by_id = {author.id: author for author in author_page.elements} + + author_page_by_project: Dict[str, AuthorPage] = {} + doi_author_map_by_project: Dict[str, Dict[str, List[Author]]] = {} + + for pid in project_ids: + dois = dois_by_project.get(pid, set()) + + doi_authors: Dict[str, List[Author]] = {} + project_author_ids: Set[str] = set() + for doi in dois: + ids_for_doi = author_ids_by_doi.get(doi, []) + doi_authors[doi] = [authors_by_id[aid] for aid in ids_for_doi if aid in authors_by_id] + project_author_ids.update(ids_for_doi) + + doi_author_map_by_project[pid] = doi_authors + + authors_for_project = [authors_by_id[aid] for aid in project_author_ids if aid in authors_by_id] + author_page_by_project[pid] = AuthorPage( + elements=authors_for_project, + total=len(authors_for_project), + page=0, + size=len(authors_for_project), + ) + + return author_page_by_project, doi_author_map_by_project + + +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.""" + author_page_by_project, _ = await _fetch_openalex_author_data_for_project_ids(project_ids) + return author_page_by_project + + async def _fetch_authors_and_topics_for_project( project_id: str, project_type: EuCordisProjectType, -) -> Tuple[Optional[AuthorPage], List[Topic]]: - """Fetches OpenAlex authors and mapped topics for a single project.""" - authors_lookup, topics_lookup = await asyncio.gather( - get_openalex_authors_for_projects_ids({project_type: [project_id]}), +) -> Tuple[Optional[AuthorPage], List[Topic], Dict[str, List[Author]]]: + """Fetches OpenAlex authors (project-level + per-DOI map) and mapped topics for a single project.""" + (author_page_by_project, doi_author_map_by_project), topics_lookup = await asyncio.gather( + _fetch_openalex_author_data_for_project_ids([project_id]), get_openalex_topics_for_eu_projects({project_type: [project_id]}), ) - author_page = authors_lookup.get((project_type, project_id)) + author_page = author_page_by_project.get(project_id) + doi_author_map = doi_author_map_by_project.get(project_id, {}) raw_topic_matches = sorted( topics_lookup.get((project_type, project_id), []), @@ -158,7 +237,26 @@ async def _fetch_authors_and_topics_for_project( if isinstance(match, dict) ] - return author_page, topics + return author_page, topics, doi_author_map + + +def _attach_authors_to_publications( + publications: List[Any], + doi_author_map: Dict[str, List[Author]], +) -> List[Any]: + """Sets oa_authors on each publication by matching its doi/qaProcessedDoi against doi_author_map.""" + for pub in publications: + doi = getattr(pub, "doi", None) + qa_processed_doi = getattr(pub, "qa_processed_doi", None) + + authors = doi_author_map.get(doi) if doi else None + if not authors and qa_processed_doi: + authors = doi_author_map.get(qa_processed_doi) + + pub.oa_authors = authors or [] + + return publications + async def _fetch_related_entities_parallel( project_id: str, @@ -258,11 +356,15 @@ async def _enrich_fp7_project( logger.error(f"Failed to validate FP7 project {project_id}: {e}") return None - related, (authors, topics) = await asyncio.gather( + related, (authors, topics, doi_author_map) = await asyncio.gather( _fetch_related_entities_parallel(project_id, _FP7_ENTITY_CONFIGS), _fetch_authors_and_topics_for_project(project_id, project_type), ) + related["publications"] = _attach_authors_to_publications( + related.get("publications", []), doi_author_map + ) + return Fp7ProjectDetails.from_project_with_relations( project=project, oa_authors=authors, oa_topics=topics, **related ) @@ -279,11 +381,15 @@ async def _enrich_h2020_project( logger.error(f"Failed to validate H2020 project {project_id}: {e}") return None - related, (authors, topics) = await asyncio.gather( + related, (authors, topics, doi_author_map) = await asyncio.gather( _fetch_related_entities_parallel(project_id, _H2020_ENTITY_CONFIGS), _fetch_authors_and_topics_for_project(project_id, project_type), ) + related["publications"] = _attach_authors_to_publications( + related.get("publications", []), doi_author_map + ) + return H2020ProjectDetails.from_project_with_relations( project=project, oa_authors=authors, oa_topics=topics, **related ) @@ -300,57 +406,19 @@ async def _enrich_heu_project( logger.error(f"Failed to validate Horizon Europe project {project_id}: {e}") return None - related, (authors, topics) = await asyncio.gather( + related, (authors, topics, doi_author_map) = await asyncio.gather( _fetch_related_entities_parallel(project_id, _HEU_ENTITY_CONFIGS), _fetch_authors_and_topics_for_project(project_id, project_type), ) + related["publications"] = _attach_authors_to_publications( + related.get("publications", []), doi_author_map + ) + return HEUProjectDetails.from_project_with_relations( project=project, oa_authors=authors, oa_topics=topics, **related ) -async def _enrich_h2020_project( - project_id: str, - project_source: Dict[str, Any], - project_type: EuCordisProjectType, -) -> Optional[H2020ProjectDetails]: - 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, (authors, topics) = await asyncio.gather( - _fetch_related_entities_parallel(project_id, _H2020_ENTITY_CONFIGS), - _fetch_authors_and_topics_for_project(project_id, project_type), - ) - - return H2020ProjectDetails.from_project_with_relations( - project=project, oa_authors=authors, oa_topics=topics, **related - ) - - -async def _enrich_heu_project( - project_id: str, - project_source: Dict[str, Any], - project_type: EuCordisProjectType, -) -> Optional[HEUProjectDetails]: - 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, (authors, topics) = await asyncio.gather( - _fetch_related_entities_parallel(project_id, _HEU_ENTITY_CONFIGS), - _fetch_authors_and_topics_for_project(project_id, project_type), - ) - - return HEUProjectDetails.from_project_with_relations( - project=project, oa_authors=authors, oa_topics=topics, **related - ) - - def _eu_project_type_index_filter( @@ -490,7 +558,6 @@ async def get_eu_project_ids_by_organization_filters( 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()}") - print(f"Project organization matches for {project_type}: {project_org_matches}") required_orgs = set() # Add ID requirements @@ -512,7 +579,6 @@ async def get_eu_project_ids_by_organization_filters( continue result[project_type].append(project_id) - print(f"Final project IDs by type: {result}") return result async def get_eu_organizations_for_projects( -- 2.56.1 From b8442213f855023169acf2f44a642296103e3a00 Mon Sep 17 00:00:00 2001 From: genja Date: Thu, 30 Jul 2026 01:21:40 +0200 Subject: [PATCH 02/11] splitted logic for ROOT and underlying institute results into 2 separated entities --- service/src/main/inse/projects/logic.py | 52 +++++++++++++++-- service/src/main/inse/projects/model.py | 25 ++++++-- .../inse/projects/projects_search_client.py | 58 ++++++++++++++----- service/src/main/inse/projects/router.py | 21 +++++-- service/src/main/inse/projects/service.py | 47 +++++++++++---- 5 files changed, 163 insertions(+), 40 deletions(-) diff --git a/service/src/main/inse/projects/logic.py b/service/src/main/inse/projects/logic.py index 2535073c..9cf20a54 100644 --- a/service/src/main/inse/projects/logic.py +++ b/service/src/main/inse/projects/logic.py @@ -46,7 +46,45 @@ async def get_dfg_institution_names_by_ids(institution_ids: List[int]) -> Option except Exception as e: logger.exception(f"Error fetching institution names for ids {institution_ids}: {str(e)}") return [] - + +async def get_institution_ids_by_institution_aliases(institution_aliases: list[str]) -> list[int]: + if not institution_aliases: + return [] + response = await elasticsearch.search( + index=ESIndex.DFG_INSTITUTES, + cluster=ESCluster.INSE, + body={ + "size": 10000, + "_source": ["institute_id"], + "query": { + "bool": { + "should": [ + clause + for name in institution_aliases + for clause in ( + # {"match": {"root_name_de": {"query": name, "operator": "and"}}}, + # {"match": {"root_name_en": {"query": name, "operator": "and"}}}, + # {"match": {"institute_name_de": {"query": name, "operator": "and"}}}, + # {"match": {"institute_name_en": {"query": name, "operator": "and"}}}, + {"match_phrase": {"root_name_de":name}}, + {"match_phrase": {"root_name_en":name}}, + {"match_phrase": {"institute_name_de":name}}, + {"match_phrase": {"institute_name_en": name}}, + ) + ], + "minimum_should_match": 1, + } + } + }, + ) + return list( + { + hit["_source"]["institute_id"] + for hit in response.get("hits", {}).get("hits", []) + if hit.get("_source", {}).get("institute_id") is not None + } + ) + async def get_person_ids_by_institution_ids( institution_ids: list[int], ) -> list[int]: @@ -59,10 +97,13 @@ async def get_person_ids_by_institution_ids( body={ "size": 10000, "_source": ["person_id"], - "query": { - "terms": { - "institute_id": institution_ids - } + "query": { "bool":{ + "should": [ + {"terms": {"institute_id": institution_ids}}, + {"terms": {"root_id": institution_ids}}, + ], + "minimum_should_match": 1, + } } }, ) @@ -108,7 +149,6 @@ async def get_bund_project_ids_by_topic_ids(topic_ids: List[str]) -> List[str]: cluster=ESCluster.INSE, body=body, ) - print(f"Response from Elasticsearch: {json.dumps(response, indent=2)}") # Debugging line hits = response.get("hits", {}).get("hits", []) if not hits: break diff --git a/service/src/main/inse/projects/model.py b/service/src/main/inse/projects/model.py index 7094cba5..5e568242 100644 --- a/service/src/main/inse/projects/model.py +++ b/service/src/main/inse/projects/model.py @@ -264,19 +264,33 @@ class DfgProjectSummary(BaseModel): institution = None if person.get("institute_id") is not None: - institution = DfgInstitutionSummary( + institute = DfgInstitutionSummary( id=person["institute_id"], institute_name_de=person.get("institute_name_de"), institute_name_en=person.get("institute_name_en"), address_country_de=person.get("address_country_de"), address_country_en=person.get("address_country_en"), - root_id=person["root_id"], - root_name_de=person.get("root_name_de"), - root_name_en=person.get("root_name_en"), + root_id=None, + root_name_de=None, + root_name_en=None, ) - institutions[person["institute_id"]] = institution + institutions[f"institute:{person['institute_id']}"] = institute + if person.get("root_id") is not None: + root_institution = DfgInstitutionSummary( + id=person["root_id"], + institute_name_de=person.get("root_name_de"), + institute_name_en=person.get("root_name_en"), + address_country_de=person.get("address_country_de"), + address_country_en=person.get("address_country_en"), + root_id=None, + root_name_de=None, + root_name_en=None, + ) + + institutions[f"root:{person['root_id']}"] = root_institution + if person.get("person_id") is not None: project_persons.append( DfgPersonSummary( @@ -290,6 +304,7 @@ class DfgProjectSummary(BaseModel): ) ) topics_raw = source.get("topics") or [] + print(f"Raw topics for DFG project {hit.get('_id', '')}: {topics_raw}") topics = None if isinstance(topics_raw, list) and topics_raw: # Sort by rank if present, so the most relevant topic comes first diff --git a/service/src/main/inse/projects/projects_search_client.py b/service/src/main/inse/projects/projects_search_client.py index 8b63aaeb..8f97b0ae 100644 --- a/service/src/main/inse/projects/projects_search_client.py +++ b/service/src/main/inse/projects/projects_search_client.py @@ -1,6 +1,6 @@ import json import logging -from typing import Any, Dict, List, Optional, Set, Tuple +from typing import Any, Dict, List, Optional, Set import urllib from inse.config import get_settings @@ -21,7 +21,7 @@ from inse.models.dfg_project_details import DfgProjectDetails from inse.models.bund_project_details import BundProjectDetails from inse.integrations import elasticsearch from inse.model import ESCluster, ESIndex -from inse.projects.logic import get_person_ids_by_institution_ids, get_dfg_project_ids_by_topic_ids,get_bund_project_ids_by_topic_ids, get_openalex_topics_for_dfg_projects, get_person_institutes, get_openalex_topics_for_bund_projects +from inse.projects.logic import get_person_ids_by_institution_ids, get_dfg_project_ids_by_topic_ids,get_bund_project_ids_by_topic_ids, get_openalex_topics_for_dfg_projects, get_person_institutes, get_openalex_topics_for_bund_projects, get_institution_ids_by_institution_aliases settings = get_settings() @@ -323,7 +323,6 @@ async def get_dfg_project_ids_by_names(names: List[str]) -> List[str]: for project in hit.get("_source", {}).get("projects", []) if "project_id" in project } - print(f"Retrieved project IDs for names {len(project_ids)}: {project_ids}") return list(project_ids) async def get_dfg_project_ids_by_dois(dois: List[str]) -> List[str]: @@ -348,8 +347,9 @@ async def get_dfg_project_ids_by_dois(dois: List[str]) -> List[str]: async def search_dfg_projects( page: int, size: int, + institution_aliases: Optional[List[str]] = None, project_ids: Optional[List[int]] = None, - institution_ids: Optional[List[int]] = None, + institution_ids: Optional[List[int]] = [], names: Optional[List[str]] = None, keywords: Optional[List[str]] = None, topic_ids: Optional[List[str]] = None, @@ -409,7 +409,7 @@ async def search_dfg_projects( "query": {}, } - must_clauses: List[Dict[str, Any]] = [] + must_clauses: List[Dict[str, Any]] = [] if project_ids: must_clauses.append({"terms": {"id": project_ids}}) # === Primary search clause: mutually exclusive fuzzy(topic_ids) vs keyword phrase search === @@ -510,6 +510,24 @@ async def search_dfg_projects( if name_must_clauses: must_clauses.append({"bool": {"must": name_must_clauses}}) + if institution_aliases: + matching_institution_ids = await get_institution_ids_by_institution_aliases( + institution_aliases=institution_aliases + ) + if not matching_institution_ids: + return DfgProjectPage(elements=[], total=0, page=page, size=size) + matching_person_ids = await get_person_ids_by_institution_ids( + institution_ids=matching_institution_ids + ) + must_clauses.append( + { + "nested": { + "path": "persons", + "query": {"terms": {"persons.person_id": matching_person_ids}}, + } + } + ) + if institution_ids: matching_person_ids = await get_person_ids_by_institution_ids( institution_ids=institution_ids @@ -550,7 +568,7 @@ async def search_dfg_projects( sort_config = {"id": {"order": sort_direction}} body["sort"] = [sort_config] - + # print(f"Executing DFG project search with body: {json.dumps(body, indent=2)}") # === Execute Search === response = await elasticsearch.search( index=ESIndex.DFG_PROJECTS, @@ -574,9 +592,7 @@ async def search_dfg_projects( for hit in hits: source = hit["_source"] project_id = source["id"] - - source["topics"] = topic_lookup.get(project_id, []) - + source["topics"] = topic_lookup.get(str(project_id), []) persons = source.get("persons", []) for person in persons: person_id = person.get("person_id") @@ -669,7 +685,8 @@ def _bund_year_filters(field: str, years: List[str]) -> Dict[str, Any]: async def search_bund_projects_with_filters( executing_agency: Optional[List[str]] = None, - institution_ids: Optional[List[str]] = None, + oa_institution_aliases: Optional[List[str]] = None, + raw_oa_institution_id: Optional[str] = None, funding_arts: Optional[List[str]] = None, # actually EuCordisProjectType, but treated as strings title: Optional[str] = None, keywords: Optional[List[str]] = None, @@ -686,7 +703,7 @@ async def search_bund_projects_with_filters( ) -> BundProjectPage: """ Main search function for BUND projects, analogous to the DFG search. - """ + """ from_ = page * size #institution_ids = ["I62318514"] # Fields we need to build BundProject objects (validation aliases match these exact names) @@ -731,6 +748,22 @@ async def search_bund_projects_with_filters( } must_clauses: List[Dict[str, Any]] = [] + if oa_institution_aliases: + must_clauses.append( + { + "bool": { + "should": [ + clause + for name in oa_institution_aliases + for clause in ( + {"match": {"Zuwendungsempfänger": {"query": name, "operator": "and"}}}, + {"match": {"Ausführende Stelle": {"query": name, "operator": "and"}}}, + ) + ], + "minimum_should_match": 1, + } + } + ) # === Primary search clause: fuzzy(topic_ids) vs keyword phrase search === if fuzzy and topic_ids: matching_project_ids = await get_bund_project_ids_by_topic_ids(topic_ids=topic_ids) @@ -804,7 +837,6 @@ async def search_bund_projects_with_filters( must_clauses.append(_bund_year_filters("funding_end", funding_end_years)) body["query"] = {"bool": {"must": must_clauses}} if must_clauses else {"match_all": {}} - # === Sorting === sort_by = sort_by.strip().lower() sort_direction = sort_direction.strip().lower() @@ -822,7 +854,7 @@ async def search_bund_projects_with_filters( sort_config = {"Förderkennzeichen.keyword": {"order": sort_direction}} body["sort"] = [sort_config] - + # print(f"Executing BUND project search with body: {json.dumps(body, indent=2)}") # === Execute Search === response = await elasticsearch.search( index=ESIndex.PROJECTS_BUND_V1, diff --git a/service/src/main/inse/projects/router.py b/service/src/main/inse/projects/router.py index 2a88d71c..614ddc6f 100644 --- a/service/src/main/inse/projects/router.py +++ b/service/src/main/inse/projects/router.py @@ -100,7 +100,9 @@ async def get_single_dfg_project( response_model_by_alias=False, ) async def search_bund_projects( - + institutions_search_client: Annotated[ + InstitutionsSearchClient, Depends(get_institutions_search_client) + ], executing_agency: Annotated[ Optional[List[str]], Query(description="Executing Agencies (Ausführende Stellen) to filter by."), @@ -137,9 +139,9 @@ async def search_bund_projects( Optional[List[str]], Query(description="Organization countries."), ] = None, - institution_ids: Annotated[ - Optional[List[str]], - Query(description="Institution IDs to filter by."), + raw_oa_institution_id: Annotated[ + Optional[str], + Query(description="The ID of the institution to filter by."), ] = None, page: Annotated[int, Query(description="The page number.", ge=0)] = 0, size: Annotated[int, Query(description="The page size.", ge=1)] = 20, @@ -154,6 +156,7 @@ async def search_bund_projects( ] = False, ) -> BundProjectPage: return await projects_service.search_bund_projects_with_filters( + institutions_search_client=institutions_search_client, executing_agency=executing_agency, funding_arts=funding_arts, title=title, @@ -163,7 +166,7 @@ async def search_bund_projects( funding_start_years=funding_start_years, funding_end_years=funding_end_years, countries=countries, - institution_ids=institution_ids, + raw_oa_institution_id=raw_oa_institution_id, page=page, size=size, sort_by=sort_by, @@ -500,6 +503,12 @@ async def get_institution_cordis_eu_projects_funding_over_time( response_model_by_alias=False, ) async def get_dfg_projects( + institutions_search_client: Annotated[ + InstitutionsSearchClient, Depends(get_institutions_search_client) + ], + raw_oa_institution_id: Annotated[ + Optional[str], Query(description="The openalex institution ID to filter by.") + ] = None, author_id: Annotated[Optional[str], Query(description="The openalex author ID to filter by.")] = None, author_filter_ids: Annotated[Optional[List[int]], Query(description="The dfg author IDs to filter by.")] = None, institution_ids: Annotated[ @@ -557,6 +566,8 @@ async def get_dfg_projects( fuzzy, ) return await projects_service.get_dfg_projects_by_author_id( + institutions_search_client=institutions_search_client, + raw_oa_institution_id=raw_oa_institution_id, author_id=author_id, author_filter_ids=author_filter_ids, institution_ids=institution_ids, diff --git a/service/src/main/inse/projects/service.py b/service/src/main/inse/projects/service.py index a0a8f406..7b05a78c 100644 --- a/service/src/main/inse/projects/service.py +++ b/service/src/main/inse/projects/service.py @@ -148,6 +148,8 @@ async def _get_dfg_project_ids_for_openalex_authors( return list(set.intersection(*project_sets)) async def get_dfg_projects_by_author_id( + institutions_search_client: InstitutionsSearchClient, + raw_oa_institution_id: Optional[str], author_id: Optional[str], author_filter_ids: Optional[List[int]], institution_ids: Optional[List[int]], @@ -206,16 +208,24 @@ async def get_dfg_projects_by_author_id( "No author names found for author_filter_ids=%s", author_filter_ids, ) - - if institution_ids: - logger.debug( - "No institutions found for institution_ids=%s", - institution_ids, + institution_aliases = [] + if raw_oa_institution_id: + institution_aliases = ( + await institutions_search_client.get_institution_aliases_by_oa_institution_id( + raw_oa_institution_id + ) ) - + if not institution_aliases: + return DfgProjectPage( + elements=[], + page=page, + size=size, + total=0, + ) return await projects_search_client.search_dfg_projects( page=page, size=size, + institution_aliases=institution_aliases, project_ids=author_project_ids, names=filter_names or [], institution_ids=institution_ids, @@ -240,7 +250,7 @@ async def get_institution_cordis_eu_projects_funding_over_time( raw_oa_institution_id=raw_oa_institution_id, institutions_search_client=institutions_search_client, ) - + print("WE GOT THE PAGE",page) return _calculate_funding_over_time( project_type=ProjectType.EU, projects=page.elements, @@ -284,8 +294,9 @@ async def get_institution_bund_projects_funding_over_time( #Bund async def search_bund_projects_with_filters( + institutions_search_client: InstitutionsSearchClient, executing_agency: Optional[str], - institution_ids: Optional[List[str]], + raw_oa_institution_id: Optional[str], title: Optional[str], keywords: Optional[List[str]], funding_arts: Optional[List[str]], @@ -300,9 +311,24 @@ async def search_bund_projects_with_filters( sort_direction: str = "asc", fuzzy: bool = False, ) -> BundProjectPage: + institution_aliases = [] + if raw_oa_institution_id: + institution_aliases = ( + await institutions_search_client.get_institution_aliases_by_oa_institution_id( + raw_oa_institution_id + ) + ) + if not institution_aliases: + return BundProjectPage( + elements=[], + page=page, + size=size, + total=0, + ) return await projects_search_client.search_bund_projects_with_filters( + oa_institution_aliases=institution_aliases, + raw_oa_institution_id=raw_oa_institution_id, executing_agency=executing_agency, - institution_ids=[], funding_arts=funding_arts, title=title, keywords=keywords, @@ -511,7 +537,7 @@ async def search_eu_cordis_projects( f"Found institution aliases for institution_id={raw_oa_institution_id}: {institution_aliases}" ) resolved_organization_names.extend(institution_aliases) - print("Resolved organization names:", resolved_organization_names) + all_author_ids: List[str] = [] if author_id: @@ -520,7 +546,6 @@ async def search_eu_cordis_projects( author_project_ids = await _get_eu_project_ids_for_openalex_authors( author_ids=all_author_ids ) - return await _search_eu_cordis_projects_es( page=page, size=size, -- 2.56.1 From abb8c9dbb553771a33f10ba6939a58d7d7e64c88 Mon Sep 17 00:00:00 2001 From: genja Date: Thu, 30 Jul 2026 01:21:53 +0200 Subject: [PATCH 03/11] fxied bug with too many author results --- service/src/main/inse/authors/v2/service.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/service/src/main/inse/authors/v2/service.py b/service/src/main/inse/authors/v2/service.py index 0c82f1bc..ba563736 100644 --- a/service/src/main/inse/authors/v2/service.py +++ b/service/src/main/inse/authors/v2/service.py @@ -142,7 +142,7 @@ async def get_authors_by_ids(author_ids: list[str]) -> AuthorPage: return await search_authors( page=0, - size=len(author_ids), + size=len(author_ids) if len(author_ids) <10000 else 10000, query={"terms": {"id": author_ids}}, source=[ "id", -- 2.56.1 From d11869c70bd202d2a7cb0b1e87f1370ac03b20df Mon Sep 17 00:00:00 2001 From: genja Date: Thu, 30 Jul 2026 01:22:56 +0200 Subject: [PATCH 04/11] inserted generic project tables to institute component --- .../institution-projects.component.html | 165 +++++++++--------- .../institution-projects.component.ts | 14 ++ 2 files changed, 94 insertions(+), 85 deletions(-) diff --git a/webapp/src/app/modules/institution-projects/institution-projects.component.html b/webapp/src/app/modules/institution-projects/institution-projects.component.html index 68aa24e5..5a9cc020 100644 --- a/webapp/src/app/modules/institution-projects/institution-projects.component.html +++ b/webapp/src/app/modules/institution-projects/institution-projects.component.html @@ -2,94 +2,89 @@

Projekte

- - - +
+ - - - - - - - - - - - -
- - - Förderung über Zeit - - - - - + + + +
+ + + Förderung über Zeit + + + + + -
- - - - +
+ + + + +
+ + + {{ row.funding_start | date: 'dd.MM.yyyy' }} + + + {{ row.funding_end | date: 'dd.MM.yyyy' }} + + + {{ row.funding_amount | currency: 'EUR' : 'symbol' : '1.0-0' : 'de' }} + + + + + open_in_new + + + + + open_in_new + +
- - - {{ row.funding_start | date: 'dd.MM.yyyy' }} - - - {{ row.funding_end | date: 'dd.MM.yyyy' }} - - - {{ row.funding_amount | currency: 'EUR' : 'symbol' : '1.0-0' : 'de' }} - - - - - open_in_new - - - - - open_in_new - - diff --git a/webapp/src/app/modules/institution-projects/institution-projects.component.ts b/webapp/src/app/modules/institution-projects/institution-projects.component.ts index 2df7d5ed..71285098 100644 --- a/webapp/src/app/modules/institution-projects/institution-projects.component.ts +++ b/webapp/src/app/modules/institution-projects/institution-projects.component.ts @@ -116,6 +116,20 @@ export class InstitutionProjectsComponent implements OnInit { return funding.annual_average_over_period ?? 0; }); + readonly childRoutes = [ + { + path: 'dfg', + label: 'DFG-Projekte', + }, + { + path: 'eu', + label: 'EU-Projekte', + }, + { + path: 'bund', + label: 'BUND-Projekte', + }, + ]; constructor( private readonly activatedRoute: ActivatedRoute, private readonly router: Router, -- 2.56.1 From 9a5cb9e9b07e3c47b987682a44d278f45e328cdd Mon Sep 17 00:00:00 2001 From: genja Date: Thu, 30 Jul 2026 01:23:31 +0200 Subject: [PATCH 05/11] added oa_authors to eu cordis details page --- .../publications-table.component.html | 52 +++++++++++-------- .../publications-table.component.scss | 22 ++++++++ .../publications-table.component.ts | 40 +++++++------- 3 files changed, 72 insertions(+), 42 deletions(-) diff --git a/webapp/src/app/modules/projects/eu-cordis-details/publications-table/publications-table.component.html b/webapp/src/app/modules/projects/eu-cordis-details/publications-table/publications-table.component.html index 99d9f154..8f444995 100644 --- a/webapp/src/app/modules/projects/eu-cordis-details/publications-table/publications-table.component.html +++ b/webapp/src/app/modules/projects/eu-cordis-details/publications-table/publications-table.component.html @@ -18,29 +18,37 @@ @if (pub.authors) { - @let authorList = parseAuthors(pub.authors); + @let authorList = pub.oaAuthors ?? []; + @let isExpanded = isPublicationAuthorsExpanded(pub); + @let visibleAuthors = + isExpanded ? authorList : authorList.slice(0, 3); +
+ @for ( + author of visibleAuthors; + track getAuthorTrackId(author, $index) + ) { + + } @empty { + - + } - @if (authorList.length > 0) { -
- @for (author of authorList; track author; let last = $last) { - - - {{ author }} - - - @if (!last) { - , - } - - } -
- } @else { - — - } + @if (authorList.length > 3) { + + } +
} @else { — } diff --git a/webapp/src/app/modules/projects/eu-cordis-details/publications-table/publications-table.component.scss b/webapp/src/app/modules/projects/eu-cordis-details/publications-table/publications-table.component.scss index c99c070b..9a8b171c 100644 --- a/webapp/src/app/modules/projects/eu-cordis-details/publications-table/publications-table.component.scss +++ b/webapp/src/app/modules/projects/eu-cordis-details/publications-table/publications-table.component.scss @@ -4,7 +4,29 @@ .card { margin-bottom: 24px; } + .publication-institution-more { + display: inline-flex; + align-items: center; + min-height: 24px; + padding: 3px 8px; + border: 1px solid var(--sg-border); + border-radius: var(--sg-radius-sm); + background: #fff; + color: var(--sg-text-muted); + font-family: inherit; + font-size: 11px; + line-height: 1.2; + cursor: pointer; + transition: all 0.2s ease; + &:hover, + &:focus-visible { + border-color: var(--sg-primary); + color: var(--sg-primary); + background: var(--sg-surface-soft); + outline: none; + } + } .section-header { display: flex; align-items: center; diff --git a/webapp/src/app/modules/projects/eu-cordis-details/publications-table/publications-table.component.ts b/webapp/src/app/modules/projects/eu-cordis-details/publications-table/publications-table.component.ts index aa95b495..bf71247b 100644 --- a/webapp/src/app/modules/projects/eu-cordis-details/publications-table/publications-table.component.ts +++ b/webapp/src/app/modules/projects/eu-cordis-details/publications-table/publications-table.component.ts @@ -15,6 +15,7 @@ import { Router } from '@angular/router'; import { TemplateRef } from '@angular/core'; import { PaginationService } from '../../../../shared/services/pagination.service'; import { MatPaginatorModule, PageEvent } from '@angular/material/paginator'; +import { AppAuthorChipComponent } from '../../../../shared/ui/app-author-chip/app-author-chip.component'; import { DataTableComponent, GenericColumn, @@ -29,6 +30,7 @@ import { MatTooltipModule, DataTableComponent, MatPaginatorModule, + AppAuthorChipComponent, ], templateUrl: './publications-table.component.html', styleUrl: './publications-table.component.scss', @@ -54,7 +56,7 @@ export class PublicationsTableComponent { yearTemplate = viewChild>('yearTemplate'); publisherTemplate = viewChild>('publisherTemplate'); linksTemplate = viewChild>('linksTemplate'); - + expandedPublicationAuthorsIds: string[] = []; // Displayed columns for the publications table columns = computed[]>(() => [ { @@ -139,25 +141,23 @@ export class PublicationsTableComponent { }, }); } - // Parse authors string into array of individual authors - parseAuthors(authorsString: string | undefined): string[] { - if (!authorsString) return []; + private getPublicationId(project: HEUPublication): string { + return String((project as any).id ?? ''); + } + isPublicationAuthorsExpanded(project: HEUPublication): boolean { + const projectId = this.getPublicationId(project); + return this.expandedPublicationAuthorsIds.includes(projectId); + } + togglePublicationAuthorsExpansion(project: HEUPublication): void { + const projectId = this.getPublicationId(project); + if (!projectId) return; - // Common separators: 'and', ',', ';', '&' - // Also handle cases like "Author1, Author2 and Author3" - let authors = authorsString; - - // Replace ' and ' with ', ' for consistent splitting - authors = authors.replace(/\s+and\s+/g, ', '); - - // Split by common separators - let authorList = authors.split(/[,;]\s*/); - - // Clean up each author name - authorList = authorList - .map((author) => author.trim()) - .filter((author) => author.length > 0); - - return authorList; + this.expandedPublicationAuthorsIds = + this.expandedPublicationAuthorsIds.includes(projectId) + ? this.expandedPublicationAuthorsIds.filter((id) => id !== projectId) + : [...this.expandedPublicationAuthorsIds, projectId]; + } + getAuthorTrackId(author: any, index: number): string { + return String(author.id ?? author.display_name ?? index); } } -- 2.56.1 From 32616fe6aae42b70ad3fb720fcc64f656c4ae4e7 Mon Sep 17 00:00:00 2001 From: genja Date: Thu, 30 Jul 2026 01:24:30 +0200 Subject: [PATCH 06/11] old chips replaced for oa_topics and oa_authors --- .../bund-project-table.component.html | 17 +++------ .../bund-project-table.component.ts | 2 + .../dfg-project-table.component.html | 17 +++------ .../dfg-project-table.component.ts | 4 +- .../eu-project-table.component.html | 37 +++++++------------ .../eu-project-table.component.ts | 17 +++------ 6 files changed, 35 insertions(+), 59 deletions(-) diff --git a/webapp/src/app/shared/ui/bund-project-table/bund-project-table.component.html b/webapp/src/app/shared/ui/bund-project-table/bund-project-table.component.html index 25d99ee9..a86e7f0f 100644 --- a/webapp/src/app/shared/ui/bund-project-table/bund-project-table.component.html +++ b/webapp/src/app/shared/ui/bund-project-table/bund-project-table.component.html @@ -94,18 +94,13 @@ isTopicsExpanded ? projectTopics : projectTopics.slice(0, 3);
@for (topic of visibleTopics; track $index) { - - + [topic]="topic" + [showIcon]="false" + [isSelected]="isTopicActive(topic)" + [isClickable]="topicFilterEnabled()" + (handleChipClick)="filterByTopic(topic)" /> } @empty { - } diff --git a/webapp/src/app/shared/ui/bund-project-table/bund-project-table.component.ts b/webapp/src/app/shared/ui/bund-project-table/bund-project-table.component.ts index e04dfdb7..1eab4fc3 100644 --- a/webapp/src/app/shared/ui/bund-project-table/bund-project-table.component.ts +++ b/webapp/src/app/shared/ui/bund-project-table/bund-project-table.component.ts @@ -11,6 +11,7 @@ import { CurrencyPipe, DatePipe } from '@angular/common'; import { BundProjectPage, Topic } from '../../../api'; import { BundProjectSummary } from '../../../api/model/bundProjectSummary'; import { TopicChipComponent } from '../topic-chip/topic-chip.component'; +import { AppTopicChipComponent } from '../app-topic-chip/app-topic-chip.component'; import { DataTableComponent, GenericColumn, @@ -38,6 +39,7 @@ import { bundProjectQueryParamKeys } from '../../../resolvers/bund-projects.reso CurrencyPipe, DatePipe, ChipComponent, + AppTopicChipComponent, ], templateUrl: './bund-project-table.component.html', styleUrl: './bund-project-table.component.scss', diff --git a/webapp/src/app/shared/ui/dfg-project-table/dfg-project-table.component.html b/webapp/src/app/shared/ui/dfg-project-table/dfg-project-table.component.html index 5d934742..607824ed 100644 --- a/webapp/src/app/shared/ui/dfg-project-table/dfg-project-table.component.html +++ b/webapp/src/app/shared/ui/dfg-project-table/dfg-project-table.component.html @@ -130,18 +130,13 @@ isTopicsExpanded ? projectTopics : projectTopics.slice(0, 3);
@for (topic of visibleTopics; track $index) { - - + [topic]="topic" + [showIcon]="false" + [isSelected]="isTopicActive(topic)" + [isClickable]="topicFilterEnabled()" + (handleChipClick)="filterByTopic(topic)" /> } @empty { - } diff --git a/webapp/src/app/shared/ui/dfg-project-table/dfg-project-table.component.ts b/webapp/src/app/shared/ui/dfg-project-table/dfg-project-table.component.ts index e26a685b..2b331607 100644 --- a/webapp/src/app/shared/ui/dfg-project-table/dfg-project-table.component.ts +++ b/webapp/src/app/shared/ui/dfg-project-table/dfg-project-table.component.ts @@ -8,7 +8,7 @@ import { inject, } from '@angular/core'; import { DfgProjectPage, DfgProjectSummary, Topic } from '../../../api'; -import { TopicChipComponent } from '../topic-chip/topic-chip.component'; +import { AppTopicChipComponent } from '../app-topic-chip/app-topic-chip.component'; import { DataTableComponent, GenericColumn, @@ -32,7 +32,7 @@ import { topicHierarchyColor } from '../../../resolvers/utils/topic-colors'; MatButtonModule, QueryParamPaginatorComponent, MatTooltip, - TopicChipComponent, + AppTopicChipComponent, ], templateUrl: './dfg-project-table.component.html', styleUrl: './dfg-project-table.component.scss', diff --git a/webapp/src/app/shared/ui/eu-project-table/eu-project-table.component.html b/webapp/src/app/shared/ui/eu-project-table/eu-project-table.component.html index 6a3c9c5c..68ef7152 100644 --- a/webapp/src/app/shared/ui/eu-project-table/eu-project-table.component.html +++ b/webapp/src/app/shared/ui/eu-project-table/eu-project-table.component.html @@ -48,19 +48,13 @@
@for (author of visibleAuthors; track getAuthorTrackId(author, $index)) { - + } @empty { - } @@ -127,18 +121,13 @@
@for (topic of visibleTopics; track topic.id ?? $index) { - - + [topic]="topic" + [showIcon]="false" + [isSelected]="isTopicActive(topic)" + [isClickable]="topicFilterEnabled()" + (handleChipClick)="filterByTopic(topic)" /> } @empty { - } diff --git a/webapp/src/app/shared/ui/eu-project-table/eu-project-table.component.ts b/webapp/src/app/shared/ui/eu-project-table/eu-project-table.component.ts index ad0ac7be..0a3fca02 100644 --- a/webapp/src/app/shared/ui/eu-project-table/eu-project-table.component.ts +++ b/webapp/src/app/shared/ui/eu-project-table/eu-project-table.component.ts @@ -21,7 +21,7 @@ import { } from '../data-table/data-table.component'; import { QueryParamPaginatorComponent } from '../query-param-paginator/query-param-paginator.component'; -import { TopicChipComponent } from '../topic-chip/topic-chip.component'; +import { AppTopicChipComponent } from '../app-topic-chip/app-topic-chip.component'; import { EuCordisProjectSearchPage } from '../../../api/model/euCordisProjectSearchPage'; import { EuCordisProjectSummary } from '../../../api/model/euCordisProjectSummary'; @@ -31,6 +31,7 @@ import { Author, Topic } from '../../../api'; import { euProjectQueryParamKeys } from '../../../resolvers/eu-cordis-projects.resolver'; import { topicHierarchyColor } from '../../../resolvers/utils/topic-colors'; import { ChipComponent } from '../chip/chip.component'; +import { AppAuthorChipComponent } from '../app-author-chip/app-author-chip.component'; @Component({ selector: 'app-eu-project-table', imports: [ @@ -42,8 +43,9 @@ import { ChipComponent } from '../chip/chip.component'; DatePipe, CurrencyPipe, QueryParamPaginatorComponent, - TopicChipComponent, + AppTopicChipComponent, ChipComponent, + AppAuthorChipComponent, ], templateUrl: './eu-project-table.component.html', styleUrl: './eu-project-table.component.scss', @@ -165,7 +167,6 @@ export class EuProjectTableComponent { }, ]); getProjectTypeColor(type: string | null | undefined): string { - //console.log(type); const normalized = (type ?? '').toLowerCase(); if (normalized == 'fp7') return 'success'; if (normalized == 'h2020') return 'help'; @@ -243,14 +244,9 @@ export class EuProjectTableComponent { } getAuthorId(author: any): string | null { - const id = - author?.id ?? - author?.author_id ?? - author?.authorId ?? - author?.openalex_id ?? - author?.openAlexId; + const id = author.id; - return id == null ? null : String(id); + return id === null ? null : String(id); } getAuthorName(author: any): string { @@ -289,7 +285,6 @@ export class EuProjectTableComponent { filterByAuthor(author: any): void { const authorId = this.getAuthorId(author); - if (!authorId || !this.authorFilterEnabled()) return; const selectedAuthorIds = this.selectedAuthorIdsQueryParams(); -- 2.56.1 From f27ee8b2954b932dc48405f00fdf1cbbb4e7b4be Mon Sep 17 00:00:00 2001 From: genja Date: Thu, 30 Jul 2026 01:30:14 +0200 Subject: [PATCH 07/11] updated resolvers for projects fetching for institutions --- webapp/src/app/app.routes.ts | 69 +++++++++++++++-- .../app/resolvers/bund-projects.resolver.ts | 77 ++++++++++++++----- .../app/resolvers/dfg-projects.resolver.ts | 27 +++++++ .../resolvers/eu-cordis-projects.resolver.ts | 20 ++--- 4 files changed, 154 insertions(+), 39 deletions(-) diff --git a/webapp/src/app/app.routes.ts b/webapp/src/app/app.routes.ts index 1a63d1a6..a7c72897 100644 --- a/webapp/src/app/app.routes.ts +++ b/webapp/src/app/app.routes.ts @@ -690,17 +690,70 @@ export const routes: Routes = [ (mod) => mod.InstitutionProjectsComponent, ), resolve: { - bundProjectPage: bundProjectPageResolver, bundProjectsFunding: bundProjectsFundingResolver, - cordisEuProjectPage: euCordisProjectsResolver, cordisEuProjectsFunding: cordisEuProjectsFundingResolver, }, - runGuardsAndResolvers: (from, to) => { - const keys = ['page', 'size', 'sort_by', 'sort_direction', 'search']; - return keys.some( - (key) => from.queryParamMap.get(key) !== to.queryParamMap.get(key), - ); - }, + 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.INSTITUTION, + }, + }, + { + path: 'eu', + component: EuProjectsComponent, + resolve: { + euCordisProjectPage: euCordisProjectsResolver, + selectedEuInstitutionsPage: selectedEuInstitutionsResolver, + selectedEuAuthorsPage: selectedAuthorsResolver, + selectedTopicsPage: selectedTopicsResolver, + }, + runGuardsAndResolvers: 'always', + data: { + resolvingFor: RESOLVING_PROJECT_PAGE_FOR.INSTITUTION, + }, + }, + { + path: 'bund', + component: BundProjectsComponent, + resolve: { + bundProjectPage: bundProjectsResolver, + selectedBundInstitutionsPage: selectedBundInstitutionsResolver, + selectedBundAuthorsPage: selectedAuthorsResolver, + selectedTopicsPage: selectedTopicsResolver, + }, + runGuardsAndResolvers: 'always', + data: { + resolvingFor: RESOLVING_PROJECT_PAGE_FOR.INSTITUTION, + }, + }, + ], + // resolve: { + // bundProjectPage: bundProjectPageResolver, + // bundProjectsFunding: bundProjectsFundingResolver, + // cordisEuProjectPage: euCordisProjectsResolver, + // cordisEuProjectsFunding: cordisEuProjectsFundingResolver, + // }, + // runGuardsAndResolvers: (from, to) => { + // const keys = ['page', 'size', 'sort_by', 'sort_direction', 'search']; + // return keys.some( + // (key) => from.queryParamMap.get(key) !== to.queryParamMap.get(key), + // ); + // }, }, { path: 'patents', diff --git a/webapp/src/app/resolvers/bund-projects.resolver.ts b/webapp/src/app/resolvers/bund-projects.resolver.ts index 78e8269a..1ae1d539 100644 --- a/webapp/src/app/resolvers/bund-projects.resolver.ts +++ b/webapp/src/app/resolvers/bund-projects.resolver.ts @@ -24,16 +24,24 @@ export const bundProjectQueryParamKeys = { topics: 'topics', agency: 'agency', } as const; +const RESOLVING_PROJECT_PAGE_FOR_KEY = 'resolvingFor'; + +export const RESOLVING_PROJECT_PAGE_FOR = { + INSTITUTION: 'INSTITUTION', + PERSON: 'PERSON', + KEYWORDS_SEARCH: 'KEYWORDS_SEARCH', +} as const; export const bundProjectsResolver: ResolveFn = ( route, state, ) => { + const resolvingFor: (typeof RESOLVING_PROJECT_PAGE_FOR)[keyof typeof RESOLVING_PROJECT_PAGE_FOR] = + route.data[RESOLVING_PROJECT_PAGE_FOR_KEY] || + RESOLVING_PROJECT_PAGE_FOR.PERSON; const page = route.queryParamMap.get(bundProjectQueryParamKeys.page) ?? '0'; const size = route.queryParamMap.get(bundProjectQueryParamKeys.size) ?? '10'; - const institutionIds = route.queryParamMap.getAll( - bundProjectQueryParamKeys.institutionId, - ); + const fundingStartYears = route.queryParamMap.getAll( bundProjectQueryParamKeys.funding_start, ); @@ -61,22 +69,49 @@ export const bundProjectsResolver: ResolveFn = ( const executingAgency = route.queryParamMap.getAll( bundProjectQueryParamKeys.agency, ); - - return inject(ProjectsService).searchBundProjectsWithFilters( - executingAgency, - fundingType, - search, - keywords, - topics, - topicIds, - fundingStartYears, - fundingEndYears, - [], - institutionIds, - Number(page), - Number(size), - sortBy, - sortDirection, - fuzzySearch, - ); + if (resolvingFor === RESOLVING_PROJECT_PAGE_FOR.KEYWORDS_SEARCH) { + return inject(ProjectsService).searchBundProjectsWithFilters( + executingAgency, + fundingType, + search, + keywords, + topics, + topicIds, + fundingStartYears, + fundingEndYears, + [], + undefined, + Number(page), + Number(size), + sortBy, + sortDirection, + fuzzySearch, + ); + } else if (resolvingFor === RESOLVING_PROJECT_PAGE_FOR.INSTITUTION) { + const oaInstitutionId = route.parent?.parent?.params['institutionId']; + if (!oaInstitutionId) { + throw new Error( + 'Institution ID is required to resolve BUND projects for institution', + ); + } + return inject(ProjectsService).searchBundProjectsWithFilters( + executingAgency, + fundingType, + search, + keywords, + topics, + topicIds, + fundingStartYears, + fundingEndYears, + [], + oaInstitutionId, + Number(page), + Number(size), + sortBy, + sortDirection, + fuzzySearch, + ); + } else { + throw new Error(`Unhandled resolvingFor value: ${resolvingFor}`); + } }; diff --git a/webapp/src/app/resolvers/dfg-projects.resolver.ts b/webapp/src/app/resolvers/dfg-projects.resolver.ts index 495abd78..1391bd49 100644 --- a/webapp/src/app/resolvers/dfg-projects.resolver.ts +++ b/webapp/src/app/resolvers/dfg-projects.resolver.ts @@ -69,6 +69,7 @@ export const dfgProjectsResolver: ResolveFn = ( if (resolvingFor === RESOLVING_PROJECT_PAGE_FOR.PERSON) { const rawAuthorId = route.parent?.parent?.params['id']; return inject(ProjectsService).getDfgProjects( + undefined, rawAuthorId, authorIds, institutionIds, @@ -89,6 +90,7 @@ export const dfgProjectsResolver: ResolveFn = ( const selectedTopicIds = route.queryParamMap.getAll('topics'); const fuzzySearch = route.queryParamMap.get('fuzzy') === 'true'; return inject(ProjectsService).getDfgProjects( + undefined, undefined, authorIds, institutionIds, @@ -104,6 +106,31 @@ export const dfgProjectsResolver: ResolveFn = ( sortDirection, fuzzySearch, ); + } else if (resolvingFor === RESOLVING_PROJECT_PAGE_FOR.INSTITUTION) { + const oaInstitutionId = route.parent?.parent?.params['institutionId']; + console.log( + 'Resolving project page for institution', + oaInstitutionId, + 'with route data:', + route.data, + ); + return inject(ProjectsService).getDfgProjects( + oaInstitutionId, + undefined, + authorIds, + institutionIds, + searchTerm, + [], + [], + filteredTopicIds, + fundingStart, + fundingEnd, + page, + size, + sortBy, + sortDirection, + false, + ); } else { throw new Error(`Unknown resolvingFor value: ${resolvingFor}`); } diff --git a/webapp/src/app/resolvers/eu-cordis-projects.resolver.ts b/webapp/src/app/resolvers/eu-cordis-projects.resolver.ts index f3ef49de..a9a14e26 100644 --- a/webapp/src/app/resolvers/eu-cordis-projects.resolver.ts +++ b/webapp/src/app/resolvers/eu-cordis-projects.resolver.ts @@ -201,7 +201,7 @@ export const euCordisProjectsResolver: ResolveFn = ( let rawInstitutionId = route.paramMap.get('institutionId') ?? undefined; if (!rawInstitutionId) { rawInstitutionId = - route.parent?.paramMap.get('institutionId') ?? undefined; + route.parent?.parent?.paramMap.get('institutionId') ?? undefined; } console.log( 'Resolving EU project page for institution with ID:', @@ -210,20 +210,20 @@ export const euCordisProjectsResolver: ResolveFn = ( return inject(ProjectsService).searchEuCordisProjects( rawInstitutionId, undefined, - [], + authorIds, organizationIds, [], - [], + projectTypes as any, searchTerm, [], [], - [], - [], - [], - [], - [], - [], - [], + filteredTopicIds, + fundingStart, + fundingEnd, + countries, + frameworkProgrammes, + fundingSchemes, + statuses, page, size, sortBy, -- 2.56.1 From 176235689f747aa3db2e2ba1ad9855a21d05e9e0 Mon Sep 17 00:00:00 2001 From: genja Date: Thu, 30 Jul 2026 01:30:30 +0200 Subject: [PATCH 08/11] removed unused imports --- .../institution-projects.component.ts | 10 +--------- .../bund-project-table/bund-project-table.component.ts | 2 -- 2 files changed, 1 insertion(+), 11 deletions(-) diff --git a/webapp/src/app/modules/institution-projects/institution-projects.component.ts b/webapp/src/app/modules/institution-projects/institution-projects.component.ts index 71285098..80b66106 100644 --- a/webapp/src/app/modules/institution-projects/institution-projects.component.ts +++ b/webapp/src/app/modules/institution-projects/institution-projects.component.ts @@ -20,18 +20,13 @@ import { MatFormFieldModule } from '@angular/material/form-field'; import { MatTabChangeEvent, MatTabsModule } from '@angular/material/tabs'; import { FormsModule } from '@angular/forms'; import { MatInputModule } from '@angular/material/input'; -import { - GenericColumn, - DataTableComponent, -} from '../../shared/ui/data-table/data-table.component'; +import { GenericColumn } from '../../shared/ui/data-table/data-table.component'; import { CurrencyPipe, DatePipe } from '@angular/common'; import { toSignal } from '@angular/core/rxjs-interop'; import { MatIconModule } from '@angular/material/icon'; import { MatButtonModule } from '@angular/material/button'; import { InstitutionProjectsFundingGraphComponent } from '../institution-projects-funding-graph/institution-projects-funding-graph.component'; import { AppInfoCardComponent } from '../../shared/ui/app-info-card/app-info-card.component'; -import { QueryParamPaginatorComponent } from '../../shared/ui/query-param-paginator/query-param-paginator.component'; -import { QueryParamInputComponent } from '../../shared/ui/query-param-input/query-param-input.component'; type BundProjectRow = { id: string; @@ -58,7 +53,6 @@ type EuProjectRow = { MatTabsModule, FormsModule, MatInputModule, - DataTableComponent, DatePipe, CurrencyPipe, MatIconModule, @@ -66,8 +60,6 @@ type EuProjectRow = { InstitutionProjectsFundingGraphComponent, AppInfoCardComponent, RouterModule, - QueryParamPaginatorComponent, - QueryParamInputComponent, ], templateUrl: './institution-projects.component.html', styleUrl: './institution-projects.component.scss', diff --git a/webapp/src/app/shared/ui/bund-project-table/bund-project-table.component.ts b/webapp/src/app/shared/ui/bund-project-table/bund-project-table.component.ts index 1eab4fc3..daeeb614 100644 --- a/webapp/src/app/shared/ui/bund-project-table/bund-project-table.component.ts +++ b/webapp/src/app/shared/ui/bund-project-table/bund-project-table.component.ts @@ -10,7 +10,6 @@ import { import { CurrencyPipe, DatePipe } from '@angular/common'; import { BundProjectPage, Topic } from '../../../api'; import { BundProjectSummary } from '../../../api/model/bundProjectSummary'; -import { TopicChipComponent } from '../topic-chip/topic-chip.component'; import { AppTopicChipComponent } from '../app-topic-chip/app-topic-chip.component'; import { DataTableComponent, @@ -35,7 +34,6 @@ import { bundProjectQueryParamKeys } from '../../../resolvers/bund-projects.reso MatButtonModule, QueryParamPaginatorComponent, MatTooltip, - TopicChipComponent, CurrencyPipe, DatePipe, ChipComponent, -- 2.56.1 From 25de01c7beb382705b339f2c9012dcc8cab12abe Mon Sep 17 00:00:00 2001 From: genja Date: Thu, 30 Jul 2026 01:30:44 +0200 Subject: [PATCH 09/11] regenerated models and services --- webapp/src/app/api/.openapi-generator/FILES | 1 + webapp/src/app/api/api/projects.service.ts | 29 ++++++------ .../api/model/dfgProjectStatusStatistics.ts | 19 ++++++++ webapp/src/app/api/model/fp7Publication.ts | 44 +++++++++---------- webapp/src/app/api/model/h2020Publication.ts | 44 +++++++++---------- webapp/src/app/api/model/hEUPublication.ts | 44 +++++++++---------- webapp/src/app/api/model/models.ts | 1 + 7 files changed, 101 insertions(+), 81 deletions(-) create mode 100644 webapp/src/app/api/model/dfgProjectStatusStatistics.ts diff --git a/webapp/src/app/api/.openapi-generator/FILES b/webapp/src/app/api/.openapi-generator/FILES index 20eadd30..e751f4aa 100644 --- a/webapp/src/app/api/.openapi-generator/FILES +++ b/webapp/src/app/api/.openapi-generator/FILES @@ -106,6 +106,7 @@ model/dfgProjectInstitutionRole.ts model/dfgProjectPage.ts model/dfgProjectPersonRole.ts model/dfgProjectPublicationSummary.ts +model/dfgProjectStatusStatistics.ts model/dfgProjectSubjectArea.ts model/dfgProjectSubprojectSummary.ts model/dfgProjectSummary.ts diff --git a/webapp/src/app/api/api/projects.service.ts b/webapp/src/app/api/api/projects.service.ts index bbe23b17..6e8b105b 100644 --- a/webapp/src/app/api/api/projects.service.ts +++ b/webapp/src/app/api/api/projects.service.ts @@ -67,6 +67,7 @@ export class ProjectsService extends BaseService { * Get DFG projects. * Returns a page of DFG projects based on the provided pagination parameters and optional institution filter. * @endpoint get /api/projects/person/dfg/search + * @param rawOaInstitutionId The openalex institution ID to filter by. * @param authorId The openalex author ID to filter by. * @param authorFilterIds The dfg author IDs to filter by. * @param institutionIds The institution IDs to filter by. @@ -84,12 +85,14 @@ export class ProjectsService extends BaseService { * @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 getDfgProjects(authorId?: string, authorFilterIds?: Array, institutionIds?: Array, title?: string, keywords?: Array, topicIds?: Array, filterTopicIds?: Array, fundingStartYears?: Array, fundingEndYears?: 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 getDfgProjects(authorId?: string, authorFilterIds?: Array, institutionIds?: Array, title?: string, keywords?: Array, topicIds?: Array, filterTopicIds?: Array, fundingStartYears?: Array, fundingEndYears?: 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 getDfgProjects(authorId?: string, authorFilterIds?: Array, institutionIds?: Array, title?: string, keywords?: Array, topicIds?: Array, filterTopicIds?: Array, fundingStartYears?: Array, fundingEndYears?: 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 getDfgProjects(authorId?: string, authorFilterIds?: Array, institutionIds?: Array, title?: string, keywords?: Array, topicIds?: Array, filterTopicIds?: Array, fundingStartYears?: Array, fundingEndYears?: 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 { + public getDfgProjects(rawOaInstitutionId?: string, authorId?: string, authorFilterIds?: Array, institutionIds?: Array, title?: string, keywords?: Array, topicIds?: Array, filterTopicIds?: Array, fundingStartYears?: Array, fundingEndYears?: 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 getDfgProjects(rawOaInstitutionId?: string, authorId?: string, authorFilterIds?: Array, institutionIds?: Array, title?: string, keywords?: Array, topicIds?: Array, filterTopicIds?: Array, fundingStartYears?: Array, fundingEndYears?: 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 getDfgProjects(rawOaInstitutionId?: string, authorId?: string, authorFilterIds?: Array, institutionIds?: Array, title?: string, keywords?: Array, topicIds?: Array, filterTopicIds?: Array, fundingStartYears?: Array, fundingEndYears?: 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 getDfgProjects(rawOaInstitutionId?: string, authorId?: string, authorFilterIds?: Array, institutionIds?: Array, title?: string, keywords?: Array, topicIds?: Array, filterTopicIds?: Array, fundingStartYears?: Array, fundingEndYears?: 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, + rawOaInstitutionId, 'raw_oa_institution_id'); localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, authorId, 'author_id'); if (authorFilterIds) { @@ -681,7 +684,7 @@ export class ProjectsService extends BaseService { * @param fundingStartYears Funding start years. * @param fundingEndYears Funding end years. * @param countries Organization countries. - * @param institutionIds Institution IDs to filter by. + * @param rawOaInstitutionId The ID of the institution to filter by. * @param page The page number. * @param size The page size. * @param sortBy Sort field. @@ -690,10 +693,10 @@ export class ProjectsService extends BaseService { * @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 searchBundProjectsWithFilters(executingAgency?: Array, fundingArts?: Array, title?: string, keywords?: Array, topicIds?: Array, filterTopicIds?: Array, fundingStartYears?: Array, fundingEndYears?: Array, countries?: Array, institutionIds?: 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 searchBundProjectsWithFilters(executingAgency?: Array, fundingArts?: Array, title?: string, keywords?: Array, topicIds?: Array, filterTopicIds?: Array, fundingStartYears?: Array, fundingEndYears?: Array, countries?: Array, institutionIds?: 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 searchBundProjectsWithFilters(executingAgency?: Array, fundingArts?: Array, title?: string, keywords?: Array, topicIds?: Array, filterTopicIds?: Array, fundingStartYears?: Array, fundingEndYears?: Array, countries?: Array, institutionIds?: 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 searchBundProjectsWithFilters(executingAgency?: Array, fundingArts?: Array, title?: string, keywords?: Array, topicIds?: Array, filterTopicIds?: Array, fundingStartYears?: Array, fundingEndYears?: Array, countries?: Array, institutionIds?: 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 { + public searchBundProjectsWithFilters(executingAgency?: Array, fundingArts?: Array, title?: string, keywords?: Array, topicIds?: Array, filterTopicIds?: Array, fundingStartYears?: Array, fundingEndYears?: Array, countries?: Array, rawOaInstitutionId?: string, page?: number, size?: number, sortBy?: string, sortDirection?: string, fuzzy?: boolean, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public searchBundProjectsWithFilters(executingAgency?: Array, fundingArts?: Array, title?: string, keywords?: Array, topicIds?: Array, filterTopicIds?: Array, fundingStartYears?: Array, fundingEndYears?: Array, countries?: Array, rawOaInstitutionId?: string, page?: number, size?: number, sortBy?: string, sortDirection?: string, fuzzy?: boolean, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public searchBundProjectsWithFilters(executingAgency?: Array, fundingArts?: Array, title?: string, keywords?: Array, topicIds?: Array, filterTopicIds?: Array, fundingStartYears?: Array, fundingEndYears?: Array, countries?: Array, rawOaInstitutionId?: string, page?: number, size?: number, sortBy?: string, sortDirection?: string, fuzzy?: boolean, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public searchBundProjectsWithFilters(executingAgency?: Array, fundingArts?: Array, title?: string, keywords?: Array, topicIds?: Array, filterTopicIds?: Array, fundingStartYears?: Array, fundingEndYears?: Array, countries?: Array, rawOaInstitutionId?: string, 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}); if (executingAgency) { @@ -746,12 +749,8 @@ export class ProjectsService extends BaseService { element, 'countries'); }) } - if (institutionIds) { - institutionIds.forEach((element) => { - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - element, 'institution_ids'); - }) - } + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + rawOaInstitutionId, 'raw_oa_institution_id'); localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, page, 'page'); localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, diff --git a/webapp/src/app/api/model/dfgProjectStatusStatistics.ts b/webapp/src/app/api/model/dfgProjectStatusStatistics.ts new file mode 100644 index 00000000..3b7d566a --- /dev/null +++ b/webapp/src/app/api/model/dfgProjectStatusStatistics.ts @@ -0,0 +1,19 @@ +/** + * 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 DfgProjectStatusStatistics { + institution_id: string; + organization_name: string; + ongoing: number; + upcoming: number; + completed: number; +} + diff --git a/webapp/src/app/api/model/fp7Publication.ts b/webapp/src/app/api/model/fp7Publication.ts index fd0e2491..e8a9a862 100644 --- a/webapp/src/app/api/model/fp7Publication.ts +++ b/webapp/src/app/api/model/fp7Publication.ts @@ -1,35 +1,35 @@ /** * 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 { Author } from './author'; /** * Fp7Publication */ -export interface Fp7Publication { - authors?: string | null; - collection?: string | null; - contentUpdateDate?: string | null; - doi?: string | null; - id?: string | null; - isPublishedAs?: string | null; - journalNumber?: string | null; - journalTitle?: string | null; - projectAcronym?: string | null; - projectID?: string | null; - publishedPages?: string | null; - publishedYear?: number | null; - publisher?: string | null; - qaProcessedDoi?: string | null; - rcn?: string | null; - repositoryUrl?: string | null; - title?: string | null; - volume?: string | null; +export interface Fp7Publication { + authors?: string | null; + oaAuthors?: Array | null; + collection?: string | null; + contentUpdateDate?: string | null; + doi?: string | null; + id?: string | null; + isPublishedAs?: string | null; + journalNumber?: string | null; + journalTitle?: string | null; + projectAcronym?: string | null; + projectID?: string | null; + publishedPages?: string | null; + publishedYear?: number | null; + publisher?: string | null; + qaProcessedDoi?: string | null; + rcn?: string | null; + repositoryUrl?: string | null; + title?: string | null; + volume?: string | null; } - diff --git a/webapp/src/app/api/model/h2020Publication.ts b/webapp/src/app/api/model/h2020Publication.ts index 945e22d2..935a64fd 100644 --- a/webapp/src/app/api/model/h2020Publication.ts +++ b/webapp/src/app/api/model/h2020Publication.ts @@ -1,35 +1,35 @@ /** * 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 { Author } from './author'; /** * H2020Publication */ -export interface H2020Publication { - authors?: string | null; - collection?: string | null; - contentUpdateDate?: string | null; - doi?: string | null; - id?: string | null; - isPublishedAs?: string | null; - journalNumber?: string | null; - journalTitle?: string | null; - projectAcronym?: string | null; - projectID?: string | null; - publishedPages?: string | null; - publishedYear?: number | null; - publisher?: string | null; - qaProcessedDoi?: string | null; - rcn?: string | null; - repositoryUrl?: string | null; - title?: string | null; - volume?: string | null; +export interface H2020Publication { + authors?: string | null; + oaAuthors?: Array | null; + collection?: string | null; + contentUpdateDate?: string | null; + doi?: string | null; + id?: string | null; + isPublishedAs?: string | null; + journalNumber?: string | null; + journalTitle?: string | null; + projectAcronym?: string | null; + projectID?: string | null; + publishedPages?: string | null; + publishedYear?: number | null; + publisher?: string | null; + qaProcessedDoi?: string | null; + rcn?: string | null; + repositoryUrl?: string | null; + title?: string | null; + volume?: string | null; } - diff --git a/webapp/src/app/api/model/hEUPublication.ts b/webapp/src/app/api/model/hEUPublication.ts index 4d067177..e607a3ed 100644 --- a/webapp/src/app/api/model/hEUPublication.ts +++ b/webapp/src/app/api/model/hEUPublication.ts @@ -1,35 +1,35 @@ /** * 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 { Author } from './author'; /** * HEUPublication */ -export interface HEUPublication { - authors?: string | null; - collection?: string | null; - contentUpdateDate?: string | null; - doi?: string | null; - id?: string | null; - isPublishedAs?: string | null; - journalNumber?: string | null; - journalTitle?: string | null; - projectAcronym?: string | null; - projectID?: string | null; - publishedPages?: string | null; - publishedYear?: number | null; - publisher?: string | null; - qaProcessedDoi?: string | null; - rcn?: string | null; - repositoryUrl?: string | null; - title?: string | null; - volume?: string | null; +export interface HEUPublication { + authors?: string | null; + oaAuthors?: Array | null; + collection?: string | null; + contentUpdateDate?: string | null; + doi?: string | null; + id?: string | null; + isPublishedAs?: string | null; + journalNumber?: string | null; + journalTitle?: string | null; + projectAcronym?: string | null; + projectID?: string | null; + publishedPages?: string | null; + publishedYear?: number | null; + publisher?: string | null; + qaProcessedDoi?: string | null; + rcn?: string | null; + repositoryUrl?: string | null; + title?: string | null; + volume?: string | null; } - diff --git a/webapp/src/app/api/model/models.ts b/webapp/src/app/api/model/models.ts index 89361c91..c16ec742 100644 --- a/webapp/src/app/api/model/models.ts +++ b/webapp/src/app/api/model/models.ts @@ -71,6 +71,7 @@ export * from './dfgProjectInstitutionRole'; export * from './dfgProjectPage'; export * from './dfgProjectPersonRole'; export * from './dfgProjectPublicationSummary'; +export * from './dfgProjectStatusStatistics'; export * from './dfgProjectSubjectArea'; export * from './dfgProjectSubprojectSummary'; export * from './dfgProjectSummary'; -- 2.56.1 From 211f7b82dc515460b53cafe3652fc1a54a492477 Mon Sep 17 00:00:00 2001 From: genja Date: Sat, 1 Aug 2026 01:57:42 +0200 Subject: [PATCH 10/11] optimized funding data retrieval + added filters --- .../projects/eu_cordis_projects_client.py | 191 ++++++++++++++++-- .../inse/projects/projects_search_client.py | 20 +- service/src/main/inse/projects/router.py | 153 +++++++++++++- service/src/main/inse/projects/service.py | 190 +++++++++++++---- 4 files changed, 483 insertions(+), 71 deletions(-) diff --git a/service/src/main/inse/projects/eu_cordis_projects_client.py b/service/src/main/inse/projects/eu_cordis_projects_client.py index 24a8fc51..473148a3 100644 --- a/service/src/main/inse/projects/eu_cordis_projects_client.py +++ b/service/src/main/inse/projects/eu_cordis_projects_client.py @@ -704,9 +704,13 @@ async def get_eu_euroscivoc_for_projects( return lookup -async def search_eu_cordis_projects( - page: int, - size: int, +class _NoMatchingEuProjects(Exception): + """Internal sentinel: some filter resolved to zero matching project IDs, + so the overall query can short-circuit to an empty result without + hitting Elasticsearch again.""" + + +async def _build_eu_cordis_search_query( project_types: Optional[List[EuCordisProjectType]] = None, organization_ids: Optional[List[str]] = None, organization_names: Optional[List[str]] = None, @@ -721,16 +725,16 @@ async def search_eu_cordis_projects( 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: +) -> Tuple[Dict[str, Any], List[EuCordisProjectType], List[Any]]: """ - 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 + Builds the (query, project_types, indices) tuple shared by every EU CORDIS + project search/aggregation. Centralizing this means the filters applied to + the results table and to any derived aggregation (e.g. funding-over-time) + can never drift apart. + + Raises _NoMatchingEuProjects if any filter resolves to zero project IDs, + so callers can short-circuit to an empty result without a wasted query. """ if not project_types: project_types = [ @@ -746,7 +750,7 @@ async def search_eu_cordis_projects( # === 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) + raise _NoMatchingEuProjects() must_clauses.append({"terms": {"id": author_project_ids}}) @@ -759,7 +763,7 @@ async def search_eu_cordis_projects( 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) + raise _NoMatchingEuProjects() must_clauses.append(topic_filter) @@ -814,7 +818,7 @@ async def search_eu_cordis_projects( 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) + raise _NoMatchingEuProjects() must_clauses.append(topic_filter) @@ -828,7 +832,7 @@ async def search_eu_cordis_projects( 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) + raise _NoMatchingEuProjects() must_clauses.append(org_filter) @@ -891,12 +895,64 @@ async def search_eu_cordis_projects( 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) + raise _NoMatchingEuProjects() must_clauses.append(country_filter) query = {"bool": {"must": must_clauses}} if must_clauses else {"match_all": {}} + return query, project_types, indices + + +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 + """ + try: + query, project_types, indices = await _build_eu_cordis_search_query( + 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, + fuzzy=fuzzy, + ) + except _NoMatchingEuProjects: + return EuCordisProjectSearchPage(elements=[], total=0, page=page, size=size) + sort_direction = sort_direction.lower() if sort_direction not in ["asc", "desc"]: sort_direction = "asc" @@ -986,7 +1042,108 @@ async def search_eu_cordis_projects( page=page, size=size, ) - + + +async def get_eu_cordis_projects_funding_data( + 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, + fuzzy: bool = False, +) -> List[Dict[str, Any]]: + """ + Fetches ONLY the fields needed for a funding-over-time aggregation + (id, startDate, endDate, ecMaxContribution) for every EU CORDIS project + matching the given filters. + + This intentionally skips the author/organization/CORDIS-topic/EuroSciVoc/ + OpenAlex-topic enrichment that `search_eu_cordis_projects` performs per + project, since none of that is needed to compute funding totals. That + enrichment is what makes the funding-over-time endpoint slow for + institutions with many projects - this function avoids it entirely. + + """ + try: + query, _, indices = await _build_eu_cordis_search_query( + 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, + fuzzy=fuzzy, + ) + except _NoMatchingEuProjects: + return [] + + results: List[Dict[str, Any]] = [] + page_size = 5000 + search_after: Optional[List[Any]] = None + + while True: + body: Dict[str, Any] = { + "size": page_size, + "track_total_hits": False, + "_source": ["id", "startDate", "endDate", "ecMaxContribution"], + "query": query, + # "id" is unique per project and used elsewhere as a term-filter + # field, so it's mapped as keyword - safe + deterministic sort + # key for search_after pagination across an arbitrarily large + # result set. + "sort": [{"id": {"order": "asc", "unmapped_type": "keyword"}}], + } + if search_after is not None: + body["search_after"] = search_after + + response = await elasticsearch.search( + index=indices, + cluster=ESCluster.INSE, + body=body, + ) + + hits = response.get("hits", {}).get("hits", []) + if not hits: + break + + for hit in hits: + source = hit.get("_source", {}) + results.append( + { + "id": source.get("id"), + "start_date": source.get("startDate"), + "end_date": source.get("endDate"), + "ec_max_contribution": source.get("ecMaxContribution"), + } + ) + + if len(hits) < page_size: + break + + search_after = hits[-1].get("sort") + if not search_after: + break + + return results + + 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').""" diff --git a/service/src/main/inse/projects/projects_search_client.py b/service/src/main/inse/projects/projects_search_client.py index 8f97b0ae..82240cc1 100644 --- a/service/src/main/inse/projects/projects_search_client.py +++ b/service/src/main/inse/projects/projects_search_client.py @@ -700,9 +700,15 @@ async def search_bund_projects_with_filters( sort_by: str = "title", sort_direction: str = "asc", fuzzy: bool = False, + skip_topic_enrichment: bool = False, ) -> BundProjectPage: """ Main search function for BUND projects, analogous to the DFG search. + + skip_topic_enrichment: when True, skips the extra OpenAlex-topics lookup + used to populate `oa_topics` on each result. Callers that only need core + project fields (e.g. funding-over-time aggregation) should set this to + avoid the unnecessary ES round trip. """ from_ = page * size #institution_ids = ["I62318514"] @@ -865,11 +871,13 @@ async def search_bund_projects_with_filters( hits = response.get("hits", {}).get("hits", []) - # Enrich with OpenAlex topics - project_ids = [hit["_id"] for hit in hits] - topic_lookup = await get_openalex_topics_for_bund_projects(project_ids=project_ids) - for hit in hits: - hit["_source"]["oa_topics"] = topic_lookup.get(hit["_id"], []) + # Enrich with OpenAlex topics (skipped for callers that don't need them, + # e.g. funding-over-time aggregation, to avoid an unnecessary ES call) + if not skip_topic_enrichment: + project_ids = [hit["_id"] for hit in hits] + topic_lookup = await get_openalex_topics_for_bund_projects(project_ids=project_ids) + for hit in hits: + hit["_source"]["oa_topics"] = topic_lookup.get(hit["_id"], []) return _complete_response_to_bund_project_page(response, page, size) @@ -1037,4 +1045,4 @@ def _hit_to_funding_project(hit: Dict[str, Any]) -> FundingProject: else: raise ValueError( "The provided hit does not belong to a recognized project index." - ) + ) \ No newline at end of file diff --git a/service/src/main/inse/projects/router.py b/service/src/main/inse/projects/router.py index 614ddc6f..82d980c3 100644 --- a/service/src/main/inse/projects/router.py +++ b/service/src/main/inse/projects/router.py @@ -435,7 +435,11 @@ async def get_single_eu_cordis_project( @router.get( "/institution/bund/funding-over-time", summary="Get funding over time for bund projects.", - description="Returns the funding over time for bund projects associated with the specified institution.", + description=( + "Returns the funding over time for BUND projects. Accepts the same " + "filters as /bund/search, so the funding total can be made to match " + "whatever the results table is currently filtered to." + ), operation_id="getInstitutionBundProjectsFundingOverTime", responses={ status.HTTP_200_OK: { @@ -451,19 +455,73 @@ async def get_institution_bund_projects_funding_over_time( InstitutionsSearchClient, Depends(get_institutions_search_client) ], raw_oa_institution_id: Annotated[ - str, Query(description="The institution ID to filter by.") - ], + Optional[str], Query(description="The institution ID to filter by.") + ] = None, + executing_agency: Annotated[ + Optional[List[str]], + Query(description="Executing Agencies (Ausführende Stellen) to filter by."), + ] = None, + funding_arts: Annotated[ + Optional[List[str]], + 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, + fuzzy: Annotated[ + bool, + Query(description="Use OpenAlex topic-id resolution if true, otherwise raw keyword search."), + ] = False, ) -> InstitutionFunderSummary: return await projects_service.get_institution_bund_projects_funding_over_time( institutions_search_client=institutions_search_client, raw_oa_institution_id=raw_oa_institution_id, + executing_agency=executing_agency, + funding_arts=funding_arts, + 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, + fuzzy=fuzzy, ) @router.get( "/institution/eu/funding-over-time", summary="Get funding over time for EU projects.", - description="Returns the funding over time for EU projects associated with the specified institution.", + description=( + "Returns the funding over time for EU CORDIS projects. Accepts the " + "same filters as /eu/search, so the funding total can be made to " + "match whatever the results table is currently filtered to." + ), operation_id="getInstitutionCordisEuProjectsFundingOverTime", responses={ status.HTTP_200_OK: { @@ -479,12 +537,93 @@ async def get_institution_cordis_eu_projects_funding_over_time( InstitutionsSearchClient, Depends(get_institutions_search_client) ], raw_oa_institution_id: Annotated[ - str, Query(description="The institution ID to filter by.") - ], + Optional[str], + Query(description="OpenAlex institution ID to filter by."), + ] = None, + 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, + fuzzy: Annotated[ + bool, + Query(description="Use OpenAlex topic-id resolution if true, otherwise raw keyword search."), + ] = False, ) -> InstitutionFunderSummary: return await projects_service.get_institution_cordis_eu_projects_funding_over_time( institutions_search_client=institutions_search_client, raw_oa_institution_id=raw_oa_institution_id, + 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, + fuzzy=fuzzy, ) @@ -623,4 +762,4 @@ async def search_projects( title=title, sort_by=sort_by, sort_direction=sort_direction, - ) + ) \ No newline at end of file diff --git a/service/src/main/inse/projects/service.py b/service/src/main/inse/projects/service.py index 7b05a78c..376ab2c0 100644 --- a/service/src/main/inse/projects/service.py +++ b/service/src/main/inse/projects/service.py @@ -29,6 +29,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.projects.eu_cordis_projects_client import ( get_enriched_cordis_project_by_id, + get_eu_cordis_projects_funding_data, search_eu_cordis_projects as _search_eu_cordis_projects_es, ) from typing import Union @@ -242,56 +243,159 @@ async def get_dfg_projects_by_author_id( async def get_institution_cordis_eu_projects_funding_over_time( institutions_search_client: InstitutionsSearchClient, - raw_oa_institution_id: str, + raw_oa_institution_id: Optional[str] = None, + 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, + fuzzy: bool = False, ) -> InstitutionFunderSummary: - page = await search_eu_cordis_projects( - page=0, - size=10000, - raw_oa_institution_id=raw_oa_institution_id, - institutions_search_client=institutions_search_client, + """ + Computes funding-over-time for EU CORDIS projects, applying the exact same + filters as `search_eu_cordis_projects` (the table search). Uses a + lightweight, fully-paginated fetch of just id/dates/amount - no author, + organization or topic enrichment - so this stays fast even when a filter + combination matches many thousands of projects. + """ + resolved_organization_names: List[str] = list(organization_names or []) + + if raw_oa_institution_id: + institution_aliases = ( + await institutions_search_client.get_institution_aliases_by_oa_institution_id( + raw_oa_institution_id + ) + ) + logger.debug( + f"Found institution aliases for institution_id={raw_oa_institution_id}: {institution_aliases}" + ) + resolved_organization_names.extend(institution_aliases) + + 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 ) - print("WE GOT THE PAGE",page) + + funding_data = await get_eu_cordis_projects_funding_data( + project_types=project_types, + organization_ids=organization_ids, + organization_names=resolved_organization_names or None, + 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, + fuzzy=fuzzy, + ) + return _calculate_funding_over_time( project_type=ProjectType.EU, - projects=page.elements, - funding_start_attr="start_date", - funding_end_attr="end_date", - funding_amount_attr="ec_max_contribution", + funding_entries=[ + (entry.get("start_date"), entry.get("end_date"), entry.get("ec_max_contribution")) + for entry in funding_data + ], ) async def get_institution_bund_projects_funding_over_time( institutions_search_client: InstitutionsSearchClient, - raw_oa_institution_id: str, + raw_oa_institution_id: Optional[str] = None, + executing_agency: Optional[List[str]] = None, + funding_arts: Optional[List[str]] = None, + title: Optional[str] = None, + keywords: Optional[List[str]] = None, + topic_ids: Optional[List[str]] = None, + filter_topic_ids: Optional[List[str]] = None, + funding_start_years: Optional[List[str]] = None, + funding_end_years: Optional[List[str]] = None, + countries: Optional[List[str]] = None, + fuzzy: bool = False, ) -> InstitutionFunderSummary: + """ + Computes funding-over-time for BUND projects, applying the exact same + filters as `search_bund_projects_with_filters` (the table search). + Skips the OpenAlex-topic enrichment step (irrelevant to a funding sum) + and pages through ALL matches rather than a single capped size=10000 + request, so totals stay correct and fast for large result sets. + """ logger.info( - f"Fetching funding over time for institution_id={raw_oa_institution_id}" + f"Fetching funding over time for institution_id={raw_oa_institution_id}, " + f"executing_agency={executing_agency}, funding_arts={funding_arts}, " + f"title={title}, keywords={keywords}, topic_ids={topic_ids}, " + f"filter_topic_ids={filter_topic_ids}, funding_start_years={funding_start_years}, " + f"funding_end_years={funding_end_years}, countries={countries}, fuzzy={fuzzy}" ) - institution_aliases = ( - await institutions_search_client.get_institution_aliases_by_oa_institution_id( - raw_oa_institution_id + + institution_aliases = [] + if raw_oa_institution_id: + institution_aliases = ( + await institutions_search_client.get_institution_aliases_by_oa_institution_id( + raw_oa_institution_id + ) ) - ) - logger.debug( - f"Found institution aliases for institution_id={raw_oa_institution_id}: {institution_aliases}" - ) - response = await projects_search_client.search_bund_projects( - filter_properties=ProjectsFilteringProperties( - project_type=ProjectType.BUND, - page=0, - size=10000, - ), - institution_names=institution_aliases, - ) + if not institution_aliases: + return _calculate_funding_over_time( + project_type=ProjectType.BUND, + funding_entries=[], + ) + + page_size = 5000 + page = 0 + funding_entries: List[Any] = [] + + while True: + response = await projects_search_client.search_bund_projects_with_filters( + oa_institution_aliases=institution_aliases, + raw_oa_institution_id=raw_oa_institution_id, + executing_agency=executing_agency, + funding_arts=funding_arts, + 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, + page=page, + size=page_size, + fuzzy=fuzzy, + skip_topic_enrichment=True, + ) + + funding_entries.extend( + (element.funding_start, element.funding_end, element.grant_amount) + for element in response.elements + ) + + if len(response.elements) < page_size: + break + page += 1 return _calculate_funding_over_time( project_type=ProjectType.BUND, - projects=response.elements, - funding_start_attr="funding_start", - funding_end_attr="funding_end", - funding_amount_attr="grant_amount", + funding_entries=funding_entries, ) - + + #Bund async def search_bund_projects_with_filters( institutions_search_client: InstitutionsSearchClient, @@ -346,20 +450,24 @@ async def search_bund_projects_with_filters( def _calculate_funding_over_time( project_type: ProjectType, - projects: List[Any], - funding_start_attr: str, - funding_end_attr: str, - funding_amount_attr: str, + funding_entries: List[Any], ) -> InstitutionFunderSummary: + """ + funding_entries: list of (funding_start, funding_end, funding_amount) + tuples. Each date value may be a date/datetime, an ISO date string, or + None; amount may be numeric or None. + """ funding_per_year: Dict[int, float] = {} - for project in projects: - funding_start = getattr(project, funding_start_attr) - funding_end = getattr(project, funding_end_attr) - funding_amount = getattr(project, funding_amount_attr) + for funding_start, funding_end, funding_amount in funding_entries: if not funding_start or not funding_end or not funding_amount: continue + if isinstance(funding_start, str): + funding_start = datetime.date.fromisoformat(funding_start[:10]) + if isinstance(funding_end, str): + funding_end = datetime.date.fromisoformat(funding_end[:10]) + if hasattr(funding_start, "date"): funding_start = funding_start.date() if hasattr(funding_end, "date"): -- 2.56.1 From 3f1ea0a4187d59d1f4f4b752366f7cd33cc77644 Mon Sep 17 00:00:00 2001 From: genja Date: Sat, 1 Aug 2026 01:58:19 +0200 Subject: [PATCH 11/11] updated project funding resolvers to apply filters --- webapp/src/app/api/api/projects.service.ts | 190 ++++++++++++++++-- webapp/src/app/app.routes.ts | 1 + .../bund-projects-funding.resolver.ts | 44 +++- .../cordis-eu-projects-funding.resolver.ts | 59 ++++++ 4 files changed, 275 insertions(+), 19 deletions(-) diff --git a/webapp/src/app/api/api/projects.service.ts b/webapp/src/app/api/api/projects.service.ts index 6e8b105b..a5095f5b 100644 --- a/webapp/src/app/api/api/projects.service.ts +++ b/webapp/src/app/api/api/projects.service.ts @@ -317,23 +317,82 @@ export class ProjectsService extends BaseService { /** * Get funding over time for bund projects. - * Returns the funding over time for bund projects associated with the specified institution. + * Returns the funding over time for BUND projects. Accepts the same filters as /bund/search, so the funding total can be made to match whatever the results table is currently filtered to. * @endpoint get /api/projects/institution/bund/funding-over-time * @param rawOaInstitutionId The institution ID to filter by. + * @param executingAgency Executing Agencies (Ausführende Stellen) to filter by. + * @param fundingArts 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 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 getInstitutionBundProjectsFundingOverTime(rawOaInstitutionId: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; - public getInstitutionBundProjectsFundingOverTime(rawOaInstitutionId: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public getInstitutionBundProjectsFundingOverTime(rawOaInstitutionId: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public getInstitutionBundProjectsFundingOverTime(rawOaInstitutionId: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { - if (rawOaInstitutionId === null || rawOaInstitutionId === undefined) { - throw new Error('Required parameter rawOaInstitutionId was null or undefined when calling getInstitutionBundProjectsFundingOverTime.'); - } + public getInstitutionBundProjectsFundingOverTime(rawOaInstitutionId?: string, executingAgency?: Array, fundingArts?: Array, title?: string, keywords?: Array, topicIds?: Array, filterTopicIds?: Array, fundingStartYears?: Array, fundingEndYears?: Array, countries?: Array, fuzzy?: boolean, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public getInstitutionBundProjectsFundingOverTime(rawOaInstitutionId?: string, executingAgency?: Array, fundingArts?: Array, title?: string, keywords?: Array, topicIds?: Array, filterTopicIds?: Array, fundingStartYears?: Array, fundingEndYears?: Array, countries?: Array, fuzzy?: boolean, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getInstitutionBundProjectsFundingOverTime(rawOaInstitutionId?: string, executingAgency?: Array, fundingArts?: Array, title?: string, keywords?: Array, topicIds?: Array, filterTopicIds?: Array, fundingStartYears?: Array, fundingEndYears?: Array, countries?: Array, fuzzy?: boolean, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getInstitutionBundProjectsFundingOverTime(rawOaInstitutionId?: string, executingAgency?: Array, fundingArts?: Array, title?: string, keywords?: Array, topicIds?: Array, filterTopicIds?: Array, fundingStartYears?: Array, fundingEndYears?: Array, countries?: Array, 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, rawOaInstitutionId, 'raw_oa_institution_id'); + if (executingAgency) { + executingAgency.forEach((element) => { + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + element, 'executing_agency'); + }) + } + if (fundingArts) { + fundingArts.forEach((element) => { + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + element, 'funding_arts'); + }) + } + 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'); + }) + } + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + fuzzy, 'fuzzy'); let localVarHeaders = this.defaultHeaders; @@ -378,23 +437,120 @@ export class ProjectsService extends BaseService { /** * Get funding over time for EU projects. - * Returns the funding over time for EU projects associated with the specified institution. + * Returns the funding over time for EU CORDIS projects. Accepts the same filters as /eu/search, so the funding total can be made to match whatever the results table is currently filtered to. * @endpoint get /api/projects/institution/eu/funding-over-time - * @param rawOaInstitutionId The institution ID to filter by. + * @param rawOaInstitutionId OpenAlex institution ID to filter by. + * @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 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 getInstitutionCordisEuProjectsFundingOverTime(rawOaInstitutionId: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; - public getInstitutionCordisEuProjectsFundingOverTime(rawOaInstitutionId: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public getInstitutionCordisEuProjectsFundingOverTime(rawOaInstitutionId: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public getInstitutionCordisEuProjectsFundingOverTime(rawOaInstitutionId: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { - if (rawOaInstitutionId === null || rawOaInstitutionId === undefined) { - throw new Error('Required parameter rawOaInstitutionId was null or undefined when calling getInstitutionCordisEuProjectsFundingOverTime.'); - } + public getInstitutionCordisEuProjectsFundingOverTime(rawOaInstitutionId?: string, 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, fuzzy?: boolean, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public getInstitutionCordisEuProjectsFundingOverTime(rawOaInstitutionId?: string, 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, fuzzy?: boolean, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getInstitutionCordisEuProjectsFundingOverTime(rawOaInstitutionId?: string, 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, fuzzy?: boolean, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getInstitutionCordisEuProjectsFundingOverTime(rawOaInstitutionId?: string, 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, 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, rawOaInstitutionId, 'raw_oa_institution_id'); + 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, + fuzzy, 'fuzzy'); let localVarHeaders = this.defaultHeaders; diff --git a/webapp/src/app/app.routes.ts b/webapp/src/app/app.routes.ts index a7c72897..6d8be115 100644 --- a/webapp/src/app/app.routes.ts +++ b/webapp/src/app/app.routes.ts @@ -693,6 +693,7 @@ export const routes: Routes = [ bundProjectsFunding: bundProjectsFundingResolver, cordisEuProjectsFunding: cordisEuProjectsFundingResolver, }, + runGuardsAndResolvers: 'always', children: [ { path: '', diff --git a/webapp/src/app/resolvers/bund-projects-funding.resolver.ts b/webapp/src/app/resolvers/bund-projects-funding.resolver.ts index 27f188c5..df29c79d 100644 --- a/webapp/src/app/resolvers/bund-projects-funding.resolver.ts +++ b/webapp/src/app/resolvers/bund-projects-funding.resolver.ts @@ -1,15 +1,55 @@ import { ResolveFn } from '@angular/router'; import { InstitutionFunderSummary, ProjectsService } from '../api'; import { inject } from '@angular/core'; +import { bundProjectQueryParamKeys } from './bund-projects.resolver'; export const bundProjectsFundingResolver: ResolveFn< InstitutionFunderSummary > = (route, state) => { let institutionId = route.parent?.paramMap.get('institutionId') ?? null; if (!institutionId) { - institutionId = route.parent?.paramMap.get('institutionId') ?? null; + institutionId = route.parent?.parent?.paramMap.get('institutionId') ?? null; } + if (!institutionId) { + throw new Error( + 'Institution ID is required to resolve BUND projects funding', + ); + } + + const fundingStartYears = route.queryParamMap.getAll( + bundProjectQueryParamKeys.funding_start, + ); + const fundingEndYears = route.queryParamMap.getAll( + bundProjectQueryParamKeys.funding_end, + ); + const keywords = + route.queryParamMap.get(bundProjectQueryParamKeys.keywords)?.split(',') || + []; + const topicIds = route.queryParamMap.getAll( + bundProjectQueryParamKeys.topicId, + ); + const topics = route.queryParamMap.getAll(bundProjectQueryParamKeys.topics); + const fundingType = route.queryParamMap.getAll( + bundProjectQueryParamKeys.funding_type, + ); + const fuzzySearch = route.queryParamMap.get('fuzzy') === 'true'; + const search = + route.queryParamMap.get(bundProjectQueryParamKeys.title) || undefined; + const executingAgency = route.queryParamMap.getAll( + bundProjectQueryParamKeys.agency, + ); + return inject(ProjectsService).getInstitutionBundProjectsFundingOverTime( - institutionId!, + institutionId, + executingAgency, + fundingType, + search, + keywords, + topics, + topicIds, + fundingStartYears, + fundingEndYears, + [], // countries - bundProjectsResolver doesn't wire this up yet either + fuzzySearch, ); }; diff --git a/webapp/src/app/resolvers/cordis-eu-projects-funding.resolver.ts b/webapp/src/app/resolvers/cordis-eu-projects-funding.resolver.ts index 4b1e5385..0e60a95b 100644 --- a/webapp/src/app/resolvers/cordis-eu-projects-funding.resolver.ts +++ b/webapp/src/app/resolvers/cordis-eu-projects-funding.resolver.ts @@ -1,17 +1,76 @@ import { ResolveFn } from '@angular/router'; import { InstitutionFunderSummary, ProjectsService } from '../api'; import { inject } from '@angular/core'; +import { euProjectQueryParamKeys } from './eu-cordis-projects.resolver'; export const cordisEuProjectsFundingResolver: ResolveFn< InstitutionFunderSummary > = (route, state) => { let institutionId = route.parent?.paramMap.get('institutionId') ?? null; + if (!institutionId) { + institutionId = route.parent?.parent?.paramMap.get('institutionId') ?? null; + } if (!institutionId) { throw new Error( 'Institution ID is required to resolve Cordis EU projects funding', ); } + + const searchTerm = + route.queryParamMap.get(euProjectQueryParamKeys.title) ?? undefined; + + const fundingStart = route.queryParamMap.getAll( + euProjectQueryParamKeys.funding_start, + ); + const fundingEnd = route.queryParamMap.getAll( + euProjectQueryParamKeys.funding_end, + ); + + const filteredTopicIds = route.queryParamMap.getAll( + euProjectQueryParamKeys.topicId, + ); + + const projectTypes = route.queryParamMap.getAll( + euProjectQueryParamKeys.projectType, + ); + + const organizationIds = route.queryParamMap.getAll( + euProjectQueryParamKeys.institutionId, + ); + + const authorIds = route.queryParamMap + .getAll(euProjectQueryParamKeys.authorId) + .map((id) => id.split('/').pop() || id); + + const countries = route.queryParamMap.getAll(euProjectQueryParamKeys.country); + + const frameworkProgrammes = route.queryParamMap.getAll( + euProjectQueryParamKeys.frameworkProgramme, + ); + + const fundingSchemes = route.queryParamMap.getAll( + euProjectQueryParamKeys.fundingScheme, + ); + + const statuses = route.queryParamMap.getAll(euProjectQueryParamKeys.status); + return inject(ProjectsService).getInstitutionCordisEuProjectsFundingOverTime( institutionId, + undefined, // authorId (single) - institution view doesn't use this + authorIds, + organizationIds, + [], // organizationNames + projectTypes as any, + searchTerm, + [], // keywords - institution view doesn't use free-text keywords + [], // topicIds (fuzzy) - institution view doesn't use fuzzy topic search + filteredTopicIds, + fundingStart, + fundingEnd, + countries, + frameworkProgrammes, + fundingSchemes, + statuses, + false, // fuzzy ); }; -- 2.56.1