feature/keywords-analysis: updated project tables, added authors to eu projects page, updated project funding retrieval #254

Merged
genja merged 12 commits from feature/keywords-analysis into dev 2026-08-01 02:17:47 +02:00
34 changed files with 1509 additions and 505 deletions
+1 -1
View File
@@ -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",
@@ -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,
@@ -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,
@@ -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,
@@ -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(
@@ -638,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,
@@ -655,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 = [
@@ -680,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}})
@@ -693,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)
@@ -748,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)
@@ -762,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)
@@ -825,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"
@@ -920,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')."""
+46 -6
View File
@@ -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
+20 -5
View File
@@ -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
@@ -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,
@@ -683,10 +700,16 @@ 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"]
# Fields we need to build BundProject objects (validation aliases match these exact names)
@@ -731,6 +754,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 +843,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 +860,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,
@@ -833,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)
@@ -1005,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."
)
)
+162 -12
View File
@@ -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,
@@ -432,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: {
@@ -448,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: {
@@ -476,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,
)
@@ -500,6 +642,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 +705,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,
@@ -612,4 +762,4 @@ async def search_projects(
title=title,
sort_by=sort_by,
sort_direction=sort_direction,
)
)
+183 -50
View File
@@ -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
@@ -148,6 +149,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 +209,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,
@@ -232,60 +243,164 @@ 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
)
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,
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 +415,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,
@@ -320,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"):
@@ -511,7 +645,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 +654,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,
@@ -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
+187 -32
View File
@@ -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<number>, institutionIds?: Array<number>, title?: string, keywords?: Array<string>, topicIds?: Array<string>, filterTopicIds?: Array<string>, fundingStartYears?: Array<string>, fundingEndYears?: Array<string>, page?: number, size?: number, sortBy?: string, sortDirection?: string, fuzzy?: boolean, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<DfgProjectPage>;
public getDfgProjects(authorId?: string, authorFilterIds?: Array<number>, institutionIds?: Array<number>, title?: string, keywords?: Array<string>, topicIds?: Array<string>, filterTopicIds?: Array<string>, fundingStartYears?: Array<string>, fundingEndYears?: Array<string>, page?: number, size?: number, sortBy?: string, sortDirection?: string, fuzzy?: boolean, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<DfgProjectPage>>;
public getDfgProjects(authorId?: string, authorFilterIds?: Array<number>, institutionIds?: Array<number>, title?: string, keywords?: Array<string>, topicIds?: Array<string>, filterTopicIds?: Array<string>, fundingStartYears?: Array<string>, fundingEndYears?: Array<string>, page?: number, size?: number, sortBy?: string, sortDirection?: string, fuzzy?: boolean, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<DfgProjectPage>>;
public getDfgProjects(authorId?: string, authorFilterIds?: Array<number>, institutionIds?: Array<number>, title?: string, keywords?: Array<string>, topicIds?: Array<string>, filterTopicIds?: Array<string>, fundingStartYears?: Array<string>, fundingEndYears?: Array<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<any> {
public getDfgProjects(rawOaInstitutionId?: string, authorId?: string, authorFilterIds?: Array<number>, institutionIds?: Array<number>, title?: string, keywords?: Array<string>, topicIds?: Array<string>, filterTopicIds?: Array<string>, fundingStartYears?: Array<string>, fundingEndYears?: Array<string>, page?: number, size?: number, sortBy?: string, sortDirection?: string, fuzzy?: boolean, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<DfgProjectPage>;
public getDfgProjects(rawOaInstitutionId?: string, authorId?: string, authorFilterIds?: Array<number>, institutionIds?: Array<number>, title?: string, keywords?: Array<string>, topicIds?: Array<string>, filterTopicIds?: Array<string>, fundingStartYears?: Array<string>, fundingEndYears?: Array<string>, page?: number, size?: number, sortBy?: string, sortDirection?: string, fuzzy?: boolean, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<DfgProjectPage>>;
public getDfgProjects(rawOaInstitutionId?: string, authorId?: string, authorFilterIds?: Array<number>, institutionIds?: Array<number>, title?: string, keywords?: Array<string>, topicIds?: Array<string>, filterTopicIds?: Array<string>, fundingStartYears?: Array<string>, fundingEndYears?: Array<string>, page?: number, size?: number, sortBy?: string, sortDirection?: string, fuzzy?: boolean, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<DfgProjectPage>>;
public getDfgProjects(rawOaInstitutionId?: string, authorId?: string, authorFilterIds?: Array<number>, institutionIds?: Array<number>, title?: string, keywords?: Array<string>, topicIds?: Array<string>, filterTopicIds?: Array<string>, fundingStartYears?: Array<string>, fundingEndYears?: Array<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<any> {
let localVarQueryParameters = new HttpParams({encoder: this.encoder});
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>rawOaInstitutionId, 'raw_oa_institution_id');
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>authorId, 'author_id');
if (authorFilterIds) {
@@ -314,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<InstitutionFunderSummary>;
public getInstitutionBundProjectsFundingOverTime(rawOaInstitutionId: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<InstitutionFunderSummary>>;
public getInstitutionBundProjectsFundingOverTime(rawOaInstitutionId: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<InstitutionFunderSummary>>;
public getInstitutionBundProjectsFundingOverTime(rawOaInstitutionId: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
if (rawOaInstitutionId === null || rawOaInstitutionId === undefined) {
throw new Error('Required parameter rawOaInstitutionId was null or undefined when calling getInstitutionBundProjectsFundingOverTime.');
}
public getInstitutionBundProjectsFundingOverTime(rawOaInstitutionId?: string, executingAgency?: Array<string>, fundingArts?: Array<string>, title?: string, keywords?: Array<string>, topicIds?: Array<string>, filterTopicIds?: Array<string>, fundingStartYears?: Array<string>, fundingEndYears?: Array<string>, countries?: Array<string>, fuzzy?: boolean, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<InstitutionFunderSummary>;
public getInstitutionBundProjectsFundingOverTime(rawOaInstitutionId?: string, executingAgency?: Array<string>, fundingArts?: Array<string>, title?: string, keywords?: Array<string>, topicIds?: Array<string>, filterTopicIds?: Array<string>, fundingStartYears?: Array<string>, fundingEndYears?: Array<string>, countries?: Array<string>, fuzzy?: boolean, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<InstitutionFunderSummary>>;
public getInstitutionBundProjectsFundingOverTime(rawOaInstitutionId?: string, executingAgency?: Array<string>, fundingArts?: Array<string>, title?: string, keywords?: Array<string>, topicIds?: Array<string>, filterTopicIds?: Array<string>, fundingStartYears?: Array<string>, fundingEndYears?: Array<string>, countries?: Array<string>, fuzzy?: boolean, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<InstitutionFunderSummary>>;
public getInstitutionBundProjectsFundingOverTime(rawOaInstitutionId?: string, executingAgency?: Array<string>, fundingArts?: Array<string>, title?: string, keywords?: Array<string>, topicIds?: Array<string>, filterTopicIds?: Array<string>, fundingStartYears?: Array<string>, fundingEndYears?: Array<string>, countries?: Array<string>, fuzzy?: boolean, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
let localVarQueryParameters = new HttpParams({encoder: this.encoder});
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>rawOaInstitutionId, 'raw_oa_institution_id');
if (executingAgency) {
executingAgency.forEach((element) => {
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>element, 'executing_agency');
})
}
if (fundingArts) {
fundingArts.forEach((element) => {
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>element, 'funding_arts');
})
}
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>title, 'title');
if (keywords) {
keywords.forEach((element) => {
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>element, 'keywords');
})
}
if (topicIds) {
topicIds.forEach((element) => {
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>element, 'topic_ids');
})
}
if (filterTopicIds) {
filterTopicIds.forEach((element) => {
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>element, 'filter_topic_ids');
})
}
if (fundingStartYears) {
fundingStartYears.forEach((element) => {
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>element, 'funding_start_years');
})
}
if (fundingEndYears) {
fundingEndYears.forEach((element) => {
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>element, 'funding_end_years');
})
}
if (countries) {
countries.forEach((element) => {
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>element, 'countries');
})
}
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>fuzzy, 'fuzzy');
let localVarHeaders = this.defaultHeaders;
@@ -375,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<InstitutionFunderSummary>;
public getInstitutionCordisEuProjectsFundingOverTime(rawOaInstitutionId: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<InstitutionFunderSummary>>;
public getInstitutionCordisEuProjectsFundingOverTime(rawOaInstitutionId: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<InstitutionFunderSummary>>;
public getInstitutionCordisEuProjectsFundingOverTime(rawOaInstitutionId: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
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<string>, organizationIds?: Array<string>, organizationNames?: Array<string>, projectTypes?: Array<EuCordisProjectType>, title?: string, keywords?: Array<string>, topicIds?: Array<string>, filterTopicIds?: Array<string>, fundingStartYears?: Array<string>, fundingEndYears?: Array<string>, countries?: Array<string>, frameworkProgrammes?: Array<string>, fundingSchemes?: Array<string>, statuses?: Array<string>, fuzzy?: boolean, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<InstitutionFunderSummary>;
public getInstitutionCordisEuProjectsFundingOverTime(rawOaInstitutionId?: string, authorId?: string, authorIds?: Array<string>, organizationIds?: Array<string>, organizationNames?: Array<string>, projectTypes?: Array<EuCordisProjectType>, title?: string, keywords?: Array<string>, topicIds?: Array<string>, filterTopicIds?: Array<string>, fundingStartYears?: Array<string>, fundingEndYears?: Array<string>, countries?: Array<string>, frameworkProgrammes?: Array<string>, fundingSchemes?: Array<string>, statuses?: Array<string>, fuzzy?: boolean, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<InstitutionFunderSummary>>;
public getInstitutionCordisEuProjectsFundingOverTime(rawOaInstitutionId?: string, authorId?: string, authorIds?: Array<string>, organizationIds?: Array<string>, organizationNames?: Array<string>, projectTypes?: Array<EuCordisProjectType>, title?: string, keywords?: Array<string>, topicIds?: Array<string>, filterTopicIds?: Array<string>, fundingStartYears?: Array<string>, fundingEndYears?: Array<string>, countries?: Array<string>, frameworkProgrammes?: Array<string>, fundingSchemes?: Array<string>, statuses?: Array<string>, fuzzy?: boolean, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<InstitutionFunderSummary>>;
public getInstitutionCordisEuProjectsFundingOverTime(rawOaInstitutionId?: string, authorId?: string, authorIds?: Array<string>, organizationIds?: Array<string>, organizationNames?: Array<string>, projectTypes?: Array<EuCordisProjectType>, title?: string, keywords?: Array<string>, topicIds?: Array<string>, filterTopicIds?: Array<string>, fundingStartYears?: Array<string>, fundingEndYears?: Array<string>, countries?: Array<string>, frameworkProgrammes?: Array<string>, fundingSchemes?: Array<string>, statuses?: Array<string>, fuzzy?: boolean, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
let localVarQueryParameters = new HttpParams({encoder: this.encoder});
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>rawOaInstitutionId, 'raw_oa_institution_id');
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>authorId, 'author_id');
if (authorIds) {
authorIds.forEach((element) => {
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>element, 'author_ids');
})
}
if (organizationIds) {
organizationIds.forEach((element) => {
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>element, 'organization_ids');
})
}
if (organizationNames) {
organizationNames.forEach((element) => {
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>element, 'organization_names');
})
}
if (projectTypes) {
projectTypes.forEach((element) => {
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>element, 'project_types');
})
}
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>title, 'title');
if (keywords) {
keywords.forEach((element) => {
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>element, 'keywords');
})
}
if (topicIds) {
topicIds.forEach((element) => {
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>element, 'topic_ids');
})
}
if (filterTopicIds) {
filterTopicIds.forEach((element) => {
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>element, 'filter_topic_ids');
})
}
if (fundingStartYears) {
fundingStartYears.forEach((element) => {
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>element, 'funding_start_years');
})
}
if (fundingEndYears) {
fundingEndYears.forEach((element) => {
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>element, 'funding_end_years');
})
}
if (countries) {
countries.forEach((element) => {
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>element, 'countries');
})
}
if (frameworkProgrammes) {
frameworkProgrammes.forEach((element) => {
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>element, 'framework_programmes');
})
}
if (fundingSchemes) {
fundingSchemes.forEach((element) => {
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>element, 'funding_schemes');
})
}
if (statuses) {
statuses.forEach((element) => {
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>element, 'statuses');
})
}
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>fuzzy, 'fuzzy');
let localVarHeaders = this.defaultHeaders;
@@ -681,7 +840,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 +849,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<string>, fundingArts?: Array<string>, title?: string, keywords?: Array<string>, topicIds?: Array<string>, filterTopicIds?: Array<string>, fundingStartYears?: Array<string>, fundingEndYears?: Array<string>, countries?: Array<string>, institutionIds?: Array<string>, page?: number, size?: number, sortBy?: string, sortDirection?: string, fuzzy?: boolean, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<BundProjectPage>;
public searchBundProjectsWithFilters(executingAgency?: Array<string>, fundingArts?: Array<string>, title?: string, keywords?: Array<string>, topicIds?: Array<string>, filterTopicIds?: Array<string>, fundingStartYears?: Array<string>, fundingEndYears?: Array<string>, countries?: Array<string>, institutionIds?: Array<string>, page?: number, size?: number, sortBy?: string, sortDirection?: string, fuzzy?: boolean, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<BundProjectPage>>;
public searchBundProjectsWithFilters(executingAgency?: Array<string>, fundingArts?: Array<string>, title?: string, keywords?: Array<string>, topicIds?: Array<string>, filterTopicIds?: Array<string>, fundingStartYears?: Array<string>, fundingEndYears?: Array<string>, countries?: Array<string>, institutionIds?: Array<string>, page?: number, size?: number, sortBy?: string, sortDirection?: string, fuzzy?: boolean, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<BundProjectPage>>;
public searchBundProjectsWithFilters(executingAgency?: Array<string>, fundingArts?: Array<string>, title?: string, keywords?: Array<string>, topicIds?: Array<string>, filterTopicIds?: Array<string>, fundingStartYears?: Array<string>, fundingEndYears?: Array<string>, countries?: Array<string>, institutionIds?: Array<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<any> {
public searchBundProjectsWithFilters(executingAgency?: Array<string>, fundingArts?: Array<string>, title?: string, keywords?: Array<string>, topicIds?: Array<string>, filterTopicIds?: Array<string>, fundingStartYears?: Array<string>, fundingEndYears?: Array<string>, countries?: Array<string>, 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<BundProjectPage>;
public searchBundProjectsWithFilters(executingAgency?: Array<string>, fundingArts?: Array<string>, title?: string, keywords?: Array<string>, topicIds?: Array<string>, filterTopicIds?: Array<string>, fundingStartYears?: Array<string>, fundingEndYears?: Array<string>, countries?: Array<string>, 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<HttpResponse<BundProjectPage>>;
public searchBundProjectsWithFilters(executingAgency?: Array<string>, fundingArts?: Array<string>, title?: string, keywords?: Array<string>, topicIds?: Array<string>, filterTopicIds?: Array<string>, fundingStartYears?: Array<string>, fundingEndYears?: Array<string>, countries?: Array<string>, 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<HttpEvent<BundProjectPage>>;
public searchBundProjectsWithFilters(executingAgency?: Array<string>, fundingArts?: Array<string>, title?: string, keywords?: Array<string>, topicIds?: Array<string>, filterTopicIds?: Array<string>, fundingStartYears?: Array<string>, fundingEndYears?: Array<string>, countries?: Array<string>, 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<any> {
let localVarQueryParameters = new HttpParams({encoder: this.encoder});
if (executingAgency) {
@@ -746,12 +905,8 @@ export class ProjectsService extends BaseService {
<any>element, 'countries');
})
}
if (institutionIds) {
institutionIds.forEach((element) => {
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>element, 'institution_ids');
})
}
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>rawOaInstitutionId, 'raw_oa_institution_id');
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>page, 'page');
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
@@ -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;
}
+22 -22
View File
@@ -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<Author> | 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;
}
+22 -22
View File
@@ -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<Author> | 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;
}
+22 -22
View File
@@ -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<Author> | 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;
}
+1
View File
@@ -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';
+62 -8
View File
@@ -690,17 +690,71 @@ 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),
);
},
runGuardsAndResolvers: 'always',
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',
@@ -2,94 +2,89 @@
<h3>Projekte</h3>
<div class="funding-area">
<mat-card appearance="outlined">
<mat-card-content>
<app-query-param-input
label="Suche nach Themen"
queryParamKey="search" />
<div class="person-projects">
<nav mat-tab-nav-bar [tabPanel]="resultTabPanel" class="result-nav">
@for (route of childRoutes; track route.path) {
<a
matTabLink
[routerLink]="[route.path]"
queryParamsHandling="merge"
routerLinkActive
#rla="routerLinkActive"
[active]="rla.isActive">
{{ route.label }}
</a>
}
</nav>
<mat-tab-group
[selectedIndex]="tabIndex()"
(selectedTabChange)="selectedTabChange($event)">
<mat-tab label="EU">
<app-data-table
[data]="euProjectData"
[columns]="euProjectColumns"
queryParamSortKey="sort_by"
queryParamSortDirectionKey="sort_direction" />
</mat-tab>
<mat-tab label="Bund">
<app-data-table
[data]="bundProjectData"
[columns]="bundProjectColumns"
queryParamSortKey="sort_by"
queryParamSortDirectionKey="sort_direction" />
</mat-tab>
</mat-tab-group>
<app-query-param-paginator
[total]="pageTotal()"
[pageSizeOptions]="[10, 20, 50]" />
</mat-card-content>
</mat-card>
<div class="funding-info-section">
<mat-card appearance="outlined">
<mat-card-header>
<mat-card-title>Förderung über Zeit</mat-card-title>
</mat-card-header>
<mat-card-content>
<app-institution-projects-funding-graph
[fundings]="[bundProjectsFunding(), cordisEuProjectsFunding()]" />
</mat-card-content>
</mat-card>
<mat-tab-nav-panel #resultTabPanel>
<router-outlet />
</mat-tab-nav-panel>
<div class="funding-info-section">
<mat-card appearance="outlined">
<mat-card-header>
<mat-card-title>Förderung über Zeit</mat-card-title>
</mat-card-header>
<mat-card-content>
<app-institution-projects-funding-graph
[fundings]="[bundProjectsFunding(), cordisEuProjectsFunding()]" />
</mat-card-content>
</mat-card>
<div class="funding-info-cards">
<app-info-card
[description]="'Gesamte Förderung durch Bund'"
[value]="
(bundTotalFunding()
| currency: 'EUR' : 'symbol' : '1.0-0' : 'de') ?? undefined
" />
<app-info-card
[description]="'Durchschnittliche jährliche Förderung durch Bund'"
[value]="
(bundAverageAnnualFunding()
| currency: 'EUR' : 'symbol' : '1.0-0' : 'de') ?? undefined
" />
<app-info-card
[description]="'Gesamte Förderung durch die Europäische Union'"
[value]="
(euTotalFunding() | currency: 'EUR' : 'symbol' : '1.0-0' : 'de') ??
undefined
" />
<app-info-card
[description]="'Durchschnittliche jährliche Förderung durch die Europäische Union'"
[value]="
(euAverageAnnualFunding()
| currency: 'EUR' : 'symbol' : '1.0-0' : 'de') ?? undefined
" />
<div class="funding-info-cards">
<app-info-card
[description]="'Gesamte Förderung durch Bund'"
[value]="
(bundTotalFunding()
| currency: 'EUR' : 'symbol' : '1.0-0' : 'de') ?? undefined
" />
<app-info-card
[description]="'Durchschnittliche jährliche Förderung durch Bund'"
[value]="
(bundAverageAnnualFunding()
| currency: 'EUR' : 'symbol' : '1.0-0' : 'de') ?? undefined
" />
<app-info-card
[description]="'Gesamte Förderung durch die Europäische Union'"
[value]="
(euTotalFunding()
| currency: 'EUR' : 'symbol' : '1.0-0' : 'de') ?? undefined
" />
<app-info-card
[description]="
'Durchschnittliche jährliche Förderung durch die Europäische Union'
"
[value]="
(euAverageAnnualFunding()
| currency: 'EUR' : 'symbol' : '1.0-0' : 'de') ?? undefined
" />
</div>
</div>
</div>
</div>
<ng-template #fundingStartTmp let-row>
{{ row.funding_start | date: 'dd.MM.yyyy' }}
</ng-template>
<ng-template #fundingEndTmp let-row>
{{ row.funding_end | date: 'dd.MM.yyyy' }}
</ng-template>
<ng-template #fundingAmountTmp let-row>
{{ row.funding_amount | currency: 'EUR' : 'symbol' : '1.0-0' : 'de' }}
</ng-template>
<ng-template #euProjectActionsTmp let-row>
<a mat-icon-button color="primary" [routerLink]="['/projects/eu', row.id]">
<mat-icon>open_in_new</mat-icon>
</a></ng-template
>
<ng-template #bundProjectActionsTmp let-row>
<a
mat-icon-button
color="primary"
[routerLink]="['/projects/bund', row.id]">
<mat-icon>open_in_new</mat-icon>
</a>
</ng-template>
</div>
<ng-template #fundingStartTmp let-row>
{{ row.funding_start | date: 'dd.MM.yyyy' }}
</ng-template>
<ng-template #fundingEndTmp let-row>
{{ row.funding_end | date: 'dd.MM.yyyy' }}
</ng-template>
<ng-template #fundingAmountTmp let-row>
{{ row.funding_amount | currency: 'EUR' : 'symbol' : '1.0-0' : 'de' }}
</ng-template>
<ng-template #euProjectActionsTmp let-row>
<a mat-icon-button color="primary" [routerLink]="['/projects/eu', row.id]">
<mat-icon>open_in_new</mat-icon>
</a></ng-template
>
<ng-template #bundProjectActionsTmp let-row>
<a mat-icon-button color="primary" [routerLink]="['/projects/bund', row.id]">
<mat-icon>open_in_new</mat-icon>
</a>
</ng-template>
@@ -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',
@@ -116,6 +108,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,
@@ -18,29 +18,37 @@
<ng-template #authorsTemplate let-pub>
@if (pub.authors) {
@let authorList = parseAuthors(pub.authors);
@let authorList = pub.oaAuthors ?? [];
@let isExpanded = isPublicationAuthorsExpanded(pub);
@let visibleAuthors =
isExpanded ? authorList : authorList.slice(0, 3);
<div
class="author-tags"
aria-label="Autoren"
style="padding: 0.5rem 0">
@for (
author of visibleAuthors;
track getAuthorTrackId(author, $index)
) {
<app-author-chip
size="mini"
[author]="author"
[showIcon]="true"
[isClickable]="false" />
} @empty {
<span class="empty-text">-</span>
}
@if (authorList.length > 0) {
<div class="authors-container">
@for (author of authorList; track author; let last = $last) {
<span class="author-wrapper">
<span
class="author-name"
(click)="
searchForPersonName(author); $event.stopPropagation()
">
{{ author }}
</span>
@if (!last) {
<span class="author-separator">, </span>
}
</span>
}
</div>
} @else {
<span class="empty-value">—</span>
}
@if (authorList.length > 3) {
<button
type="button"
class="publication-institution-more"
[attr.aria-expanded]="isExpanded"
(click)="togglePublicationAuthorsExpansion(pub)">
{{ isExpanded ? 'weniger' : '+' + (authorList.length - 3) }}
</button>
}
</div>
} @else {
<span class="empty-value">—</span>
}
@@ -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;
@@ -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<TemplateRef<any>>('yearTemplate');
publisherTemplate = viewChild<TemplateRef<any>>('publisherTemplate');
linksTemplate = viewChild<TemplateRef<any>>('linksTemplate');
expandedPublicationAuthorsIds: string[] = [];
// Displayed columns for the publications table
columns = computed<GenericColumn<HEUPublication>[]>(() => [
{
@@ -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);
}
}
@@ -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,
);
};
@@ -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<BundProjectPage> = (
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<BundProjectPage> = (
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}`);
}
};
@@ -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
);
};
@@ -69,6 +69,7 @@ export const dfgProjectsResolver: ResolveFn<DfgProjectPage> = (
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<DfgProjectPage> = (
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<DfgProjectPage> = (
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}`);
}
@@ -201,7 +201,7 @@ export const euCordisProjectsResolver: ResolveFn<EuCordisProjectSearchPage> = (
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<EuCordisProjectSearchPage> = (
return inject(ProjectsService).searchEuCordisProjects(
rawInstitutionId,
undefined,
[],
authorIds,
organizationIds,
[],
[],
projectTypes as any,
searchTerm,
[],
[],
[],
[],
[],
[],
[],
[],
[],
filteredTopicIds,
fundingStart,
fundingEnd,
countries,
frameworkProgrammes,
fundingSchemes,
statuses,
page,
size,
sortBy,
@@ -94,18 +94,13 @@
isTopicsExpanded ? projectTopics : projectTopics.slice(0, 3);
<div class="topic-chips" aria-label="Themen" style="padding: 0.5rem 0">
@for (topic of visibleTopics; track $index) {
<app-topic-chip
<app-topic-chip-2
size="mini"
[label]="topic.display_name || ''"
[description]="topic.description"
[subfieldName]="topic.subfield?.display_name"
[fieldName]="topic.field?.display_name"
[domainName]="topic.domain?.display_name"
[color]="getWorkTopicColor(topic)"
[disabled]="!topic.id"
[active]="isTopicActive(topic)"
(chipClick)="filterByTopic(topic)">
</app-topic-chip>
[topic]="topic"
[showIcon]="false"
[isSelected]="isTopicActive(topic)"
[isClickable]="topicFilterEnabled()"
(handleChipClick)="filterByTopic(topic)" />
} @empty {
<span class="empty-text">-</span>
}
@@ -10,7 +10,7 @@ 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,
GenericColumn,
@@ -34,10 +34,10 @@ import { bundProjectQueryParamKeys } from '../../../resolvers/bund-projects.reso
MatButtonModule,
QueryParamPaginatorComponent,
MatTooltip,
TopicChipComponent,
CurrencyPipe,
DatePipe,
ChipComponent,
AppTopicChipComponent,
],
templateUrl: './bund-project-table.component.html',
styleUrl: './bund-project-table.component.scss',
@@ -130,18 +130,13 @@
isTopicsExpanded ? projectTopics : projectTopics.slice(0, 3);
<div class="topic-chips" aria-label="Themen" style="padding: 0.5rem 0">
@for (topic of visibleTopics; track $index) {
<app-topic-chip
<app-topic-chip-2
size="mini"
[label]="topic.display_name || ''"
[description]="topic.description"
[subfieldName]="topic.subfield?.display_name"
[fieldName]="topic.field?.display_name"
[domainName]="topic.domain?.display_name"
[color]="getWorkTopicColor(topic)"
[disabled]="!topic.id"
[active]="isTopicActive(topic)"
(chipClick)="filterByTopic(topic)">
</app-topic-chip>
[topic]="topic"
[showIcon]="false"
[isSelected]="isTopicActive(topic)"
[isClickable]="topicFilterEnabled()"
(handleChipClick)="filterByTopic(topic)" />
} @empty {
<span class="empty-text">-</span>
}
@@ -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',
@@ -48,19 +48,13 @@
<div class="author-tags" aria-label="Autoren" style="padding: 0.5rem 0">
@for (author of visibleAuthors; track getAuthorTrackId(author, $index)) {
<button
type="button"
class="publication-institution-tag"
[class.active]="isAuthorActive(getAuthorId(author))"
[class.disabled]="!getAuthorId(author)"
[matTooltip]="getAuthorTooltipText(author)"
matTooltipPosition="above"
[attr.aria-label]="getAuthorTooltipText(author)"
[disabled]="!getAuthorId(author) || !authorFilterEnabled()"
(click)="filterByAuthor(author)">
<mat-icon class="institution-icon">person</mat-icon>
<span class="institution-name">{{ getAuthorName(author) }}</span>
</button>
<app-author-chip
size="mini"
[author]="author"
[showIcon]="true"
[isSelected]="isAuthorActive(author.id!)"
[isClickable]="authorFilterEnabled()"
(handleChipClick)="filterByAuthor($event!)" />
} @empty {
<span class="empty-text">-</span>
}
@@ -127,18 +121,13 @@
<div class="topic-chips" aria-label="Themen" style="padding: 0.5rem 0">
@for (topic of visibleTopics; track topic.id ?? $index) {
<app-topic-chip
<app-topic-chip-2
size="mini"
[label]="topic.display_name || ''"
[description]="topic.description"
[subfieldName]="topic.subfield?.display_name"
[fieldName]="topic.field?.display_name"
[domainName]="topic.domain?.display_name"
[color]="getWorkTopicColor(topic)"
[disabled]="!topic.id"
[active]="isTopicActive(topic)"
(chipClick)="filterByTopic(topic)">
</app-topic-chip>
[topic]="topic"
[showIcon]="false"
[isSelected]="isTopicActive(topic)"
[isClickable]="topicFilterEnabled()"
(handleChipClick)="filterByTopic(topic)" />
} @empty {
<span class="empty-text">-</span>
}
@@ -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();