diff --git a/service/src/main/inse/dashboard/service.py b/service/src/main/inse/dashboard/service.py index 42f8a9b6..ce9a9b2b 100644 --- a/service/src/main/inse/dashboard/service.py +++ b/service/src/main/inse/dashboard/service.py @@ -182,7 +182,7 @@ async def get_dashboard_dfg_projects( normalized_id = _normalize_institution_id(institution_id) aliases = await _institution_aliases(normalized_id, organization_name) response = await elasticsearch.search( - index=ESIndex.PROJECTS_DFG_ALL, + index=ESIndex.DFG_PROJECTS, query=_dfg_institution_query(aliases), size=0, track_total_hits=True, @@ -639,7 +639,7 @@ async def _top_dfg_project_author_buckets( aliases: list[str], ) -> list[dict[str, Any]]: response = await elasticsearch.search( - index=ESIndex.PROJECTS_DFG_ALL, + index=ESIndex.DFG_PROJECTS, body={ "size": 0, "query": _dfg_institution_query(aliases), diff --git a/service/src/main/inse/dashboard/test_service.py b/service/src/main/inse/dashboard/test_service.py index ca3288b8..0d2914c0 100644 --- a/service/src/main/inse/dashboard/test_service.py +++ b/service/src/main/inse/dashboard/test_service.py @@ -68,7 +68,7 @@ async def test_dashboard_statistics_counts_organization_data_and_all_projects(): assert [call.kwargs["index"] for call in calls[2:]] == [ ESIndex.CORDIS_EU_ORGANIZATIONS_WILDCARD, ESIndex.PROJECTS_BUND_V1, - ESIndex.PROJECTS_DFG_ALL, + ESIndex.DFG_PROJECTS, ] assert calls[2].kwargs["body"]["query"] == { "terms": { @@ -131,7 +131,7 @@ async def test_top_authors_maps_works_and_dfg_project_aggregations(): } } } - if kwargs["index"] == ESIndex.PROJECTS_DFG_ALL: + if kwargs["index"] == ESIndex.DFG_PROJECTS: return { "aggregations": { "people": { @@ -181,10 +181,10 @@ async def test_top_authors_maps_works_and_dfg_project_aggregations(): call for call in mocked_search.await_args_list if call.kwargs["index"] - in {ESIndex.PROJECTS_DFG_ALL, ESIndex.PROJECTS_BUND_V1} + in {ESIndex.DFG_PROJECTS, ESIndex.PROJECTS_BUND_V1} ] assert len(project_calls) == 1 - assert project_calls[0].kwargs["index"] == ESIndex.PROJECTS_DFG_ALL + assert project_calls[0].kwargs["index"] == ESIndex.DFG_PROJECTS assert project_calls[0].kwargs["body"]["query"]["bool"][ "minimum_should_match" ] == 1 @@ -198,7 +198,7 @@ async def test_top_authors_keeps_dfg_project_authors_without_openalex_match(): async def search(**kwargs): if kwargs["index"] == ESIndex.OPENALEX_AUTHORS: return {"hits": {"hits": []}} - if kwargs["index"] == ESIndex.PROJECTS_DFG_ALL: + if kwargs["index"] == ESIndex.DFG_PROJECTS: return { "aggregations": { "people": { @@ -232,7 +232,7 @@ async def test_top_authors_returns_top_ten_dfg_project_people_by_project_count() async def search(**kwargs): if kwargs["index"] == ESIndex.OPENALEX_AUTHORS: return {"hits": {"hits": []}} - if kwargs["index"] == ESIndex.PROJECTS_DFG_ALL: + if kwargs["index"] == ESIndex.DFG_PROJECTS: return { "aggregations": { "people": { @@ -280,7 +280,7 @@ async def test_top_authors_combines_dfg_involved_people_case_insensitively(): ] } } - if kwargs["index"] == ESIndex.PROJECTS_DFG_ALL: + if kwargs["index"] == ESIndex.DFG_PROJECTS: return { "aggregations": { "people": { diff --git a/service/src/main/inse/integrations/elasticsearch.py b/service/src/main/inse/integrations/elasticsearch.py index 3777d6fc..4193f55b 100644 --- a/service/src/main/inse/integrations/elasticsearch.py +++ b/service/src/main/inse/integrations/elasticsearch.py @@ -100,7 +100,7 @@ def _index_to_cluster(index: ESIndex) -> Optional[ESCluster]: ESIndex.CORDIS_EU_PROJECTS_WILDCARD, ESIndex.CORDIS_EU_PUBLICATIONS_WILDCARD, ESIndex.PROJECTS_BUND_V1, - ESIndex.PROJECTS_DFG_ALL, + ESIndex.DFG_PROJECTS, }: return ESCluster.INSE else: diff --git a/service/src/main/inse/model.py b/service/src/main/inse/model.py index 30f0a153..970ec14f 100644 --- a/service/src/main/inse/model.py +++ b/service/src/main/inse/model.py @@ -62,9 +62,6 @@ class ESIndex(StrEnum): ORG_PATENTS = "org_patents" PROJECTS_BUND_V1 = "projects_bund_v1" - PROJECTS_DFG_ALL = "dfg_projects_2.0" - PROJECTS_DFG_PERSONS = "dfg_persons_2.0" - PROJECTS_DFG_INSTITUTES = "dfg_institutes_2.0" CORDIS_EU_ORGANIZATIONS_WILDCARD = "cordis_eu_*_organizations" CORDIS_EU_PROJECTS_WILDCARD = "cordis_eu_*_projects" diff --git a/service/src/main/inse/projects/dfg_institutions/service.py b/service/src/main/inse/projects/dfg_institutions/service.py index aeb1f5e4..71c687b0 100644 --- a/service/src/main/inse/projects/dfg_institutions/service.py +++ b/service/src/main/inse/projects/dfg_institutions/service.py @@ -32,7 +32,7 @@ async def search_institutions( DfgInstitutionSummaryPage: A page of institutions matching the search criteria. """ response = await elasticsearch.search( - index=ESIndex.PROJECTS_DFG_INSTITUTES, + index=ESIndex.DFG_INSTITUTES, cluster=ESCluster.INSE, query=query, source=source, diff --git a/service/src/main/inse/projects/dfg_persons/service.py b/service/src/main/inse/projects/dfg_persons/service.py index 9685add4..a0929cb7 100644 --- a/service/src/main/inse/projects/dfg_persons/service.py +++ b/service/src/main/inse/projects/dfg_persons/service.py @@ -32,7 +32,7 @@ async def search_persons( """ print(query) response = await elasticsearch.search( - index=ESIndex.PROJECTS_DFG_PERSONS, + index=ESIndex.DFG_PERSONS, cluster=ESCluster.INSE, query=query, source=source, diff --git a/service/src/main/inse/projects/logic.py b/service/src/main/inse/projects/logic.py index 1ced04f9..2a01e5ca 100644 --- a/service/src/main/inse/projects/logic.py +++ b/service/src/main/inse/projects/logic.py @@ -2,35 +2,12 @@ import json import logging from typing import Any, Dict, List, Optional, Set, Tuple -import urllib -from inse.config import get_settings -from inse.models.bund_project import BundProject -from inse.projects.model import ( - BundProjectPage, - CordisEuProjectPage, - DfgProjectPage, - DfgProjectSummary, - EuOrganizationProjectSummary, - EuOrganizationProjectSummaryPage, - EuOrganizationShort, - EuProjectShort, - FundingProject, - FundingProjectPage, - ProjectType, - ProjectsFilteringProperties, - ProjectsSortBy, - SortDirection, -) +from collections import defaultdict from inse.projects.eu_cordis_projects_enrichment_client import get_enriched_cordis_project_by_id -from inse.models.dfg_project_details import DfgProjectDetails -from inse.models.bund_project_details import BundProjectDetails -from inse.models.cordis_eu_project import CordisEuProject + from inse.integrations import elasticsearch from inse.model import ESCluster, ESIndex -from inse.models.projects_eu_cordis.horizon2020.h2020_project_details import H2020ProjectDetails -from inse.models.projects_eu_cordis.horizon_europe.heu_project_details import HEUProjectDetails -from inse.models.projects_eu_cordis.fp7.fp7_project_details import Fp7ProjectDetails -from typing import Union + logger = logging.getLogger(__name__) @@ -43,8 +20,7 @@ async def get_dfg_author_names_by_ids(author_ids: List[int]) -> Optional[List[st }, "size": len(author_ids), } - print(body) - data = await elasticsearch.search(index=ESIndex.PROJECTS_DFG_PERSONS, body=body, cluster=ESCluster.INSE) + data = await elasticsearch.search(index=ESIndex.DFG_PERSONS, body=body, cluster=ESCluster.INSE) hits = data.get("hits", {}).get("hits", []) if not hits: return [] @@ -63,7 +39,7 @@ async def get_dfg_institution_names_by_ids(institution_ids: List[int]) -> Option "size": len(institution_ids), } - data = await elasticsearch.search(index=ESIndex.PROJECTS_DFG_INSTITUTES, body=body, cluster=ESCluster.INSE) + data = await elasticsearch.search(index=ESIndex.DFG_INSTITUTES, body=body, cluster=ESCluster.INSE) hits = data.get("hits", {}).get("hits", []) if not hits: return [] @@ -71,50 +47,24 @@ async def get_dfg_institution_names_by_ids(institution_ids: List[int]) -> Option except Exception as e: logger.exception(f"Error fetching institution names for ids {institution_ids}: {str(e)}") return [] - -async def get_person_ids_by_institution_names( - institution_names: list[str], + +async def get_person_ids_by_institution_ids( + institution_ids: list[int], ) -> list[int]: - cleaned_names = [ - name.strip() - for name in institution_names - if name and name.strip() - ] - - if not cleaned_names: + if not institution_ids: return [] - institution_fields = [ - "institute_name_de", - "institute_name_en", - "root_name_de", - "root_name_en", - ] - - should_clauses = [] - - for name in cleaned_names: - for field in institution_fields: - should_clauses.append( - { - "match_phrase": { - field: name - } - } - ) - response = await elasticsearch.search( - index=ESIndex.PROJECTS_DFG_PERSONS, + index=ESIndex.DFG_PERSONS, cluster=ESCluster.INSE, body={ "size": 10000, "_source": ["person_id"], "query": { - "bool": { - "should": should_clauses, - "minimum_should_match": 1, + "terms": { + "institute_id": institution_ids } - }, + } }, ) @@ -124,4 +74,173 @@ async def get_person_ids_by_institution_names( for hit in response.get("hits", {}).get("hits", []) if hit.get("_source", {}).get("person_id") is not None } - ) \ No newline at end of file + ) +async def get_dfg_project_ids_by_topic_ids(topic_ids: List[str]) -> List[str]: + """Fetches project IDs whose topic_matches contain EVERY given topic ID, + even if the topics are distributed across multiple documents for the same project. + """ + if not topic_ids: + return [] + + required_topics = set(topic_ids) + + 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=ESIndex.PROJECTS_DFG_TOPICS, + cluster=ESCluster.INSE, + body=body, + ) + + hits = response.get("hits", {}).get("hits", []) + if not hits: + break + + for hit in hits: + source = hit["_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 + + return [ + project_id + for project_id, found_topics in project_topics.items() + if required_topics.issubset(found_topics) + ] +async def get_openalex_topics_for_dfg_projects( + project_ids: List[str], +) -> Dict[int, List[Dict[str, Any]]]: + """Fetches OpenAlex topic matches for the given DFG project IDs. + + Args: + project_ids (List[str]): The DFG project IDs to fetch topics for. + + Returns: + Dict[int, List[Dict[str, Any]]]: Mapping of project_id -> list of topic match dicts, + each containing topic_id, topic_display_name, domain, field, subfield, rank. + """ + if not project_ids: + return {} + + topic_lookup: Dict[int, List[Dict[str, Any]]] = {} + + page_size = 1000 + from_ = 0 + # print(f"Fetching topics for {len(project_ids)} DFG projects in batches of {page_size}...{project_ids}") + while True: + response = await elasticsearch.search( + index=ESIndex.PROJECTS_DFG_TOPICS, + cluster=ESCluster.INSE, + body={ + "size": page_size, + "from": from_, + "query": { + "terms": { + "project_id.keyword": project_ids + } + }, + }, + ) + + hits = response.get("hits", {}).get("hits", []) + if not hits: + break + + for hit in hits: + source = hit["_source"] + project_id = int(source.get("project_id")) + if project_id is None: + continue + + topic_matches = source.get("topic_matches") or [] + if isinstance(topic_matches, dict): + topic_matches = [topic_matches] + + topic_lookup.setdefault(project_id, []).extend(topic_matches) + + if len(hits) < page_size: + break + + from_ += page_size + #logger.info(f"Fetched topics for {len(topic_lookup)} DFG projects.") + return topic_lookup + +async def get_person_institutes( + person_ids: list[int], +) -> dict[str, dict]: + + if not person_ids: + return {} + + response = await elasticsearch.search( + index=ESIndex.DFG_PERSONS, + cluster=ESCluster.INSE, + body={ + "size": len(person_ids), + "_source": [ + "person_id", + "root_id", + "institute_id", + "root_name_de", + "root_name_en", + "institute_name_de", + "institute_name_en", + "address_country_de", + "address_country_en", + ], + "query": { + "terms": { + "person_id": person_ids, + } + }, + }, + ) + + result = {} + + for hit in response["hits"]["hits"]: + source = hit["_source"] + + result[source["person_id"]] = { + "person_id": source["person_id"], + "root_id": source.get("root_id"), + "institute_id": source.get("institute_id"), + "root_name_de": source.get("root_name_de"), + "root_name_en": source.get("root_name_en"), + "institute_name_de": source.get("institute_name_de"), + "institute_name_en": source.get("institute_name_en"), + "address_country_de": source.get("address_country_de"), + "address_country_en": source.get("address_country_en"), + } + return result diff --git a/service/src/main/inse/projects/model.py b/service/src/main/inse/projects/model.py index 00a59479..8284b33a 100644 --- a/service/src/main/inse/projects/model.py +++ b/service/src/main/inse/projects/model.py @@ -1,7 +1,7 @@ from datetime import date import datetime from enum import StrEnum -from typing import List, Optional +from typing import List, Optional, Dict, Any from pydantic import BaseModel, Field, field_validator @@ -13,6 +13,7 @@ from inse.models.projects_eu_cordis.horizon2020.h2020_project_details import H20 from inse.models.projects_eu_cordis.horizon_europe.heu_project_details import HEUProjectDetails from inse.models.projects_eu_cordis.fp7.fp7_project_details import Fp7ProjectDetails from inse.models.projects_dfg_v2.project.dfg_project_fachgebiete_inner import DFGProjectFachgebieteInner +from inse.models.openalex.topic import Topic, TopicDomain, TopicField, TopicSubfield from typing import Union class ProjectType(StrEnum): @@ -24,7 +25,7 @@ class ProjectType(StrEnum): mapping = { self.BUND: ESIndex.PROJECTS_BUND_V1, self.EU: ESIndex.CORDIS_EU_PROJECTS_WILDCARD, - self.DFG: ESIndex.PROJECTS_DFG_ALL, + self.DFG: ESIndex.DFG_PROJECTS, } index = mapping.get(self) if index is None: @@ -155,6 +156,10 @@ class DfgProjectSummary(BaseModel): default=None, description="The subject classifications of the DFG project.", ) + topics: Optional[List[Topic]] = Field( + default=None, + description="The topics associated with the DFG project.", + ) @classmethod def from_hit(cls, hit: dict) -> "DfgProjectSummary": source = hit.get("_source", {}) @@ -203,6 +208,16 @@ class DfgProjectSummary(BaseModel): institution=institution, ) ) + topics_raw = source.get("topics") or [] + topics = None + if isinstance(topics_raw, list) and topics_raw: + # Sort by rank if present, so the most relevant topic comes first + sorted_topics_raw = sorted( + (t for t in topics_raw if isinstance(t, dict)), + key=lambda t: t.get("rank") if t.get("rank") is not None else float("inf"), + ) + topics = [cls._topic_from_match(t) for t in sorted_topics_raw] + return cls( id=hit.get("_id", ""), link=source.get("link") or source.get("page_url"), @@ -229,9 +244,44 @@ class DfgProjectSummary(BaseModel): institutions=list(institutions.values()), names=names, persons=project_persons, - subject_classifications=[DFGProjectFachgebieteInner.from_dict(cls) for cls in source.get('subject_classifications', [])] + subject_classifications=[DFGProjectFachgebieteInner.from_dict(cls) for cls in source.get('subject_classifications', [])], + topics=topics ) + @staticmethod + def _topic_from_match(match: Dict[str, Any]) -> Topic: + """Builds a (partial) Topic model from a flattened topic_match dict + coming from the `projects_dfg_openalex_topics` index. + Args: + match (Dict[str, Any]): A single topic match entry, e.g.: + { + "rank": 1, + "topic_id": "https://openalex.org/T12220", + "topic_display_name": "Quantum Electrodynamics and Casimir Effect", + "subfield": "Atomic and Molecular Physics, and Optics", + "field": "Physics and Astronomy", + "domain": "Physical Sciences", + "match_score": None + } + + Returns: + Topic: The constructed Topic instance. + """ + 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 DfgProjectPage(Page): elements: List[DfgProjectSummary] = Field( @@ -371,9 +421,9 @@ class FundingProject(BaseModel): @classmethod def from_dfg_projects_hit(cls, hit: dict) -> "FundingProject": - if hit.get("_index") != ESIndex.PROJECTS_DFG_ALL.value: + if hit.get("_index") != ESIndex.DFG_PROJECTS.value: raise ValueError( - f"The provided hit does not belong to the '{ESIndex.PROJECTS_DFG_ALL.value}' index." + f"The provided hit does not belong to the '{ESIndex.DFG_PROJECTS.value}' index." ) source = hit.get("_source", {}) diff --git a/service/src/main/inse/projects/projects_search_client.py b/service/src/main/inse/projects/projects_search_client.py index 638991c7..3a0a7557 100644 --- a/service/src/main/inse/projects/projects_search_client.py +++ b/service/src/main/inse/projects/projects_search_client.py @@ -30,7 +30,7 @@ from inse.model import ESCluster, ESIndex from inse.models.projects_eu_cordis.horizon2020.h2020_project_details import H2020ProjectDetails from inse.models.projects_eu_cordis.horizon_europe.heu_project_details import HEUProjectDetails from inse.models.projects_eu_cordis.fp7.fp7_project_details import Fp7ProjectDetails -from inse.projects.logic import get_person_ids_by_institution_names +from inse.projects.logic import get_person_ids_by_institution_ids, get_dfg_project_ids_by_topic_ids, get_openalex_topics_for_dfg_projects, get_person_institutes from typing import Union settings = get_settings() @@ -577,32 +577,44 @@ async def get_eu_cordis_projects_by_id( project_id=project_id ) return enriched_project + + # DFG - - async def search_dfg_projects( page: int, size: int, - institution_names: Optional[List[str]] = None, + institution_ids: Optional[List[int]] = None, names: Optional[List[str]] = None, - topics: 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_years: Optional[List[str]] = None, + funding_start_years: Optional[List[str]] = None, + funding_end_years: Optional[List[str]] = None, sort_by: str = "id", sort_direction: str = "asc", + fuzzy: bool = False, ) -> DfgProjectPage: """Searches for DFG projects based on the provided filtering and sorting criteria. Args: page (int): The page number. size (int): The number of items per page. - institution_names (Optional[List[str]], optional): The list of institution names to filter by. Defaults to None. - names (Optional[List[str]], optional): The list of names to search for. Defaults to None. - topics (Optional[List[str]], optional): The list of topics to search for. Defaults to None. - title (Optional[str], optional): The title to search for. Defaults to None. - funding_years (Optional[List[str]], optional): The funding years to filter by. Defaults to None. - sort_by (str, optional): The field to sort by. Defaults to "id". - sort_direction (str, optional): The direction to sort. Defaults to "asc". + institution_ids (Optional[List[int]], optional): Institution IDs to filter by. + names (Optional[List[str]], optional): Names to search for. + keywords (Optional[List[str]], optional): Raw keywords to search in title/abstract/subject fields. + Only used when `fuzzy=False` (or when no topic_ids are given). + topic_ids (Optional[List[str]], optional): Topic IDs to resolve to matching projects. + Only used when `fuzzy=True`. + filter_topic_ids (Optional[List[str]], optional): Additional topic IDs to filter results by + (OR semantics within this list), applied independently of the fuzzy/keyword search mode. + title (Optional[str], optional): Title to search for. + funding_start_years (Optional[List[str]], optional): Funding start years to filter by. + funding_end_years (Optional[List[str]], optional): Funding end years to filter by. + sort_by (str, optional): Field to sort by. Defaults to "id". + sort_direction (str, optional): Sort direction. Defaults to "asc". + fuzzy (bool, optional): If True, use topic_id resolution. If False, use raw keyword + phrase-prefix search. Defaults to False. Returns: DfgProjectPage: The search results. @@ -631,20 +643,56 @@ async def search_dfg_projects( } must_clauses: List[Dict[str, Any]] = [] - if topics: - for topic in topics: - if topic.strip() != "": - must_clauses.append( - { - "multi_match": { - "query": topic, - "fields": ["title", "title_de", "title_en","abstract_de","abstract_en","subject_area_de","subject_area_en","subject_classifications.fach","subject_classifications.fachkollegium","subject_classifications.fachgebiet,subject_classifications.fachgebiet_de","subject_classifications.wissenschaftsbereich"], - "type": "phrase_prefix", - "max_expansions": 100, - } - } + + # === Primary search clause: mutually exclusive fuzzy(topic_ids) vs keyword phrase search === + if fuzzy and topic_ids: + matching_project_ids = await get_dfg_project_ids_by_topic_ids( + topic_ids=topic_ids ) + if not matching_project_ids: + return DfgProjectPage(elements=[], total=0, page=page, size=size) + + must_clauses.append({"terms": {"id": matching_project_ids}}) + + elif keywords: + keyword_clauses = [] + for keyword in keywords: + if keyword.strip() == "": + continue + keyword_clauses.append( + { + "multi_match": { + "query": keyword, + "fields": [ + "title", "title_de", "title_en", + "abstract_de", "abstract_en", + "subject_area_de", "subject_area_en", + "subject_classifications.fach", + "subject_classifications.fachkollegium", + "subject_classifications.fachgebiet", + "subject_classifications.fachgebiet_de", + "subject_classifications.wissenschaftsbereich", + ], + "type": "phrase_prefix", + "max_expansions": 100, + } + } + ) + if keyword_clauses: + must_clauses.append({"bool": {"must": keyword_clauses}}) + + # === Additional independent filters (applied regardless of fuzzy/keyword mode) === + if filter_topic_ids: + matching_filter_project_ids = await get_dfg_project_ids_by_topic_ids( + topic_ids=filter_topic_ids + ) + + if not matching_filter_project_ids: + return DfgProjectPage(elements=[], total=0, page=page, size=size) + + must_clauses.append({"terms": {"id": matching_filter_project_ids}}) + if title: must_clauses.append( { @@ -656,101 +704,66 @@ async def search_dfg_projects( } } ) - if funding_years: - must_clauses.append( - { - "terms": { - "funding_start": funding_years - } - } - ) + + if funding_start_years: + must_clauses.append({"terms": {"funding_start": funding_start_years}}) + + if funding_end_years: + must_clauses.append({"terms": {"funding_end": funding_end_years}}) + if names: name_must_clauses = [] - for full_name in names: name_parts = full_name.strip().split() if not name_parts: continue - match_musts = [] - - for part in name_parts: - match_musts.append( - { - "match": { - "persons.full_name": { - "query": part, - "operator": "and", - } + match_musts = [ + { + "match": { + "persons.full_name": { + "query": part, + "operator": "and", } } - ) + } + for part in name_parts + ] name_must_clauses.append( { "nested": { "path": "persons", - "query": { - "bool": { - "must": match_musts - } - }, + "query": {"bool": {"must": match_musts}}, } } ) if name_must_clauses: - must_clauses.append( - { - "bool": { - "must": name_must_clauses - } - } - ) + must_clauses.append({"bool": {"must": name_must_clauses}}) - - if institution_names: - matching_person_ids = await get_person_ids_by_institution_names( - institution_names + if institution_ids: + matching_person_ids = await get_person_ids_by_institution_ids( + institution_ids=institution_ids ) if not matching_person_ids: - return DfgProjectPage( - elements=[], - total=0, - page=page, - size=size, - ) + return DfgProjectPage(elements=[], total=0, page=page, size=size) must_clauses.append( { "nested": { "path": "persons", - "query": { - "terms": { - "persons.person_id": matching_person_ids - } - }, + "query": {"terms": {"persons.person_id": matching_person_ids}}, } } ) + body["query"] = ( + {"bool": {"must": must_clauses}} if must_clauses else {"match_all": {}} + ) - if must_clauses: - body["query"] = { - "bool": { - "must": must_clauses - } - } - else: - body["query"] = { - "match_all": {} - } - if must_clauses: - body["query"] = {"bool": {"must": must_clauses}} - else: - body["query"] = {"match_all": {}} - + # === Sorting === sort_by = sort_by.strip().lower() sort_direction = sort_direction.strip().lower() if sort_direction not in ["asc", "desc"]: @@ -758,69 +771,61 @@ async def search_dfg_projects( logger.debug(f"Sorting DFG projects by {sort_by} with direction {sort_direction}") if sort_by in ["topic", "title"]: - logger.debug(f"Sorting DFG projects by title with direction {sort_direction}") sort_config = {"title_de.keyword": {"order": sort_direction}} elif sort_by == "funding_start": - logger.debug( - f"Sorting DFG projects by funding_start with direction {sort_direction}" - ) sort_config = {"funding_start": {"order": sort_direction}} elif sort_by == "funding_end": - logger.debug( - f"Sorting DFG projects by funding_end with direction {sort_direction}" - ) sort_config = {"funding_end": {"order": sort_direction}} elif sort_by == "professional_classification": - logger.debug( - f"Sorting DFG projects by Fachliche Zuordnung with direction {sort_direction}" - ) sort_config = {"subject_area_de.keyword": {"order": sort_direction}} else: - logger.debug(f"Sorting DFG projects by id with direction {sort_direction}") sort_config = {"id": {"order": sort_direction}} body["sort"] = [sort_config] - print(body) + + # === Execute Search === response = await elasticsearch.search( - index=ESIndex.PROJECTS_DFG_ALL, + index=ESIndex.DFG_PROJECTS, body=body, - cluster=ESCluster.INSE + cluster=ESCluster.INSE, + track_total_hits=True, ) hits = response.get("hits", {}).get("hits", []) + project_ids = [hit["_source"]["id"] for hit in hits] + topic_lookup = await get_openalex_topics_for_dfg_projects(project_ids=project_ids) + person_ids = { person["person_id"] for hit in hits for person in hit["_source"].get("persons", []) if person.get("person_id") is not None } + person_lookup = await get_person_institutes(person_ids=list(person_ids)) - person_lookup = await get_person_institutes(person_ids = list(person_ids), institution_names=institution_names) for hit in hits: - persons = hit["_source"].get("persons", []) + source = hit["_source"] + project_id = source["id"] + source["topics"] = topic_lookup.get(project_id, []) + + persons = source.get("persons", []) for person in persons: person_id = person.get("person_id") - institute = person_lookup.get(person_id) if institute: person["root_id"] = institute.get("root_id") person["institute_id"] = institute.get("institute_id") - person["root_name_de"] = institute.get("root_name_de") person["root_name_en"] = institute.get("root_name_en") - person["institute_name_de"] = institute.get("institute_name_de") person["institute_name_en"] = institute.get("institute_name_en") person["address_country_de"] = institute.get("address_country_de") person["address_country_en"] = institute.get("address_country_en") - - - - return _complete_response_to_dfg_project_page(response, page, size) + return _complete_response_to_dfg_project_page(response, page, size) def _complete_response_to_dfg_project_page( response: dict, page: int, size: int @@ -840,96 +845,6 @@ def _complete_response_to_dfg_project_page( elements = [DfgProjectSummary.from_hit(hit) for hit in hits_block.get("hits", [])] return DfgProjectPage(elements=elements, total=total_hits, page=page, size=size) -async def get_person_institutes( - person_ids: list[int], - institution_names: list[str] | None = None, -) -> dict[str, dict]: - - if not person_ids: - return {} - query = { - "bool": { - "must": [ - { - "terms": { - "id": person_ids, - } - } - ] - } - } - if institution_names: - query["bool"]["must"].append( - { - "bool": { - "must": [ - { - "match_phrase": { - "institute_name_de": institution_names - } - }, - { - "match_phrase": { - "institute_name_en": institution_names - } - }, - { - "match_phrase": { - "root_name_de": institution_names - } - }, - { - "match_phrase": { - "root_name_en": institution_names - } - }, - ], - "minimum_should_match": 1, - } - } - ) - - response = await elasticsearch.search( - index=ESIndex.PROJECTS_DFG_PERSONS, - cluster=ESCluster.INSE, - body={ - "size": len(person_ids), - "_source": [ - "person_id", - "root_id", - "institute_id", - "root_name_de", - "root_name_en", - "institute_name_de", - "institute_name_en", - "address_country_de", - "address_country_en", - ], - "query": { - "terms": { - "person_id": person_ids, - } - }, - }, - ) - - result = {} - - for hit in response["hits"]["hits"]: - source = hit["_source"] - - result[source["person_id"]] = { - "person_id": source["person_id"], - "root_id": source.get("root_id"), - "institute_id": source.get("institute_id"), - "root_name_de": source.get("root_name_de"), - "root_name_en": source.get("root_name_en"), - "institute_name_de": source.get("institute_name_de"), - "institute_name_en": source.get("institute_name_en"), - "address_country_de": source.get("address_country_de"), - "address_country_en": source.get("address_country_en"), - } - return result async def get_dfg_project_by_id(project_id: str) -> Optional[DfgProjectDetails]: """Fetches the details of a single DFG project based on its project ID. @@ -943,7 +858,7 @@ async def get_dfg_project_by_id(project_id: str) -> Optional[DfgProjectDetails]: query = {"ids": {"values": [project_id]}} response = await elasticsearch.search( - index=ESIndex.PROJECTS_DFG_ALL, + index=ESIndex.DFG_PROJECTS, query=query, size=1, ) @@ -1114,7 +1029,7 @@ def _hit_to_funding_project(hit: Dict[str, Any]) -> FundingProject: return FundingProject.from_cordis_projects_hit(hit=hit) elif hit.get("_index") == ESIndex.PROJECTS_BUND_V1.value: return FundingProject.from_bund_projects_hit(hit=hit) - elif hit.get("_index") == ESIndex.PROJECTS_DFG_ALL.value: + elif hit.get("_index") == ESIndex.DFG_PROJECTS.value: return FundingProject.from_dfg_projects_hit(hit=hit) else: raise ValueError( diff --git a/service/src/main/inse/projects/router.py b/service/src/main/inse/projects/router.py index 10647600..699b4d22 100644 --- a/service/src/main/inse/projects/router.py +++ b/service/src/main/inse/projects/router.py @@ -322,44 +322,71 @@ async def get_dfg_projects( title: Annotated[ Optional[str], Query(description="The title to filter by.") ] = None, - topics: Annotated[ - Optional[List[str]], Query(description="The topics to filter by.") + keywords: Annotated[ + Optional[List[str]], Query(description="Raw keywords to search in title/abstract/subject fields.") ] = None, - funding_years: Annotated[Optional[List[str]], Query(description="The funding years to filter by.")] = None, + topic_ids: Annotated[ + Optional[List[str]], Query(description="The openalex topic IDs to filter by.") + ] = None, + filter_topic_ids: Annotated[ + Optional[List[str]], + Query( + description="Additional topic IDs to merge into the fuzzy topic-id resolution " + "(union with topic_ids). Only used when fuzzy=True." + ), + ] = None, + funding_start_years: Annotated[Optional[List[str]], Query(description="The funding start years to filter by.")] = None, + funding_end_years: Annotated[Optional[List[str]], Query(description="The funding end years to filter by.")] = None, + page: Annotated[int, Query(description="The page number.", ge=0)] = 0, size: Annotated[int, Query(description="The page size.", ge=1)] = 20, sort_by: Annotated[str, Query(description="The field to sort by.")] = "title", sort_direction: Annotated[ str, Query(description="The sort direction (asc or desc).") ] = "asc", - + fuzzy: Annotated[ + bool, + Query(description="Use topic_id resolution if True, otherwise use raw keyword search."), + ] = False, + ) -> DfgProjectPage: logger.debug( - "Received request to get DFG projects for author_id=%s, author_filter_ids=%s, topics=%s, title=%s, funding_years=%s, page=%d, size=%d, sort_by=%s, sort_direction=%s", + "Received request to get DFG projects for author_id=%s, author_filter_ids=%s, " + "institution_ids=%s, keywords=%s, topic_ids=%s, filter_topic_ids=%s, title=%s, " + "funding_start_years=%s, funding_end_years=%s, page=%d, size=%d, sort_by=%s, " + "sort_direction=%s, fuzzy=%s", author_id, author_filter_ids, - topics, + institution_ids, + keywords, + topic_ids, + filter_topic_ids, title, - funding_years, + funding_start_years, + funding_end_years, page, size, sort_by, sort_direction, + fuzzy, ) return await projects_service.get_dfg_projects_by_author_id( author_id=author_id, author_filter_ids=author_filter_ids, institution_ids=institution_ids, - funding_years=funding_years, + funding_start_years=funding_start_years, + funding_end_years=funding_end_years, title=title, - topics=topics, + keywords=keywords, + topic_ids=topic_ids, + filter_topic_ids=filter_topic_ids, page=page, size=size, sort_by=sort_by, sort_direction=sort_direction, + fuzzy=fuzzy, ) - @router.get( "/search", summary="Search projects across all funders.", diff --git a/service/src/main/inse/projects/service.py b/service/src/main/inse/projects/service.py index b91f9325..86637a6f 100644 --- a/service/src/main/inse/projects/service.py +++ b/service/src/main/inse/projects/service.py @@ -151,28 +151,37 @@ async def get_dfg_projects_by_author_id( author_id: Optional[str], author_filter_ids: Optional[List[int]], institution_ids: Optional[List[int]], - topics: Optional[List[str]], + keywords: Optional[List[str]], + topic_ids: Optional[List[str]], + filter_topic_ids: Optional[List[str]], title: Optional[str], - funding_years: Optional[List[str]], + funding_start_years: Optional[List[str]], + funding_end_years: Optional[List[str]], page: int, size: int, sort_by: str = "topic", sort_direction: str = "asc", + fuzzy: bool = False, ) -> DfgProjectPage: logger.debug( "Fetching DFG projects for author_id=%s, author_filter_ids=%s, " - "institution_ids=%s, topics=%s, title=%s, funding_years=%s, " - "page=%s, size=%s, sort_by=%s, sort_direction=%s", + "institution_ids=%s, keywords=%s, topic_ids=%s, filter_topic_ids=%s, title=%s, " + "funding_start_years=%s, funding_end_years=%s, " + "page=%s, size=%s, sort_by=%s, sort_direction=%s, fuzzy=%s", author_id, author_filter_ids, institution_ids, - topics, + keywords, + topic_ids, + filter_topic_ids, title, - funding_years, + funding_start_years, + funding_end_years, page, size, sort_by, sort_direction, + fuzzy, ) filter_names = [] author_name = ( @@ -184,7 +193,7 @@ async def get_dfg_projects_by_author_id( logger.debug("No author name found for author_id=%s", author_id) filter_names = ( - await get_dfg_author_names_by_ids(author_ids = author_filter_ids) + await get_dfg_author_names_by_ids(author_ids=author_filter_ids) if author_filter_ids else [] ) @@ -197,13 +206,7 @@ async def get_dfg_projects_by_author_id( if author_name: filter_names.append(author_name) - institution_names = ( - await get_dfg_institution_names_by_ids(institution_ids) - if institution_ids - else [] - ) - - if institution_ids and not institution_names: + if institution_ids: logger.debug( "No institutions found for institution_ids=%s", institution_ids, @@ -213,13 +216,18 @@ async def get_dfg_projects_by_author_id( page=page, size=size, names=filter_names or [], - institution_names=institution_names, - topics=topics, + institution_ids=institution_ids, + keywords=keywords, + topic_ids=topic_ids, + filter_topic_ids=filter_topic_ids, title=title, - funding_years=funding_years, + funding_start_years=funding_start_years, + funding_end_years=funding_end_years, sort_by=sort_by, sort_direction=sort_direction, + fuzzy=fuzzy, ) + async def get_institution_cordis_eu_projects_funding_over_time( institutions_search_client: InstitutionsSearchClient, raw_oa_institution_id: str, diff --git a/webapp/src/app/api/api/projects.service.ts b/webapp/src/app/api/api/projects.service.ts index 0928793a..9689556f 100644 --- a/webapp/src/app/api/api/projects.service.ts +++ b/webapp/src/app/api/api/projects.service.ts @@ -69,19 +69,23 @@ export class ProjectsService extends BaseService { * @param authorFilterIds The author IDs to filter by. * @param institutionIds The institution IDs to filter by. * @param title The title to filter by. - * @param topics The topics to filter by. - * @param fundingYears The funding years to filter by. + * @param keywords Raw keywords to search in title/abstract/subject fields. + * @param topicIds The openalex topic IDs to filter by. + * @param filterTopicIds Additional topic IDs to merge into the fuzzy topic-id resolution (union with topic_ids). Only used when fuzzy=True. + * @param fundingStartYears The funding start years to filter by. + * @param fundingEndYears The funding end years to filter by. * @param page The page number. * @param size The page size. * @param sortBy The field to sort by. * @param sortDirection The sort direction (asc or desc). + * @param fuzzy Use topic_id resolution if True, otherwise use 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 getDfgProjects(authorId?: string, authorFilterIds?: Array, institutionIds?: Array, title?: string, topics?: Array, fundingYears?: Array, page?: number, size?: number, sortBy?: string, sortDirection?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; - public getDfgProjects(authorId?: string, authorFilterIds?: Array, institutionIds?: Array, title?: string, topics?: Array, fundingYears?: Array, page?: number, size?: number, sortBy?: string, sortDirection?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public getDfgProjects(authorId?: string, authorFilterIds?: Array, institutionIds?: Array, title?: string, topics?: Array, fundingYears?: Array, page?: number, size?: number, sortBy?: string, sortDirection?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public getDfgProjects(authorId?: string, authorFilterIds?: Array, institutionIds?: Array, title?: string, topics?: Array, fundingYears?: Array, page?: number, size?: number, sortBy?: string, sortDirection?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + public getDfgProjects(authorId?: string, authorFilterIds?: Array, institutionIds?: Array, title?: string, keywords?: Array, topicIds?: Array, filterTopicIds?: Array, fundingStartYears?: Array, fundingEndYears?: Array, page?: number, size?: number, sortBy?: string, sortDirection?: string, fuzzy?: boolean, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public getDfgProjects(authorId?: string, authorFilterIds?: Array, institutionIds?: Array, title?: string, keywords?: Array, topicIds?: Array, filterTopicIds?: Array, fundingStartYears?: Array, fundingEndYears?: Array, page?: number, size?: number, sortBy?: string, sortDirection?: string, fuzzy?: boolean, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getDfgProjects(authorId?: string, authorFilterIds?: Array, institutionIds?: Array, title?: string, keywords?: Array, topicIds?: Array, filterTopicIds?: Array, fundingStartYears?: Array, fundingEndYears?: Array, page?: number, size?: number, sortBy?: string, sortDirection?: string, fuzzy?: boolean, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getDfgProjects(authorId?: string, authorFilterIds?: Array, institutionIds?: Array, title?: string, keywords?: Array, topicIds?: Array, filterTopicIds?: Array, fundingStartYears?: Array, fundingEndYears?: Array, page?: number, size?: number, sortBy?: string, sortDirection?: string, fuzzy?: boolean, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { let localVarQueryParameters = new HttpParams({encoder: this.encoder}); localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, @@ -100,16 +104,34 @@ export class ProjectsService extends BaseService { } localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, title, 'title'); - if (topics) { - topics.forEach((element) => { + if (keywords) { + keywords.forEach((element) => { localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - element, 'topics'); + element, 'keywords'); }) } - if (fundingYears) { - fundingYears.forEach((element) => { + if (topicIds) { + topicIds.forEach((element) => { localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - element, 'funding_years'); + 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'); }) } localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, @@ -120,6 +142,8 @@ export class ProjectsService extends BaseService { sortBy, 'sort_by'); localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, sortDirection, 'sort_direction'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + fuzzy, 'fuzzy'); let localVarHeaders = this.defaultHeaders; diff --git a/webapp/src/app/api/model/dfgProjectSummary.ts b/webapp/src/app/api/model/dfgProjectSummary.ts index f3e80b4a..cc1d2b59 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 @@ -9,31 +9,31 @@ */ import { DfgInstitutionSummary } from './dfgInstitutionSummary'; 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; +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/app.routes.ts b/webapp/src/app/app.routes.ts index d633eecf..d3cfe683 100644 --- a/webapp/src/app/app.routes.ts +++ b/webapp/src/app/app.routes.ts @@ -8,7 +8,10 @@ import { personResolver } from './resolvers/person.resolver'; import { personNewsResolver } from './resolvers/person-news.resolver'; import { institutionResolver } from './resolvers/institution.resolver'; import { bundProjectPageResolver } from './resolvers/bund-project-page.resolver'; -import { dfgProjectsResolver } from './resolvers/dfg-projects.resolver'; +import { + dfgProjectsResolver, + RESOLVING_PROJECT_PAGE_FOR, +} from './resolvers/dfg-projects.resolver'; import { institutionsResolver } from './resolvers/institutions.resolver'; import { bundProjectsFundingResolver } from './resolvers/bund-projects-funding.resolver'; import { dfgSingleProjectResolver } from './resolvers/dfg-single-project-resolver'; @@ -167,7 +170,23 @@ export const routes: Routes = [ children: [ { path: '', pathMatch: 'full', redirectTo: 'persons' }, { path: 'persons', component: KeywordsToPersonsResultsComponent }, - { path: 'projects', component: KeywordsToProjectsResultsComponent }, + { + 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, + }, + }, { path: 'patents', component: KeywordsToPatentsResultsComponent }, { path: 'works', @@ -177,6 +196,10 @@ export const routes: Routes = [ selectedTopicsPage: selectedTopicsResolver, selectedAuthorsPage: selectedAuthorsResolver, selectedInstitutionsPage: selectedInstitutionsResolver, + workPage: workPageResolver, + }, + data: { + resolvingFor: RESOLVING_WORK_PAGE_FOR.KEYWORDS_SEARCH, }, }, { path: 'news', component: KeywordsToNewsResultsComponent }, @@ -384,10 +407,14 @@ export const routes: Routes = [ personCordisEuProjectPage: personCordisEuProjectPageResolver, selectedDfgInstitutionsPage: selectedDfgInstitutionsResolver, selectedDfgAuthorsPage: selectedDfgAuthorsResolver, + selectedTopicsPage: selectedTopicsResolver, selectedEuInstitutionsPage: selectedInstitutionsResolver, selectedEuAuthorsPage: selectedAuthorsResolver, }, runGuardsAndResolvers: 'always', + data: { + resolvingFor: RESOLVING_PROJECT_PAGE_FOR.PERSON, + }, }, { path: 'publications', 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 80f6a51b..dd9481b3 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 @@ -1,31 +1,36 @@ -
- - - groups -

Projectsliste

-

- Die aktuelle Gewichtung ist unter normalized verfügbar. -

-
-
- - +
+
+
Projekte
+

Übersicht der durchgeführten Projekte.

+
+ - + + + + + + + + + +
diff --git a/webapp/src/app/modules/keywords-search/search-results/projects-results/projects-results.component.scss b/webapp/src/app/modules/keywords-search/search-results/projects-results/projects-results.component.scss index ffeea20d..9bd15288 100644 --- a/webapp/src/app/modules/keywords-search/search-results/projects-results/projects-results.component.scss +++ b/webapp/src/app/modules/keywords-search/search-results/projects-results/projects-results.component.scss @@ -1,29 +1,13 @@ -/* ============================================================ - RESULT LAYOUT - ============================================================ */ -.result-layout { - display: grid; - grid-template-columns: minmax(300px, 420px) 1fr; - grid-template-areas: 'summary results'; - gap: 0.75rem; - align-items: start; +.person-projects { + padding: 2rem; } -.search-summary-card { - grid-area: summary; +.description-container { + display: flex; + flex-direction: column; } -.results-card { - grid-area: results; -} - -.search-summary-card, -.results-card { - background: var(--sg-surface, #ffffff); - border: 1px solid var(--sg-divider, rgba(0, 0, 0, 0.12)); - box-shadow: none; - - .mat-mdc-card-content { - padding: 0.75rem; - } +mat-card, +mat-paginator { + background-color: var(--sg-background); } 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 61c4e797..aec16222 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,111 +1,73 @@ -import { Component, inject, signal } from '@angular/core'; - -import { MatCardModule } from '@angular/material/card'; -import { MatIconModule } from '@angular/material/icon'; - +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 { - WeightMap, - WeightSliderOption, - WeightsSlidersComponent, - WeightsSlidersValue, -} from '../../../../shared/ui/weights-sliders/weights-sliders.component'; + CordisEuProjectPage, + DfgProjectPage, + AuthorPage, + InstitutionPageV2, + DfgPersonSummaryPage, + TopicPageV2, +} from '../../../../api'; +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'; + import { SearchResultsStateService } from '../search-results-state.service'; @Component({ selector: 'app-projects-results', - imports: [MatCardModule, MatIconModule, WeightsSlidersComponent], + imports: [ + MatCardModule, + MatTabsModule, + ProjectFilterComponent, + DfgProjectTableComponent, + EuProjectTableComponent, + ], templateUrl: './projects-results.component.html', styleUrl: './projects-results.component.scss', }) export class KeywordsToProjectsResultsComponent { - // injects the state set by the parent route — no duplicate parsing here - private readonly state = inject(SearchResultsStateService); + dfgProjectPage = input.required(); + personCordisEuProjectPage = input.required(); - readonly defaultWeights: WeightMap = { - param1: 0.33, - param2: 0.33, - param3: 0.34, - }; + selectedDfgInstitutionsPage = input.required(); + selectedDfgAuthorsPage = input.required(); + selectedTopicsPage = input.required(); - readonly weightOptions: WeightSliderOption[] = [ - { - key: 'param1', - label: 'Parameter 1', - icon: 'workspace_premium', - description: 'Gewichtet Parameter 1.', - defaultValue: 0.5, - queryParamName: 'wParam1', - }, - { - key: 'param2', - label: 'Parameter 2', - icon: 'workspace_premium', - description: 'Gewichtet Parameter 2.', - defaultValue: 0.5, - queryParamName: 'wParam2', - }, - { - key: 'param3', - label: 'Parameter 3', - icon: 'workspace_premium', - description: 'Gewichtet Parameter 3.', - defaultValue: 0.5, - queryParamName: 'wParam3', - }, - ]; + selectedEuInstitutionsPage = input.required(); + selectedEuAuthorsPage = input.required(); - readonly currentWeights = signal({ - raw: this.defaultWeights, - normalized: { - param1: 0.33, - param2: 0.33, - param3: 0.34, - }, - rawSum: 2.5, - normalizedSum: 1, - valid: true, + 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; }); - readonly projects = signal([]); // placeholder until the results service lands - - private hasLoadedInitial = false; - - onWeightsChange(value: WeightsSlidersValue): void { - this.currentWeights.set(value); - - // fires once with the query-param-aware initial state — use it to load - if (!this.hasLoadedInitial) { - this.hasLoadedInitial = true; - this.loadprojects(); - } - } - - onApplyWeights(value: WeightsSlidersValue): void { - this.currentWeights.set(value); - this.loadprojects(); - } - - private loadprojects(): void { - const weights = this.currentWeights(); - - const requestPayload = { - manualKeywords: this.state.manualKeywords(), - extractedKeywords: this.state.extractedKeywords(), - keywords: this.state.keywords(), - fuzzy: this.state.fuzzySearch(), - weights: { - raw: weights.raw, - normalized: weights.normalized, - }, - }; - - console.log(requestPayload); - - /** - * TODO: - * this.projectsService.searchprojects(requestPayload).subscribe({ - * next: results => this.projects.set(results), - * error: error => console.error(error), - * }); - */ + onTabChange(index: number): void { + const type = index === 1 ? 'eu' : 'dfg'; + this.router.navigate([], { + queryParams: { [PROJECT_TAB_QUERY_PARAM_KEY]: type }, + queryParamsHandling: 'merge', + }); } } diff --git a/webapp/src/app/modules/keywords-search/search-results/works-results/works-results.component.html b/webapp/src/app/modules/keywords-search/search-results/works-results/works-results.component.html index 0edb91db..7f6d987c 100644 --- a/webapp/src/app/modules/keywords-search/search-results/works-results/works-results.component.html +++ b/webapp/src/app/modules/keywords-search/search-results/works-results/works-results.component.html @@ -5,15 +5,11 @@ [selectedAuthorsPage]="selectedAuthorsPage()" [showTopicFilter]="fuzzySearch()" /> - @if (loading()) { - - } @else { - - } + (false); - - private readonly yearParamKey = workQueryParamKeys.years; - private readonly typeParamKey = workQueryParamKeys.types; - private readonly languageParamKey = workQueryParamKeys.language; private readonly institutionParamKey = workQueryParamKeys.institutionId; private readonly authorParamKey = workQueryParamKeys.authorId; private readonly topicParamKey = workQueryParamKeys.topicId; - private readonly pageParamKey = workQueryParamKeys.page; queryParamMap = toSignal(this.route.queryParamMap, { initialValue: this.route.snapshot.queryParamMap, @@ -87,122 +52,20 @@ export class KeywordsToWorksResultsComponent implements OnInit { this.queryParamMap().getAll(this.topicParamKey), ); - total = computed(() => this.works()?.total ?? 0); - totalElements = computed(() => this.works()?.total ?? 0); - elements = computed(() => this.works()?.elements ?? []); - fuzzySearch = computed(() => this.queryParamMap().get('fuzzy') === 'true'); - - readonly works = toSignal( - this.route.queryParamMap.pipe( - switchMap((params) => this.fetchWorks(params)), - takeUntilDestroyed(this.destroyRef), - ), - { initialValue: EMPTY_WORK_PAGE }, - ); - - private readonly institutionsFromWorks = computed(() => { - const map = new Map(); - for (const work of this.works().elements ?? []) { - for (const authorship of work.authorships ?? []) { - for (const institution of authorship.institutions ?? []) { - if (institution.id) map.set(institution.id, institution); - } - } - } - return map; - }); - private readonly authorsFromWorks = computed(() => { - const map = new Map(); - for (const work of this.works().elements ?? []) { - for (const authorship of work.authorships ?? []) { - const author = authorship.author; - if (author?.id) map.set(author.id, author); - } - } - return map; - }); - - private readonly topicsFromWorks = computed(() => { - const map = new Map(); - for (const work of this.works().elements ?? []) { - for (const topic of work.topics ?? []) { - if (topic.id) map.set(topic.id, topic); - } - } - return map; - }); - selectedAuthors = computed(() => { - const byId = this.authorsFromWorks(); - return this.selectedAuthorIdsQueryParams() - .map((id) => byId.get(id)) - .filter((author): author is Author => !!author); - }); + workPage = input.required(); selectedInstitutionsPage = input.required(); selectedTopicsPage = input.required(); selectedAuthorsPage = input.required(); + total = computed(() => this.workPage().total ?? 0); + totalElements = computed(() => this.workPage().total ?? 0); + elements = computed(() => this.workPage().elements ?? []); + + fuzzySearch = computed(() => this.queryParamMap().get('fuzzy') === 'true'); + ngOnInit(): void {} - private fetchWorks(params: ParamMap) { - this.loading.set(true); - // Base search topics — derived from the keyword→topic mapping. - // This remains the actual search criterion. - const baseTopicIds = this.state - .selectedKeywordEntries() - .map((entry) => entry.topic_mapping?.topic?.id) - .filter((id): id is string => !!id); - - const keywords = this.state.keywords(); - - if (baseTopicIds.length === 0 && keywords.length === 0) { - this.loading.set(false); - return of(EMPTY_WORK_PAGE); - } - const title = params.get('title') ?? undefined; - const filterTopicIds = params.getAll(this.topicParamKey); - const page = Number(params.get(this.pageParamKey)) || 0; - const size = Number(params.get('size')) || 10; - const publicationYears = params - .getAll(this.yearParamKey) - .map(Number) - .filter((year) => !Number.isNaN(year)); - const publicationTypes = params.getAll(this.typeParamKey); - const publicationLanguages = params.getAll(this.languageParamKey); - const institutionIds = params.getAll(this.institutionParamKey); - const authorIds = params.getAll(this.authorParamKey); - const fuzzy = params.get('fuzzy') === 'true'; - const sortBy = (params.get('sort_by') ?? 'publication_year') as WorkSortBy; - const sortDirection = (params.get('sort_direction') ?? - 'desc') as SortDirection; - - return this.worksService - .getWorksByKeywords( - [], - baseTopicIds, - filterTopicIds, - keywords, - fuzzy, - publicationYears, - publicationTypes, - institutionIds, - authorIds, - publicationLanguages, - title, - page, - size, - sortBy, - sortDirection, - ) - .pipe( - catchError((err) => { - console.error(err); - return of(EMPTY_WORK_PAGE); - }), - finalize(() => this.loading.set(false)), - ); - } - clearFilters(): void { this.router.navigate([], { queryParams: { 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 e5d5bad9..5372cfb4 100644 --- a/webapp/src/app/modules/person-projects/person-projects.component.html +++ b/webapp/src/app/modules/person-projects/person-projects.component.html @@ -11,11 +11,17 @@ 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 2328bff5..91dda724 100644 --- a/webapp/src/app/modules/person-projects/person-projects.component.ts +++ b/webapp/src/app/modules/person-projects/person-projects.component.ts @@ -5,10 +5,10 @@ import { DfgInstitutionSummaryPage } from '../../api/model/dfgInstitutionSummary import { CordisEuProjectPage, DfgProjectPage, - Author, - Institution, AuthorPage, InstitutionPageV2, + TopicPageV2, + DfgPersonSummaryPage, } from '../../api'; import { MatCardModule } from '@angular/material/card'; import { MatTabsModule } from '@angular/material/tabs'; @@ -37,9 +37,10 @@ export class PersonProjectsComponent { personCordisEuProjectPage = input.required(); selectedDfgInstitutionsPage = input.required(); - selectedDfgAuthorsPage = input.required(); + selectedDfgAuthorsPage = input.required(); selectedEuInstitutionsPage = input.required(); selectedEuAuthorsPage = input.required(); + selectedTopicsPage = input.required(); readonly dfgQueryParamKeys = projectQueryParamKeys; readonly euQueryParamKeys = euProjectQueryParamKeys; diff --git a/webapp/src/app/resolvers/dfg-projects.resolver.ts b/webapp/src/app/resolvers/dfg-projects.resolver.ts index 7d19daba..ab88d9c7 100644 --- a/webapp/src/app/resolvers/dfg-projects.resolver.ts +++ b/webapp/src/app/resolvers/dfg-projects.resolver.ts @@ -7,17 +7,33 @@ export const projectQueryParamKeys = { size: 'size', title: 'title', institutionId: 'institutionId', - years: 'years', + funding_start: 'funding_start', + funding_end: 'funding_end', authorId: 'authorId', topicId: 'topicId', sortBy: 'sort_by', sortDirection: 'sort_direction', } as const; - +const RESOLVING_PROJECT_PAGE_FOR_KEY = 'resolvingFor'; +export const RESOLVING_PROJECT_PAGE_FOR = { + PERSON: 'PERSON', + KEYWORDS_SEARCH: 'KEYWORDS_SEARCH', +} as const; export const dfgProjectsResolver: ResolveFn = ( route, state, ) => { + const resolvingFor: (typeof RESOLVING_PROJECT_PAGE_FOR)[keyof typeof RESOLVING_PROJECT_PAGE_FOR] = + route.data[RESOLVING_PROJECT_PAGE_FOR_KEY] || + RESOLVING_PROJECT_PAGE_FOR.PERSON; + + console.log( + 'Resolving project page for', + resolvingFor, + 'with route data:', + route.data, + ); + const rawAuthorId = route.parent?.params['id']; const page = Number(route.queryParamMap.get(projectQueryParamKeys.page)) || 0; @@ -30,11 +46,15 @@ export const dfgProjectsResolver: ResolveFn = ( const sortDirection = route.queryParamMap.get(projectQueryParamKeys.sortDirection) || 'asc'; - // TODO: verify ProjectsService.getDfgProjects accepts institution/author - // filters. Wire these in once the service signature supports them. - const topics = route.queryParamMap.getAll(projectQueryParamKeys.topicId); - - const years = route.queryParamMap.getAll(projectQueryParamKeys.years); + const fundingStart = route.queryParamMap.getAll( + projectQueryParamKeys.funding_start, + ); + const fundingEnd = route.queryParamMap.getAll( + projectQueryParamKeys.funding_end, + ); + const filteredTopicIds = route.queryParamMap.getAll( + projectQueryParamKeys.topicId, + ); const institutionIds = route.queryParamMap .getAll(projectQueryParamKeys.institutionId) .map((id) => Number(id)) @@ -43,24 +63,44 @@ export const dfgProjectsResolver: ResolveFn = ( .getAll(projectQueryParamKeys.authorId) .map((id) => Number(id)) .filter((id) => !isNaN(id)); - console.log( - 'RESOLVING', - authorIds, - institutionIds, - topics, - years, - searchTerm, - ); - return inject(ProjectsService).getDfgProjects( - rawAuthorId, - authorIds, - institutionIds, - searchTerm, - topics, - years, - page, - size, - sortBy, - sortDirection, - ); + if (resolvingFor === RESOLVING_PROJECT_PAGE_FOR.PERSON) { + return inject(ProjectsService).getDfgProjects( + rawAuthorId, + authorIds, + institutionIds, + searchTerm, + [], + [], + filteredTopicIds, + fundingStart, + fundingEnd, + page, + size, + sortBy, + sortDirection, + false, + ); + } else if (resolvingFor === RESOLVING_PROJECT_PAGE_FOR.KEYWORDS_SEARCH) { + const keywords = route.queryParamMap.get('keywords')?.split(',') ?? []; + const selectedTopicIds = route.queryParamMap.getAll('topics'); + const fuzzySearch = route.queryParamMap.get('fuzzy') === 'true'; + return inject(ProjectsService).getDfgProjects( + undefined, + authorIds, + institutionIds, + searchTerm, + keywords, + selectedTopicIds, + filteredTopicIds, + fundingStart, + fundingEnd, + page, + size, + sortBy, + sortDirection, + fuzzySearch, + ); + } else { + throw new Error(`Unknown resolvingFor value: ${resolvingFor}`); + } }; diff --git a/webapp/src/app/resolvers/person-cordis-eu-project-page.resolver.ts b/webapp/src/app/resolvers/person-cordis-eu-project-page.resolver.ts index 1bec6001..9632940c 100644 --- a/webapp/src/app/resolvers/person-cordis-eu-project-page.resolver.ts +++ b/webapp/src/app/resolvers/person-cordis-eu-project-page.resolver.ts @@ -15,10 +15,10 @@ export const euProjectQueryParamKeys = { export const personCordisEuProjectPageResolver: ResolveFn< CordisEuProjectPage > = (route, state) => { - const rawAuthorId = route.parent?.paramMap.get('id') ?? null; - if (!rawAuthorId) { - throw new Error('Author ID is required to resolve EU projects.'); - } + const rawAuthorId = route.parent?.params['id']; + // if (!rawAuthorId) { + // throw new Error('Author ID is required to resolve EU projects.'); + // } const page = Number(route.queryParamMap.get(euProjectQueryParamKeys.page)) || 0; @@ -38,7 +38,7 @@ export const personCordisEuProjectPageResolver: ResolveFn< euProjectQueryParamKeys.authorId, ); return inject(ProjectsService).getEuProjectsForAuthor( - rawAuthorId, + rawAuthorId || '1', // searchTerm, // page, // size, diff --git a/webapp/src/app/resolvers/work-page.resolver.ts b/webapp/src/app/resolvers/work-page.resolver.ts index 1d186e9e..f42a153d 100644 --- a/webapp/src/app/resolvers/work-page.resolver.ts +++ b/webapp/src/app/resolvers/work-page.resolver.ts @@ -8,6 +8,7 @@ import { SortDirection, WorkSortBy, WorksV2Service, + WorksService, } from '../api'; import { inject } from '@angular/core'; @@ -15,6 +16,7 @@ const RESOLVING_WORK_PAGE_FOR_KEY = 'resolvingFor'; export const RESOLVING_WORK_PAGE_FOR = { PERSON: 'PERSON', INSTITUTION: 'INSTITUTION', + KEYWORDS_SEARCH: 'KEYWORDS_SEARCH', } as const; export const workQueryParamKeys = { @@ -106,6 +108,55 @@ export const workPageResolver: ResolveFn = ( sortBy, sortDirection, ); + } else if (resolvingFor === RESOLVING_WORK_PAGE_FOR.KEYWORDS_SEARCH) { + const baseTopicIds = route.queryParamMap.get('topics')?.split(',') ?? []; + const keywords = route.queryParamMap.get('keywords')?.split(',') ?? []; + + const title = + route.queryParamMap.get(workQueryParamKeys.title) ?? undefined; + const filterTopicIds = route.queryParamMap.getAll( + workQueryParamKeys.topicId, + ); + const page = Number(route.queryParamMap.get(workQueryParamKeys.page)) || 0; + const size = Number(route.queryParamMap.get(workQueryParamKeys.size)) || 10; + const publicationYears = route.queryParamMap + .getAll(workQueryParamKeys.years) + .map(Number) + .filter((year) => !Number.isNaN(year)); + const publicationTypes = route.queryParamMap.getAll( + workQueryParamKeys.types, + ); + const publicationLanguages = route.queryParamMap.getAll( + workQueryParamKeys.language, + ); + const institutionIds = route.queryParamMap.getAll( + workQueryParamKeys.institutionId, + ); + const authorIds = route.queryParamMap.getAll(workQueryParamKeys.authorId); + const fuzzy = route.queryParamMap.get('fuzzy') === 'true'; + const sortBy = (route.queryParamMap.get(workQueryParamKeys.sortBy) ?? + 'publication_year') as WorkSortBy; + const sortDirection = (route.queryParamMap.get( + workQueryParamKeys.sortDirection, + ) ?? 'desc') as SortDirection; + + return inject(WorksV2Service).getWorksByKeywords( + [], + baseTopicIds, + filterTopicIds, + keywords, + fuzzy, + publicationYears, + publicationTypes, + institutionIds, + authorIds, + publicationLanguages, + title, + page, + size, + sortBy, + sortDirection, + ); } else { throw new Error(`Unknown resolvingFor value: ${resolvingFor}`); } diff --git a/webapp/src/app/shared/ui/dfg-project-table/dfg-project-table.component.html b/webapp/src/app/shared/ui/dfg-project-table/dfg-project-table.component.html index 2d3860e5..9eeee1aa 100644 --- a/webapp/src/app/shared/ui/dfg-project-table/dfg-project-table.component.html +++ b/webapp/src/app/shared/ui/dfg-project-table/dfg-project-table.component.html @@ -11,7 +11,11 @@ [pageSizeOptions]="[10]" /> - {{ element.funding_end == '2999' ? 'laufend' : element.funding_end }} + {{ + element.funding_end == '2999' || element.funding_end == null + ? 'laufend' + : element.funding_end + }} @@ -23,6 +27,20 @@ open_in_new + +
+ @for (classification of element.subject_classifications; track $index) { +

+ {{ classification.wissenschaftsbereich || '-' }} + → {{ classification.fachkollegium || '-' }} → + {{ classification.fachgebiet || '-' }} → + {{ classification.fach || '-' }} +

+ } @empty { + - + } +
+
@let projectAuthors = getProjectAuthors(project); @@ -104,59 +122,37 @@ }
- + diff --git a/webapp/src/app/shared/ui/dfg-project-table/dfg-project-table.component.scss b/webapp/src/app/shared/ui/dfg-project-table/dfg-project-table.component.scss index fe4f1b94..3fd1bb17 100644 --- a/webapp/src/app/shared/ui/dfg-project-table/dfg-project-table.component.scss +++ b/webapp/src/app/shared/ui/dfg-project-table/dfg-project-table.component.scss @@ -4,189 +4,10 @@ margin: 0 auto; } -.publication-filter-stack { - display: flex; - align-items: flex-start; - flex-direction: column; - gap: 8px; - padding-top: 10px; - padding-bottom: 25px; -} +// ------------------------ +// Shared tags & chips +// ------------------------ -.publication-filters { - display: flex; - flex-wrap: wrap; - justify-content: flex-end; - align-items: center; - gap: 10px; -} - -.publication-filters mat-form-field { - width: 175px; -} - -.publication-filters .institution-filter, -.publication-filters .topic-filter { - flex: 1 1 200px; - width: auto; - min-width: 180px; - max-width: 320px; -} - -.publication-filters .sort-field { - width: 235px; -} - -.publication-filters .reset-filter-btn { - min-width: 132px; - height: 42px; - padding: 0 14px; - border-color: #d9e2f0; - border-radius: var(--sg-radius-sm); - color: var(--sg-text); - background: #fff; -} - -.publication-filters .reset-filter-btn mat-icon { - margin-right: 6px; - width: 20px; - height: 20px; - font-size: 20px; -} - -::ng-deep .publication-filters .mat-mdc-form-field-subscript-wrapper { - display: none; -} - -::ng-deep .publication-filters .mat-mdc-text-field-wrapper { - height: 42px; - background: var(--sg-surface-soft); - border: 1px solid var(--sg-border); - border-radius: var(--sg-radius-sm); - transition: - border-color 0.15s, - box-shadow 0.15s; -} - -::ng-deep .publication-filters .mat-focused .mat-mdc-text-field-wrapper { - border-color: var(--sg-primary); - box-shadow: 0 0 0 2px var(--sg-primary-soft); -} - -::ng-deep .publication-filters .mat-mdc-form-field-flex { - height: 100%; - align-items: center; -} - -::ng-deep .publication-filters .mat-mdc-form-field-infix { - min-height: 0; - padding-top: 0; - padding-bottom: 0; -} - -::ng-deep .publication-filters .mdc-notched-outline__leading, -::ng-deep .publication-filters .mdc-notched-outline__notch, -::ng-deep .publication-filters .mdc-notched-outline__trailing { - border: none; -} - -.filter-prefix-icon { - width: 18px; - height: 18px; - font-size: 18px; - color: var(--sg-text-soft); -} - -::ng-deep .publication-filters .mat-mdc-form-field-icon-prefix { - padding: 0 4px 0 10px; - color: var(--sg-text-soft); -} - -::ng-deep .publication-filters .mat-mdc-select-value, -::ng-deep .publication-filters input.mat-mdc-input-element { - color: var(--sg-text); - font-size: 14px; -} - -::ng-deep .publication-filters .mat-mdc-select-placeholder, -::ng-deep .publication-filters input.mat-mdc-input-element::placeholder { - color: var(--sg-text-muted); - opacity: 1; - font-size: 14px; -} - -::ng-deep .publication-filters .mat-mdc-form-field-icon-suffix, -::ng-deep .publication-filters .mat-mdc-select-arrow-wrapper { - transform: none; -} - -.active-filters-row { - display: flex; - align-items: center; - flex-wrap: wrap; - gap: 10px; - padding: 8px 16px; - border: 1px solid var(--sg-border); - border-radius: var(--sg-radius-sm); - background: var(--sg-surface); - font-size: 13px; -} - -.active-filters-label { - font-weight: 600; - color: var(--sg-text-muted); -} - -.chips-container { - display: flex; - align-items: center; - flex-wrap: wrap; - gap: 6px; -} - -.filter-meta-chip { - display: inline-flex; - align-items: center; - padding: 2px 8px; - border: 1px solid var(--sg-border-strong); - border-radius: 4px; - background: var(--sg-surface-soft); - color: var(--sg-text); - font-size: 11px; - font-weight: 600; -} - -.filter-topic-chip { - display: inline-flex; - align-items: center; - gap: 4px; - max-width: min(320px, 46vw); - padding: 3px 8px; - border-radius: 7px; - background: color-mix(in srgb, var(--topic-color) 22%, #ffffff); - color: color-mix(in srgb, var(--topic-color) 45%, #07163d); - font-size: 11px; - font-weight: 700; - box-shadow: inset 0 0 0 1px - color-mix(in srgb, var(--topic-color) 45%, transparent); -} - -.filter-topic-chip__icon { - flex: 0 0 auto; - width: 14px; - height: 14px; - font-size: 14px; -} - -.active-institution-filter, -.active-meta-filter { - display: inline-flex; - align-items: center; - gap: 4px; - max-width: 100%; -} - -.filter-institution-chip, .publication-institution-tag { display: inline-flex; align-items: center; @@ -198,13 +19,6 @@ font-size: 10px; font-weight: 600; line-height: normal; -} - -.filter-institution-chip { - max-width: 340px; -} - -.publication-institution-tag { max-width: 100%; margin: 0; font-family: inherit; @@ -234,222 +48,59 @@ background: var(--sg-primary); color: #fff; } -} -.filter-institution-chip .institution-icon, -.publication-institution-tag .institution-icon, -.filter-meta-chip__icon { - flex-shrink: 0; - width: 12px; - height: 12px; - margin-right: 4px; - font-size: 12px; -} + .institution-icon { + flex-shrink: 0; + width: 12px; + height: 12px; + margin-right: 4px; + font-size: 12px; + } -.filter-meta-chip__icon { - color: var(--sg-text-soft); -} + .institution-name { + display: -webkit-box; + -webkit-line-clamp: 2; + -webkit-box-orient: vertical; + overflow: hidden; + min-width: 0; + white-space: normal; + overflow-wrap: anywhere; + } -.filter-institution-chip .institution-name, -.publication-institution-tag .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; + } -.filter-institution-chip .flag-img, -.publication-institution-tag .flag-img { - flex-shrink: 0; - margin-left: 6px; - border: 1px solid; -} + .country-code { + flex-shrink: 0; + margin-left: 2px; + font-size: 9px; + } -.filter-institution-chip .country-code, -.publication-institution-tag .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; + } -.filter-institution-chip .institution-open-icon, -.publication-institution-tag .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; + } -.filter-institution-chip:hover .institution-open-icon, -.publication-institution-tag:hover .institution-open-icon { - opacity: 0.7; -} - -.filter-institution-chip .institution-open-icon:hover, -.publication-institution-tag .institution-open-icon:hover { - opacity: 1; -} - -.filter-meta-chip__label, -.filter-topic-chip__label { - overflow: hidden; - text-overflow: ellipsis; - white-space: nowrap; - min-width: 0; -} - -.active-institution-filter button, -.active-meta-filter button { - display: flex; - padding: 0; - border: 0; - background: transparent; - color: var(--sg-text-soft); - cursor: pointer; - - &:hover { - color: var(--sg-text); + .institution-open-icon:hover { + opacity: 1; } } -.active-institution-filter button mat-icon, -.active-meta-filter button mat-icon { - width: 12px; - height: 12px; - font-size: 12px; -} - -.table-wrap { - position: relative; - overflow-x: auto; -} - -table { - width: 100%; - min-width: 1120px; - border-collapse: separate; - border-spacing: 0 10px; - box-shadow: none; - background: transparent; -} - -.title { - display: inline-block; - max-width: 520px; - line-height: 1.35; - color: var(--sg-text); - font-size: 14px; - font-weight: 700; - text-decoration: none; -} - -a.title:hover { - color: var(--sg-text); - text-decoration: underline; -} - -table.is-hidden { - display: none; -} - -.table-status { - display: flex; - flex-direction: column; - align-items: center; - justify-content: center; - gap: 12px; - min-height: 240px; - padding: 32px; - color: var(--sg-text-muted); - font-size: 14px; - text-align: center; -} - -.empty-text { - color: rgba(0, 0, 0, 0.54); -} - -.cell-filter-pill { - display: inline-flex; - align-items: center; - margin: 0; - padding: 3px 10px; - border: 1px solid var(--sg-border); - border-radius: 999px; - background: #fff; - color: var(--sg-text); - font-family: inherit; - font-size: 12px; - line-height: 1.2; - cursor: pointer; - transition: all 0.2s ease; - - &:hover, - &:focus-visible { - border-color: var(--sg-primary); - background: var(--sg-surface-soft); - outline: none; - } - - &.active { - border-color: var(--sg-primary); - color: var(--sg-primary); - font-weight: 600; - box-shadow: - 0 0 0 1px #ffffff, - 0 0 0 3px var(--sg-primary); - } -} - -.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); - } -} - -.topic-chips, -.institution-tags { - display: flex; - flex-wrap: wrap; - gap: 6px; -} - -.topic-chips { - max-width: 320px; -} - -.institution-tags { - align-items: flex-start; - max-width: 280px; -} - -.publication-institution-more, -.publication-topic-more { +.publication-institution-more { display: inline-flex; align-items: center; min-height: 24px; @@ -473,122 +124,97 @@ table.is-hidden { } } -.publication-topic-more { - max-width: 180px; -} +// ------------------------ +// Containers for chips +// ------------------------ -::ng-deep .mat-mdc-header-cell { - color: var(--sg-text-muted); - font-size: 12px; - font-weight: 700; -} - -::ng-deep .mat-mdc-row { - height: 86px; -} - -::ng-deep .mat-mdc-cell { - color: var(--sg-text); - border-bottom-color: var(--sg-border); - font-size: 13px; -} - -.table-wrap ::ng-deep { - .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; - } -} - -mat-paginator { - background: transparent; -} - -.table-footer { +.topic-chips, +.institution-tags, +.author-tags { display: flex; - align-items: center; - justify-content: space-between; - min-height: 66px; - padding: 0 22px 0 28px; - border: 0; - color: var(--sg-text-muted); - font-size: 13px; + flex-wrap: wrap; + gap: 6px; } +.topic-chips { + max-width: 320px; +} + +.institution-tags { + align-items: flex-start; + max-width: 280px; +} + +.author-tags { + align-items: flex-start; + max-width: 280px; + padding: 0.5rem 0; +} + +// ------------------------ +// Empty text +// ------------------------ + +.empty-text { + color: rgba(0, 0, 0, 0.54); +} + +// ------------------------ +// Classification container +// ------------------------ + +.classification-container { + max-width: 200px; +} + +// ------------------------ +// Data table overrides (applied via ::ng-deep) +// ------------------------ + +::ng-deep { + .mat-mdc-header-cell { + color: var(--sg-text-muted); + font-size: 12px; + font-weight: 700; + } + + .mat-mdc-row { + height: 86px; + } + + .mat-mdc-cell { + color: var(--sg-text); + border-bottom-color: var(--sg-border); + font-size: 13px; + } + + .table-wrap { + .mat-column-type, + .mat-column-year, + .mat-column-language, + .mat-column-citations, + .mat-mdc-header-cell { + text-align: center; + } + + .mat-mdc-cell:not(:last-child), + .mat-mdc-header-cell:not(:last-child) { + border-right: 1px solid var(--sg-border); + } + + .mat-column-institutions, + .mat-column-topics { + overflow: visible; + } + } +} + +// ------------------------ +// Responsive adjustments +// ------------------------ + @media (max-width: 600px) { .page { padding: 16px; } - - .table-footer { - align-items: stretch; - flex-direction: column; - } - - .publication-filter-stack { - align-items: stretch; - } - - .publication-filters { - justify-content: stretch; - max-width: none; - } - - .publication-filters mat-form-field, - .publication-filters button { - width: 100%; - } - - .publication-filters .institution-filter, - .publication-filters .topic-filter { - width: 100%; - } - - .active-filters-row { - align-self: stretch; - } -} - -mat-expansion-panel { - border: 1px solid var(--sg-border); - border-radius: var(--sg-radius-sm); - background: var(--sg-none); - box-shadow: none; -} - -mat-expansion-panel-header { - padding: 0 16px; - min-height: 48px; -} - -mat-panel-title { - font-size: 16px; - font-weight: 700; -} - -mat-panel-description { - font-size: 14px; - color: var(--sg-text-muted); -} -// ------------------------ - -.author-tags { - display: flex; - flex-wrap: wrap; - gap: 0.5rem; - align-items: flex-start; - max-width: 280px; } 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 050730c8..dc166678 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 @@ -7,7 +7,8 @@ import { viewChild, inject, } from '@angular/core'; -import { DfgProjectPage, DfgProjectSummary } from '../../../api'; +import { DfgProjectPage, DfgProjectSummary, Topic } from '../../../api'; +import { TopicChipComponent } from '../topic-chip/topic-chip.component'; import { DataTableComponent, GenericColumn, @@ -21,6 +22,7 @@ import { toSignal } from '@angular/core/rxjs-interop'; import { ActivatedRoute, Router } from '@angular/router'; import { DfgPersonSummary } from '../../../api/model/dfgPersonSummary'; import { MatTooltip } from '@angular/material/tooltip'; +import { topicHierarchyColor } from '../../../resolvers/utils/topic-colors'; @Component({ selector: 'app-dfg-project-table', imports: [ @@ -30,6 +32,7 @@ import { MatTooltip } from '@angular/material/tooltip'; MatButtonModule, QueryParamPaginatorComponent, MatTooltip, + TopicChipComponent, ], templateUrl: './dfg-project-table.component.html', styleUrl: './dfg-project-table.component.scss', @@ -48,14 +51,15 @@ export class DfgProjectTableComponent implements OnInit { queryParamMap = toSignal(this.activatedRoute.queryParamMap, { initialValue: this.activatedRoute.snapshot.queryParamMap, }); + queryParamKeys = projectQueryParamKeys; total = computed(() => this.page().total ?? 0); columns: GenericColumn[] = []; titleTmp = viewChild.required>('titleTmp'); - yearTmp = viewChild.required>('yearTmp'); authorsTmp = viewChild.required>('authorsTmp'); institutionsTmp = viewChild.required>('institutionsTmp'); + fundingStartTmp = viewChild.required>('fundingStartTmp'); fundingEndTmp = viewChild.required>('fundingEndTmp'); actionsTmp = viewChild.required>('actionsTmp'); detailRowTmp = viewChild.required>('detailRowTmp'); @@ -63,9 +67,18 @@ export class DfgProjectTableComponent implements OnInit { expandedProjectAuthorsId: string[] = []; expandedProjectInstitutionsId: string[] = []; + expandedProjectTopicsId: string[] = []; - selectedYearsQueryParams = computed(() => { - return this.queryParamMap().getAll(this.queryParamKeys.years).map(Number); + selectedFundingStartYearsQueryParams = computed(() => { + return this.queryParamMap() + .getAll(this.queryParamKeys.funding_start) + .map(Number); + }); + + selectedFundingEndYearsQueryParams = computed(() => { + return this.queryParamMap() + .getAll(this.queryParamKeys.funding_end) + .map(Number); }); selectedAuthorIdsQueryParams = computed(() => { @@ -115,6 +128,14 @@ export class DfgProjectTableComponent implements OnInit { header: 'Fachliche Zuordnung', type: 'accessor', accessorKey: 'professional_classification', + cellTemplate: this.detailRowTmp(), + }, + + { + id: 'topics', + header: 'Themen', + type: 'display', + cellTemplate: this.topicsTmp(), }, { id: 'actions', @@ -282,4 +303,63 @@ export class DfgProjectTableComponent implements OnInit { return `Institution: ${name}`; } + + getWorkTopicColor(topic: Topic): string { + return topicHierarchyColor({ + id: topic.id, + name: topic.display_name, + field_id: topic.field?.id, + field_name: topic.field?.display_name, + domain_id: topic.domain?.id, + domain_name: topic.domain?.display_name, + }); + } + + isTopicActive(topic: Topic): boolean { + return ( + !!topic.id && + this.authorFilterEnabled() && + this.selectedTopicIdsQueryParams().includes(topic.id) + ); + } + + filterByTopic(topic: Topic): void { + if (!topic.id || !this.topicFilterEnabled()) return; + const selectedTopicIds = this.selectedTopicIdsQueryParams(); + if (selectedTopicIds.includes(topic.id)) { + this.router.navigate([], { + queryParams: { + [this.queryParamKeys.topicId]: selectedTopicIds.filter( + (id) => id !== topic.id, + ), + [this.queryParamKeys.page]: 0, + }, + queryParamsHandling: 'merge', + }); + } else { + this.router.navigate([], { + queryParams: { + [this.queryParamKeys.topicId]: [...selectedTopicIds, topic.id], + [this.queryParamKeys.page]: 0, + }, + queryParamsHandling: 'merge', + }); + } + } + toggleProjectTopicsExpansion(project: DfgProjectSummary): void { + if (!project.id) return; + + if (this.expandedProjectTopicsId.includes(project.id)) { + this.expandedProjectTopicsId = this.expandedProjectTopicsId.filter( + (id) => id !== project.id, + ); + } else { + this.expandedProjectTopicsId.push(project.id); + } + } + isProjectTopicsExpanded(project: DfgProjectSummary): boolean { + if (!project.id) return false; + + return this.expandedProjectTopicsId.includes(project.id); + } } 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 bc7d53da..c04b5464 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 @@ -7,6 +7,18 @@ [debounceTime]="300" /> }
+ @if (showFundingStartFilter()) { + + } + @if (showFundingEndFilter()) { + + } @if (showInstitutionFilter()) { } - @if (showYearFilter()) { - - } @if (showAuthorFilter()) { } + @if (showTopicFilter()) { + + }