Merge pull request 'feature/keywords-analysis' (#239) from feature/keywords-analysis into dev
LocationBasedServices/smartguide/pipeline/head This commit looks good

Reviewed-on: #239
This commit was merged in pull request #239.
This commit is contained in:
2026-07-24 14:13:20 +02:00
50 changed files with 3789 additions and 1909 deletions
+21
View File
@@ -105,6 +105,27 @@ async def get_author_name_by_id(author_id: str) -> Optional[str]:
except Exception as e:
logger.exception(f"Error fetching author name for id {author_id}: {str(e)}")
return None
async def get_author_name_with_alternatives_by_id(author_id: str) -> Optional[List[str]]:
try:
query = {
"_source": ["id", "display_name","display_name_alternatives"],
"query": {
"terms": {"id": [f"https://openalex.org/{author_id.upper()}"]}
},
"size": 1,
}
data = await elasticsearch.search(index=ESIndex.OPENALEX_AUTHORS, body=query)
hits = data.get("hits", {}).get("hits", [])
if not hits:
return None
names = hits[0].get("_source", {}).get("display_name_alternatives", [])
names.append(hits[0].get("_source", {}).get("display_name"))
return names
except Exception as e:
logger.exception(f"Error fetching author name for id {author_id}: {str(e)}")
return None
async def search_persons(
author_id: Optional[str] = None,
@@ -47,6 +47,17 @@ from inse.models.projects_eu_cordis.horizon_europe.heu_eurosci_voc import HEUEur
from inse.models.projects_eu_cordis.horizon_europe.heu_legal_basis import HEULegalBasis
from inse.models.projects_eu_cordis.horizon_europe.heu_project_details import HEUProjectDetails
from inse.projects.model import (
EuCordisProjectType,
EuCordisProjectSearchPage,
EuCordisProjectSummary,
EuCordisOrganizationSummary,
EuCordisTopicSummary,
EuCordisEurosciVocSummary,
)
from inse.projects.logic import get_eu_project_ids_by_openalex_topic_ids, get_openalex_topics_for_eu_projects
settings = get_settings()
logger = logging.getLogger(__name__)
logger.setLevel(settings.logging_level)
@@ -284,19 +295,6 @@ async def _enrich_heu_project(
from inse.projects.model import (
EuCordisProjectType,
EuCordisProjectSearchPage,
EuCordisProjectSummary,
EuCordisOrganizationSummary,
EuCordisTopicSummary,
EuCordisEurosciVocSummary,
)
from inse.projects.logic import (
get_eu_project_ids_by_openalex_topic_ids,
get_openalex_topics_for_eu_projects,
)
def _eu_project_type_index_filter(
project_ids_by_type: Dict[EuCordisProjectType, List[str]],
) -> Optional[Dict[str, Any]]:
@@ -396,11 +394,8 @@ async def get_eu_project_ids_by_organization_filters(
for name in organization_names:
should.append(
{
"match": {
"name": {
"query": name,
"operator": "and",
}
"match_phrase": {
"name": name
}
}
)
@@ -421,7 +416,7 @@ async def get_eu_project_ids_by_organization_filters(
)
hits = response.get("hits", {}).get("hits", [])
for hit in hits:
source = hit.get("_source", {})
project_id = source.get("projectID")
@@ -437,16 +432,29 @@ 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()
required = {f"id:{x}" for x in organization_ids}
required.update({f"name:{x.lower()}" for x in organization_names})
# Add ID requirements
for org_id in organization_ids:
required_orgs.add(f"id:{org_id}")
result[project_type] = [
project_id
for project_id, found in project_org_matches.items()
if required.issubset(found)
]
required_id_set = {f"id:{x}" for x in organization_ids}
required_name_match = len(organization_names) > 0 # if any names, need at least one match
result[project_type] = []
for project_id, found in project_org_matches.items():
# Check ID matches
if not required_id_set.issubset(found):
continue
# Check name match: at least one name alias must be in found
if required_name_match:
if not any(f"name:{name.lower()}" in found for name in organization_names):
continue
result[project_type].append(project_id)
print(f"Final project IDs by type: {result}")
return result
async def get_eu_organizations_for_projects(
-1
View File
@@ -3,7 +3,6 @@ import logging
from typing import Any, Dict, List, Optional, Set, Tuple
from collections import defaultdict
from inse.projects.eu_cordis_projects_client import get_enriched_cordis_project_by_id
from inse.integrations import elasticsearch
from inse.model import ESCluster, ESIndex
+82 -64
View File
@@ -7,7 +7,6 @@ from pydantic import BaseModel, Field, field_validator
from inse.models.bund_project import BundProject
from inse.models.eu_project import EuProject
from inse.models.cordis_eu_project import CordisEuProject
from inse.model import ESIndex
from inse.models.projects_eu_cordis.horizon2020.h2020_project_details import H2020ProjectDetails
from inse.models.projects_eu_cordis.horizon_europe.heu_project_details import HEUProjectDetails
@@ -69,15 +68,95 @@ class Page(BaseModel):
size: int = Field(default=20, description="The requested page size.")
total: int = Field(default=0, description="The total number of items.")
class BundProjectSummary(BundProject):
oa_topics: Optional[list[Topic]] = Field(
default=None,
validation_alias="oa_topics",
description="The OpenAlex topics of the project",
examples=[["Artificial Intelligence", "Machine Learning"]],
)
@classmethod
def from_hit(cls, hit: dict) -> "BundProjectSummary":
"""Create a BundProjectSummary from an Elasticsearch hit."""
source = hit.get("_source", {})
topics_raw = source.get("oa_topics") or []
oa_topics = None
if isinstance(topics_raw, list) and topics_raw:
sorted_topics_raw = sorted(
(t for t in topics_raw if isinstance(t, dict)),
key=lambda t: t.get("rank") if t.get("rank") is not None else float("inf"),
)
oa_topics = [cls._topic_from_match(t) for t in sorted_topics_raw]
print(f"oa_topics: {oa_topics}")
return cls(
funding_code=source.get("Förderkennzeichen"),
department=source.get("Ressort"),
department_fullname=source.get("Ressort_fullname"),
referat=source.get("Referat"),
project_sponsor=source.get("Projektträger"),
project_sponsor_fullname=source.get("Projektträger_fullname"),
work_unit=source.get("Arb.-Einh."),
recipient=source.get("Zuwendungsempfänger"),
municipal_code=source.get("Gemeindekennziffer"),
municipality=source.get("Stadt/Gemeinde"),
place=source.get("Ort"),
state=source.get("Bundesland"),
country=source.get("Staat"),
implementing_agency=source.get("Ausführende Stelle"),
topic=source.get("Thema"),
performance_plan_system=source.get("Leistungsplansystematik"),
performance_plan_system_text=source.get("Klartext Leistungsplansystematik"),
funding_start=source.get("Förderbeginn"),
funding_end=source.get("Förderende"),
grant_amount=source.get("Fördersumme"),
funding_profile=source.get("Förderprofil"),
joint_project=source.get("Verbundprojekt"),
funding_type=source.get("Förderart"),
publication_date=source.get("Publikationsdatum"),
unix_timestamp=source.get("Unix-Timestamp"),
date=source.get("datum"),
new=source.get("neu"),
duration=source.get("Laufzeit"),
oa_topics=oa_topics,
)
@staticmethod
def _topic_from_match(match: Dict[str, Any]) -> Topic:
"""Builds a Topic model from a flattened topic_match dict.
Same logic as DfgProjectSummary._topic_from_match and EuCordisProjectSummary.topic_from_match
"""
domain_name = match.get("domain")
field_name = match.get("field")
subfield_name = match.get("subfield")
domain = TopicDomain(display_name=domain_name) if domain_name else None
field = TopicField(display_name=field_name) if field_name else None
subfield = TopicSubfield(display_name=subfield_name) if subfield_name else None
return Topic(
id=match.get("topic_id"),
display_name=match.get("topic_display_name"),
domain=domain,
field=field,
subfield=subfield,
)
class BundProjectPage(Page):
elements: List[BundProject] = Field(
elements: List[BundProjectSummary] = Field(
default_factory=list, description="The bund projects on this page."
)
class BundProjectList(BaseModel):
elements: List[BundProject] = Field(
elements: List[BundProjectSummary] = Field(
default_factory=list, description="All bund projects."
)
total: int = Field(default=0, description="The total number of bund projects.")
@@ -317,11 +396,6 @@ class ProjectsFilteringProperties(BaseModel):
)
class CordisEuProjectPage(Page):
elements: List[CordisEuProject] = Field(
default_factory=list, description="The CORDIS EU projects on this page."
)
class EuCordisProjectResponse(BaseModel):
"""
Response model for EU Cordis project endpoints.
@@ -445,62 +519,6 @@ class EuProjectPage(Page):
default_factory=list, description="The EU projects on this page."
)
class EuOrganizationShort(BaseModel):
project_id: str = Field(description="The unique identifier of the project.")
organization_id: str = Field(
description="The unique identifier of the organization."
)
ec_contribution: Optional[float] = Field(
default=None,
description="The EC contribution amount for the organization in the project.",
)
class EuProjectShort(BaseModel):
id: str = Field(description="The unique identifier of the EU project.")
title: Optional[str] = Field(
default=None, description="The title of the EU project."
)
start_date: Optional[date] = Field(
default=None, description="The funding start date of the EU project."
)
end_date: Optional[date] = Field(
default=None, description="The funding end date of the EU project."
)
acronym: Optional[str] = Field(
default=None, description="The acronym of the EU project."
)
class EuOrganizationProjectSummary(BaseModel):
organization_id: str = Field(
description="The unique identifier of the organization."
)
project_id: str = Field(description="The unique identifier of the project.")
title: Optional[str] = Field(default=None, description="The title of the project.")
start_date: Optional[date] = Field(
default=None, description="The funding start date of the project."
)
end_date: Optional[date] = Field(
default=None, description="The funding end date of the project."
)
acronym: Optional[str] = Field(
default=None, description="The acronym of the project."
)
ec_contribution: Optional[float] = Field(
default=None,
description="The EC contribution amount for the organization in the project.",
)
class EuOrganizationProjectSummaryPage(Page):
elements: List[EuOrganizationProjectSummary] = Field(
default_factory=list,
description="The organization project summaries on this page.",
)
################
class EuCordisProjectType(StrEnum):
FP7 = "fp7"
@@ -6,14 +6,10 @@ import urllib
from inse.config import get_settings
from inse.models.bund_project import BundProject
from inse.projects.model import (
BundProjectSummary,
BundProjectPage,
CordisEuProjectPage,
DfgProjectPage,
DfgProjectSummary,
EuOrganizationProjectSummary,
EuOrganizationProjectSummaryPage,
EuOrganizationShort,
EuProjectShort,
FundingProject,
FundingProjectPage,
ProjectType,
@@ -21,17 +17,12 @@ from inse.projects.model import (
ProjectsSortBy,
SortDirection,
)
from inse.projects.eu_cordis_projects_client import get_enriched_cordis_project_by_id
from inse.models.dfg_project_details import DfgProjectDetails
from inse.models.bund_project_details import BundProjectDetails
from inse.models.cordis_eu_project import CordisEuProject
from inse.integrations import elasticsearch
from inse.model import ESCluster, ESIndex
from inse.models.projects_eu_cordis.horizon2020.h2020_project_details import H2020ProjectDetails
from inse.models.projects_eu_cordis.horizon_europe.heu_project_details import HEUProjectDetails
from inse.models.projects_eu_cordis.fp7.fp7_project_details import Fp7ProjectDetails
from inse.projects.logic import get_person_ids_by_institution_ids, get_dfg_project_ids_by_topic_ids, get_openalex_topics_for_dfg_projects, get_person_institutes
from typing import Union
settings = get_settings()
logger = logging.getLogger(__name__)
@@ -162,6 +153,7 @@ async def search_bund_projects(
response = await elasticsearch.search(
index=ESIndex.PROJECTS_BUND_V1,
track_total_hits=True,
query=query,
sort=sort,
size=filter_properties.size,
@@ -189,7 +181,7 @@ def _complete_response_to_bund_project_page(
hits_block = response.get("hits", {})
total_hits = hits_block.get("total", {}).get("value", 0)
elements = [
BundProject.model_validate(hit["_source"]) for hit in hits_block.get("hits", [])
BundProjectSummary.from_hit(hit) for hit in hits_block.get("hits", [])
]
return BundProjectPage(elements=elements, total=total_hits, page=page, size=size)
@@ -221,263 +213,10 @@ async def get_bund_project_by_id(project_id: str) -> Optional[BundProjectDetails
return None
# EU
async def get_eu_organization_project_contributions(
organization_names: List[str],
projects_filtering_properties: ProjectsFilteringProperties,
) -> EuOrganizationProjectSummaryPage:
"""Fetches the contributions of EU organizations to projects based on the provided organization names and filtering properties, and returns a paginated summary of the projects.
Args:
organization_names (List[str]): The list of organization names to fetch contributions for.
projects_filtering_properties (ProjectsFilteringProperties): The filtering properties for the projects.
Returns:
EuOrganizationProjectSummaryPage: The paginated summary of the projects.
"""
# Pagination depending on sorting criteria
# For FUNDING_AMOUNT before on the organization project contributions
# For the rest after the contributions are known on the real projects
organization_project_contributions = await get_eu_organization_contributions(
organization_names=organization_names,
)
total_projects, projects = await get_eu_organization_projects(
project_contributions=list(organization_project_contributions.values()),
projects_filtering_properties=projects_filtering_properties,
)
elements: List[EuOrganizationProjectSummary] = _merge_project_data(
projects=projects, contributions=organization_project_contributions
)
if projects_filtering_properties.sort_by == ProjectsSortBy.FUNDING_AMOUNT:
elements.sort(
key=lambda x: x.ec_contribution or 0,
reverse=projects_filtering_properties.sort_direction == SortDirection.DESC,
)
start = projects_filtering_properties.page * projects_filtering_properties.size
end = start + projects_filtering_properties.size
elements = elements[start:end]
return EuOrganizationProjectSummaryPage(
elements=elements,
total=total_projects,
page=projects_filtering_properties.page,
size=projects_filtering_properties.size,
)
async def get_eu_organization_contributions(
organization_names: List[str],
) -> Dict[str, EuOrganizationShort]:
"""Fetches the contributions of EU organizations to projects based on the provided organization names.
Args:
organization_names (List[str]): The list of organization names to fetch contributions for.
Returns:
Dict[str, EuOrganizationShort]: A dictionary mapping project IDs to their corresponding organization contributions.
"""
source = ["projectID", "organisationID", "ecContribution"]
query = {
"terms": {
"name.keyword": [
name.upper() for name in organization_names if name.strip()
],
}
}
response = await elasticsearch.search(
index=ESIndex.CORDIS_EU_ORGANIZATIONS_WILDCARD,
cluster=ESCluster.INSE,
source=source,
size=10000,
query=query,
)
logger.debug(
f"Received organization project contributions response: {json.dumps(response, indent=2)}"
)
organization_project_contributions = _process_organization_project_contributions(
response
)
logger.debug(
f"Found organization project contributions for organization names {organization_names}: {organization_project_contributions}"
)
return organization_project_contributions
def _process_organization_project_contributions(
response: Dict[str, Any],
) -> Dict[str, EuOrganizationShort]:
"""Processes the raw Elasticsearch response to extract the contributions of EU organizations to projects.
Args:
response (Dict[str, Any]): The raw Elasticsearch response.
Returns:
Dict[str, EuOrganizationShort]: A dictionary mapping project IDs to their corresponding organization contributions.
"""
hits_block = response.get("hits", {})
project_contributions: Dict[str, EuOrganizationShort] = {}
for hit in hits_block.get("hits", []):
source = hit.get("_source", {})
project_id = source.get("projectID")
organization_id = source.get("organisationID")
ec_contribution = source.get("ecContribution")
if project_id and organization_id:
project_contributions[project_id] = EuOrganizationShort(
project_id=project_id,
organization_id=organization_id,
ec_contribution=ec_contribution,
)
return project_contributions
async def get_eu_organization_projects(
project_contributions: List[EuOrganizationShort],
projects_filtering_properties: ProjectsFilteringProperties,
) -> Tuple[int, Dict[str, EuProjectShort]]:
"""Fetches the projects associated with the given list of organization contributions, applying the specified filtering properties.
Args:
project_contributions (List[EuOrganizationShort]): The list of organization contributions to fetch projects for.
projects_filtering_properties (ProjectsFilteringProperties): The filtering properties to apply to the project search.
Returns:
Tuple[int, Dict[str, EuProjectShort]]: A tuple containing the total number of projects and a dictionary mapping project IDs to their corresponding project details.
"""
project_ids = [contribution.project_id for contribution in project_contributions]
source = ["id", "title", "startDate", "endDate", "acronym"]
query = {
"terms": {
"id": project_ids,
}
}
if (
projects_filtering_properties.query
and projects_filtering_properties.query.strip()
):
query = {
"bool": {
"must": [
{
"match_phrase_prefix": {
"title": {
"query": projects_filtering_properties.query,
"max_expansions": 50,
}
}
}
],
"filter": query,
}
}
# Project contributions have been filtered before based on ecContribution
if projects_filtering_properties.sort_by == ProjectsSortBy.FUNDING_AMOUNT:
response = await elasticsearch.search(
index=ESIndex.CORDIS_EU_PROJECTS_WILDCARD,
cluster=ESCluster.INSE,
source=source,
query=query,
size=10000,
)
else:
response = await elasticsearch.search(
index=ESIndex.CORDIS_EU_PROJECTS_WILDCARD,
cluster=ESCluster.INSE,
source=source,
query=query,
size=projects_filtering_properties.size,
offset=projects_filtering_properties.page
* projects_filtering_properties.size,
sort=[
{
projects_filtering_properties.sort_by.to_cordis_eu_project_sort_field(): {
"order": projects_filtering_properties.sort_direction
}
}
],
)
return _process_projects_response(response)
def _process_projects_response(
response: Dict[str, Any],
) -> Tuple[int, Dict[str, EuProjectShort]]:
"""Processes the raw Elasticsearch response to extract the project details and total count.
Args:
response (Dict[str, Any]): The raw Elasticsearch response.
Returns:
Tuple[int, Dict[str, EuProjectShort]]: A tuple containing the total number of projects and a dictionary mapping project IDs to their corresponding project details.
"""
hits_block = response.get("hits", {})
total = hits_block.get("total", {}).get("value", 0)
projects: Dict[str, EuProjectShort] = {}
for hit in hits_block.get("hits", []):
source = hit.get("_source", {})
project_id = source.get("id")
title = source.get("title")
start_date = source.get("startDate")
end_date = source.get("endDate")
acronym = source.get("acronym")
if not project_id:
continue
projects[project_id] = EuProjectShort(
id=project_id,
title=title,
start_date=start_date,
end_date=end_date,
acronym=acronym,
)
return total, projects
def _merge_project_data(
projects: Dict[str, EuProjectShort], contributions: Dict[str, EuOrganizationShort]
) -> List[EuOrganizationProjectSummary]:
"""Merges the project details with the organization contributions to create a list of EuOrganizationProjectSummary objects.
Args:
projects (Dict[str, EuProjectShort]): The dictionary of project details.
contributions (Dict[str, EuOrganizationShort]): The dictionary of organization contributions.
Returns:
List[EuOrganizationProjectSummary]: The list of merged project-summary objects.
"""
merged_data = []
for project_id, project_info in projects.items():
contribution_info = contributions.get(project_id)
if contribution_info:
merged_entry = EuOrganizationProjectSummary(
project_id=project_id,
title=project_info.title,
start_date=project_info.start_date,
end_date=project_info.end_date,
acronym=project_info.acronym,
organization_id=contribution_info.organization_id,
ec_contribution=contribution_info.ec_contribution,
)
merged_data.append(merged_entry)
return merged_data
def _get_raw_doi(doi: str) -> str:
"""Extracts the raw DOI from a given DOI string, removing any URL prefixes if present.
@@ -563,50 +302,110 @@ async def get_cordis_eu_project_ids_by_dois(dois: List[str]) -> List[str]:
return list(project_ids)
async def get_cordis_eu_projects_by_project_ids(
project_ids: List[str],
) -> CordisEuProjectPage:
query = {"bool": {"filter": [{"terms": {"id": project_ids}}]}}
# DFG
async def get_dfg_publications_by_dois(dois: List[str]):
"""Retrieves DFG publications associated with the given list of DOIs.
Args:
dois (List[str]): The list of DOIs for which to retrieve publications.
Returns:
_type_: The retrieved publications.
"""
query_dois = list({
variant
for doi in dois
for variant in (
doi,
)
})
query = {
"bool": {
"filter": [
{
"nested": {
"path": "publications",
"query": {
"terms": {
"publications.doi":
query_dois
}
}
}
}
]
}
}
response = await elasticsearch.search(
size=1000,
query=query,
index=ESIndex.CORDIS_EU_PROJECTS_WILDCARD,
index=ESIndex.DFG_PROJECTS,
cluster=ESCluster.INSE,
)
hits_block = response.get("hits", {})
total_hits = hits_block.get("total", {}).get("value", 0)
elements = [
CordisEuProject.model_validate(hit["_source"])
for hit in hits_block.get("hits", [])
]
return CordisEuProjectPage(
elements=elements, total=total_hits, page=0, size=len(elements)
logger.debug(f"Received publications response: {json.dumps(response, indent=2)}")
return response
async def get_dfg_project_ids_by_names(names: List[str]) -> List[str]:
query = {
"bool": {
"should": [
{
"match_phrase": {
"full_name": name
}
}
for name in names
],
"minimum_should_match": 1,
}
}
response = await elasticsearch.search(
source=["projects.project_id"],
size=1000,
query=query,
index=ESIndex.DFG_PERSONS,
cluster=ESCluster.INSE,
)
project_ids = {
project["project_id"]
for hit in response.get("hits", {}).get("hits", [])
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]:
"""Retrieves the project IDs of DFG projects associated with the given list of DOIs.
async def get_eu_cordis_projects_by_id(
project_id: str,
) -> Optional[Union[Fp7ProjectDetails, H2020ProjectDetails, HEUProjectDetails]]:
"""
Fetches and enriches a single Cordis EU project by its ID.
Args:
project_id: The project ID to fetch
dois (List[str]): The list of DOIs for which to retrieve project IDs.
Returns:
The enriched project details, or None if not found
List[str]: The list of project IDs.
"""
enriched_project = await get_enriched_cordis_project_by_id(
project_id=project_id
)
return enriched_project
response = await get_dfg_publications_by_dois(dois=dois)
hits_block = response.get("hits", {})
project_ids = set()
for hit in hits_block.get("hits", []):
source = hit.get("_source", {})
project_id = source.get("id")
if project_id:
project_ids.add(project_id)
return list(project_ids)
# DFG
async def search_dfg_projects(
page: int,
size: int,
project_ids: Optional[List[int]] = None,
institution_ids: Optional[List[int]] = None,
names: Optional[List[str]] = None,
keywords: Optional[List[str]] = None,
@@ -648,6 +447,7 @@ async def search_dfg_projects(
body: Dict[str, Any] = {
"size": size,
"from": from_,
"track_total_hits": True,
"_source": [
"id",
"link",
@@ -667,7 +467,8 @@ async def search_dfg_projects(
}
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 ===
if fuzzy and topic_ids:
matching_project_ids = await get_dfg_project_ids_by_topic_ids(
@@ -812,7 +613,6 @@ async def search_dfg_projects(
index=ESIndex.DFG_PROJECTS,
body=body,
cluster=ESCluster.INSE,
track_total_hits=True,
)
hits = response.get("hits", {}).get("hits", [])
@@ -894,6 +694,232 @@ async def get_dfg_project_by_id(project_id: str) -> Optional[DfgProjectDetails]:
return details
return None
#BUND
async def get_bund_project_ids_by_topic_ids(topic_ids: List[str]) -> List[str]:
"""
Query the `projects_bund_openalex_topics` index to find BUND project IDs
that match any of the given OpenAlex topic IDs.
"""
body: Dict[str, Any] = {
"size": 0,
"query": {
"terms": {
"topic_matches.topic_id": topic_ids
}
},
"aggs": {
"project_ids": {
"terms": {
"field": "project_id.keyword",
"size": 10000
}
}
}
}
response = await elasticsearch.search(
index=ESIndex.PROJECTS_BUND_TOPICS,
body=body,
cluster=ESCluster.INSE
)
print(f"Received response for topic_ids {topic_ids}: {json.dumps(response, indent=2)}")
buckets = response.get("aggregations", {}).get("project_ids", {}).get("buckets", [])
return [bucket["key"] for bucket in buckets]
async def get_openalex_topics_for_bund_projects(project_ids: List[str]) -> Dict[str, List[Dict]]:
"""
Retrieve OpenAlex topic details for a list of BUND project IDs.
Returns a dict mapping `project_id` -> list of topic_match objects.
"""
if not project_ids:
return {}
body: Dict[str, Any] = {
"size": 10000,
"query": {
"terms": {
"project_id.keyword": project_ids
}
},
"_source": ["project_id", "topic_matches"]
}
response = await elasticsearch.search(
index=ESIndex.PROJECTS_BUND_TOPICS,
body=body,
cluster=ESCluster.INSE
)
lookup: Dict[str, List[Dict]] = {}
for hit in response.get("hits", {}).get("hits", []):
src = hit["_source"]
pid = src.get("project_id")
if pid:
lookup[pid] = src.get("topic_matches", [])
return lookup
async def search_bund_projects_with_filters(
executing_agency: Optional[List[str]] = None,
institution_ids: Optional[List[int]] = None,
funding_arts: Optional[List[str]] = None, # actually EuCordisProjectType, but treated as strings
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,
page: int = 0,
size: int = 10,
sort_by: str = "title",
sort_direction: str = "asc",
fuzzy: bool = False,
) -> BundProjectPage:
"""
Main search function for BUND projects, analogous to the DFG search.
"""
from_ = page * size
# Fields we need to build BundProject objects (validation aliases match these exact names)
source_fields = [
"Förderkennzeichen",
"Ressort",
"Ressort_fullname",
"Referat",
"Projektträger",
"Projektträger_fullname",
"Arb.-Einh.",
"Zuwendungsempfänger",
"Gemeindekennziffer",
"Stadt/Gemeinde",
"Ort",
"Bundesland",
"Staat",
"Ausführende Stelle",
"Thema",
"Leistungsplansystematik",
"Klartext Leistungsplansystematik",
"Förderbeginn",
"Förderende",
"Fördersumme",
"Förderprofil",
"Verbundprojekt",
"Förderart",
"Publikationsdatum",
"Unix-Timestamp",
"datum",
"neu",
"Laufzeit",
# Also include funding_start/end for sorting and filtering (they may also be needed)
"funding_start",
"funding_end",
]
body: Dict[str, Any] = {
"size": size,
"from": from_,
"_source": source_fields,
"query": {},
}
must_clauses: List[Dict[str, Any]] = []
# === 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)
if not matching_project_ids:
return BundProjectPage(elements=[], total=0, page=page, size=size)
must_clauses.append({"terms": {"Förderkennzeichen.keyword": matching_project_ids}})
elif keywords:
keyword_clauses = []
for kw in keywords:
if kw.strip() == "":
continue
keyword_clauses.append({
"multi_match": {
"query": kw,
"fields": ["Verbundprojekt"], # searching title/acronym field
"type": "phrase_prefix",
"max_expansions": 100,
}
})
if keyword_clauses:
must_clauses.append({"bool": {"must": keyword_clauses}})
# === Additional independent filters (applied regardless of fuzzy/keyword mode) ===
if filter_topic_ids:
matching_filter_ids = await get_bund_project_ids_by_topic_ids(topic_ids=filter_topic_ids)
if not matching_filter_ids:
return BundProjectPage(elements=[], total=0, page=page, size=size)
must_clauses.append({"terms": {"Förderkennzeichen.keyword": matching_filter_ids}})
if title:
must_clauses.append({
"multi_match": {
"query": title,
"fields": ["Verbundprojekt"],
"type": "phrase_prefix",
"max_expansions": 100,
}
})
if executing_agency:
must_clauses.append({"terms": {"Ausführende Stelle.keyword": executing_agency}})
if funding_arts:
must_clauses.append({"terms": {"Förderart.keyword": funding_arts}})
if countries:
must_clauses.append({"terms": {"Staat.keyword": countries}})
if funding_start_years:
must_clauses.append({"terms": {"funding_start": funding_start_years}})
if funding_end_years:
must_clauses.append({"terms": {"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()
if sort_direction not in ("asc", "desc"):
sort_direction = "asc"
if sort_by == "title":
sort_config = {"Verbundprojekt.keyword": {"order": sort_direction}}
elif sort_by == "funding_start":
sort_config = {"funding_start": {"order": sort_direction}}
elif sort_by == "funding_end":
sort_config = {"funding_end": {"order": sort_direction}}
else:
# Fallback to project ID
sort_config = {"Förderkennzeichen.keyword": {"order": sort_direction}}
body["sort"] = [sort_config]
# === Execute Search ===
response = await elasticsearch.search(
index=ESIndex.PROJECTS_BUND_V1,
body=body,
cluster=ESCluster.INSE,
track_total_hits=True,
)
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)
print(f"Enriched BUND projects with topics: {json.dumps(topic_lookup, indent=2)}")
for hit in hits:
hit["_source"]["oa_topics"] = topic_lookup.get(hit["_id"], [])
return _complete_response_to_bund_project_page(response, page, size)
# All
+110 -65
View File
@@ -5,9 +5,7 @@ from fastapi import APIRouter, Body, Depends, Path, Query, status
from inse.projects.model import (
BundProjectPage,
CordisEuProjectPage,
DfgProjectPage,
EuOrganizationProjectSummaryPage,
FundingProjectPage,
InstitutionFunderSummary,
ProjectType,
@@ -36,31 +34,6 @@ logger = logging.getLogger(__name__)
router = APIRouter(prefix="/api/projects", tags=[Tags.PROJECTS])
@router.get(
"/author/{raw_oa_author_id}/eu",
summary="Get EU projects for an author.",
description="Returns a list of EU projects associated with the specified author ID.",
operation_id="getEuProjectsForAuthor",
responses={
status.HTTP_200_OK: {
"description": "Successful Response",
"model": CordisEuProjectPage,
},
status.HTTP_404_NOT_FOUND: {"description": "Author not found"},
},
response_model_by_alias=False,
)
async def get_eu_projects_for_author(
raw_oa_author_id: Annotated[str, Path(description="The author ID to filter by.")],
) -> CordisEuProjectPage:
logger.debug(
f"Received request to get EU projects for author_id={raw_oa_author_id}"
)
return await projects_service.search_cordis_eu_projects_for_author_id(
raw_oa_author_id=raw_oa_author_id,
)
@router.post(
"/institution/bund/search",
summary="Get bund projects.",
@@ -113,6 +86,91 @@ async def get_single_dfg_project(
)
@router.get(
"/bund/search",
summary="Search BUND projects.",
description="Returns a page of BUND project summaries.",
operation_id="searchBundProjectsWithFilters",
responses={
status.HTTP_200_OK: {
"description": "Successful Response",
"model": BundProjectPage,
},
},
response_model_by_alias=False,
)
async def search_bund_projects(
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,
institution_ids: Annotated[
Optional[List[str]],
Query(description="Institution IDs to filter by."),
] = None,
page: Annotated[int, Query(description="The page number.", ge=0)] = 0,
size: Annotated[int, Query(description="The page size.", ge=1)] = 20,
sort_by: Annotated[str, Query(description="Sort field.")] = "title",
sort_direction: Annotated[
str,
Query(description="Sort direction: asc or desc."),
] = "asc",
fuzzy: Annotated[
bool,
Query(description="Use OpenAlex topic-id resolution if true, otherwise raw keyword search."),
] = False,
) -> BundProjectPage:
return await projects_service.search_bund_projects_with_filters(
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,
institution_ids=institution_ids,
page=page,
size=size,
sort_by=sort_by,
sort_direction=sort_direction,
fuzzy=fuzzy
)
@router.get(
"/bund/{id}",
summary="Get a single BUND project.",
@@ -134,25 +192,37 @@ async def get_single_bund_project(
return await projects_service.get_single_bund_project(
project_id=id,
)
########
from inse.projects.model import EuCordisProjectSearchPage, EuCordisProjectType
from inse.projects.service import search_eu_cordis_projects_summary_impl
from inse.projects.service import search_eu_cordis_projects
@router.get(
"/eu/search",
summary="Search EU CORDIS projects.",
description="Returns a page of EU CORDIS project summaries across FP7, Horizon 2020 and Horizon Europe.",
operation_id="searchEuCordisProjectsSummary",
description=(
"Returns a page of EU CORDIS project summaries across FP7, Horizon 2020 and "
"Horizon Europe. Single entry point for EU CORDIS project search: filter by "
"institution, author(s), organization, OpenAlex topic, programme, funding "
"scheme, status, funding years and/or country, in any combination."
),
operation_id="searchEuCordisProjects",
responses={
status.HTTP_200_OK: {
"description": "Successful Response",
"model": EuCordisProjectSearchPage,
},
status.HTTP_404_NOT_FOUND: {"description": "Institution not found"},
},
response_model_by_alias=False,
)
async def search_eu_cordis_projects_summary(
async def search_eu_cordis_projects_endpoint(
institutions_search_client: Annotated[
InstitutionsSearchClient, Depends(get_institutions_search_client)
],
raw_oa_institution_id: Annotated[
Optional[str],
Query(description="OpenAlex institution ID to filter by."),
] = None,
author_id: Annotated[
Optional[str],
Query(description="OpenAlex author ID to filter by."),
@@ -226,12 +296,14 @@ async def search_eu_cordis_projects_summary(
] = False,
) -> EuCordisProjectSearchPage:
logger.debug(
"Received EU CORDIS search request: author_id=%s, author_ids=%s, "
"Received EU CORDIS search request: raw_oa_institution_id=%s, "
"author_id=%s, author_ids=%s, "
"organization_ids=%s, organization_names=%s, project_types=%s, "
"title=%s, keywords=%s, topic_ids=%s, filter_topic_ids=%s, "
"funding_start_years=%s, funding_end_years=%s, countries=%s, "
"framework_programmes=%s, funding_schemes=%s, statuses=%s, "
"page=%s, size=%s, sort_by=%s, sort_direction=%s, fuzzy=%s",
raw_oa_institution_id,
author_id,
author_ids,
organization_ids,
@@ -254,7 +326,9 @@ async def search_eu_cordis_projects_summary(
fuzzy,
)
return await search_eu_cordis_projects_summary_impl(
return await search_eu_cordis_projects(
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,
@@ -383,35 +457,6 @@ async def get_institution_bund_projects_funding_over_time(
)
@router.post(
"/institution/eu/search",
summary="Get EU projects.",
description="Returns a page of EU projects based on the provided pagination parameters and optional institution filter.",
operation_id="searchCordisEuProjects",
responses={
status.HTTP_200_OK: {
"description": "Successful Response",
"model": EuOrganizationProjectSummaryPage,
},
status.HTTP_404_NOT_FOUND: {"description": "Institution not found"},
},
response_model_by_alias=False,
)
async def search_cordis_eu_projects(
institutions_search_client: Annotated[
InstitutionsSearchClient, Depends(get_institutions_search_client)
],
projects_filtering_properties: Annotated[
ProjectsFilteringProperties,
Body(description="The filtering properties for the projects search."),
],
) -> EuOrganizationProjectSummaryPage:
return await projects_service.search_cordis_eu_projects(
institutions_search_client=institutions_search_client,
projects_filtering_properties=projects_filtering_properties,
)
@router.get(
"/institution/eu/funding-over-time",
summary="Get funding over time for EU projects.",
@@ -456,7 +501,7 @@ async def get_institution_cordis_eu_projects_funding_over_time(
)
async def get_dfg_projects(
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 author IDs to filter by.")] = None,
author_filter_ids: Annotated[Optional[List[int]], Query(description="The dfg author IDs to filter by.")] = None,
institution_ids: Annotated[
Optional[List[int]], Query(description="The institution IDs to filter by.")
] = None,
+145 -112
View File
@@ -3,21 +3,17 @@ import logging
from typing import Any, Dict, List, Optional, Set
from inse.projects import projects_search_client
from inse.projects.projects_search_client import (
get_eu_organization_project_contributions,
)
from inse.projects.model import (
BundProjectPage,
CordisEuProjectPage,
DfgProjectPage,
EuOrganizationProjectSummaryPage,
EuCordisProjectSearchPage,
EuCordisProjectType,
FundingProjectPage,
InstitutionFunderSummary,
ProjectType,
ProjectsFilteringProperties,
ProjectsSortBy,
SortDirection,
CordisEuProject
)
from inse.models.dfg_project_details import DfgProjectDetails
from inse.models.bund_project_details import BundProjectDetails
@@ -25,12 +21,16 @@ from inse.institutions.institutions_search_client import (
InstitutionsSearchClient,
)
from inse.exceptions import NotFoundException
from inse.persons.logic import get_author_name_by_id
from inse.persons.logic import get_author_name_by_id, get_author_name_with_alternatives_by_id
from inse.projects.logic import get_dfg_author_names_by_ids, get_dfg_institution_names_by_ids
from inse.works.logic import get_publication_dois_of_author
from inse.models.projects_eu_cordis.horizon2020.h2020_project_details import H2020ProjectDetails
from inse.models.projects_eu_cordis.horizon_europe.heu_project_details import HEUProjectDetails
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,
search_eu_cordis_projects as _search_eu_cordis_projects_es,
)
from typing import Union
logger = logging.getLogger(__name__)
@@ -102,50 +102,50 @@ async def get_bund_projects_by_institution_id(
return response
async def search_cordis_eu_projects(
institutions_search_client: InstitutionsSearchClient,
projects_filtering_properties: ProjectsFilteringProperties,
) -> EuOrganizationProjectSummaryPage:
if projects_filtering_properties.project_type != "eu":
raise ValueError(
f"Invalid project type: {projects_filtering_properties.project_type}. Expected 'eu'."
async def _get_dfg_project_ids_for_openalex_authors(
author_ids: List[str],
) -> Optional[List[str]]:
"""
Resolves OpenAlex authors to DFG project IDs via publication DOIs.
Multiple authors use AND semantics:
project must be connected to publications from every selected author.
"""
author_ids = [author_id for author_id in author_ids if author_id and author_id.strip()]
if not author_ids:
return None
project_sets: List[Set[str]] = []
for author_id in author_ids:
project_ids = []
#Outcommented should we use it?
# dois = await get_publication_dois_of_author(raw_oa_author_id=author_id)
# if not dois:
# return []
# logger.info("DOIs for author_id:%s: %s", author_id, dois)
# project_ids = await projects_search_client.get_dfg_project_ids_by_dois(
# dois=dois
# )
author_names_with_alternatives = (
await get_author_name_with_alternatives_by_id(author_id)
if author_id
else None
)
logger.info("Author names with alternatives for author_id:%s: %s", author_id, author_names_with_alternatives)
project_ids_by_names = await projects_search_client.get_dfg_project_ids_by_names(names=author_names_with_alternatives)
logger.info("Project IDs by names for author_id:%s: %s", author_id, project_ids_by_names)
project_ids = list(set(project_ids) | set(project_ids_by_names))
if not project_ids:
return []
return await get_cordis_eu_projects_by_institution_id(
institutions_search_client=institutions_search_client,
projects_filtering_properties=projects_filtering_properties,
)
project_sets.append(set(project_ids))
logger.info("Project sets for author_ids:%s: %s", author_ids, project_sets)
if not project_sets:
return None
async def get_cordis_eu_projects_by_institution_id(
institutions_search_client: InstitutionsSearchClient,
projects_filtering_properties: ProjectsFilteringProperties,
) -> EuOrganizationProjectSummaryPage:
if not projects_filtering_properties.raw_oa_institution_id:
raise ValueError(
"raw_oa_institution_id must be provided to fetch CORDIS EU projects by institution ID"
)
logger.info(
f"Fetching CORDIS EU projects for institution_id={projects_filtering_properties.raw_oa_institution_id}, page={projects_filtering_properties.page}, size={projects_filtering_properties.size}"
)
institution_aliases = (
await institutions_search_client.get_institution_aliases_by_oa_institution_id(
projects_filtering_properties.raw_oa_institution_id
)
)
logger.debug(
f"Found institution aliases for institution_id={projects_filtering_properties.raw_oa_institution_id}: {institution_aliases}"
)
page = await get_eu_organization_project_contributions(
organization_names=institution_aliases,
projects_filtering_properties=projects_filtering_properties,
)
logger.debug(f"get_cordis_eu_projects_by_institution_id response: {page}")
return page
return list(set.intersection(*project_sets))
async def get_dfg_projects_by_author_id(
author_id: Optional[str],
@@ -184,28 +184,29 @@ async def get_dfg_projects_by_author_id(
fuzzy,
)
filter_names = []
author_name = (
await get_author_name_by_id(author_id)
if author_id
else None
)
if author_id and not author_name:
logger.debug("No author name found for author_id=%s", author_id)
author_project_ids = []
if author_id:
author_project_ids = await _get_dfg_project_ids_for_openalex_authors([author_id])
logger.info("Author project IDs for author_id:%s: %s", author_id, author_project_ids)
if not author_project_ids:
return DfgProjectPage(
elements=[],
page=page,
size=size,
total=0)
filter_names = (
await get_dfg_author_names_by_ids(author_ids=author_filter_ids)
if author_filter_ids
else []
)
if author_filter_ids:
filter_names = (
await get_dfg_author_names_by_ids(author_ids=author_filter_ids)
if author_filter_ids
else []
)
if author_filter_ids and not filter_names:
logger.debug(
"No author names found for author_filter_ids=%s",
author_filter_ids,
)
if author_name:
filter_names.append(author_name)
if institution_ids:
logger.debug(
"No institutions found for institution_ids=%s",
@@ -215,6 +216,7 @@ async def get_dfg_projects_by_author_id(
return await projects_search_client.search_dfg_projects(
page=page,
size=size,
project_ids=author_project_ids,
names=filter_names or [],
institution_ids=institution_ids,
keywords=keywords,
@@ -232,18 +234,11 @@ async def get_institution_cordis_eu_projects_funding_over_time(
institutions_search_client: InstitutionsSearchClient,
raw_oa_institution_id: str,
) -> InstitutionFunderSummary:
institution_aliases = (
await institutions_search_client.get_institution_aliases_by_oa_institution_id(
raw_oa_institution_id
)
)
page = await get_eu_organization_project_contributions(
organization_names=institution_aliases,
projects_filtering_properties=ProjectsFilteringProperties(
project_type=ProjectType.EU,
page=0,
size=10000,
),
page = await search_eu_cordis_projects(
page=0,
size=10000,
raw_oa_institution_id=raw_oa_institution_id,
institutions_search_client=institutions_search_client,
)
return _calculate_funding_over_time(
@@ -251,7 +246,7 @@ async def get_institution_cordis_eu_projects_funding_over_time(
projects=page.elements,
funding_start_attr="start_date",
funding_end_attr="end_date",
funding_amount_attr="ec_contribution",
funding_amount_attr="ec_max_contribution",
)
@@ -286,7 +281,42 @@ async def get_institution_bund_projects_funding_over_time(
funding_end_attr="funding_end",
funding_amount_attr="grant_amount",
)
#Bund
async def search_bund_projects_with_filters(
executing_agency: Optional[str],
institution_ids: Optional[List[str]],
title: Optional[str],
keywords: Optional[List[str]],
funding_arts: Optional[List[str]],
topic_ids: Optional[List[str]],
filter_topic_ids: Optional[List[str]],
funding_start_years: Optional[List[str]],
funding_end_years: Optional[List[str]],
countries: Optional[List[str]],
page: int,
size: int,
sort_by: str = "title",
sort_direction: str = "asc",
fuzzy: bool = False,
) -> BundProjectPage:
return await projects_search_client.search_bund_projects_with_filters(
executing_agency=executing_agency,
institution_ids=[],
funding_arts=funding_arts,
title=title,
keywords=keywords,
filter_topic_ids=filter_topic_ids,
topic_ids=topic_ids,
funding_start_years=funding_start_years,
funding_end_years=funding_end_years,
countries=countries,
page=page,
size=size,
sort_by=sort_by,
sort_direction=sort_direction,
fuzzy=fuzzy
)
def _calculate_funding_over_time(
project_type: ProjectType,
@@ -383,43 +413,14 @@ async def get_single_eu_cordis_project(
) -> Optional[Union[Fp7ProjectDetails, H2020ProjectDetails, HEUProjectDetails]]:
logger.debug(f"Fetching single EU Cordis project for id={project_id}")
project = await projects_search_client.get_eu_cordis_projects_by_id(project_id)
project = await get_enriched_cordis_project_by_id(project_id)
if not project:
return None
return project
async def search_cordis_eu_projects_for_author_id(
raw_oa_author_id: str,
) -> CordisEuProjectPage:
# EU CORDIS project search
# Direct search not possible -> multi stage search
# 1. Exisiting author has publications with DOIs
# 2. CORDIS EU projects have associated publications with DOIs
# 3. Matching DOIs of author publications with DOIs of CORDIS EU project publications -> projects with associated publications of the author
dois = await get_publication_dois_of_author(raw_oa_author_id=raw_oa_author_id)
logger.debug(f"Found DOIs for author_id={raw_oa_author_id}: {dois}")
project_ids = await projects_search_client.get_cordis_eu_project_ids_by_dois(dois=dois)
logger.debug(
f"Found project IDs {project_ids} for author_id={raw_oa_author_id} and dois={dois}"
)
funding_project_page = await projects_search_client.get_cordis_eu_projects_by_project_ids(
project_ids=project_ids
)
return funding_project_page
################
from inse.projects.eu_cordis_projects_client import search_eu_cordis_projects
from inse.projects.model import EuCordisProjectType, EuCordisProjectSearchPage
from inse.works.logic import get_publication_dois_of_author
async def _get_eu_project_ids_for_openalex_authors(
author_ids: List[str],
@@ -456,10 +457,12 @@ async def _get_eu_project_ids_for_openalex_authors(
return list(set.intersection(*project_sets))
async def search_eu_cordis_projects_summary_impl(
async def search_eu_cordis_projects(
page: int,
size: int,
project_types: Optional[List[EuCordisProjectType]] = None,
raw_oa_institution_id: Optional[str] = None,
institutions_search_client: Optional[InstitutionsSearchClient] = None,
author_id: Optional[str] = None,
author_ids: Optional[List[str]] = None,
organization_ids: Optional[List[str]] = None,
@@ -478,7 +481,37 @@ async def search_eu_cordis_projects_summary_impl(
sort_direction: str = "asc",
fuzzy: bool = False,
) -> EuCordisProjectSearchPage:
"""Single entry point for EU CORDIS project search.
Institution search: pass raw_oa_institution_id (and institutions_search_client
to resolve it to name aliases) - equivalent to what used to be a separate
"institution projects" endpoint, now just another organization_names source.
Author search: pass author_id/author_ids (OpenAlex author ids). Multiple
authors use AND semantics - a project must be linked to publications from
every selected author.
All other filters (organization id/name, topic, framework programme,
funding scheme, status, funding years, country) are ANDed together as in
eu_cordis_projects_client.search_eu_cordis_projects.
"""
resolved_organization_names: List[str] = list(organization_names or [])
if raw_oa_institution_id:
if institutions_search_client is None:
raise ValueError(
"institutions_search_client must be provided when raw_oa_institution_id is set"
)
institution_aliases = (
await institutions_search_client.get_institution_aliases_by_oa_institution_id(
raw_oa_institution_id
)
)
logger.debug(
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:
@@ -488,12 +521,12 @@ async def search_eu_cordis_projects_summary_impl(
author_ids=all_author_ids
)
return await search_eu_cordis_projects(
return await _search_eu_cordis_projects_es(
page=page,
size=size,
project_types=project_types,
organization_ids=organization_ids,
organization_names=organization_names,
organization_names=resolved_organization_names or None,
author_project_ids=author_project_ids,
keywords=keywords,
topic_ids=topic_ids,
+1 -7
View File
@@ -64,9 +64,9 @@ model/bodyLogin.ts
model/bodyRequestOtk.ts
model/bodyRequestPasswordReset.ts
model/bodyResetPassword.ts
model/bundProject.ts
model/bundProjectDetails.ts
model/bundProjectPage.ts
model/bundProjectSummary.ts
model/careerMetrics.ts
model/careerStage.ts
model/collaborationNetwork.ts
@@ -76,8 +76,6 @@ model/companyConnection.ts
model/companyConnectionsAvailability.ts
model/companyConnectionsResponse.ts
model/companyStatusFilter.ts
model/cordisEuProject.ts
model/cordisEuProjectPage.ts
model/costUsd.ts
model/createAccountRequest.ts
model/createOrganizationRequest.ts
@@ -107,8 +105,6 @@ model/euCordisProjectSearchPage.ts
model/euCordisProjectSummary.ts
model/euCordisProjectType.ts
model/euCordisTopicSummary.ts
model/euOrganizationProjectSummary.ts
model/euOrganizationProjectSummaryPage.ts
model/euProjectData.ts
model/extractedKeywords.ts
model/extractedKeywordsLLM.ts
@@ -176,7 +172,6 @@ model/keywordPatentSearchDiagnostics.ts
model/keywordPatentSearchItem.ts
model/keywordToAuthorRequest.ts
model/keywordTopicMatch.ts
model/keywords.ts
model/keywordsRequest.ts
model/keywordsTopicsRequest.ts
model/keywordsTopicsResponse.ts
@@ -242,7 +237,6 @@ model/topicIds.ts
model/topicPageV2.ts
model/topicSubfield.ts
model/topicYearlyData.ts
model/topics.ts
model/topicsByTime.ts
model/topicsByYear.ts
model/topicsListResponse.ts
File diff suppressed because it is too large Load Diff
+19 -21
View File
@@ -1,31 +1,29 @@
/**
* Innovation Search Engine API
*
*
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
import { BundProject } from './bundProject';
import { BundProjectSummary } from './bundProjectSummary';
export interface BundProjectPage {
/**
* The current page number.
*/
page?: number;
/**
* The requested page size.
*/
size?: number;
/**
* The total number of items.
*/
total?: number;
/**
* The bund projects on this page.
*/
elements?: Array<BundProject>;
export interface BundProjectPage {
/**
* The current page number.
*/
page?: number;
/**
* The requested page size.
*/
size?: number;
/**
* The total number of items.
*/
total?: number;
/**
* The bund projects on this page.
*/
elements?: Array<BundProjectSummary>;
}
@@ -7,9 +7,10 @@
* https://openapi-generator.tech
* Do not edit the class manually.
*/
import { Topic } from './topic';
export interface BundProject {
export interface BundProjectSummary {
funding_code?: string | null;
department?: string | null;
department_fullname?: string | null;
@@ -38,5 +39,6 @@ export interface BundProject {
date?: string | null;
'new'?: boolean | null;
duration?: string | null;
oa_topics?: Array<Topic> | null;
}
@@ -1,41 +0,0 @@
/**
* Innovation Search Engine API
*
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
import { Keywords } from './keywords';
import { Topics } from './topics';
export interface CordisEuProject {
/**
* Unique identifier for the project, typically the CORDIS ID
*/
id: string;
rcn?: string | null;
acronym?: string | null;
title?: string | null;
objective?: string | null;
frameworkProgramme?: string | null;
fundingScheme?: string | null;
legalBasis?: string | null;
masterCall?: string | null;
subCall?: string | null;
topics?: Topics | null;
nature?: string | null;
status?: string | null;
ecMaxContribution?: number | null;
totalCost?: number | null;
startDate?: string | null;
endDate?: string | null;
ecSignatureDate?: string | null;
contentUpdateDate?: string | null;
grantDoi?: string | null;
humanValidated?: boolean | null;
keywords?: Keywords | null;
}
@@ -1,31 +0,0 @@
/**
* Innovation Search Engine API
*
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
import { CordisEuProject } from './cordisEuProject';
export interface CordisEuProjectPage {
/**
* The current page number.
*/
page?: number;
/**
* The requested page size.
*/
size?: number;
/**
* The total number of items.
*/
total?: number;
/**
* The CORDIS EU projects on this page.
*/
elements?: Array<CordisEuProject>;
}
@@ -1,27 +0,0 @@
/**
* Innovation Search Engine API
*
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
export interface EuOrganizationProjectSummary {
/**
* The unique identifier of the organization.
*/
organization_id: string;
/**
* The unique identifier of the project.
*/
project_id: string;
title?: string | null;
start_date?: string | null;
end_date?: string | null;
acronym?: string | null;
ec_contribution?: number | null;
}
@@ -1,31 +0,0 @@
/**
* Innovation Search Engine API
*
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
import { EuOrganizationProjectSummary } from './euOrganizationProjectSummary';
export interface EuOrganizationProjectSummaryPage {
/**
* The current page number.
*/
page?: number;
/**
* The requested page size.
*/
size?: number;
/**
* The total number of items.
*/
total?: number;
/**
* The organization project summaries on this page.
*/
elements?: Array<EuOrganizationProjectSummary>;
}
-17
View File
@@ -1,17 +0,0 @@
/**
* Innovation Search Engine API
*
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
/**
* Keywords associated with the project
*/
export interface Keywords {
}
+1 -7
View File
@@ -30,9 +30,9 @@ export * from './bodyLogin';
export * from './bodyRequestOtk';
export * from './bodyRequestPasswordReset';
export * from './bodyResetPassword';
export * from './bundProject';
export * from './bundProjectDetails';
export * from './bundProjectPage';
export * from './bundProjectSummary';
export * from './careerMetrics';
export * from './careerStage';
export * from './collaborationNetwork';
@@ -42,8 +42,6 @@ export * from './companyConnection';
export * from './companyConnectionsAvailability';
export * from './companyConnectionsResponse';
export * from './companyStatusFilter';
export * from './cordisEuProject';
export * from './cordisEuProjectPage';
export * from './costUsd';
export * from './createAccountRequest';
export * from './createOrganizationRequest';
@@ -73,8 +71,6 @@ export * from './euCordisProjectSearchPage';
export * from './euCordisProjectSummary';
export * from './euCordisProjectType';
export * from './euCordisTopicSummary';
export * from './euOrganizationProjectSummary';
export * from './euOrganizationProjectSummaryPage';
export * from './euProjectData';
export * from './extractedKeywords';
export * from './extractedKeywordsLLM';
@@ -142,7 +138,6 @@ export * from './keywordPatentSearchDiagnostics';
export * from './keywordPatentSearchItem';
export * from './keywordToAuthorRequest';
export * from './keywordTopicMatch';
export * from './keywords';
export * from './keywordsRequest';
export * from './keywordsTopicsRequest';
export * from './keywordsTopicsResponse';
@@ -207,7 +202,6 @@ export * from './topicIds';
export * from './topicPageV2';
export * from './topicSubfield';
export * from './topicYearlyData';
export * from './topics';
export * from './topicsByTime';
export * from './topicsByYear';
export * from './topicsListResponse';
-14
View File
@@ -1,14 +0,0 @@
/**
* Innovation Search Engine API
*
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
export interface Topics {
}
+20 -4
View File
@@ -15,8 +15,8 @@ import {
import { institutionsResolver } from './resolvers/institutions.resolver';
import { bundProjectsFundingResolver } from './resolvers/bund-projects-funding.resolver';
import { dfgSingleProjectResolver } from './resolvers/dfg-single-project-resolver';
import { bundSingleProjectResolver } from './resolvers/bund-single-project-resolver';
import { cordisEuProjectPageResolver } from './resolvers/cordis-eu-project-page.resolver';
import { bundSingleProjectResolver } from './resolvers/bund-single-project.resolver';
//import { cordisEuProjectPageResolver } from './resolvers/cordis-eu-project-page.resolver';
import { cordisEuProjectsFundingResolver } from './resolvers/cordis-eu-projects-funding.resolver';
import { fundingProjectPageResolver } from './resolvers/funding-project-page.resolver';
import { euSingleProjectResolver } from './resolvers/eu-single-project-resolver';
@@ -40,7 +40,7 @@ import { selectedInstitutionsResolver } from './resolvers/selected-institutions.
import { SearchResultsStateService } from './modules/keywords-search/search-results/search-results-state.service';
import { roleGuard } from './shared/guards/role.guard';
import { UserRole } from './api';
import { personCordisEuProjectPageResolver } from './resolvers/person-cordis-eu-project-page.resolver';
//import { personCordisEuProjectPageResolver } from './resolvers/person-cordis-eu-project-page.resolver';
import { euCordisProjectsResolver } from './resolvers/eu-cordis-projects.resolver';
import { selectedAuthorsResolver } from './resolvers/selected-authors.resolver';
import { workClassificationResolver } from './resolvers/work-classification.resolver';
@@ -51,6 +51,8 @@ import { selectedEuInstitutionsResolver } from './resolvers/selected-eu-institut
import { uniTrendResolver } from './resolvers/uni-trend.resolver';
import { EuProjectsComponent } from './shared/ui/eu-projects/eu-projects.component';
import { DfgProjectsComponent } from './shared/ui/dfg-projects/dfg-projects.component';
import { BundProjectsComponent } from './shared/ui/bund-projects/bund-projects.component';
import { bundProjectsResolver } from './resolvers/bund-projects.resolver';
export const routes: Routes = [
{
path: '',
@@ -502,6 +504,20 @@ export const routes: Routes = [
resolvingFor: RESOLVING_PROJECT_PAGE_FOR.PERSON,
},
},
{
path: 'bund',
component: BundProjectsComponent,
resolve: {
bundProjectPage: bundProjectsResolver,
selectedBundInstitutionsPage: selectedInstitutionsResolver,
selectedBundAuthorsPage: selectedAuthorsResolver,
selectedTopicsPage: selectedTopicsResolver,
},
runGuardsAndResolvers: 'always',
data: {
resolvingFor: RESOLVING_PROJECT_PAGE_FOR.KEYWORDS_SEARCH,
},
},
],
},
{
@@ -659,7 +675,7 @@ export const routes: Routes = [
resolve: {
bundProjectPage: bundProjectPageResolver,
bundProjectsFunding: bundProjectsFundingResolver,
cordisEuProjectPage: cordisEuProjectPageResolver,
cordisEuProjectPage: euCordisProjectsResolver,
cordisEuProjectsFunding: cordisEuProjectsFundingResolver,
},
runGuardsAndResolvers: (from, to) => {
@@ -9,12 +9,12 @@ import {
} from '@angular/core';
import { ActivatedRoute, Router, RouterModule } from '@angular/router';
import {
BundProject,
BundProjectPage,
EuOrganizationProjectSummary,
EuOrganizationProjectSummaryPage,
EuCordisProjectSearchPage,
InstitutionFunderSummary,
EuCordisProjectSummary,
} from '../../api';
import { BundProjectSummary } from '../../api/model/bundProjectSummary';
import { MatCardModule } from '@angular/material/card';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatTabChangeEvent, MatTabsModule } from '@angular/material/tabs';
@@ -77,12 +77,13 @@ export class InstitutionProjectsComponent implements OnInit {
fundingEndTmp = viewChild.required<TemplateRef<any>>('fundingEndTmp');
fundingAmountTmp = viewChild.required<TemplateRef<any>>('fundingAmountTmp');
cordisEuProjectPage = input.required<EuOrganizationProjectSummaryPage>();
cordisEuProjectPage = input.required<EuCordisProjectSearchPage>();
euProjectColumns: GenericColumn<EuProjectRow>[] = [];
euProjectData: EuProjectRow[] = [];
euProjectActionsTmp = viewChild.required<TemplateRef<any>>(
'euProjectActionsTmp',
);
acronymTmp = viewChild.required<TemplateRef<any>>('acronymTmp');
bundProjectPage = input.required<BundProjectPage>();
bundProjectColumns: GenericColumn<BundProjectRow>[] = [];
@@ -165,6 +166,7 @@ export class InstitutionProjectsComponent implements OnInit {
type: 'accessor',
accessorKey: 'topic',
},
{
id: 'funding_start',
header: 'Förderbeginn',
@@ -181,7 +183,7 @@ export class InstitutionProjectsComponent implements OnInit {
},
{
id: 'funding_amount',
header: 'Fördersumme',
header: 'Fördersumme (EC)',
type: 'accessor',
accessorKey: 'funding_amount',
cellTemplate: this.fundingAmountTmp(),
@@ -230,19 +232,19 @@ export class InstitutionProjectsComponent implements OnInit {
];
}
transformEuRow(project: EuOrganizationProjectSummary): EuProjectRow {
transformEuRow(project: EuCordisProjectSummary): EuProjectRow {
return {
id: project.project_id,
id: project.id,
topic: project.title || '',
funding_start: project.start_date
? new Date(project.start_date)
: new Date(0),
funding_end: project.end_date ? new Date(project.end_date) : new Date(0),
funding_amount: Number(project.ec_contribution) || 0,
funding_amount: Number(project.ec_max_contribution) || 0,
};
}
transformBundRow(project: BundProject): BundProjectRow {
transformBundRow(project: BundProjectSummary): BundProjectRow {
return {
id: project.funding_code || '',
topic: project.topic || '',
@@ -22,9 +22,9 @@
<span class="mode-badge">
<mat-slide-toggle
labelPosition="before"
matTooltip="Wenn aktiviert, werden die extrahierten Keywords auf bekannte Themenbereiche abgebildet, man kann dann nach Themen filtern. Wenn deaktiviert, werden die Keywords direkt für die Suche verwendet."
(change)="onToggleFuzzySearch($event)"
[checked]="state.fuzzySearch()"
matTooltip="Wenn aktiviert, werden die extrahierten Keywords auf bekannte Themenbereiche abgebildet, was die Suchergebnisse vermehrt">
[checked]="state.fuzzySearch()">
Fuzzy Search
</mat-slide-toggle>
</span>
@@ -7,7 +7,7 @@ import {
RouterLinkActive,
RouterOutlet,
} from '@angular/router';
import { MatTooltipModule } from '@angular/material/tooltip';
import { MatButtonModule } from '@angular/material/button';
import { MatCardModule } from '@angular/material/card';
import { MatIconModule } from '@angular/material/icon';
@@ -38,6 +38,7 @@ import {
TopicChipComponent,
MatTabsModule,
MatSlideToggleModule,
MatTooltipModule,
],
providers: [SearchResultsStateService],
templateUrl: './search-results.component.html',
@@ -27,5 +27,9 @@ export class PersonProjectsComponent {
path: 'eu',
label: 'EU-Projekte',
},
{
path: 'bund',
label: 'Bund-Projekte',
},
];
}
@@ -47,9 +47,9 @@
</ng-template>
<ng-template #journalTemplate let-pub>
@if (pub.journalNumber) {
<span class="journal-chip" [matTooltip]="pub.journalNumber">
{{ pub.journalNumber }}
@if (pub.journalNumber ?? pub.journalTitle) {
<span class="journal-chip" [matTooltip]="pub.journalTitle">
{{ pub.journalNumber || pub.journalTitle }}
</span>
} @else {
<span class="empty-value">—</span>
@@ -71,10 +71,10 @@ export class PublicationsTableComponent {
cellTemplate: this.authorsTemplate(),
},
{
id: 'journalNumber',
id: 'journalTitle',
header: 'Zeitschrift',
type: 'accessor',
accessorKey: 'journalNumber',
accessorKey: 'journalTitle',
cellTemplate: this.journalTemplate(),
},
{
@@ -115,7 +115,7 @@ export class PublicationsTableComponent {
return;
}
const doi = pub.doi?.trim() ?? 'unknown';
const doi = (pub.doi ?? pub.qaProcessedDoi)?.trim() ?? 'unknown';
// Encode DOI and navigate
const encodedDoi = encodeURIComponent(doi);
@@ -0,0 +1,71 @@
import { ResolveFn } from '@angular/router';
import {
BundProjectPage,
ProjectsService,
ProjectsSortBy,
SortDirection,
} from '../api';
import { inject } from '@angular/core';
export const bundProjectQueryParamKeys = {
page: 'page',
size: 'size',
title: 'title',
authorId: 'authorId',
funding_art: 'funding_art',
institutionId: 'institutionId',
funding_start: 'funding_start',
funding_end: 'funding_end',
topicId: 'topicId',
sortBy: 'sort_by',
sortDirection: 'sort_direction',
legend: 'legend',
legend_expanded: 'legend_expanded',
} as const;
export const bundProjectsResolver: ResolveFn<BundProjectPage> = (
route,
state,
) => {
console.log('bundProjectsResolver called with route:', route);
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,
);
const fundingEndYears = route.queryParamMap.getAll(
bundProjectQueryParamKeys.funding_end,
);
const topicIds = route.queryParamMap.get(bundProjectQueryParamKeys.topicId);
const fundingArts = route.queryParamMap.getAll(
bundProjectQueryParamKeys.funding_art,
);
const sortBy = (route.queryParamMap.get(bundProjectQueryParamKeys.sortBy) ||
'title') as ProjectsSortBy;
const sortDirection = (route.queryParamMap.get(
bundProjectQueryParamKeys.sortDirection,
) || 'asc') as SortDirection;
const search =
route.queryParamMap.get(bundProjectQueryParamKeys.title) || undefined;
return inject(ProjectsService).searchBundProjectsWithFilters(
institutionIds,
fundingArts,
search,
[],
[],
[],
fundingStartYears,
fundingEndYears,
[],
[],
Number(page),
Number(size),
sortBy,
sortDirection,
false,
);
};
@@ -1,35 +1,35 @@
import { ResolveFn } from '@angular/router';
import {
EuOrganizationProjectSummaryPage,
ProjectsService,
ProjectsSortBy,
SortDirection,
} from '../api';
import { inject } from '@angular/core';
// import { ResolveFn } from '@angular/router';
// import {
// EuOrganizationProjectSummaryPage,
// ProjectsService,
// ProjectsSortBy,
// SortDirection,
// } from '../api';
// import { inject } from '@angular/core';
export const cordisEuProjectPageResolver: ResolveFn<
EuOrganizationProjectSummaryPage
> = (route, state) => {
const page = route.queryParamMap.get('page') ?? '1';
const size = route.queryParamMap.get('size') ?? '10';
let institutionId = route.paramMap.get('institutionId');
if (!institutionId) {
institutionId = route.parent?.paramMap.get('institutionId') ?? null;
}
// export const cordisEuProjectPageResolver: ResolveFn<
// EuOrganizationProjectSummaryPage
// > = (route, state) => {
// const page = route.queryParamMap.get('page') ?? '1';
// const size = route.queryParamMap.get('size') ?? '10';
// let institutionId = route.paramMap.get('institutionId');
// if (!institutionId) {
// institutionId = route.parent?.paramMap.get('institutionId') ?? null;
// }
const sortBy = (route.queryParamMap.get('sort_by') ||
'title') as ProjectsSortBy;
const sortDirection = (route.queryParamMap.get('sort_direction') ||
'asc') as SortDirection;
const search = route.queryParamMap.get('search');
// const sortBy = (route.queryParamMap.get('sort_by') ||
// 'title') as ProjectsSortBy;
// const sortDirection = (route.queryParamMap.get('sort_direction') ||
// 'asc') as SortDirection;
// const search = route.queryParamMap.get('search');
return inject(ProjectsService).searchCordisEuProjects({
project_type: 'eu',
page: Number(page),
size: Number(size),
raw_oa_institution_id: institutionId,
query: search,
sort_by: sortBy,
sort_direction: sortDirection,
});
};
// return inject(ProjectsService).searchCordisEuProjects({
// project_type: 'eu',
// page: Number(page),
// size: Number(size),
// raw_oa_institution_id: institutionId,
// query: search,
// sort_by: sortBy,
// sort_direction: sortDirection,
// });
// };
@@ -2,7 +2,7 @@ import { inject } from '@angular/core';
import { ResolveFn } from '@angular/router';
import { DfgProjectPage, ProjectsService } from '../api';
export const projectQueryParamKeys = {
export const dfgProjectQueryParamKeys = {
page: 'page',
size: 'size',
title: 'title',
@@ -17,10 +17,13 @@ export const projectQueryParamKeys = {
legend_expanded: 'legend_expanded',
} 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 dfgProjectsResolver: ResolveFn<DfgProjectPage> = (
route,
state,
@@ -36,30 +39,31 @@ export const dfgProjectsResolver: ResolveFn<DfgProjectPage> = (
route.data,
);
const page = Number(route.queryParamMap.get(projectQueryParamKeys.page)) || 0;
const page =
Number(route.queryParamMap.get(dfgProjectQueryParamKeys.page)) || 0;
const size =
Number(route.queryParamMap.get(projectQueryParamKeys.size)) || 10;
Number(route.queryParamMap.get(dfgProjectQueryParamKeys.size)) || 10;
const searchTerm =
route.queryParamMap.get(projectQueryParamKeys.title) ?? undefined;
route.queryParamMap.get(dfgProjectQueryParamKeys.title) ?? undefined;
const sortBy =
route.queryParamMap.get(projectQueryParamKeys.sortBy) || 'title';
route.queryParamMap.get(dfgProjectQueryParamKeys.sortBy) || 'title';
const sortDirection =
route.queryParamMap.get(projectQueryParamKeys.sortDirection) || 'asc';
route.queryParamMap.get(dfgProjectQueryParamKeys.sortDirection) || 'asc';
const fundingStart = route.queryParamMap.getAll(
projectQueryParamKeys.funding_start,
dfgProjectQueryParamKeys.funding_start,
);
const fundingEnd = route.queryParamMap.getAll(
projectQueryParamKeys.funding_end,
dfgProjectQueryParamKeys.funding_end,
);
const filteredTopicIds = route.queryParamMap.getAll(
projectQueryParamKeys.topicId,
dfgProjectQueryParamKeys.topicId,
);
const institutionIds = route.queryParamMap
.getAll(projectQueryParamKeys.institutionId)
.getAll(dfgProjectQueryParamKeys.institutionId)
.map((id) => Number(id));
const authorIds = route.queryParamMap
.getAll(projectQueryParamKeys.authorId)
.getAll(dfgProjectQueryParamKeys.authorId)
.map((id) => Number(id));
if (resolvingFor === RESOLVING_PROJECT_PAGE_FOR.PERSON) {
@@ -33,6 +33,7 @@ export const euProjectQueryParamKeys = {
const RESOLVING_PROJECT_PAGE_FOR_KEY = 'resolvingFor';
export const RESOLVING_PROJECT_PAGE_FOR = {
INSTITUTION: 'INSTITUTION',
PERSON: 'PERSON',
KEYWORDS_SEARCH: 'KEYWORDS_SEARCH',
} as const;
@@ -142,7 +143,8 @@ export const euCordisProjectsResolver: ResolveFn<EuCordisProjectSearchPage> = (
if (resolvingFor === RESOLVING_PROJECT_PAGE_FOR.PERSON) {
const rawAuthorId = route.parent?.parent?.params['id'];
return inject(ProjectsService).searchEuCordisProjectsSummary(
return inject(ProjectsService).searchEuCordisProjects(
undefined,
rawAuthorId,
authorIds,
organizationIds,
@@ -171,7 +173,8 @@ export const euCordisProjectsResolver: ResolveFn<EuCordisProjectSearchPage> = (
const selectedTopicIds = route.queryParamMap.getAll('topics');
const fuzzySearch = route.queryParamMap.get('fuzzy') === 'true';
return inject(ProjectsService).searchEuCordisProjectsSummary(
return inject(ProjectsService).searchEuCordisProjects(
undefined,
undefined,
authorIds,
organizationIds,
@@ -194,6 +197,38 @@ export const euCordisProjectsResolver: ResolveFn<EuCordisProjectSearchPage> = (
fuzzySearch,
);
}
throw new Error(`Unknown resolvingFor value: ${resolvingFor}`);
if (resolvingFor === RESOLVING_PROJECT_PAGE_FOR.INSTITUTION) {
let rawInstitutionId = route.paramMap.get('institutionId') ?? undefined;
if (!rawInstitutionId) {
rawInstitutionId =
route.parent?.paramMap.get('institutionId') ?? undefined;
}
console.log(
'Resolving EU project page for institution with ID:',
rawInstitutionId,
);
return inject(ProjectsService).searchEuCordisProjects(
rawInstitutionId,
undefined,
[],
organizationIds,
[],
[],
searchTerm,
[],
[],
[],
[],
[],
[],
[],
[],
[],
page,
size,
sortBy,
sortDirection,
false,
);
} else throw new Error(`Unknown resolvingFor value: ${resolvingFor}`);
};
@@ -1,50 +1,50 @@
import { inject } from '@angular/core';
import { ResolveFn } from '@angular/router';
import { CordisEuProjectPage, ProjectsService } from '../api';
// import { inject } from '@angular/core';
// import { ResolveFn } from '@angular/router';
// import { CordisEuProjectPage, ProjectsService } from '../api';
export const euProjectQueryParamKeys = {
page: 'page',
size: 'size',
title: 'title',
institutionId: 'institutionId',
authorId: 'authorId',
sortBy: 'sort_by',
sortDirection: 'sort_direction',
} as const;
// export const euProjectQueryParamKeys = {
// page: 'page',
// size: 'size',
// title: 'title',
// institutionId: 'institutionId',
// authorId: 'authorId',
// sortBy: 'sort_by',
// sortDirection: 'sort_direction',
// } as const;
export const personCordisEuProjectPageResolver: ResolveFn<
CordisEuProjectPage
> = (route, state) => {
const rawAuthorId = route.parent?.params['id'];
// if (!rawAuthorId) {
// throw new Error('Author ID is required to resolve EU projects.');
// }
// export const personCordisEuProjectPageResolver: ResolveFn<
// CordisEuProjectPage
// > = (route, state) => {
// const rawAuthorId = route.parent?.params['id'];
// // if (!rawAuthorId) {
// // throw new Error('Author ID is required to resolve EU projects.');
// // }
const page =
Number(route.queryParamMap.get(euProjectQueryParamKeys.page)) || 0;
const size =
Number(route.queryParamMap.get(euProjectQueryParamKeys.size)) || 10;
const searchTerm =
route.queryParamMap.get(euProjectQueryParamKeys.title) ?? undefined;
const sortBy =
route.queryParamMap.get(euProjectQueryParamKeys.sortBy) || 'title';
const sortDirection =
route.queryParamMap.get(euProjectQueryParamKeys.sortDirection) || 'asc';
// const page =
// Number(route.queryParamMap.get(euProjectQueryParamKeys.page)) || 0;
// const size =
// Number(route.queryParamMap.get(euProjectQueryParamKeys.size)) || 10;
// const searchTerm =
// route.queryParamMap.get(euProjectQueryParamKeys.title) ?? undefined;
// const sortBy =
// route.queryParamMap.get(euProjectQueryParamKeys.sortBy) || 'title';
// const sortDirection =
// route.queryParamMap.get(euProjectQueryParamKeys.sortDirection) || 'asc';
const institutionIds = route.queryParamMap.getAll(
euProjectQueryParamKeys.institutionId,
);
const authorIds = route.queryParamMap.getAll(
euProjectQueryParamKeys.authorId,
);
return inject(ProjectsService).getEuProjectsForAuthor(
rawAuthorId || '1',
// searchTerm,
// page,
// size,
// sortBy,
// sortDirection,
// institutionIds,
// authorIds,
);
};
// const institutionIds = route.queryParamMap.getAll(
// euProjectQueryParamKeys.institutionId,
// );
// const authorIds = route.queryParamMap.getAll(
// euProjectQueryParamKeys.authorId,
// );
// return inject(ProjectsService).searchEuCordisProjects(
// rawAuthorId,
// // searchTerm,
// // page,
// // size,
// // sortBy,
// // sortDirection,
// // institutionIds,
// // authorIds,
// );
// };
@@ -0,0 +1,158 @@
<app-data-table
[columns]="columns"
[data]="elements()"
[queryParamSortKey]="queryParamKeys.sortBy"
[queryParamSortDirectionKey]="queryParamKeys.sortDirection" />
<app-query-param-paginator
[total]="total()"
[queryParamPageKey]="queryParamKeys.page"
[queryParamSizeKey]="queryParamKeys.size"
[pageSizeOptions]="[10]" />
<ng-template #fundingEndTmp let-element>
{{
element.funding_end == '2999' || element.funding_end == null
? 'laufend'
: element.funding_end
}}
</ng-template>
<ng-template #actionsTmp let-element>
<a
[routerLink]="['/projects/dfg', element.id]"
target="_blank"
mat-icon-button
color="primary">
<mat-icon>open_in_new</mat-icon>
</a>
</ng-template>
<ng-template #detailRowTmp let-element>
<div class="classification-container">
@for (classification of element.subject_classifications; track $index) {
<p>
{{ classification.wissenschaftsbereich || '-' }}
→ {{ classification.fachkollegium || '-' }} →
{{ classification.fachgebiet || '-' }} →
{{ classification.fach || '-' }}
</p>
} @empty {
<span>-</span>
}
</div>
</ng-template>
<!-- <ng-template #authorsTmp let-project>
@let projectAuthors = getProjectAuthors(project);
@let isProjectAuthorsExpanded = isProjectPersonsExpanded(project);
@let visibleAuthors =
isProjectAuthorsExpanded ? projectAuthors : projectAuthors.slice(0, 3); -->
<!-- <div class="author-tags" aria-label="Autoren" style="padding: 0.5rem 0">
@for (author of visibleAuthors; track author.person_id) {
<button
type="button"
class="publication-institution-tag"
[class.active]="isAuthorActive(author.person_id!)"
[matTooltip]="getAuthorTooltipText(author)"
matTooltipPosition="above"
[attr.aria-label]="getAuthorTooltipText(author)"
(click)="filterByAuthor(author.person_id!)">
<mat-icon class="institution-icon">person</mat-icon>
<span class="institution-name">{{ author.full_name }}</span>
</button>
} @empty {
<span class="empty-text">-</span>
} -->
<!-- @if (projectAuthors.length > 3) {
<button
type="button"
class="publication-institution-more"
[attr.aria-expanded]="isProjectAuthorsExpanded"
(click)="toggleProjectAuthorsExpansion(project)">
{{
isProjectAuthorsExpanded
? 'weniger'
: '+' + (projectAuthors.length - 3)
}}
</button>
} -->
<!-- </div>
</ng-template> -->
<ng-template #institutionsTmp let-project>
@let institutions = getProjectInstitutions(project);
<div
class="institution-tags"
aria-label="Institutionen"
style="padding: 0.5rem 0">
@for (
institution of isProjectInstitutionsExpanded(project)
? institutions
: institutions.slice(0, 3);
track getProjectInstitutionId(institution)
) {
<button
type="button"
class="publication-institution-tag"
[class.active]="isInstitutionActive(institution.id!)"
[matTooltip]="getInstitutionTooltipText(institution)"
matTooltipPosition="above"
[attr.aria-label]="getInstitutionTooltipText(institution)"
(click)="filterByInstitution(institution)">
<mat-icon class="institution-icon">apartment</mat-icon>
<span class="institution-name">{{
institution.institute_name_de || institution.institute_name_en
}}</span>
</button>
} @empty {
<span class="empty-text">-</span>
}
@if (institutions.length > 3) {
<button
type="button"
class="publication-institution-more"
(click)="toggleProjectInstitutionsExpansion(project)">
@if (isProjectInstitutionsExpanded(project)) {
Weniger anzeigen
} @else {
+{{ institutions.length - 3 }} weitere
}
</button>
}
</div>
</ng-template>
<ng-template #topicsTmp let-project>
@let projectTopics = project.topics ?? [];
@let isTopicsExpanded = isProjectTopicsExpanded(project);
@let visibleTopics =
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
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>
} @empty {
<span class="empty-text">-</span>
}
@if (projectTopics.length > 3) {
<button
type="button"
class="publication-institution-more"
[attr.aria-expanded]="isTopicsExpanded"
(click)="toggleProjectTopicsExpansion(project)">
{{ isTopicsExpanded ? 'weniger' : '+' + (projectTopics.length - 3) }}
</button>
}
</div>
</ng-template>
@@ -0,0 +1,220 @@
.page {
padding: 28px 32px 42px;
max-width: 100%;
margin: 0 auto;
}
// ------------------------
// Shared tags & chips
// ------------------------
.publication-institution-tag {
display: inline-flex;
align-items: center;
padding: 2px 6px;
border: 1px solid var(--sg-primary-border, var(--sg-border));
border-radius: 4px;
background: var(--sg-primary-soft);
color: var(--sg-primary);
font-size: 10px;
font-weight: 600;
line-height: normal;
max-width: 100%;
margin: 0;
font-family: inherit;
cursor: pointer;
transition: all 0.2s ease;
&:hover,
&:focus-visible {
background: var(--sg-primary);
color: #fff;
border-color: var(--sg-primary);
outline: none;
box-shadow:
0 0 0 2px var(--sg-background),
0 0 0 4px var(--sg-primary);
}
&.active {
border-color: var(--sg-primary);
box-shadow:
0 0 0 1px #ffffff,
0 0 0 3px var(--sg-primary);
}
&.active:hover,
&.active:focus-visible {
background: var(--sg-primary);
color: #fff;
}
.institution-icon {
flex-shrink: 0;
width: 12px;
height: 12px;
margin-right: 4px;
font-size: 12px;
}
.institution-name {
display: -webkit-box;
-webkit-line-clamp: 2;
-webkit-box-orient: vertical;
overflow: hidden;
min-width: 0;
white-space: normal;
overflow-wrap: anywhere;
}
.flag-img {
flex-shrink: 0;
margin-left: 6px;
border: 1px solid;
}
.country-code {
flex-shrink: 0;
margin-left: 2px;
font-size: 9px;
}
.institution-open-icon {
flex-shrink: 0;
width: 12px;
height: 12px;
margin-left: 5px;
font-size: 12px;
line-height: 1;
cursor: pointer;
opacity: 0;
transition: opacity 0.15s ease;
}
&:hover .institution-open-icon {
opacity: 0.7;
}
.institution-open-icon:hover {
opacity: 1;
}
}
.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;
}
}
// ------------------------
// Containers for chips
// ------------------------
.topic-chips,
.institution-tags,
.author-tags {
display: flex;
flex-wrap: wrap;
gap: 6px;
}
.topic-chips {
max-width: 320px;
}
.institution-tags {
align-items: flex-start;
max-width: 280px;
}
.author-tags {
align-items: flex-start;
max-width: 280px;
padding: 0.5rem 0;
}
// ------------------------
// Empty text
// ------------------------
.empty-text {
color: rgba(0, 0, 0, 0.54);
}
// ------------------------
// Classification container
// ------------------------
.classification-container {
max-width: 200px;
}
// ------------------------
// Data table overrides (applied via ::ng-deep)
// ------------------------
::ng-deep {
.mat-mdc-header-cell {
color: var(--sg-text-muted);
font-size: 12px;
font-weight: 700;
}
.mat-mdc-row {
height: 86px;
}
.mat-mdc-cell {
color: var(--sg-text);
border-bottom-color: var(--sg-border);
font-size: 13px;
}
.table-wrap {
.mat-column-type,
.mat-column-year,
.mat-column-language,
.mat-column-citations,
.mat-mdc-header-cell {
text-align: center;
}
.mat-mdc-cell:not(:last-child),
.mat-mdc-header-cell:not(:last-child) {
border-right: 1px solid var(--sg-border);
}
.mat-column-institutions,
.mat-column-topics {
overflow: visible;
}
}
}
// ------------------------
// Responsive adjustments
// ------------------------
@media (max-width: 600px) {
.page {
padding: 16px;
}
}
@@ -0,0 +1,369 @@
import {
Component,
computed,
input,
OnInit,
TemplateRef,
viewChild,
inject,
} from '@angular/core';
import {
BundProjectPage,
DfgProjectPage,
DfgProjectSummary,
Topic,
} from '../../../api';
import { BundProjectSummary } from '../../../api/model/bundProjectSummary';
import { TopicChipComponent } from '../topic-chip/topic-chip.component';
import {
DataTableComponent,
GenericColumn,
} from '../data-table/data-table.component';
import { RouterModule } from '@angular/router';
import { MatIconModule } from '@angular/material/icon';
import { MatButtonModule } from '@angular/material/button';
import { QueryParamPaginatorComponent } from '../query-param-paginator/query-param-paginator.component';
import { dfgProjectQueryParamKeys } from '../../../resolvers/dfg-projects.resolver';
import { toSignal } from '@angular/core/rxjs-interop';
import { ActivatedRoute, Router } from '@angular/router';
import { DfgPersonSummary } from '../../../api/model/dfgPersonSummary';
import { MatTooltip } from '@angular/material/tooltip';
import { topicHierarchyColor } from '../../../resolvers/utils/topic-colors';
@Component({
selector: 'app-bund-project-table',
imports: [
DataTableComponent,
RouterModule,
MatIconModule,
MatButtonModule,
QueryParamPaginatorComponent,
MatTooltip,
TopicChipComponent,
],
templateUrl: './bund-project-table.component.html',
styleUrl: './bund-project-table.component.scss',
})
export class BundProjectTableComponent implements OnInit {
private readonly activatedRoute = inject(ActivatedRoute);
private readonly router = inject(Router);
page = input.required<BundProjectPage>();
authorFilterEnabled = input<boolean>(false);
institutionFilterEnabled = input<boolean>(false);
topicFilterEnabled = input<boolean>(false);
elements = computed(() => this.page().elements ?? []);
queryParamMap = toSignal(this.activatedRoute.queryParamMap, {
initialValue: this.activatedRoute.snapshot.queryParamMap,
});
queryParamKeys = dfgProjectQueryParamKeys;
total = computed(() => this.page().total ?? 0);
columns: GenericColumn<BundProjectSummary>[] = [];
titleTmp = viewChild.required<TemplateRef<any>>('titleTmp');
authorsTmp = viewChild.required<TemplateRef<any>>('authorsTmp');
institutionsTmp = viewChild.required<TemplateRef<any>>('institutionsTmp');
fundingStartTmp = viewChild.required<TemplateRef<any>>('fundingStartTmp');
fundingEndTmp = viewChild.required<TemplateRef<any>>('fundingEndTmp');
actionsTmp = viewChild.required<TemplateRef<any>>('actionsTmp');
detailRowTmp = viewChild.required<TemplateRef<any>>('detailRowTmp');
topicsTmp = viewChild.required<TemplateRef<any>>('topicsTmp');
expandedProjectAuthorsId: string[] = [];
expandedProjectInstitutionsId: string[] = [];
expandedProjectTopicsId: string[] = [];
selectedFundingStartYearsQueryParams = computed(() => {
return this.queryParamMap()
.getAll(this.queryParamKeys.funding_start)
.map(Number);
});
selectedFundingEndYearsQueryParams = computed(() => {
return this.queryParamMap()
.getAll(this.queryParamKeys.funding_end)
.map(Number);
});
selectedAuthorIdsQueryParams = computed(() => {
return this.queryParamMap().getAll(this.queryParamKeys.authorId);
});
selectedInstitutionIdsQueryParams = computed(() => {
return this.queryParamMap().getAll(this.queryParamKeys.institutionId);
});
selectedTopicIdsQueryParams = computed(() => {
return this.queryParamMap().getAll(this.queryParamKeys.topicId);
});
ngOnInit(): void {
this.columns = [
{ id: 'title', header: 'Titel', type: 'accessor', accessorKey: 'topic' },
{
id: 'funding_start',
header: 'Förderbeginn',
type: 'accessor',
accessorKey: 'funding_start',
},
{
id: 'funding_end',
header: 'Förderende',
type: 'accessor',
accessorKey: 'funding_end',
cellTemplate: this.fundingEndTmp(),
},
// {
// id: 'names',
// header: 'Autoren',
// type: 'accessor',
// accessorKey: 'names',
// cellTemplate: this.authorsTmp(),
// },
{
id: 'institutions',
header: 'Institutionen',
type: 'display',
cellTemplate: this.institutionsTmp(),
},
{
id: 'professional_classification',
header: 'Fachliche Zuordnung',
type: 'display',
cellTemplate: this.detailRowTmp(),
},
{
id: 'topics',
header: 'Themen',
type: 'display',
cellTemplate: this.topicsTmp(),
},
{
id: 'actions',
header: '',
type: 'display',
cellTemplate: this.actionsTmp(),
},
];
}
sortNames(names: string[] | undefined): string[] {
return [...(names ?? [])].sort((a, b) => a.localeCompare(b));
}
isAuthorActive(authorId: number): boolean {
return (
!!authorId &&
this.authorFilterEnabled() &&
this.selectedAuthorIdsQueryParams().includes(String(authorId))
);
}
// getProjectAuthors(project: DfgProjectSummary): DfgPersonSummary[] {
// return project.persons?.filter((a): a is DfgPersonSummary => !!a) || [];
// }
// toggleProjectAuthorsExpansion(project: DfgProjectSummary): void {
// if (!project.id) return;
// if (this.expandedProjectAuthorsId.includes(project.id)) {
// this.expandedProjectAuthorsId = this.expandedProjectAuthorsId.filter(
// (id) => id !== project.id,
// );
// } else {
// this.expandedProjectAuthorsId.push(project.id);
// }
// }
isProjectPersonsExpanded(project: DfgProjectSummary): boolean {
if (!project.id) return false;
return this.expandedProjectAuthorsId.includes(project.id);
}
// getAuthorTooltipText(author: DfgPersonSummary): string {
// if (this.authorFilterEnabled() && author.person_id) {
// return `Nach Autor filtern: ${author.full_name}`;
// }
// return `Autor: ${author.full_name}`;
// }
// filterByAuthor(authorId: number): void {
// if (!authorId || !this.authorFilterEnabled()) return;
// const selectedAuthorIds = this.selectedAuthorIdsQueryParams();
// if (selectedAuthorIds.includes(String(authorId))) {
// this.router.navigate([], {
// queryParams: {
// [this.queryParamKeys.authorId]: selectedAuthorIds.filter(
// (id) => id !== String(authorId),
// ),
// [this.queryParamKeys.page]: 0,
// },
// queryParamsHandling: 'merge',
// });
// } else {
// this.router.navigate([], {
// queryParams: {
// [this.queryParamKeys.authorId]: [
// ...selectedAuthorIds,
// String(authorId),
// ],
// [this.queryParamKeys.page]: 0,
// },
// queryParamsHandling: 'merge',
// });
// }
// }
isProjectInstitutionsExpanded(project: DfgProjectSummary): boolean {
if (!project.id) return false;
return this.expandedProjectInstitutionsId.includes(project.id);
}
toggleProjectInstitutionsExpansion(project: DfgProjectSummary): void {
if (!project.id) return;
if (this.expandedProjectInstitutionsId.includes(project.id)) {
this.expandedProjectInstitutionsId =
this.expandedProjectInstitutionsId.filter((id) => id !== project.id);
} else {
this.expandedProjectInstitutionsId.push(project.id);
}
}
getProjectInstitutions(project: DfgProjectSummary): any[] {
const institutions = new Map<string, any>();
for (const institution of project.institutions ?? []) {
const id = this.getProjectInstitutionId(institution);
if (!id) continue;
institutions.set(id, institution);
}
return Array.from(institutions.values()).sort((a, b) =>
this.getProjectInstitutionName(a).localeCompare(
this.getProjectInstitutionName(b),
),
);
}
getProjectInstitutionId(institution: any): string | null {
const id = institution.id;
return id == null ? null : String(id);
}
getProjectInstitutionName(institution: any): string {
return institution.institute_name_de ?? institution.institute_name_en;
}
isInstitutionActive(
institutionId: string | number | null | undefined,
): boolean {
return (
!!institutionId &&
this.institutionFilterEnabled() &&
this.selectedInstitutionIdsQueryParams().includes(String(institutionId))
);
}
filterByInstitution(institution: any): void {
const institutionId = this.getProjectInstitutionId(institution);
if (!institutionId || !this.institutionFilterEnabled()) return;
const selectedInstitutionIds = this.selectedInstitutionIdsQueryParams();
if (selectedInstitutionIds.includes(institutionId)) {
this.router.navigate([], {
queryParams: {
[this.queryParamKeys.institutionId]: selectedInstitutionIds.filter(
(id) => id !== institutionId,
),
[this.queryParamKeys.page]: 0,
},
queryParamsHandling: 'merge',
});
} else {
this.router.navigate([], {
queryParams: {
[this.queryParamKeys.institutionId]: [
...selectedInstitutionIds,
institutionId,
],
[this.queryParamKeys.page]: 0,
},
queryParamsHandling: 'merge',
});
}
}
getInstitutionTooltipText(institution: any): string {
const name = this.getProjectInstitutionName(institution);
if (this.institutionFilterEnabled()) {
return `Nach Institution filtern: ${name}`;
}
return `Institution: ${name}`;
}
getWorkTopicColor(topic: Topic): string {
return topicHierarchyColor({
id: topic.id,
name: topic.display_name,
field_id: topic.field?.id,
field_name: topic.field?.display_name,
domain_id: topic.domain?.id,
domain_name: topic.domain?.display_name,
});
}
isTopicActive(topic: Topic): boolean {
return (
!!topic.id &&
this.authorFilterEnabled() &&
this.selectedTopicIdsQueryParams().includes(topic.id)
);
}
filterByTopic(topic: Topic): void {
if (!topic.id || !this.topicFilterEnabled()) return;
const selectedTopicIds = this.selectedTopicIdsQueryParams();
if (selectedTopicIds.includes(topic.id)) {
this.router.navigate([], {
queryParams: {
[this.queryParamKeys.topicId]: selectedTopicIds.filter(
(id) => id !== topic.id,
),
[this.queryParamKeys.page]: 0,
},
queryParamsHandling: 'merge',
});
} else {
this.router.navigate([], {
queryParams: {
[this.queryParamKeys.topicId]: [...selectedTopicIds, topic.id],
[this.queryParamKeys.page]: 0,
},
queryParamsHandling: 'merge',
});
}
}
toggleProjectTopicsExpansion(project: DfgProjectSummary): void {
if (!project.id) return;
if (this.expandedProjectTopicsId.includes(project.id)) {
this.expandedProjectTopicsId = this.expandedProjectTopicsId.filter(
(id) => id !== project.id,
);
} else {
this.expandedProjectTopicsId.push(project.id);
}
}
isProjectTopicsExpanded(project: DfgProjectSummary): boolean {
if (!project.id) return false;
return this.expandedProjectTopicsId.includes(project.id);
}
}
@@ -0,0 +1,19 @@
<div>
<app-project-filters
filterMode="bund"
[queryParamKeys]="bundQueryParamKeys"
[selectedBundInstitutionsPage]="selectedBundInstitutionsPage()"
[selectedTopicsPage]="selectedTopicsPage()"
[showFundingStartFilter]="true"
[showTopicFilter]="topicFilterEnabled()"
[showFundingEndFilter]="true"
[showAuthorFilter]="true"
[showInstitutionFilter]="true"
[showEuProjectTypeFilter]="false" />
<app-bund-project-table
[page]="bundProjectPage()"
[authorFilterEnabled]="true"
[topicFilterEnabled]="topicFilterEnabled()"
[institutionFilterEnabled]="true" />
</div>
@@ -0,0 +1,53 @@
import { Component, computed, input } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { toSignal } from '@angular/core/rxjs-interop';
import {
BundProjectPage,
DfgPersonSummaryPage,
TopicPageV2,
} from '../../../api';
import { DfgInstitutionSummaryPage } from '../../../api/model/dfgInstitutionSummaryPage';
import { MatCardModule } from '@angular/material/card';
import { MatTabsModule } from '@angular/material/tabs';
import { ProjectFilterComponent } from '../project-filters/project-filters.component';
import { BundProjectTableComponent } from '../bund-project-table/bund-project-table.component';
import { bundProjectQueryParamKeys } from '../../../resolvers/bund-projects.resolver';
@Component({
selector: 'app-bund-projects',
imports: [
MatCardModule,
MatTabsModule,
ProjectFilterComponent,
BundProjectTableComponent,
],
templateUrl: './bund-projects.component.html',
styleUrl: './bund-projects.component.scss',
})
export class BundProjectsComponent {
bundProjectPage = input.required<BundProjectPage>();
selectedBundInstitutionsPage = input.required<DfgInstitutionSummaryPage>();
selectedBundAuthorsPage = input.required<DfgPersonSummaryPage>();
selectedTopicsPage = input.required<TopicPageV2>();
readonly bundQueryParamKeys = bundProjectQueryParamKeys;
constructor(
private readonly router: Router,
private readonly activatedRoute: ActivatedRoute,
) {
console.log('BundProjectsComponent created');
}
ngOnInit(): void {
console.log('BUND PROJECTS', this.bundProjectPage());
}
queryParamMap = toSignal(this.activatedRoute.queryParamMap, {
initialValue: this.activatedRoute.snapshot.queryParamMap,
});
readonly topicFilterEnabled = computed(
() =>
this.queryParamMap().get('fuzzy') === 'true' ||
this.queryParamMap().get('fuzzy') === null,
);
}
@@ -48,7 +48,7 @@
@let visibleAuthors =
isProjectAuthorsExpanded ? projectAuthors : projectAuthors.slice(0, 3);
<div class="author-tags" aria-label="Autoren" style="padding: 0.5rem 0">
@for (author of visibleAuthors; track author.person_id) {
@for (author of visibleAuthors; track author.person_id + $index) {
<button
type="button"
class="publication-institution-tag"
@@ -17,7 +17,7 @@ import { RouterModule } from '@angular/router';
import { MatIconModule } from '@angular/material/icon';
import { MatButtonModule } from '@angular/material/button';
import { QueryParamPaginatorComponent } from '../query-param-paginator/query-param-paginator.component';
import { projectQueryParamKeys } from '../../../resolvers/dfg-projects.resolver';
import { dfgProjectQueryParamKeys } from '../../../resolvers/dfg-projects.resolver';
import { toSignal } from '@angular/core/rxjs-interop';
import { ActivatedRoute, Router } from '@angular/router';
import { DfgPersonSummary } from '../../../api/model/dfgPersonSummary';
@@ -52,7 +52,7 @@ export class DfgProjectTableComponent implements OnInit {
initialValue: this.activatedRoute.snapshot.queryParamMap,
});
queryParamKeys = projectQueryParamKeys;
queryParamKeys = dfgProjectQueryParamKeys;
total = computed(() => this.page().total ?? 0);
columns: GenericColumn<DfgProjectSummary>[] = [];
@@ -6,7 +6,7 @@
[selectedDfgAuthorsPage]="selectedDfgAuthorsPage()"
[selectedTopicsPage]="selectedTopicsPage()"
[showFundingStartFilter]="true"
[showTopicFilter]="fuzzySearch()"
[showTopicFilter]="topicFilterEnabled()"
[showFundingEndFilter]="true"
[showAuthorFilter]="true"
[showInstitutionFilter]="true"
@@ -15,6 +15,6 @@
<app-dfg-project-table
[page]="dfgProjectPage()"
[authorFilterEnabled]="true"
[topicFilterEnabled]="fuzzySearch()"
[topicFilterEnabled]="topicFilterEnabled()"
[institutionFilterEnabled]="true" />
</div>
@@ -8,7 +8,7 @@ import { MatCardModule } from '@angular/material/card';
import { MatTabsModule } from '@angular/material/tabs';
import { ProjectFilterComponent } from '../project-filters/project-filters.component';
import { DfgProjectTableComponent } from '../dfg-project-table/dfg-project-table.component';
import { projectQueryParamKeys } from '../../../resolvers/dfg-projects.resolver';
import { dfgProjectQueryParamKeys } from '../../../resolvers/dfg-projects.resolver';
@Component({
selector: 'app-dfg-projects',
@@ -29,7 +29,7 @@ export class DfgProjectsComponent {
selectedTopicsPage = input.required<TopicPageV2>();
readonly dfgQueryParamKeys = projectQueryParamKeys;
readonly dfgQueryParamKeys = dfgProjectQueryParamKeys;
constructor(
private readonly router: Router,
@@ -41,7 +41,10 @@ export class DfgProjectsComponent {
queryParamMap = toSignal(this.activatedRoute.queryParamMap, {
initialValue: this.activatedRoute.snapshot.queryParamMap,
});
readonly fuzzySearch = computed(
() => this.queryParamMap().get('fuzzy') === 'true',
readonly topicFilterEnabled = computed(
() =>
// fuz
this.queryParamMap().get('fuzzy') === 'true' ||
this.queryParamMap().get('fuzzy') === null,
);
}
@@ -5,7 +5,7 @@
[selectedEuAuthorsPage]="selectedEuAuthorsPage()"
[selectedTopicsPage]="selectedTopicsPage()"
[showFundingStartFilter]="true"
[showTopicFilter]="fuzzySearch()"
[showTopicFilter]="topicFilterEnabled()"
[showFundingEndFilter]="true"
[showAuthorFilter]="true"
[showInstitutionFilter]="true"
@@ -14,5 +14,5 @@
<app-eu-project-table
[page]="euCordisProjectPage()"
[authorFilterEnabled]="true"
[topicFilterEnabled]="fuzzySearch()"
[topicFilterEnabled]="topicFilterEnabled()"
[institutionFilterEnabled]="true" />
@@ -39,7 +39,9 @@ export class EuProjectsComponent implements OnInit {
initialValue: this.activatedRoute.snapshot.queryParamMap,
});
readonly fuzzySearch = computed(
() => this.queryParamMap().get('fuzzy') === 'true',
readonly topicFilterEnabled = computed(
() =>
this.queryParamMap().get('fuzzy') === 'true' ||
this.queryParamMap().get('fuzzy') === null,
);
}
@@ -69,25 +69,19 @@
[selectedTopics]="selectedTopics()"
(handleTopicSelectChange)="handleTopicSelectChange($event)" />
}
<button mat-stroked-button color="primary" (click)="resetFilters()">
<mat-icon>filter_alt_off</mat-icon>
Filter zurücksetzen
</button>
</div>
<app-selected-filters [observers]="observers()" />
@if (topicLegendGroups.length > 0) {
<app-topic-legend
[groups]="topicLegendGroups"
[visible]="subfieldLegendVisible()"
[expanded]="subfieldLegendExpanded()"
[collapsedGroupLimit]="3"
variant="default"
(visibleChange)="handleLegendVisibleChange($event)"
(expandedChange)="handleLegendExpandedChange($event)">
</app-topic-legend>
}
</div>
@if (topicLegendGroups.length > 0) {
<app-topic-legend
[groups]="topicLegendGroups"
[visible]="subfieldLegendVisible()"
[expanded]="subfieldLegendExpanded()"
[collapsedGroupLimit]="3"
variant="default"
(visibleChange)="handleLegendVisibleChange($event)"
(expandedChange)="handleLegendExpandedChange($event)">
</app-topic-legend>
}
</div>
@@ -45,15 +45,17 @@ import {
SelectedFiltersComponent,
} from '../selected-filters/selected-filters.component';
import { projectQueryParamKeys } from '../../../resolvers/dfg-projects.resolver';
import { dfgProjectQueryParamKeys } from '../../../resolvers/dfg-projects.resolver';
import { euProjectQueryParamKeys } from '../../../resolvers/eu-cordis-projects.resolver';
import { SearchableAuthorSelectComponent } from '../searchable-author-select/searchable-author-select.component';
import { bundProjectQueryParamKeys } from '../../../resolvers/bund-projects.resolver';
type ProjectFilterMode = 'dfg' | 'eu';
type ProjectFilterMode = 'dfg' | 'eu' | 'bund';
type ProjectQueryParamKeys =
| typeof projectQueryParamKeys
| typeof euProjectQueryParamKeys;
| typeof dfgProjectQueryParamKeys
| typeof euProjectQueryParamKeys
| typeof bundProjectQueryParamKeys;
@Component({
selector: 'app-project-filters',
@@ -81,11 +83,11 @@ export class ProjectFilterComponent {
filterMode = input<ProjectFilterMode>('dfg');
queryParamKeys = input<ProjectQueryParamKeys>(projectQueryParamKeys);
queryParamKeys = input<ProjectQueryParamKeys>(dfgProjectQueryParamKeys);
selectedDfgInstitutionsPage = input<DfgInstitutionSummaryPage>();
selectedEuInstitutionsPage = input<EuCordisOrganizationSelectorPage>();
selectedBundInstitutionsPage = input<DfgInstitutionSummaryPage>();
selectedDfgAuthorsPage = input<DfgPersonSummaryPage>();
selectedEuAuthorsPage = input<AuthorPage>();
@@ -532,36 +534,6 @@ export class ProjectFilterComponent {
});
};
resetFilters = (): void => {
const keys = this.queryParamKeys();
const resetQueryParams: Record<string, unknown> = {
[keys.title]: null,
[keys.institutionId]: null,
[keys.authorId]: null,
[keys.funding_start]: null,
[keys.funding_end]: null,
[keys.topicId]: null,
[keys.legend]: null,
[keys.legend_expanded]: null,
[keys.page]: 0,
};
if (this.filterMode() === 'eu') {
const euKeys = keys as typeof euProjectQueryParamKeys;
resetQueryParams[euKeys.projectType] = null;
resetQueryParams[euKeys.country] = null;
resetQueryParams[euKeys.frameworkProgramme] = null;
resetQueryParams[euKeys.fundingScheme] = null;
resetQueryParams[euKeys.status] = null;
}
this.router.navigate([], {
queryParams: resetQueryParams,
queryParamsHandling: 'merge',
});
};
get topicLegendGroups(): TopicLegendGroup[] {
const topics = this.selectedTopics().map((topic) =>
this.toTopicLegendTopic(topic),
@@ -45,10 +45,6 @@
[selectedTopics]="selectedTopics()"
(handleTopicSelectChange)="handleTopicSelectChange($event)" />
}
<button mat-stroked-button color="primary" (click)="resetFilters()">
<mat-icon>filter_alt_off</mat-icon>
Filter zurücksetzen
</button>
</div>
<app-selected-filters [observers]="observers" />
</div>
@@ -363,19 +363,4 @@ export class PublicationFilterComponent {
});
}
};
resetFilters = (): void => {
this.router.navigate([], {
queryParams: {
[workQueryParamKeys.title]: null,
[workQueryParamKeys.years]: null,
[workQueryParamKeys.types]: null,
[workQueryParamKeys.language]: null,
[workQueryParamKeys.authorId]: null,
[workQueryParamKeys.institutionId]: null,
[workQueryParamKeys.topicId]: null,
},
queryParamsHandling: 'merge',
});
};
}
@@ -36,5 +36,11 @@
}
}
</div>
<button
class="clear-all-btn"
aria-label="Alle Filter zurücksetzen"
(click)="removeAllFilters()">
Alle Filter zurücksetzen
</button>
</div>
}
@@ -9,6 +9,15 @@
background: var(--sg-surface);
font-size: 13px;
}
.clear-all-btn {
font-size: 11px;
font-weight: 600;
color: var(--sg-warning);
text-decoration: underline;
border: none;
background: transparent;
cursor: pointer;
}
@media (max-width: 600px) {
.active-filters-row {
@@ -88,4 +88,16 @@ export class SelectedFiltersComponent {
queryParamsHandling: 'merge',
});
}
removeAllFilters() {
const queryParams: { [key: string]: null } = {};
this.observedQueryParamKeys().forEach((key) => {
queryParams[key] = null;
});
this.router.navigate([], {
relativeTo: this.activatedRoute,
queryParams,
queryParamsHandling: 'merge',
});
}
}