diff --git a/service/src/main/inse/main.py b/service/src/main/inse/main.py index bb55e148..65f076d7 100644 --- a/service/src/main/inse/main.py +++ b/service/src/main/inse/main.py @@ -61,6 +61,9 @@ from inse.topics.v2.router import router as topics_v2_router from inse.projects.dfg_institutions.router import router as dfg_institutions_router from inse.projects.dfg_persons.router import router as dfg_persons_router + +from inse.projects.eu_organizations.router import router as eu_organizations_router + logger = logging.getLogger(__name__) ### startup @@ -120,6 +123,7 @@ app.include_router(dfg_institutions_router) app.include_router(dfg_persons_router) app.include_router(bookmarks_router) +app.include_router(eu_organizations_router) app.add_middleware( ETagCacheMiddleware, ttl=120, # 2 minutes expiration time diff --git a/service/src/main/inse/projects/eu_cordis_projects_client.py b/service/src/main/inse/projects/eu_cordis_projects_client.py new file mode 100644 index 00000000..8efd3813 --- /dev/null +++ b/service/src/main/inse/projects/eu_cordis_projects_client.py @@ -0,0 +1,1027 @@ +import logging +import asyncio +from typing import Any, Dict, List, Optional, Union, Tuple, Set +from collections import defaultdict +from inse.config import get_settings +from inse.integrations import elasticsearch +from inse.model import ESCluster, ESIndex +from inse.authors.v2.model import AuthorPage +from inse.authors.v2.service import get_authors_by_ids +# Import base models +from inse.models.cordis_eu_project import CordisEuProject + +# Import FP7 models +from inse.models.projects_eu_cordis.fp7.fp7_project import Fp7Project +from inse.models.projects_eu_cordis.fp7.fp7_organization import Fp7Organization +from inse.models.projects_eu_cordis.fp7.fp7_publication import Fp7Publication +from inse.models.projects_eu_cordis.fp7.fp7_project_ipr import Fp7ProjectIPR +from inse.models.projects_eu_cordis.fp7.fp7_report_summary import Fp7ReportSummary +from inse.models.projects_eu_cordis.fp7.fp7_topic import Fp7Topic +from inse.models.projects_eu_cordis.fp7.fp7_web_link import Fp7WebLink +from inse.models.projects_eu_cordis.fp7.fp7_eurosci_voc import Fp7EurosciVoc +from inse.models.projects_eu_cordis.fp7.fp7_legal_basis import Fp7LegalBasis +from inse.models.projects_eu_cordis.fp7.fp7_project_details import Fp7ProjectDetails + +# Import H2020 models +from inse.models.projects_eu_cordis.horizon2020.h2020_project import H2020Project +from inse.models.projects_eu_cordis.horizon2020.h2020_organization import H2020Organization +from inse.models.projects_eu_cordis.horizon2020.h2020_publication import H2020Publication +from inse.models.projects_eu_cordis.horizon2020.h2020_deliverable import H2020Deliverable +from inse.models.projects_eu_cordis.horizon2020.h2020_report_summary import H2020ReportSummary +from inse.models.projects_eu_cordis.horizon2020.h2020_topic import H2020Topic +from inse.models.projects_eu_cordis.horizon2020.h2020_web_link import H2020WebLink +from inse.models.projects_eu_cordis.horizon2020.h2020_eurosci_voc import H2020EurosciVoc +from inse.models.projects_eu_cordis.horizon2020.h2020_legal_basis import H2020LegalBasis +from inse.models.projects_eu_cordis.horizon2020.h2020_erc_pi import H2020ErcPI +from inse.models.projects_eu_cordis.horizon2020.h2020_project_details import H2020ProjectDetails + +# Import Horizon Europe models +from inse.models.projects_eu_cordis.horizon_europe.heu_project import HEUProject +from inse.models.projects_eu_cordis.horizon_europe.heu_organization import HEUOrganization +from inse.models.projects_eu_cordis.horizon_europe.heu_publication import HEUPublication +from inse.models.projects_eu_cordis.horizon_europe.heu_deliverable import HEUDeliverable +from inse.models.projects_eu_cordis.horizon_europe.heu_report_summary import HEUReportSummary +from inse.models.projects_eu_cordis.horizon_europe.heu_topic import HEUTopic +from inse.models.projects_eu_cordis.horizon_europe.heu_web_link import HEUWebLink +from inse.models.projects_eu_cordis.horizon_europe.heu_eurosci_voc import HEUEurosciVoc +from inse.models.projects_eu_cordis.horizon_europe.heu_legal_basis import HEULegalBasis +from inse.models.projects_eu_cordis.horizon_europe.heu_project_details import HEUProjectDetails + +settings = get_settings() +logger = logging.getLogger(__name__) +logger.setLevel(settings.logging_level) + +# Entity config +_FP7_ENTITY_CONFIGS = [ + {"key": "organizations", "index_pattern": ESIndex.CORDIS_EU_FP7_ORGANIZATIONS, "model_class": Fp7Organization}, + {"key": "publications", "index_pattern": ESIndex.CORDIS_EU_FP7_PUBLICATIONS, "model_class": Fp7Publication}, + {"key": "iprs", "index_pattern": ESIndex.CORDIS_EU_FP7_PROJECT_IPRS, "model_class": Fp7ProjectIPR}, + {"key": "report_summaries", "index_pattern": ESIndex.CORDIS_EU_FP7_REPORT_SUMMARIES, "model_class": Fp7ReportSummary}, + {"key": "topics_list", "index_pattern": ESIndex.CORDIS_EU_FP7_TOPICS, "model_class": Fp7Topic}, + {"key": "web_links", "index_pattern": ESIndex.CORDIS_EU_FP7_WEB_LINKS, "model_class": Fp7WebLink}, + {"key": "eurosci_voc", "index_pattern": ESIndex.CORDIS_EU_FP7_EUROSCIVOC, "model_class": Fp7EurosciVoc}, + {"key": "legal_basis_list", "index_pattern": ESIndex.CORDIS_EU_FP7_LEGAL_BASIS, "model_class": Fp7LegalBasis}, +] + +_H2020_ENTITY_CONFIGS = [ + {"key": "organizations", "index_pattern": ESIndex.CORDIS_EU_HORIZON_2020_ORGANIZATIONS, "model_class": H2020Organization}, + {"key": "publications", "index_pattern": ESIndex.CORDIS_EU_HORIZON_2020_PUBLICATIONS, "model_class": H2020Publication}, + {"key": "deliverables", "index_pattern": ESIndex.CORDIS_EU_HORIZON_2020_DELIVERABLES, "model_class": H2020Deliverable}, + {"key": "report_summaries", "index_pattern": ESIndex.CORDIS_EU_HORIZON_2020_REPORT_SUMMARIES, "model_class": H2020ReportSummary}, + {"key": "topics_list", "index_pattern": ESIndex.CORDIS_EU_HORIZON_2020_TOPICS, "model_class": H2020Topic}, + {"key": "web_links", "index_pattern": ESIndex.CORDIS_EU_HORIZON_2020_WEB_LINKS, "model_class": H2020WebLink}, + {"key": "eurosci_voc", "index_pattern": ESIndex.CORDIS_EU_HORIZON_2020_EUROSCIVOC, "model_class": H2020EurosciVoc}, + {"key": "legal_basis_list", "index_pattern": ESIndex.CORDIS_EU_HORIZON_2020_LEGAL_BASIS, "model_class": H2020LegalBasis}, + {"key": "erc_principal_investigators", "index_pattern": ESIndex.CORDIS_EU_HORIZON_2020_ERC_PIS, "model_class": H2020ErcPI}, +] + +_HEU_ENTITY_CONFIGS = [ + {"key": "organizations", "index_pattern": ESIndex.CORDIS_EU_HORIZON_EUROPE_ORGANIZATIONS, "model_class": HEUOrganization}, + {"key": "publications", "index_pattern": ESIndex.CORDIS_EU_HORIZON_EUROPE_PUBLICATIONS, "model_class": HEUPublication}, + {"key": "deliverables", "index_pattern": ESIndex.CORDIS_EU_HORIZON_EUROPE_DELIVERABLES, "model_class": HEUDeliverable}, + {"key": "report_summaries", "index_pattern": ESIndex.CORDIS_EU_HORIZON_EUROPE_REPORT_SUMMARIES, "model_class": HEUReportSummary}, + {"key": "topics_list", "index_pattern": ESIndex.CORDIS_EU_HORIZON_EUROPE_TOPICS, "model_class": HEUTopic}, + {"key": "web_links", "index_pattern": ESIndex.CORDIS_EU_HORIZON_EUROPE_WEB_LINKS, "model_class": HEUWebLink}, + {"key": "eurosci_voc", "index_pattern": ESIndex.CORDIS_EU_HORIZON_EUROPE_EUROSCIVOC, "model_class": HEUEurosciVoc}, + {"key": "legal_basis_list", "index_pattern": ESIndex.CORDIS_EU_HORIZON_EUROPE_LEGAL_BASIS, "model_class": HEULegalBasis}, +] + +async def get_enriched_cordis_project_by_id( + project_id: str, +) -> Optional[Union[Fp7ProjectDetails, H2020ProjectDetails, HEUProjectDetails]]: + """ + Fetches and enriches a single Cordis EU project by its ID across all programme types. + + Args: + project_id: The project ID to fetch. + + Returns: + The enriched detailed project model, or None if not found. + """ + if not project_id: + return None + + query = {"bool": {"filter": [{"term": {"id": project_id}}]}} + + response = await elasticsearch.search( + query=query, + index=ESIndex.CORDIS_EU_PROJECTS_WILDCARD, + cluster=ESCluster.INSE, + size=1, + ) + + hits = response.get("hits", {}).get("hits", []) + if not hits: + logger.info(f"No project found with ID: {project_id}") + return None + + hit = hits[0] + index = hit.get("_index", "") + source = hit.get("_source", {}) + + program_type = _determine_program_type_from_index(index) + + enrichers = { + "fp7": _enrich_fp7_project, + "h2020": _enrich_h2020_project, + "heu": _enrich_heu_project, + } + + enricher = enrichers.get(program_type) + if enricher is None: + logger.warning(f"Unknown programme type for index: {index}") + return CordisEuProject.model_validate(source) + + return await enricher(project_id, source) + +# helpers +def _determine_program_type_from_index(index: str) -> str: + """Determines the programme type from the Elasticsearch index name.""" + index_lower = index.lower() + if "fp7" in index_lower: + return "fp7" + if "horizon_2020" in index_lower: + return "h2020" + if "heu" in index_lower or "horizon_europe" in index_lower: + return "heu" + return "unknown" + + +async def _fetch_related_entities_parallel( + project_id: str, + entity_configs: List[Dict[str, Any]], +) -> Dict[str, List[Any]]: + """ + Fetches all related entity types for a project in parallel. + + Args: + project_id: The project ID to fetch entities for. + entity_configs: List of dicts with keys 'key', 'index_pattern', 'model_class'. + + Returns: + Dictionary mapping each config 'key' to a list of validated entities. + """ + async def _fetch_one(config: Dict[str, Any]): + entities = await _fetch_related_entities( + project_ids=[project_id], + index_pattern=config["index_pattern"], + model_class=config["model_class"], + ) + return config["key"], entities.get(project_id, []) + + tasks = [_fetch_one(cfg) for cfg in entity_configs] + completed = await asyncio.gather(*tasks, return_exceptions=True) + + results: Dict[str, List[Any]] = {} + for cfg, res in zip(entity_configs, completed): + key = cfg["key"] + if isinstance(res, Exception): + logger.error(f"Parallel fetch failed for '{key}': {res}") + results[key] = [] + else: + key_name, data = res + results[key_name] = data + + return results + + +async def _fetch_related_entities( + project_ids: List[str], + index_pattern: str, + model_class: Any, +) -> Dict[str, List[Any]]: + """ + Fetches and groups related entities from Elasticsearch by project ID. + + Args: + project_ids: List of project IDs to fetch entities for. + index_pattern: The index pattern to search (supports wildcards). + model_class: The Pydantic model class to validate against. + + Returns: + Dictionary mapping project IDs to lists of validated entities. + """ + query = {"bool": {"filter": [{"terms": {"projectID": project_ids}}]}} + + try: + response = await elasticsearch.search( + query=query, + index=index_pattern, + cluster=ESCluster.INSE, + size=10000, + ) + except Exception as e: + logger.warning(f"Failed to fetch from {index_pattern}: {e}") + return {} + + grouped: Dict[str, List[Any]] = {} + + for hit in response.get("hits", {}).get("hits", []): + source = hit.get("_source", {}) + project_id = source.get("projectID") + + if not project_id: + continue + + grouped.setdefault(project_id, []) + + try: + entity = model_class.model_validate(source) + grouped[project_id].append(entity) + except Exception as e: + logger.warning(f"Failed to validate {model_class.__name__} for project {project_id}: {e}") + + return grouped + + +async def _enrich_fp7_project( + project_id: str, + project_source: Dict[str, Any], +) -> Optional[Fp7ProjectDetails]: + """Enriches a single FP7 project with all related data.""" + try: + project = Fp7Project.model_validate(project_source) + except Exception as e: + logger.error(f"Failed to validate FP7 project {project_id}: {e}") + return None + + related = await _fetch_related_entities_parallel(project_id, _FP7_ENTITY_CONFIGS) + + return Fp7ProjectDetails.from_project_with_relations(project=project, **related) + + +async def _enrich_h2020_project( + project_id: str, + project_source: Dict[str, Any], +) -> Optional[H2020ProjectDetails]: + """Enriches a single H2020 project with all related data.""" + try: + project = H2020Project.model_validate(project_source) + except Exception as e: + logger.error(f"Failed to validate H2020 project {project_id}: {e}") + return None + + related = await _fetch_related_entities_parallel(project_id, _H2020_ENTITY_CONFIGS) + + return H2020ProjectDetails.from_project_with_relations(project=project, **related) + + +async def _enrich_heu_project( + project_id: str, + project_source: Dict[str, Any], +) -> Optional[HEUProjectDetails]: + """Enriches a single Horizon Europe project with all related data.""" + try: + project = HEUProject.model_validate(project_source) + except Exception as e: + logger.error(f"Failed to validate Horizon Europe project {project_id}: {e}") + return None + + related = await _fetch_related_entities_parallel(project_id, _HEU_ENTITY_CONFIGS) + + return HEUProjectDetails.from_project_with_relations(project=project, **related) + + + + +from inse.projects.model import ( + EuCordisProjectType, + EuCordisProjectSearchPage, + EuCordisProjectSummary, + EuCordisOrganizationSummary, + EuCordisTopicSummary, + EuCordisEurosciVocSummary, +) +from inse.projects.logic import ( + get_eu_project_ids_by_openalex_topic_ids, + get_openalex_topics_for_eu_projects, +) + +def _eu_project_type_index_filter( + project_ids_by_type: Dict[EuCordisProjectType, List[str]], +) -> Optional[Dict[str, Any]]: + should_clauses = [] + + for project_type, project_ids in project_ids_by_type.items(): + if not project_ids: + continue + + should_clauses.append( + { + "bool": { + "filter": [ + {"term": {"_index": project_type.to_project_index().value}}, + {"terms": {"id": project_ids}}, + ] + } + } + ) + + if not should_clauses: + return None + + return { + "bool": { + "should": should_clauses, + "minimum_should_match": 1, + } + } + + +def _eu_year_filters(field: str, years: List[str]) -> Dict[str, Any]: + should = [] + + for year in years: + year = str(year).strip() + if not year: + continue + + should.append( + { + "range": { + field: { + "gte": f"{year}-01-01", + "lte": f"{year}-12-31", + } + } + } + ) + + return { + "bool": { + "should": should, + "minimum_should_match": 1, + } + } + + +def _eu_sort_field(sort_by: str) -> str: + mapping = { + "title": "title.keyword", + "funding_start": "startDate", + "funding_end": "endDate", + "funding_amount": "ecMaxContribution", + "id": "id", + "project_type": "_index", + } + return mapping.get(sort_by, "title.keyword") + + +async def get_eu_project_ids_by_organization_filters( + project_types: List[EuCordisProjectType], + organization_ids: Optional[List[str]] = None, + organization_names: Optional[List[str]] = None, +) -> Dict[EuCordisProjectType, List[str]]: + """ + Returns project IDs matching ALL selected organizations. + If organization_ids=[A,B], a project must have both A and B. + Same semantics requested as DFG topic filters. + """ + organization_ids = [x for x in (organization_ids or []) if str(x).strip()] + organization_names = [x for x in (organization_names or []) if str(x).strip()] + + if not organization_ids and not organization_names: + return {} + + result: Dict[EuCordisProjectType, List[str]] = {} + + for project_type in project_types: + project_org_matches: Dict[str, Set[str]] = defaultdict(set) + + should = [] + + if organization_ids: + should.append({"terms": {"organisationID": organization_ids}}) + + for name in organization_names: + should.append( + { + "match": { + "name": { + "query": name, + "operator": "and", + } + } + } + ) + + response = await elasticsearch.search( + index=project_type.to_organization_index(), + cluster=ESCluster.INSE, + body={ + "size": 10000, + "_source": ["projectID", "organisationID", "name"], + "query": { + "bool": { + "should": should, + "minimum_should_match": 1, + } + }, + }, + ) + + hits = response.get("hits", {}).get("hits", []) + + for hit in hits: + source = hit.get("_source", {}) + project_id = source.get("projectID") + if not project_id: + continue + + organisation_id = source.get("organisationID") + name = source.get("name") + + if organisation_id in organization_ids: + project_org_matches[project_id].add(f"id:{organisation_id}") + + for org_name in organization_names: + if name and org_name.lower() in name.lower(): + project_org_matches[project_id].add(f"name:{org_name.lower()}") + + required = {f"id:{x}" for x in organization_ids} + required.update({f"name:{x.lower()}" for x in organization_names}) + + result[project_type] = [ + project_id + for project_id, found in project_org_matches.items() + if required.issubset(found) + ] + + return result + +async def get_eu_organizations_for_projects( + project_ids_by_type: Dict[EuCordisProjectType, List[str]], +) -> Dict[Tuple[EuCordisProjectType, str], List[EuCordisOrganizationSummary]]: + lookup: Dict[Tuple[EuCordisProjectType, str], List[EuCordisOrganizationSummary]] = {} + + for project_type, project_ids in project_ids_by_type.items(): + if not project_ids: + continue + + response = await elasticsearch.search( + index=project_type.to_organization_index(), + cluster=ESCluster.INSE, + body={ + "size": 10000, + "_source": [ + "id", + "organisationID", + "name", + "shortName", + "country", + "city", + "role", + "activityType", + "projectID", + "ecContribution", + "totalCost", + ], + "query": { + "terms": { + "projectID": project_ids + } + }, + "sort": [ + {"order": {"order": "asc", "unmapped_type": "integer"}} + ], + }, + ) + + for hit in response.get("hits", {}).get("hits", []): + source = hit.get("_source", {}) + project_id = source.get("projectID") + if not project_id: + continue + + lookup.setdefault((project_type, project_id), []).append( + EuCordisOrganizationSummary.from_es_source(source) + ) + + return lookup + + +async def get_eu_cordis_topics_for_projects( + project_ids_by_type: Dict[EuCordisProjectType, List[str]], +) -> Dict[Tuple[EuCordisProjectType, str], List[EuCordisTopicSummary]]: + lookup: Dict[Tuple[EuCordisProjectType, str], List[EuCordisTopicSummary]] = {} + + for project_type, project_ids in project_ids_by_type.items(): + if not project_ids: + continue + + response = await elasticsearch.search( + index=project_type.to_cordis_topic_index(), + cluster=ESCluster.INSE, + body={ + "size": 10000, + "_source": ["id", "projectID", "title", "topic"], + "query": { + "terms": { + "projectID": project_ids + } + }, + }, + ) + + for hit in response.get("hits", {}).get("hits", []): + source = hit.get("_source", {}) + project_id = source.get("projectID") + if not project_id: + continue + + lookup.setdefault((project_type, project_id), []).append( + EuCordisTopicSummary.from_es_source(source) + ) + + return lookup + + +async def get_eu_euroscivoc_for_projects( + project_ids_by_type: Dict[EuCordisProjectType, List[str]], +) -> Dict[Tuple[EuCordisProjectType, str], List[EuCordisEurosciVocSummary]]: + lookup: Dict[Tuple[EuCordisProjectType, str], List[EuCordisEurosciVocSummary]] = {} + + for project_type, project_ids in project_ids_by_type.items(): + if not project_ids: + continue + + response = await elasticsearch.search( + index=project_type.to_euroscivoc_index(), + cluster=ESCluster.INSE, + body={ + "size": 10000, + "_source": ["id", "projectID", "code", "title", "description", "path"], + "query": { + "terms": { + "projectID": project_ids + } + }, + }, + ) + + for hit in response.get("hits", {}).get("hits", []): + source = hit.get("_source", {}) + project_id = source.get("projectID") + if not project_id: + continue + + lookup.setdefault((project_type, project_id), []).append( + EuCordisEurosciVocSummary.from_es_source(source) + ) + + return lookup + + +async def search_eu_cordis_projects( + page: int, + size: int, + project_types: Optional[List[EuCordisProjectType]] = None, + organization_ids: Optional[List[str]] = None, + organization_names: Optional[List[str]] = None, + author_project_ids: Optional[List[str]] = None, + keywords: Optional[List[str]] = None, + topic_ids: Optional[List[str]] = None, + filter_topic_ids: Optional[List[str]] = None, + title: Optional[str] = None, + funding_start_years: Optional[List[str]] = None, + funding_end_years: Optional[List[str]] = None, + countries: Optional[List[str]] = None, + framework_programmes: Optional[List[str]] = None, + funding_schemes: Optional[List[str]] = None, + statuses: Optional[List[str]] = None, + sort_by: str = "title", + sort_direction: str = "asc", + fuzzy: bool = False, +) -> EuCordisProjectSearchPage: + """ + Generic EU CORDIS project search across FP7, H2020 and Horizon Europe. + Mirrors DFG behavior: + - fuzzy=True + topic_ids => OpenAlex topic mapping lookup + - filter_topic_ids are always applied independently + - selected organizations/topics must ALL match + """ + if not project_types: + project_types = [ + EuCordisProjectType.FP7, + EuCordisProjectType.H2020, + EuCordisProjectType.HEU, + ] + + indices = [project_type.to_project_index() for project_type in project_types] + + must_clauses: List[Dict[str, Any]] = [] + + # === Author filter resolved in service layer === + if author_project_ids is not None: + if not author_project_ids: + return EuCordisProjectSearchPage(elements=[], total=0, page=page, size=size) + + must_clauses.append({"terms": {"id": author_project_ids}}) + + # === Primary search: fuzzy OpenAlex topics or raw keywords === + if fuzzy and topic_ids: + topic_project_ids_by_type = await get_eu_project_ids_by_openalex_topic_ids( + project_types=project_types, + topic_ids=topic_ids, + ) + + topic_filter = _eu_project_type_index_filter(topic_project_ids_by_type) + if not topic_filter: + return EuCordisProjectSearchPage(elements=[], total=0, page=page, size=size) + + must_clauses.append(topic_filter) + + elif keywords: + keyword_clauses = [] + + for keyword in keywords: + keyword = keyword.strip() + if not keyword: + continue + + keyword_clauses.append( + { + "bool": { + "should": [ + { + "multi_match": { + "query": keyword, + "fields": [ + "title^4", + "acronym^3", + "objective^2", + "keywords^2", + ], + "type": "phrase_prefix", + "max_expansions": 100, + } + }, + { + "wildcard": { + "topics": { + "value": f"*{keyword}*", + "case_insensitive": True, + } + } + }, + ], + "minimum_should_match": 1, + } + } + ) + + if keyword_clauses: + must_clauses.append({"bool": {"must": keyword_clauses}}) + + # === Independent OpenAlex topic filters === + if filter_topic_ids: + filter_topic_project_ids_by_type = await get_eu_project_ids_by_openalex_topic_ids( + project_types=project_types, + topic_ids=filter_topic_ids, + ) + + topic_filter = _eu_project_type_index_filter(filter_topic_project_ids_by_type) + if not topic_filter: + return EuCordisProjectSearchPage(elements=[], total=0, page=page, size=size) + + must_clauses.append(topic_filter) + + # === Organization filters: all selected organizations must match === + if organization_ids or organization_names: + org_project_ids_by_type = await get_eu_project_ids_by_organization_filters( + project_types=project_types, + organization_ids=organization_ids, + organization_names=organization_names, + ) + + org_filter = _eu_project_type_index_filter(org_project_ids_by_type) + if not org_filter: + return EuCordisProjectSearchPage(elements=[], total=0, page=page, size=size) + + must_clauses.append(org_filter) + + # === Title === + if title: + must_clauses.append( + { + "multi_match": { + "query": title, + "fields": ["title^4", "acronym^2"], + "type": "phrase_prefix", + "max_expansions": 100, + } + } + ) + + # === Funding dates === + if funding_start_years: + must_clauses.append(_eu_year_filters("startDate", funding_start_years)) + + if funding_end_years: + must_clauses.append(_eu_year_filters("endDate", funding_end_years)) + + # === Project core filters === + if framework_programmes: + must_clauses.append({"terms": {"frameworkProgramme": framework_programmes}}) + + if funding_schemes: + must_clauses.append({"terms": {"fundingScheme": funding_schemes}}) + + if statuses: + must_clauses.append({"terms": {"status": statuses}}) + + # === Country filter requires organization lookup === + if countries: + country_project_ids_by_type: Dict[EuCordisProjectType, List[str]] = {} + + for project_type in project_types: + response = await elasticsearch.search( + index=project_type.to_organization_index(), + cluster=ESCluster.INSE, + body={ + "size": 10000, + "_source": ["projectID"], + "query": { + "terms": { + "country": countries + } + }, + }, + ) + + country_project_ids_by_type[project_type] = list( + { + hit.get("_source", {}).get("projectID") + for hit in response.get("hits", {}).get("hits", []) + if hit.get("_source", {}).get("projectID") + } + ) + + country_filter = _eu_project_type_index_filter(country_project_ids_by_type) + if not country_filter: + return EuCordisProjectSearchPage(elements=[], total=0, page=page, size=size) + + must_clauses.append(country_filter) + + query = {"bool": {"must": must_clauses}} if must_clauses else {"match_all": {}} + + sort_direction = sort_direction.lower() + if sort_direction not in ["asc", "desc"]: + sort_direction = "asc" + + sort_field = _eu_sort_field(sort_by.strip().lower()) + response = await elasticsearch.search( + index=indices, + cluster=ESCluster.INSE, + body={ + "size": size, + "from": page * size, + "track_total_hits": True, + "_source": [ + "id", + "title", + "acronym", + "objective", + "keywords", + "frameworkProgramme", + "fundingScheme", + "status", + "startDate", + "endDate", + "ecMaxContribution", + "totalCost", + ], + "query": query, + "sort": [ + { + sort_field: { + "order": sort_direction, + "missing": "_last", + "unmapped_type": "keyword" if sort_field.endswith(".keyword") else "date", + } + } + ], + }, + ) + + hits = response.get("hits", {}).get("hits", []) + total = response.get("hits", {}).get("total", {}).get("value", 0) + + project_ids_by_type: Dict[EuCordisProjectType, List[str]] = defaultdict(list) + + for hit in hits: + project_type = EuCordisProjectType.from_index_name(hit.get("_index", "")) + project_id = hit.get("_source", {}).get("id") + if project_id: + project_ids_by_type[project_type].append(project_id) + authors_lookup = await get_openalex_authors_for_projects_ids(project_ids_by_type) + organizations_lookup = await get_eu_organizations_for_projects(project_ids_by_type) + cordis_topics_lookup = await get_eu_cordis_topics_for_projects(project_ids_by_type) + euroscivoc_lookup = await get_eu_euroscivoc_for_projects(project_ids_by_type) + openalex_topics_lookup = await get_openalex_topics_for_eu_projects(project_ids_by_type) + + elements: List[EuCordisProjectSummary] = [] + + for hit in hits: + source = hit.get("_source", {}) + project_type = EuCordisProjectType.from_index_name(hit.get("_index", "")) + project_id = source.get("id") + + raw_topic_matches = openalex_topics_lookup.get((project_type, project_id), []) + raw_topic_matches = sorted( + raw_topic_matches, + key=lambda t: t.get("rank") if t.get("rank") is not None else float("inf"), + ) + + topics = [ + EuCordisProjectSummary.topic_from_match(match) + for match in raw_topic_matches + if isinstance(match, dict) + ] + elements.append( + EuCordisProjectSummary.from_hit( + hit=hit, + authors=authors_lookup.get((project_type, project_id), AuthorPage(elements=[], total=0, page=0, size=0)), + organizations=organizations_lookup.get((project_type, project_id), []), + cordis_topics=cordis_topics_lookup.get((project_type, project_id), []), + eurosci_voc=euroscivoc_lookup.get((project_type, project_id), []), + topics=topics, + ) + ) + return EuCordisProjectSearchPage( + elements=elements, + total=total, + page=page, + size=size, + ) + +def _to_openalex_doi_url(raw_doi: str) -> str: + """CORDIS stores bare DOIs (e.g. '10.1093/toxsci/kfs018'); + OpenAlex works index stores full URLs ('https://doi.org/10.1093/toxsci/kfs018').""" + raw_doi = raw_doi.strip() + if raw_doi.startswith("http://") or raw_doi.startswith("https://"): + return raw_doi + return f"https://doi.org/{raw_doi}" + +async def get_dois_by_cordis_eu_project_id(project_id: str) -> List[str]: + """Retrieves the raw DOIs of publications associated with a given CORDIS EU project ID.""" + query = {"bool": {"filter": [{"term": {"projectID": project_id}}]}} + + response = await elasticsearch.search( + query=query, + index=ESIndex.CORDIS_EU_PUBLICATIONS_WILDCARD, + cluster=ESCluster.INSE, + source=["doi","qaProcessedDoi"], + size=10000, + ) + + dois = [] + for hit in response.get("hits", {}).get("hits", []): + doi = hit.get("_source", {}).get("doi") + qa_processed_doi = hit.get("_source", {}).get("qaProcessedDoi") + if doi: + dois.append(doi) + if qa_processed_doi: + dois.append(qa_processed_doi) + return list(set(dois)) # Remove duplicates + +async def get_openalex_author_ids_by_dois( + dois: List[str], +) -> Dict[str, List[str]]: + """Retrieves the OpenAlex author IDs (full URL form) authoring works for each + given (raw, non-prefixed) DOI. Returns a mapping of the *original raw DOI* + (as passed in) -> list of author_ids, so callers can trace authors back to + whatever the DOI was associated with (e.g. a project).""" + if not dois: + return {} + + url_to_raw = { + _to_openalex_doi_url(doi.lower()): doi + for doi in dois + } + + doi_urls = list(url_to_raw.keys()) + + query = { + "bool": { + "filter": [ + { + "terms": { + "doi": doi_urls + } + } + ] + } + } + + response = await elasticsearch.search( + index=ESIndex.OPENALEX_WORKS_WILDCARD, + source=["doi", "authorships.author.id"], + query=query, + size=10000, + cluster=ESCluster.NES, + ) + result: Dict[str, List[str]] = {} + for hit in response.get("hits", {}).get("hits", []): + source = hit.get("_source", {}) + doi_url = source.get("doi") + raw_doi = url_to_raw.get(doi_url) + if not raw_doi: + continue + author_ids = [ + authorship.get("author", {}).get("id") + for authorship in source.get("authorships", []) + if authorship.get("author", {}).get("id") + ] + result.setdefault(raw_doi, []).extend(author_ids) + + return result + + +async def get_openalex_authors_for_cordis_project_ids( + project_ids: List[str], +) -> Dict[str, AuthorPage]: + """Returns a mapping of project_id -> AuthorPage for a batch of projects.""" + if not project_ids: + return {} + + query = {"bool": {"filter": [{"terms": {"projectID": project_ids}}]}} + response = await elasticsearch.search( + query=query, + index=ESIndex.CORDIS_EU_PUBLICATIONS_WILDCARD, + cluster=ESCluster.INSE, + source=["projectID", "doi","qaProcessedDoi"], + size=10000, + ) + dois_by_project: Dict[str, Set[str]] = {} + for hit in response.get("hits", {}).get("hits", []): + source = hit.get("_source", {}) + pid = source.get("projectID") + doi = source.get("doi") + qa_processed_doi = source.get("qaProcessedDoi") + if pid: + dois_by_project.setdefault(pid, set()) + if doi: + dois_by_project[pid].add(doi) + elif qa_processed_doi: + dois_by_project[pid].add(qa_processed_doi) + + all_dois = list({doi for dois in dois_by_project.values() for doi in dois}) + + # single ES call for the whole batch, keyed by raw DOI + author_ids_by_doi = await get_openalex_author_ids_by_dois(dois=all_dois) + + # aggregate per project, dedupe author_ids within a project + author_ids_by_project: Dict[str, List[str]] = {} + for pid, dois in dois_by_project.items(): + project_author_ids: Set[str] = set() + for doi in dois: + project_author_ids.update(author_ids_by_doi.get(doi, [])) + author_ids_by_project[pid] = list(project_author_ids) + + # single ES call to fetch all Author objects across every project + all_author_ids = list({aid for ids in author_ids_by_project.values() for aid in ids}) + + author_page = await get_authors_by_ids(author_ids=all_author_ids) + authors_by_id = {author.id: author for author in author_page.elements} + + # split the fetched authors back out per project + result: Dict[str, AuthorPage] = {} + for pid in project_ids: + ids_for_project = author_ids_by_project.get(pid, []) + authors_for_project = [ + authors_by_id[aid] for aid in ids_for_project if aid in authors_by_id + ] + result[pid] = AuthorPage( + elements=authors_for_project, + total=len(authors_for_project), + page=0, + size=len(authors_for_project), + ) + + return result + +async def get_openalex_authors_for_projects_ids( + project_ids_by_type: Dict[EuCordisProjectType, List[str]], +) -> Dict[Tuple[EuCordisProjectType, str], AuthorPage]: + """Adapts get_openalex_authors_for_cordis_project_ids to the + (project_type, project_id)-keyed lookup convention used across this module.""" + all_project_ids = [ + pid for pids in project_ids_by_type.values() for pid in pids + ] + if not all_project_ids: + return {} + + # NOTE: get_openalex_authors_for_cordis_project_ids is keyed purely by project_id, + # not (type, id). This assumes project_id is globally unique across FP7/H2020/HEU. + author_pages_by_project_id = await get_openalex_authors_for_cordis_project_ids( + project_ids=all_project_ids + ) + + result: Dict[Tuple[EuCordisProjectType, str], AuthorPage] = {} + for project_type, project_ids in project_ids_by_type.items(): + for pid in project_ids: + result[(project_type, pid)] = author_pages_by_project_id.get( + pid, AuthorPage(elements=[], total=0, page=0, size=0) + ) + return result \ No newline at end of file diff --git a/service/src/main/inse/projects/eu_cordis_projects_enrichment_client.py b/service/src/main/inse/projects/eu_cordis_projects_enrichment_client.py deleted file mode 100644 index cb120418..00000000 --- a/service/src/main/inse/projects/eu_cordis_projects_enrichment_client.py +++ /dev/null @@ -1,281 +0,0 @@ -import logging -import asyncio -from typing import Any, Dict, List, Optional, Union - -from inse.config import get_settings -from inse.integrations import elasticsearch -from inse.model import ESCluster, ESIndex - -# Import base models -from inse.models.cordis_eu_project import CordisEuProject - -# Import FP7 models -from inse.models.projects_eu_cordis.fp7.fp7_project import Fp7Project -from inse.models.projects_eu_cordis.fp7.fp7_organization import Fp7Organization -from inse.models.projects_eu_cordis.fp7.fp7_publication import Fp7Publication -from inse.models.projects_eu_cordis.fp7.fp7_project_ipr import Fp7ProjectIPR -from inse.models.projects_eu_cordis.fp7.fp7_report_summary import Fp7ReportSummary -from inse.models.projects_eu_cordis.fp7.fp7_topic import Fp7Topic -from inse.models.projects_eu_cordis.fp7.fp7_web_link import Fp7WebLink -from inse.models.projects_eu_cordis.fp7.fp7_eurosci_voc import Fp7EurosciVoc -from inse.models.projects_eu_cordis.fp7.fp7_legal_basis import Fp7LegalBasis -from inse.models.projects_eu_cordis.fp7.fp7_project_details import Fp7ProjectDetails - -# Import H2020 models -from inse.models.projects_eu_cordis.horizon2020.h2020_project import H2020Project -from inse.models.projects_eu_cordis.horizon2020.h2020_organization import H2020Organization -from inse.models.projects_eu_cordis.horizon2020.h2020_publication import H2020Publication -from inse.models.projects_eu_cordis.horizon2020.h2020_deliverable import H2020Deliverable -from inse.models.projects_eu_cordis.horizon2020.h2020_report_summary import H2020ReportSummary -from inse.models.projects_eu_cordis.horizon2020.h2020_topic import H2020Topic -from inse.models.projects_eu_cordis.horizon2020.h2020_web_link import H2020WebLink -from inse.models.projects_eu_cordis.horizon2020.h2020_eurosci_voc import H2020EurosciVoc -from inse.models.projects_eu_cordis.horizon2020.h2020_legal_basis import H2020LegalBasis -from inse.models.projects_eu_cordis.horizon2020.h2020_erc_pi import H2020ErcPI -from inse.models.projects_eu_cordis.horizon2020.h2020_project_details import H2020ProjectDetails - -# Import Horizon Europe models -from inse.models.projects_eu_cordis.horizon_europe.heu_project import HEUProject -from inse.models.projects_eu_cordis.horizon_europe.heu_organization import HEUOrganization -from inse.models.projects_eu_cordis.horizon_europe.heu_publication import HEUPublication -from inse.models.projects_eu_cordis.horizon_europe.heu_deliverable import HEUDeliverable -from inse.models.projects_eu_cordis.horizon_europe.heu_report_summary import HEUReportSummary -from inse.models.projects_eu_cordis.horizon_europe.heu_topic import HEUTopic -from inse.models.projects_eu_cordis.horizon_europe.heu_web_link import HEUWebLink -from inse.models.projects_eu_cordis.horizon_europe.heu_eurosci_voc import HEUEurosciVoc -from inse.models.projects_eu_cordis.horizon_europe.heu_legal_basis import HEULegalBasis -from inse.models.projects_eu_cordis.horizon_europe.heu_project_details import HEUProjectDetails - -settings = get_settings() -logger = logging.getLogger(__name__) -logger.setLevel(settings.logging_level) - -# Entity config -_FP7_ENTITY_CONFIGS = [ - {"key": "organizations", "index_pattern": ESIndex.CORDIS_EU_FP7_ORGANIZATIONS, "model_class": Fp7Organization}, - {"key": "publications", "index_pattern": ESIndex.CORDIS_EU_FP7_PUBLICATIONS, "model_class": Fp7Publication}, - {"key": "iprs", "index_pattern": ESIndex.CORDIS_EU_FP7_PROJECT_IPRS, "model_class": Fp7ProjectIPR}, - {"key": "report_summaries", "index_pattern": ESIndex.CORDIS_EU_FP7_REPORT_SUMMARIES, "model_class": Fp7ReportSummary}, - {"key": "topics_list", "index_pattern": ESIndex.CORDIS_EU_FP7_TOPICS, "model_class": Fp7Topic}, - {"key": "web_links", "index_pattern": ESIndex.CORDIS_EU_FP7_WEB_LINKS, "model_class": Fp7WebLink}, - {"key": "eurosci_voc", "index_pattern": ESIndex.CORDIS_EU_FP7_EUROSCIVOC, "model_class": Fp7EurosciVoc}, - {"key": "legal_basis_list", "index_pattern": ESIndex.CORDIS_EU_FP7_LEGAL_BASIS, "model_class": Fp7LegalBasis}, -] - -_H2020_ENTITY_CONFIGS = [ - {"key": "organizations", "index_pattern": ESIndex.CORDIS_EU_HORIZON_2020_ORGANIZATIONS, "model_class": H2020Organization}, - {"key": "publications", "index_pattern": ESIndex.CORDIS_EU_HORIZON_2020_PUBLICATIONS, "model_class": H2020Publication}, - {"key": "deliverables", "index_pattern": ESIndex.CORDIS_EU_HORIZON_2020_DELIVERABLES, "model_class": H2020Deliverable}, - {"key": "report_summaries", "index_pattern": ESIndex.CORDIS_EU_HORIZON_2020_REPORT_SUMMARIES, "model_class": H2020ReportSummary}, - {"key": "topics_list", "index_pattern": ESIndex.CORDIS_EU_HORIZON_2020_TOPICS, "model_class": H2020Topic}, - {"key": "web_links", "index_pattern": ESIndex.CORDIS_EU_HORIZON_2020_WEB_LINKS, "model_class": H2020WebLink}, - {"key": "eurosci_voc", "index_pattern": ESIndex.CORDIS_EU_HORIZON_2020_EUROSCIVOC, "model_class": H2020EurosciVoc}, - {"key": "legal_basis_list", "index_pattern": ESIndex.CORDIS_EU_HORIZON_2020_LEGAL_BASIS, "model_class": H2020LegalBasis}, - {"key": "erc_principal_investigators", "index_pattern": ESIndex.CORDIS_EU_HORIZON_2020_ERC_PIS, "model_class": H2020ErcPI}, -] - -_HEU_ENTITY_CONFIGS = [ - {"key": "organizations", "index_pattern": ESIndex.CORDIS_EU_HORIZON_EUROPE_ORGANIZATIONS, "model_class": HEUOrganization}, - {"key": "publications", "index_pattern": ESIndex.CORDIS_EU_HORIZON_EUROPE_PUBLICATIONS, "model_class": HEUPublication}, - {"key": "deliverables", "index_pattern": ESIndex.CORDIS_EU_HORIZON_EUROPE_DELIVERABLES, "model_class": HEUDeliverable}, - {"key": "report_summaries", "index_pattern": ESIndex.CORDIS_EU_HORIZON_EUROPE_REPORT_SUMMARIES, "model_class": HEUReportSummary}, - {"key": "topics_list", "index_pattern": ESIndex.CORDIS_EU_HORIZON_EUROPE_TOPICS, "model_class": HEUTopic}, - {"key": "web_links", "index_pattern": ESIndex.CORDIS_EU_HORIZON_EUROPE_WEB_LINKS, "model_class": HEUWebLink}, - {"key": "eurosci_voc", "index_pattern": ESIndex.CORDIS_EU_HORIZON_EUROPE_EUROSCIVOC, "model_class": HEUEurosciVoc}, - {"key": "legal_basis_list", "index_pattern": ESIndex.CORDIS_EU_HORIZON_EUROPE_LEGAL_BASIS, "model_class": HEULegalBasis}, -] - -async def get_enriched_cordis_project_by_id( - project_id: str, -) -> Optional[Union[Fp7ProjectDetails, H2020ProjectDetails, HEUProjectDetails]]: - """ - Fetches and enriches a single Cordis EU project by its ID across all programme types. - - Args: - project_id: The project ID to fetch. - - Returns: - The enriched detailed project model, or None if not found. - """ - if not project_id: - return None - - query = {"bool": {"filter": [{"term": {"id": project_id}}]}} - - response = await elasticsearch.search( - query=query, - index=ESIndex.CORDIS_EU_PROJECTS_WILDCARD, - cluster=ESCluster.INSE, - size=1, - ) - - hits = response.get("hits", {}).get("hits", []) - if not hits: - logger.info(f"No project found with ID: {project_id}") - return None - - hit = hits[0] - index = hit.get("_index", "") - source = hit.get("_source", {}) - - program_type = _determine_program_type_from_index(index) - - enrichers = { - "fp7": _enrich_fp7_project, - "h2020": _enrich_h2020_project, - "heu": _enrich_heu_project, - } - - enricher = enrichers.get(program_type) - if enricher is None: - logger.warning(f"Unknown programme type for index: {index}") - return CordisEuProject.model_validate(source) - - return await enricher(project_id, source) - -# helpers -def _determine_program_type_from_index(index: str) -> str: - """Determines the programme type from the Elasticsearch index name.""" - index_lower = index.lower() - if "fp7" in index_lower: - return "fp7" - if "horizon_2020" in index_lower: - return "h2020" - if "heu" in index_lower or "horizon_europe" in index_lower: - return "heu" - return "unknown" - - -async def _fetch_related_entities_parallel( - project_id: str, - entity_configs: List[Dict[str, Any]], -) -> Dict[str, List[Any]]: - """ - Fetches all related entity types for a project in parallel. - - Args: - project_id: The project ID to fetch entities for. - entity_configs: List of dicts with keys 'key', 'index_pattern', 'model_class'. - - Returns: - Dictionary mapping each config 'key' to a list of validated entities. - """ - async def _fetch_one(config: Dict[str, Any]): - entities = await _fetch_related_entities( - project_ids=[project_id], - index_pattern=config["index_pattern"], - model_class=config["model_class"], - ) - return config["key"], entities.get(project_id, []) - - tasks = [_fetch_one(cfg) for cfg in entity_configs] - completed = await asyncio.gather(*tasks, return_exceptions=True) - - results: Dict[str, List[Any]] = {} - for cfg, res in zip(entity_configs, completed): - key = cfg["key"] - if isinstance(res, Exception): - logger.error(f"Parallel fetch failed for '{key}': {res}") - results[key] = [] - else: - key_name, data = res - results[key_name] = data - - return results - - -async def _fetch_related_entities( - project_ids: List[str], - index_pattern: str, - model_class: Any, -) -> Dict[str, List[Any]]: - """ - Fetches and groups related entities from Elasticsearch by project ID. - - Args: - project_ids: List of project IDs to fetch entities for. - index_pattern: The index pattern to search (supports wildcards). - model_class: The Pydantic model class to validate against. - - Returns: - Dictionary mapping project IDs to lists of validated entities. - """ - query = {"bool": {"filter": [{"terms": {"projectID": project_ids}}]}} - - try: - response = await elasticsearch.search( - query=query, - index=index_pattern, - cluster=ESCluster.INSE, - size=10000, - ) - except Exception as e: - logger.warning(f"Failed to fetch from {index_pattern}: {e}") - return {} - - grouped: Dict[str, List[Any]] = {} - - for hit in response.get("hits", {}).get("hits", []): - source = hit.get("_source", {}) - project_id = source.get("projectID") - - if not project_id: - continue - - grouped.setdefault(project_id, []) - - try: - entity = model_class.model_validate(source) - grouped[project_id].append(entity) - except Exception as e: - logger.warning(f"Failed to validate {model_class.__name__} for project {project_id}: {e}") - - return grouped - - -async def _enrich_fp7_project( - project_id: str, - project_source: Dict[str, Any], -) -> Optional[Fp7ProjectDetails]: - """Enriches a single FP7 project with all related data.""" - try: - project = Fp7Project.model_validate(project_source) - except Exception as e: - logger.error(f"Failed to validate FP7 project {project_id}: {e}") - return None - - related = await _fetch_related_entities_parallel(project_id, _FP7_ENTITY_CONFIGS) - - return Fp7ProjectDetails.from_project_with_relations(project=project, **related) - - -async def _enrich_h2020_project( - project_id: str, - project_source: Dict[str, Any], -) -> Optional[H2020ProjectDetails]: - """Enriches a single H2020 project with all related data.""" - try: - project = H2020Project.model_validate(project_source) - except Exception as e: - logger.error(f"Failed to validate H2020 project {project_id}: {e}") - return None - - related = await _fetch_related_entities_parallel(project_id, _H2020_ENTITY_CONFIGS) - - return H2020ProjectDetails.from_project_with_relations(project=project, **related) - - -async def _enrich_heu_project( - project_id: str, - project_source: Dict[str, Any], -) -> Optional[HEUProjectDetails]: - """Enriches a single Horizon Europe project with all related data.""" - try: - project = HEUProject.model_validate(project_source) - except Exception as e: - logger.error(f"Failed to validate Horizon Europe project {project_id}: {e}") - return None - - related = await _fetch_related_entities_parallel(project_id, _HEU_ENTITY_CONFIGS) - - return HEUProjectDetails.from_project_with_relations(project=project, **related) \ No newline at end of file diff --git a/service/src/main/inse/projects/eu_organizations/model.py b/service/src/main/inse/projects/eu_organizations/model.py new file mode 100644 index 00000000..e69de29b diff --git a/service/src/main/inse/projects/eu_organizations/router.py b/service/src/main/inse/projects/eu_organizations/router.py new file mode 100644 index 00000000..263587c4 --- /dev/null +++ b/service/src/main/inse/projects/eu_organizations/router.py @@ -0,0 +1,51 @@ +import logging +from typing import Annotated, List + +from fastapi import APIRouter, Query + +from inse.projects.eu_organizations.service import autocomplete_organizations_for_selector, get_organizations_by_ids + +from inse.projects.model import EuCordisOrganizationSelectorPage +from inse.tags import Tags + +logger = logging.getLogger(__name__) + +EU_ORGANIZATIONS_PREFIX = "/api/eu/organizations" + +router = APIRouter(prefix=EU_ORGANIZATIONS_PREFIX, tags=[Tags.PROJECTS]) + + +@router.get( + "/ids", + operation_id="getEuOrganizationsByIds", + summary="Returns EU CORDIS organizations by organisation IDs.", + response_model=EuCordisOrganizationSelectorPage, +) +async def get_eu_organizations_by_ids( + organization_ids: Annotated[ + List[str], + Query(description="CORDIS organisation IDs to retrieve."), + ] = [], +) -> EuCordisOrganizationSelectorPage: + return await get_organizations_by_ids(organization_ids=organization_ids or []) + + +@router.get( + "/autocomplete/selector", + operation_id="getEuOrganizationAutocompleteForSelector", + summary="Returns EU CORDIS organizations based on a search term.", + response_model=EuCordisOrganizationSelectorPage, +) +async def get_eu_organization_autocomplete( + query: Annotated[ + str, + Query(description="Search term for organization autocomplete."), + ] = "", + page: Annotated[int, Query(ge=0)] = 0, + size: Annotated[int, Query(ge=1)] = 10, +) -> EuCordisOrganizationSelectorPage: + return await autocomplete_organizations_for_selector( + query=query, + page=page, + size=size, + ) \ No newline at end of file diff --git a/service/src/main/inse/projects/eu_organizations/service.py b/service/src/main/inse/projects/eu_organizations/service.py new file mode 100644 index 00000000..376cb592 --- /dev/null +++ b/service/src/main/inse/projects/eu_organizations/service.py @@ -0,0 +1,160 @@ +import logging +from typing import Dict, List, Optional + +from inse.integrations import elasticsearch +from inse.model import ESCluster, ESIndex +from inse.projects.model import ( + EuCordisOrganizationSelectorPage, + EuCordisOrganizationSelectorSummary, + EuCordisProjectType, +) + +logger = logging.getLogger(__name__) + + +def _project_type_from_org_index(index_name: str) -> Optional[EuCordisProjectType]: + if index_name == ESIndex.CORDIS_EU_FP7_ORGANIZATIONS.value: + return EuCordisProjectType.FP7 + if index_name == ESIndex.CORDIS_EU_HORIZON_2020_ORGANIZATIONS.value: + return EuCordisProjectType.H2020 + if index_name == ESIndex.CORDIS_EU_HORIZON_EUROPE_ORGANIZATIONS.value: + return EuCordisProjectType.HEU + return None + + +async def get_organizations_by_ids( + organization_ids: List[str], +) -> EuCordisOrganizationSelectorPage: + if not organization_ids: + return EuCordisOrganizationSelectorPage(elements=[], total=0, page=0, size=0) + + response = await elasticsearch.search( + index=ESIndex.CORDIS_EU_ORGANIZATIONS_WILDCARD, + cluster=ESCluster.INSE, + body={ + "size": len(organization_ids) * 3, + "_source": [ + "id", + "organisationID", + "name", + "shortName", + "country", + "city", + ], + "query": { + "terms": { + "organisationID": organization_ids + } + }, + "collapse": { + "field": "organisationID" + }, + }, + ) + + elements: List[EuCordisOrganizationSelectorSummary] = [] + + for hit in response.get("hits", {}).get("hits", []): + source = hit.get("_source", {}) + source["project_type"] = _project_type_from_org_index(hit.get("_index", "")) + elements.append(EuCordisOrganizationSelectorSummary.from_es_source(source)) + + return EuCordisOrganizationSelectorPage( + elements=elements, + total=response.get("hits", {}).get("total", {}).get("value", len(elements)), + page=0, + size=len(elements), + ) + + +async def autocomplete_organizations_for_selector( + query: str, + page: int = 0, + size: int = 10, +) -> EuCordisOrganizationSelectorPage: + if not query or not query.strip(): + return EuCordisOrganizationSelectorPage( + elements=[], + total=0, + page=page, + size=size, + ) + + query = query.strip() + + response = await elasticsearch.search( + index=ESIndex.CORDIS_EU_ORGANIZATIONS_WILDCARD, + cluster=ESCluster.INSE, + body={ + "size": size, + "from": page * size, + "_source": [ + "id", + "organisationID", + "name", + "shortName", + "country", + "city", + ], + "query": { + "bool": { + "should": [ + { + "match_phrase_prefix": { + "name": { + "query": query, + "max_expansions": 50, + } + } + }, + { + "wildcard": { + "shortName": { + "value": f"*{query}*", + "case_insensitive": True, + } + } + }, + { + "term": { + "organisationID": query, + } + }, + ], + "minimum_should_match": 1, + } + }, + "collapse": { + "field": "organisationID", + }, + "sort": [ + { + "name.keyword": { + "order": "asc", + "missing": "_last", + "unmapped_type": "keyword", + } + } + ], + }, + ) + + elements: List[EuCordisOrganizationSelectorSummary] = [] + + for hit in response.get("hits", {}).get("hits", []): + source = hit.get("_source", {}) + source["project_type"] = _project_type_from_org_index(hit.get("_index", "")) + + elements.append( + EuCordisOrganizationSelectorSummary.from_es_source( + source=source, + project_type=source["project_type"], + ) + ) + + return EuCordisOrganizationSelectorPage( + elements=elements, + total=response.get("hits", {}).get("total", {}).get("value", len(elements)), + page=page, + size=size, + ) \ No newline at end of file diff --git a/service/src/main/inse/projects/logic.py b/service/src/main/inse/projects/logic.py index 2a01e5ca..01b3fa7a 100644 --- a/service/src/main/inse/projects/logic.py +++ b/service/src/main/inse/projects/logic.py @@ -3,11 +3,11 @@ import logging from typing import Any, Dict, List, Optional, Set, Tuple from collections import defaultdict -from inse.projects.eu_cordis_projects_enrichment_client import get_enriched_cordis_project_by_id +from inse.projects.eu_cordis_projects_client import get_enriched_cordis_project_by_id from inse.integrations import elasticsearch from inse.model import ESCluster, ESIndex - +from inse.projects.model import EuCordisProjectType logger = logging.getLogger(__name__) @@ -244,3 +244,133 @@ async def get_person_institutes( "address_country_en": source.get("address_country_en"), } return result + + +#EU Cordis Projects + + + +async def get_eu_project_ids_by_openalex_topic_ids( + project_types: List[EuCordisProjectType], + topic_ids: List[str], +) -> Dict[EuCordisProjectType, List[str]]: + """ + Returns EU CORDIS project IDs whose mapped OpenAlex topic_matches contain + EVERY given topic ID. Same semantics as DFG topic filtering. + """ + if not topic_ids: + return {project_type: [] for project_type in project_types} + + required_topics = set(topic_ids) + result: Dict[EuCordisProjectType, List[str]] = {} + + for project_type in project_types: + project_topics: Dict[str, Set[str]] = defaultdict(set) + + page_size = 1000 + from_ = 0 + + while True: + body = { + "size": page_size, + "from": from_, + "_source": ["project_id", "topic_matches"], + "query": { + "terms": { + "topic_matches.topic_id.keyword": topic_ids + } + }, + } + + response = await elasticsearch.search( + index=project_type.to_openalex_topics_index(), + cluster=ESCluster.INSE, + body=body, + ) + + hits = response.get("hits", {}).get("hits", []) + if not hits: + break + + for hit in hits: + source = hit.get("_source", {}) + project_id = source.get("project_id") + if not project_id: + continue + + topic_matches = source.get("topic_matches") or [] + if isinstance(topic_matches, dict): + topic_matches = [topic_matches] + + for match in topic_matches: + topic_id = match.get("topic_id") + if topic_id in required_topics: + project_topics[project_id].add(topic_id) + + if len(hits) < page_size: + break + + from_ += page_size + + result[project_type] = [ + project_id + for project_id, found_topics in project_topics.items() + if required_topics.issubset(found_topics) + ] + + return result + + +async def get_openalex_topics_for_eu_projects( + project_ids_by_type: Dict[EuCordisProjectType, List[str]], +) -> Dict[Tuple[EuCordisProjectType, str], List[Dict[str, Any]]]: + """ + Fetches mapped OpenAlex topic matches for EU CORDIS projects. + """ + topic_lookup: Dict[Tuple[EuCordisProjectType, str], List[Dict[str, Any]]] = {} + + for project_type, project_ids in project_ids_by_type.items(): + if not project_ids: + continue + + page_size = 1000 + from_ = 0 + + while True: + response = await elasticsearch.search( + index=project_type.to_openalex_topics_index(), + cluster=ESCluster.INSE, + body={ + "size": page_size, + "from": from_, + "_source": ["project_id", "topic_matches"], + "query": { + "terms": { + "project_id.keyword": project_ids + } + }, + }, + ) + + hits = response.get("hits", {}).get("hits", []) + if not hits: + break + + for hit in hits: + source = hit.get("_source", {}) + project_id = source.get("project_id") + if not project_id: + continue + + topic_matches = source.get("topic_matches") or [] + if isinstance(topic_matches, dict): + topic_matches = [topic_matches] + + topic_lookup.setdefault((project_type, project_id), []).extend(topic_matches) + + if len(hits) < page_size: + break + + from_ += page_size + + return topic_lookup \ No newline at end of file diff --git a/service/src/main/inse/projects/model.py b/service/src/main/inse/projects/model.py index 8284b33a..558cdadb 100644 --- a/service/src/main/inse/projects/model.py +++ b/service/src/main/inse/projects/model.py @@ -14,6 +14,7 @@ from inse.models.projects_eu_cordis.horizon_europe.heu_project_details import HE from inse.models.projects_eu_cordis.fp7.fp7_project_details import Fp7ProjectDetails from inse.models.projects_dfg_v2.project.dfg_project_fachgebiete_inner import DFGProjectFachgebieteInner from inse.models.openalex.topic import Topic, TopicDomain, TopicField, TopicSubfield +from inse.authors.v2.model import AuthorPage from typing import Union class ProjectType(StrEnum): @@ -81,11 +82,6 @@ class BundProjectList(BaseModel): ) total: int = Field(default=0, description="The total number of bund projects.") - -class EuProjectPage(Page): - elements: List[EuProject] = Field( - default_factory=list, description="The EU projects on this page." - ) class DfgInstitutionSummary(BaseModel): """A summary of a DFG institution.""" @@ -443,6 +439,12 @@ class FundingProjectPage(Page): ) +#EU CORDIS PROJECTS +class EuProjectPage(Page): + elements: List[EuProject] = Field( + default_factory=list, description="The EU projects on this page." + ) + class EuOrganizationShort(BaseModel): project_id: str = Field(description="The unique identifier of the project.") organization_id: str = Field( @@ -496,3 +498,258 @@ class EuOrganizationProjectSummaryPage(Page): default_factory=list, description="The organization project summaries on this page.", ) + + + +################ +class EuCordisProjectType(StrEnum): + FP7 = "fp7" + H2020 = "h2020" + HEU = "heu" + + def to_project_index(self) -> ESIndex: + mapping = { + self.FP7: ESIndex.CORDIS_EU_FP7_PROJECTS, + self.H2020: ESIndex.CORDIS_EU_HORIZON_2020_PROJECTS, + self.HEU: ESIndex.CORDIS_EU_HORIZON_EUROPE_PROJECTS, + } + return mapping[self] + + def to_organization_index(self) -> ESIndex: + mapping = { + self.FP7: ESIndex.CORDIS_EU_FP7_ORGANIZATIONS, + self.H2020: ESIndex.CORDIS_EU_HORIZON_2020_ORGANIZATIONS, + self.HEU: ESIndex.CORDIS_EU_HORIZON_EUROPE_ORGANIZATIONS, + } + return mapping[self] + + def to_cordis_topic_index(self) -> ESIndex: + mapping = { + self.FP7: ESIndex.CORDIS_EU_FP7_TOPICS, + self.H2020: ESIndex.CORDIS_EU_HORIZON_2020_TOPICS, + self.HEU: ESIndex.CORDIS_EU_HORIZON_EUROPE_TOPICS, + } + return mapping[self] + def to_cordis_publications_index(self) -> ESIndex: + mapping = { + self.FP7: ESIndex.CORDIS_EU_FP7_PUBLICATIONS, + self.H2020: ESIndex.CORDIS_EU_HORIZON_2020_PUBLICATIONS, + self.HEU: ESIndex.CORDIS_EU_HORIZON_EUROPE_PUBLICATIONS, + } + return mapping[self] + + def to_euroscivoc_index(self) -> ESIndex: + mapping = { + self.FP7: ESIndex.CORDIS_EU_FP7_EUROSCIVOC, + self.H2020: ESIndex.CORDIS_EU_HORIZON_2020_EUROSCIVOC, + self.HEU: ESIndex.CORDIS_EU_HORIZON_EUROPE_EUROSCIVOC, + } + return mapping[self] + + def to_openalex_topics_index(self) -> ESIndex: + mapping = { + self.FP7: ESIndex.PROJECTS_CORDIS_EU_FP7_TOPICS_MAPPING, + self.H2020: ESIndex.PROJECTS_CORDIS_EU_H2020_TOPICS, + self.HEU: ESIndex.PROJECTS_CORDIS_EU_HEUROPE_TOPICS, + } + return mapping[self] + + + @classmethod + def from_index_name(cls, index_name: str) -> "EuCordisProjectType": + if index_name == ESIndex.CORDIS_EU_FP7_PROJECTS.value: + return cls.FP7 + if index_name == ESIndex.CORDIS_EU_HORIZON_2020_PROJECTS.value: + return cls.H2020 + if index_name == ESIndex.CORDIS_EU_HORIZON_EUROPE_PROJECTS.value: + return cls.HEU + + raise ValueError(f"Unsupported EU CORDIS project index: {index_name}") + + +class EuCordisOrganizationSummary(BaseModel): + id: Optional[str] = None + organisation_id: Optional[str] = None + name: Optional[str] = None + short_name: Optional[str] = None + country: Optional[str] = None + city: Optional[str] = None + role: Optional[str] = None + activity_type: Optional[str] = None + project_id: Optional[str] = None + ec_contribution: Optional[float] = None + total_cost: Optional[float] = None + + @classmethod + def from_es_source(cls, source: Dict[str, Any]) -> "EuCordisOrganizationSummary": + return cls( + id=source.get("id"), + organisation_id=source.get("organisationID"), + name=source.get("name"), + short_name=source.get("shortName"), + country=source.get("country"), + city=source.get("city"), + role=source.get("role"), + activity_type=source.get("activityType"), + project_id=source.get("projectID"), + ec_contribution=source.get("ecContribution"), + total_cost=source.get("totalCost"), + ) + + + +class EuCordisTopicSummary(BaseModel): + id: Optional[str] = None + project_id: Optional[str] = None + title: Optional[str] = None + topic: Optional[str] = None + + @classmethod + def from_es_source(cls, source: Dict[str, Any]) -> "EuCordisTopicSummary": + return cls( + id=source.get("id"), + project_id=source.get("projectID"), + title=source.get("title"), + topic=source.get("topic"), + ) + + + +class EuCordisEurosciVocSummary(BaseModel): + id: Optional[str] = None + project_id: Optional[str] = None + code: Optional[str] = None + title: Optional[str] = None + description: Optional[str] = None + path: Optional[str] = None + + @classmethod + def from_es_source(cls, source: Dict[str, Any]) -> "EuCordisEurosciVocSummary": + return cls( + id=source.get("id"), + project_id=source.get("projectID"), + code=source.get("code"), + title=source.get("title"), + description=source.get("description"), + path=source.get("path"), + ) + + +class EuCordisProjectSummary(BaseModel): + id: str + project_type: EuCordisProjectType + + title: Optional[str] = None + acronym: Optional[str] = None + objective: Optional[str] = None + keywords: Optional[str] = None + + framework_programme: Optional[str] = None + funding_scheme: Optional[str] = None + status: Optional[str] = None + + start_date: Optional[date] = None + end_date: Optional[date] = None + + ec_max_contribution: Optional[float] = None + total_cost: Optional[float] = None + authors: Optional[AuthorPage] = None + organizations: List[EuCordisOrganizationSummary] = Field(default_factory=list) + cordis_topics: List[EuCordisTopicSummary] = Field(default_factory=list) + eurosci_voc: List[EuCordisEurosciVocSummary] = Field(default_factory=list) + topics: List[Topic] = Field(default_factory=list, description="Mapped OpenAlex topics.") + + @classmethod + def from_hit( + cls, + hit: Dict[str, Any], + authors: Optional[AuthorPage] = None, + organizations: Optional[List[EuCordisOrganizationSummary]] = None, + cordis_topics: Optional[List[EuCordisTopicSummary]] = None, + eurosci_voc: Optional[List[EuCordisEurosciVocSummary]] = None, + topics: Optional[List[Topic]] = None, + ) -> "EuCordisProjectSummary": + source = hit.get("_source", {}) + project_type = EuCordisProjectType.from_index_name(hit.get("_index", "")) + + return cls( + id=source.get("id") or hit.get("_id", ""), + project_type=project_type, + + title=source.get("title"), + acronym=source.get("acronym"), + objective=source.get("objective"), + keywords=source.get("keywords"), + + framework_programme=source.get("frameworkProgramme"), + funding_scheme=source.get("fundingScheme"), + status=source.get("status"), + + start_date=source.get("startDate"), + end_date=source.get("endDate"), + + ec_max_contribution=source.get("ecMaxContribution"), + total_cost=source.get("totalCost"), + + authors=authors or None, + organizations=organizations or [], + cordis_topics=cordis_topics or [], + eurosci_voc=eurosci_voc or [], + topics=topics or [], + ) + + @staticmethod + def topic_from_match(match: Dict[str, Any]) -> Topic: + domain_name = match.get("domain") + field_name = match.get("field") + subfield_name = match.get("subfield") + + domain = TopicDomain(display_name=domain_name) if domain_name else None + field = TopicField(display_name=field_name) if field_name else None + subfield = TopicSubfield(display_name=subfield_name) if subfield_name else None + + return Topic( + id=match.get("topic_id"), + display_name=match.get("topic_display_name"), + domain=domain, + field=field, + subfield=subfield, + ) + + +class EuCordisProjectSearchPage(Page): + elements: List[EuCordisProjectSummary] = Field( + default_factory=list, + description="The EU CORDIS project summaries on this page.", + ) + + +class EuCordisOrganizationSelectorSummary(BaseModel): + id: Optional[str] = None + organisation_id: Optional[str] = None + name: Optional[str] = None + short_name: Optional[str] = None + country: Optional[str] = None + city: Optional[str] = None + project_type: Optional[EuCordisProjectType] = None + + @classmethod + def from_es_source( + cls, + source: Dict[str, Any], + project_type: Optional[EuCordisProjectType] = None, + ) -> "EuCordisOrganizationSelectorSummary": + return cls( + id=source.get("id"), + organisation_id=source.get("organisationID"), + name=source.get("name"), + short_name=source.get("shortName"), + country=source.get("country"), + city=source.get("city"), + project_type=project_type, + ) + + + +class EuCordisOrganizationSelectorPage(Page): + elements: List[EuCordisOrganizationSelectorSummary] = Field(default_factory=list) \ No newline at end of file diff --git a/service/src/main/inse/projects/projects_search_client.py b/service/src/main/inse/projects/projects_search_client.py index 3a0a7557..7404421a 100644 --- a/service/src/main/inse/projects/projects_search_client.py +++ b/service/src/main/inse/projects/projects_search_client.py @@ -21,7 +21,7 @@ from inse.projects.model import ( ProjectsSortBy, SortDirection, ) -from inse.projects.eu_cordis_projects_enrichment_client import get_enriched_cordis_project_by_id +from inse.projects.eu_cordis_projects_client import get_enriched_cordis_project_by_id from inse.models.dfg_project_details import DfgProjectDetails from inse.models.bund_project_details import BundProjectDetails from inse.models.cordis_eu_project import CordisEuProject @@ -505,8 +505,32 @@ async def get_cordis_eu_publications_by_dois(dois: List[str]): Returns: _type_: The retrieved publications. """ - raw_dois = [_get_raw_doi(doi) for doi in dois] - query = {"bool": {"filter": [{"terms": {"qaProcessedDoi": raw_dois}}]}} + + query_dois = list({ + variant + for doi in dois + for variant in ( + _get_raw_doi(doi), + _get_raw_doi(doi).lower(), + _get_raw_doi(doi).upper(), + ) + }) + + query = { + "bool": { + "filter": [ + { + "bool": { + "should": [ + {"terms": {"doi": query_dois}}, + {"terms": {"qaProcessedDoi": query_dois}}, + ], + "minimum_should_match": 1, + } + } + ] + } + } response = await elasticsearch.search( query=query, diff --git a/service/src/main/inse/projects/router.py b/service/src/main/inse/projects/router.py index 699b4d22..8fbc5f70 100644 --- a/service/src/main/inse/projects/router.py +++ b/service/src/main/inse/projects/router.py @@ -134,7 +134,148 @@ async def get_single_bund_project( return await projects_service.get_single_bund_project( project_id=id, ) + + +######## +from inse.projects.model import EuCordisProjectSearchPage, EuCordisProjectType +from inse.projects.service import search_eu_cordis_projects_summary_impl +@router.get( + "/eu/search", + summary="Search EU CORDIS projects.", + description="Returns a page of EU CORDIS project summaries across FP7, Horizon 2020 and Horizon Europe.", + operation_id="searchEuCordisProjectsSummary", + responses={ + status.HTTP_200_OK: { + "description": "Successful Response", + "model": EuCordisProjectSearchPage, + }, + }, + response_model_by_alias=False, +) +async def search_eu_cordis_projects_summary( + author_id: Annotated[ + Optional[str], + Query(description="OpenAlex author ID to filter by."), + ] = None, + author_ids: Annotated[ + Optional[List[str]], + Query(description="Additional OpenAlex author IDs to filter by. All selected authors must match."), + ] = None, + organization_ids: Annotated[ + Optional[List[str]], + Query(description="CORDIS organisation IDs. All selected organizations must match."), + ] = None, + organization_names: Annotated[ + Optional[List[str]], + Query(description="CORDIS organization names. All selected organizations must match."), + ] = None, + project_types: Annotated[ + Optional[List[EuCordisProjectType]], + Query(description="Project types to include: fp7, h2020, heu."), + ] = None, + title: Annotated[ + Optional[str], + Query(description="Project title/acronym search."), + ] = None, + keywords: Annotated[ + Optional[List[str]], + Query(description="Raw keywords to search in title/objective/keywords/topics."), + ] = None, + topic_ids: Annotated[ + Optional[List[str]], + Query(description="OpenAlex topic IDs used for fuzzy topic resolution."), + ] = None, + filter_topic_ids: Annotated[ + Optional[List[str]], + Query(description="Additional OpenAlex topic IDs used as mandatory filters."), + ] = None, + funding_start_years: Annotated[ + Optional[List[str]], + Query(description="Funding start years."), + ] = None, + funding_end_years: Annotated[ + Optional[List[str]], + Query(description="Funding end years."), + ] = None, + countries: Annotated[ + Optional[List[str]], + Query(description="Organization countries."), + ] = None, + framework_programmes: Annotated[ + Optional[List[str]], + Query(description="Framework programme filters."), + ] = None, + funding_schemes: Annotated[ + Optional[List[str]], + Query(description="Funding scheme filters."), + ] = None, + statuses: Annotated[ + Optional[List[str]], + Query(description="Project status filters."), + ] = None, + page: Annotated[int, Query(description="The page number.", ge=0)] = 0, + size: Annotated[int, Query(description="The page size.", ge=1)] = 20, + sort_by: Annotated[str, Query(description="Sort field.")] = "title", + sort_direction: Annotated[ + str, + Query(description="Sort direction: asc or desc."), + ] = "asc", + fuzzy: Annotated[ + bool, + Query(description="Use OpenAlex topic-id resolution if true, otherwise raw keyword search."), + ] = False, +) -> EuCordisProjectSearchPage: + logger.debug( + "Received EU CORDIS search request: author_id=%s, author_ids=%s, " + "organization_ids=%s, organization_names=%s, project_types=%s, " + "title=%s, keywords=%s, topic_ids=%s, filter_topic_ids=%s, " + "funding_start_years=%s, funding_end_years=%s, countries=%s, " + "framework_programmes=%s, funding_schemes=%s, statuses=%s, " + "page=%s, size=%s, sort_by=%s, sort_direction=%s, fuzzy=%s", + author_id, + author_ids, + organization_ids, + organization_names, + project_types, + title, + keywords, + topic_ids, + filter_topic_ids, + funding_start_years, + funding_end_years, + countries, + framework_programmes, + funding_schemes, + statuses, + page, + size, + sort_by, + sort_direction, + fuzzy, + ) + return await search_eu_cordis_projects_summary_impl( + author_id=author_id, + author_ids=author_ids, + organization_ids=organization_ids, + organization_names=organization_names, + project_types=project_types, + title=title, + keywords=keywords, + topic_ids=topic_ids, + filter_topic_ids=filter_topic_ids, + funding_start_years=funding_start_years, + funding_end_years=funding_end_years, + countries=countries, + framework_programmes=framework_programmes, + funding_schemes=funding_schemes, + statuses=statuses, + page=page, + size=size, + sort_by=sort_by, + sort_direction=sort_direction, + fuzzy=fuzzy, + ) @router.get( "/eu/{id}", @@ -209,7 +350,7 @@ async def get_single_eu_cordis_project( return EuCordisProjectResponse( success=False, project_type=None, - data=None, + eu_project_data=None, error=f"Internal server error: {str(e)}" ) diff --git a/service/src/main/inse/projects/service.py b/service/src/main/inse/projects/service.py index 86637a6f..65a7ded5 100644 --- a/service/src/main/inse/projects/service.py +++ b/service/src/main/inse/projects/service.py @@ -385,7 +385,7 @@ async def get_single_eu_cordis_project( project = await projects_search_client.get_eu_cordis_projects_by_id(project_id) if not project: - raise NotFoundException(f"EU project with id {project_id} not found") + return None return project @@ -414,3 +414,98 @@ async def search_cordis_eu_projects_for_author_id( return funding_project_page + + +################ +from inse.projects.eu_cordis_projects_client import search_eu_cordis_projects +from inse.projects.model import EuCordisProjectType, EuCordisProjectSearchPage +from inse.works.logic import get_publication_dois_of_author + +async def _get_eu_project_ids_for_openalex_authors( + author_ids: List[str], +) -> Optional[List[str]]: + """ + Resolves OpenAlex authors to CORDIS EU project IDs via publication DOIs. + + Multiple authors use AND semantics: + project must be connected to publications from every selected author. + """ + author_ids = [author_id for author_id in author_ids if author_id and author_id.strip()] + if not author_ids: + return None + + project_sets: List[Set[str]] = [] + + for author_id in author_ids: + dois = await get_publication_dois_of_author(raw_oa_author_id=author_id) + if not dois: + return [] + + project_ids = await projects_search_client.get_cordis_eu_project_ids_by_dois( + dois=dois + ) + + if not project_ids: + return [] + + project_sets.append(set(project_ids)) + + if not project_sets: + return None + + return list(set.intersection(*project_sets)) + + +async def search_eu_cordis_projects_summary_impl( + page: int, + size: int, + project_types: Optional[List[EuCordisProjectType]] = None, + author_id: Optional[str] = None, + author_ids: Optional[List[str]] = None, + organization_ids: Optional[List[str]] = None, + organization_names: Optional[List[str]] = None, + keywords: Optional[List[str]] = None, + topic_ids: Optional[List[str]] = None, + filter_topic_ids: Optional[List[str]] = None, + title: Optional[str] = None, + funding_start_years: Optional[List[str]] = None, + funding_end_years: Optional[List[str]] = None, + countries: Optional[List[str]] = None, + framework_programmes: Optional[List[str]] = None, + funding_schemes: Optional[List[str]] = None, + statuses: Optional[List[str]] = None, + sort_by: str = "title", + sort_direction: str = "asc", + fuzzy: bool = False, +) -> EuCordisProjectSearchPage: + + all_author_ids: List[str] = [] + + if author_id: + all_author_ids.append(author_id) + all_author_ids.extend(author_ids or []) + author_project_ids = await _get_eu_project_ids_for_openalex_authors( + author_ids=all_author_ids + ) + + return await search_eu_cordis_projects( + page=page, + size=size, + project_types=project_types, + organization_ids=organization_ids, + organization_names=organization_names, + author_project_ids=author_project_ids, + keywords=keywords, + topic_ids=topic_ids, + filter_topic_ids=filter_topic_ids, + title=title, + funding_start_years=funding_start_years, + funding_end_years=funding_end_years, + countries=countries, + framework_programmes=framework_programmes, + funding_schemes=funding_schemes, + statuses=statuses, + sort_by=sort_by, + sort_direction=sort_direction, + fuzzy=fuzzy, + ) \ No newline at end of file diff --git a/service/src/main/inse/projects/test_eu_cordis_search_client.py b/service/src/main/inse/projects/test_eu_cordis_search_client.py new file mode 100644 index 00000000..b9bc7aa1 --- /dev/null +++ b/service/src/main/inse/projects/test_eu_cordis_search_client.py @@ -0,0 +1,364 @@ +import pytest +from inse.projects import eu_cordis_projects_client as eu_cordis_search_client + +@pytest.mark.anyio +async def test_search_eu_cordis_projects_by_title(): + """Test searching EU CORDIS projects by title.""" + res = await eu_cordis_search_client.search_eu_cordis_projects( + page=0, + size=5, + title="Artificial Intelligence", + ) + assert res is not None + assert res.total > 0 + assert len(res.elements) > 0 + for element in res.elements: + assert element.id is not None + assert element.title is not None + assert "artificial" in element.title.lower() or "intelligence" in element.title.lower() + + +@pytest.mark.anyio +async def test_search_eu_cordis_projects_by_keywords(): + """Test searching EU CORDIS projects by keywords.""" + res = await eu_cordis_search_client.search_eu_cordis_projects( + page=0, + size=5, + keywords=["machine learning", "deep learning"], + ) + assert res is not None + assert res.total > 0 + assert len(res.elements) > 0 + for element in res.elements: + assert element.id is not None + assert element.title is not None + + +@pytest.mark.anyio +async def test_search_eu_cordis_projects_by_framework_programme(): + """Test filtering EU CORDIS projects by framework programme.""" + res = await eu_cordis_search_client.search_eu_cordis_projects( + page=0, + size=5, + framework_programmes=["H2020"], + ) + assert res is not None + assert res.total > 0 + assert len(res.elements) > 0 + for element in res.elements: + assert element.id is not None + assert element.framework_programme == "H2020" + + +@pytest.mark.anyio +async def test_search_eu_cordis_projects_by_status(): + """Test filtering EU CORDIS projects by status.""" + res = await eu_cordis_search_client.search_eu_cordis_projects( + page=0, + size=5, + statuses=["SIGNED"], + ) + assert res is not None + assert res.total > 0 + assert len(res.elements) > 0 + for element in res.elements: + assert element.id is not None + assert element.status == "SIGNED" + + +@pytest.mark.anyio +async def test_search_eu_cordis_projects_by_funding_years(): + """Test filtering EU CORDIS projects by funding start years.""" + res = await eu_cordis_search_client.search_eu_cordis_projects( + page=0, + size=5, + funding_start_years=["2020"], + ) + + assert res is not None + assert res.total > 0 + assert len(res.elements) > 0 + for element in res.elements: + assert element.id is not None + assert element.start_date is not None + assert element.start_date.year == 2020 + + +@pytest.mark.anyio +async def test_search_eu_cordis_projects_by_country(): + """Test filtering EU CORDIS projects by country.""" + res = await eu_cordis_search_client.search_eu_cordis_projects( + page=0, + size=5, + countries=["DE"], + ) + assert res is not None + assert res.total > 0 + assert len(res.elements) > 0 + for element in res.elements: + assert element.id is not None + # Verify at least one organization is from Germany + assert any( + org.country == "DE" for org in element.organizations + ) + + +@pytest.mark.anyio +async def test_search_eu_cordis_projects_by_organization_name(): + """Test filtering EU CORDIS projects by organization name.""" + res = await eu_cordis_search_client.search_eu_cordis_projects( + page=0, + size=5, + organization_names=["Max Planck"], + ) + assert res is not None + assert res.total > 0 + assert len(res.elements) > 0 + for element in res.elements: + assert element.id is not None + # Verify at least one organization matches the name + assert any( + "max planck" in org.name.lower() for org in element.organizations + ) + + +@pytest.mark.anyio +async def test_search_eu_cordis_projects_by_organization_id(): + """Test filtering EU CORDIS projects by organization ID.""" + # Use a known organization ID (e.g., Max Planck Society) + known_org_id = "999990267" + res = await eu_cordis_search_client.search_eu_cordis_projects( + page=0, + size=5, + organization_ids=[known_org_id], + ) + assert res is not None + assert res.total > 0 + assert len(res.elements) > 0 + for element in res.elements: + assert element.id is not None + # Verify the organization is present in the project + assert any( + org.organisation_id == known_org_id for org in element.organizations + ) + + +@pytest.mark.anyio +async def test_search_eu_cordis_projects_by_project_type(): + """Test filtering EU CORDIS projects by project type (FP7, H2020, HEU).""" + from inse.projects.model import EuCordisProjectType + + # Test FP7 projects + res_fp7 = await eu_cordis_search_client.search_eu_cordis_projects( + page=0, + size=5, + project_types=[EuCordisProjectType.FP7], + ) + assert res_fp7 is not None + assert res_fp7.total > 0 + assert len(res_fp7.elements) > 0 + for element in res_fp7.elements: + assert element.id is not None + assert element.project_type == EuCordisProjectType.FP7 + + # Test H2020 projects + res_h2020 = await eu_cordis_search_client.search_eu_cordis_projects( + page=0, + size=5, + project_types=[EuCordisProjectType.H2020], + ) + assert res_h2020 is not None + assert res_h2020.total > 0 + assert len(res_h2020.elements) > 0 + for element in res_h2020.elements: + assert element.id is not None + assert element.project_type == EuCordisProjectType.H2020 + + +@pytest.mark.anyio +async def test_search_eu_cordis_projects_with_sorting(): + """Test sorting EU CORDIS projects.""" + # Test ascending sort by title + res_asc = await eu_cordis_search_client.search_eu_cordis_projects( + page=0, + size=5, + sort_by="title", + sort_direction="asc", + ) + assert res_asc is not None + assert len(res_asc.elements) > 0 + + titles_asc = [element.title for element in res_asc.elements] + assert titles_asc == sorted(titles_asc) + + # Test descending sort by title + res_desc = await eu_cordis_search_client.search_eu_cordis_projects( + page=0, + size=5, + sort_by="title", + sort_direction="desc", + ) + assert res_desc is not None + assert len(res_desc.elements) > 0 + + titles_desc = [element.title for element in res_desc.elements] + assert titles_desc == sorted(titles_desc, reverse=True) + + +@pytest.mark.anyio +async def test_search_eu_cordis_projects_pagination(): + """Test pagination of EU CORDIS project search results.""" + # Get first page + page1 = await eu_cordis_search_client.search_eu_cordis_projects( + page=0, + size=3, + ) + assert page1 is not None + assert len(page1.elements) <= 3 + assert page1.page == 0 + assert page1.size == 3 + + # Get second page + page2 = await eu_cordis_search_client.search_eu_cordis_projects( + page=1, + size=3, + ) + assert page2 is not None + assert len(page2.elements) <= 3 + assert page2.page == 1 + assert page2.size == 3 + + # Ensure pages don't overlap + page1_ids = {element.id for element in page1.elements} + page2_ids = {element.id for element in page2.elements} + assert page1_ids.isdisjoint(page2_ids) + + +@pytest.mark.anyio +async def test_get_enriched_cordis_project_by_id(): + """Test fetching an enriched EU CORDIS project by ID.""" + # Use a known project ID (e.g., an H2020 project) + known_id = "101016442" # Example H2020 project ID + project = await eu_cordis_search_client.get_enriched_cordis_project_by_id(known_id) + assert project is not None + assert project.id == known_id + assert project.title is not None + assert project.objective is not None + + # Verify enriched data + assert hasattr(project, 'organizations') + assert hasattr(project, 'publications') + assert hasattr(project, 'report_summaries') + assert hasattr(project, 'topics_list') + + +@pytest.mark.anyio +async def test_get_enriched_cordis_project_by_id_not_found(): + """Test fetching a non-existent EU CORDIS project.""" + project = await eu_cordis_search_client.get_enriched_cordis_project_by_id("nonexistent_id") + assert project is None + + +@pytest.mark.anyio +async def test_get_enriched_cordis_project_by_id_empty(): + """Test fetching with empty project ID.""" + project = await eu_cordis_search_client.get_enriched_cordis_project_by_id("") + assert project is None + + project = await eu_cordis_search_client.get_enriched_cordis_project_by_id(None) + assert project is None + + +@pytest.mark.anyio +async def test_get_dois_by_cordis_eu_project_id(): + """Test retrieving DOIs for a CORDIS EU project.""" + known_id = "101016442" # Example H2020 project ID + dois = await eu_cordis_search_client.get_dois_by_cordis_eu_project_id(known_id) + assert dois is not None + assert len(dois) > 0 + + +@pytest.mark.anyio +async def test_get_openalex_authors_for_cordis_project_ids(): + """Test retrieving OpenAlex authors for CORDIS project IDs.""" + project_ids = ["101016442"] # Example H2020 project ID + authors_by_project = await eu_cordis_search_client.get_openalex_authors_for_cordis_project_ids(project_ids) + assert authors_by_project is not None + assert len(authors_by_project) > 0 + + for project_id, author_page in authors_by_project.items(): + assert project_id in project_ids + assert author_page is not None + if author_page.total > 0: + for author in author_page.elements: + assert author.id is not None + assert author.display_name is not None + + +@pytest.mark.anyio +async def test_search_eu_cordis_projects_with_multiple_filters(): + """Test combining multiple filters in EU CORDIS project search.""" + res = await eu_cordis_search_client.search_eu_cordis_projects( + page=0, + size=5, + framework_programmes=["H2020"], + funding_start_years=["2020"], + countries=["US"], + statuses=["SIGNED"], + ) + assert res is not None + assert res.total > 0 + assert len(res.elements) > 0 + for element in res.elements: + assert element.id is not None + assert element.framework_programme == "H2020" + assert element.status == "SIGNED" + assert element.start_date.year == 2020 + assert any(org.country == "US" for org in element.organizations) + + +@pytest.mark.anyio +async def test_search_eu_cordis_projects_empty_results(): + """Test search that should return no results.""" + res = await eu_cordis_search_client.search_eu_cordis_projects( + page=0, + size=5, + title="ThisProjectDoesNotExistXYZ123", + ) + assert res is not None + assert res.total == 0 + assert len(res.elements) == 0 + + +@pytest.mark.anyio +async def test_search_eu_cordis_projects_by_funding_scheme(): + """Test filtering EU CORDIS projects by funding scheme.""" + res = await eu_cordis_search_client.search_eu_cordis_projects( + page=0, + size=5, + funding_schemes=["ERC-ADG"], # ERC Advanced Grant + ) + assert res is not None + assert res.total > 0 + assert len(res.elements) > 0 + for element in res.elements: + assert element.id is not None + assert element.funding_scheme == "ERC-ADG" + + +@pytest.mark.anyio +async def test_search_eu_cordis_projects_with_fuzzy_topic_search(): + """Test fuzzy search with OpenAlex topic IDs.""" + # This test requires known OpenAlex topic IDs + topic_ids = ["https://openalex.org/T12345"] # Example topic ID + res = await eu_cordis_search_client.search_eu_cordis_projects( + page=0, + size=5, + topic_ids=topic_ids, + fuzzy=True, + ) + assert res is not None + # Note: This may return 0 results if the topic ID doesn't exist + # The important thing is that it doesn't crash + assert isinstance(res.total, int) + assert isinstance(res.elements, list) \ No newline at end of file diff --git a/service/src/main/inse/works/logic.py b/service/src/main/inse/works/logic.py index ec4f16af..6384b39b 100644 --- a/service/src/main/inse/works/logic.py +++ b/service/src/main/inse/works/logic.py @@ -22,7 +22,7 @@ from inse.models.openalex.topics_by_year import TopicsByYear from inse.models.openalex.topics_by_time import TopicsByTime from inse.exceptions import MissingApiKeyError, ElasticsearchException, UpstreamAPIException from .search_client import OpenAlexWorksSearchClient - +from inse.model import ESCluster, ESIndex logger = logging.getLogger(__name__) TOPIC_DETAIL_SOURCE_FIELDS = [ @@ -183,7 +183,8 @@ async def _get_primary_topic_counts_from_es(author_id: str) -> list[dict]: try: response = await elasticsearch.search( - index=config.settings.openalex_works_search_index, + index=ESIndex.OPENALEX_WORKS_WILDCARD, + cluster=ESCluster.NES, body=body, ) except ElasticsearchException as exc: @@ -273,7 +274,8 @@ async def _get_topic_details(topic_ids: List[str]) -> dict[str, dict]: try: response = await elasticsearch.search( - index="openalex-topics", + index=ESIndex.OPENALEX_TOPICS, + cluster=ESCluster.NES, query={"terms": {"id": topic_ids}}, source=TOPIC_DETAIL_SOURCE_FIELDS, size=len(topic_ids), @@ -698,7 +700,8 @@ async def _get_publication_year_counts_from_es(author_id: str) -> tuple[list[dic try: response = await elasticsearch.search( - index=config.settings.openalex_works_search_index, + index=ESIndex.OPENALEX_WORKS_WILDCARD, + cluster=ESCluster.NES, body=body, ) except ElasticsearchException as exc: @@ -766,7 +769,8 @@ async def _get_timeline_topic_counts_from_es( try: response = await elasticsearch.search( - index=config.settings.openalex_works_search_index, + index=ESIndex.OPENALEX_WORKS_WILDCARD, + cluster=ESCluster.NES, body=body, ) except ElasticsearchException as exc: @@ -1015,11 +1019,11 @@ async def get_publication_dois_of_author( try: response = await elasticsearch.search( - index="openalex-works", + index=ESIndex.OPENALEX_WORKS_WILDCARD, source=["doi"], size=10000, query=query, - cluster="nes", + cluster=ESCluster.NES, ) except ElasticsearchException as exc: logger.exception("Request for publication DOIs of author failed.") diff --git a/webapp/src/app/api/.openapi-generator/FILES b/webapp/src/app/api/.openapi-generator/FILES index bcaf568d..9122548b 100644 --- a/webapp/src/app/api/.openapi-generator/FILES +++ b/webapp/src/app/api/.openapi-generator/FILES @@ -22,6 +22,7 @@ api/patents.service.ts api/personNetwork.service.ts api/persons.service.ts api/projects.service.ts +api/ranking.service.ts api/topics.service.ts api/topicsV2.service.ts api/universityRankings.service.ts @@ -40,11 +41,15 @@ model/author.ts model/authorAffiliationsInner.ts model/authorCountsByYearInner.ts model/authorIds.ts +model/authorMetricsRequest.ts model/authorNetworkNode.ts model/authorPage.ts model/authorParsedLongestName.ts model/authorPositionCount.ts +model/authorStaticStats.ts model/authorSummaryStats.ts +model/authorTopicProfile.ts +model/authorTopicStats.ts model/authorsFilterProperties.ts model/authorsListResponse.ts model/authorship.ts @@ -63,11 +68,13 @@ model/bundProject.ts model/bundProjectDetails.ts model/bundProjectPage.ts model/careerMetrics.ts +model/careerStage.ts model/collaborationNetwork.ts model/collaborationNetworkEdge.ts model/collaborationNetworkNodeType.ts model/companyConnection.ts model/companyConnectionsResponse.ts +model/companyStatusFilter.ts model/cordisEuProject.ts model/cordisEuProjectPage.ts model/costUsd.ts @@ -90,7 +97,15 @@ model/dfgPersonSummaryPage.ts model/dfgProjectDetails.ts model/dfgProjectPage.ts model/dfgProjectSummary.ts +model/euCordisEurosciVocSummary.ts +model/euCordisOrganizationSelectorPage.ts +model/euCordisOrganizationSelectorSummary.ts +model/euCordisOrganizationSummary.ts model/euCordisProjectResponse.ts +model/euCordisProjectSearchPage.ts +model/euCordisProjectSummary.ts +model/euCordisProjectType.ts +model/euCordisTopicSummary.ts model/euOrganizationProjectSummary.ts model/euOrganizationProjectSummaryPage.ts model/euProjectData.ts @@ -100,6 +115,7 @@ model/extractedKeywordsResponse.ts model/fileUpload.ts model/filterInformation.ts model/filterProperties.ts +model/filterType.ts model/fp7EurosciVoc.ts model/fp7LegalBasis.ts model/fp7Organization.ts @@ -151,11 +167,13 @@ model/ipcClassification.ts model/keywordEntry.ts model/keywordEntryWithTopic.ts model/keywordEvidence.ts +model/keywordOperator.ts model/keywordPatentLevel.ts model/keywordPatentMappingStatus.ts model/keywordPatentMatch.ts model/keywordPatentSearchDiagnostics.ts model/keywordPatentSearchItem.ts +model/keywordToAuthorRequest.ts model/keywordTopicMatch.ts model/keywords.ts model/keywordsRequest.ts @@ -195,11 +213,17 @@ model/projectsFilteringProperties.ts model/projectsSortBy.ts model/publicationDetailByFunder.ts model/publicationIdsByAuthorPosition.ts +model/publicationType.ts model/publicationsByAuthorResponse.ts +model/rankedAuthor.ts model/rankingResponse.ts +model/rankingWeights.ts model/rebuildResponse.ts model/score.ts +model/selectedAuthorsRequest.ts model/sortDirection.ts +model/subfieldShare.ts +model/timespan.ts model/tokenType.ts model/topAuthor.ts model/topAuthorStatistics.ts diff --git a/webapp/src/app/api/api/projects.service.ts b/webapp/src/app/api/api/projects.service.ts index 57111cb9..a63fc5bc 100644 --- a/webapp/src/app/api/api/projects.service.ts +++ b/webapp/src/app/api/api/projects.service.ts @@ -33,8 +33,14 @@ import { DfgProjectDetails } from '../model/dfgProjectDetails'; // @ts-ignore import { DfgProjectPage } from '../model/dfgProjectPage'; // @ts-ignore +import { EuCordisOrganizationSelectorPage } from '../model/euCordisOrganizationSelectorPage'; +// @ts-ignore import { EuCordisProjectResponse } from '../model/euCordisProjectResponse'; // @ts-ignore +import { EuCordisProjectSearchPage } from '../model/euCordisProjectSearchPage'; +// @ts-ignore +import { EuCordisProjectType } from '../model/euCordisProjectType'; +// @ts-ignore import { EuOrganizationProjectSummaryPage } from '../model/euOrganizationProjectSummaryPage'; // @ts-ignore import { FundingProjectPage } from '../model/fundingProjectPage'; @@ -331,6 +337,238 @@ export class ProjectsService extends BaseService { ); } + /** + * Returns EU CORDIS organizations based on a search term. + * @endpoint get /api/eu/organizations/autocomplete/selector + * @param query Search term for organization autocomplete. + * @param page + * @param size + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public getEuOrganizationAutocompleteForSelector( + query?: string, + page?: number, + size?: number, + observe?: 'body', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable; + public getEuOrganizationAutocompleteForSelector( + query?: string, + page?: number, + size?: number, + observe?: 'response', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public getEuOrganizationAutocompleteForSelector( + query?: string, + page?: number, + size?: number, + observe?: 'events', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public getEuOrganizationAutocompleteForSelector( + query?: string, + page?: number, + size?: number, + observe: any = 'body', + reportProgress: boolean = false, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable { + let localVarQueryParameters = new HttpParams({ encoder: this.encoder }); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + query, + 'query', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + page, + 'page', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + size, + 'size', + ); + + let localVarHeaders = this.defaultHeaders; + + const localVarHttpHeaderAcceptSelected: string | undefined = + options?.httpHeaderAccept ?? + this.configuration.selectHeaderAccept(['application/json']); + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set( + 'Accept', + localVarHttpHeaderAcceptSelected, + ); + } + + const localVarHttpContext: HttpContext = + options?.context ?? new HttpContext(); + + const localVarTransferCache: boolean = options?.transferCache ?? true; + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if ( + this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected) + ) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/api/eu/organizations/autocomplete/selector`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request( + 'get', + `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + params: localVarQueryParameters, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined + ? { transferCache: localVarTransferCache } + : {}), + reportProgress: reportProgress, + }, + ); + } + + /** + * Returns EU CORDIS organizations by organisation IDs. + * @endpoint get /api/eu/organizations/ids + * @param organizationIds CORDIS organisation IDs to retrieve. + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public getEuOrganizationsByIds( + organizationIds?: Array, + observe?: 'body', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable; + public getEuOrganizationsByIds( + organizationIds?: Array, + observe?: 'response', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public getEuOrganizationsByIds( + organizationIds?: Array, + observe?: 'events', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public getEuOrganizationsByIds( + organizationIds?: Array, + observe: any = 'body', + reportProgress: boolean = false, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable { + let localVarQueryParameters = new HttpParams({ encoder: this.encoder }); + if (organizationIds) { + organizationIds.forEach((element) => { + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + element, + 'organization_ids', + ); + }); + } + + let localVarHeaders = this.defaultHeaders; + + const localVarHttpHeaderAcceptSelected: string | undefined = + options?.httpHeaderAccept ?? + this.configuration.selectHeaderAccept(['application/json']); + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set( + 'Accept', + localVarHttpHeaderAcceptSelected, + ); + } + + const localVarHttpContext: HttpContext = + options?.context ?? new HttpContext(); + + const localVarTransferCache: boolean = options?.transferCache ?? true; + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if ( + this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected) + ) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/api/eu/organizations/ids`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request( + 'get', + `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + params: localVarQueryParameters, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined + ? { transferCache: localVarTransferCache } + : {}), + reportProgress: reportProgress, + }, + ); + } + /** * Get EU projects for an author. * Returns a list of EU projects associated with the specified author ID. @@ -1201,6 +1439,353 @@ export class ProjectsService extends BaseService { ); } + /** + * Search EU CORDIS projects. + * Returns a page of EU CORDIS project summaries across FP7, Horizon 2020 and Horizon Europe. + * @endpoint get /api/projects/eu/search + * @param authorId OpenAlex author ID to filter by. + * @param authorIds Additional OpenAlex author IDs to filter by. All selected authors must match. + * @param organizationIds CORDIS organisation IDs. All selected organizations must match. + * @param organizationNames CORDIS organization names. All selected organizations must match. + * @param projectTypes Project types to include: fp7, h2020, heu. + * @param title Project title/acronym search. + * @param keywords Raw keywords to search in title/objective/keywords/topics. + * @param topicIds OpenAlex topic IDs used for fuzzy topic resolution. + * @param filterTopicIds Additional OpenAlex topic IDs used as mandatory filters. + * @param fundingStartYears Funding start years. + * @param fundingEndYears Funding end years. + * @param countries Organization countries. + * @param frameworkProgrammes Framework programme filters. + * @param fundingSchemes Funding scheme filters. + * @param statuses Project status filters. + * @param page The page number. + * @param size The page size. + * @param sortBy Sort field. + * @param sortDirection Sort direction: asc or desc. + * @param fuzzy Use OpenAlex topic-id resolution if true, otherwise raw keyword search. + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public searchEuCordisProjectsSummary( + authorId?: string, + authorIds?: Array, + organizationIds?: Array, + organizationNames?: Array, + projectTypes?: Array, + title?: string, + keywords?: Array, + topicIds?: Array, + filterTopicIds?: Array, + fundingStartYears?: Array, + fundingEndYears?: Array, + countries?: Array, + frameworkProgrammes?: Array, + fundingSchemes?: Array, + statuses?: Array, + page?: number, + size?: number, + sortBy?: string, + sortDirection?: string, + fuzzy?: boolean, + observe?: 'body', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable; + public searchEuCordisProjectsSummary( + authorId?: string, + authorIds?: Array, + organizationIds?: Array, + organizationNames?: Array, + projectTypes?: Array, + title?: string, + keywords?: Array, + topicIds?: Array, + filterTopicIds?: Array, + fundingStartYears?: Array, + fundingEndYears?: Array, + countries?: Array, + frameworkProgrammes?: Array, + fundingSchemes?: Array, + statuses?: Array, + page?: number, + size?: number, + sortBy?: string, + sortDirection?: string, + fuzzy?: boolean, + observe?: 'response', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public searchEuCordisProjectsSummary( + authorId?: string, + authorIds?: Array, + organizationIds?: Array, + organizationNames?: Array, + projectTypes?: Array, + title?: string, + keywords?: Array, + topicIds?: Array, + filterTopicIds?: Array, + fundingStartYears?: Array, + fundingEndYears?: Array, + countries?: Array, + frameworkProgrammes?: Array, + fundingSchemes?: Array, + statuses?: Array, + page?: number, + size?: number, + sortBy?: string, + sortDirection?: string, + fuzzy?: boolean, + observe?: 'events', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public searchEuCordisProjectsSummary( + authorId?: string, + authorIds?: Array, + organizationIds?: Array, + organizationNames?: Array, + projectTypes?: Array, + title?: string, + keywords?: Array, + topicIds?: Array, + filterTopicIds?: Array, + fundingStartYears?: Array, + fundingEndYears?: Array, + countries?: Array, + frameworkProgrammes?: Array, + fundingSchemes?: Array, + statuses?: Array, + page?: number, + size?: number, + sortBy?: string, + sortDirection?: string, + fuzzy?: boolean, + observe: any = 'body', + reportProgress: boolean = false, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable { + let localVarQueryParameters = new HttpParams({ encoder: this.encoder }); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + authorId, + 'author_id', + ); + if (authorIds) { + authorIds.forEach((element) => { + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + element, + 'author_ids', + ); + }); + } + if (organizationIds) { + organizationIds.forEach((element) => { + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + element, + 'organization_ids', + ); + }); + } + if (organizationNames) { + organizationNames.forEach((element) => { + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + element, + 'organization_names', + ); + }); + } + if (projectTypes) { + projectTypes.forEach((element) => { + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + element, + 'project_types', + ); + }); + } + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + title, + 'title', + ); + if (keywords) { + keywords.forEach((element) => { + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + element, + 'keywords', + ); + }); + } + if (topicIds) { + topicIds.forEach((element) => { + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + element, + 'topic_ids', + ); + }); + } + if (filterTopicIds) { + filterTopicIds.forEach((element) => { + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + element, + 'filter_topic_ids', + ); + }); + } + if (fundingStartYears) { + fundingStartYears.forEach((element) => { + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + element, + 'funding_start_years', + ); + }); + } + if (fundingEndYears) { + fundingEndYears.forEach((element) => { + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + element, + 'funding_end_years', + ); + }); + } + if (countries) { + countries.forEach((element) => { + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + element, + 'countries', + ); + }); + } + if (frameworkProgrammes) { + frameworkProgrammes.forEach((element) => { + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + element, + 'framework_programmes', + ); + }); + } + if (fundingSchemes) { + fundingSchemes.forEach((element) => { + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + element, + 'funding_schemes', + ); + }); + } + if (statuses) { + statuses.forEach((element) => { + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + element, + 'statuses', + ); + }); + } + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + page, + 'page', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + size, + 'size', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + sortBy, + 'sort_by', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + sortDirection, + 'sort_direction', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + fuzzy, + 'fuzzy', + ); + + let localVarHeaders = this.defaultHeaders; + + const localVarHttpHeaderAcceptSelected: string | undefined = + options?.httpHeaderAccept ?? + this.configuration.selectHeaderAccept(['application/json']); + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set( + 'Accept', + localVarHttpHeaderAcceptSelected, + ); + } + + const localVarHttpContext: HttpContext = + options?.context ?? new HttpContext(); + + const localVarTransferCache: boolean = options?.transferCache ?? true; + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if ( + this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected) + ) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/api/projects/eu/search`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request( + 'get', + `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + params: localVarQueryParameters, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined + ? { transferCache: localVarTransferCache } + : {}), + reportProgress: reportProgress, + }, + ); + } + /** * Search projects across all funders. * Returns a page of projects across all funders based on the provided pagination parameters and optional institution filter. diff --git a/webapp/src/app/api/model/careerStage.ts b/webapp/src/app/api/model/careerStage.ts new file mode 100644 index 00000000..d2a4e844 --- /dev/null +++ b/webapp/src/app/api/model/careerStage.ts @@ -0,0 +1,20 @@ +/** + * Innovation Search Engine API + * + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +export const CareerStage = { + Unknown: 'unknown', + Early: 'Early', + Emerging: 'Emerging', + Established: 'Established', + Senior: 'Senior' +} as const; +export type CareerStage = typeof CareerStage[keyof typeof CareerStage]; + diff --git a/webapp/src/app/api/model/companyStatusFilter.ts b/webapp/src/app/api/model/companyStatusFilter.ts new file mode 100644 index 00000000..7d4355e7 --- /dev/null +++ b/webapp/src/app/api/model/companyStatusFilter.ts @@ -0,0 +1,18 @@ +/** + * Innovation Search Engine API + * + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +export const CompanyStatusFilter = { + All: 'all', + Active: 'active', + Deleted: 'deleted' +} as const; +export type CompanyStatusFilter = typeof CompanyStatusFilter[keyof typeof CompanyStatusFilter]; + diff --git a/webapp/src/app/api/model/dfgProjectSummary.ts b/webapp/src/app/api/model/dfgProjectSummary.ts index cc1d2b59..c68e8926 100644 --- a/webapp/src/app/api/model/dfgProjectSummary.ts +++ b/webapp/src/app/api/model/dfgProjectSummary.ts @@ -1,7 +1,7 @@ /** * Innovation Search Engine API * - * + * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech @@ -12,28 +12,30 @@ import { DFGProjectFachgebieteInner } from './dFGProjectFachgebieteInner'; import { Topic } from './topic'; import { DfgPersonSummary } from './dfgPersonSummary'; -export interface DfgProjectSummary { - /** - * The unique identifier of the DFG project. - */ - id: string; - link?: string | null; - title?: string | null; - professional_classification?: string | null; - funding_start?: string | null; - funding_end?: string | null; - /** - * Institutions associated with the project. - */ - institutions?: Array; - /** - * The names of the persons involved in the DFG project. - */ - names?: Array; - /** - * The persons involved in the DFG project. - */ - persons?: Array; - subject_classifications?: Array | null; - topics?: Array | null; + +export interface DfgProjectSummary { + /** + * The unique identifier of the DFG project. + */ + id: string; + link?: string | null; + title?: string | null; + professional_classification?: string | null; + funding_start?: string | null; + funding_end?: string | null; + /** + * Institutions associated with the project. + */ + institutions?: Array; + /** + * The names of the persons involved in the DFG project. + */ + names?: Array; + /** + * The persons involved in the DFG project. + */ + persons?: Array; + subject_classifications?: Array | null; + topics?: Array | null; } + diff --git a/webapp/src/app/api/model/euCordisEurosciVocSummary.ts b/webapp/src/app/api/model/euCordisEurosciVocSummary.ts new file mode 100644 index 00000000..c45f9b09 --- /dev/null +++ b/webapp/src/app/api/model/euCordisEurosciVocSummary.ts @@ -0,0 +1,20 @@ +/** + * Innovation Search Engine API + * + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +export interface EuCordisEurosciVocSummary { + id?: string | null; + project_id?: string | null; + code?: string | null; + title?: string | null; + description?: string | null; + path?: string | null; +} + diff --git a/webapp/src/app/api/model/euCordisOrganizationSelectorPage.ts b/webapp/src/app/api/model/euCordisOrganizationSelectorPage.ts new file mode 100644 index 00000000..824bf430 --- /dev/null +++ b/webapp/src/app/api/model/euCordisOrganizationSelectorPage.ts @@ -0,0 +1,28 @@ +/** + * Innovation Search Engine API + * + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ +import { EuCordisOrganizationSelectorSummary } from './euCordisOrganizationSelectorSummary'; + + +export interface EuCordisOrganizationSelectorPage { + /** + * The current page number. + */ + page?: number; + /** + * The requested page size. + */ + size?: number; + /** + * The total number of items. + */ + total?: number; + elements?: Array; +} + diff --git a/webapp/src/app/api/model/euCordisOrganizationSelectorSummary.ts b/webapp/src/app/api/model/euCordisOrganizationSelectorSummary.ts new file mode 100644 index 00000000..647c7a90 --- /dev/null +++ b/webapp/src/app/api/model/euCordisOrganizationSelectorSummary.ts @@ -0,0 +1,25 @@ +/** + * Innovation Search Engine API + * + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ +import { EuCordisProjectType } from './euCordisProjectType'; + + +export interface EuCordisOrganizationSelectorSummary { + id?: string | null; + organisation_id?: string | null; + name?: string | null; + short_name?: string | null; + country?: string | null; + city?: string | null; + project_type?: EuCordisProjectType | null; +} +export namespace EuCordisOrganizationSelectorSummary { +} + + diff --git a/webapp/src/app/api/model/euCordisOrganizationSummary.ts b/webapp/src/app/api/model/euCordisOrganizationSummary.ts new file mode 100644 index 00000000..7fe70356 --- /dev/null +++ b/webapp/src/app/api/model/euCordisOrganizationSummary.ts @@ -0,0 +1,25 @@ +/** + * Innovation Search Engine API + * + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +export interface EuCordisOrganizationSummary { + id?: string | null; + organisation_id?: string | null; + name?: string | null; + short_name?: string | null; + country?: string | null; + city?: string | null; + role?: string | null; + activity_type?: string | null; + project_id?: string | null; + ec_contribution?: number | null; + total_cost?: number | null; +} + diff --git a/webapp/src/app/api/model/euCordisProjectSearchPage.ts b/webapp/src/app/api/model/euCordisProjectSearchPage.ts new file mode 100644 index 00000000..c78066c6 --- /dev/null +++ b/webapp/src/app/api/model/euCordisProjectSearchPage.ts @@ -0,0 +1,31 @@ +/** + * Innovation Search Engine API + * + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ +import { EuCordisProjectSummary } from './euCordisProjectSummary'; + + +export interface EuCordisProjectSearchPage { + /** + * The current page number. + */ + page?: number; + /** + * The requested page size. + */ + size?: number; + /** + * The total number of items. + */ + total?: number; + /** + * The EU CORDIS project summaries on this page. + */ + elements?: Array; +} + diff --git a/webapp/src/app/api/model/euCordisProjectSummary.ts b/webapp/src/app/api/model/euCordisProjectSummary.ts new file mode 100644 index 00000000..41197749 --- /dev/null +++ b/webapp/src/app/api/model/euCordisProjectSummary.ts @@ -0,0 +1,44 @@ +/** + * Innovation Search Engine API + * + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ +import { EuCordisTopicSummary } from './euCordisTopicSummary'; +import { AuthorPage } from './authorPage'; +import { EuCordisEurosciVocSummary } from './euCordisEurosciVocSummary'; +import { Topic } from './topic'; +import { EuCordisOrganizationSummary } from './euCordisOrganizationSummary'; +import { EuCordisProjectType } from './euCordisProjectType'; + + +export interface EuCordisProjectSummary { + id: string; + project_type: EuCordisProjectType; + title?: string | null; + acronym?: string | null; + objective?: string | null; + keywords?: string | null; + framework_programme?: string | null; + funding_scheme?: string | null; + status?: string | null; + start_date?: string | null; + end_date?: string | null; + ec_max_contribution?: number | null; + total_cost?: number | null; + authors?: AuthorPage | null; + organizations?: Array; + cordis_topics?: Array; + eurosci_voc?: Array; + /** + * Mapped OpenAlex topics. + */ + topics?: Array; +} +export namespace EuCordisProjectSummary { +} + + diff --git a/webapp/src/app/api/model/euCordisProjectType.ts b/webapp/src/app/api/model/euCordisProjectType.ts new file mode 100644 index 00000000..7720922b --- /dev/null +++ b/webapp/src/app/api/model/euCordisProjectType.ts @@ -0,0 +1,18 @@ +/** + * Innovation Search Engine API + * + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +export const EuCordisProjectType = { + Fp7: 'fp7', + H2020: 'h2020', + Heu: 'heu' +} as const; +export type EuCordisProjectType = typeof EuCordisProjectType[keyof typeof EuCordisProjectType]; + diff --git a/webapp/src/app/api/model/euCordisTopicSummary.ts b/webapp/src/app/api/model/euCordisTopicSummary.ts new file mode 100644 index 00000000..c13fbb8b --- /dev/null +++ b/webapp/src/app/api/model/euCordisTopicSummary.ts @@ -0,0 +1,18 @@ +/** + * Innovation Search Engine API + * + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +export interface EuCordisTopicSummary { + id?: string | null; + project_id?: string | null; + title?: string | null; + topic?: string | null; +} + diff --git a/webapp/src/app/api/model/filterType.ts b/webapp/src/app/api/model/filterType.ts new file mode 100644 index 00000000..bee9d0d7 --- /dev/null +++ b/webapp/src/app/api/model/filterType.ts @@ -0,0 +1,17 @@ +/** + * Innovation Search Engine API + * + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +export const FilterType = { + Keyword: 'keyword', + Topic: 'topic' +} as const; +export type FilterType = typeof FilterType[keyof typeof FilterType]; + diff --git a/webapp/src/app/api/model/keywordOperator.ts b/webapp/src/app/api/model/keywordOperator.ts new file mode 100644 index 00000000..d4d4bf1f --- /dev/null +++ b/webapp/src/app/api/model/keywordOperator.ts @@ -0,0 +1,17 @@ +/** + * Innovation Search Engine API + * + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +export const KeywordOperator = { + And: 'and', + Or: 'or' +} as const; +export type KeywordOperator = typeof KeywordOperator[keyof typeof KeywordOperator]; + diff --git a/webapp/src/app/api/model/models.ts b/webapp/src/app/api/model/models.ts index 6eefd7b1..46e3858a 100644 --- a/webapp/src/app/api/model/models.ts +++ b/webapp/src/app/api/model/models.ts @@ -57,7 +57,15 @@ export * from './dfgPersonSummaryPage'; export * from './dfgProjectDetails'; export * from './dfgProjectPage'; export * from './dfgProjectSummary'; +export * from './euCordisEurosciVocSummary'; +export * from './euCordisOrganizationSelectorPage'; +export * from './euCordisOrganizationSelectorSummary'; +export * from './euCordisOrganizationSummary'; export * from './euCordisProjectResponse'; +export * from './euCordisProjectSearchPage'; +export * from './euCordisProjectSummary'; +export * from './euCordisProjectType'; +export * from './euCordisTopicSummary'; export * from './euOrganizationProjectSummary'; export * from './euOrganizationProjectSummaryPage'; export * from './euProjectData'; diff --git a/webapp/src/app/api/model/publicationType.ts b/webapp/src/app/api/model/publicationType.ts new file mode 100644 index 00000000..753c47e8 --- /dev/null +++ b/webapp/src/app/api/model/publicationType.ts @@ -0,0 +1,39 @@ +/** + * Innovation Search Engine API + * + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +export const PublicationType = { + Article: 'article', + Other: 'other', + Dataset: 'dataset', + BookChapter: 'book-chapter', + Book: 'book', + Dissertation: 'dissertation', + Preprint: 'preprint', + Paratext: 'paratext', + Libguides: 'libguides', + Review: 'review', + Letter: 'letter', + ReferenceEntry: 'reference-entry', + Editorial: 'editorial', + PeerReview: 'peer-review', + Report: 'report', + Standard: 'standard', + Erratum: 'erratum', + Retraction: 'retraction', + SupplementaryMaterials: 'supplementary-materials', + BookSection: 'book-section', + Database: 'database', + Software: 'software', + ReportComponent: 'report-component', + Grant: 'grant' +} as const; +export type PublicationType = typeof PublicationType[keyof typeof PublicationType]; + diff --git a/webapp/src/app/api/model/selectedAuthorsRequest.ts b/webapp/src/app/api/model/selectedAuthorsRequest.ts new file mode 100644 index 00000000..79f008fe --- /dev/null +++ b/webapp/src/app/api/model/selectedAuthorsRequest.ts @@ -0,0 +1,42 @@ +/** + * Innovation Search Engine API + * + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ +import { Timespan } from './timespan'; +import { FilterType } from './filterType'; +import { KeywordOperator } from './keywordOperator'; +import { PublicationType } from './publicationType'; + + +export interface SelectedAuthorsRequest { + /** + * OpenAlex IDs of the authors to rank. + */ + author_ids: Array; + /** + * One or more keywords defining the topic. + */ + keywords: Array; + /** + * How to combine the keywords: \'and\' or \'or\'. Defaults to \'and\'. + */ + operator?: KeywordOperator; + /** + * What the \'keywords\' values match against: \'keyword\' (OpenAlex keyword display names) or \'topic\' (OpenAlex topic ids). Defaults to \'keyword\'. + */ + filter_type?: FilterType; + /** + * Optional filter: only count works of these publication types. Empty = no filter. + */ + publication_types?: Array; + timespan?: Timespan | null; +} +export namespace SelectedAuthorsRequest { +} + + diff --git a/webapp/src/app/api/model/subfieldShare.ts b/webapp/src/app/api/model/subfieldShare.ts new file mode 100644 index 00000000..83185941 --- /dev/null +++ b/webapp/src/app/api/model/subfieldShare.ts @@ -0,0 +1,22 @@ +/** + * Innovation Search Engine API + * + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +export interface SubfieldShare { + /** + * The subfield display name. + */ + name: string; + /** + * Number of works whose primary topic belongs to this subfield. + */ + count: number; +} + diff --git a/webapp/src/app/api/model/timespan.ts b/webapp/src/app/api/model/timespan.ts new file mode 100644 index 00000000..c44eee8a --- /dev/null +++ b/webapp/src/app/api/model/timespan.ts @@ -0,0 +1,22 @@ +/** + * Innovation Search Engine API + * + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +export interface Timespan { + /** + * Start year (inclusive). + */ + from: number; + /** + * End year (inclusive). + */ + to: number; +} + diff --git a/webapp/src/app/app.routes.ts b/webapp/src/app/app.routes.ts index 5afe8de7..70d53fd4 100644 --- a/webapp/src/app/app.routes.ts +++ b/webapp/src/app/app.routes.ts @@ -41,11 +41,15 @@ import { SearchResultsStateService } from './modules/keywords-search/search-resu import { roleGuard } from './shared/guards/role.guard'; import { UserRole } from './api'; import { personCordisEuProjectPageResolver } from './resolvers/person-cordis-eu-project-page.resolver'; +import { euCordisProjectsResolver } from './resolvers/eu-cordis-projects.resolver'; import { selectedAuthorsResolver } from './resolvers/selected-authors.resolver'; import { workClassificationResolver } from './resolvers/work-classification.resolver'; import { selectedDfgAuthorsResolver } from './resolvers/selected-dfg-authors.resolver'; import { selectedDfgInstitutionsResolver } from './resolvers/selected-dfg-institutions.resolver'; import { primaryCategoryYearAggregationPageResolver } from './resolvers/primary-category-year-aggregation-page.resolver'; +import { selectedEuInstitutionsResolver } from './resolvers/selected-eu-institutions.resolver'; +import { EuProjectsComponent } from './shared/ui/eu-projects/eu-projects.component'; +import { DfgProjectsComponent } from './shared/ui/dfg-projects/dfg-projects.component'; export const routes: Routes = [ { path: '', @@ -188,19 +192,41 @@ export const routes: Routes = [ { path: 'projects', component: KeywordsToProjectsResultsComponent, - runGuardsAndResolvers: 'always', - resolve: { - dfgProjectPage: dfgProjectsResolver, - personCordisEuProjectPage: personCordisEuProjectPageResolver, - selectedDfgInstitutionsPage: selectedDfgInstitutionsResolver, - selectedDfgAuthorsPage: selectedDfgAuthorsResolver, - selectedTopicsPage: selectedTopicsResolver, - selectedEuInstitutionsPage: selectedInstitutionsResolver, - selectedEuAuthorsPage: selectedAuthorsResolver, - }, - data: { - resolvingFor: RESOLVING_PROJECT_PAGE_FOR.KEYWORDS_SEARCH, - }, + children: [ + { + path: '', + pathMatch: 'full', + redirectTo: 'dfg', + }, + { + path: 'dfg', + component: DfgProjectsComponent, + resolve: { + dfgProjectPage: dfgProjectsResolver, + selectedDfgInstitutionsPage: selectedDfgInstitutionsResolver, + selectedDfgAuthorsPage: selectedDfgAuthorsResolver, + selectedTopicsPage: selectedTopicsResolver, + }, + runGuardsAndResolvers: 'always', + data: { + resolvingFor: RESOLVING_PROJECT_PAGE_FOR.KEYWORDS_SEARCH, + }, + }, + { + path: 'eu', + component: EuProjectsComponent, + resolve: { + euCordisProjectPage: euCordisProjectsResolver, + selectedEuInstitutionsPage: selectedEuInstitutionsResolver, + selectedEuAuthorsPage: selectedAuthorsResolver, + selectedTopicsPage: selectedTopicsResolver, + }, + runGuardsAndResolvers: 'always', + data: { + resolvingFor: RESOLVING_PROJECT_PAGE_FOR.KEYWORDS_SEARCH, + }, + }, + ], }, { path: 'patents', component: KeywordsToPatentsResultsComponent }, { @@ -417,19 +443,41 @@ export const routes: Routes = [ import('./modules/person-projects/person-projects.component').then( (mod) => mod.PersonProjectsComponent, ), - resolve: { - dfgProjectPage: dfgProjectsResolver, - personCordisEuProjectPage: personCordisEuProjectPageResolver, - selectedDfgInstitutionsPage: selectedDfgInstitutionsResolver, - selectedDfgAuthorsPage: selectedDfgAuthorsResolver, - selectedTopicsPage: selectedTopicsResolver, - selectedEuInstitutionsPage: selectedInstitutionsResolver, - selectedEuAuthorsPage: selectedAuthorsResolver, - }, - runGuardsAndResolvers: 'always', - data: { - resolvingFor: RESOLVING_PROJECT_PAGE_FOR.PERSON, - }, + children: [ + { + path: '', + pathMatch: 'full', + redirectTo: 'dfg', + }, + { + path: 'dfg', + component: DfgProjectsComponent, + resolve: { + dfgProjectPage: dfgProjectsResolver, + selectedDfgInstitutionsPage: selectedDfgInstitutionsResolver, + selectedDfgAuthorsPage: selectedDfgAuthorsResolver, + selectedTopicsPage: selectedTopicsResolver, + }, + runGuardsAndResolvers: 'always', + data: { + resolvingFor: RESOLVING_PROJECT_PAGE_FOR.PERSON, + }, + }, + { + path: 'eu', + component: EuProjectsComponent, + resolve: { + euCordisProjectPage: euCordisProjectsResolver, + selectedEuInstitutionsPage: selectedEuInstitutionsResolver, + selectedEuAuthorsPage: selectedAuthorsResolver, + selectedTopicsPage: selectedTopicsResolver, + }, + runGuardsAndResolvers: 'always', + data: { + resolvingFor: RESOLVING_PROJECT_PAGE_FOR.PERSON, + }, + }, + ], }, { path: 'publications', diff --git a/webapp/src/app/modules/keywords-search/keywords-search.component.ts b/webapp/src/app/modules/keywords-search/keywords-search.component.ts index b698ea4e..1e30196d 100644 --- a/webapp/src/app/modules/keywords-search/keywords-search.component.ts +++ b/webapp/src/app/modules/keywords-search/keywords-search.component.ts @@ -962,8 +962,8 @@ export class KeywordsSearchComponent { const selected = this.parseKeywordList(queryParams.get('selected')); const source = queryParams.get('source') ?? ''; const view = queryParams.get('view') ?? 'llm'; - const legend = queryParams.get('legend') ?? 'on'; - const legendExpanded = queryParams.get('legendExpanded') ?? 'off'; + const legend = queryParams.get('legend') === 'true'; + const legendExpanded = queryParams.get('legendExpanded') === 'true'; const fuzzy = queryParams.get('fuzzy') === 'true'; this.isRestoringState = true; this.form.patchValue( @@ -975,8 +975,8 @@ export class KeywordsSearchComponent { { emitEvent: false }, ); this.keywordView.set(view as KeywordView); - this.subfieldLegendVisible.set(legend === 'on'); - this.subfieldLegendExpanded.set(legendExpanded === 'on'); + this.subfieldLegendVisible.set(legend); + this.subfieldLegendExpanded.set(legendExpanded); this.extractionSource.set(source as InputMode); this.topicMappingSearch.set(fuzzy); this.restoreStateFromSession(); @@ -1036,8 +1036,8 @@ export class KeywordsSearchComponent { url: this.toNullableParam(this.form.controls.urlInput.value), text: this.toNullableParam(this.form.controls.textInput.value), view: this.keywordView(), - legend: this.subfieldLegendVisible() ? 'on' : 'off', - legendExpanded: this.subfieldLegendExpanded() ? 'on' : 'off', + legend: this.subfieldLegendVisible() ? 'true' : 'false', + legendExpanded: this.subfieldLegendExpanded() ? 'true' : 'false', broad: this.serializeKeywords( this.getKeywordLabels(this.broadKeywords()), ), diff --git a/webapp/src/app/modules/keywords-search/search-results/projects-results/projects-results.component.html b/webapp/src/app/modules/keywords-search/search-results/projects-results/projects-results.component.html index dd9481b3..3d42eb98 100644 --- a/webapp/src/app/modules/keywords-search/search-results/projects-results/projects-results.component.html +++ b/webapp/src/app/modules/keywords-search/search-results/projects-results/projects-results.component.html @@ -3,34 +3,22 @@
Projekte

Übersicht der durchgeführten Projekte.

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

Übersicht der durchgeführten Projekte.

- - - - - - - - - - - - - - + + + + + + diff --git a/webapp/src/app/modules/person-projects/person-projects.component.ts b/webapp/src/app/modules/person-projects/person-projects.component.ts index 91dda724..359a9d9c 100644 --- a/webapp/src/app/modules/person-projects/person-projects.component.ts +++ b/webapp/src/app/modules/person-projects/person-projects.component.ts @@ -1,69 +1,31 @@ -import { Component, computed, input } from '@angular/core'; -import { ActivatedRoute, Router } from '@angular/router'; -import { toSignal } from '@angular/core/rxjs-interop'; -import { DfgInstitutionSummaryPage } from '../../api/model/dfgInstitutionSummaryPage'; -import { - CordisEuProjectPage, - DfgProjectPage, - AuthorPage, - InstitutionPageV2, - TopicPageV2, - DfgPersonSummaryPage, -} from '../../api'; +import { Component } from '@angular/core'; +import { RouterLink, RouterLinkActive, RouterOutlet } from '@angular/router'; + import { MatCardModule } from '@angular/material/card'; import { MatTabsModule } from '@angular/material/tabs'; -import { ProjectFilterComponent } from '../../shared/ui/project-filters/project-filters.component'; -import { DfgProjectTableComponent } from '../../shared/ui/dfg-project-table/dfg-project-table.component'; -import { EuProjectTableComponent } from '../../shared/ui/eu-project-table/eu-project-table.component'; -import { projectQueryParamKeys } from '../../resolvers/dfg-projects.resolver'; -import { euProjectQueryParamKeys } from '../../resolvers/person-cordis-eu-project-page.resolver'; - -const PROJECT_TAB_QUERY_PARAM_KEY = 'project_type'; @Component({ selector: 'app-person-projects', + standalone: true, imports: [ MatCardModule, MatTabsModule, - ProjectFilterComponent, - DfgProjectTableComponent, - EuProjectTableComponent, + RouterOutlet, + RouterLink, + RouterLinkActive, ], templateUrl: './person-projects.component.html', styleUrl: './person-projects.component.scss', }) export class PersonProjectsComponent { - dfgProjectPage = input.required(); - personCordisEuProjectPage = input.required(); - - selectedDfgInstitutionsPage = input.required(); - selectedDfgAuthorsPage = input.required(); - selectedEuInstitutionsPage = input.required(); - selectedEuAuthorsPage = input.required(); - selectedTopicsPage = input.required(); - - readonly dfgQueryParamKeys = projectQueryParamKeys; - readonly euQueryParamKeys = euProjectQueryParamKeys; - - constructor( - private readonly router: Router, - private readonly activatedRoute: ActivatedRoute, - ) {} - - queryParamMap = toSignal(this.activatedRoute.queryParamMap, { - initialValue: this.activatedRoute.snapshot.queryParamMap, - }); - - selectedTabIndex = computed(() => { - const type = this.queryParamMap().get(PROJECT_TAB_QUERY_PARAM_KEY); - return type === 'eu' ? 1 : 0; - }); - - onTabChange(index: number): void { - const type = index === 1 ? 'eu' : 'dfg'; - this.router.navigate([], { - queryParams: { [PROJECT_TAB_QUERY_PARAM_KEY]: type }, - queryParamsHandling: 'merge', - }); - } + readonly childRoutes = [ + { + path: 'dfg', + label: 'DFG-Projekte', + }, + { + path: 'eu', + label: 'EU-Projekte', + }, + ]; } diff --git a/webapp/src/app/resolvers/dfg-projects.resolver.ts b/webapp/src/app/resolvers/dfg-projects.resolver.ts index ab88d9c7..59f06e3a 100644 --- a/webapp/src/app/resolvers/dfg-projects.resolver.ts +++ b/webapp/src/app/resolvers/dfg-projects.resolver.ts @@ -13,6 +13,8 @@ export const projectQueryParamKeys = { topicId: 'topicId', sortBy: 'sort_by', sortDirection: 'sort_direction', + legend: 'legend', + legend_expanded: 'legend_expanded', } as const; const RESOLVING_PROJECT_PAGE_FOR_KEY = 'resolvingFor'; export const RESOLVING_PROJECT_PAGE_FOR = { @@ -34,8 +36,6 @@ export const dfgProjectsResolver: ResolveFn = ( route.data, ); - const rawAuthorId = route.parent?.params['id']; - const page = Number(route.queryParamMap.get(projectQueryParamKeys.page)) || 0; const size = Number(route.queryParamMap.get(projectQueryParamKeys.size)) || 10; @@ -57,13 +57,13 @@ export const dfgProjectsResolver: ResolveFn = ( ); const institutionIds = route.queryParamMap .getAll(projectQueryParamKeys.institutionId) - .map((id) => Number(id)) - .filter((id) => !isNaN(id)); + .map((id) => Number(id)); const authorIds = route.queryParamMap .getAll(projectQueryParamKeys.authorId) - .map((id) => Number(id)) - .filter((id) => !isNaN(id)); + .map((id) => Number(id)); + if (resolvingFor === RESOLVING_PROJECT_PAGE_FOR.PERSON) { + const rawAuthorId = route.parent?.parent?.params['id']; return inject(ProjectsService).getDfgProjects( rawAuthorId, authorIds, diff --git a/webapp/src/app/resolvers/eu-cordis-projects.resolver.ts b/webapp/src/app/resolvers/eu-cordis-projects.resolver.ts new file mode 100644 index 00000000..41fc1f3b --- /dev/null +++ b/webapp/src/app/resolvers/eu-cordis-projects.resolver.ts @@ -0,0 +1,199 @@ +import { inject } from '@angular/core'; +import { ResolveFn } from '@angular/router'; +import { ProjectsService } from '../api'; +import { EuCordisProjectSearchPage } from '../api/model/euCordisProjectSearchPage'; + +export const euProjectQueryParamKeys = { + page: 'page', + size: 'size', + title: 'title', + + institutionId: 'institutionId', + + funding_start: 'funding_start', + funding_end: 'funding_end', + + authorId: 'authorId', + topicId: 'topicId', + + projectType: 'projectType', + + country: 'country', + frameworkProgramme: 'frameworkProgramme', + fundingScheme: 'fundingScheme', + status: 'status', + + sortBy: 'sort_by', + sortDirection: 'sort_direction', + + legend: 'legend', + legend_expanded: 'legend_expanded', +} as const; + +const RESOLVING_PROJECT_PAGE_FOR_KEY = 'resolvingFor'; + +export const RESOLVING_PROJECT_PAGE_FOR = { + PERSON: 'PERSON', + KEYWORDS_SEARCH: 'KEYWORDS_SEARCH', +} as const; + +type ResolvingEuProjectPageFor = + (typeof RESOLVING_PROJECT_PAGE_FOR)[keyof typeof RESOLVING_PROJECT_PAGE_FOR]; + +function getRepeatedOrCsv(routeQueryParamMap: any, key: string): string[] { + const repeatedValues = routeQueryParamMap.getAll(key) ?? []; + + const csvValues = + routeQueryParamMap + .get(key) + ?.split(',') + .map((value: string) => value.trim()) + .filter(Boolean) ?? []; + + return Array.from( + new Set( + [...repeatedValues, ...csvValues] + .map((value) => String(value).trim()) + .filter(Boolean), + ), + ); +} + +export const euCordisProjectsResolver: ResolveFn = ( + route, + state, +) => { + const resolvingFor: ResolvingEuProjectPageFor = + route.data[RESOLVING_PROJECT_PAGE_FOR_KEY] || + RESOLVING_PROJECT_PAGE_FOR.PERSON; + + console.log( + 'Resolving EU project page for', + resolvingFor, + 'with route data:', + route.data, + ); + + /** + * For EU author filtering, this should be an OpenAlex author ID. + * Backend resolves: + * OpenAlex author -> publication DOIs -> CORDIS publications -> CORDIS project IDs + */ + + 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 fundingStart = route.queryParamMap.getAll( + euProjectQueryParamKeys.funding_start, + ); + + const fundingEnd = route.queryParamMap.getAll( + euProjectQueryParamKeys.funding_end, + ); + + const filteredTopicIds = route.queryParamMap.getAll( + euProjectQueryParamKeys.topicId, + ); + + /** + * EU project types: + * fp7 | h2020 | heu + */ + const projectTypes = route.queryParamMap.getAll( + euProjectQueryParamKeys.projectType, + ); + + /** + * CORDIS organisation IDs are strings, not numeric DFG institution IDs. + */ + const organizationIds = route.queryParamMap.getAll( + euProjectQueryParamKeys.institutionId, + ); + + /** + * Additional OpenAlex author IDs from query params. + * Keep them as strings. + */ + const authorIds = route.queryParamMap + .getAll(euProjectQueryParamKeys.authorId) + .map((id) => id.split('/').pop() || id); // Extract the last part of the OpenAlex ID if it's a URL + const countries = route.queryParamMap.getAll(euProjectQueryParamKeys.country); + + const frameworkProgrammes = route.queryParamMap.getAll( + euProjectQueryParamKeys.frameworkProgramme, + ); + + const fundingSchemes = route.queryParamMap.getAll( + euProjectQueryParamKeys.fundingScheme, + ); + + const statuses = route.queryParamMap.getAll(euProjectQueryParamKeys.status); + + if (resolvingFor === RESOLVING_PROJECT_PAGE_FOR.PERSON) { + const rawAuthorId = route.parent?.parent?.params['id']; + return inject(ProjectsService).searchEuCordisProjectsSummary( + rawAuthorId, + authorIds, + organizationIds, + [], + projectTypes as any, + searchTerm, + [], + [], + filteredTopicIds, + fundingStart, + fundingEnd, + countries, + frameworkProgrammes, + fundingSchemes, + statuses, + page, + size, + sortBy, + sortDirection, + false, + ); + } + + if (resolvingFor === RESOLVING_PROJECT_PAGE_FOR.KEYWORDS_SEARCH) { + const keywords = getRepeatedOrCsv(route.queryParamMap, 'keywords'); + const selectedTopicIds = route.queryParamMap.getAll('topics'); + const fuzzySearch = route.queryParamMap.get('fuzzy') === 'true'; + + return inject(ProjectsService).searchEuCordisProjectsSummary( + undefined, + authorIds, + organizationIds, + [], + projectTypes as any, + searchTerm, + keywords, + selectedTopicIds, + filteredTopicIds, + fundingStart, + fundingEnd, + countries, + frameworkProgrammes, + fundingSchemes, + statuses, + page, + size, + sortBy, + sortDirection, + fuzzySearch, + ); + } + + throw new Error(`Unknown resolvingFor value: ${resolvingFor}`); +}; diff --git a/webapp/src/app/resolvers/selected-dfg-authors.resolver.ts b/webapp/src/app/resolvers/selected-dfg-authors.resolver.ts index c932e13d..b2c811c8 100644 --- a/webapp/src/app/resolvers/selected-dfg-authors.resolver.ts +++ b/webapp/src/app/resolvers/selected-dfg-authors.resolver.ts @@ -11,12 +11,13 @@ export const selectedDfgAuthorsResolver: ResolveFn = ( const authorIdQueryParamKey = (route.data['authorIdQueryParamKey'] as string) || 'authorId'; - const authorIds = route.queryParamMap.getAll(authorIdQueryParamKey); + const authorIds = route.queryParamMap + .getAll(authorIdQueryParamKey) + .map((id) => Number(id)) + .filter((id) => !isNaN(id)); if (authorIds.length === 0) { return { elements: [] }; } - return inject(DFGPersonsService).getDfgPersonsByIds( - authorIds.map((id) => id.trim()).filter((id) => id.length > 0), - ); + return inject(DFGPersonsService).getDfgPersonsByIds(authorIds.map(String)); }; diff --git a/webapp/src/app/resolvers/selected-eu-institutions.resolver.ts b/webapp/src/app/resolvers/selected-eu-institutions.resolver.ts new file mode 100644 index 00000000..b2ad9206 --- /dev/null +++ b/webapp/src/app/resolvers/selected-eu-institutions.resolver.ts @@ -0,0 +1,17 @@ +import { inject } from '@angular/core'; +import { ResolveFn } from '@angular/router'; +import { ProjectsService } from '../api'; +import { EuCordisOrganizationSelectorPage } from '../api/model/euCordisOrganizationSelectorPage'; +export const selectedEuInstitutionsResolver: ResolveFn< + EuCordisOrganizationSelectorPage +> = (route, state) => { + const institutionIdQueryParamKey = + (route.data['institutionIdQueryParamKey'] as string) || 'institutionId'; + + const institutionIds = route.queryParamMap + .getAll(institutionIdQueryParamKey) + .map((id) => id.trim()) + .filter((id) => id.length > 0); + + return inject(ProjectsService).getEuOrganizationsByIds(institutionIds); +}; diff --git a/webapp/src/app/shared/ui/dfg-project-table/dfg-project-table.component.ts b/webapp/src/app/shared/ui/dfg-project-table/dfg-project-table.component.ts index dc166678..f0d4906e 100644 --- a/webapp/src/app/shared/ui/dfg-project-table/dfg-project-table.component.ts +++ b/webapp/src/app/shared/ui/dfg-project-table/dfg-project-table.component.ts @@ -94,7 +94,6 @@ export class DfgProjectTableComponent implements OnInit { }); ngOnInit(): void { - console.log('DFG PROJECTS', this.page()); this.columns = [ { id: 'title', header: 'Titel', type: 'accessor', accessorKey: 'title' }, { @@ -126,8 +125,7 @@ export class DfgProjectTableComponent implements OnInit { { id: 'professional_classification', header: 'Fachliche Zuordnung', - type: 'accessor', - accessorKey: 'professional_classification', + type: 'display', cellTemplate: this.detailRowTmp(), }, diff --git a/webapp/src/app/shared/ui/dfg-projects/dfg-projects.component.html b/webapp/src/app/shared/ui/dfg-projects/dfg-projects.component.html new file mode 100644 index 00000000..13fb5295 --- /dev/null +++ b/webapp/src/app/shared/ui/dfg-projects/dfg-projects.component.html @@ -0,0 +1,20 @@ +
+ + + +
diff --git a/webapp/src/app/shared/ui/dfg-projects/dfg-projects.component.scss b/webapp/src/app/shared/ui/dfg-projects/dfg-projects.component.scss new file mode 100644 index 00000000..e69de29b diff --git a/webapp/src/app/shared/ui/dfg-projects/dfg-projects.component.ts b/webapp/src/app/shared/ui/dfg-projects/dfg-projects.component.ts new file mode 100644 index 00000000..4e82df6b --- /dev/null +++ b/webapp/src/app/shared/ui/dfg-projects/dfg-projects.component.ts @@ -0,0 +1,47 @@ +import { Component, computed, input } from '@angular/core'; +import { ActivatedRoute, Router } from '@angular/router'; +import { toSignal } from '@angular/core/rxjs-interop'; +import { DfgPersonSummaryPage, TopicPageV2 } from '../../../api'; +import { DfgProjectPage } from '../../../api/model/dfgProjectPage'; +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 { DfgProjectTableComponent } from '../dfg-project-table/dfg-project-table.component'; +import { projectQueryParamKeys } from '../../../resolvers/dfg-projects.resolver'; + +@Component({ + selector: 'app-dfg-projects', + imports: [ + MatCardModule, + MatTabsModule, + ProjectFilterComponent, + DfgProjectTableComponent, + ], + templateUrl: './dfg-projects.component.html', + styleUrl: './dfg-projects.component.scss', +}) +export class DfgProjectsComponent { + dfgProjectPage = input.required(); + + selectedDfgInstitutionsPage = input.required(); + selectedDfgAuthorsPage = input.required(); + + selectedTopicsPage = input.required(); + + readonly dfgQueryParamKeys = projectQueryParamKeys; + + constructor( + private readonly router: Router, + private readonly activatedRoute: ActivatedRoute, + ) {} + ngOnInit(): void { + console.log('DFG PROJECTS', this.dfgProjectPage()); + } + queryParamMap = toSignal(this.activatedRoute.queryParamMap, { + initialValue: this.activatedRoute.snapshot.queryParamMap, + }); + readonly fuzzySearch = computed( + () => this.queryParamMap().get('fuzzy') === 'true', + ); +} diff --git a/webapp/src/app/shared/ui/eu-project-table/eu-project-table.component.html b/webapp/src/app/shared/ui/eu-project-table/eu-project-table.component.html index 46ba403b..47dc0938 100644 --- a/webapp/src/app/shared/ui/eu-project-table/eu-project-table.component.html +++ b/webapp/src/app/shared/ui/eu-project-table/eu-project-table.component.html @@ -1,6 +1,6 @@ @@ -10,16 +10,149 @@ [queryParamSizeKey]="queryParamKeys.size" [pageSizeOptions]="[10]" /> + + @if (project.project_type) { + + } @else { + - + } + + - {{ element.startDate | date: 'dd.MM.yyyy' }} + {{ getStartDate(element) | date: 'dd.MM.yyyy' }} - {{ element.endDate | date: 'dd.MM.yyyy' }} + {{ getEndDate(element) | date: 'dd.MM.yyyy' }} - {{ element.ecMaxContribution | currency: 'EUR' : 'symbol' : '1.0-0' : 'de' }} + {{ getFundingAmount(element) | currency: 'EUR' : 'symbol' : '1.0-0' : 'de' }} + + + + @let projectAuthors = getProjectAuthors(project); + @let isExpanded = isProjectAuthorsExpanded(project); + @let visibleAuthors = + isExpanded ? projectAuthors : projectAuthors.slice(0, 3); + +
+ @for (author of visibleAuthors; track getAuthorTrackId(author, $index)) { + + } @empty { + - + } + + @if (projectAuthors.length > 3) { + + } +
+
+ + + @let organizations = getProjectOrganizations(project); + @let isExpanded = isProjectOrganizationsExpanded(project); + @let visibleOrganizations = + isExpanded ? organizations : organizations.slice(0, 3); + +
+ @for ( + organization of visibleOrganizations; + track getOrganizationId(organization) + ) { + + } @empty { + - + } + + @if (organizations.length > 3) { + + } +
+
+ + + @let projectTopics = getProjectTopics(project); + @let isExpanded = isProjectTopicsExpanded(project); + @let visibleTopics = isExpanded ? projectTopics : projectTopics.slice(0, 3); + +
+ @for (topic of visibleTopics; track topic.id ?? $index) { + + + } @empty { + - + } + + @if (projectTopics.length > 3) { + + } +
diff --git a/webapp/src/app/shared/ui/eu-project-table/eu-project-table.component.scss b/webapp/src/app/shared/ui/eu-project-table/eu-project-table.component.scss index e69de29b..4028f9e4 100644 --- a/webapp/src/app/shared/ui/eu-project-table/eu-project-table.component.scss +++ b/webapp/src/app/shared/ui/eu-project-table/eu-project-table.component.scss @@ -0,0 +1,242 @@ +.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; + } + } +} +.type-filter-btn { + display: inline-flex; + margin: 0; + padding: 0; + border: 0; + border-radius: 7px; + background: transparent; + cursor: pointer; + transition: box-shadow 0.2s ease; + + &:hover, + &:focus-visible { + outline: none; + box-shadow: 0 0 0 1px var(--sg-primary); + } + + &.active { + box-shadow: + 0 0 0 1px #ffffff, + 0 0 0 3px var(--sg-primary); + } +} + +// ------------------------ +// Responsive adjustments +// ------------------------ + +@media (max-width: 600px) { + .page { + padding: 16px; + } +} diff --git a/webapp/src/app/shared/ui/eu-project-table/eu-project-table.component.ts b/webapp/src/app/shared/ui/eu-project-table/eu-project-table.component.ts index abd257a5..d0dd36ef 100644 --- a/webapp/src/app/shared/ui/eu-project-table/eu-project-table.component.ts +++ b/webapp/src/app/shared/ui/eu-project-table/eu-project-table.component.ts @@ -2,22 +2,35 @@ import { Component, computed, input, - OnInit, TemplateRef, viewChild, + inject, } from '@angular/core'; -import { CordisEuProject, CordisEuProjectPage } from '../../../api'; + +import { ActivatedRoute, Router, RouterModule } from '@angular/router'; +import { toSignal } from '@angular/core/rxjs-interop'; + +import { MatIconModule } from '@angular/material/icon'; +import { MatButtonModule } from '@angular/material/button'; +import { MatTooltip } from '@angular/material/tooltip'; +import { CurrencyPipe, DatePipe } from '@angular/common'; + 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 { CurrencyPipe, DatePipe } from '@angular/common'; -import { QueryParamPaginatorComponent } from '../query-param-paginator/query-param-paginator.component'; -import { projectQueryParamKeys } from '../../../resolvers/dfg-projects.resolver'; +import { QueryParamPaginatorComponent } from '../query-param-paginator/query-param-paginator.component'; +import { TopicChipComponent } from '../topic-chip/topic-chip.component'; + +import { EuCordisProjectSearchPage } from '../../../api/model/euCordisProjectSearchPage'; +import { EuCordisProjectSummary } from '../../../api/model/euCordisProjectSummary'; +import { EuCordisOrganizationSummary } from '../../../api/model/euCordisOrganizationSummary'; +import { Author, Topic } from '../../../api'; + +import { euProjectQueryParamKeys } from '../../../resolvers/eu-cordis-projects.resolver'; +import { topicHierarchyColor } from '../../../resolvers/utils/topic-colors'; +import { ChipComponent } from '../chip/chip.component'; @Component({ selector: 'app-eu-project-table', imports: [ @@ -25,54 +38,450 @@ import { projectQueryParamKeys } from '../../../resolvers/dfg-projects.resolver' RouterModule, MatIconModule, MatButtonModule, + MatTooltip, DatePipe, CurrencyPipe, QueryParamPaginatorComponent, + TopicChipComponent, + ChipComponent, ], templateUrl: './eu-project-table.component.html', styleUrl: './eu-project-table.component.scss', }) -export class EuProjectTableComponent implements OnInit { - page = input.required(); - queryParamKeys = projectQueryParamKeys; +export class EuProjectTableComponent { + private readonly activatedRoute = inject(ActivatedRoute); + private readonly router = inject(Router); - elements = computed(() => this.page().elements ?? []); - total = computed(() => this.page().total ?? 0); + queryParamKeys = euProjectQueryParamKeys; - columns: GenericColumn[] = []; + page = input(); - fundingStartTmp = viewChild.required>('fundingStartTmp'); - fundingEndTmp = viewChild.required>('fundingEndTmp'); - fundingAmountTmp = viewChild.required>('fundingAmountTmp'); - actionsTmp = viewChild.required>('actionsTmp'); + authorFilterEnabled = input(false); + institutionFilterEnabled = input(false); + topicFilterEnabled = input(false); - ngOnInit(): void { - this.columns = [ - { id: 'title', header: 'Titel', type: 'accessor', accessorKey: 'title' }, - { - id: 'startDate', - header: 'Startdatum', - type: 'display', - cellTemplate: this.fundingStartTmp(), + projects = computed(() => { + return this.page()?.elements ?? []; + }); + + total = computed(() => { + return this.page()?.total ?? 0; + }); + + queryParamMap = toSignal(this.activatedRoute.queryParamMap, { + initialValue: this.activatedRoute.snapshot.queryParamMap, + }); + + selectedAuthorIdsQueryParams = computed(() => { + return this.queryParamMap().getAll(this.queryParamKeys.authorId); + }); + + selectedOrganizationIdsQueryParams = computed(() => { + return this.queryParamMap().getAll(this.queryParamKeys.institutionId); + }); + + selectedTopicIdsQueryParams = computed(() => { + return this.queryParamMap().getAll(this.queryParamKeys.topicId); + }); + selectedTypesQueryParams = computed(() => { + return this.queryParamMap().getAll(this.queryParamKeys.projectType); + }); + + projectTypeTmp = viewChild.required>('projectTypeTmp'); + fundingStartTmp = viewChild.required>('fundingStartTmp'); + fundingEndTmp = viewChild.required>('fundingEndTmp'); + fundingAmountTmp = + viewChild.required>('fundingAmountTmp'); + + authorsTmp = viewChild.required>('authorsTmp'); + organizationsTmp = + viewChild.required>('organizationsTmp'); + topicsTmp = viewChild.required>('topicsTmp'); + + actionsTmp = viewChild.required>('actionsTmp'); + + expandedProjectAuthorsIds: string[] = []; + expandedProjectOrganizationsIds: string[] = []; + expandedProjectTopicsIds: string[] = []; + + columns = computed[]>(() => [ + { + id: 'title', + header: 'Titel', + type: 'accessor', + accessorKey: 'title', + }, + { + id: 'projectType', + header: 'Typ', + type: 'accessor', + accessorKey: 'project_type', + cellTemplate: this.projectTypeTmp(), + }, + { + id: 'startDate', + header: 'Startdatum', + type: 'accessor', + accessorKey: 'start_date', + cellTemplate: this.fundingStartTmp(), + }, + { + id: 'endDate', + header: 'Enddatum', + type: 'accessor', + accessorKey: 'end_date', + cellTemplate: this.fundingEndTmp(), + }, + { + id: 'ecMaxContribution', + header: 'Förderbetrag (EU)', + type: 'accessor', + accessorKey: 'ec_max_contribution', + cellTemplate: this.fundingAmountTmp(), + }, + { + id: 'authors', + header: 'Autoren', + type: 'display', + cellTemplate: this.authorsTmp(), + }, + { + id: 'organizations', + header: 'Organisationen', + type: 'display', + cellTemplate: this.organizationsTmp(), + }, + { + id: 'topics', + header: 'Themen', + type: 'display', + cellTemplate: this.topicsTmp(), + }, + { + id: 'actions', + header: '', + type: 'display', + cellTemplate: this.actionsTmp(), + }, + ]); + getProjectTypeColor(type: string | null | undefined): string { + //console.log(type); + const normalized = (type ?? '').toLowerCase(); + if (normalized == 'fp7') return 'success'; + if (normalized == 'h2020') return 'help'; + return 'info'; + } + isTypeActive(type: string): boolean { + return this.selectedTypesQueryParams().includes(type); + } + toggleTypeFilter(type: string): void { + const selectedTypes = this.selectedTypesQueryParams(); + if (selectedTypes.includes(type)) { + this.router.navigate([], { + queryParams: { + [this.queryParamKeys.projectType]: selectedTypes.filter( + (t) => t !== type, + ), + [this.queryParamKeys.page]: 0, + }, + queryParamsHandling: 'merge', + }); + } else { + this.router.navigate([], { + queryParams: { + [this.queryParamKeys.projectType]: [...selectedTypes, type], + [this.queryParamKeys.page]: 0, + }, + queryParamsHandling: 'merge', + }); + } + } + getProjectTypeLabel(element: EuCordisProjectSummary): string { + const value = (element as any).project_type ?? (element as any).projectType; + + switch (value) { + case 'fp7': + return 'FP7'; + case 'h2020': + return 'Horizon 2020'; + case 'heu': + return 'Horizon Europe'; + default: + return value ?? ''; + } + } + + getStartDate(element: EuCordisProjectSummary): string | Date | undefined { + return (element as any).start_date ?? (element as any).startDate; + } + + getEndDate(element: EuCordisProjectSummary): string | Date | undefined { + return (element as any).end_date ?? (element as any).endDate; + } + + getFundingAmount(element: EuCordisProjectSummary): number | undefined { + return ( + (element as any).ec_max_contribution ?? (element as any).ecMaxContribution + ); + } + + private getProjectId(project: EuCordisProjectSummary): string { + return String((project as any).id ?? ''); + } + + // ------------------------- + // Authors + // ------------------------- + + getProjectAuthors(project: EuCordisProjectSummary): Author[] { + return project.authors?.elements ?? []; + } + getAuthorTrackId(author: any, index: number): string { + return String( + this.getAuthorId(author) ?? this.getAuthorName(author) ?? index, + ); + } + + getAuthorId(author: any): string | null { + const id = + author?.id ?? + author?.author_id ?? + author?.authorId ?? + author?.openalex_id ?? + author?.openAlexId; + + return id == null ? null : String(id); + } + + getAuthorName(author: any): string { + return ( + author?.display_name ?? + author?.displayName ?? + author?.full_name ?? + author?.fullName ?? + author?.name ?? + '-' + ); + } + + isAuthorActive(authorId: string | null): boolean { + return ( + !!authorId && + this.authorFilterEnabled() && + this.selectedAuthorIdsQueryParams().includes(String(authorId)) + ); + } + + getAuthorTooltipText(author: any): string { + const name = this.getAuthorName(author); + const id = this.getAuthorId(author); + + if (!id) { + return `Autor: ${name}`; + } + + if (this.authorFilterEnabled()) { + return `Nach Autor filtern: ${name}`; + } + + return `Autor: ${name}`; + } + + filterByAuthor(author: any): void { + const authorId = this.getAuthorId(author); + + if (!authorId || !this.authorFilterEnabled()) return; + + const selectedAuthorIds = this.selectedAuthorIdsQueryParams(); + + const nextIds = selectedAuthorIds.includes(authorId) + ? selectedAuthorIds.filter((id) => id !== authorId) + : [...selectedAuthorIds, authorId]; + + this.router.navigate([], { + queryParams: { + [this.queryParamKeys.authorId]: nextIds, + [this.queryParamKeys.page]: 0, }, - { - id: 'endDate', - header: 'Enddatum', - type: 'display', - cellTemplate: this.fundingEndTmp(), + queryParamsHandling: 'merge', + }); + } + + isProjectAuthorsExpanded(project: EuCordisProjectSummary): boolean { + const projectId = this.getProjectId(project); + return this.expandedProjectAuthorsIds.includes(projectId); + } + + toggleProjectAuthorsExpansion(project: EuCordisProjectSummary): void { + const projectId = this.getProjectId(project); + if (!projectId) return; + + this.expandedProjectAuthorsIds = this.expandedProjectAuthorsIds.includes( + projectId, + ) + ? this.expandedProjectAuthorsIds.filter((id) => id !== projectId) + : [...this.expandedProjectAuthorsIds, projectId]; + } + + // ------------------------- + // Organizations + // ------------------------- + + getProjectOrganizations( + project: EuCordisProjectSummary, + ): EuCordisOrganizationSummary[] { + const organizations = + (project as any).organizations ?? (project as any).organisations ?? []; + + if (!Array.isArray(organizations)) { + return []; + } + + const byId = new Map(); + + for (const organization of organizations) { + const id = this.getOrganizationId(organization); + if (!id) continue; + + byId.set(id, organization); + } + + return Array.from(byId.values()).sort((a, b) => + this.getOrganizationName(a).localeCompare(this.getOrganizationName(b)), + ); + } + + getOrganizationId( + organization: EuCordisOrganizationSummary | any, + ): string | null { + const id = organization?.organisation_id ?? organization?.id; + + return id == null ? null : String(id); + } + + getOrganizationName(organization: EuCordisOrganizationSummary | any): string { + return ( + organization?.name ?? + organization?.short_name ?? + organization?.organisation_id ?? + '-' + ); + } + + isOrganizationActive(organizationId: string | null): boolean { + return ( + !!organizationId && + this.institutionFilterEnabled() && + this.selectedOrganizationIdsQueryParams().includes(String(organizationId)) + ); + } + + getOrganizationTooltipText( + organization: EuCordisOrganizationSummary | any, + ): string { + const name = this.getOrganizationName(organization); + + if (this.institutionFilterEnabled()) { + return `Nach Organisation filtern: ${name}`; + } + + return `Organisation: ${name}`; + } + + filterByOrganization(organization: EuCordisOrganizationSummary | any): void { + const organizationId = this.getOrganizationId(organization); + + if (!organizationId || !this.institutionFilterEnabled()) return; + + const selectedOrganizationIds = this.selectedOrganizationIdsQueryParams(); + + const nextIds = selectedOrganizationIds.includes(organizationId) + ? selectedOrganizationIds.filter((id) => id !== organizationId) + : [...selectedOrganizationIds, organizationId]; + + this.router.navigate([], { + queryParams: { + [this.queryParamKeys.institutionId]: nextIds, + [this.queryParamKeys.page]: 0, }, - { - id: 'ecMaxContribution', - header: 'Förderbetrag (EU)', - type: 'display', - cellTemplate: this.fundingAmountTmp(), + queryParamsHandling: 'merge', + }); + } + + isProjectOrganizationsExpanded(project: EuCordisProjectSummary): boolean { + const projectId = this.getProjectId(project); + return this.expandedProjectOrganizationsIds.includes(projectId); + } + + toggleProjectOrganizationsExpansion(project: EuCordisProjectSummary): void { + const projectId = this.getProjectId(project); + if (!projectId) return; + + this.expandedProjectOrganizationsIds = + this.expandedProjectOrganizationsIds.includes(projectId) + ? this.expandedProjectOrganizationsIds.filter((id) => id !== projectId) + : [...this.expandedProjectOrganizationsIds, projectId]; + } + + // ------------------------- + // Topics + // ------------------------- + + getProjectTopics(project: EuCordisProjectSummary): Topic[] { + const topics = (project as any).topics ?? []; + return Array.isArray(topics) ? topics : []; + } + + 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.topicFilterEnabled() && + this.selectedTopicIdsQueryParams().includes(topic.id) + ); + } + + filterByTopic(topic: Topic): void { + if (!topic.id || !this.topicFilterEnabled()) return; + + const selectedTopicIds = this.selectedTopicIdsQueryParams(); + + const nextIds = selectedTopicIds.includes(topic.id) + ? selectedTopicIds.filter((id) => id !== topic.id) + : [...selectedTopicIds, topic.id]; + + this.router.navigate([], { + queryParams: { + [this.queryParamKeys.topicId]: nextIds, + [this.queryParamKeys.page]: 0, }, - { - id: 'actions', - header: '', - type: 'display', - cellTemplate: this.actionsTmp(), - }, - ]; + queryParamsHandling: 'merge', + }); + } + + isProjectTopicsExpanded(project: EuCordisProjectSummary): boolean { + const projectId = this.getProjectId(project); + return this.expandedProjectTopicsIds.includes(projectId); + } + + toggleProjectTopicsExpansion(project: EuCordisProjectSummary): void { + const projectId = this.getProjectId(project); + if (!projectId) return; + + this.expandedProjectTopicsIds = this.expandedProjectTopicsIds.includes( + projectId, + ) + ? this.expandedProjectTopicsIds.filter((id) => id !== projectId) + : [...this.expandedProjectTopicsIds, projectId]; } } diff --git a/webapp/src/app/shared/ui/eu-projects/eu-projects.component.html b/webapp/src/app/shared/ui/eu-projects/eu-projects.component.html new file mode 100644 index 00000000..8f49a79f --- /dev/null +++ b/webapp/src/app/shared/ui/eu-projects/eu-projects.component.html @@ -0,0 +1,18 @@ + + + diff --git a/webapp/src/app/shared/ui/eu-projects/eu-projects.component.scss b/webapp/src/app/shared/ui/eu-projects/eu-projects.component.scss new file mode 100644 index 00000000..e69de29b diff --git a/webapp/src/app/shared/ui/eu-projects/eu-projects.component.ts b/webapp/src/app/shared/ui/eu-projects/eu-projects.component.ts new file mode 100644 index 00000000..d9b0c770 --- /dev/null +++ b/webapp/src/app/shared/ui/eu-projects/eu-projects.component.ts @@ -0,0 +1,45 @@ +import { Component, computed, input, OnInit } from '@angular/core'; +import { ActivatedRoute, Router } from '@angular/router'; +import { toSignal } from '@angular/core/rxjs-interop'; +import { AuthorPage, TopicPageV2 } from '../../../api'; + +import { EuCordisProjectSearchPage } from '../../../api/model/euCordisProjectSearchPage'; +import { EuCordisOrganizationSelectorPage } from '../../../api/model/euCordisOrganizationSelectorPage'; +import { ProjectFilterComponent } from '../project-filters/project-filters.component'; +import { EuProjectTableComponent } from '../eu-project-table/eu-project-table.component'; + +import { euProjectQueryParamKeys } from '../../../resolvers/eu-cordis-projects.resolver'; + +@Component({ + selector: 'app-eu-projects', + imports: [ProjectFilterComponent, EuProjectTableComponent], + templateUrl: './eu-projects.component.html', + styleUrl: './eu-projects.component.scss', +}) +export class EuProjectsComponent implements OnInit { + euCordisProjectPage = input.required(); + + selectedEuInstitutionsPage = + input.required(); + + selectedEuAuthorsPage = input.required(); + + selectedTopicsPage = input.required(); + + readonly euQueryParamKeys = euProjectQueryParamKeys; + + constructor( + private readonly router: Router, + private readonly activatedRoute: ActivatedRoute, + ) {} + ngOnInit(): void { + console.log('EU PROJECTS', this.euCordisProjectPage()); + } + queryParamMap = toSignal(this.activatedRoute.queryParamMap, { + initialValue: this.activatedRoute.snapshot.queryParamMap, + }); + + readonly fuzzySearch = computed( + () => this.queryParamMap().get('fuzzy') === 'true', + ); +} diff --git a/webapp/src/app/shared/ui/project-filters/project-filters.component.html b/webapp/src/app/shared/ui/project-filters/project-filters.component.html index c04b5464..dfba58c4 100644 --- a/webapp/src/app/shared/ui/project-filters/project-filters.component.html +++ b/webapp/src/app/shared/ui/project-filters/project-filters.component.html @@ -1,48 +1,93 @@
@if (showTitleFilter()) { } +
- @if (showFundingStartFilter()) { - +
+ @if (showFundingStartFilter()) { + + } + + @if (showFundingEndFilter()) { + + } + @if (showEuProjectTypeFilter() && filterMode() === 'eu') { + + } + + @if (showInstitutionFilter() && filterMode() === 'dfg') { + + } + + @if (showInstitutionFilter() && filterMode() === 'eu') { + + } + + @if (showAuthorFilter() && filterMode() === 'dfg') { + + } + + @if (showAuthorFilter() && filterMode() === 'eu') { + + } + + @if (showTopicFilter()) { + + } + + +
+ + + + @if (topicLegendGroups.length > 0) { + + } - @if (showFundingEndFilter()) { - - } - @if (showInstitutionFilter()) { - - } - @if (showAuthorFilter()) { - - } - @if (showTopicFilter()) { - - } -
-
diff --git a/webapp/src/app/shared/ui/project-filters/project-filters.component.scss b/webapp/src/app/shared/ui/project-filters/project-filters.component.scss index 94044ea1..76941729 100644 --- a/webapp/src/app/shared/ui/project-filters/project-filters.component.scss +++ b/webapp/src/app/shared/ui/project-filters/project-filters.component.scss @@ -2,6 +2,9 @@ display: flex; flex-direction: column; gap: 1rem; + ::ng-deep app-topic-legend .topic-legend { + width: 100%; + } } .select-area { diff --git a/webapp/src/app/shared/ui/project-filters/project-filters.component.ts b/webapp/src/app/shared/ui/project-filters/project-filters.component.ts index 22f41f3b..bafccf35 100644 --- a/webapp/src/app/shared/ui/project-filters/project-filters.component.ts +++ b/webapp/src/app/shared/ui/project-filters/project-filters.component.ts @@ -1,40 +1,77 @@ import { Component, computed, input } from '@angular/core'; import { Router } from '@angular/router'; import { toSignal } from '@angular/core/rxjs-interop'; + import { MatButtonModule } from '@angular/material/button'; import { MatIconModule } from '@angular/material/icon'; +import { MatFormFieldModule } from '@angular/material/form-field'; +import { MatSelectModule } from '@angular/material/select'; + import { DfgInstitutionSummaryPage } from '../../../api/model/dfgInstitutionSummaryPage'; import { DfgInstitutionSummary } from '../../../api/model/dfgInstitutionSummary'; + import { + Author, + AuthorPage, DfgPersonSummary, DfgPersonSummaryPage, Topic, TopicPageV2, } from '../../../api'; + +import { EuCordisOrganizationSelectorPage } from '../../../api/model/euCordisOrganizationSelectorPage'; +import { EuCordisOrganizationSelectorSummary } from '../../../api/model/euCordisOrganizationSelectorSummary'; + +import { + buildTopicLegendGroups, + TopicLegendGroup, + TopicLegendTopic, +} from '../../../resolvers/utils/topic-legend'; + +import { TopicLegendComponent } from '../topic-legend/topic-legend.component'; import { QueryParamInputComponent } from '../query-param-input/query-param-input.component'; import { SearchableDfgInstitutionSelectComponent } from '../searchable-dfg-institution-select/searchable-dfg-institution-select.component'; - +import { SearchableEuInstitutionSelectComponent } from '../searchable-eu-institution-select/searchable-eu-institution-select.component'; import { SearchableYearSelectComponent } from '../searchable-year-select/searchable-year-select.component'; -import { projectQueryParamKeys } from '../../../resolvers/dfg-projects.resolver'; +import { SearchableDfgAuthorSelectComponent } from '../searchable-dfg-author-select/searchable-dfg-author-select.component'; +import { SearchableTopicSelectComponent } from '../searchable-topic-select/searchable-topic-select.component'; +import { + SearchableEuProjectTypeSelectComponent, + ProjectType, + findprojectTypeById, +} from '../searchable-eu-project-type-select/searchable-eu-project-type-select.component'; import { FilterObserver, SelectedFiltersComponent, } from '../selected-filters/selected-filters.component'; -import { map } from 'rxjs/internal/operators/map'; -import { SearchableDfgAuthorSelectComponent } from '../searchable-dfg-author-select/searchable-dfg-author-select.component'; -import { SearchableTopicSelectComponent } from '../searchable-topic-select/searchable-topic-select.component'; + +import { projectQueryParamKeys } from '../../../resolvers/dfg-projects.resolver'; +import { euProjectQueryParamKeys } from '../../../resolvers/eu-cordis-projects.resolver'; +import { SearchableAuthorSelectComponent } from '../searchable-author-select/searchable-author-select.component'; + +type ProjectFilterMode = 'dfg' | 'eu'; + +type ProjectQueryParamKeys = + | typeof projectQueryParamKeys + | typeof euProjectQueryParamKeys; @Component({ selector: 'app-project-filters', imports: [ MatButtonModule, MatIconModule, + MatFormFieldModule, + MatSelectModule, QueryParamInputComponent, SearchableDfgInstitutionSelectComponent, + SearchableEuInstitutionSelectComponent, SearchableDfgAuthorSelectComponent, + SearchableAuthorSelectComponent, SearchableYearSelectComponent, SelectedFiltersComponent, SearchableTopicSelectComponent, + TopicLegendComponent, + SearchableEuProjectTypeSelectComponent, ], templateUrl: './project-filters.component.html', styleUrl: './project-filters.component.scss', @@ -42,25 +79,17 @@ import { SearchableTopicSelectComponent } from '../searchable-topic-select/searc export class ProjectFilterComponent { constructor(private readonly router: Router) {} - // Each tab (DFG / EU) passes its OWN key set so they never collide. - queryParamKeys = projectQueryParamKeys; + filterMode = input('dfg'); + + queryParamKeys = input(projectQueryParamKeys); + + selectedDfgInstitutionsPage = input(); + selectedEuInstitutionsPage = input(); + + selectedDfgAuthorsPage = input(); + selectedEuAuthorsPage = input(); - // selectedAuthorsPage = input(); - // selectedAuthors = computed( - // () => this.selectedAuthorsPage()?.elements || [], - // ); - selectedAuthorsPage = input(); - selectedAuthors = computed( - () => this.selectedAuthorsPage()?.elements || [], - ); - selectedInstitutionsPage = input(); - selectedInstitutions = computed( - () => this.selectedInstitutionsPage()?.elements || [], - ); selectedTopicsPage = input(); - selectedTopics = computed( - () => this.selectedTopicsPage()?.elements || [], - ); showTitleFilter = input(true); showInstitutionFilter = input(true); @@ -68,78 +97,190 @@ export class ProjectFilterComponent { showFundingStartFilter = input(true); showFundingEndFilter = input(false); showTopicFilter = input(true); + showEuProjectTypeFilter = input(false); + + selectedDfgAuthors = computed( + () => this.selectedDfgAuthorsPage()?.elements || [], + ); + + selectedEuAuthors = computed( + () => this.selectedEuAuthorsPage()?.elements || [], + ); + + selectedDfgInstitutions = computed( + () => this.selectedDfgInstitutionsPage()?.elements || [], + ); + + selectedEuInstitutions = computed( + () => this.selectedEuInstitutionsPage()?.elements || [], + ); + + selectedTopics = computed( + () => this.selectedTopicsPage()?.elements || [], + ); + queryParamMap = toSignal(this.router.routerState.root.queryParamMap, { initialValue: this.router.routerState.snapshot.root.queryParamMap, }); - selectedInstitutionIds = computed(() => - this.queryParamMap().getAll(this.queryParamKeys.institutionId), + subfieldLegendVisible = computed( + () => this.queryParamMap().get(this.queryParamKeys().legend) === 'true', ); - selectedAuthorIds = computed(() => - this.queryParamMap().getAll(this.queryParamKeys.authorId), + subfieldLegendExpanded = computed( + () => + this.queryParamMap().get(this.queryParamKeys().legend_expanded) === + 'true', + ); + + selectedInstitutionIds = computed(() => + this.queryParamMap().getAll(this.queryParamKeys().institutionId), + ); + + euSelectedAuthorIds = computed(() => + this.queryParamMap().getAll(this.queryParamKeys().authorId), + ); + dfgSelectedAuthorIds = computed(() => + this.queryParamMap().getAll(this.queryParamKeys().authorId), ); selectedFundingStartYears = computed(() => - this.queryParamMap().getAll(this.queryParamKeys.funding_start).map(Number), + this.queryParamMap() + .getAll(this.queryParamKeys().funding_start) + .map(Number), ); + selectedFundingEndYears = computed(() => - this.queryParamMap().getAll(this.queryParamKeys.funding_end).map(Number), + this.queryParamMap().getAll(this.queryParamKeys().funding_end).map(Number), ); + + selectedEuProjectTypes = computed(() => { + const projectTypeIds = this.queryParamMap().getAll( + (this.queryParamKeys() as any).projectType, + ); + return projectTypeIds + .map((id) => findprojectTypeById(id)) + .filter((type) => type !== undefined) as ProjectType[]; + }); + fundingStartYearLabel = computed(() => { const selectedYears = this.selectedFundingStartYears(); - if (selectedYears.length === 0) { - return 'Förderbeginn'; - } else if (selectedYears.length === 1) { - return selectedYears[0].toString(); - } else { - return `${selectedYears.join(', ')} Jahre`; - } + + if (selectedYears.length === 0) return 'Förderbeginn'; + if (selectedYears.length === 1) return selectedYears[0].toString(); + + return `${selectedYears.join(', ')} Jahre`; }); fundingEndYearLabel = computed(() => { const selectedYears = this.selectedFundingEndYears(); - if (selectedYears.length === 0) { - return 'Förderende'; - } else if (selectedYears.length === 1) { - return selectedYears[0].toString(); - } else { - return `${selectedYears.join(', ')} Jahre`; - } + + if (selectedYears.length === 0) return 'Förderende'; + if (selectedYears.length === 1) return selectedYears[0].toString(); + + return `${selectedYears.join(', ')} Jahre`; }); - institutionLabel = computed(() => { - const selected = this.selectedInstitutions().filter((i) => + dfgInstitutionLabel = computed(() => { + const selected = this.selectedDfgInstitutions().filter((i) => this.selectedInstitutionIds().includes(String(i.id!)), ); + if (selected.length === 0) return 'Institution'; - if (selected.length === 1) + if (selected.length === 1) { return selected[0].institute_name_de ?? 'Institution'; + } + + return `${selected.length} Institutionen`; + }); + euProjectTypeLabel = computed(() => { + const selected = this.selectedEuProjectTypes(); + + if (selected.length === 0) return 'Projekttyp'; + if (selected.length === 1) { + switch (selected[0].id) { + case 'fp7': + return 'FP7'; + case 'h2020': + return 'Horizon 2020'; + case 'heu': + return 'Horizon Europe'; + default: + return selected[0].name ?? 'Projekttyp'; + } + } + + return `${selected.length} Projekttypen`; + }); + + euInstitutionLabel = computed(() => { + const selected = this.selectedEuInstitutions().filter((org) => + this.selectedInstitutionIds().includes(String(org.organisation_id)), + ); + + if (selected.length === 0) return 'Institution'; + if (selected.length === 1) { + return selected[0].name ?? selected[0].short_name ?? 'Institution'; + } + return `${selected.length} Institutionen`; }); - authorLabel = computed(() => { - const selected = this.selectedAuthors().filter((a) => - this.selectedAuthorIds().includes(String(a.person_id!)), + dfgAuthorLabel = computed(() => { + const selected = this.selectedDfgAuthors().filter((a) => + this.dfgSelectedAuthorIds().includes(String(a.person_id!)), ); + if (selected.length === 0) return 'Autor'; if (selected.length === 1) return selected[0].full_name ?? 'Autor'; + return `${selected.length} Autoren`; }); + euAuthorLabel = computed(() => { + const selected = this.selectedEuAuthors().filter((a: any) => + this.euSelectedAuthorIds().includes(String(a.id)), + ); + + if (selected.length === 0) return 'Autor'; + if (selected.length === 1) { + return selected[0].display_name ?? 'Autor'; + } + + return `${selected.length} Autoren`; + }); + + topicLabel = computed(() => { + const selectedTopicIds = this.selectedTopics().map((t) => t.id); + + if (selectedTopicIds.length === 0) return 'Thema'; + + if (selectedTopicIds.length === 1) { + const topic = this.selectedTopics()[0]; + return topic.display_name || 'Thema'; + } + + return `${selectedTopicIds.length} Themen`; + }); + observers = computed(() => { - const keys = this.queryParamKeys; - return [ - { id: 'search', queryParamKey: keys.title, icon: 'search' }, + const keys = this.queryParamKeys(); + + const observers: FilterObserver[] = [ + { + id: 'search', + queryParamKey: keys.title, + icon: 'search', + }, { id: 'fundingStart', - queryParamKey: projectQueryParamKeys.funding_start, + queryParamKey: keys.funding_start, icon: 'calendar_today', valueFormatter: (value: string) => `Förderbeginn ${value}`, }, { id: 'fundingEnd', - queryParamKey: projectQueryParamKeys.funding_end, + queryParamKey: keys.funding_end, icon: 'event_busy', valueFormatter: (value: string) => `Förderende ${value}`, }, @@ -147,17 +288,39 @@ export class ProjectFilterComponent { id: 'institutions', queryParamKey: keys.institutionId, icon: 'apartment', - valueFormatter: (value: string) => - this.selectedInstitutions().find((i) => String(i.id) === value) - ?.institute_name_de ?? value, + valueFormatter: (value: string) => { + if (this.filterMode() === 'eu') { + return ( + this.selectedEuInstitutions().find( + (org) => String(org.organisation_id) === value, + )?.name ?? 'pizda' + ); + } + + return ( + this.selectedDfgInstitutions().find((i) => String(i.id) === value) + ?.institute_name_de ?? value + ); + }, }, { id: 'authors', queryParamKey: keys.authorId, icon: 'person', - valueFormatter: (value: string) => - this.selectedAuthors().find((a) => String(a.person_id) === value) - ?.full_name ?? value, + valueFormatter: (value: string) => { + if (this.filterMode() === 'eu') { + const author = this.selectedEuAuthors().find( + (a: any) => String(a.id) === value, + ) as any; + + return author?.display_name ?? author?.full_name ?? value; + } + + return ( + this.selectedDfgAuthors().find((a) => String(a.person_id) === value) + ?.full_name ?? value + ); + }, }, { id: 'topics', @@ -169,131 +332,257 @@ export class ProjectFilterComponent { }, }, ]; + + if (this.filterMode() === 'eu') { + const euKeys = keys as typeof euProjectQueryParamKeys; + + observers.push({ + id: 'projectTypes', + queryParamKey: euKeys.projectType, + icon: 'category', + valueFormatter: (value: string) => { + switch (value) { + case 'fp7': + return 'Framework Programme 7'; + case 'h2020': + return 'Horizon 2020'; + case 'heu': + return 'Horizon Europe'; + default: + return value; + } + }, + }); + } + + return observers; }); handleFundingStartSelectChange = (selectedYear: number): void => { - if (this.selectedFundingStartYears().includes(selectedYear)) { - this.router.navigate([], { - queryParams: { - [projectQueryParamKeys.funding_start]: - this.selectedFundingStartYears().filter( - (year) => year !== selectedYear, - ), - }, - queryParamsHandling: 'merge', - }); - } else { - this.router.navigate([], { - queryParams: { - [projectQueryParamKeys.funding_start]: [ - ...this.selectedFundingStartYears(), - selectedYear, - ], - }, - queryParamsHandling: 'merge', - }); - } - }; - handleFundingEndSelectChange = (selectedYear: number): void => { - if (this.selectedFundingEndYears().includes(selectedYear)) { - this.router.navigate([], { - queryParams: { - [projectQueryParamKeys.funding_end]: - this.selectedFundingEndYears().filter( - (year) => year !== selectedYear, - ), - }, - queryParamsHandling: 'merge', - }); - } else { - this.router.navigate([], { - queryParams: { - [projectQueryParamKeys.funding_end]: [ - ...this.selectedFundingEndYears(), - selectedYear, - ], - }, - queryParamsHandling: 'merge', - }); - } - }; - handleInstitutionSelectChange = ( - institution: DfgInstitutionSummary, - ): void => { - if (!institution.id) return; - const keys = this.queryParamKeys; - const selectedIds = this.selectedInstitutionIds(); - const nextIds = selectedIds.includes(String(institution.id)) - ? selectedIds.filter((id) => id !== String(institution.id)) - : [...selectedIds, String(institution.id)]; + const keys = this.queryParamKeys(); + const selectedYears = this.selectedFundingStartYears(); - this.router.navigate([], { - queryParams: { [keys.institutionId]: nextIds, [keys.page]: 0 }, - queryParamsHandling: 'merge', - }); - }; + const nextYears = selectedYears.includes(selectedYear) + ? selectedYears.filter((year) => year !== selectedYear) + : [...selectedYears, selectedYear]; - handleAuthorSelectChange = (author: DfgPersonSummary): void => { - if (!author.person_id) return; - const keys = this.queryParamKeys; - const selectedIds = this.selectedAuthorIds(); - const nextIds = selectedIds.includes(String(author.person_id)) - ? selectedIds.filter((id) => id !== String(author.person_id)) - : [...selectedIds, String(author.person_id)]; - - this.router.navigate([], { - queryParams: { [keys.authorId]: nextIds, [keys.page]: 0 }, - queryParamsHandling: 'merge', - }); - }; - - topicLabel = computed(() => { - const selectedTopicIds = this.selectedTopics().map((t) => t.id); - if (selectedTopicIds.length === 0) { - return 'Thema'; - } else if (selectedTopicIds.length === 1) { - const topic = this.selectedTopics()[0]; - return topic.display_name || 'Thema'; - } else { - return `${selectedTopicIds.length} Themen`; - } - }); - - handleTopicSelectChange = (selectedTopic: Topic): void => { - if (this.selectedTopics().some((t) => t.id === selectedTopic.id)) { - this.router.navigate([], { - queryParams: { - [this.queryParamKeys.topicId]: this.selectedTopics() - .filter((t) => t.id !== selectedTopic.id) - .map((t) => t.id), - }, - queryParamsHandling: 'merge', - }); - } else { - this.router.navigate([], { - queryParams: { - [this.queryParamKeys.topicId]: [ - ...this.selectedTopics().map((t) => t.id!), - selectedTopic.id, - ], - }, - queryParamsHandling: 'merge', - }); - } - }; - - resetFilters = (): void => { - const keys = this.queryParamKeys; this.router.navigate([], { queryParams: { - [keys.title]: null, - [keys.institutionId]: null, - [keys.authorId]: null, - [keys.funding_start]: null, - [keys.funding_end]: null, + [keys.funding_start]: nextYears, [keys.page]: 0, }, queryParamsHandling: 'merge', }); }; + + handleFundingEndSelectChange = (selectedYear: number): void => { + const keys = this.queryParamKeys(); + const selectedYears = this.selectedFundingEndYears(); + + const nextYears = selectedYears.includes(selectedYear) + ? selectedYears.filter((year) => year !== selectedYear) + : [...selectedYears, selectedYear]; + + this.router.navigate([], { + queryParams: { + [keys.funding_end]: nextYears, + [keys.page]: 0, + }, + queryParamsHandling: 'merge', + }); + }; + + handleLegendVisibleChange = (visible: boolean): void => { + const keys = this.queryParamKeys(); + + this.router.navigate([], { + queryParams: { + [keys.legend]: visible ? 'true' : null, + }, + queryParamsHandling: 'merge', + }); + }; + + handleLegendExpandedChange = (expanded: boolean): void => { + const keys = this.queryParamKeys(); + + this.router.navigate([], { + queryParams: { + [keys.legend_expanded]: expanded ? 'true' : null, + }, + queryParamsHandling: 'merge', + }); + }; + + handleDfgInstitutionSelectChange = ( + institution: DfgInstitutionSummary, + ): void => { + if (!institution.id) return; + + const keys = this.queryParamKeys(); + const selectedIds = this.selectedInstitutionIds(); + + const nextIds = selectedIds.includes(String(institution.id)) + ? selectedIds.filter((id) => id !== String(institution.id)) + : [...selectedIds, String(institution.id)]; + + this.router.navigate([], { + queryParams: { + [keys.institutionId]: nextIds, + [keys.page]: 0, + }, + queryParamsHandling: 'merge', + }); + }; + + handleEuInstitutionSelectChange = ( + organization: EuCordisOrganizationSelectorSummary, + ): void => { + if (!organization.organisation_id) return; + + const keys = this.queryParamKeys(); + const selectedIds = this.selectedInstitutionIds(); + + const organizationId = String(organization.organisation_id); + + const nextIds = selectedIds.includes(organizationId) + ? selectedIds.filter((id) => id !== organizationId) + : [...selectedIds, organizationId]; + + this.router.navigate([], { + queryParams: { + [keys.institutionId]: nextIds, + [keys.page]: 0, + }, + queryParamsHandling: 'merge', + }); + }; + + handleDfgAuthorSelectChange = (author: DfgPersonSummary): void => { + if (!author.person_id) return; + + const keys = this.queryParamKeys(); + const selectedIds = this.dfgSelectedAuthorIds(); + + const authorId = String(author.person_id); + + const nextIds = selectedIds.includes(authorId) + ? selectedIds.filter((id) => id !== authorId) + : [...selectedIds, authorId]; + + this.router.navigate([], { + queryParams: { + [keys.authorId]: nextIds, + [keys.page]: 0, + }, + queryParamsHandling: 'merge', + }); + }; + + handleEuAuthorSelectChange = (author: Author): void => { + const rawAuthor = author as any; + if (!rawAuthor.id) return; + + const keys = this.queryParamKeys(); + const selectedIds = this.euSelectedAuthorIds(); + + const authorId = String(rawAuthor.id); + + const nextIds = selectedIds.includes(authorId) + ? selectedIds.filter((id) => id !== authorId) + : [...selectedIds, authorId]; + + this.router.navigate([], { + queryParams: { + [keys.authorId]: nextIds, + [keys.page]: 0, + }, + queryParamsHandling: 'merge', + }); + }; + + handleTopicSelectChange = (selectedTopic: Topic): void => { + const keys = this.queryParamKeys(); + const selectedTopicIds = this.selectedTopics().map((t) => t.id!); + + const nextIds = selectedTopicIds.includes(selectedTopic.id!) + ? selectedTopicIds.filter((id) => id !== selectedTopic.id) + : [...selectedTopicIds, selectedTopic.id!]; + + this.router.navigate([], { + queryParams: { + [keys.topicId]: nextIds, + [keys.page]: 0, + }, + queryParamsHandling: 'merge', + }); + }; + + handleEuProjectTypeSelectChange = ( + selectedProjectTypes: ProjectType, + ): void => { + const keys = this.queryParamKeys() as typeof euProjectQueryParamKeys; + + this.router.navigate([], { + queryParams: { + [keys.projectType]: selectedProjectTypes.id, + [keys.page]: 0, + }, + queryParamsHandling: 'merge', + }); + }; + + resetFilters = (): void => { + const keys = this.queryParamKeys(); + + const resetQueryParams: Record = { + [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), + ); + + return buildTopicLegendGroups(topics); + } + + private toTopicLegendTopic(topic: Topic): TopicLegendTopic { + return { + id: topic.id ?? topic.display_name ?? '', + name: topic.display_name ?? '', + field_id: topic.field?.id ?? null, + field_name: topic.field?.display_name ?? null, + field_description: null, + domain_id: topic.domain?.id ?? null, + domain_name: topic.domain?.display_name ?? null, + domain_description: null, + subfield_id: topic.subfield?.id ?? null, + subfield_name: topic.subfield?.display_name ?? null, + subfield_description: null, + }; + } } diff --git a/webapp/src/app/shared/ui/searchable-eu-institution-select/searchable-eu-institution-select.component.html b/webapp/src/app/shared/ui/searchable-eu-institution-select/searchable-eu-institution-select.component.html new file mode 100644 index 00000000..ea0f7c1f --- /dev/null +++ b/webapp/src/app/shared/ui/searchable-eu-institution-select/searchable-eu-institution-select.component.html @@ -0,0 +1,12 @@ + diff --git a/webapp/src/app/shared/ui/searchable-eu-institution-select/searchable-eu-institution-select.component.scss b/webapp/src/app/shared/ui/searchable-eu-institution-select/searchable-eu-institution-select.component.scss new file mode 100644 index 00000000..e69de29b diff --git a/webapp/src/app/shared/ui/searchable-eu-institution-select/searchable-eu-institution-select.component.ts b/webapp/src/app/shared/ui/searchable-eu-institution-select/searchable-eu-institution-select.component.ts new file mode 100644 index 00000000..bbd4254b --- /dev/null +++ b/webapp/src/app/shared/ui/searchable-eu-institution-select/searchable-eu-institution-select.component.ts @@ -0,0 +1,48 @@ +import { Component, inject, input, output } from '@angular/core'; + +import { ProjectsService } from '../../../api'; +import { Observable } from 'rxjs'; +import { SearchableSelectComponent } from '../searchable-select/searchable-select.component'; +import { EuCordisOrganizationSelectorPage } from '../../../api/model/euCordisOrganizationSelectorPage'; +import { EuCordisOrganizationSelectorSummary } from '../../../api/model/euCordisOrganizationSelectorSummary'; +@Component({ + selector: 'app-searchable-eu-institution-select', + imports: [SearchableSelectComponent], + templateUrl: './searchable-eu-institution-select.component.html', + styleUrl: './searchable-eu-institution-select.component.scss', +}) +export class SearchableEuInstitutionSelectComponent { + private readonly projectsService = inject(ProjectsService); + + label = input('Institutionen'); + selectedInstitutions = + input.required(); + + handleInstitutionSelectChange = output(); + + fetchInstitutions = ( + searchTerm: string, + ): Observable => { + return this.projectsService.getEuOrganizationAutocompleteForSelector( + searchTerm, + ); + }; + + getInstitutionLabel = ( + institution: EuCordisOrganizationSelectorSummary, + ): string => { + return institution.name ?? institution.short_name ?? 'Institution'; + }; + + getInstitutionValue = ( + institution: EuCordisOrganizationSelectorSummary, + ): string => { + return institution.id!; + }; + + getInstitutionDescription = ( + institution: EuCordisOrganizationSelectorSummary, + ): string => { + return institution.country + ' - ' + institution.city; + }; +} diff --git a/webapp/src/app/shared/ui/searchable-eu-project-type-select/searchable-eu-project-type-select.component.html b/webapp/src/app/shared/ui/searchable-eu-project-type-select/searchable-eu-project-type-select.component.html new file mode 100644 index 00000000..f2d998e4 --- /dev/null +++ b/webapp/src/app/shared/ui/searchable-eu-project-type-select/searchable-eu-project-type-select.component.html @@ -0,0 +1,11 @@ + diff --git a/webapp/src/app/shared/ui/searchable-eu-project-type-select/searchable-eu-project-type-select.component.scss b/webapp/src/app/shared/ui/searchable-eu-project-type-select/searchable-eu-project-type-select.component.scss new file mode 100644 index 00000000..e69de29b diff --git a/webapp/src/app/shared/ui/searchable-eu-project-type-select/searchable-eu-project-type-select.component.ts b/webapp/src/app/shared/ui/searchable-eu-project-type-select/searchable-eu-project-type-select.component.ts new file mode 100644 index 00000000..3a26e038 --- /dev/null +++ b/webapp/src/app/shared/ui/searchable-eu-project-type-select/searchable-eu-project-type-select.component.ts @@ -0,0 +1,57 @@ +import { Component, input, output } from '@angular/core'; +import { SearchableSelectComponent } from '../searchable-select/searchable-select.component'; +import { Observable } from 'rxjs'; + +export type ProjectType = { + id: string; + name: string; +}; + +export const projectTypes: ProjectType[] = [ + { id: 'h2020', name: 'Horizon 2020' }, + { id: 'heu', name: 'Horizon Europe' }, + { id: 'fp7', name: 'Framework Programme 7' }, +]; + +export const findprojectTypeById = (id: string): ProjectType | undefined => { + return projectTypes.find((projectType) => projectType.id === id); +}; + +type ProjectTypePage = { + elements?: ProjectType[]; + page?: number; + size?: number; + total?: number; +}; + +@Component({ + selector: 'app-searchable-eu-project-type-select', + imports: [SearchableSelectComponent], + templateUrl: './searchable-eu-project-type-select.component.html', + styleUrl: './searchable-eu-project-type-select.component.scss', +}) +export class SearchableEuProjectTypeSelectComponent { + label = input('Typen'); + selectedEuProjectTypes = input.required(); + + handleEuProjectTypeSelectChange = output(); + + fetchprojectTypes = (searchTerm: string): Observable => { + return new Observable((observer) => { + observer.next({ + elements: projectTypes.filter((projectType) => + projectType.name.toLowerCase().includes(searchTerm.toLowerCase()), + ), + }); + observer.complete(); + }); + }; + + getprojectTypeLabel = (projectType: ProjectType): string => { + return projectType.name; + }; + + getprojectTypeValue = (projectType: ProjectType): string => { + return projectType.id; + }; +}