From 897edab3cfdf6308da6a565ae44732ab27104665 Mon Sep 17 00:00:00 2001 From: taguesokoudjou Date: Mon, 3 Aug 2026 17:01:19 +0200 Subject: [PATCH 001/114] refactor(patents): unify keyword patent UI and remove text-search --- .../src/main/inse/patents/keywords/logic.py | 462 +----------------- .../inse/patents/keywords/search_queries.py | 129 ----- .../main/inse/patents/keywords/test_logic.py | 351 +++---------- .../keywords-patents.component.html | 169 ++++--- .../keywords-patents.component.scss | 365 +++++++++----- .../keywords-patents.component.ts | 143 ++++-- .../keywords-search/patent-search.utils.ts | 78 --- .../patents-results.component.html | 20 - .../patents-results.component.scss | 33 +- .../patents-results.component.ts | 99 +--- .../person-funding.component.html | 31 +- .../person-funding.component.scss | 1 - .../person-funding.component.ts | 5 - 13 files changed, 524 insertions(+), 1362 deletions(-) diff --git a/service/src/main/inse/patents/keywords/logic.py b/service/src/main/inse/patents/keywords/logic.py index 1e030675..c7165ec7 100644 --- a/service/src/main/inse/patents/keywords/logic.py +++ b/service/src/main/inse/patents/keywords/logic.py @@ -1,4 +1,4 @@ -"""Find patents for extracted OpenAlex keywords via patents_openalex_keywords index.""" +"""Find patents for extracted OpenAlex keywords via IPC/CPC reverse lookup.""" from __future__ import annotations import asyncio @@ -31,7 +31,6 @@ from inse.patents.ipc_lookup import ( ) from inse.patents.ipc_search_client import IpcSearchClient from inse.patents.keywords.model import ( - KeywordEvidence, KeywordPatentMappingStatus, KeywordPatentMatch, KeywordPatentSearchDiagnostics, @@ -69,13 +68,7 @@ _MIN_LEADER_RELATIVE_MASS = 0.20 _MIN_LEADER_MASS_RATIO = 1.5 _TARGET_CUMULATIVE_CLUSTER_MASS = 0.75 _MIN_PATENT_MATCH_SCORE = 0.50 -_MIN_TEXT_PATENT_MATCH_SCORE = 0.30 _DEFAULT_SCORE_WEIGHTS = {"ipc": 0.60, "topic": 0.25, "text": 0.15} -# When IPC mapping is abstained, score only topic + text evidence. -_TEXT_SCORE_WEIGHTS = {"ipc": 0.0, "topic": 0.45, "text": 0.55} -# Also try title/abstract search when IPC mapping produced terms but scoring -# returned no patents (empty retrieval or over-filtering). -_TEXT_SEARCH_AFTER_EMPTY_IPC = True _TOPIC_SCORE_TOPIC_ID = 1.0 _TOPIC_SCORE_SUBFIELD = 0.7 _TOPIC_SCORE_COMPATIBLE_FIELD = 0.3 @@ -611,12 +604,6 @@ class TopicEvidence: score: float -@dataclass(frozen=True) -class TextGateDecision: - accepted: bool - reason: str - - def _compute_topic_evidence( patent_topics: list[MappedOpenAlexTopic], keyword_topic_ids: frozenset[str], @@ -695,16 +682,6 @@ def _tokenize_words(text: str) -> list[str]: return re.findall(r"[a-z0-9äöüß]+", (text or "").casefold()) -def _contains_token_sequence(haystack: list[str], needle: list[str]) -> bool: - if not needle or len(needle) > len(haystack): - return False - width = len(needle) - for index in range(len(haystack) - width + 1): - if haystack[index : index + width] == needle: - return True - return False - - def _token_set(tokens: list[str]) -> set[str]: return set(tokens) @@ -728,23 +705,6 @@ def _text_search_terms(items: list[KeywordPatentSearchItem]) -> list[str]: return terms -def _text_search_phrases(items: list[KeywordPatentSearchItem]) -> list[str]: - """Full phrases for ES title/abstract retrieval (text path).""" - phrases: list[str] = [] - seen: set[str] = set() - for item in items: - for value in (item.keyword, item.topic_display_name): - cleaned = " ".join((value or "").strip().split()) - if len(cleaned) < 3: - continue - key = cleaned.casefold() - if key in seen: - continue - seen.add(key) - phrases.append(cleaned) - return phrases - - def _text_overlap_score( patent: model.PatentEntry, search_terms: list[str], @@ -765,173 +725,6 @@ def _text_overlap_score( return min(hits / 3, 1.0) -def _text_match_kind( - *, - phrase_in_title: bool, - phrase_in_abstract: bool, - full_token_match: bool, - partial_token_match: bool, -) -> str: - if phrase_in_title: - return "phrase_title" - if phrase_in_abstract: - return "phrase_abstract" - if full_token_match: - return "full_token" - if partial_token_match: - return "partial_token" - return "none" - - -def _collect_keyword_text_evidence( - patent: model.PatentEntry, - phrases: list[str], - search_terms: list[str], -) -> KeywordEvidence: - """Record phrase / full-token / partial-token evidence separately.""" - title_tokens = _tokenize_words(patent.title or "") - abstract_tokens = _tokenize_words(patent.abstract or "") - combined_tokens = _token_set(title_tokens + abstract_tokens) - - phrase_in_title = False - phrase_in_abstract = False - full_token_match = False - partial_token_match = False - matched_phrases: list[str] = [] - - for phrase in phrases: - phrase_tokens = _tokenize_words(phrase) - if not phrase_tokens: - continue - if _contains_token_sequence(title_tokens, phrase_tokens): - phrase_in_title = True - matched_phrases.append(phrase) - elif _contains_token_sequence(abstract_tokens, phrase_tokens): - phrase_in_abstract = True - matched_phrases.append(phrase) - - present = [token for token in phrase_tokens if token in combined_tokens] - if present and len(present) == len(phrase_tokens): - full_token_match = True - elif present: - partial_token_match = True - - matched_words = [term for term in search_terms if term in combined_tokens] - if matched_words and not full_token_match and not partial_token_match: - # Lone search-term hits without a covering phrase count as partial. - partial_token_match = True - - word_match_score = ( - min(len(matched_words) / 3, 1.0) if search_terms and matched_words else 0.0 - ) - kind = _text_match_kind( - phrase_in_title=phrase_in_title, - phrase_in_abstract=phrase_in_abstract, - full_token_match=full_token_match, - partial_token_match=partial_token_match, - ) - - return KeywordEvidence( - phrase_in_title=phrase_in_title, - phrase_in_abstract=phrase_in_abstract, - full_token_match=full_token_match, - partial_token_match=partial_token_match, - word_match_score=round(word_match_score, 4), - matched_phrases=list(dict.fromkeys(matched_phrases)), - matched_words=matched_words, - text_match_kind=kind, - ) - - -def _keyword_text_score(evidence: KeywordEvidence) -> float: - if evidence.phrase_in_title: - return 1.0 - if evidence.phrase_in_abstract: - return 0.85 - if evidence.full_token_match: - return 0.55 - if evidence.partial_token_match: - return 0.25 - return 0.0 - - -def _exact_topic_or_subfield_match( - patent_topics: list[MappedOpenAlexTopic], - keyword_topic_ids: frozenset[str], - keyword_subfield_names: frozenset[str], -) -> bool: - evidence = _compute_topic_evidence( - patent_topics, - keyword_topic_ids, - keyword_subfield_names, - frozenset(), - ) - return evidence.match_kind in {"topic_id", "subfield"} - - -def _keyword_text_passes_relevance_gate( - evidence: KeywordEvidence, - *, - topic_evidence: TopicEvidence, -) -> TextGateDecision: - """Keyword text acceptance policy (no domain hardcoding). - - Accept: - - phrase in title (strong) - - phrase in abstract (medium) - - exact topic/subfield together with full token text evidence - Reject: - - partial/general words alone - - compatible field alone - - exact topic/subfield without text evidence - """ - exact = topic_evidence.match_kind in {"topic_id", "subfield"} - - if evidence.phrase_in_title: - return TextGateDecision(True, "phrase_in_title") - if evidence.phrase_in_abstract: - return TextGateDecision(True, "phrase_in_abstract") - if exact and evidence.full_token_match: - return TextGateDecision( - True, - f"{topic_evidence.match_kind}_with_full_token_match", - ) - if exact and evidence.partial_token_match: - return TextGateDecision(False, "exact_topic_with_partial_tokens_only") - if exact: - return TextGateDecision(False, "exact_topic_without_text") - if topic_evidence.match_kind == "compatible_field": - return TextGateDecision(False, "compatible_field_only") - if evidence.partial_token_match or evidence.matched_words: - return TextGateDecision(False, "partial_or_loose_words_only") - return TextGateDecision(False, "insufficient_evidence") - - -def _matched_keyword_labels_from_evidence( - items: list[KeywordPatentSearchItem], - evidence: KeywordEvidence, -) -> list[str]: - matched: list[str] = [] - seen: set[str] = set() - phrase_keys = {phrase.casefold() for phrase in evidence.matched_phrases} - word_keys = set(evidence.matched_words) - - for item in items: - for value in (item.keyword, item.topic_display_name): - label = (value or "").strip() - if not label: - continue - key = label.casefold() - if key in seen: - continue - label_tokens = _tokenize_words(label) - if key in phrase_keys or any(token in word_keys for token in label_tokens): - seen.add(key) - matched.append(label) - break - return matched - - def _patent_passes_relevance_gate( patent_topics: list[MappedOpenAlexTopic], *, @@ -1254,210 +1047,6 @@ async def _score_patents_with_ipc( } -async def _score_patents_text_search( - *, - raw_patents: list[model.PatentEntry], - search_keywords: list[KeywordPatentSearchItem], - phrases: list[str], - text_search_terms: list[str], - keyword_topic_ids: frozenset[str], - keyword_subfield_names: frozenset[str], - keyword_soft_field_names: frozenset[str], - resolver: PatentOpenAlexMappingResolver, -) -> tuple[list[KeywordPatentMatch], dict[str, int]]: - """Score patents without IPC using graded topic + structured text evidence.""" - patent_topics_by_key = await resolver.resolve_topics_for_patents(raw_patents) - scored: list[KeywordPatentMatch] = [] - filtered_by_relevance_gate = 0 - filtered_by_min_score = 0 - passed_relevance_gate = 0 - - for patent in raw_patents: - patent_topics = patent_topics_by_key.get(patent_map_key(patent), []) - evidence = _collect_keyword_text_evidence(patent, phrases, text_search_terms) - topic_evidence = _compute_topic_evidence( - patent_topics, - keyword_topic_ids, - keyword_subfield_names, - keyword_soft_field_names, - ) - decision = _keyword_text_passes_relevance_gate( - evidence, - topic_evidence=topic_evidence, - ) - if not decision.accepted: - filtered_by_relevance_gate += 1 - logger.info( - "Text reject: id=%s title=%s topic_kind=%s topic_score=%.2f " - "text_kind=%s phrase_title=%s phrase_abstract=%s " - "full_token=%s partial_token=%s reason=%s", - patent.patent_id, - patent.title, - topic_evidence.match_kind, - topic_evidence.score, - evidence.text_match_kind, - evidence.phrase_in_title, - evidence.phrase_in_abstract, - evidence.full_token_match, - evidence.partial_token_match, - decision.reason, - ) - continue - - passed_relevance_gate += 1 - text_score = _keyword_text_score(evidence) - # Field-only remains a weak ranking signal when already accepted via phrase. - score = _compute_final_score( - 0.0, - topic_evidence.score, - text_score, - weights=_TEXT_SCORE_WEIGHTS, - ) - if score < _MIN_TEXT_PATENT_MATCH_SCORE: - filtered_by_min_score += 1 - logger.info( - "Text reject: id=%s reason=below_min_score score=%.4f", - patent.patent_id, - score, - ) - continue - - logger.info( - "Text accept: id=%s title=%s topic_kind=%s topic_score=%.2f " - "text_kind=%s text_score=%.2f final_score=%.4f reason=%s", - patent.patent_id, - patent.title, - topic_evidence.match_kind, - topic_evidence.score, - evidence.text_match_kind, - text_score, - score, - decision.reason, - ) - scored.append( - KeywordPatentMatch( - patent=patent, - match_score=score, - ipc_score=0.0, - topic_score=topic_evidence.score, - text_score=text_score, - matched_keywords=_matched_keyword_labels_from_evidence( - search_keywords, - evidence, - ), - matched_ipc_symbols=[], - text_retrieval=True, - keyword_evidence=evidence, - topic_match_kind=topic_evidence.match_kind, - ) - ) - - logger.info( - "Keyword patent text search: filtered_by_relevance_gate=%d " - "filtered_by_min_score=%d passed_relevance_gate=%d scored=%d", - filtered_by_relevance_gate, - filtered_by_min_score, - passed_relevance_gate, - len(scored), - ) - return scored, { - "filtered_by_relevance_gate": filtered_by_relevance_gate, - "filtered_by_min_score": filtered_by_min_score, - "passed_relevance_gate": passed_relevance_gate, - } - - -async def _search_patents_text_search( - *, - client: BasePatentSearchClient, - queries: IpcPatentSearchQueries, - ipc_search: IpcSearchClient, - resolver: PatentOpenAlexMappingResolver, - search_keywords: list[KeywordPatentSearchItem], - keyword_topic_ids: frozenset[str], - keyword_subfield_names: frozenset[str], - keyword_soft_field_names: frozenset[str], - mapping_status: KeywordPatentMappingStatus, - ipc_cluster_selections: list[dict] | None = None, -) -> PatentsByKeywordsResponse: - cluster_dicts = list(ipc_cluster_selections or []) - phrases = _text_search_phrases(search_keywords) - text_search_terms = _text_search_terms(search_keywords) - if not phrases: - logger.info( - "Keyword patent text search: no phrases for keywords %s", - [item.keyword for item in search_keywords], - ) - return PatentsByKeywordsResponse( - patent_count=0, - patents=[], - mapping_status="no_patents_found", - diagnostics=_empty_diagnostics( - search_path="text", - ipc_cluster_selections=cluster_dicts, - ), - ) - - logger.info( - "Keyword patent text search: mapping_status=%s phrases=%s", - mapping_status, - phrases, - ) - raw_patents = await _fetch_patents_for_queries( - client, - queries.epo_query_by_text_phrases(phrases, size=_MAX_PATENTS), - queries.uspto_query_by_text_phrases(phrases, size=_MAX_PATENTS), - ) - if raw_patents is None: - return PatentsByKeywordsResponse( - patent_count=0, - patents=[], - mapping_status="search_error", - diagnostics=_empty_diagnostics( - search_path="text", - ipc_cluster_selections=cluster_dicts, - ), - ) - - logger.info("Keyword patent text search: raw_patents=%d", len(raw_patents)) - scored, filter_counts = await _score_patents_text_search( - raw_patents=raw_patents, - search_keywords=search_keywords, - phrases=phrases, - text_search_terms=text_search_terms, - keyword_topic_ids=keyword_topic_ids, - keyword_subfield_names=keyword_subfield_names, - keyword_soft_field_names=keyword_soft_field_names, - resolver=resolver, - ) - scored, diagnostics = _finalize_scored_patents( - scored, - raw_count=len(raw_patents), - filtered_by_ipc=0, - filtered_by_relevance_gate=filter_counts["filtered_by_relevance_gate"], - filtered_by_min_score=filter_counts["filtered_by_min_score"], - passed_relevance_gate=filter_counts["passed_relevance_gate"], - search_path="text", - ipc_cluster_selections=cluster_dicts, - ) - await enrich_patents_classifications([item.patent for item in scored], ipc_search) - - if not scored: - return PatentsByKeywordsResponse( - patent_count=0, - patents=[], - mapping_status="no_patents_found", - diagnostics=diagnostics, - ) - - return PatentsByKeywordsResponse( - patent_count=len(scored), - patents=scored, - mapping_status=mapping_status, - diagnostics=diagnostics, - ) - - async def get_patents_by_keywords( request: PatentsByKeywordsRequest, *, @@ -1521,21 +1110,18 @@ async def get_patents_by_keywords( ) logger.info( "Keyword patent search: no IPC search terms for keywords %s " - "(mapping_status=%s) — trying keyword text search", + "(mapping_status=%s)", [item.keyword for item in search_keywords], mapping_status, ) - return await _search_patents_text_search( - client=client, - queries=queries, - ipc_search=ipc_search, - resolver=resolver, - search_keywords=search_keywords, - keyword_topic_ids=keyword_topic_ids, - keyword_subfield_names=keyword_subfield_names, - keyword_soft_field_names=keyword_soft_field_names, + return PatentsByKeywordsResponse( + patent_count=0, + patents=[], mapping_status=mapping_status, - ipc_cluster_selections=cluster_dicts, + diagnostics=_empty_diagnostics( + search_path="none", + ipc_cluster_selections=cluster_dicts, + ), ) text_search_terms = _text_search_terms(search_keywords) @@ -1587,31 +1173,11 @@ async def get_patents_by_keywords( diagnostics=diagnostics, ) - if not _TEXT_SEARCH_AFTER_EMPTY_IPC: - return PatentsByKeywordsResponse( - patent_count=0, - patents=[], - mapping_status="no_patents_found", - diagnostics=diagnostics, - ) - - logger.info( - "Keyword patent search: IPC path yielded no scored patents — " - "trying keyword text search (policy=_TEXT_SEARCH_AFTER_EMPTY_IPC)" - ) - return await _search_patents_text_search( - client=client, - queries=queries, - ipc_search=ipc_search, - resolver=resolver, - search_keywords=search_keywords, - keyword_topic_ids=keyword_topic_ids, - keyword_subfield_names=keyword_subfield_names, - keyword_soft_field_names=keyword_soft_field_names, - # IPC was selected but produced no usable hits; UI treats this like - # uncertain IPC evidence and labels patents via text_retrieval. - mapping_status="uncertain", - ipc_cluster_selections=cluster_dicts, + return PatentsByKeywordsResponse( + patent_count=0, + patents=[], + mapping_status="no_patents_found", + diagnostics=diagnostics, ) diff --git a/service/src/main/inse/patents/keywords/search_queries.py b/service/src/main/inse/patents/keywords/search_queries.py index 02139697..8bf954be 100644 --- a/service/src/main/inse/patents/keywords/search_queries.py +++ b/service/src/main/inse/patents/keywords/search_queries.py @@ -43,19 +43,12 @@ _USPTO_SOURCE_FIELDS = [ ] _MIN_MATCH_TERM_LEN = 4 -_MIN_TEXT_PHRASE_LEN = 3 # Prefer concrete group/subgroup hits over broad subclass prefixes. _BOOST_SUBGROUP = 4.0 _BOOST_MAIN_GROUP = 2.5 _BOOST_SUBCLASS = 1.0 -# Text search: prefer exact phrases in title over abstract / loose match. -_BOOST_TEXT_PHRASE_TITLE = 5.0 -_BOOST_TEXT_PHRASE_ABSTRACT = 3.0 -_BOOST_TEXT_MATCH_TITLE = 1.5 -_BOOST_TEXT_MATCH_ABSTRACT = 1.0 - def _add_term_boost(weights: dict[str, float], term: str, boost: float) -> None: cleaned = term.strip() @@ -154,76 +147,6 @@ def _ipc_match_clauses(field: str, term_boosts: dict[str, float]) -> list[dict[s return clauses -def _normalize_text_phrases(phrases: list[str]) -> list[str]: - cleaned: list[str] = [] - seen: set[str] = set() - for phrase in phrases: - value = " ".join((phrase or "").strip().split()) - if len(value) < _MIN_TEXT_PHRASE_LEN: - continue - key = value.casefold() - if key in seen: - continue - seen.add(key) - cleaned.append(value) - return cleaned - - -def _text_match_clauses( - phrases: list[str], - *, - title_fields: tuple[str, ...], - abstract_field: str, -) -> list[dict[str, Any]]: - """Build title/abstract should-clauses with phrase boosts over loose match.""" - clauses: list[dict[str, Any]] = [] - for phrase in _normalize_text_phrases(phrases): - for field in title_fields: - clauses.append( - { - "match_phrase": { - field: { - "query": phrase, - "boost": _BOOST_TEXT_PHRASE_TITLE, - } - } - } - ) - clauses.append( - { - "match": { - field: { - "query": phrase, - "operator": "and", - "boost": _BOOST_TEXT_MATCH_TITLE, - } - } - } - ) - clauses.append( - { - "match_phrase": { - abstract_field: { - "query": phrase, - "boost": _BOOST_TEXT_PHRASE_ABSTRACT, - } - } - } - ) - clauses.append( - { - "match": { - abstract_field: { - "query": phrase, - "operator": "and", - "boost": _BOOST_TEXT_MATCH_ABSTRACT, - } - } - } - ) - return clauses - - class IpcPatentSearchQueries: def epo_query_by_ipc_terms( self, @@ -296,55 +219,3 @@ class IpcPatentSearchQueries: size: int = DEFAULT_SEARCH_SIZE, ) -> dict[str, Any]: return self.uspto_query_by_ipc_terms(_merge_term_boosts(symbols), size=size) - - def epo_query_by_text_phrases( - self, - phrases: list[str], - size: int = DEFAULT_SEARCH_SIZE, - ) -> dict[str, Any]: - should = _text_match_clauses( - phrases, - title_fields=("title_en", "title_de"), - abstract_field="abstract", - ) - query: dict[str, Any] = ( - {"match_none": {}} - if not should - else {"bool": {"should": should, "minimum_should_match": 1}} - ) - return { - "size": size, - "track_total_hits": True, - "sort": [ - {"_score": {"order": "desc"}}, - {"date_publication": {"order": "desc", "missing": "_last"}}, - ], - "_source": _PATENT_SOURCE_FIELDS, - "query": query, - } - - def uspto_query_by_text_phrases( - self, - phrases: list[str], - size: int = DEFAULT_SEARCH_SIZE, - ) -> dict[str, Any]: - should = _text_match_clauses( - phrases, - title_fields=("title",), - abstract_field="abstract", - ) - query: dict[str, Any] = ( - {"match_none": {}} - if not should - else {"bool": {"should": should, "minimum_should_match": 1}} - ) - return { - "size": size, - "track_total_hits": True, - "sort": [ - {"_score": {"order": "desc"}}, - {"publication_date": {"order": "desc", "missing": "_last"}}, - ], - "_source": _USPTO_SOURCE_FIELDS, - "query": query, - } diff --git a/service/src/main/inse/patents/keywords/test_logic.py b/service/src/main/inse/patents/keywords/test_logic.py index b6f14912..5bcb3ffd 100644 --- a/service/src/main/inse/patents/keywords/test_logic.py +++ b/service/src/main/inse/patents/keywords/test_logic.py @@ -12,10 +12,6 @@ from inse.patents.keywords.logic import ( TopicEvidence, _compute_final_score, _compute_topic_evidence, - _collect_keyword_text_evidence, - _exact_topic_or_subfield_match, - _keyword_text_passes_relevance_gate, - _keyword_text_score, _filter_keywords_for_patent_search, _ipc_hierarchy_quality, _keyword_is_patent_searchable, @@ -643,132 +639,6 @@ def test_text_overlap_score_uses_word_boundaries_not_substrings() -> None: assert _text_overlap_score(patent, ["chemistry", "organic"]) == 0.0 -def test_fallback_rejects_mechanical_patent_for_organic_chemistry() -> None: - """Soft field / loose words must not accept a mechanical separator patent.""" - patent = model.PatentEntry( - patent_id="EP-MECH", - source="EPO", - title=( - "Rotating machine for separating materials in different " - "states of aggregation" - ), - abstract="Apparatus for mechanical separation of materials.", - ipc=["B01D45/12"], - ) - phrases = ["Organic Chemistry", "organische Chemie"] - terms = ["organic", "chemistry", "organische", "chemie"] - evidence = _collect_keyword_text_evidence(patent, phrases, terms) - - assert evidence.phrase_in_title is False - assert evidence.phrase_in_abstract is False - assert evidence.full_token_match is False - assert evidence.matched_phrases == [] - assert evidence.matched_words == [] - - field_only = TopicEvidence(match_kind="compatible_field", score=0.3) - assert not _keyword_text_passes_relevance_gate( - evidence, - topic_evidence=field_only, - ).accepted - exact = TopicEvidence(match_kind="topic_id", score=1.0) - assert not _keyword_text_passes_relevance_gate( - evidence, - topic_evidence=exact, - ).accepted - - -def test_fallback_accepts_strong_phrase_or_exact_topic_with_full_tokens() -> None: - phrase_patent = model.PatentEntry( - patent_id="EP-PHRASE", - source="EPO", - title="Process for organic chemistry synthesis", - abstract="Catalytic reactions.", - ) - phrases = ["organic chemistry"] - terms = ["organic", "chemistry"] - evidence = _collect_keyword_text_evidence(phrase_patent, phrases, terms) - assert evidence.phrase_in_title is True - assert evidence.text_match_kind == "phrase_title" - assert _keyword_text_score(evidence) == 1.0 - assert _keyword_text_passes_relevance_gate( - evidence, - topic_evidence=TopicEvidence(match_kind="none", score=0.0), - ).accepted - - full_token_patent = model.PatentEntry( - patent_id="EP-WORDS", - source="EPO", - title="Catalytic organic synthesis method", - abstract="Uses chemistry laboratory techniques.", - ) - full_evidence = _collect_keyword_text_evidence( - full_token_patent, - phrases, - terms, - ) - assert full_evidence.phrase_in_title is False - assert full_evidence.phrase_in_abstract is False - assert full_evidence.full_token_match is True - assert not _keyword_text_passes_relevance_gate( - full_evidence, - topic_evidence=TopicEvidence(match_kind="none", score=0.0), - ).accepted - assert _keyword_text_passes_relevance_gate( - full_evidence, - topic_evidence=TopicEvidence(match_kind="topic_id", score=1.0), - ).accepted - - partial_patent = model.PatentEntry( - patent_id="EP-PARTIAL", - source="EPO", - title="Organic polymer blend", - abstract="Industrial materials processing.", - ) - partial_evidence = _collect_keyword_text_evidence( - partial_patent, - phrases, - terms, - ) - assert partial_evidence.partial_token_match is True - assert partial_evidence.full_token_match is False - decision = _keyword_text_passes_relevance_gate( - partial_evidence, - topic_evidence=TopicEvidence(match_kind="topic_id", score=1.0), - ) - assert not decision.accepted - assert decision.reason == "exact_topic_with_partial_tokens_only" - - assert _exact_topic_or_subfield_match( - [ - MappedOpenAlexTopic( - topic_id="https://openalex.org/TORG", - topic_display_name="Organic Chemistry", - subfield_name="Organic Chemistry", - field_name="Chemistry", - ) - ], - frozenset({"TORG"}), - frozenset({"organic chemistry"}), - ) - - -def test_token_match_rejects_machine_inside_micromachined() -> None: - patent = model.PatentEntry( - patent_id="EP-MICRO", - source="EPO", - title="Micromachined sensor device", - abstract="Fabrication of micromachined structures.", - ) - assert _text_overlap_score(patent, ["machine", "learning"]) == 0.0 - evidence = _collect_keyword_text_evidence( - patent, - ["Machine Learning"], - ["machine", "learning"], - ) - assert evidence.matched_words == [] - assert evidence.full_token_match is False - - def test_patent_passes_relevance_gate_with_text_but_no_topics() -> None: patent = model.PatentEntry( patent_id="EP1", @@ -911,8 +781,7 @@ def test_get_patents_by_keywords_uses_symbol_queries() -> None: uspto_symbols.assert_called_once() assert epo_symbols.call_args.args[0][0] == "C07C243/08" assert "C07C" in epo_symbols.call_args.args[0] - # IPC search returns empty → text fallback also queries EPO/USPTO. - assert captured == ["epo", "uspto", "epo", "uspto"] + assert captured == ["epo", "uspto"] def test_text_search_terms_include_topic_metadata() -> None: @@ -990,64 +859,84 @@ def test_epo_and_uspto_queries_boost_specific_symbols_over_subclass() -> None: assert uspto["sort"][0] == {"_score": {"order": "desc"}} -def test_text_queries_prefer_phrase_match_in_title() -> None: - queries = IpcPatentSearchQueries() - epo = queries.epo_query_by_text_phrases(["organic chemistry"]) - uspto = queries.uspto_query_by_text_phrases(["organic chemistry"]) - - epo_should = epo["query"]["bool"]["should"] - uspto_should = uspto["query"]["bool"]["should"] - - def clause_boost(clauses: list[dict], kind: str, field: str) -> float | None: - for clause in clauses: - payload = clause.get(kind, {}).get(field) - if isinstance(payload, dict) and payload.get("query") == "organic chemistry": - return float(payload.get("boost", 1.0)) - return None - - assert clause_boost(epo_should, "match_phrase", "title_en") == 5.0 - assert clause_boost(epo_should, "match_phrase", "abstract") == 3.0 - assert clause_boost(epo_should, "match", "title_en") == 1.5 - assert clause_boost(uspto_should, "match_phrase", "title") == 5.0 - assert epo["sort"][0] == {"_score": {"order": "desc"}} - - -def test_uncertain_mapping_uses_text_fallback_not_empty_list() -> None: - """Fragmented IPC abstention must fall back to title/abstract search.""" - patent = model.PatentEntry( - patent_id="EP123", - source="EPO", - title="Process for organic chemistry synthesis", - abstract="A catalytic method in organic chemistry.", - publication_date="20240101", - ipc=["C07C243/08"], - cpc=[], +def test_technical_search_failure_returns_search_error_not_no_patents_found() -> None: + request = PatentsByKeywordsRequest( + keywords=[ + KeywordPatentSearchItem( + keyword="organische Chemie", + keyword_level="coarse", + topic_id="https://openalex.org/TORG", + topic_display_name="Organic Chemistry", + field_name="Chemistry", + relevance_score=1.0, + ) + ] ) + ipc_matches = [ + IpcCodeMatch( + "subgroup", + "C07C243/08", + 0.90, + "organische Chemie", + "topic", + "TORG", + ) + ] - async def fake_search_epo(query): - assert "match_phrase" in str(query) or "title_en" in str(query) - return { - "hits": { - "hits": [ - { - "_source": { - "doc_number": "123", - "country": "EP", - "kind": "A1", - "date_publication": "20240101", - "title_en": patent.title, - "abstract": patent.abstract, - "ipc": patent.ipc, - "cpc": [], - } - } - ] - } - } + with patch( + "inse.patents.keywords.logic.KeywordIpcReverseLookup.lookup_ipc_codes", + new=AsyncMock(return_value=ipc_matches), + ), patch( + "inse.patents.keywords.logic.BasePatentSearchClient.search_epo", + new=AsyncMock(side_effect=httpx.HTTPError("boom")), + ), patch( + "inse.patents.keywords.logic.BasePatentSearchClient.search_uspto", + new=AsyncMock(return_value={"hits": {"hits": []}}), + ): + response = asyncio.run(get_patents_by_keywords(request)) - async def fake_search_uspto(query): - return {"hits": {"hits": []}} + assert response.mapping_status == "search_error" + assert response.patent_count == 0 + +def test_no_ipc_search_terms_returns_without_text_fallback() -> None: + """Without usable IPC symbols the search abstains — no title/abstract path.""" + request = PatentsByKeywordsRequest( + keywords=[ + KeywordPatentSearchItem( + keyword="organische Chemie", + keyword_level="coarse", + topic_id="https://openalex.org/TORG", + topic_display_name="Organic Chemistry", + field_name="Chemistry", + relevance_score=1.0, + ) + ] + ) + search_epo = AsyncMock(return_value={"hits": {"hits": []}}) + search_uspto = AsyncMock(return_value={"hits": {"hits": []}}) + + with patch( + "inse.patents.keywords.logic.KeywordIpcReverseLookup.lookup_ipc_codes", + new=AsyncMock(return_value=[]), + ), patch( + "inse.patents.keywords.logic.BasePatentSearchClient.search_epo", + new=search_epo, + ), patch( + "inse.patents.keywords.logic.BasePatentSearchClient.search_uspto", + new=search_uspto, + ): + response = asyncio.run(get_patents_by_keywords(request)) + + assert response.mapping_status == "no_mapping" + assert response.patent_count == 0 + assert response.patents == [] + search_epo.assert_not_called() + search_uspto.assert_not_called() + + +def test_uncertain_ipc_cluster_abstention_returns_without_text_fallback() -> None: + """Fragmented IPC mapping abstains without falling back to text retrieval.""" fragmented = [ IpcCodeMatch( "subgroup", @@ -1071,106 +960,24 @@ def test_uncertain_mapping_uses_text_fallback_not_empty_list() -> None: ) ] ) + search_epo = AsyncMock(return_value={"hits": {"hits": []}}) with patch( "inse.patents.keywords.logic.KeywordIpcReverseLookup.lookup_ipc_codes", new=AsyncMock(return_value=fragmented), ), patch( "inse.patents.keywords.logic.BasePatentSearchClient.search_epo", - new=AsyncMock(side_effect=fake_search_epo), - ), patch( - "inse.patents.keywords.logic.BasePatentSearchClient.search_uspto", - new=AsyncMock(side_effect=fake_search_uspto), - ), patch( - "inse.patents.keywords.logic.PatentOpenAlexMappingResolver.resolve_topics_for_patents", - new=AsyncMock(return_value={}), - ), patch( - "inse.patents.keywords.logic.enrich_patents_classifications", - new=AsyncMock(), - ), patch.object( - IpcPatentSearchQueries, - "epo_query_by_text_phrases", - wraps=IpcPatentSearchQueries().epo_query_by_text_phrases, - ) as epo_text: - response = asyncio.run(get_patents_by_keywords(request)) - - epo_text.assert_called_once() - assert response.mapping_status == "uncertain" - assert response.patent_count == 1 - assert response.patents[0].text_retrieval is True - assert response.patents[0].ipc_score == 0.0 - assert response.patents[0].text_score > 0.0 - assert response.patents[0].matched_ipc_symbols == [] - assert response.patents[0].keyword_evidence is not None - assert response.patents[0].keyword_evidence.phrase_in_title is True - assert response.patents[0].keyword_evidence.text_match_kind == "phrase_title" - - -def test_text_fallback_empty_yields_no_patents_found() -> None: - request = PatentsByKeywordsRequest( - keywords=[ - KeywordPatentSearchItem( - keyword="organische Chemie", - keyword_level="coarse", - topic_id="https://openalex.org/TORG", - topic_display_name="Organic Chemistry", - field_name="Chemistry", - relevance_score=1.0, - ) - ] - ) - - with patch( - "inse.patents.keywords.logic.KeywordIpcReverseLookup.lookup_ipc_codes", - new=AsyncMock(return_value=[]), - ), patch( - "inse.patents.keywords.logic.BasePatentSearchClient.search_epo", - new=AsyncMock(return_value={"hits": {"hits": []}}), + new=search_epo, ), patch( "inse.patents.keywords.logic.BasePatentSearchClient.search_uspto", new=AsyncMock(return_value={"hits": {"hits": []}}), - ), patch( - "inse.patents.keywords.logic.PatentOpenAlexMappingResolver.resolve_topics_for_patents", - new=AsyncMock(return_value={}), - ), patch( - "inse.patents.keywords.logic.enrich_patents_classifications", - new=AsyncMock(), ): response = asyncio.run(get_patents_by_keywords(request)) - assert response.mapping_status == "no_patents_found" + assert response.mapping_status == "uncertain" assert response.patent_count == 0 assert response.patents == [] - - -def test_technical_search_failure_returns_search_error_not_no_patents_found() -> None: - request = PatentsByKeywordsRequest( - keywords=[ - KeywordPatentSearchItem( - keyword="organische Chemie", - keyword_level="coarse", - topic_id="https://openalex.org/TORG", - topic_display_name="Organic Chemistry", - field_name="Chemistry", - relevance_score=1.0, - ) - ] - ) - - with patch( - "inse.patents.keywords.logic.KeywordIpcReverseLookup.lookup_ipc_codes", - new=AsyncMock(return_value=[]), - ), patch( - "inse.patents.keywords.logic.BasePatentSearchClient.search_epo", - new=AsyncMock(side_effect=httpx.HTTPError("boom")), - ), patch( - "inse.patents.keywords.logic.BasePatentSearchClient.search_uspto", - new=AsyncMock(return_value={"hits": {"hits": []}}), - ): - response = asyncio.run(get_patents_by_keywords(request)) - - assert response.mapping_status == "search_error" - assert response.patent_count == 0 + search_epo.assert_not_called() def test_json_lookup_returns_empty_without_mapping(monkeypatch) -> None: diff --git a/webapp/src/app/modules/keywords-search/keywords-patents/keywords-patents.component.html b/webapp/src/app/modules/keywords-search/keywords-patents/keywords-patents.component.html index 7f3312ef..3eb93948 100644 --- a/webapp/src/app/modules/keywords-search/keywords-patents/keywords-patents.component.html +++ b/webapp/src/app/modules/keywords-search/keywords-patents/keywords-patents.component.html @@ -1,46 +1,63 @@ @if (loading()) { -
- - -
+ } @else if (error()) { -
- -

Fehler beim Laden der Patente.

-
+

Fehler beim Laden der Patente.

} @else if (matches().length === 0) { -
- -

{{ emptyMessage() }}

-
+

{{ emptyMessage() }}

} @else {
- -
+
+ + + + Filter nach Quelle + Alle + EPO + USPTO + + + + + + Sortieren nach + Datum + Titel + + +
+ - + + - @for (item of pagedMatches(); track trackMatch($index, item)) { + @for (item of getPagedMatches(); track trackMatch($index, item)) { - + }
PatentScore Quelle JahrErfinderAnmelder
{{ item.patent.title ?? item.patent.patent_id }} {{ formatScore(item.match_score) }} + {{ getInventorsLabel(item.patent) }} + + {{ getAssigneesLabel(item.patent) }} +
- @if (hasPagination()) { - - } +
@if (selectedMatch(); as match) {

{{ match.patent.title ?? match.patent.patent_id }}

-
- Match-Score - {{ - formatScore(match.match_score) - }} -
-
- Gematchte Keywords - {{ - formatMatchList(match.matched_keywords) - }} -
-
- Gematchte IPC/CPC - {{ - formatMatchList(match.matched_ipc_symbols) - }} -
Quelle @@ -123,6 +123,10 @@ }
+ @if (getAbstractPreview(match.patent.abstract); as abstractPreview) { +

{{ abstractPreview }}

+ } + +

+ Abstract, Erfinder, Anmelder und IPC/CPC-Klassifikation +

+
+ } @else { +
+

Patentübersicht

+

Patente mit passenden Keywords.

+
+
+ {{ matches().length }} + Patente +
+
+ {{ getEpoCount() }} + EPO +
+
+ {{ getUsptoCount() }} + USPTO +
+
+

+ Wähle links ein Patent aus, um Details zu sehen. +

}
} - - -
-

Passende Patente

-
- @if (matches().length > 0) { - - } - - @if (showReload()) { - - } -
-
-
diff --git a/webapp/src/app/modules/keywords-search/keywords-patents/keywords-patents.component.scss b/webapp/src/app/modules/keywords-search/keywords-patents/keywords-patents.component.scss index 18059791..004cec79 100644 --- a/webapp/src/app/modules/keywords-search/keywords-patents/keywords-patents.component.scss +++ b/webapp/src/app/modules/keywords-search/keywords-patents/keywords-patents.component.scss @@ -1,68 +1,21 @@ .message { - padding: 16px; color: #666; } -.fallback-notice { - margin: 0 0 12px; - padding: 10px 12px; - border-radius: 8px; - background: #f4f7fb; - color: #3d4f63; - font-size: 0.9rem; -} - -.section-title { - margin: 0; - font-size: 1.25rem; -} - .patents-container { - margin-top: 0; - padding: 16px; - border-radius: 12px; - background: #fff; - box-shadow: 0 1px 3px rgba(0, 0, 0, 0.08); -} - -.patents-header { display: flex; - flex-wrap: wrap; - align-items: center; - justify-content: space-between; - gap: 12px; - margin-bottom: 16px; + flex-direction: column; + gap: 16px; } -.patents-header-actions { - display: flex; - flex-wrap: wrap; - align-items: center; - justify-content: flex-end; - gap: 10px; - margin-left: auto; +app-query-param-paginator { + display: block; + margin-top: 14px; } -.reload-btn { - min-height: 40px; - white-space: nowrap; -} - -.sort-control { - display: inline-flex; - align-items: center; - gap: 6px; - padding: 10px 14px; - border-radius: 20px; - background: #f2f2f2; - font-size: 14px; - - select { - border: 0; - background: transparent; - font: inherit; - cursor: pointer; - } +.patents-toolbar-field { + width: fit-content; + min-width: 180px; } .patents-content { @@ -73,126 +26,276 @@ .patents-list { flex: 1; + min-width: 0; + + .patents-list-toolbar { + display: flex; + align-items: center; + justify-content: space-between; + gap: 16px; + margin-bottom: 18px; + flex-wrap: wrap; + } table { width: 100%; - border-collapse: collapse; - } + border-collapse: separate; + border-spacing: 0; + border: 1px solid var(--sg-border); + border-radius: var(--sg-radius-sm); + overflow: hidden; - th { - text-align: left; - padding: 10px 12px; - border-bottom: 2px solid #e0e0e0; - } - - tr { - cursor: pointer; - - &:hover { - background: #f5f5f5; + th { + text-align: left; + padding: 12px 16px; + background: var(--sg-surface-muted); + border-bottom: 1px solid var(--sg-border); + font-size: 12px; + font-weight: 700; + text-transform: uppercase; + letter-spacing: 0.02em; + color: var(--sg-text-muted); } - &.selected { - background: #f0f0f0; + tr { + cursor: pointer; + transition: background-color 0.15s ease; + + &:hover td { + background: rgba(16, 26, 61, 0.04); + } + + &.selected td { + background: var(--sg-primary-soft); + } + + &:last-child td { + border-bottom: 0; + } + } + + td { + padding: 12px 16px; + border-bottom: 1px solid var(--sg-border); + color: var(--sg-text); + font-size: 13px; + transition: background-color 0.15s ease; + } + + .patent-title { + color: var(--sg-text); + font-weight: 600; + max-width: 400px; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; + } + + .patent-people { + max-width: 220px; + color: var(--sg-text-muted); + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; } } - - td { - padding: 10px 12px; - border-bottom: 1px solid #eee; - } -} - -.patent-title { - font-weight: 500; } .source-badge { - display: inline-block; - padding: 2px 8px; + display: inline-flex; + align-items: center; + padding: 3px 10px; border-radius: 999px; - font-size: 12px; - font-weight: 600; + font-size: 0.75rem; + font-weight: 700; &--epo { - background: #dbeafe; - color: #1e40af; + background: #effaf3; + color: #24834f; + border: 1px solid #bdebcf; } &--uspto { - background: #dcfce7; - color: #166534; + background: #f0f6ff; + color: #0b63ce; + border: 1px solid #bdd4ff; } } -.pagination { - display: flex; - align-items: center; - gap: 12px; - margin-top: 12px; -} - .patent-detail { - flex: 0 0 320px; - padding: 16px; - border-radius: 12px; - background: #f8fafc; + width: 440px; + border: 1px solid var(--sg-border); + border-radius: var(--sg-radius-sm); + padding: 24px; + background: var(--sg-surface); + box-shadow: var(--sg-shadow-sm); + + &.overview { + display: flex; + flex-direction: column; + gap: 12px; + + .overview-title { + font-size: 15px; + font-weight: 700; + color: var(--sg-text); + margin: 0; + } + + .overview-subtitle { + font-size: 13px; + color: var(--sg-text-muted); + margin: 0; + } + + .overview-stats { + display: grid; + grid-template-columns: 1fr 1fr 1fr; + gap: 10px; + margin-top: 4px; + } + + .overview-stat { + background: var(--sg-surface); + border: 1px solid var(--sg-border); + border-radius: var(--sg-radius-sm); + padding: 12px 8px; + text-align: center; + + .overview-value { + display: block; + font-size: 22px; + font-weight: 700; + color: var(--sg-text); + } + + .overview-label { + display: block; + font-size: 12px; + color: var(--sg-text-muted); + margin-top: 4px; + } + + &--total { + .overview-value, + .overview-label { + color: #7255d9; + } + } + + &--epo { + .overview-value, + .overview-label { + color: #24834f; + } + } + + &--uspto { + .overview-value, + .overview-label { + color: #0b63ce; + } + } + } + + .overview-hint { + font-size: 12px; + color: var(--sg-text-muted); + margin: 0; + } + } + + h3 { + margin: 0 0 16px 0; + font-size: 16px; + font-weight: 700; + color: var(--sg-text); + line-height: 1.4; + } } .detail-stats { display: grid; + grid-template-columns: 1fr 1fr; gap: 10px; - margin: 12px 0; + + .stat { + background: var(--sg-surface); + border: 1px solid var(--sg-border); + border-radius: var(--sg-radius-sm); + padding: 10px; + text-align: center; + + .stat-label { + display: block; + font-size: 11px; + color: var(--sg-text-muted); + margin-bottom: 4px; + text-transform: uppercase; + letter-spacing: 0.03em; + } + + .stat-value { + display: block; + font-size: 15px; + font-weight: bold; + color: var(--sg-text); + } + } } -.match-score { - font-variant-numeric: tabular-nums; - color: #374151; - white-space: nowrap; -} - -.stat-label { - display: block; - font-size: 12px; - color: #666; -} - -.stat-value { - display: block; - word-break: break-word; +.patent-detail-preview { + margin: 14px 0 0; + font-size: 13px; + line-height: 1.55; + color: var(--sg-text-muted); } .patent-detail-action { display: flex; align-items: center; justify-content: space-between; + gap: 8px; width: 100%; - margin-top: 12px; - padding: 10px 12px; - border: 0; - border-radius: 8px; - background: #111827; - color: #fff; + margin-top: 16px; + padding: 12px 14px; + border: 1px solid #bdd4ff; + border-radius: 10px; + background: linear-gradient(180deg, #f8fbff 0%, #eef4ff 100%); + color: #0b63ce; + font-size: 14px; + font-weight: 600; cursor: pointer; + transition: + border-color 0.15s, + background 0.15s, + box-shadow 0.15s; + + &:hover { + border-color: #0b63ce; + background: #f0f6ff; + box-shadow: 0 2px 8px rgba(11, 99, 206, 0.12); + } + + .material-icons { + font-size: 20px; + } } -@media (max-width: 900px) { - .patents-header { - flex-direction: column; - align-items: stretch; - } - - .patents-header-actions { - margin-left: 0; - justify-content: space-between; - } +.patent-detail-hint { + margin: 8px 0 0; + font-size: 12px; + line-height: 1.4; + color: #888; + text-align: center; +} +@media (max-width: 960px) { .patents-content { flex-direction: column; } .patent-detail { - flex: 1; width: 100%; } } diff --git a/webapp/src/app/modules/keywords-search/keywords-patents/keywords-patents.component.ts b/webapp/src/app/modules/keywords-search/keywords-patents/keywords-patents.component.ts index 42af4436..4a636af1 100644 --- a/webapp/src/app/modules/keywords-search/keywords-patents/keywords-patents.component.ts +++ b/webapp/src/app/modules/keywords-search/keywords-patents/keywords-patents.component.ts @@ -1,11 +1,14 @@ -import { NgTemplateOutlet } from '@angular/common'; -import { Component, input, output, signal } from '@angular/core'; -import { MatButtonModule } from '@angular/material/button'; +import { Component, computed, inject, input, output, signal } from '@angular/core'; +import { toSignal } from '@angular/core/rxjs-interop'; +import { MatFormFieldModule } from '@angular/material/form-field'; import { MatIconModule } from '@angular/material/icon'; -import { Router } from '@angular/router'; +import { MatSelectModule } from '@angular/material/select'; +import { PageEvent } from '@angular/material/paginator'; +import { ActivatedRoute, Router } from '@angular/router'; import { PatentEntry } from '../../../api/model/patentEntry'; import { KeywordPatentMatch } from '../../../api/model/keywordPatentMatch'; import { LoadingComponent } from '../../../shared/ui/loading/loading.component'; +import { QueryParamPaginatorComponent } from '../../../shared/ui/query-param-paginator/query-param-paginator.component'; import { formatPatentDate, getPublicationStageLabel, @@ -13,14 +16,25 @@ import { import { KeywordPatentMappingStatus } from '../../../api'; type SourceFilter = 'all' | 'EPO' | 'USPTO'; +type SortMode = 'date' | 'title'; @Component({ selector: 'app-keywords-patents', - imports: [NgTemplateOutlet, MatButtonModule, MatIconModule, LoadingComponent], + imports: [ + MatFormFieldModule, + MatIconModule, + MatSelectModule, + LoadingComponent, + QueryParamPaginatorComponent, + ], templateUrl: './keywords-patents.component.html', styleUrl: './keywords-patents.component.scss', }) export class KeywordsPatentsComponent { + private readonly route = inject(ActivatedRoute); + private readonly router = inject(Router); + private readonly queryParams = toSignal(this.route.queryParams); + readonly matches = input([]); readonly mappingStatus = input(null); readonly loading = input(false); @@ -30,54 +44,65 @@ export class KeywordsPatentsComponent { readonly reload = output(); activeFilter = signal('all'); + sortMode = signal('date'); selectedMatch = signal(null); - selectedPage = signal(1); - readonly pageSize = 10; - constructor(private readonly router: Router) {} + readonly pageIndex = computed(() => { + const params = this.queryParams(); + return params?.['page'] ? +params['page'] || 0 : 0; + }); + + readonly pageSize = computed(() => { + const params = this.queryParams(); + return params?.['size'] ? +params['size'] || 10 : 10; + }); + + readonly filteredMatches = computed(() => { + const filter = this.activeFilter(); + let items = this.matches(); + if (filter !== 'all') { + items = items.filter((item) => item.patent.source === filter); + } + return this.sortMatches(items); + }); emptyMessage(): string { switch (this.mappingStatus()) { case 'search_error': return 'Die Patentrecherche ist technisch fehlgeschlagen. Bitte später erneut versuchen.'; default: - return 'Keine passenden Patente gefunden'; + return 'Keine passenden Patente gefunden.'; } } - filteredMatches(): KeywordPatentMatch[] { - const filter = this.activeFilter(); - const items = this.matches(); - if (filter === 'all') { - return items; - } - return items.filter((item) => item.patent.source === filter); - } - - pagedMatches(): KeywordPatentMatch[] { - const start = (this.selectedPage() - 1) * this.pageSize; - return this.filteredMatches().slice(start, start + this.pageSize); - } - - pageCount(): number { - return Math.max( - 1, - Math.ceil(this.filteredMatches().length / this.pageSize), - ); - } - - hasPagination(): boolean { - return this.pageCount() > 1; + getPagedMatches(): KeywordPatentMatch[] { + const start = this.pageIndex() * this.pageSize(); + return this.filteredMatches().slice(start, start + this.pageSize()); } setFilter(filter: SourceFilter): void { this.activeFilter.set(filter); - this.selectedPage.set(1); + this.selectedMatch.set(null); + this.resetPage(); + } + + setSortMode(sortMode: SortMode): void { + this.sortMode.set(sortMode); + this.selectedMatch.set(null); + this.resetPage(); + } + + onPatentPageChange(_event: PageEvent): void { this.selectedMatch.set(null); } - setPage(page: number): void { - this.selectedPage.set(Math.min(Math.max(page, 1), this.pageCount())); + private resetPage(): void { + void this.router.navigate([], { + relativeTo: this.route, + queryParams: { page: 0 }, + queryParamsHandling: 'merge', + replaceUrl: true, + }); } selectMatch(item: KeywordPatentMatch): void { @@ -90,8 +115,21 @@ export class KeywordsPatentsComponent { void this.router.navigate(['/patent', match.patent.patent_id]); } - onReload(): void { - this.reload.emit(); + getEpoCount(): number { + return this.matches().filter((item) => item.patent.source === 'EPO').length; + } + + getUsptoCount(): number { + return this.matches().filter((item) => item.patent.source === 'USPTO') + .length; + } + + getInventorsLabel(patent: PatentEntry): string { + return patent.inventors?.length ? patent.inventors.join(', ') : '-'; + } + + getAssigneesLabel(patent: PatentEntry): string { + return patent.assignees?.length ? patent.assignees.join(', ') : '-'; } formatDate(date: string | null | undefined): string { @@ -102,18 +140,15 @@ export class KeywordsPatentsComponent { return getPublicationStageLabel(patent); } - formatScore(score: number | null | undefined): string { - if (score == null || Number.isNaN(score)) { - return '-'; + getAbstractPreview(abstract: string | null | undefined): string | null { + if (!abstract?.trim()) { + return null; } - return score.toFixed(2); - } - - formatMatchList(values: string[] | null | undefined): string { - if (!values || values.length === 0) { - return '-'; + const text = abstract.trim(); + if (text.length <= 160) { + return text; } - return values.join(', '); + return `${text.slice(0, 160).trimEnd()}…`; } trackMatch(_index: number, item: KeywordPatentMatch): string { @@ -126,4 +161,18 @@ export class KeywordsPatentsComponent { item.match_score, ].join('|'); } + + private sortMatches(items: KeywordPatentMatch[]): KeywordPatentMatch[] { + const mode = this.sortMode(); + return [...items].sort((a, b) => { + if (mode === 'date') { + return (b.patent.publication_date ?? '').localeCompare( + a.patent.publication_date ?? '', + ); + } + return (a.patent.title ?? '').localeCompare(b.patent.title ?? '', 'de', { + sensitivity: 'base', + }); + }); + } } diff --git a/webapp/src/app/modules/keywords-search/patent-search.utils.ts b/webapp/src/app/modules/keywords-search/patent-search.utils.ts index 13224bb1..46c879af 100644 --- a/webapp/src/app/modules/keywords-search/patent-search.utils.ts +++ b/webapp/src/app/modules/keywords-search/patent-search.utils.ts @@ -108,81 +108,3 @@ function sameKeywordSet(a: string[], b: string[]): boolean { const setA = new Set(a.map((keyword) => normalizeKeyword(keyword))); return b.every((keyword) => setA.has(normalizeKeyword(keyword))); } - -export interface PatentScoreWeights { - ipc: number; - topic: number; - text: number; -} - -export const DEFAULT_PATENT_SCORE_WEIGHTS: PatentScoreWeights = { - ipc: 0.6, - topic: 0.25, - text: 0.15, -}; - -export function normalizePatentScoreWeights( - raw: Record, -): PatentScoreWeights { - const ipc = raw['ipc'] ?? DEFAULT_PATENT_SCORE_WEIGHTS.ipc; - const topic = raw['topic'] ?? DEFAULT_PATENT_SCORE_WEIGHTS.topic; - const text = raw['text'] ?? DEFAULT_PATENT_SCORE_WEIGHTS.text; - const sum = ipc + topic + text; - if (sum <= 0) { - return { ...DEFAULT_PATENT_SCORE_WEIGHTS }; - } - return { ipc: ipc / sum, topic: topic / sum, text: text / sum }; -} - -export function computePatentMatchScore( - match: Pick, - weights: PatentScoreWeights, -): number { - return ( - Math.round( - (weights.ipc * match.ipc_score + - weights.topic * match.topic_score + - weights.text * match.text_score) * - 10000, - ) / 10000 - ); -} - -export function applyPatentScoreWeights( - matches: KeywordPatentMatch[], - weights: PatentScoreWeights, -): KeywordPatentMatch[] { - return [...matches] - .map((match) => ({ - ...match, - match_score: computePatentMatchScore(match, weights), - })) - .sort((a, b) => { - const scoreDiff = b.match_score - a.match_score; - if (scoreDiff !== 0) { - return scoreDiff; - } - - const dateA = a.patent.publication_date ?? ''; - const dateB = b.patent.publication_date ?? ''; - if (dateA !== dateB) { - return dateB.localeCompare(dateA); - } - - return a.patent.patent_id.localeCompare(b.patent.patent_id); - }); -} - -function hasPatentComponentScores(match: KeywordPatentMatch): boolean { - return ( - typeof match.ipc_score === 'number' && - typeof match.topic_score === 'number' && - typeof match.text_score === 'number' - ); -} - -export function canReweightPatentMatches( - matches: KeywordPatentMatch[], -): boolean { - return matches.length > 0 && matches.every(hasPatentComponentScores); -} diff --git a/webapp/src/app/modules/keywords-search/search-results/patents-results/patents-results.component.html b/webapp/src/app/modules/keywords-search/search-results/patents-results/patents-results.component.html index 3e0cb344..bd5b16b4 100644 --- a/webapp/src/app/modules/keywords-search/search-results/patents-results/patents-results.component.html +++ b/webapp/src/app/modules/keywords-search/search-results/patents-results/patents-results.component.html @@ -1,24 +1,4 @@
- - - - - -
({ - raw: this.defaultWeights, - normalized: { ...DEFAULT_PATENT_SCORE_WEIGHTS }, - rawSum: 1, - normalizedSum: 1, - valid: true, - }); - readonly patentMatches = signal([]); readonly mappingStatus = signal(null); readonly loadingPatents = signal(false); readonly patentsError = signal(false); - private readonly patentMatchesBase = signal([]); - ngOnInit(): void { const cached = readPatentsCache(this.state.keywords()); if (cached) { @@ -100,19 +38,6 @@ export class KeywordsToPatentsResultsComponent implements OnInit { this.loadMatchingPatents(); } - onWeightsChange(value: WeightsSlidersValue): void { - this.currentWeights.set(value); - } - - onApplyWeights(value: WeightsSlidersValue): void { - this.currentWeights.set(value); - if (!canReweightPatentMatches(this.patentMatchesBase())) { - this.reloadPatents(); - return; - } - this.updateDisplayedMatches(); - } - reloadPatents(): void { clearPatentsCache(); this.loadMatchingPatents(); @@ -149,26 +74,8 @@ export class KeywordsToPatentsResultsComponent implements OnInit { matches: KeywordPatentMatch[], mappingStatus: KeywordPatentMappingStatus | null = null, ): void { - this.patentMatchesBase.set(matches); + this.patentMatches.set(matches); this.mappingStatus.set(mappingStatus); - this.updateDisplayedMatches(); - writePatentsCache( - this.state.keywords(), - this.patentMatchesBase(), - mappingStatus, - ); - } - - private updateDisplayedMatches(): void { - const base = this.patentMatchesBase(); - if (!canReweightPatentMatches(base)) { - this.patentMatches.set(base); - return; - } - - const weights = normalizePatentScoreWeights( - this.currentWeights().normalized, - ); - this.patentMatches.set(applyPatentScoreWeights(base, weights)); + writePatentsCache(this.state.keywords(), matches, mappingStatus); } } diff --git a/webapp/src/app/modules/person-funding/person-funding.component.html b/webapp/src/app/modules/person-funding/person-funding.component.html index a741047e..058cffb5 100644 --- a/webapp/src/app/modules/person-funding/person-funding.component.html +++ b/webapp/src/app/modules/person-funding/person-funding.component.html @@ -120,25 +120,22 @@

Publikationen

- @if (getSubjectArea()) { -
- category -
- {{ getSubjectArea() }} - Fachliche Zuordnung -
-
- } @if (dfgProject.dfg_procedure) {
gavel @@ -142,6 +133,44 @@ } + + @if (getSubjectClassifications().length > 0) { + +
+ category +

Fachsystematik

+ {{ + getSubjectClassifications().length + }} +
+
+ @for (entry of getSubjectClassifications(); track $index) { +
+ @for ( + segment of getClassificationParentSegments(entry); + track $index + ) { + {{ segment }} + chevron_right + } +
+ @for ( + leaf of getClassificationLeafSegments(entry); + track $index + ) { + + {{ leaf }} + + } +
+
+ } +
+
+ }
@@ -335,18 +364,7 @@
Fachliche Zuordnung
{{ getSubjectArea() || 'N/A' }}
- @if (getSubjectClassifications().length > 0) { -
-
Fachsystematik
-
- @for (entry of getSubjectClassifications(); track $index) { -
- {{ formatSubjectClassification(entry) }} -
- } -
-
- } +
DFG-Verfahren
{{ dfgProject.dfg_procedure || 'N/A' }}
diff --git a/webapp/src/app/modules/projects/dfg-details/dfg-details.component.scss b/webapp/src/app/modules/projects/dfg-details/dfg-details.component.scss index 80885471..68d5ae71 100644 --- a/webapp/src/app/modules/projects/dfg-details/dfg-details.component.scss +++ b/webapp/src/app/modules/projects/dfg-details/dfg-details.component.scss @@ -154,7 +154,7 @@ h1 { .metrics-grid { display: grid; - grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); + grid-template-columns: repeat(auto-fit, minmax(300px, 1fr)); gap: 16px; padding-top: 20px; border-top: 1px solid var(--sg-border); @@ -473,10 +473,54 @@ h1 { color: var(--sg-text-muted); } +.classification-list { + display: flex; + flex-direction: column; + gap: 10px; + padding: 16px 20px 20px; +} + .classification-path { - font-size: 13px; - color: var(--sg-text); - line-height: 1.5; + display: flex; + align-items: center; + flex-wrap: wrap; + gap: 4px 2px; + padding: 10px 12px; + border: 1px solid var(--sg-border); + border-radius: var(--sg-radius-sm); + background: var(--sg-surface); +} + +.classification-segment { + font-size: 12px; + line-height: 1.3; + padding: 3px 10px; + border-radius: 10px; + background: var(--sg-surface-soft); + color: var(--sg-text-muted); + white-space: nowrap; + + &--leaf { + background: var(--sg-primary-soft); + color: var(--sg-text); + font-weight: 500; + white-space: normal; + } +} + +.classification-leaf-group { + display: flex; + flex-wrap: wrap; + gap: 4px; +} + +.classification-separator { + width: 16px; + height: 16px; + font-size: 16px; + color: var(--sg-text-muted); + flex-shrink: 0; + opacity: 0.5; } .website-html { diff --git a/webapp/src/app/modules/projects/dfg-details/dfg-details.component.ts b/webapp/src/app/modules/projects/dfg-details/dfg-details.component.ts index add0ec44..7b72ac75 100644 --- a/webapp/src/app/modules/projects/dfg-details/dfg-details.component.ts +++ b/webapp/src/app/modules/projects/dfg-details/dfg-details.component.ts @@ -8,13 +8,9 @@ import { DfgProjectPublicationSummary } from '../../../api/model/dfgProjectPubli import { DfgProjectSubprojectSummary } from '../../../api/model/dfgProjectSubprojectSummary'; import { DfgProjectInstitutionRole } from '../../../api/model/dfgProjectInstitutionRole'; import { DfgProjectPersonRole } from '../../../api/model/dfgProjectPersonRole'; -import { DfgProjectSubjectArea } from '../../../api/model/dfgProjectSubjectArea'; +import { DFGProjectFachgebieteInner } from '../../../api/model/dFGProjectFachgebieteInner'; import { ProjectOaTopicsComponent } from '../../../shared/ui/project-oa-topics/project-oa-topics.component'; -import { Topic } from '../../../api'; -import { - topicHierarchyColor, - TopicHierarchyColorInput, -} from '../../../resolvers/utils/topic-colors'; + @Component({ selector: 'app-dfg-details', standalone: true, @@ -159,22 +155,26 @@ export class DfgDetailsComponent implements OnInit { ); } - // --- Subject classification (DFG Fachsystematik) --- + //(DFG Fachsystematik) - getSubjectClassifications(): DfgProjectSubjectArea[] { + getSubjectClassifications(): DFGProjectFachgebieteInner[] { return this.dfgProject?.subject_classifications ?? []; } - /** Renders one classification entry as a breadcrumb-like path. */ - formatSubjectClassification(entry: DfgProjectSubjectArea): string { + getClassificationParentSegments(entry: DFGProjectFachgebieteInner): string[] { return [ entry.wissenschaftsbereich, entry.fachkollegium, entry.fachgebiet, - entry.fach, - ] - .filter((part) => !!part) - .join(' › '); + ].filter((part): part is string => !!part); + } + + getClassificationLeafSegments(entry: DFGProjectFachgebieteInner): string[] { + if (!entry.fach) return []; + return entry.fach + .split(',') + .map((s) => s.trim()) + .filter((s) => !!s); } // --- Subprojects & publications --- 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 607824ed..9c86010c 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 @@ -27,17 +27,41 @@ open_in_new - -
- @for (classification of element.subject_classifications; track $index) { -

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

+ + @let classifications = getProjectClassifications(project); + @let isClassificationsExpanded = isProjectClassificationsExpanded(project); + @let visibleClassifications = + isClassificationsExpanded ? classifications : classifications.slice(0, 3); +
+ @for (classification of visibleClassifications; track $index) { + + category + {{ + getClassificationFullChain(classification) + }} + } @empty { - - + - + } + @if (classifications.length > 3) { + }
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 5fbc4c11..82987ff1 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 @@ -130,6 +130,7 @@ .topic-chips, .institution-tags, +.classification-tags, .author-tags { display: flex; flex-wrap: wrap; @@ -163,8 +164,16 @@ // Classification container // ------------------------ -.classification-container { - max-width: 200px; +.classification-tag { + max-width: 280px; + cursor: default; // not clickable/filterable, unlike author/institution tags + + .institution-name { + display: block; + overflow: hidden; + white-space: nowrap; + text-overflow: ellipsis; + } } // ------------------------ 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 cc8a9015..baa2ae18 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 @@ -360,4 +360,39 @@ export class DfgProjectTableComponent implements OnInit { return this.expandedProjectTopicsId.includes(project.id); } + expandedProjectClassificationsId: string[] = []; + //classifications + getProjectClassifications(project: DfgProjectSummary): any[] { + return project.subject_classifications ?? []; + } + + isProjectClassificationsExpanded(project: DfgProjectSummary): boolean { + if (!project.id) return false; + + return this.expandedProjectClassificationsId.includes(project.id); + } + + toggleProjectClassificationsExpansion(project: DfgProjectSummary): void { + if (!project.id) return; + + if (this.expandedProjectClassificationsId.includes(project.id)) { + this.expandedProjectClassificationsId = + this.expandedProjectClassificationsId.filter((id) => id !== project.id); + } else { + this.expandedProjectClassificationsId.push(project.id); + } + } + + getClassificationFullChain(classification: any): string { + return [ + classification.wissenschaftsbereich || '-', + classification.fachkollegium || '-', + classification.fachgebiet || '-', + classification.fach || '-', + ].join(' → '); + } + + getClassificationTooltipText(classification: any): string { + return this.getClassificationFullChain(classification); + } } From 32a38b46fe786fc28d1cb01399f9eb79dcf3390b Mon Sep 17 00:00:00 2001 From: genja Date: Mon, 3 Aug 2026 20:29:47 +0200 Subject: [PATCH 010/114] unified fachgebiete and subject_classifications. Added subject classifications to dfg detail project page --- .../main/inse/models/dfg_project_details.py | 25 +--- .../projects_dfg_v2/project/dfg_project.py | 18 +-- .../inse/projects/projects_search_client.py | 128 +++++++++++++++++- 3 files changed, 128 insertions(+), 43 deletions(-) diff --git a/service/src/main/inse/models/dfg_project_details.py b/service/src/main/inse/models/dfg_project_details.py index fe914373..a5a704f9 100644 --- a/service/src/main/inse/models/dfg_project_details.py +++ b/service/src/main/inse/models/dfg_project_details.py @@ -170,25 +170,6 @@ class DfgProjectPublicationSummary(BaseModel): ) -class DfgProjectSubjectArea(BaseModel): - """A single subject-area classification entry (DFG 'Fachsystematik').""" - - model_config = ConfigDict(populate_by_name=True) - - fach: str | None = None - fachgebiet: str | None = None - fachkollegium: str | None = None - wissenschaftsbereich: str | None = None - - @classmethod - def from_inner(cls, f: DFGProjectFachgebieteInner) -> "DfgProjectSubjectArea": - return cls( - fach=f.fach, - fachgebiet=f.fachgebiet, - fachkollegium=f.fachkollegium, - wissenschaftsbereich=f.wissenschaftsbereich, - ) - class DfgProjectDetails(BaseModel): """ @@ -253,7 +234,7 @@ class DfgProjectDetails(BaseModel): subject_area_de: str | None = Field(default=None, description="Subject area, summary text (German)") subject_area_en: str | None = Field(default=None, description="Subject area, summary text (English)") - subject_classifications: list[DfgProjectSubjectArea] = Field( + subject_classifications: list[DFGProjectFachgebieteInner] = Field( default_factory=list, description="Detailed DFG subject-area classification entries (Fachsystematik)", ) @@ -319,7 +300,7 @@ class DfgProjectDetails(BaseModel): DfgProjectPublicationSummary.from_inner(p) for p in (project.publications or []) ] subject_classifications = [ - DfgProjectSubjectArea.from_inner(f) for f in (project.fachgebiete or []) + DFGProjectFachgebieteInner.from_dict(f) for f in (project.subject_classifications or []) ] # De-duplicated flat views, order-preserving @@ -383,8 +364,6 @@ class DfgProjectDetails(BaseModel): @classmethod def from_dict(cls, obj: dict) -> "DfgProjectDetails": - """Convenience constructor from a raw dict (e.g. a JSON API response body).""" - obj = cls._sanitize_raw_project_dict(obj) return cls.from_dfg_project(DFGProject.from_dict(obj)) @staticmethod diff --git a/service/src/main/inse/models/projects_dfg_v2/project/dfg_project.py b/service/src/main/inse/models/projects_dfg_v2/project/dfg_project.py index 8ae70f97..8d874a7e 100644 --- a/service/src/main/inse/models/projects_dfg_v2/project/dfg_project.py +++ b/service/src/main/inse/models/projects_dfg_v2/project/dfg_project.py @@ -49,7 +49,6 @@ class DFGProject(BaseModel): equipment_group: StrictStr | None = None equipment_name: StrictStr | None = None external_link: StrictStr | None = None - fachgebiete: list[DFGProjectFachgebieteInner] | None = None fetched_at: datetime | None = None final_report_abstract_de: StrictStr | None = None final_report_abstract_en: StrictStr | None = None @@ -81,7 +80,7 @@ class DFGProject(BaseModel): publications: list[DFGProjectPublicationsInner] | None = None subject_area_de: StrictStr | None = None subject_area_en: StrictStr | None = None - subject_classifications: DFGProjectFachgebieteInner | None = None + subject_classifications: list[DFGProjectFachgebieteInner] | None = None subproject_order: list[StrictStr] | None = None subprojects: list[DFGProjectSubprojectsInner] | None = None template_type: StrictStr | None = None @@ -90,7 +89,7 @@ class DFGProject(BaseModel): website_html_de: StrictStr | None = None website_html_en: StrictStr | None = None topics: list[Topic] | None = None - __properties: ClassVar[list[str]] = ["abstract_de", "abstract_en", "equipment_group", "equipment_name", "external_link", "fachgebiete", "fetched_at", "final_report_abstract_de", "final_report_abstract_en", "funding_end", "funding_period_de", "funding_period_en", "funding_start", "funding_type_de", "funding_type_en", "funding_type_key", "funding_type_sort", "id", "institution_roles_order", "institutions", "international_relation_de", "international_relation_en", "is_transfer_project", "link", "page_url", "parent_project_id", "parent_title_de", "parent_title_en", "person_roles_order", "persons", "project", "project_id", "project_identifier_de", "project_identifier_en", "publications", "subject_area_de", "subject_area_en", "subject_classifications", "subproject_order", "subprojects", "template_type", "title_de", "title_en", "website_html_de", "website_html_en"] + __properties: ClassVar[list[str]] = ["abstract_de", "abstract_en", "equipment_group", "equipment_name", "external_link","fetched_at", "final_report_abstract_de", "final_report_abstract_en", "funding_end", "funding_period_de", "funding_period_en", "funding_start", "funding_type_de", "funding_type_en", "funding_type_key", "funding_type_sort", "id", "institution_roles_order", "institutions", "international_relation_de", "international_relation_en", "is_transfer_project", "link", "page_url", "parent_project_id", "parent_title_de", "parent_title_en", "person_roles_order", "persons", "project", "project_id", "project_identifier_de", "project_identifier_en", "publications", "subject_area_de", "subject_area_en", "subject_classifications", "subproject_order", "subprojects", "template_type", "title_de", "title_en", "website_html_de", "website_html_en"] model_config = ConfigDict( validate_by_name=True, @@ -131,13 +130,6 @@ class DFGProject(BaseModel): exclude=excluded_fields, exclude_none=True, ) - # override the default output from pydantic by calling `to_dict()` of each item in fachgebiete (list) - _items = [] - if self.fachgebiete: - for _item_fachgebiete in self.fachgebiete: - if _item_fachgebiete: - _items.append(_item_fachgebiete.to_dict()) - _dict['fachgebiete'] = _items # override the default output from pydantic by calling `to_dict()` of each item in institutions (list) _items = [] if self.institutions: @@ -164,7 +156,7 @@ class DFGProject(BaseModel): _dict['publications'] = _items # override the default output from pydantic by calling `to_dict()` of subject_classifications if self.subject_classifications: - _dict['subject_classifications'] = self.subject_classifications.to_dict() + _dict['subject_classifications'] = [f.to_dict() for f in self.subject_classifications] # override the default output from pydantic by calling `to_dict()` of each item in subprojects (list) _items = [] if self.subprojects: @@ -191,14 +183,12 @@ class DFGProject(BaseModel): 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] - _obj = cls.model_validate({ "abstract_de": obj.get("abstract_de"), "abstract_en": obj.get("abstract_en"), "equipment_group": obj.get("equipment_group"), "equipment_name": obj.get("equipment_name"), "external_link": obj.get("external_link"), - "fachgebiete": [DFGProjectFachgebieteInner.from_dict(_item) for _item in obj["fachgebiete"]] if obj.get("fachgebiete") is not None else None, "fetched_at": obj.get("fetched_at"), "final_report_abstract_de": obj.get("final_report_abstract_de"), "final_report_abstract_en": obj.get("final_report_abstract_en"), @@ -230,7 +220,7 @@ class DFGProject(BaseModel): "publications": [DFGProjectPublicationsInner.from_dict(_item) for _item in obj["publications"]] if obj.get("publications") is not None else None, "subject_area_de": obj.get("subject_area_de"), "subject_area_en": obj.get("subject_area_en"), - "subject_classifications": DFGProjectFachgebieteInner.from_dict(obj["subject_classifications"]) if obj.get("subject_classifications") is not None else None, + "subject_classifications": [DFGProjectFachgebieteInner.from_dict(f) for f in (obj.get("subject_classifications") or [])], "subproject_order": obj.get("subproject_order"), "subprojects": [DFGProjectSubprojectsInner.from_dict(_item) for _item in obj["subprojects"]] if obj.get("subprojects") is not None else None, "template_type": obj.get("template_type"), diff --git a/service/src/main/inse/projects/projects_search_client.py b/service/src/main/inse/projects/projects_search_client.py index b6b0a041..72c9194a 100644 --- a/service/src/main/inse/projects/projects_search_client.py +++ b/service/src/main/inse/projects/projects_search_client.py @@ -654,12 +654,128 @@ async def get_dfg_project_by_id(project_id: str) -> DfgProjectDetails | None: ) hits = response.get("hits", {}).get("hits", []) - if hits: - hit = hits[0] - hit["_source"]["topics"] = topic_lookup.get(project_id, []) - details = DfgProjectDetails.from_elastic_hit(hit=hit) - return details - return None + if not hits: + return None + + hit = hits[0] + source = hit["_source"] + source["topics"] = topic_lookup.get(project_id, []) + + persons = source.get("persons", []) + + # --- Enrich persons with institute/root info (mirrors search_dfg_projects) --- + person_ids = { + person["person_id"] + for person in persons + if isinstance(person, dict) and person.get("person_id") is not None + } + person_lookup = await get_person_institutes(person_ids=list(person_ids)) + + institutions: dict[str, dict] = {} + + for person in persons: + person_id = person.get("person_id") + institute = person_lookup.get(person_id) + if not institute: + continue + + 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") + + if institute.get("institute_id") is not None: + institutions[f"institute:{institute['institute_id']}"] = { + "institute_id": institute["institute_id"], + "institute_name_de": institute.get("institute_name_de"), + "institute_name_en": institute.get("institute_name_en"), + } + + if institute.get("root_id") is not None: + institutions[f"root:{institute['root_id']}"] = { + "institute_id": institute["root_id"], + "institute_name_de": institute.get("root_name_de"), + "institute_name_en": institute.get("root_name_en"), + } + + source["institutions"] = list(institutions.values()) + + return DfgProjectDetails.from_elastic_hit(hit=hit) + +async def get_dfg_project_by_id(project_id: str) -> DfgProjectDetails | None: + """Fetches the details of a single DFG project based on its project ID. + + Args: + project_id (str): The project ID to fetch. + + Returns: + Optional[DfgProjectDetails]: The project details or None if not found. + """ + topic_lookup = await get_openalex_topics_for_dfg_projects(project_ids=[project_id]) + query = {"ids": {"values": [project_id]}} + + response = await elasticsearch.search( + index=ESIndex.DFG_PROJECTS, + query=query, + size=1, + ) + hits = response.get("hits", {}).get("hits", []) + + if not hits: + return None + + hit = hits[0] + source = hit["_source"] + source["topics"] = topic_lookup.get(project_id, []) + + persons = source.get("persons", []) + + #Enrich persons with institute/root info + person_ids = { + person["person_id"] + for person in persons + if isinstance(person, dict) and person.get("person_id") is not None + } + person_lookup = await get_person_institutes(person_ids=list(person_ids)) + + institutions: dict[str, dict] = {} + + for person in persons: + person_id = person.get("person_id") + institute = person_lookup.get(person_id) + if not institute: + continue + + 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") + + if institute.get("institute_id") is not None: + institutions[f"institute:{institute['institute_id']}"] = { + "institute_id": institute["institute_id"], + "institute_name_de": institute.get("institute_name_de"), + "institute_name_en": institute.get("institute_name_en"), + } + + if institute.get("root_id") is not None: + institutions[f"root:{institute['root_id']}"] = { + "institute_id": institute["root_id"], + "institute_name_de": institute.get("root_name_de"), + "institute_name_en": institute.get("root_name_en"), + } + + source["institutions"] = list(institutions.values()) + + return DfgProjectDetails.from_elastic_hit(hit=hit) #BUND From fd0bc89771ce8f4868bef17b0dfd8703da79a412 Mon Sep 17 00:00:00 2001 From: genja Date: Mon, 3 Aug 2026 20:29:57 +0200 Subject: [PATCH 011/114] regenerated models and services --- webapp/src/app/api/.openapi-generator/FILES | 2 +- webapp/src/app/api/model/dfgProjectDetails.ts | 4 ++-- webapp/src/app/api/model/dfgProjectKeyword.ts | 16 ++++++++++++++ .../app/api/model/dfgProjectSubjectArea.ts | 21 ------------------- webapp/src/app/api/model/dfgProjectTopic.ts | 2 ++ webapp/src/app/api/model/models.ts | 2 +- 6 files changed, 22 insertions(+), 25 deletions(-) create mode 100644 webapp/src/app/api/model/dfgProjectKeyword.ts delete mode 100644 webapp/src/app/api/model/dfgProjectSubjectArea.ts diff --git a/webapp/src/app/api/.openapi-generator/FILES b/webapp/src/app/api/.openapi-generator/FILES index e751f4aa..3c0e087f 100644 --- a/webapp/src/app/api/.openapi-generator/FILES +++ b/webapp/src/app/api/.openapi-generator/FILES @@ -103,11 +103,11 @@ model/dfgPersonSummary.ts model/dfgPersonSummaryPage.ts model/dfgProjectDetails.ts model/dfgProjectInstitutionRole.ts +model/dfgProjectKeyword.ts model/dfgProjectPage.ts model/dfgProjectPersonRole.ts model/dfgProjectPublicationSummary.ts model/dfgProjectStatusStatistics.ts -model/dfgProjectSubjectArea.ts model/dfgProjectSubprojectSummary.ts model/dfgProjectSummary.ts model/dfgProjectTopic.ts diff --git a/webapp/src/app/api/model/dfgProjectDetails.ts b/webapp/src/app/api/model/dfgProjectDetails.ts index 7d58d592..07bcced0 100644 --- a/webapp/src/app/api/model/dfgProjectDetails.ts +++ b/webapp/src/app/api/model/dfgProjectDetails.ts @@ -10,7 +10,7 @@ import { DfgProjectPersonRole } from './dfgProjectPersonRole'; import { DfgProjectSubprojectSummary } from './dfgProjectSubprojectSummary'; import { DfgProjectInstitutionRole } from './dfgProjectInstitutionRole'; -import { DfgProjectSubjectArea } from './dfgProjectSubjectArea'; +import { DFGProjectFachgebieteInner } from './dFGProjectFachgebieteInner'; import { Topic } from './topic'; import { DfgProjectPublicationSummary } from './dfgProjectPublicationSummary'; @@ -49,7 +49,7 @@ export interface DfgProjectDetails { /** * Detailed DFG subject-area classification entries (Fachsystematik) */ - subject_classifications?: Array; + subject_classifications?: Array; international_relation_de?: string | null; international_relation_en?: string | null; /** diff --git a/webapp/src/app/api/model/dfgProjectKeyword.ts b/webapp/src/app/api/model/dfgProjectKeyword.ts new file mode 100644 index 00000000..2e898f1c --- /dev/null +++ b/webapp/src/app/api/model/dfgProjectKeyword.ts @@ -0,0 +1,16 @@ +/** + * 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 DfgProjectKeyword { + name: string; + project_count: number; +} + diff --git a/webapp/src/app/api/model/dfgProjectSubjectArea.ts b/webapp/src/app/api/model/dfgProjectSubjectArea.ts deleted file mode 100644 index c46f610d..00000000 --- a/webapp/src/app/api/model/dfgProjectSubjectArea.ts +++ /dev/null @@ -1,21 +0,0 @@ -/** - * Innovation Search Engine API - * - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -/** - * A single subject-area classification entry (DFG \'Fachsystematik\'). - */ -export interface DfgProjectSubjectArea { - fach?: string | null; - fachgebiet?: string | null; - fachkollegium?: string | null; - wissenschaftsbereich?: string | null; -} - diff --git a/webapp/src/app/api/model/dfgProjectTopic.ts b/webapp/src/app/api/model/dfgProjectTopic.ts index baaff946..4b99c034 100644 --- a/webapp/src/app/api/model/dfgProjectTopic.ts +++ b/webapp/src/app/api/model/dfgProjectTopic.ts @@ -7,6 +7,7 @@ * https://openapi-generator.tech * Do not edit the class manually. */ +import { DfgProjectKeyword } from './dfgProjectKeyword'; export interface DfgProjectTopic { @@ -16,5 +17,6 @@ export interface DfgProjectTopic { field?: string | null; domain?: string | null; project_count: number; + keywords: Array; } diff --git a/webapp/src/app/api/model/models.ts b/webapp/src/app/api/model/models.ts index c16ec742..afed834d 100644 --- a/webapp/src/app/api/model/models.ts +++ b/webapp/src/app/api/model/models.ts @@ -68,11 +68,11 @@ export * from './dfgPersonSummary'; export * from './dfgPersonSummaryPage'; export * from './dfgProjectDetails'; export * from './dfgProjectInstitutionRole'; +export * from './dfgProjectKeyword'; export * from './dfgProjectPage'; export * from './dfgProjectPersonRole'; export * from './dfgProjectPublicationSummary'; export * from './dfgProjectStatusStatistics'; -export * from './dfgProjectSubjectArea'; export * from './dfgProjectSubprojectSummary'; export * from './dfgProjectSummary'; export * from './dfgProjectTopic'; From f74396e97b9fde95c2d2dbd3b8b8b62c0b5520fa Mon Sep 17 00:00:00 2001 From: louis-19041904 Date: Mon, 3 Aug 2026 21:06:31 +0200 Subject: [PATCH 012/114] fix: correct query param key for topic filter from person profile --- webapp/src/app/modules/person/person.component.ts | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/webapp/src/app/modules/person/person.component.ts b/webapp/src/app/modules/person/person.component.ts index a34e38b6..adf3cffa 100644 --- a/webapp/src/app/modules/person/person.component.ts +++ b/webapp/src/app/modules/person/person.component.ts @@ -23,6 +23,7 @@ import { PersonBioResolved } from '../../resolvers/person-bio.resolver'; import { PersonDataResolved } from '../../resolvers/person.resolver'; import { BookmarkService } from '../../shared/services/bookmark.service'; import { collaborationGraphQueryParamKeys } from '../../resolvers/collaboration-graph.resolver'; +import { workQueryParamKeys } from '../../resolvers/work-page.resolver'; type PersonLink = { label: string; @@ -342,8 +343,8 @@ export class PersonComponent { void this.router.navigate(['publications'], { relativeTo: this.activatedRoute, queryParams: { - page: 0, - publicationTopicId: selection.id, + [workQueryParamKeys.page]: 0, + [workQueryParamKeys.topicId]: selection.id, }, }); } From f9591c512ccb709582af00e208ffa4170a590509 Mon Sep 17 00:00:00 2001 From: louis-19041904 Date: Mon, 3 Aug 2026 21:06:54 +0200 Subject: [PATCH 013/114] fix: correct query param keys for topic/year filters from timeline and wordcloud --- .../person-overview.component.ts | 21 +++++++------------ 1 file changed, 8 insertions(+), 13 deletions(-) diff --git a/webapp/src/app/modules/person-overview/person-overview.component.ts b/webapp/src/app/modules/person-overview/person-overview.component.ts index 6966b0de..ff8821fd 100644 --- a/webapp/src/app/modules/person-overview/person-overview.component.ts +++ b/webapp/src/app/modules/person-overview/person-overview.component.ts @@ -14,6 +14,7 @@ import { TopicTimelineElement, TopicTimelineTopic, } from './components/research-timeline/research-timeline.component'; +import { workQueryParamKeys } from '../../resolvers/work-page.resolver'; import { TopicLegendTopic } from '../../resolvers/utils/topic-legend'; import { topicHierarchyColor } from '../../resolvers/utils/topic-colors'; import { buildTopicHierarchyTooltip } from '../../resolvers/utils/topic-tooltip'; @@ -184,12 +185,9 @@ export class PersonOverviewComponent implements OnInit { void this.router.navigate(['../publications'], { relativeTo: this.route, queryParams: { - publicationPage: 1, - publicationYear: selection.years, - publicationTopicId: selection.topic.id, - publicationTopicName: selection.topic.name, - publicationTopicField: selection.topic.field_name ?? null, - publicationTopicDomain: selection.topic.domain_name ?? null, + [workQueryParamKeys.page]: 0, + [workQueryParamKeys.years]: selection.years, + [workQueryParamKeys.topicId]: selection.topic.id, }, }); } @@ -202,8 +200,8 @@ export class PersonOverviewComponent implements OnInit { void this.router.navigate(['../publications'], { relativeTo: this.route, queryParams: { - publicationPage: 1, - publicationYear: years, + [workQueryParamKeys.page]: 0, + [workQueryParamKeys.years]: years, }, }); } @@ -226,11 +224,8 @@ export class PersonOverviewComponent implements OnInit { void this.router.navigate(['../publications'], { relativeTo: this.route, queryParams: { - publicationPage: 1, - publicationTopicId: word.topicId, - publicationTopicName: word.name, - publicationTopicField: word.fieldName ?? null, - publicationTopicDomain: word.domainName ?? null, + [workQueryParamKeys.page]: 0, + [workQueryParamKeys.topicId]: word.topicId, }, }); } From 1d24f912aeb2e472e2ccbd040bd8e4cea1b23b67 Mon Sep 17 00:00:00 2001 From: louis-19041904 Date: Mon, 3 Aug 2026 21:17:02 +0200 Subject: [PATCH 014/114] add country-flag component --- .../country-flag/country-flag.component.html | 9 ++++++ .../country-flag/country-flag.component.scss | 12 ++++++++ .../ui/country-flag/country-flag.component.ts | 29 +++++++++++++++++++ 3 files changed, 50 insertions(+) create mode 100644 webapp/src/app/shared/ui/country-flag/country-flag.component.html create mode 100644 webapp/src/app/shared/ui/country-flag/country-flag.component.scss create mode 100644 webapp/src/app/shared/ui/country-flag/country-flag.component.ts diff --git a/webapp/src/app/shared/ui/country-flag/country-flag.component.html b/webapp/src/app/shared/ui/country-flag/country-flag.component.html new file mode 100644 index 00000000..6d7a322a --- /dev/null +++ b/webapp/src/app/shared/ui/country-flag/country-flag.component.html @@ -0,0 +1,9 @@ +@if (flagUrl(); as url) { + +} diff --git a/webapp/src/app/shared/ui/country-flag/country-flag.component.scss b/webapp/src/app/shared/ui/country-flag/country-flag.component.scss new file mode 100644 index 00000000..816e2013 --- /dev/null +++ b/webapp/src/app/shared/ui/country-flag/country-flag.component.scss @@ -0,0 +1,12 @@ +.country-flag-img { + display: inline-block; + vertical-align: middle; + + &--bordered { + border: 1px solid var(--sg-border); + } + + &--rounded { + border-radius: 2px; + } +} diff --git a/webapp/src/app/shared/ui/country-flag/country-flag.component.ts b/webapp/src/app/shared/ui/country-flag/country-flag.component.ts new file mode 100644 index 00000000..7d2acbe7 --- /dev/null +++ b/webapp/src/app/shared/ui/country-flag/country-flag.component.ts @@ -0,0 +1,29 @@ +import { Component, computed, input } from '@angular/core'; + +const COUNTRY_CODE_ALIASES: Record = { + uk: 'gb', +}; + +@Component({ + selector: 'app-country-flag', + standalone: true, + templateUrl: './country-flag.component.html', + styleUrl: './country-flag.component.scss', +}) +export class CountryFlagComponent { + readonly countryCode = input(null); + readonly height = input(12); + readonly bordered = input(true); + readonly rounded = input(false); + + readonly normalizedCode = computed(() => { + const code = this.countryCode()?.trim().toLowerCase(); + if (!code) return null; + return COUNTRY_CODE_ALIASES[code] ?? code; + }); + + readonly flagUrl = computed(() => { + const code = this.normalizedCode(); + return code ? `https://flagcdn.io/${code}.svg` : null; + }); +} From 60e74c49168872bb9a529f5b1ed61c866ef04cce Mon Sep 17 00:00:00 2001 From: louis-19041904 Date: Mon, 3 Aug 2026 21:17:30 +0200 Subject: [PATCH 015/114] use country-flag component in profile header --- webapp/src/app/modules/person/person.component.html | 8 +------- webapp/src/app/modules/person/person.component.scss | 5 ----- webapp/src/app/modules/person/person.component.ts | 2 ++ 3 files changed, 3 insertions(+), 12 deletions(-) diff --git a/webapp/src/app/modules/person/person.component.html b/webapp/src/app/modules/person/person.component.html index f87644e4..173406d8 100644 --- a/webapp/src/app/modules/person/person.component.html +++ b/webapp/src/app/modules/person/person.component.html @@ -41,13 +41,7 @@ } @if (countryCode(); as countryCode) { - + {{ countryCode }} } diff --git a/webapp/src/app/modules/person/person.component.scss b/webapp/src/app/modules/person/person.component.scss index cfa06e88..556a78dc 100644 --- a/webapp/src/app/modules/person/person.component.scss +++ b/webapp/src/app/modules/person/person.component.scss @@ -158,11 +158,6 @@ font-size: 13px; } -.institution-country .flag-img { - border: 1px solid var(--sg-border); - border-radius: 2px; -} - .stat-item.has-tooltip { cursor: help; } diff --git a/webapp/src/app/modules/person/person.component.ts b/webapp/src/app/modules/person/person.component.ts index adf3cffa..a7a9c9cc 100644 --- a/webapp/src/app/modules/person/person.component.ts +++ b/webapp/src/app/modules/person/person.component.ts @@ -17,6 +17,7 @@ import { import { of, switchMap, finalize, map, catchError, combineLatest } from 'rxjs'; import { PersonInterestingComponent } from '../person-interesting/person-interesting.component'; +import { CountryFlagComponent } from '../../shared/ui/country-flag/country-flag.component'; import { WorksService } from '../../api'; import { LoadingComponent } from '../../shared/ui/loading/loading.component'; import { PersonBioResolved } from '../../resolvers/person-bio.resolver'; @@ -44,6 +45,7 @@ type PersonLink = { RouterOutlet, RouterModule, LoadingComponent, + CountryFlagComponent, ], templateUrl: './person.component.html', styleUrl: './person.component.scss', From 53a36e79748096f857cadb4316c43b27ae685689 Mon Sep 17 00:00:00 2001 From: louis-19041904 Date: Mon, 3 Aug 2026 21:18:02 +0200 Subject: [PATCH 016/114] use country-flag component in publication detail institutions --- .../publication-detail.component.html | 13 ++++--------- .../publication-detail.component.scss | 5 ----- .../publication-detail.component.ts | 2 ++ 3 files changed, 6 insertions(+), 14 deletions(-) diff --git a/webapp/src/app/modules/publication-detail/publication-detail.component.html b/webapp/src/app/modules/publication-detail/publication-detail.component.html index 91648d77..fed2db7d 100644 --- a/webapp/src/app/modules/publication-detail/publication-detail.component.html +++ b/webapp/src/app/modules/publication-detail/publication-detail.component.html @@ -409,15 +409,10 @@ @if (institution.country) { - + {{ institution.country.toUpperCase() }} } @else if (institution.type) { diff --git a/webapp/src/app/modules/publication-detail/publication-detail.component.scss b/webapp/src/app/modules/publication-detail/publication-detail.component.scss index 254181d3..985c2efd 100644 --- a/webapp/src/app/modules/publication-detail/publication-detail.component.scss +++ b/webapp/src/app/modules/publication-detail/publication-detail.component.scss @@ -491,11 +491,6 @@ dd { font-size: 13px; } -.institution-country .flag-img { - border: 1px solid var(--sg-border); - border-radius: 2px; -} - .link-list a { display: flex; align-items: center; diff --git a/webapp/src/app/modules/publication-detail/publication-detail.component.ts b/webapp/src/app/modules/publication-detail/publication-detail.component.ts index 98311081..51616f1a 100644 --- a/webapp/src/app/modules/publication-detail/publication-detail.component.ts +++ b/webapp/src/app/modules/publication-detail/publication-detail.component.ts @@ -17,6 +17,7 @@ import { WorkClassification, } from '../../api'; import { TopicChipComponent } from '../../shared/ui/topic-chip/topic-chip.component'; +import { CountryFlagComponent } from '../../shared/ui/country-flag/country-flag.component'; import { topicHierarchyColor } from '../../resolvers/utils/topic-colors'; import { WorkTypePipe } from '../../shared/pipes/work-type.pipe'; import { LanguageCodePipe } from '../../shared/pipes/language-code.pipe'; @@ -50,6 +51,7 @@ interface InstitutionDetail { LanguageCodePipe, WorkPrimaryCategoryPipe, ResearchProfileComponent, + CountryFlagComponent, ], templateUrl: './publication-detail.component.html', styleUrl: './publication-detail.component.scss', From c31aef41316e021d58c7bbd0a2950dca086ee74a Mon Sep 17 00:00:00 2001 From: louis-19041904 Date: Mon, 3 Aug 2026 21:19:00 +0200 Subject: [PATCH 017/114] use country-flag component in person card --- .../modules/person-card/person-card.component.html | 11 +++++------ .../modules/person-card/person-card.component.scss | 8 ++------ .../app/modules/person-card/person-card.component.ts | 2 ++ 3 files changed, 9 insertions(+), 12 deletions(-) diff --git a/webapp/src/app/modules/person-card/person-card.component.html b/webapp/src/app/modules/person-card/person-card.component.html index 1231d2a5..e5e1d0b2 100644 --- a/webapp/src/app/modules/person-card/person-card.component.html +++ b/webapp/src/app/modules/person-card/person-card.component.html @@ -86,12 +86,11 @@ >{{ inst.display_name ?? '' }} @if (inst.country_code && !loading()) { - + Date: Mon, 3 Aug 2026 21:19:40 +0200 Subject: [PATCH 018/114] use country-flag component in person-list filter chip --- .../modules/person-list/person-list.component.html | 12 ++++-------- .../app/modules/person-list/person-list.component.ts | 2 ++ 2 files changed, 6 insertions(+), 8 deletions(-) diff --git a/webapp/src/app/modules/person-list/person-list.component.html b/webapp/src/app/modules/person-list/person-list.component.html index 6560642e..782692fb 100644 --- a/webapp/src/app/modules/person-list/person-list.component.html +++ b/webapp/src/app/modules/person-list/person-list.component.html @@ -69,15 +69,11 @@ institutionFilterLabel(filter) }} @if (filter.countryCode) { - + [countryCode]="filter.countryCode" + [height]="10" + [bordered]="false" /> {{ filter.countryCode.toUpperCase() }} diff --git a/webapp/src/app/modules/person-list/person-list.component.ts b/webapp/src/app/modules/person-list/person-list.component.ts index e54df52b..43b342ec 100644 --- a/webapp/src/app/modules/person-list/person-list.component.ts +++ b/webapp/src/app/modules/person-list/person-list.component.ts @@ -25,6 +25,7 @@ import { import { TopicsService } from '../../api/api/topics.service'; import { TopicHierarchyComponent } from '../topic-hierarchy/topic-hierarchy.component'; import { PersonCardComponent } from '../person-card/person-card.component'; +import { CountryFlagComponent } from '../../shared/ui/country-flag/country-flag.component'; import { topicHierarchyColor } from '../../resolvers/utils/topic-colors'; import { buildTopicHierarchyTooltip } from '../../resolvers/utils/topic-tooltip'; import { SharedStateService } from '../../shared/services/shared-state.service'; @@ -65,6 +66,7 @@ type InstitutionYearFilterMode = 'in' | 'from' | 'between'; PersonCardComponent, SkTextDirective, MatAutocompleteModule, + CountryFlagComponent, ], templateUrl: './person-list.component.html', styleUrl: './person-list.component.scss', From 876fbb99806dff853caa6a333094ea0a87ab99e6 Mon Sep 17 00:00:00 2001 From: louis-19041904 Date: Mon, 3 Aug 2026 21:20:32 +0200 Subject: [PATCH 019/114] use country-flag component in EU-Cordis organizations table --- .../organizations-table.component.html | 12 ++++-------- .../organizations-table.component.ts | 16 ++-------------- 2 files changed, 6 insertions(+), 22 deletions(-) diff --git a/webapp/src/app/modules/projects/eu-cordis-details/organizations-table/organizations-table.component.html b/webapp/src/app/modules/projects/eu-cordis-details/organizations-table/organizations-table.component.html index 5cbd973b..45101292 100644 --- a/webapp/src/app/modules/projects/eu-cordis-details/organizations-table/organizations-table.component.html +++ b/webapp/src/app/modules/projects/eu-cordis-details/organizations-table/organizations-table.component.html @@ -33,15 +33,11 @@ {{ org.city }} @if (org.country) { - + [countryCode]="org.country" + [height]="10" + [bordered]="false" /> } } @else { diff --git a/webapp/src/app/modules/projects/eu-cordis-details/organizations-table/organizations-table.component.ts b/webapp/src/app/modules/projects/eu-cordis-details/organizations-table/organizations-table.component.ts index ea6adba6..bf190a58 100644 --- a/webapp/src/app/modules/projects/eu-cordis-details/organizations-table/organizations-table.component.ts +++ b/webapp/src/app/modules/projects/eu-cordis-details/organizations-table/organizations-table.component.ts @@ -19,6 +19,7 @@ import { DataTableComponent, GenericColumn, } from '../../../../shared/ui/data-table/data-table.component'; +import { CountryFlagComponent } from '../../../../shared/ui/country-flag/country-flag.component'; @Component({ selector: 'app-organizations-table', @@ -29,6 +30,7 @@ import { CurrencyPipe, DataTableComponent, MatPaginatorModule, + CountryFlagComponent, ], templateUrl: './organizations-table.component.html', styleUrl: './organizations-table.component.scss', @@ -128,20 +130,6 @@ export class OrganizationsTableComponent { this.pageSize.set(event.pageSize); } - getSvgByCountryCode(code: string | undefined | null): string { - if (!code) { - return ''; - } - - const codeLower = code.toLowerCase(); - - if (codeLower === 'uk') { - return 'gb'; - } - - return codeLower; - } - getOrgsCount(): number { return this.orgs?.length || 0; } From 0afb6a94811d0111b08ba5f9c6f9021dd02d551a Mon Sep 17 00:00:00 2001 From: louis-19041904 Date: Mon, 3 Aug 2026 21:38:46 +0200 Subject: [PATCH 020/114] remove unintended flag border in person card and filter chip --- webapp/src/app/modules/person-card/person-card.component.scss | 1 - webapp/src/app/modules/person-list/person-list.component.scss | 1 - 2 files changed, 2 deletions(-) diff --git a/webapp/src/app/modules/person-card/person-card.component.scss b/webapp/src/app/modules/person-card/person-card.component.scss index 04ab37f9..1b8b015a 100644 --- a/webapp/src/app/modules/person-card/person-card.component.scss +++ b/webapp/src/app/modules/person-card/person-card.component.scss @@ -176,7 +176,6 @@ app-country-flag { flex-shrink: 0; - border: 1px solid; } .country-code { diff --git a/webapp/src/app/modules/person-list/person-list.component.scss b/webapp/src/app/modules/person-list/person-list.component.scss index 51b4f2e0..d6616b57 100644 --- a/webapp/src/app/modules/person-list/person-list.component.scss +++ b/webapp/src/app/modules/person-list/person-list.component.scss @@ -210,7 +210,6 @@ .filter-institution-chip__flag { flex-shrink: 0; margin-left: 6px; - border: 1px solid var(--sg-primary-border, var(--sg-border)); vertical-align: middle; } From 40bb0feaf81fbea0f7208d28abfd8ca9d4efa809 Mon Sep 17 00:00:00 2001 From: louis-19041904 Date: Mon, 3 Aug 2026 21:38:49 +0200 Subject: [PATCH 021/114] Revert "use country-flag component in EU-Cordis organizations table" This reverts commit 876fbb99806dff853caa6a333094ea0a87ab99e6. --- .../organizations-table.component.html | 12 ++++++++---- .../organizations-table.component.ts | 16 ++++++++++++++-- 2 files changed, 22 insertions(+), 6 deletions(-) diff --git a/webapp/src/app/modules/projects/eu-cordis-details/organizations-table/organizations-table.component.html b/webapp/src/app/modules/projects/eu-cordis-details/organizations-table/organizations-table.component.html index 45101292..5cbd973b 100644 --- a/webapp/src/app/modules/projects/eu-cordis-details/organizations-table/organizations-table.component.html +++ b/webapp/src/app/modules/projects/eu-cordis-details/organizations-table/organizations-table.component.html @@ -33,11 +33,15 @@ {{ org.city }} @if (org.country) { - + [src]=" + 'https://flagcdn.io/' + + getSvgByCountryCode(org.country) + + '.svg' + " + height="10" /> } } @else { diff --git a/webapp/src/app/modules/projects/eu-cordis-details/organizations-table/organizations-table.component.ts b/webapp/src/app/modules/projects/eu-cordis-details/organizations-table/organizations-table.component.ts index bf190a58..ea6adba6 100644 --- a/webapp/src/app/modules/projects/eu-cordis-details/organizations-table/organizations-table.component.ts +++ b/webapp/src/app/modules/projects/eu-cordis-details/organizations-table/organizations-table.component.ts @@ -19,7 +19,6 @@ import { DataTableComponent, GenericColumn, } from '../../../../shared/ui/data-table/data-table.component'; -import { CountryFlagComponent } from '../../../../shared/ui/country-flag/country-flag.component'; @Component({ selector: 'app-organizations-table', @@ -30,7 +29,6 @@ import { CountryFlagComponent } from '../../../../shared/ui/country-flag/country CurrencyPipe, DataTableComponent, MatPaginatorModule, - CountryFlagComponent, ], templateUrl: './organizations-table.component.html', styleUrl: './organizations-table.component.scss', @@ -130,6 +128,20 @@ export class OrganizationsTableComponent { this.pageSize.set(event.pageSize); } + getSvgByCountryCode(code: string | undefined | null): string { + if (!code) { + return ''; + } + + const codeLower = code.toLowerCase(); + + if (codeLower === 'uk') { + return 'gb'; + } + + return codeLower; + } + getOrgsCount(): number { return this.orgs?.length || 0; } From fc8260494761f1d7ef565045ec64c90e4e4183c6 Mon Sep 17 00:00:00 2001 From: louis-19041904 Date: Mon, 3 Aug 2026 21:41:41 +0200 Subject: [PATCH 022/114] Reapply "use country-flag component in EU-Cordis organizations table" This reverts commit 40bb0feaf81fbea0f7208d28abfd8ca9d4efa809. --- .../organizations-table.component.html | 12 ++++-------- .../organizations-table.component.ts | 16 ++-------------- 2 files changed, 6 insertions(+), 22 deletions(-) diff --git a/webapp/src/app/modules/projects/eu-cordis-details/organizations-table/organizations-table.component.html b/webapp/src/app/modules/projects/eu-cordis-details/organizations-table/organizations-table.component.html index 5cbd973b..45101292 100644 --- a/webapp/src/app/modules/projects/eu-cordis-details/organizations-table/organizations-table.component.html +++ b/webapp/src/app/modules/projects/eu-cordis-details/organizations-table/organizations-table.component.html @@ -33,15 +33,11 @@ {{ org.city }} @if (org.country) { - + [countryCode]="org.country" + [height]="10" + [bordered]="false" /> } } @else { diff --git a/webapp/src/app/modules/projects/eu-cordis-details/organizations-table/organizations-table.component.ts b/webapp/src/app/modules/projects/eu-cordis-details/organizations-table/organizations-table.component.ts index ea6adba6..bf190a58 100644 --- a/webapp/src/app/modules/projects/eu-cordis-details/organizations-table/organizations-table.component.ts +++ b/webapp/src/app/modules/projects/eu-cordis-details/organizations-table/organizations-table.component.ts @@ -19,6 +19,7 @@ import { DataTableComponent, GenericColumn, } from '../../../../shared/ui/data-table/data-table.component'; +import { CountryFlagComponent } from '../../../../shared/ui/country-flag/country-flag.component'; @Component({ selector: 'app-organizations-table', @@ -29,6 +30,7 @@ import { CurrencyPipe, DataTableComponent, MatPaginatorModule, + CountryFlagComponent, ], templateUrl: './organizations-table.component.html', styleUrl: './organizations-table.component.scss', @@ -128,20 +130,6 @@ export class OrganizationsTableComponent { this.pageSize.set(event.pageSize); } - getSvgByCountryCode(code: string | undefined | null): string { - if (!code) { - return ''; - } - - const codeLower = code.toLowerCase(); - - if (codeLower === 'uk') { - return 'gb'; - } - - return codeLower; - } - getOrgsCount(): number { return this.orgs?.length || 0; } From 78e54248e3c635d40fb62aacc8f379f4725ce507 Mon Sep 17 00:00:00 2001 From: louis-19041904 Date: Mon, 3 Aug 2026 21:43:34 +0200 Subject: [PATCH 023/114] vertically center flag image in country-flag component --- .../app/shared/ui/country-flag/country-flag.component.scss | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/webapp/src/app/shared/ui/country-flag/country-flag.component.scss b/webapp/src/app/shared/ui/country-flag/country-flag.component.scss index 816e2013..3fedf3a6 100644 --- a/webapp/src/app/shared/ui/country-flag/country-flag.component.scss +++ b/webapp/src/app/shared/ui/country-flag/country-flag.component.scss @@ -1,3 +1,8 @@ +:host { + display: inline-flex; + align-items: center; +} + .country-flag-img { display: inline-block; vertical-align: middle; From 52ca2f7339d80ea1c6bfa3e71f8d4291ab68eb1d Mon Sep 17 00:00:00 2001 From: louis-19041904 Date: Mon, 3 Aug 2026 21:49:21 +0200 Subject: [PATCH 024/114] fix overlapping thumbs in year-range-slider not draggable both ways --- .../ui/year-range-slider/year-range-slider.component.html | 2 ++ .../ui/year-range-slider/year-range-slider.component.scss | 8 -------- .../ui/year-range-slider/year-range-slider.component.ts | 5 +++++ 3 files changed, 7 insertions(+), 8 deletions(-) diff --git a/webapp/src/app/shared/ui/year-range-slider/year-range-slider.component.html b/webapp/src/app/shared/ui/year-range-slider/year-range-slider.component.html index 5df6425b..827cab90 100644 --- a/webapp/src/app/shared/ui/year-range-slider/year-range-slider.component.html +++ b/webapp/src/app/shared/ui/year-range-slider/year-range-slider.component.html @@ -22,6 +22,7 @@ { + const mid = (this.minYear() + this.maxYear()) / 2; + return this.dragStartYear() > mid; + }); + constructor() { // Sync external model updates back to drag state effect(() => { From 79320f27c950e0e10e1859370d88d96a52139fff Mon Sep 17 00:00:00 2001 From: louis-19041904 Date: Mon, 3 Aug 2026 21:56:36 +0200 Subject: [PATCH 025/114] use shared year-range-slider component in research timeline --- .../research-timeline.component.html | 57 ++------ .../research-timeline.component.scss | 134 +----------------- .../research-timeline.component.ts | 70 +-------- 3 files changed, 17 insertions(+), 244 deletions(-) diff --git a/webapp/src/app/modules/person-overview/components/research-timeline/research-timeline.component.html b/webapp/src/app/modules/person-overview/components/research-timeline/research-timeline.component.html index 2d2a289e..89bc937d 100644 --- a/webapp/src/app/modules/person-overview/components/research-timeline/research-timeline.component.html +++ b/webapp/src/app/modules/person-overview/components/research-timeline/research-timeline.component.html @@ -56,56 +56,15 @@
-
-
- Zeitraum - - - {{ selectedStartYear }} bis {{ selectedEndYear }} - - - -
- -
-
- - - - -
- -
- {{ minYear }} - {{ maxYear }} -
-
+ class="timeline-year-filter" + [minYear]="minYear" + [maxYear]="maxYear" + [startYear]="selectedStartYear" + [endYear]="selectedEndYear" + (startYearChange)="onYearRangeSliderStartChange($event)" + (endYearChange)="onYearRangeSliderEndChange($event)" />
diff --git a/webapp/src/app/modules/person-overview/components/research-timeline/research-timeline.component.scss b/webapp/src/app/modules/person-overview/components/research-timeline/research-timeline.component.scss index 15b7eef6..55959018 100644 --- a/webapp/src/app/modules/person-overview/components/research-timeline/research-timeline.component.scss +++ b/webapp/src/app/modules/person-overview/components/research-timeline/research-timeline.component.scss @@ -110,143 +110,20 @@ } } -.year-filter { +.timeline-year-filter { grid-column: 3; grid-row: 1; justify-self: end; width: min(var(--year-filter-width), 100%); - padding: 5px 10px; - border: 1px solid var(--sg-border); - border-radius: 10px; - background: var(--sg-surface-muted); - box-sizing: border-box; } -.year-filter-top, -.year-filter-values, -.year-filter-bounds, .phase-meta-row { display: flex; align-items: center; -} - -.year-filter-top, -.phase-meta-row { justify-content: space-between; gap: 10px; } -.year-filter-top { - margin-bottom: 4px; -} - -.year-filter-label { - color: var(--sg-text); - font-size: 12px; - font-weight: 700; -} - -.reset-range-button { - color: var(--accent); - font-size: 11px; - - &:disabled { - color: var(--sg-text-soft); - } -} - -.year-filter-values { - gap: 5px; - color: var(--sg-text-muted); - font-size: 12px; - font-weight: 600; - white-space: nowrap; -} - -.year-filter-bounds { - justify-content: space-between; - margin-top: 0; - color: var(--sg-text-soft); - font-size: 10px; -} - -.year-range-slider { - --range-start: 0%; - --range-end: 100%; - - position: relative; - height: 16px; -} - -.range-track { - position: absolute; - top: 50%; - left: 0; - right: 0; - height: 5px; - transform: translateY(-50%); - border-radius: 999px; - background: linear-gradient( - to right, - var(--sg-border) 0%, - var(--sg-border) var(--range-start), - var(--accent) var(--range-start), - var(--accent) var(--range-end), - var(--sg-border) var(--range-end), - var(--sg-border) 100% - ); -} - -.range-input { - position: absolute; - inset: 0; - width: 100%; - height: 22px; - margin: 0; - appearance: none; - background: transparent; - pointer-events: none; -} - -.range-input::-webkit-slider-runnable-track, -.range-input::-moz-range-track { - height: 5px; - background: transparent; - border: none; -} - -.range-input::-webkit-slider-thumb { - appearance: none; - width: 15px; - height: 15px; - margin-top: -5px; - border: 2px solid var(--sg-surface); - border-radius: 50%; - background: var(--accent); - box-shadow: var(--sg-shadow-sm); - cursor: pointer; - pointer-events: auto; -} - -.range-input::-moz-range-thumb { - width: 15px; - height: 15px; - border: 2px solid var(--sg-surface); - border-radius: 50%; - background: var(--accent); - box-shadow: var(--sg-shadow-sm); - cursor: pointer; - pointer-events: auto; -} - -.range-input-start { - z-index: 2; -} - -.range-input-end { - z-index: 3; -} - .timeline-wrapper { width: 100%; overflow-x: auto; @@ -565,11 +442,6 @@ app-topic-chip.timeline-topic-chip { gap: 7px; } -.timeline-title .reset-range-button { - display: inline-flex; - margin-top: 8px; -} - .timeline-title > .no-topics { display: block; margin-top: 6px; @@ -603,7 +475,7 @@ app-topic-chip.timeline-topic-chip { .timeline-title, .timeline-legend, .view-toggle, - .year-filter { + .timeline-year-filter { grid-column: auto; grid-row: auto; } @@ -616,7 +488,7 @@ app-topic-chip.timeline-topic-chip { justify-self: start; } - .year-filter { + .timeline-year-filter { justify-self: stretch; width: 100%; } diff --git a/webapp/src/app/modules/person-overview/components/research-timeline/research-timeline.component.ts b/webapp/src/app/modules/person-overview/components/research-timeline/research-timeline.component.ts index f879586a..c4ec9ef4 100644 --- a/webapp/src/app/modules/person-overview/components/research-timeline/research-timeline.component.ts +++ b/webapp/src/app/modules/person-overview/components/research-timeline/research-timeline.component.ts @@ -14,6 +14,7 @@ import { } from '@angular/core'; import { TopicChipComponent } from '../../../../shared/ui/topic-chip/topic-chip.component'; import { TopicLegendComponent } from '../../../../shared/ui/topic-legend/topic-legend.component'; +import { YearRangeSliderComponent } from '../../../../shared/ui/year-range-slider/year-range-slider.component'; import { topicHierarchyColor } from '../../../../resolvers/utils/topic-colors'; import { buildTopicLegendGroups, @@ -97,6 +98,7 @@ interface TimelineScrollAnchor { MatTooltipModule, TopicChipComponent, TopicLegendComponent, + YearRangeSliderComponent, ], templateUrl: './research-timeline.component.html', styleUrl: './research-timeline.component.scss', @@ -200,13 +202,6 @@ export class ResearchTimelineComponent implements OnChanges, AfterViewChecked { return this.minYear > 0 && this.maxYear > 0 && this.minYear < this.maxYear; } - get canResetYearRange(): boolean { - return ( - this.selectedStartYear !== this.minYear || - this.selectedEndYear !== this.maxYear - ); - } - get showEarlierYearsControl(): boolean { return this.canLoadEarlierYears || this.loadingEarlierYears; } @@ -223,14 +218,6 @@ export class ResearchTimelineComponent implements OnChanges, AfterViewChecked { return 'Frühere Jahre anzeigen'; } - get rangeStartPercent(): string { - return `${this.calculateRangePercent(this.selectedStartYear)}%`; - } - - get rangeEndPercent(): string { - return `${this.calculateRangePercent(this.selectedEndYear)}%`; - } - get gridTemplateColumns(): string { const count = Math.max( this.timelineItems.length + this.earlierYearsColumnCount, @@ -266,33 +253,13 @@ export class ResearchTimelineComponent implements OnChanges, AfterViewChecked { this.viewModeChange.emit(mode); } - onStartYearInput(event: Event): void { - const nextStartYear = this.parseYearInput(event); - - this.selectedStartYear = this.clampYear(nextStartYear); - - if (this.selectedStartYear > this.selectedEndYear) { - this.selectedEndYear = this.selectedStartYear; - } - + onYearRangeSliderStartChange(year: number): void { + this.selectedStartYear = year; this.emitYearRangeChange(); } - onEndYearInput(event: Event): void { - const nextEndYear = this.parseYearInput(event); - - this.selectedEndYear = this.clampYear(nextEndYear); - - if (this.selectedEndYear < this.selectedStartYear) { - this.selectedStartYear = this.selectedEndYear; - } - - this.emitYearRangeChange(); - } - - resetYearRange(): void { - this.selectedStartYear = this.minYear; - this.selectedEndYear = this.maxYear; + onYearRangeSliderEndChange(year: number): void { + this.selectedEndYear = year; this.emitYearRangeChange(); } @@ -1003,35 +970,10 @@ export class ResearchTimelineComponent implements OnChanges, AfterViewChecked { return topicName.trim().toLowerCase(); } - private parseYearInput(event: Event): number { - const input = event.target as HTMLInputElement | null; - const value = Number(input?.value ?? this.minYear); - - if (!Number.isFinite(value)) { - return this.minYear; - } - - return value; - } - private clampYear(year: number): number { return Math.min(Math.max(year, this.minYear), this.maxYear); } - private calculateRangePercent(year: number): number { - if (!this.hasYearRange) { - return 0; - } - - const totalRange = this.maxYear - this.minYear; - - if (totalRange <= 0) { - return 0; - } - - return ((year - this.minYear) / totalRange) * 100; - } - private isTimelineViewMode(value: string): value is TimelineViewMode { return value === 'years' || value === 'compact' || value === 'wordcloud'; } From b02358e3a0d36fb927c900e2409cb1a6b57b2e36 Mon Sep 17 00:00:00 2001 From: louis-19041904 Date: Mon, 3 Aug 2026 22:02:54 +0200 Subject: [PATCH 026/114] use shared year-range-slider component in patents page --- .../modules/patents/patents.component.html | 56 ++------ .../modules/patents/patents.component.scss | 128 +----------------- .../app/modules/patents/patents.component.ts | 66 +-------- 3 files changed, 12 insertions(+), 238 deletions(-) diff --git a/webapp/src/app/modules/patents/patents.component.html b/webapp/src/app/modules/patents/patents.component.html index a030c35c..76bac5ac 100644 --- a/webapp/src/app/modules/patents/patents.component.html +++ b/webapp/src/app/modules/patents/patents.component.html @@ -26,54 +26,14 @@ USPTO -
-
- Zeitraum - - - {{ selectedStartYear }} bis {{ selectedEndYear }} - - - -
- -
-
- - -
- -
- {{ minYear }} - {{ maxYear }} -
-
+
diff --git a/webapp/src/app/modules/patents/patents.component.scss b/webapp/src/app/modules/patents/patents.component.scss index c60cb02b..67227c82 100644 --- a/webapp/src/app/modules/patents/patents.component.scss +++ b/webapp/src/app/modules/patents/patents.component.scss @@ -32,134 +32,8 @@ h1 { border-radius: var(--sg-radius-sm); } -.year-filter { +.patent-year-filter { width: min(285px, 100%); - padding: 5px 10px; - border: 1px solid var(--sg-border); - border-radius: 10px; - background: var(--sg-surface-muted); - box-sizing: border-box; -} - -.year-filter-top { - display: flex; - align-items: center; - justify-content: space-between; - gap: 10px; - margin-bottom: 4px; -} - -.year-filter-label { - color: var(--sg-text); - font-size: 12px; - font-weight: 700; -} - -.reset-range-button { - border: 0; - background: transparent; - color: var(--sg-blue-highlight); - font-size: 11px; - cursor: pointer; - padding: 0; - font-family: inherit; - - &:disabled { - color: var(--sg-text-soft); - cursor: default; - } -} - -.year-filter-values { - color: var(--sg-text-muted); - font-size: 12px; - font-weight: 600; - white-space: nowrap; -} - -.year-filter-bounds { - display: flex; - justify-content: space-between; - margin-top: 0; - color: var(--sg-text-soft); - font-size: 10px; -} - -.year-range-slider { - --range-start: 0%; - --range-end: 100%; - --accent: var(--sg-blue-highlight); - - position: relative; - height: 16px; -} - -.range-track { - position: absolute; - top: 50%; - left: 0; - right: 0; - height: 5px; - transform: translateY(-50%); - border-radius: 999px; - background: linear-gradient( - to right, - var(--sg-border) 0%, - var(--sg-border) var(--range-start), - var(--accent) var(--range-start), - var(--accent) var(--range-end), - var(--sg-border) var(--range-end), - var(--sg-border) 100% - ); -} - -.range-input { - position: absolute; - inset: 0; - width: 100%; - height: 22px; - margin: 0; - appearance: none; - background: transparent; - pointer-events: none; - - &::-webkit-slider-runnable-track, - &::-moz-range-track { - height: 5px; - background: transparent; - border: none; - } - - &::-webkit-slider-thumb { - appearance: none; - width: 15px; - height: 15px; - margin-top: -5px; - border: 2px solid var(--sg-surface); - border-radius: 50%; - background: var(--sg-blue-highlight); - box-shadow: var(--sg-shadow-sm); - cursor: pointer; - pointer-events: auto; - } - - &::-moz-range-thumb { - width: 15px; - height: 15px; - border: 2px solid var(--sg-surface); - border-radius: 50%; - background: var(--sg-blue-highlight); - box-shadow: var(--sg-shadow-sm); - cursor: pointer; - pointer-events: auto; - } -} - -.range-input-start { - z-index: 2; -} -.range-input-end { - z-index: 3; } .state-message { diff --git a/webapp/src/app/modules/patents/patents.component.ts b/webapp/src/app/modules/patents/patents.component.ts index 3eb7e479..abd3d722 100644 --- a/webapp/src/app/modules/patents/patents.component.ts +++ b/webapp/src/app/modules/patents/patents.component.ts @@ -17,6 +17,7 @@ import { IpcClassification } from '../../api'; import { OpenAlexTopicTag } from '../../api/model/openAlexTopicTag'; import { TopicChipComponent } from '../../shared/ui/topic-chip/topic-chip.component'; import { LoadingComponent } from '../../shared/ui/loading/loading.component'; +import { YearRangeSliderComponent } from '../../shared/ui/year-range-slider/year-range-slider.component'; import { classificationSectionColor, topicHierarchyColor, @@ -54,6 +55,7 @@ const MIN_YEAR = 1978; MatDividerModule, TopicChipComponent, LoadingComponent, + YearRangeSliderComponent, ], templateUrl: './patents.component.html', styleUrl: './patents.component.scss', @@ -117,69 +119,7 @@ export class PatentsComponent implements OnInit { this.loadPatents(); } - get rangeStartPercent(): string { - const total = this.maxYear - this.minYear; - return `${((this.selectedStartYear - this.minYear) / total) * 100}%`; - } - - get rangeEndPercent(): string { - const total = this.maxYear - this.minYear; - return `${((this.selectedEndYear - this.minYear) / total) * 100}%`; - } - - get canResetYearRange(): boolean { - return ( - this.selectedStartYear !== this.minYear || - this.selectedEndYear !== this.maxYear - ); - } - - // Fired continuously while dragging: only updates the displayed value/handle - // position, no HTTP request yet. - onStartYearDrag(event: Event): void { - const input = event.target as HTMLInputElement; - this.selectedStartYear = Math.min( - parseInt(input.value, 10), - this.selectedEndYear, - ); - } - - onEndYearDrag(event: Event): void { - const input = event.target as HTMLInputElement; - this.selectedEndYear = Math.max( - parseInt(input.value, 10), - this.selectedStartYear, - ); - } - - // Fired once on release: commits the value and triggers the search request. - onStartYearInput(event: Event): void { - const input = event.target as HTMLInputElement; - this.selectedStartYear = Math.min( - parseInt(input.value, 10), - this.selectedEndYear, - ); - input.value = String(this.selectedStartYear); - this.page = 0; - this.loadPatents(); - this.updateQueryParams(); - } - - onEndYearInput(event: Event): void { - const input = event.target as HTMLInputElement; - this.selectedEndYear = Math.max( - parseInt(input.value, 10), - this.selectedStartYear, - ); - input.value = String(this.selectedEndYear); - this.page = 0; - this.loadPatents(); - this.updateQueryParams(); - } - - resetYearRange(): void { - this.selectedStartYear = this.minYear; - this.selectedEndYear = this.maxYear; + onYearRangeChange(): void { this.page = 0; this.loadPatents(); this.updateQueryParams(); From cea32deba2f8a57773738c71d8fc0f88c05bc153 Mon Sep 17 00:00:00 2001 From: louis-19041904 Date: Mon, 3 Aug 2026 22:23:36 +0200 Subject: [PATCH 027/114] use shared year-range-slider component in news page --- .../src/app/modules/news/news.component.html | 30 +++--------- .../src/app/modules/news/news.component.scss | 49 +------------------ webapp/src/app/modules/news/news.component.ts | 14 +----- 3 files changed, 11 insertions(+), 82 deletions(-) diff --git a/webapp/src/app/modules/news/news.component.html b/webapp/src/app/modules/news/news.component.html index 7db1c785..0c7d74d7 100644 --- a/webapp/src/app/modules/news/news.component.html +++ b/webapp/src/app/modules/news/news.component.html @@ -28,28 +28,14 @@ -
-
- Datum - - {{ yearFrom.value }} – {{ yearTo.value }} - -
- - - - -
- - +
diff --git a/webapp/src/app/modules/news/news.component.scss b/webapp/src/app/modules/news/news.component.scss index 94f2534b..0e90d177 100644 --- a/webapp/src/app/modules/news/news.component.scss +++ b/webapp/src/app/modules/news/news.component.scss @@ -57,54 +57,7 @@ } .year-field { - display: flex; - flex-direction: column; - justify-content: center; - min-width: 220px; - padding: 0 6px; - margin-top: -20px; -} - -.year-field__head { - display: flex; - align-items: baseline; - justify-content: space-between; - gap: 10px; - font-size: 12px; - margin-bottom: 20px; -} - -.year-field__label { - color: var(--sg-text-muted); - font-weight: 600; -} - -.year-field__range { - color: var(--sg-text); - font-weight: 600; - white-space: nowrap; -} - -.year-field mat-slider { - width: 100%; - margin: 0; -} - -.reset-filter-btn { - min-width: 132px; - height: 42px; - padding: 0 14px; - border: 1px solid var(--sg-border); - border-radius: var(--sg-radius-sm); - color: var(--sg-text); - background: var(--sg-surface); - - mat-icon { - margin-right: 6px; - width: 20px; - height: 20px; - font-size: 20px; - } + min-width: 280px; } @media (max-width: 600px) { diff --git a/webapp/src/app/modules/news/news.component.ts b/webapp/src/app/modules/news/news.component.ts index f1072f5d..9d916390 100644 --- a/webapp/src/app/modules/news/news.component.ts +++ b/webapp/src/app/modules/news/news.component.ts @@ -13,9 +13,6 @@ import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; import { debounceTime, merge } from 'rxjs'; import { MatFormFieldModule } from '@angular/material/form-field'; import { MatSelectModule } from '@angular/material/select'; -import { MatSliderModule } from '@angular/material/slider'; -import { MatButtonModule } from '@angular/material/button'; -import { MatIconModule } from '@angular/material/icon'; import { WorksService } from '../../api'; import { @@ -28,6 +25,7 @@ import { NEWS_MIN_YEAR, } from '../../shared/ui/news-card/news-card.component'; import { SelectorOption } from '../../shared/ui/query-param-selector/query-param-selector.component'; +import { YearRangeSliderComponent } from '../../shared/ui/year-range-slider/year-range-slider.component'; interface NewsArticle extends NewsArticleBase { author?: string | null; @@ -49,11 +47,9 @@ type SortOrder = 'desc' | 'asc'; ReactiveFormsModule, MatFormFieldModule, MatSelectModule, - MatSliderModule, - MatButtonModule, - MatIconModule, CardSearchComponent, NewsCardComponent, + YearRangeSliderComponent, ], templateUrl: './news.component.html', styleUrl: './news.component.scss', @@ -138,12 +134,6 @@ export class NewsComponent implements OnInit { .subscribe(() => this.applyFilters()); } - resetFilters(): void { - this.relevanceFilter.setValue([]); - this.yearFrom.setValue(this.minYear); - this.yearTo.setValue(this.maxYear); - } - private applyFilters(): void { const relevance = this.relevanceFilter.value.length > 0 From 8035e7aecb5a531134a89a94660370e7919340ef Mon Sep 17 00:00:00 2001 From: louis-19041904 Date: Mon, 3 Aug 2026 22:54:15 +0200 Subject: [PATCH 028/114] add career-stage-chip component --- .../career-stage-chip.component.html | 16 +++++++ .../career-stage-chip.component.scss | 45 +++++++++++++++++++ .../career-stage-chip.component.ts | 45 +++++++++++++++++++ 3 files changed, 106 insertions(+) create mode 100644 webapp/src/app/shared/ui/career-stage-chip/career-stage-chip.component.html create mode 100644 webapp/src/app/shared/ui/career-stage-chip/career-stage-chip.component.scss create mode 100644 webapp/src/app/shared/ui/career-stage-chip/career-stage-chip.component.ts diff --git a/webapp/src/app/shared/ui/career-stage-chip/career-stage-chip.component.html b/webapp/src/app/shared/ui/career-stage-chip/career-stage-chip.component.html new file mode 100644 index 00000000..68043006 --- /dev/null +++ b/webapp/src/app/shared/ui/career-stage-chip/career-stage-chip.component.html @@ -0,0 +1,16 @@ +@if (normalizedStage(); as stage) { +
+ Career Stage: + + {{ stage }} + +
+} diff --git a/webapp/src/app/shared/ui/career-stage-chip/career-stage-chip.component.scss b/webapp/src/app/shared/ui/career-stage-chip/career-stage-chip.component.scss new file mode 100644 index 00000000..f2447d79 --- /dev/null +++ b/webapp/src/app/shared/ui/career-stage-chip/career-stage-chip.component.scss @@ -0,0 +1,45 @@ +.career-stage-line { + display: flex; + align-items: center; + gap: 8px; + color: var(--sg-text-muted); + font-size: 13px; + + &--sm { + gap: 6px; + margin-top: 6px; + font-size: 10px; + min-height: 18px; + } +} + +.career-stage-label { + color: var(--sg-text-muted); + flex-shrink: 0; +} + +.career-stage-chip { + display: inline-flex; + align-items: center; + min-height: 24px; + padding: 2px 10px; + border: 1px solid var(--sg-border); + border-radius: 999px; + background: var(--sg-surface-muted); + color: var(--sg-primary); + font-size: 13px; + font-weight: 600; + line-height: 1.2; + cursor: help; + + &--sm { + min-height: 0; + min-width: 0; + max-width: 100%; + padding: 2px 8px; + font-size: 10px; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + } +} diff --git a/webapp/src/app/shared/ui/career-stage-chip/career-stage-chip.component.ts b/webapp/src/app/shared/ui/career-stage-chip/career-stage-chip.component.ts new file mode 100644 index 00000000..fd3357c2 --- /dev/null +++ b/webapp/src/app/shared/ui/career-stage-chip/career-stage-chip.component.ts @@ -0,0 +1,45 @@ +import { Component, computed, input } from '@angular/core'; +import { MatTooltipModule } from '@angular/material/tooltip'; + +@Component({ + selector: 'app-career-stage-chip', + standalone: true, + imports: [MatTooltipModule], + templateUrl: './career-stage-chip.component.html', + styleUrl: './career-stage-chip.component.scss', +}) +export class CareerStageChipComponent { + readonly careerStage = input(null); + readonly activeYears = input(null); + readonly size = input<'sm' | 'md'>('md'); + + readonly normalizedStage = computed(() => { + const stage = this.careerStage(); + if (!stage || stage === 'unknown') { + return null; + } + return stage; + }); + + readonly tooltip = computed(() => { + const stage = this.normalizedStage(); + if (!stage) { + return ''; + } + + const activeYears = this.activeYears() ?? '-'; + + return [ + `Aktuell: ${stage.replace(' Researcher', '')}`, + `Aktive Publikationsjahre: ${activeYears}`, + '', + 'Einteilung:', + 'Early: 1–4 aktive Publikationsjahre', + 'Emerging: 5–9 aktive Publikationsjahre', + 'Established: 10–14 aktive Publikationsjahre', + 'Senior: ab 15 aktiven Publikationsjahren', + '', + 'Diese Einschätzung basiert ausschließlich auf OpenAlex-Publikationsdaten und ist kein offizieller akademischer Status.', + ].join('\n'); + }); +} From 1f09f0cf68c03e7b84386f4320691a5da16decfe Mon Sep 17 00:00:00 2001 From: louis-19041904 Date: Mon, 3 Aug 2026 22:55:07 +0200 Subject: [PATCH 029/114] use career-stage-chip component in person card --- .../person-card/person-card.component.html | 17 +++------- .../person-card/person-card.component.scss | 33 ------------------- .../person-card/person-card.component.ts | 29 ++-------------- 3 files changed, 6 insertions(+), 73 deletions(-) diff --git a/webapp/src/app/modules/person-card/person-card.component.html b/webapp/src/app/modules/person-card/person-card.component.html index e5e1d0b2..67cf3832 100644 --- a/webapp/src/app/modules/person-card/person-card.component.html +++ b/webapp/src/app/modules/person-card/person-card.component.html @@ -40,19 +40,10 @@ {{ hIndexString() }}

@if (!loading()) { - @if (careerStage(); as careerStage) { -
- Career Stage: - - {{ careerStage }} - -
- } + } diff --git a/webapp/src/app/modules/person-card/person-card.component.scss b/webapp/src/app/modules/person-card/person-card.component.scss index 1b8b015a..fb46ab44 100644 --- a/webapp/src/app/modules/person-card/person-card.component.scss +++ b/webapp/src/app/modules/person-card/person-card.component.scss @@ -264,39 +264,6 @@ white-space: nowrap; } -.career-stage-line { - display: flex; - align-items: center; - gap: 6px; - margin-top: 6px; - color: var(--sg-text-muted); - font-size: 10px; - min-height: 18px; -} - -.career-stage-label { - flex-shrink: 0; -} - -.career-stage-chip { - display: inline-flex; - align-items: center; - min-width: 0; - max-width: 100%; - padding: 2px 8px; - border: 1px solid var(--sg-border); - border-radius: 999px; - background: var(--sg-surface-muted); - color: var(--sg-primary); - font-size: 10px; - font-weight: 600; - line-height: 1.2; - overflow: hidden; - text-overflow: ellipsis; - white-space: nowrap; - cursor: help; -} - .card-body { padding: 16px; flex-grow: 1; diff --git a/webapp/src/app/modules/person-card/person-card.component.ts b/webapp/src/app/modules/person-card/person-card.component.ts index 89cc4362..eea6f571 100644 --- a/webapp/src/app/modules/person-card/person-card.component.ts +++ b/webapp/src/app/modules/person-card/person-card.component.ts @@ -7,6 +7,7 @@ import { CustomAuthor, DehydratedInstitution, WorkTopic } from '../../api'; import { SkTextDirective } from '../../custom-directives/sk-text.directive'; import { TopicChipComponent } from '../../shared/ui/topic-chip/topic-chip.component'; import { CountryFlagComponent } from '../../shared/ui/country-flag/country-flag.component'; +import { CareerStageChipComponent } from '../../shared/ui/career-stage-chip/career-stage-chip.component'; import { topicHierarchyColor } from '../../resolvers/utils/topic-colors'; @Component({ @@ -20,6 +21,7 @@ import { topicHierarchyColor } from '../../resolvers/utils/topic-colors'; MatTooltipModule, TopicChipComponent, CountryFlagComponent, + CareerStageChipComponent, ], templateUrl: './person-card.component.html', styleUrl: './person-card.component.scss', @@ -128,16 +130,6 @@ export class PersonCardComponent { return ''; }); - careerStage = computed(() => { - const stage = this.person().career_metrics?.career_stage; - - if (!stage || stage === 'unknown') { - return null; - } - - return stage; - }); - getRatingClass(rating: string | null | undefined): string { const r = (rating || '').toLowerCase(); if (r === 'sehr geeignet') return 'very-suitable'; @@ -174,23 +166,6 @@ export class PersonCardComponent { return id.replace('https://openalex.org/', '').trim().toUpperCase(); } - getCareerStageTooltip(careerStage: string): string { - const activeYears = this.person().career_metrics?.active_years ?? '-'; - - return [ - `Aktuell: ${careerStage.replace(' Researcher', '')}`, - `Aktive Publikationsjahre: ${activeYears}`, - '', - 'Einteilung:', - 'Early: 1-4 aktive Publikationsjahre', - 'Emerging: 5-9 aktive Publikationsjahre', - 'Established: 10-14 aktive Publikationsjahre', - 'Senior: ab 15 aktiven Publikationsjahren', - '', - 'Diese Einschätzung basiert ausschließlich auf OpenAlex-Publikationsdaten und ist kein offizieller akademischer Status.', - ].join('\n'); - } - toggleBookmark(): void { this.bookmarkToggle.emit(this.person()); } From 90149ddb4e5867d6dd09c07f21c256cc65e369f8 Mon Sep 17 00:00:00 2001 From: louis-19041904 Date: Mon, 3 Aug 2026 22:57:29 +0200 Subject: [PATCH 030/114] use career-stage-chip component in person profile --- .../app/modules/person/person.component.html | 16 +++-------- .../app/modules/person/person.component.scss | 27 ------------------- .../app/modules/person/person.component.ts | 23 ++-------------- 3 files changed, 5 insertions(+), 61 deletions(-) diff --git a/webapp/src/app/modules/person/person.component.html b/webapp/src/app/modules/person/person.component.html index 173406d8..362af283 100644 --- a/webapp/src/app/modules/person/person.component.html +++ b/webapp/src/app/modules/person/person.component.html @@ -93,19 +93,9 @@ } @if (displayCareerStage() || orcid()) {
- @if (displayCareerStage()) { -
- Career Stage: - - {{ displayCareerStage() }} - -
- } + @if (orcid(); as orcidId) { { - const stage = this.displayCareerStage(); - if (!stage) { - return ''; - } - - const activeYears = this.person()?.career_metrics?.active_years ?? '-'; - - return [ - `Aktuell: ${stage.replace(' Researcher', '')}`, - `Aktive Publikationsjahre: ${activeYears}`, - '', - 'Einteilung:', - 'Early: 1\u20134 aktive Publikationsjahre', - 'Emerging: 5\u20139 aktive Publikationsjahre', - 'Established: 10\u201314 aktive Publikationsjahre', - 'Senior: ab 15 aktiven Publikationsjahren', - '', - 'Diese Einschätzung basiert ausschließlich auf OpenAlex-Publikationsdaten und ist kein offizieller akademischer Status.', - ].join('\n'); - }); readonly orcid = computed(() => { const rawOrcid = this.getId('orcid'); if (!rawOrcid) { From b4a90131bb1338c99bb25ad3c4e3ca20678e8e08 Mon Sep 17 00:00:00 2001 From: louis-19041904 Date: Mon, 3 Aug 2026 23:01:22 +0200 Subject: [PATCH 031/114] remove preprocessing-mock-backup template --- .../preprocessing.component.html | 204 ------------------ 1 file changed, 204 deletions(-) delete mode 100644 webapp/src/app/modules/preprocessing-mock-backup/preprocessing.component.html diff --git a/webapp/src/app/modules/preprocessing-mock-backup/preprocessing.component.html b/webapp/src/app/modules/preprocessing-mock-backup/preprocessing.component.html deleted file mode 100644 index b13eb6f3..00000000 --- a/webapp/src/app/modules/preprocessing-mock-backup/preprocessing.component.html +++ /dev/null @@ -1,204 +0,0 @@ -
- - - - -
- - -
- {{ containerStatus().name }} -
- {{ containerStatus().image }} - {{ - containerStatus().imageDigest - }} - @switch (containerStatus().state) { - @case ('running') { - Läuft{{ - containerStatus().uptime - ? ' · seit ' + containerStatus().uptime - : '' - }} - } - @case ('stopped') { - Gestoppt - } - @case ('restarting') { - Wird neu gestartet … - } - } - @if (containerStatus().updateAvailable) { - - upgrade - Neue Version verfügbar - - } -
-
-
- -
- @if (containerStatus().updateAvailable) { - - } - @if (containerStatus().state === 'running') { - - - } @else { - - } -
-
-
- - - - - - -
- - -
- {{ row.name }} - {{ row.description }} - {{ row.targetIndex }} -
-
- - -
- {{ formatSchedule(row.schedule) }} - -
-
- - - @switch (row.status) { - @case ('running') { - - - Läuft - - } - @case ('success') { - - check_circle - Erfolgreich - - } - @case ('failed') { - - error - Fehlgeschlagen - - } - @default { - - schedule - Bereit - - } - } - - - - @if (row.lastRun) { -
- {{ row.lastRun.startedAt | date: 'dd.MM.yyyy HH:mm' }} - {{ row.lastRun.message }} -
- } @else { - Noch nicht ausgeführt - } -
- - -
- - -
-
From 340b5f22b7487346351ce65a9fd78e490a019db7 Mon Sep 17 00:00:00 2001 From: louis-19041904 Date: Tue, 4 Aug 2026 07:44:22 +0200 Subject: [PATCH 032/114] use app-loading component in several pages --- .../bookmarks/bookmarks.component.html | 9 ++++---- .../bookmarks/bookmarks.component.scss | 1 - .../modules/bookmarks/bookmarks.component.ts | 9 ++------ .../job-logs-dialog.component.html | 22 +++++++++---------- .../job-logs-dialog.component.scss | 20 ----------------- .../job-logs-dialog.component.ts | 4 ++-- .../news-detail/news-detail.component.html | 9 ++++---- .../news-detail/news-detail.component.ts | 4 ++-- .../patent-detail.component.html | 9 ++++---- .../patent-detail/patent-detail.component.ts | 4 ++-- .../person-company-connections.component.html | 9 ++++---- .../person-company-connections.component.ts | 4 ++-- .../person-interesting.component.html | 9 +++++--- .../person-interesting.component.scss | 22 ------------------- .../person-interesting.component.ts | 4 ++-- .../publication-detail.component.html | 9 ++++---- .../publication-detail.component.ts | 4 ++-- .../topic-hierarchy.component.html | 9 ++++---- .../topic-hierarchy.component.scss | 10 --------- .../topic-hierarchy.component.ts | 4 ++-- 20 files changed, 62 insertions(+), 113 deletions(-) diff --git a/webapp/src/app/modules/bookmarks/bookmarks.component.html b/webapp/src/app/modules/bookmarks/bookmarks.component.html index 76f61397..756e6203 100644 --- a/webapp/src/app/modules/bookmarks/bookmarks.component.html +++ b/webapp/src/app/modules/bookmarks/bookmarks.component.html @@ -13,10 +13,11 @@ @if (loading()) { -
- -

Bookmarks werden geladen …

-
+ } @else if (persons().length) {
@for (person of persons(); track person.id) { diff --git a/webapp/src/app/modules/bookmarks/bookmarks.component.scss b/webapp/src/app/modules/bookmarks/bookmarks.component.scss index 1f6b9dc1..87f7f20e 100644 --- a/webapp/src/app/modules/bookmarks/bookmarks.component.scss +++ b/webapp/src/app/modules/bookmarks/bookmarks.component.scss @@ -65,7 +65,6 @@ gap: 20px; } -.loading-state, .empty-state { display: flex; min-height: 320px; diff --git a/webapp/src/app/modules/bookmarks/bookmarks.component.ts b/webapp/src/app/modules/bookmarks/bookmarks.component.ts index c9c9e46e..2192e77b 100644 --- a/webapp/src/app/modules/bookmarks/bookmarks.component.ts +++ b/webapp/src/app/modules/bookmarks/bookmarks.component.ts @@ -2,12 +2,12 @@ import { CommonModule } from '@angular/common'; import { Component, DestroyRef, inject, signal } from '@angular/core'; import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; import { MatIconModule } from '@angular/material/icon'; -import { MatProgressSpinnerModule } from '@angular/material/progress-spinner'; import { catchError, forkJoin, map, of, switchMap } from 'rxjs'; import { CustomAuthor, PersonsService } from '../../api'; import { BookmarkService } from '../../shared/services/bookmark.service'; import { PersonCardComponent } from '../person-card/person-card.component'; +import { LoadingComponent } from '../../shared/ui/loading/loading.component'; const PERSON_INCLUDE_TAGS = 'display_name,works_count,cited_by_count,summary_stats,ids,' + @@ -17,12 +17,7 @@ const PERSON_INCLUDE_TAGS = @Component({ selector: 'app-bookmarks', standalone: true, - imports: [ - CommonModule, - MatIconModule, - MatProgressSpinnerModule, - PersonCardComponent, - ], + imports: [CommonModule, MatIconModule, PersonCardComponent, LoadingComponent], templateUrl: './bookmarks.component.html', styleUrl: './bookmarks.component.scss', }) diff --git a/webapp/src/app/modules/jobs/job-logs-dialog/job-logs-dialog.component.html b/webapp/src/app/modules/jobs/job-logs-dialog/job-logs-dialog.component.html index 13917cdf..f6510c90 100644 --- a/webapp/src/app/modules/jobs/job-logs-dialog/job-logs-dialog.component.html +++ b/webapp/src/app/modules/jobs/job-logs-dialog/job-logs-dialog.component.html @@ -2,12 +2,11 @@ @if (runsLoading() && runs().length === 0) { -
- - Läufe werden geladen … -
+ } @else if (runsError()) {

{{ runsError() }}

} @else if (runs().length === 0) { @@ -79,12 +78,11 @@
@if (loading() && !logs()) { -
- - Logs werden geladen … -
+ } @else {
{{ logs() }}
} diff --git a/webapp/src/app/modules/jobs/job-logs-dialog/job-logs-dialog.component.scss b/webapp/src/app/modules/jobs/job-logs-dialog/job-logs-dialog.component.scss index 18ae63d9..c358a766 100644 --- a/webapp/src/app/modules/jobs/job-logs-dialog/job-logs-dialog.component.scss +++ b/webapp/src/app/modules/jobs/job-logs-dialog/job-logs-dialog.component.scss @@ -3,14 +3,6 @@ margin: 0; } -.runs-loading { - display: flex; - align-items: center; - gap: 10px; - min-height: 120px; - color: var(--sg-text-muted); -} - .logs-error { margin: 0; padding: 16px; @@ -93,18 +85,6 @@ white-space: pre-wrap; word-break: break-word; } - - .logs-loading { - color: var(--sg-text-muted); - } -} - -.logs-loading { - display: flex; - align-items: center; - gap: 10px; - color: var(--sg-text-muted); - font-size: 13px; } .run-select { diff --git a/webapp/src/app/modules/jobs/job-logs-dialog/job-logs-dialog.component.ts b/webapp/src/app/modules/jobs/job-logs-dialog/job-logs-dialog.component.ts index 3828598b..fd208fbe 100644 --- a/webapp/src/app/modules/jobs/job-logs-dialog/job-logs-dialog.component.ts +++ b/webapp/src/app/modules/jobs/job-logs-dialog/job-logs-dialog.component.ts @@ -18,11 +18,11 @@ import { } from '@angular/material/dialog'; import { MatFormFieldModule } from '@angular/material/form-field'; import { MatIconModule } from '@angular/material/icon'; -import { MatProgressSpinnerModule } from '@angular/material/progress-spinner'; import { MatSelectModule } from '@angular/material/select'; import { MatTooltipModule } from '@angular/material/tooltip'; import { finalize, timer } from 'rxjs'; import { BackgroundJobsService, BackgroundJobTask, JobRun } from '../../../api'; +import { LoadingComponent } from '../../../shared/ui/loading/loading.component'; import { formatRunDuration, formatRunElapsed, @@ -42,9 +42,9 @@ export interface JobLogsDialogData { MatDialogModule, MatFormFieldModule, MatIconModule, - MatProgressSpinnerModule, MatSelectModule, MatTooltipModule, + LoadingComponent, ], templateUrl: './job-logs-dialog.component.html', styleUrl: './job-logs-dialog.component.scss', diff --git a/webapp/src/app/modules/news-detail/news-detail.component.html b/webapp/src/app/modules/news-detail/news-detail.component.html index 4580694d..4f7a14b7 100644 --- a/webapp/src/app/modules/news-detail/news-detail.component.html +++ b/webapp/src/app/modules/news-detail/news-detail.component.html @@ -9,10 +9,11 @@ @if (loading) { -
- -

Nachricht wird geladen...

-
+ } @else if (notFound || !article) {
search_off diff --git a/webapp/src/app/modules/news-detail/news-detail.component.ts b/webapp/src/app/modules/news-detail/news-detail.component.ts index aa495516..707f191f 100644 --- a/webapp/src/app/modules/news-detail/news-detail.component.ts +++ b/webapp/src/app/modules/news-detail/news-detail.component.ts @@ -11,13 +11,13 @@ import { HttpClient } from '@angular/common/http'; import { ActivatedRoute, Router, RouterLink } from '@angular/router'; import { MatButtonModule } from '@angular/material/button'; import { MatIconModule } from '@angular/material/icon'; -import { MatProgressSpinnerModule } from '@angular/material/progress-spinner'; import { MatTooltipModule } from '@angular/material/tooltip'; import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; import { DomSanitizer, SafeHtml } from '@angular/platform-browser'; import { WorksService } from '../../api'; import { topicHierarchyColor } from '../../resolvers/utils/topic-colors'; +import { LoadingComponent } from '../../shared/ui/loading/loading.component'; interface MentionedPerson { name: string; @@ -52,9 +52,9 @@ interface NewsArticleDetail { imports: [ MatButtonModule, MatIconModule, - MatProgressSpinnerModule, MatTooltipModule, RouterLink, + LoadingComponent, ], templateUrl: './news-detail.component.html', styleUrl: './news-detail.component.scss', diff --git a/webapp/src/app/modules/patent-detail/patent-detail.component.html b/webapp/src/app/modules/patent-detail/patent-detail.component.html index 639e160d..3ab15299 100644 --- a/webapp/src/app/modules/patent-detail/patent-detail.component.html +++ b/webapp/src/app/modules/patent-detail/patent-detail.component.html @@ -9,10 +9,11 @@ @if (loading) { -
- -

Patent wird geladen...

-
+ } @else if (notFound || !patent) {
search_off diff --git a/webapp/src/app/modules/patent-detail/patent-detail.component.ts b/webapp/src/app/modules/patent-detail/patent-detail.component.ts index 18816a39..3355e8fd 100644 --- a/webapp/src/app/modules/patent-detail/patent-detail.component.ts +++ b/webapp/src/app/modules/patent-detail/patent-detail.component.ts @@ -3,7 +3,6 @@ import { Component, DestroyRef, OnInit, inject } from '@angular/core'; import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; import { MatButtonModule } from '@angular/material/button'; import { MatIconModule } from '@angular/material/icon'; -import { MatProgressSpinnerModule } from '@angular/material/progress-spinner'; import { ActivatedRoute, RouterLink } from '@angular/router'; import { finalize } from 'rxjs'; @@ -15,6 +14,7 @@ import { classificationSectionColor, topicHierarchyColor, } from '../../resolvers/utils/topic-colors'; +import { LoadingComponent } from '../../shared/ui/loading/loading.component'; import { ClassificationCard, ClassificationSystem, @@ -32,9 +32,9 @@ import { imports: [ MatButtonModule, MatIconModule, - MatProgressSpinnerModule, RouterLink, TopicChipComponent, + LoadingComponent, ], templateUrl: './patent-detail.component.html', styleUrl: './patent-detail.component.scss', diff --git a/webapp/src/app/modules/person-company-connections/person-company-connections.component.html b/webapp/src/app/modules/person-company-connections/person-company-connections.component.html index 7526b3db..5bf24c01 100644 --- a/webapp/src/app/modules/person-company-connections/person-company-connections.component.html +++ b/webapp/src/app/modules/person-company-connections/person-company-connections.component.html @@ -1,8 +1,9 @@ @if (loading) { -
- - Verbindungen zu Unternehmen werden geladen ... -
+ } @else if (error) {
Verbindungen zu Unternehmen konnten nicht geladen werden. diff --git a/webapp/src/app/modules/person-company-connections/person-company-connections.component.ts b/webapp/src/app/modules/person-company-connections/person-company-connections.component.ts index c1db293b..e8e15636 100644 --- a/webapp/src/app/modules/person-company-connections/person-company-connections.component.ts +++ b/webapp/src/app/modules/person-company-connections/person-company-connections.component.ts @@ -14,7 +14,6 @@ import { MatButtonModule } from '@angular/material/button'; import { MatCardModule } from '@angular/material/card'; import { MatIconModule } from '@angular/material/icon'; import { MatTooltip, MatTooltipModule } from '@angular/material/tooltip'; -import { MatProgressSpinnerModule } from '@angular/material/progress-spinner'; import { ActivatedRoute, Router, RouterModule } from '@angular/router'; import { EChartsOption } from 'echarts'; import { NgxEchartsDirective } from 'ngx-echarts'; @@ -27,6 +26,7 @@ import { } from '../../api'; import { PersonDataResolved } from '../../resolvers/person.resolver'; import { ChartThemeService } from '../../shared/services/chart-theme.service'; +import { LoadingComponent } from '../../shared/ui/loading/loading.component'; interface RoleLegendItem { role: string; @@ -44,7 +44,6 @@ interface GraphSymbols { selector: 'app-person-company-connections', imports: [ CommonModule, - MatProgressSpinnerModule, NgxEchartsDirective, MatButtonModule, MatCardModule, @@ -52,6 +51,7 @@ interface GraphSymbols { MatTooltipModule, MatTooltip, RouterModule, + LoadingComponent, ], templateUrl: './person-company-connections.component.html', styleUrl: './person-company-connections.component.scss', diff --git a/webapp/src/app/modules/person-interesting/person-interesting.component.html b/webapp/src/app/modules/person-interesting/person-interesting.component.html index 3a30b7bd..cb8215f7 100644 --- a/webapp/src/app/modules/person-interesting/person-interesting.component.html +++ b/webapp/src/app/modules/person-interesting/person-interesting.component.html @@ -24,9 +24,12 @@
@if (loading()) { -
- - Themen werden geladen ... +
+
} @else if (tags().length > 0) { @for (tag of tags(); track tag.label) { diff --git a/webapp/src/app/modules/person-interesting/person-interesting.component.scss b/webapp/src/app/modules/person-interesting/person-interesting.component.scss index c1c334c5..173d465c 100644 --- a/webapp/src/app/modules/person-interesting/person-interesting.component.scss +++ b/webapp/src/app/modules/person-interesting/person-interesting.component.scss @@ -58,25 +58,3 @@ font-size: 13px; font-weight: 600; } - -.interest-state { - display: flex; - width: 100%; - min-height: 90px; - align-items: center; - justify-content: center; - padding: 20px; - color: var(--sg-text-muted); - font-size: 14px; - text-align: center; -} - -.interest-card-loading .interest-state { - min-height: 48px; - padding: 8px; -} - -.interest-state-loading { - flex-direction: column; - gap: 10px; -} diff --git a/webapp/src/app/modules/person-interesting/person-interesting.component.ts b/webapp/src/app/modules/person-interesting/person-interesting.component.ts index 2d4dc1e3..ad3307bf 100644 --- a/webapp/src/app/modules/person-interesting/person-interesting.component.ts +++ b/webapp/src/app/modules/person-interesting/person-interesting.component.ts @@ -10,13 +10,13 @@ import { } from '@angular/core'; import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; import { MatIconModule } from '@angular/material/icon'; -import { MatProgressSpinnerModule } from '@angular/material/progress-spinner'; import { CommonModule } from '@angular/common'; import { ActivatedRoute, Router } from '@angular/router'; import { TopicCount } from '../../api'; import { TopicChipComponent } from '../../shared/ui/topic-chip/topic-chip.component'; import { TopicLegendComponent } from '../../shared/ui/topic-legend/topic-legend.component'; +import { LoadingComponent } from '../../shared/ui/loading/loading.component'; import { topicHierarchyColor } from '../../resolvers/utils/topic-colors'; import { buildTopicLegendGroups, @@ -52,9 +52,9 @@ const MAX_TAGS = 5; imports: [ CommonModule, MatIconModule, - MatProgressSpinnerModule, TopicChipComponent, TopicLegendComponent, + LoadingComponent, ], templateUrl: './person-interesting.component.html', styleUrl: './person-interesting.component.scss', diff --git a/webapp/src/app/modules/publication-detail/publication-detail.component.html b/webapp/src/app/modules/publication-detail/publication-detail.component.html index fed2db7d..6ffbe5c3 100644 --- a/webapp/src/app/modules/publication-detail/publication-detail.component.html +++ b/webapp/src/app/modules/publication-detail/publication-detail.component.html @@ -9,10 +9,11 @@ @if (loading) { -
- -

Publikation wird geladen...

-
+ } @else if (notFound || !publication) {
search_off diff --git a/webapp/src/app/modules/publication-detail/publication-detail.component.ts b/webapp/src/app/modules/publication-detail/publication-detail.component.ts index 51616f1a..f9c8f3e6 100644 --- a/webapp/src/app/modules/publication-detail/publication-detail.component.ts +++ b/webapp/src/app/modules/publication-detail/publication-detail.component.ts @@ -5,7 +5,6 @@ import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; import { HttpClient } from '@angular/common/http'; import { MatButtonModule } from '@angular/material/button'; import { MatIconModule } from '@angular/material/icon'; -import { MatProgressSpinnerModule } from '@angular/material/progress-spinner'; import { MatTooltipModule } from '@angular/material/tooltip'; import { ActivatedRoute, Router, RouterLink } from '@angular/router'; import { @@ -18,6 +17,7 @@ import { } from '../../api'; import { TopicChipComponent } from '../../shared/ui/topic-chip/topic-chip.component'; import { CountryFlagComponent } from '../../shared/ui/country-flag/country-flag.component'; +import { LoadingComponent } from '../../shared/ui/loading/loading.component'; import { topicHierarchyColor } from '../../resolvers/utils/topic-colors'; import { WorkTypePipe } from '../../shared/pipes/work-type.pipe'; import { LanguageCodePipe } from '../../shared/pipes/language-code.pipe'; @@ -43,7 +43,6 @@ interface InstitutionDetail { DecimalPipe, MatButtonModule, MatIconModule, - MatProgressSpinnerModule, MatTooltipModule, RouterLink, TopicChipComponent, @@ -52,6 +51,7 @@ interface InstitutionDetail { WorkPrimaryCategoryPipe, ResearchProfileComponent, CountryFlagComponent, + LoadingComponent, ], templateUrl: './publication-detail.component.html', styleUrl: './publication-detail.component.scss', diff --git a/webapp/src/app/modules/topic-hierarchy/topic-hierarchy.component.html b/webapp/src/app/modules/topic-hierarchy/topic-hierarchy.component.html index 3df414de..c8553b15 100644 --- a/webapp/src/app/modules/topic-hierarchy/topic-hierarchy.component.html +++ b/webapp/src/app/modules/topic-hierarchy/topic-hierarchy.component.html @@ -45,10 +45,11 @@
} @if (loading()) { -
- - Lade Themen... -
+ } @else { @if (searchQuery()) { diff --git a/webapp/src/app/modules/topic-hierarchy/topic-hierarchy.component.scss b/webapp/src/app/modules/topic-hierarchy/topic-hierarchy.component.scss index 24c8f08c..416e6a6b 100644 --- a/webapp/src/app/modules/topic-hierarchy/topic-hierarchy.component.scss +++ b/webapp/src/app/modules/topic-hierarchy/topic-hierarchy.component.scss @@ -11,16 +11,6 @@ box-sizing: border-box; } -.loading-state { - display: flex; - align-items: center; - justify-content: center; - gap: 8px; - padding: 16px; - color: var(--sg-text-muted); - font-size: 12px; -} - /* Flat Search Results Styles */ .search-results { display: flex; diff --git a/webapp/src/app/modules/topic-hierarchy/topic-hierarchy.component.ts b/webapp/src/app/modules/topic-hierarchy/topic-hierarchy.component.ts index f7bfc203..25949b3a 100644 --- a/webapp/src/app/modules/topic-hierarchy/topic-hierarchy.component.ts +++ b/webapp/src/app/modules/topic-hierarchy/topic-hierarchy.component.ts @@ -2,11 +2,11 @@ import { Component, input, model, output, OnInit, signal } from '@angular/core'; import { CommonModule } from '@angular/common'; import { MatCheckboxModule } from '@angular/material/checkbox'; import { MatIconModule } from '@angular/material/icon'; -import { MatProgressSpinnerModule } from '@angular/material/progress-spinner'; import { MatRadioModule } from '@angular/material/radio'; import { MatTooltipModule } from '@angular/material/tooltip'; import { TopicsService } from '../../api/api/topics.service'; import { topicHierarchyColor } from '../../resolvers/utils/topic-colors'; +import { LoadingComponent } from '../../shared/ui/loading/loading.component'; import { combineLatest, of } from 'rxjs'; import { toObservable } from '@angular/core/rxjs-interop'; import { @@ -50,9 +50,9 @@ interface FlatTopic { CommonModule, MatCheckboxModule, MatIconModule, - MatProgressSpinnerModule, MatRadioModule, MatTooltipModule, + LoadingComponent, ], templateUrl: './topic-hierarchy.component.html', styleUrl: './topic-hierarchy.component.scss', From ff43d07b6dd902d6d95aa267d0c2d42cb0e2cbd7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mats=20Paul=20Ton=C4=8Dik?= Date: Tue, 4 Aug 2026 08:22:12 +0200 Subject: [PATCH 033/114] fix(institution-card): removed project button for institutions other than one's own --- .../app-institution-card.component.html | 26 ++++++++++--------- .../app-institution-card.component.ts | 13 ++++++++++ 2 files changed, 27 insertions(+), 12 deletions(-) diff --git a/webapp/src/app/shared/ui/app-institution-card/app-institution-card.component.html b/webapp/src/app/shared/ui/app-institution-card/app-institution-card.component.html index 637356fa..49172464 100644 --- a/webapp/src/app/shared/ui/app-institution-card/app-institution-card.component.html +++ b/webapp/src/app/shared/ui/app-institution-card/app-institution-card.component.html @@ -65,18 +65,20 @@ menu_book Publikationen
- - work - Projekte - + @if (isOwnInstitution()) { + + work + Projekte + + } @if (hasPatents()) { (); @@ -43,6 +45,17 @@ export class AppInstitutionCardComponent { return 'Unbekannte Institution'; }); + isOwnInstitution = computed(() => { + const id = this.stripOpenAlexId(this.institution().id); + if (!id) return false; + + console.log( + `Comparing institution ID ${id} with effective institution ID ${this.credentialService.effectiveInstitutionId()}`, + ); + + return id === this.credentialService.effectiveInstitutionId(); + }); + // The "Patente" action only makes sense once org_patents has been indexed // for this institution (currently a manual, per-institution process), so // it's hidden by default and only shown once a cheap count check confirms From a407cfb514e05f6aa86b55dc9f3e743243a15186 Mon Sep 17 00:00:00 2001 From: louis-19041904 Date: Tue, 4 Aug 2026 08:37:52 +0200 Subject: [PATCH 034/114] center loading spinner in person interesting --- .../person-interesting/person-interesting.component.html | 2 +- .../person-interesting/person-interesting.component.scss | 6 ++++++ 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/webapp/src/app/modules/person-interesting/person-interesting.component.html b/webapp/src/app/modules/person-interesting/person-interesting.component.html index cb8215f7..5ac37496 100644 --- a/webapp/src/app/modules/person-interesting/person-interesting.component.html +++ b/webapp/src/app/modules/person-interesting/person-interesting.component.html @@ -24,7 +24,7 @@
@if (loading()) { -
+
Date: Tue, 4 Aug 2026 09:02:05 +0200 Subject: [PATCH 035/114] Added "funder" to Institution type list with fallbacklogic to default to "other" --- .../institutions_search_client.py | 1 + service/src/main/inse/institutions/logic.py | 1 + .../src/main/inse/institutions/test_logic.py | 31 +++++++++++++++++++ .../main/inse/models/openalex/institution.py | 7 +++-- 4 files changed, 37 insertions(+), 3 deletions(-) diff --git a/service/src/main/inse/institutions/institutions_search_client.py b/service/src/main/inse/institutions/institutions_search_client.py index 482194d9..7896a01d 100644 --- a/service/src/main/inse/institutions/institutions_search_client.py +++ b/service/src/main/inse/institutions/institutions_search_client.py @@ -361,6 +361,7 @@ class InstitutionsSearchClient: "government", "facility", "other", + "funder", } cleaned_source = {} diff --git a/service/src/main/inse/institutions/logic.py b/service/src/main/inse/institutions/logic.py index 9e7eeb2e..4437c6c9 100644 --- a/service/src/main/inse/institutions/logic.py +++ b/service/src/main/inse/institutions/logic.py @@ -33,6 +33,7 @@ _VALID_INSTITUTION_TYPES = { "government", "facility", "other", + "funder", } diff --git a/service/src/main/inse/institutions/test_logic.py b/service/src/main/inse/institutions/test_logic.py index cca61dc9..d19b6ba7 100644 --- a/service/src/main/inse/institutions/test_logic.py +++ b/service/src/main/inse/institutions/test_logic.py @@ -174,3 +174,34 @@ async def test_list_institutions_accepts_practical_openalex_type_variants(): assert result.results[0].counts_by_year[0].cited_by_count is None assert result.group_by[0].key == "true" + +@pytest.mark.anyio +async def test_list_institutions_accepts_funder_institution_type(): + def handler(_: httpx.Request) -> httpx.Response: + return httpx.Response( + 200, + json={ + "meta": {"count": 1, "page": 1, "per_page": 25}, + "results": [ + { + "id": "https://openalex.org/I4210119759", + "display_name": "Essen University Hospital", + "country_code": "DE", + "type": "funder", + } + ], + }, + ) + + client = OpenAlexInstitutionsClient( + api_key="test-key", + transport=httpx.MockTransport(handler), + ) + + result = await logic.list_institutions(client=client) + + assert result.results[0].id == "https://openalex.org/I4210119759" + assert result.results[0].display_name == "Essen University Hospital" + assert result.results[0].type == "funder" + + diff --git a/service/src/main/inse/models/openalex/institution.py b/service/src/main/inse/models/openalex/institution.py index deede4f7..089013ba 100644 --- a/service/src/main/inse/models/openalex/institution.py +++ b/service/src/main/inse/models/openalex/institution.py @@ -37,7 +37,7 @@ class Institution(BaseModel): ror: StrictStr | None = Field(default=None, description="The ROR ID for this institution. This is the Canonical External ID for institutions.") display_name: StrictStr | None = Field(default=None, description="The primary name of the institution.") country_code: StrictStr | None = Field(default=None, description="ISO two-letter country code where this institution is located.") - type: StrictStr | None = Field(default=None, description="The institution's primary type (ROR vocabulary): `Education`, `Healthcare`, `Company`, `Archive`, `Nonprofit`, `Government`, `Facility`, `Other`.") + type: StrictStr | None = Field(default=None, description="The institution's primary type (ROR vocabulary): `Education`, `Healthcare`, `Company`, `Archive`, `Nonprofit`, `Government`, `Facility`, `Other`, `Funder`.") homepage_url: StrictStr | None = Field(default=None, description="URL for the institution's primary homepage.") image_url: StrictStr | None = Field(default=None, description="URL for an image representing this institution (usually from Wikimedia).") image_thumbnail_url: StrictStr | None = Field(default=None, description="Smaller version of `image_url`.") @@ -61,8 +61,9 @@ class Institution(BaseModel): if value is None: return value - if value not in set(['education', 'healthcare', 'company', 'archive', 'nonprofit', 'government', 'facility', 'other']): - raise ValueError("must be one of enum values ('education', 'healthcare', 'company', 'archive', 'nonprofit', 'government', 'facility', 'other')") + valid_types = {'education', 'healthcare', 'company', 'archive', 'nonprofit', 'government', 'facility', 'other', 'funder'} + if value not in valid_types: + return 'other' return value model_config = ConfigDict( From 9a005cabe99d5ef53c04ff57c5f43b1277b45ed5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mats=20Paul=20Ton=C4=8Dik?= Date: Tue, 4 Aug 2026 09:16:20 +0200 Subject: [PATCH 036/114] fix(institution-search): fixed router endpoint ambiguity --- service/src/main/inse/works/v2/router.py | 2 +- webapp/src/app/api/api/worksV2.service.ts | 4 +- webapp/src/app/api/model/dfgProjectDetails.ts | 128 +++++++++--------- webapp/src/app/api/model/dfgProjectKeyword.ts | 10 +- webapp/src/app/api/model/dfgProjectTopic.ts | 20 +-- .../app-institution-card.component.ts | 11 +- 6 files changed, 90 insertions(+), 85 deletions(-) diff --git a/service/src/main/inse/works/v2/router.py b/service/src/main/inse/works/v2/router.py index 87596cdd..13446ecd 100644 --- a/service/src/main/inse/works/v2/router.py +++ b/service/src/main/inse/works/v2/router.py @@ -24,7 +24,7 @@ router = APIRouter(prefix=RouterPrefixes.WORKS_V2, tags=[Tags.WORKS_V2]) @router.get( - "/{raw_oa_work_id}", + "/single/{raw_oa_work_id}", operation_id="getWorkById", summary="Returns a work based on its ID.", ) diff --git a/webapp/src/app/api/api/worksV2.service.ts b/webapp/src/app/api/api/worksV2.service.ts index 5e4801f2..9b8dc65d 100644 --- a/webapp/src/app/api/api/worksV2.service.ts +++ b/webapp/src/app/api/api/worksV2.service.ts @@ -511,7 +511,7 @@ export class WorksV2Service extends BaseService { /** * Returns a work based on its ID. - * @endpoint get /api/works/v2/{raw_oa_work_id} + * @endpoint get /api/works/v2/single/{raw_oa_work_id} * @param rawOaWorkId The raw OpenAlex work id. * @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. @@ -549,7 +549,7 @@ export class WorksV2Service extends BaseService { } } - let localVarPath = `/api/works/v2/${this.configuration.encodeParam({name: "rawOaWorkId", value: rawOaWorkId, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: undefined})}`; + let localVarPath = `/api/works/v2/single/${this.configuration.encodeParam({name: "rawOaWorkId", value: rawOaWorkId, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: undefined})}`; const { basePath, withCredentials } = this.configuration; return this.httpClient.request('get', `${basePath}${localVarPath}`, { diff --git a/webapp/src/app/api/model/dfgProjectDetails.ts b/webapp/src/app/api/model/dfgProjectDetails.ts index f3846507..07bcced0 100644 --- a/webapp/src/app/api/model/dfgProjectDetails.ts +++ b/webapp/src/app/api/model/dfgProjectDetails.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 @@ -14,69 +14,71 @@ import { DFGProjectFachgebieteInner } from './dFGProjectFachgebieteInner'; import { Topic } from './topic'; import { DfgProjectPublicationSummary } from './dfgProjectPublicationSummary'; + /** * Clean, enriched summary model for a DFG project. */ -export interface DfgProjectDetails { - id?: number | null; - link?: string | null; - page_url?: string | null; - external_link?: string | null; - title_de?: string | null; - title_en?: string | null; - description_de?: string | null; - description_en?: string | null; - final_report_abstract_de?: string | null; - final_report_abstract_en?: string | null; - project_identifier_de?: string | null; - project_identifier_en?: string | null; - funding_start?: number | null; - funding_end?: number | null; - funding_period_de?: string | null; - funding_period_en?: string | null; - funding_type_de?: string | null; - funding_type_en?: string | null; - funding_type_key?: string | null; - dfg_procedure?: string | null; - is_transfer_project?: boolean | null; - website_html_de?: string | null; - website_html_en?: string | null; - equipment_group?: string | null; - equipment_name?: string | null; - subject_area_de?: string | null; - subject_area_en?: string | null; - /** - * Detailed DFG subject-area classification entries (Fachsystematik) - */ - subject_classifications?: Array; - international_relation_de?: string | null; - international_relation_en?: string | null; - /** - * All persons associated with the project, each with their role - */ - persons?: Array; - /** - * All institutions associated with the project, each with their role - */ - institutions?: Array; - /** - * Flat, de-duplicated list of all person full names (convenience view) - */ - associated_persons?: Array; - /** - * Flat, de-duplicated list of all institution names (convenience view) - */ - associated_institutions?: Array; - parent_project_id?: number | null; - parent_title_de?: string | null; - parent_title_en?: string | null; - /** - * Sub-projects of this project, if any - */ - subprojects?: Array; - /** - * Publications resulting from the project - */ - publications?: Array; - topics?: Array | null; +export interface DfgProjectDetails { + id?: number | null; + link?: string | null; + page_url?: string | null; + external_link?: string | null; + title_de?: string | null; + title_en?: string | null; + description_de?: string | null; + description_en?: string | null; + final_report_abstract_de?: string | null; + final_report_abstract_en?: string | null; + project_identifier_de?: string | null; + project_identifier_en?: string | null; + funding_start?: number | null; + funding_end?: number | null; + funding_period_de?: string | null; + funding_period_en?: string | null; + funding_type_de?: string | null; + funding_type_en?: string | null; + funding_type_key?: string | null; + dfg_procedure?: string | null; + is_transfer_project?: boolean | null; + website_html_de?: string | null; + website_html_en?: string | null; + equipment_group?: string | null; + equipment_name?: string | null; + subject_area_de?: string | null; + subject_area_en?: string | null; + /** + * Detailed DFG subject-area classification entries (Fachsystematik) + */ + subject_classifications?: Array; + international_relation_de?: string | null; + international_relation_en?: string | null; + /** + * All persons associated with the project, each with their role + */ + persons?: Array; + /** + * All institutions associated with the project, each with their role + */ + institutions?: Array; + /** + * Flat, de-duplicated list of all person full names (convenience view) + */ + associated_persons?: Array; + /** + * Flat, de-duplicated list of all institution names (convenience view) + */ + associated_institutions?: Array; + parent_project_id?: number | null; + parent_title_de?: string | null; + parent_title_en?: string | null; + /** + * Sub-projects of this project, if any + */ + subprojects?: Array; + /** + * Publications resulting from the project + */ + publications?: Array; + topics?: Array | null; } + diff --git a/webapp/src/app/api/model/dfgProjectKeyword.ts b/webapp/src/app/api/model/dfgProjectKeyword.ts index f81b6ad4..2e898f1c 100644 --- a/webapp/src/app/api/model/dfgProjectKeyword.ts +++ b/webapp/src/app/api/model/dfgProjectKeyword.ts @@ -1,14 +1,16 @@ /** * 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 DfgProjectKeyword { - name: string; - project_count: number; + +export interface DfgProjectKeyword { + name: string; + project_count: number; } + diff --git a/webapp/src/app/api/model/dfgProjectTopic.ts b/webapp/src/app/api/model/dfgProjectTopic.ts index ca22eb28..4b99c034 100644 --- a/webapp/src/app/api/model/dfgProjectTopic.ts +++ b/webapp/src/app/api/model/dfgProjectTopic.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,12 +9,14 @@ */ import { DfgProjectKeyword } from './dfgProjectKeyword'; -export interface DfgProjectTopic { - id: string; - name: string; - subfield?: string | null; - field?: string | null; - domain?: string | null; - project_count: number; - keywords: Array; + +export interface DfgProjectTopic { + id: string; + name: string; + subfield?: string | null; + field?: string | null; + domain?: string | null; + project_count: number; + keywords: Array; } + diff --git a/webapp/src/app/shared/ui/app-institution-card/app-institution-card.component.ts b/webapp/src/app/shared/ui/app-institution-card/app-institution-card.component.ts index 2502c36f..8b92a5b4 100644 --- a/webapp/src/app/shared/ui/app-institution-card/app-institution-card.component.ts +++ b/webapp/src/app/shared/ui/app-institution-card/app-institution-card.component.ts @@ -46,14 +46,13 @@ export class AppInstitutionCardComponent { }); isOwnInstitution = computed(() => { - const id = this.stripOpenAlexId(this.institution().id); - if (!id) return false; + const institutionId = this.stripOpenAlexId(this.institution().id); + if (!institutionId) return false; - console.log( - `Comparing institution ID ${id} with effective institution ID ${this.credentialService.effectiveInstitutionId()}`, - ); + const effectiveInstitutionId = + this.credentialService.effectiveInstitutionId(); - return id === this.credentialService.effectiveInstitutionId(); + return institutionId === effectiveInstitutionId; }); // The "Patente" action only makes sense once org_patents has been indexed From 07c7343f942ce140c9654fa71a94039492584064 Mon Sep 17 00:00:00 2001 From: louis-19041904 Date: Tue, 4 Aug 2026 09:20:22 +0200 Subject: [PATCH 037/114] center and space out news filter row --- webapp/src/app/modules/news/news.component.html | 5 ++++- webapp/src/app/modules/news/news.component.scss | 2 +- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/webapp/src/app/modules/news/news.component.html b/webapp/src/app/modules/news/news.component.html index 0c7d74d7..c5fcd597 100644 --- a/webapp/src/app/modules/news/news.component.html +++ b/webapp/src/app/modules/news/news.component.html @@ -18,7 +18,10 @@
- + Date: Tue, 4 Aug 2026 09:37:42 +0200 Subject: [PATCH 038/114] fix(person-funding): funding tables to plain row lines --- .../modules/person-funding/person-funding.component.scss | 9 ++------- 1 file changed, 2 insertions(+), 7 deletions(-) diff --git a/webapp/src/app/modules/person-funding/person-funding.component.scss b/webapp/src/app/modules/person-funding/person-funding.component.scss index 37fa666c..da4883e4 100644 --- a/webapp/src/app/modules/person-funding/person-funding.component.scss +++ b/webapp/src/app/modules/person-funding/person-funding.component.scss @@ -85,24 +85,19 @@ app-query-param-paginator { display: inline-flex; align-items: center; justify-content: center; - min-width: 26px; - padding: 2px 8px; - border-radius: 999px; - font-size: 12px; + min-width: 20px; + font-size: 13px; font-weight: 700; &--first { - background: #effaf3; color: #24834f; } &--middle { - background: #f6f0ff; color: #7255d9; } &--last { - background: #fff1f2; color: #be123c; } } From c1641fdb38753c35f9d653ee663cee7b5ce71e07 Mon Sep 17 00:00:00 2001 From: Farajollahi Date: Tue, 4 Aug 2026 09:51:48 +0200 Subject: [PATCH 039/114] check counts --- service/src/main/inse/dashboard/service.py | 419 +++++++++++++----- .../src/main/inse/dashboard/test_service.py | 247 ++++++++--- .../projects/eu_cordis_projects_client.py | 11 +- .../inse/projects/projects_search_client.py | 6 +- service/src/main/inse/projects/service.py | 6 +- service/src/main/inse/ranking/logic.py | 76 ++-- 6 files changed, 570 insertions(+), 195 deletions(-) diff --git a/service/src/main/inse/dashboard/service.py b/service/src/main/inse/dashboard/service.py index d2056d48..2a3e37f7 100644 --- a/service/src/main/inse/dashboard/service.py +++ b/service/src/main/inse/dashboard/service.py @@ -11,13 +11,12 @@ from sqlmodel import Session from inse import config from inse.auth.model import AccessToken, Organization -from inse.authors.institution_membership_query import ( - build_institution_membership_query, -) from inse.institutions.institutions_search_client import InstitutionsSearchClient from inse.integrations import elasticsearch from inse.model import ESCluster, ESIndex from inse.patents.org.elastic_search_client import OrgPatentsSearchClient +from inse.persons import service as persons_service +from inse.projects import service as projects_service from inse.projects.dfg_institutions.service import ( autocomplete_institutions_for_selector, ) @@ -270,20 +269,25 @@ async def get_dashboard_persons( status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, detail="from_year and to_year must either both be provided or both omitted.", ) - membership_query = build_institution_membership_query( + persons = await persons_service.search_persons_list( + query=None, institution_id=normalized_id, - year_mode="between" if period[0] is not None else "all", - year=period[0], - year_to=period[1], + sort_by=None, + sort_order=None, + topic=None, + page=1, + page_size=1, + include="", + year_filter_enabled=period[0] is not None, + filter_mode="between" if period[0] is not None else None, + filter_year=period[0], + filter_year_to=period[1], ) - response = await elasticsearch.search( - index=ESIndex.OPENALEX_AUTHORS, - query=membership_query, - size=0, - track_total_hits=True, - cluster=ESCluster.NES, + return DashboardStatisticValue( + institution_id=normalized_id, + organization_name=organization_name, + value=int(persons.meta.count or 0) if persons.meta else 0, ) - return _dashboard_statistic_value(normalized_id, organization_name, response) async def get_dashboard_patents( @@ -315,45 +319,43 @@ async def get_dashboard_eu_projects( to_year: int | None = None, ) -> DashboardStatisticValue: normalized_id = _normalize_institution_id(institution_id) - aliases = await _institution_aliases(normalized_id, organization_name) period = _dashboard_period(from_year, to_year) - period_filter = _project_overlap_filter( - "startDate", - "endDate", - _date_period(period, "iso"), - ) - if period_filter: - project_ids = await _eu_project_ids_for_aliases(aliases) - value = await _count_eu_projects_in_period(project_ids, period_filter) - return DashboardStatisticValue( - institution_id=normalized_id, - organization_name=organization_name, - value=value, - ) - - response = await elasticsearch.search( - index=ESIndex.CORDIS_EU_ORGANIZATIONS_WILDCARD, - body={ - "size": 0, - "query": _eu_organization_query(aliases), - "aggs": { - "projects": { - "cardinality": { - "field": "projectID", - } - } - }, - }, - cluster=ESCluster.INSE, + projects = await projects_service.search_eu_cordis_projects( + institutions_search_client=InstitutionsSearchClient(), + raw_oa_institution_id=_raw_institution_id(normalized_id), + author_id=None, + author_ids=None, + organization_ids=None, + organization_names=None, + project_types=list(EuCordisProjectType), + keywords=None, + topic_ids=None, + filter_topic_ids=None, + title=None, + funding_start_years=( + [str(year) for year in range(1900, period[1] + 1)] + if period[1] is not None + else None + ), + funding_end_years=( + [str(year) for year in range(period[0], 2101)] + if period[0] is not None + else None + ), + countries=None, + framework_programmes=None, + funding_schemes=None, + statuses=None, + page=0, + size=1, + sort_by="id", + sort_direction="asc", + fuzzy=False, ) return DashboardStatisticValue( institution_id=normalized_id, organization_name=organization_name, - value=int( - response.get("aggregations", {}) - .get("projects", {}) - .get("value", 0) - ), + value=projects.total, ) @@ -368,10 +370,18 @@ async def get_dashboard_eu_project_statuses( project_ids = await _eu_project_ids_for_aliases(aliases) if not project_ids: + total = ( + await get_dashboard_eu_projects( + normalized_id, + organization_name, + from_year=from_year, + to_year=to_year, + ) + ).value return EuProjectStatusStatistics( institution_id=normalized_id, organization_name=organization_name, - ongoing=0, + ongoing=total, upcoming=0, completed=0, ) @@ -426,12 +436,26 @@ async def get_dashboard_eu_project_statuses( cluster=ESCluster.INSE, ) aggregations = response.get("aggregations", {}) + total = ( + await get_dashboard_eu_projects( + normalized_id, + organization_name, + from_year=from_year, + to_year=to_year, + ) + ).value + ongoing, upcoming, completed = _reconcile_project_status_counts( + total, + _project_status_count(aggregations, "ongoing"), + _project_status_count(aggregations, "upcoming"), + _project_status_count(aggregations, "completed"), + ) return EuProjectStatusStatistics( institution_id=normalized_id, organization_name=organization_name, - ongoing=_project_status_count(aggregations, "ongoing"), - upcoming=_project_status_count(aggregations, "upcoming"), - completed=_project_status_count(aggregations, "completed"), + ongoing=ongoing, + upcoming=upcoming, + completed=completed, ) @@ -441,6 +465,32 @@ def _project_status_count(aggregations: dict[str, Any], status_name: str) -> int ) +def _reconcile_project_status_counts( + total: int, + ongoing: int, + upcoming: int, + completed: int, +) -> tuple[int, int, int]: + """Makes status buckets add up to the authoritative project-service total.""" + counts = [max(0, ongoing), max(0, upcoming), max(0, completed)] + difference = total - sum(counts) + if difference >= 0: + counts[0] += difference + return counts[0], counts[1], counts[2] + + # Defensive fallback for stale/duplicated status documents: reduce buckets + # without ever returning negative values, preferring the inferred ongoing + # bucket before changing explicit upcoming/completed classifications. + excess = -difference + for index in (0, 1, 2): + reduction = min(counts[index], excess) + counts[index] -= reduction + excess -= reduction + if excess == 0: + break + return counts[0], counts[1], counts[2] + + async def get_dashboard_bmbf_projects( institution_id: str, organization_name: str, @@ -448,23 +498,38 @@ async def get_dashboard_bmbf_projects( to_year: int | None = None, ) -> DashboardStatisticValue: normalized_id = _normalize_institution_id(institution_id) - aliases = await _institution_aliases(normalized_id, organization_name) period = _dashboard_period(from_year, to_year) - filters = [_alias_match_query("Zuwendungsempfänger", aliases)] - if period_filter := _project_overlap_filter( - "funding_start", - "funding_end", - _date_period(period, "de"), - ): - filters.append(period_filter) - response = await elasticsearch.search( - index=ESIndex.PROJECTS_BUND_V1, - query=filters[0] if len(filters) == 1 else {"bool": {"filter": filters}}, - size=0, - track_total_hits=True, - cluster=ESCluster.INSE, + projects = await projects_service.search_bund_projects_with_filters( + institutions_search_client=InstitutionsSearchClient(), + executing_agency=None, + raw_oa_institution_id=_raw_institution_id(normalized_id), + title=None, + keywords=None, + funding_arts=None, + topic_ids=None, + filter_topic_ids=None, + funding_start_years=( + [str(year) for year in range(1900, period[1] + 1)] + if period[1] is not None + else None + ), + funding_end_years=( + [str(year) for year in range(period[0], 2101)] + if period[0] is not None + else None + ), + countries=None, + page=0, + size=1, + sort_by="id", + sort_direction="asc", + fuzzy=False, + ) + return DashboardStatisticValue( + institution_id=normalized_id, + organization_name=organization_name, + value=projects.total, ) - return _dashboard_statistic_value(normalized_id, organization_name, response) async def get_dashboard_bmbf_project_statuses( @@ -498,12 +563,26 @@ async def get_dashboard_bmbf_project_statuses( cluster=ESCluster.INSE, ) aggregations = response.get("aggregations", {}) + total = ( + await get_dashboard_bmbf_projects( + normalized_id, + organization_name, + from_year=from_year, + to_year=to_year, + ) + ).value + ongoing, upcoming, completed = _reconcile_project_status_counts( + total, + int(aggregations.get("ongoing", {}).get("doc_count", 0)), + int(aggregations.get("upcoming", {}).get("doc_count", 0)), + int(aggregations.get("completed", {}).get("doc_count", 0)), + ) return BmbfProjectStatusStatistics( institution_id=normalized_id, organization_name=organization_name, - ongoing=int(aggregations.get("ongoing", {}).get("doc_count", 0)), - upcoming=int(aggregations.get("upcoming", {}).get("doc_count", 0)), - completed=int(aggregations.get("completed", {}).get("doc_count", 0)), + ongoing=ongoing, + upcoming=upcoming, + completed=completed, ) @@ -535,15 +614,37 @@ async def get_dashboard_dfg_projects( to_year: int | None = None, ) -> DashboardStatisticValue: normalized_id = _normalize_institution_id(institution_id) - project_ids = await _get_dfg_project_ids_for_institution( - normalized_id, - from_year=from_year, - to_year=to_year, + period = _dashboard_period(from_year, to_year) + projects = await projects_service.get_dfg_projects_by_author_id( + institutions_search_client=InstitutionsSearchClient(), + raw_oa_institution_id=_raw_institution_id(normalized_id), + author_id=None, + author_filter_ids=None, + institution_ids=None, + keywords=None, + topic_ids=None, + filter_topic_ids=None, + title=None, + funding_start_years=( + [str(year) for year in range(1900, period[1] + 1)] + if period[1] is not None + else None + ), + funding_end_years=( + [str(year) for year in range(period[0], 2101)] + if period[0] is not None + else None + ), + page=0, + size=1, + sort_by="id", + sort_direction="asc", + fuzzy=False, ) return DashboardStatisticValue( institution_id=normalized_id, organization_name=organization_name, - value=len(project_ids), + value=projects.total, ) @@ -559,10 +660,18 @@ async def get_dashboard_dfg_project_statuses( normalized_id, ) if not project_ids: + total = ( + await get_dashboard_dfg_projects( + normalized_id, + organization_name, + from_year=from_year, + to_year=to_year, + ) + ).value return DfgProjectStatusStatistics( institution_id=normalized_id, organization_name=organization_name, - ongoing=0, + ongoing=total, upcoming=0, completed=0, ) @@ -640,12 +749,26 @@ async def get_dashboard_dfg_project_statuses( .get("projects_nested", {}) .get("selected_projects", {}) ) + total = ( + await get_dashboard_dfg_projects( + normalized_id, + organization_name, + from_year=from_year, + to_year=to_year, + ) + ).value + ongoing, upcoming, completed = _reconcile_project_status_counts( + total, + _project_status_count(aggregations, "ongoing"), + 0, + _project_status_count(aggregations, "completed"), + ) return DfgProjectStatusStatistics( institution_id=normalized_id, organization_name=organization_name, - ongoing=_project_status_count(aggregations, "ongoing"), - upcoming=0, - completed=_project_status_count(aggregations, "completed"), + ongoing=ongoing, + upcoming=upcoming, + completed=completed, ) @@ -656,17 +779,11 @@ async def get_dashboard_dfg_topics( to_year: int | None = None, ) -> DfgProjectTopics: normalized_id = _normalize_institution_id(institution_id) - project_ids = await _get_dfg_project_ids_for_institution( + project_ids = await _get_dfg_project_ids_from_projects_service( normalized_id, from_year=from_year, to_year=to_year, ) - print( - "Dashboard DFG project topics " - f"for institution {normalized_id}: " - f"{len(project_ids)} project IDs={project_ids}", - flush=True, - ) topics: dict[str, dict[str, Any]] = {} matched_project_ids: set[str] = set() @@ -735,6 +852,53 @@ async def get_dashboard_dfg_topics( ) +async def _get_dfg_project_ids_from_projects_service( + institution_id: str, + from_year: int | None = None, + to_year: int | None = None, +) -> list[str]: + """Returns every matching DFG project ID through the canonical project service.""" + period = _dashboard_period(from_year, to_year) + page_size = 1000 + page_number = 0 + project_ids: set[str] = set() + + while True: + projects = await projects_service.get_dfg_projects_by_author_id( + institutions_search_client=InstitutionsSearchClient(), + raw_oa_institution_id=_raw_institution_id(institution_id), + author_id=None, + author_filter_ids=None, + institution_ids=None, + keywords=None, + topic_ids=None, + filter_topic_ids=None, + title=None, + funding_start_years=( + [str(year) for year in range(1900, period[1] + 1)] + if period[1] is not None + else None + ), + funding_end_years=( + [str(year) for year in range(period[0], 2101)] + if period[0] is not None + else None + ), + page=page_number, + size=page_size, + sort_by="id", + sort_direction="asc", + fuzzy=False, + skip_enrichment=True, + ) + project_ids.update(project.id for project in projects.elements if project.id) + if len(project_ids) >= projects.total or not projects.elements: + break + page_number += 1 + + return sorted(project_ids) + + async def _get_dfg_project_ids_for_institution( institution_id: str, from_year: int | None = None, @@ -1011,7 +1175,6 @@ async def get_top_authors( from_year = datetime.now().year - 4 to_year = datetime.now().year period = _dashboard_period(from_year, to_year) - aliases = await _institution_aliases(normalized_id, organization_name) authors = await _safe_institution_authors(normalized_id) works = _top_work_authors(authors, period) projects = await _safe_top_authors( @@ -1025,7 +1188,12 @@ async def get_top_authors( ) eu_projects = await _safe_top_authors( "eu_projects", - _top_eu_project_publication_authors(normalized_id, aliases, authors), + _top_eu_project_publication_authors( + normalized_id, + authors, + from_year=period[0], + to_year=period[1], + ), ) patents = await _safe_top_authors( @@ -1998,8 +2166,9 @@ async def _top_patent_authors( async def _top_eu_project_publication_authors( institution_id: str, - organization_names: list[str], institution_authors: list[dict[str, Any]], + from_year: int | None = None, + to_year: int | None = None, ) -> list[TopAuthor]: institution_author_ids = { author_id @@ -2009,17 +2178,12 @@ async def _top_eu_project_publication_authors( if not institution_author_ids: return [] - project_page = await get_eu_organization_project_contributions( - organization_names=organization_names, - projects_filtering_properties=ProjectsFilteringProperties( - project_type=ProjectType.EU, - page=0, - size=10000, - ), + project_ids = await _get_eu_project_ids_from_projects_service( + institution_id, + from_year=from_year, + to_year=to_year, ) - project_ids = [project.project_id for project in project_page.elements] - if not project_ids: return [] @@ -2028,11 +2192,7 @@ async def _top_eu_project_publication_authors( body={ "size": 10000, "_source": ["projectID", "qaProcessedDoi"], - "query": { - "terms": { - "projectID": project_ids, - } - }, + "query": {"terms": {"projectID": project_ids}}, }, cluster=ESCluster.INSE, ) @@ -2074,6 +2234,59 @@ async def _top_eu_project_publication_authors( ) +async def _get_eu_project_ids_from_projects_service( + institution_id: str, + from_year: int | None = None, + to_year: int | None = None, +) -> list[str]: + """Loads all organization EU project IDs from the canonical project service.""" + period = _dashboard_period(from_year, to_year) + page_size = 1000 + page_number = 0 + project_ids: set[str] = set() + + while True: + projects = await projects_service.search_eu_cordis_projects( + institutions_search_client=InstitutionsSearchClient(), + raw_oa_institution_id=_raw_institution_id(institution_id), + author_id=None, + author_ids=None, + organization_ids=None, + organization_names=None, + project_types=list(EuCordisProjectType), + keywords=None, + topic_ids=None, + filter_topic_ids=None, + title=None, + funding_start_years=( + [str(year) for year in range(1900, period[1] + 1)] + if period[1] is not None + else None + ), + funding_end_years=( + [str(year) for year in range(period[0], 2101)] + if period[0] is not None + else None + ), + countries=None, + framework_programmes=None, + funding_schemes=None, + statuses=None, + page=page_number, + size=page_size, + sort_by="id", + sort_direction="asc", + fuzzy=False, + skip_enrichment=True, + ) + project_ids.update(project.id for project in projects.elements if project.id) + if len(project_ids) >= projects.total or not projects.elements: + break + page_number += 1 + + return sorted(project_ids) + + def _cordis_publication_doi_project_ids( response: dict[str, Any], allowed_project_ids: set[str], diff --git a/service/src/main/inse/dashboard/test_service.py b/service/src/main/inse/dashboard/test_service.py index 2e58db2e..53f1dc02 100644 --- a/service/src/main/inse/dashboard/test_service.py +++ b/service/src/main/inse/dashboard/test_service.py @@ -10,7 +10,13 @@ from inse import config from inse.auth.model import AccessToken, Organization, UserRole from inse.dashboard.service import ( _openalex_work_authors_by_eu_projects, + _get_dfg_project_ids_from_projects_service, + _reconcile_project_status_counts, + get_dashboard_bmbf_projects, + get_dashboard_dfg_projects, + get_dashboard_eu_projects, get_dashboard_organization, + get_dashboard_persons, get_dashboard_statistics, get_top_authors, get_topic_heatmap, @@ -18,6 +24,16 @@ from inse.dashboard.service import ( ) from inse.model import ESCluster, ESIndex from inse.models.openalex.institution import Institution +from inse.models.openalex.meta import Meta +from inse.persons.model import CustomAuthorsListResponse +from inse.projects.model import ( + BundProjectPage, + DfgProjectPage, + DfgProjectSummary, + EuCordisProjectSearchPage, + EuCordisProjectSummary, + EuCordisProjectType, +) ORG_INSTITUTION_ID = "https://openalex.org/I123" @@ -27,6 +43,47 @@ def anyio_backend(): return "asyncio" +def test_project_status_counts_match_authoritative_total(): + assert _reconcile_project_status_counts(12, 4, 1, 5) == (6, 1, 5) + assert _reconcile_project_status_counts(7, 4, 2, 3) == (2, 2, 3) + + +@pytest.mark.anyio +async def test_dfg_topic_project_ids_use_paginated_projects_service(): + pages = [ + DfgProjectPage( + elements=[DfgProjectSummary(id="101"), DfgProjectSummary(id="102")], + total=3, + page=0, + size=1000, + ), + DfgProjectPage( + elements=[DfgProjectSummary(id="103")], + total=3, + page=1, + size=1000, + ), + ] + + with patch( + "inse.dashboard.service.projects_service.get_dfg_projects_by_author_id", + new=AsyncMock(side_effect=pages), + ) as mocked_get_projects: + project_ids = await _get_dfg_project_ids_from_projects_service( + ORG_INSTITUTION_ID, + from_year=2020, + to_year=2022, + ) + + assert project_ids == ["101", "102", "103"] + assert mocked_get_projects.await_count == 2 + first_call = mocked_get_projects.await_args_list[0] + assert first_call.kwargs["raw_oa_institution_id"] == "I123" + assert first_call.kwargs["skip_enrichment"] is True + assert first_call.kwargs["funding_start_years"][-1] == "2022" + assert first_call.kwargs["funding_end_years"][0] == "2020" + + @pytest.mark.anyio async def test_dashboard_statistics_counts_organization_data_and_all_projects(): async def search(**kwargs): @@ -84,6 +141,30 @@ async def test_dashboard_statistics_counts_organization_data_and_all_projects(): display_name_alternatives=["Example Universität"], ) ), + ), patch( + "inse.dashboard.service.projects_service.get_dfg_projects_by_author_id", + new=AsyncMock( + return_value=DfgProjectPage(elements=[], total=3, page=0, size=1) + ), + ), patch( + "inse.dashboard.service.projects_service.search_eu_cordis_projects", + new=AsyncMock( + return_value=EuCordisProjectSearchPage( + elements=[], total=10, page=0, size=1 + ) + ), + ), patch( + "inse.dashboard.service.projects_service.search_bund_projects_with_filters", + new=AsyncMock( + return_value=BundProjectPage(elements=[], total=5, page=0, size=1) + ), + ), patch( + "inse.dashboard.service.persons_service.search_persons_list", + new=AsyncMock( + return_value=CustomAuthorsListResponse( + results=[], meta=Meta(count=35, page=1, per_page=1) + ) + ), ): result = await get_dashboard_statistics( ORG_INSTITUTION_ID, @@ -110,55 +191,109 @@ async def test_dashboard_statistics_counts_organization_data_and_all_projects(): "authorships.institutions.id": ORG_INSTITUTION_ID } - person_call = next( - call - for call in mocked_search.await_args_list - if call.kwargs["index"] == ESIndex.OPENALEX_AUTHORS +@pytest.mark.anyio +async def test_dashboard_persons_uses_persons_service_for_organization(): + response = CustomAuthorsListResponse( + results=[], meta=Meta(count=64, page=1, per_page=1) ) - person_query = person_call.kwargs["query"] - affiliation = person_query["bool"]["should"][0]["bool"]["filter"][1] - assert affiliation["nested"]["path"] == "affiliations" - assert affiliation["nested"]["query"]["bool"]["filter"][0] == { - "term": {"affiliations.institution.id": ORG_INSTITUTION_ID} - } - eu_call = next( - call - for call in mocked_search.await_args_list - if call.kwargs["index"] == ESIndex.CORDIS_EU_ORGANIZATIONS_WILDCARD + with patch( + "inse.dashboard.service.persons_service.search_persons_list", + new=AsyncMock(return_value=response), + ) as mocked_search_persons: + result = await get_dashboard_persons( + ORG_INSTITUTION_ID, + "Example Org", + from_year=2020, + to_year=2023, + ) + + assert result.value == 64 + call = mocked_search_persons.await_args + assert call.kwargs["institution_id"] == ORG_INSTITUTION_ID + assert call.kwargs["filter_mode"] == "between" + assert call.kwargs["filter_year"] == 2020 + assert call.kwargs["filter_year_to"] == 2023 + assert call.kwargs["page"] == 1 + assert call.kwargs["page_size"] == 1 + + +@pytest.mark.anyio +async def test_dashboard_dfg_projects_uses_projects_service_total(): + project_page = DfgProjectPage(elements=[], total=42, page=0, size=1) + + with patch( + "inse.dashboard.service.projects_service.get_dfg_projects_by_author_id", + new=AsyncMock(return_value=project_page), + ) as mocked_get_projects: + result = await get_dashboard_dfg_projects( + ORG_INSTITUTION_ID, + "Example Org", + from_year=2020, + to_year=2022, + ) + + assert result.value == 42 + mocked_get_projects.assert_awaited_once() + call = mocked_get_projects.await_args + assert call.kwargs["raw_oa_institution_id"] == "I123" + assert call.kwargs["funding_start_years"][-1] == "2022" + assert call.kwargs["funding_end_years"][0] == "2020" + assert call.kwargs["page"] == 0 + assert call.kwargs["size"] == 1 + + +@pytest.mark.anyio +async def test_dashboard_bmbf_projects_uses_projects_service_total(): + project_page = BundProjectPage(elements=[], total=29, page=0, size=1) + + with patch( + "inse.dashboard.service.projects_service.search_bund_projects_with_filters", + new=AsyncMock(return_value=project_page), + ) as mocked_get_projects: + result = await get_dashboard_bmbf_projects( + ORG_INSTITUTION_ID, + "Example Org", + from_year=2018, + to_year=2020, + ) + + assert result.value == 29 + mocked_get_projects.assert_awaited_once() + call = mocked_get_projects.await_args + assert call.kwargs["raw_oa_institution_id"] == "I123" + assert call.kwargs["funding_start_years"][-1] == "2020" + assert call.kwargs["funding_end_years"][0] == "2018" + assert call.kwargs["page"] == 0 + assert call.kwargs["size"] == 1 + + +@pytest.mark.anyio +async def test_dashboard_eu_projects_uses_projects_service_total(): + project_page = EuCordisProjectSearchPage( + elements=[], total=37, page=0, size=1 ) - assert eu_call.kwargs["cluster"] == ESCluster.INSE - assert eu_call.kwargs["body"]["query"] == { - "terms": { - "name.keyword": [ - "EXAMPLE ORG", - "EXAMPLE UNI", - "EXAMPLE UNIVERSITY", - ] - } - } - bund_call = next( - call - for call in mocked_search.await_args_list - if call.kwargs["index"] == ESIndex.PROJECTS_BUND_V1 - ) - assert bund_call.kwargs["cluster"] == ESCluster.INSE - assert bund_call.kwargs["query"]["bool"]["minimum_should_match"] == 1 - assert bund_call.kwargs["query"]["bool"]["should"][0]["match"] == { - "Zuwendungsempfänger": { - "query": "Example Org", - "operator": "and", - } - } + with patch( + "inse.dashboard.service.projects_service.search_eu_cordis_projects", + new=AsyncMock(return_value=project_page), + ) as mocked_get_projects: + result = await get_dashboard_eu_projects( + ORG_INSTITUTION_ID, + "Example Org", + from_year=2019, + to_year=2021, + ) - dfg_calls = [ - call - for call in mocked_search.await_args_list - if call.kwargs["index"] == ESIndex.DFG_INSTITUTES_V2 - ] - assert len(dfg_calls) == 2 - assert all(call.kwargs["cluster"] == ESCluster.INSE for call in dfg_calls) + assert result.value == 37 + mocked_get_projects.assert_awaited_once() + call = mocked_get_projects.await_args + assert call.kwargs["raw_oa_institution_id"] == "I123" + assert call.kwargs["funding_start_years"][-1] == "2021" + assert call.kwargs["funding_end_years"][0] == "2019" + assert call.kwargs["project_types"] == list(EuCordisProjectType) + assert call.kwargs["page"] == 0 + assert call.kwargs["size"] == 1 @pytest.mark.anyio @@ -279,14 +414,17 @@ async def test_top_authors_maps_works_patents_news_and_eu_projects(): "inse.dashboard.service.InstitutionsSearchClient.get_institution_aliases_by_oa_institution_id", new=AsyncMock(return_value=["Example University"]), ), patch( - "inse.dashboard.service.get_eu_organization_project_contributions", + "inse.dashboard.service.projects_service.search_eu_cordis_projects", new=AsyncMock( - return_value=SimpleNamespace( + return_value=EuCordisProjectSearchPage( elements=[ - SimpleNamespace(project_id="P1"), - SimpleNamespace(project_id="P2"), - SimpleNamespace(project_id="P3"), + EuCordisProjectSummary(id="P1", project_type=EuCordisProjectType.FP7), + EuCordisProjectSummary(id="P2", project_type=EuCordisProjectType.H2020), + EuCordisProjectSummary(id="P3", project_type=EuCordisProjectType.HEU), ], + total=3, + page=0, + size=1000, ) ), ), patch( @@ -580,13 +718,16 @@ async def test_top_eu_project_authors_count_filtered_projects_by_stable_author_i "inse.dashboard.service.InstitutionsSearchClient.get_institution_aliases_by_oa_institution_id", new=AsyncMock(return_value=["Example University"]), ), patch( - "inse.dashboard.service.get_eu_organization_project_contributions", + "inse.dashboard.service.projects_service.search_eu_cordis_projects", new=AsyncMock( - return_value=SimpleNamespace( + return_value=EuCordisProjectSearchPage( elements=[ - SimpleNamespace(project_id="P1"), - SimpleNamespace(project_id="P2"), + EuCordisProjectSummary(id="P1", project_type=EuCordisProjectType.FP7), + EuCordisProjectSummary(id="P2", project_type=EuCordisProjectType.H2020), ], + total=2, + page=0, + size=1000, ) ), ), patch( diff --git a/service/src/main/inse/projects/eu_cordis_projects_client.py b/service/src/main/inse/projects/eu_cordis_projects_client.py index c0df87bb..8f0af70f 100644 --- a/service/src/main/inse/projects/eu_cordis_projects_client.py +++ b/service/src/main/inse/projects/eu_cordis_projects_client.py @@ -944,6 +944,7 @@ async def search_eu_cordis_projects( sort_by: str = "title", sort_direction: str = "asc", fuzzy: bool = False, + skip_enrichment: bool = False, ) -> EuCordisProjectSearchPage: """ Generic EU CORDIS project search across FP7, H2020 and Horizon Europe. @@ -1015,6 +1016,14 @@ async def search_eu_cordis_projects( hits = response.get("hits", {}).get("hits", []) total = response.get("hits", {}).get("total", {}).get("value", 0) + if skip_enrichment: + return EuCordisProjectSearchPage( + elements=[EuCordisProjectSummary.from_hit(hit) for hit in hits], + total=total, + page=page, + size=size, + ) + project_ids_by_type: dict[EuCordisProjectType, list[str]] = defaultdict(list) for hit in hits: @@ -1333,4 +1342,4 @@ async def get_openalex_authors_for_projects_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 + return result diff --git a/service/src/main/inse/projects/projects_search_client.py b/service/src/main/inse/projects/projects_search_client.py index 72c9194a..66fa8632 100644 --- a/service/src/main/inse/projects/projects_search_client.py +++ b/service/src/main/inse/projects/projects_search_client.py @@ -366,6 +366,7 @@ async def search_dfg_projects( sort_by: str = "id", sort_direction: str = "asc", fuzzy: bool = False, + skip_enrichment: bool = False, ) -> DfgProjectPage: """Searches for DFG projects based on the provided filtering and sorting criteria. @@ -584,6 +585,9 @@ async def search_dfg_projects( hits = response.get("hits", {}).get("hits", []) + if skip_enrichment: + return _complete_response_to_dfg_project_page(response, page, size) + project_ids = [hit["_source"]["id"] for hit in hits] topic_lookup = await get_openalex_topics_for_dfg_projects(project_ids=project_ids) @@ -1167,4 +1171,4 @@ def _hit_to_funding_project(hit: dict[str, Any]) -> FundingProject: else: raise ValueError( "The provided hit does not belong to a recognized project index." - ) \ No newline at end of file + ) diff --git a/service/src/main/inse/projects/service.py b/service/src/main/inse/projects/service.py index 4666c640..ab5fa644 100644 --- a/service/src/main/inse/projects/service.py +++ b/service/src/main/inse/projects/service.py @@ -174,6 +174,7 @@ async def get_dfg_projects_by_author_id( sort_by: str = "topic", sort_direction: str = "asc", fuzzy: bool = False, + skip_enrichment: bool = False, ) -> DfgProjectPage: logger.debug( "Fetching DFG projects for author_id=%s, author_filter_ids=%s, " @@ -248,6 +249,7 @@ async def get_dfg_projects_by_author_id( sort_by=sort_by, sort_direction=sort_direction, fuzzy=fuzzy, + skip_enrichment=skip_enrichment, ) async def get_institution_cordis_eu_projects_funding_over_time( @@ -623,6 +625,7 @@ async def search_eu_cordis_projects( sort_by: str = "title", sort_direction: str = "asc", fuzzy: bool = False, + skip_enrichment: bool = False, ) -> EuCordisProjectSearchPage: """Single entry point for EU CORDIS project search. @@ -683,4 +686,5 @@ async def search_eu_cordis_projects( sort_by=sort_by, sort_direction=sort_direction, fuzzy=fuzzy, - ) \ No newline at end of file + skip_enrichment=skip_enrichment, + ) diff --git a/service/src/main/inse/ranking/logic.py b/service/src/main/inse/ranking/logic.py index 06cf19f0..bde34bc2 100644 --- a/service/src/main/inse/ranking/logic.py +++ b/service/src/main/inse/ranking/logic.py @@ -3,11 +3,10 @@ import asyncio import logging from dataclasses import dataclass +from math import floor from time import time from typing import Any -import pandas as pd - from inse.authors.institution_membership_query import ( build_active_institution_membership_query, ) @@ -746,15 +745,29 @@ def _bucket_to_ranked_author(author_bucket: dict) -> RankedAuthor: ) -def _min_max_normalize(values: pd.Series) -> pd.Series: +def _quantile(values: list[float], quantile: float) -> float: + """Returns a linearly interpolated quantile (the former pandas default).""" + ordered = sorted(values) + if not ordered: + return 0.0 + position = (len(ordered) - 1) * quantile + lower_index = floor(position) + upper_index = min(lower_index + 1, len(ordered) - 1) + fraction = position - lower_index + return ordered[lower_index] + ( + ordered[upper_index] - ordered[lower_index] + ) * fraction + + +def _min_max_normalize(values: list[float]) -> list[float]: """Scales a numeric column to the range [0, 1] via min-max normalization.""" - minimum = values.min() - maximum = values.max() + minimum = min(values) + maximum = max(values) # if all values are the same, return a series of 1.0 to avoid division by zero. if maximum == minimum: - return pd.Series([1.0] * len(values)) + return [1.0] * len(values) - return (values - minimum) / (maximum - minimum) + return [(value - minimum) / (maximum - minimum) for value in values] def _apply_scores(authors: list[RankedAuthor], weights: RankingWeights) -> None: @@ -775,38 +788,29 @@ def _apply_scores(authors: list[RankedAuthor], weights: RankingWeights) -> None: news_counts.append(author.news_count) patents_counts.append(author.patents_count) - frame = pd.DataFrame({ - "works": works_counts, - "citations": citations_counts, - "companies": companies_counts, - "news": news_counts, - "patents": patents_counts, - }) - quantile_value = 0.95 - - frame["works"] = frame["works"].clip(upper=frame["works"].quantile(quantile_value)) - frame["citations"] = frame["citations"].clip(upper=frame["citations"].quantile(quantile_value)) - frame["companies"] = frame["companies"].clip(upper=frame["companies"].quantile(quantile_value)) - frame["news"] = frame["news"].clip(upper=frame["news"].quantile(quantile_value)) - frame["patents"] = frame["patents"].clip(upper=frame["patents"].quantile(quantile_value)) - - works_normalized = _min_max_normalize(frame["works"]) - citations_normalized = _min_max_normalize(frame["citations"]) - companies_normalized = _min_max_normalize(frame["companies"]) - news_normalized = _min_max_normalize(frame["news"]) - patents_normalized = _min_max_normalize(frame["patents"]) - - scores = ( - works_normalized * weights.works - + citations_normalized * weights.citation - + companies_normalized * weights.companies - + news_normalized * weights.news - + patents_normalized * weights.patents - ) + metrics = [ + works_counts, + citations_counts, + companies_counts, + news_counts, + patents_counts, + ] + normalized_metrics = [ + _min_max_normalize( + [min(value, _quantile(values, quantile_value)) for value in values] + ) + for values in metrics + ] for index, author in enumerate(authors): - author.score = float(scores.iloc[index]) + author.score = float( + normalized_metrics[0][index] * weights.works + + normalized_metrics[1][index] * weights.citation + + normalized_metrics[2][index] * weights.companies + + normalized_metrics[3][index] * weights.news + + normalized_metrics[4][index] * weights.patents + ) def _author_score(author: RankedAuthor) -> float: From 06f34bec45c2b9b2998601195ed05a0e39f79383 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mats=20Paul=20Ton=C4=8Dik?= Date: Tue, 4 Aug 2026 10:28:12 +0200 Subject: [PATCH 040/114] fix(projects): removed project tabs from institution and person detail page for foreign entities --- service/src/main/inse/auth/router.py | 29 +++- service/src/main/inse/auth/service.py | 67 ++++++++ webapp/src/app/api/api/auth.service.ts | 65 ++++++++ webapp/src/app/app.routes.ts | 8 +- .../institution/institution.component.html | 8 +- .../institution/institution.component.ts | 89 +++++------ .../app/modules/person/person.component.ts | 148 ++++++++++-------- .../can-fetch-gdpr-relevant-data.resolver.ts | 10 ++ .../app-author-card.component.html | 20 +-- .../app-author-card.component.ts | 26 ++- 10 files changed, 332 insertions(+), 138 deletions(-) create mode 100644 webapp/src/app/resolvers/can-fetch-gdpr-relevant-data.resolver.ts diff --git a/service/src/main/inse/auth/router.py b/service/src/main/inse/auth/router.py index 9bf5d85a..4bb2ab31 100644 --- a/service/src/main/inse/auth/router.py +++ b/service/src/main/inse/auth/router.py @@ -2,7 +2,7 @@ import logging import uuid from typing import Annotated -from fastapi import APIRouter, Body, Depends, Response, status +from fastapi import APIRouter, Body, Depends, Query, Response, status from sqlmodel import Session import inse.auth.service as auth_service @@ -204,3 +204,30 @@ async def change_password( current_password=current_password, new_password=new_password, ) + + +@router.get( + "/can-fetch-gdpr-relevant-data", + summary="Check if user can fetch GDPR-relevant data", + description="Check if the authenticated user can fetch GDPR-relevant data for a given author and institution.", + operation_id="canFetchGdprRelevantData", +) +async def can_fetch_gdpr_relevant_data( + access_token: Annotated[ + AccessTokenMetadata, + auth_service.CurrentUserAccessTokenPayloadDep, + ], + raw_oa_author_id: Annotated[ + str | None, + Query(description="OpenAlex author ID to check access for"), + ] = None, + raw_oa_institution_id: Annotated[ + str | None, + Query(description="OpenAlex institution ID to check access for"), + ] = None, +) -> bool: + return await auth_service.can_fetch_gdpr_relevant_data( + access_token=access_token, + raw_oa_author_id=raw_oa_author_id, + raw_oa_institution_id=raw_oa_institution_id, + ) diff --git a/service/src/main/inse/auth/service.py b/service/src/main/inse/auth/service.py index 9ce83f9c..4898ebef 100644 --- a/service/src/main/inse/auth/service.py +++ b/service/src/main/inse/auth/service.py @@ -31,6 +31,7 @@ from inse.auth.model import ( effective_role_for_roles, normalize_roles, ) +from inse.authors.v2 import service as authors_service from inse.config import get_settings from inse.database import get_session @@ -1451,3 +1452,69 @@ def change_password( logger.info("Password changed successfully for account %s", account.id) return {"status": "ok"} + + +async def can_fetch_gdpr_relevant_data( + access_token: AccessTokenMetadata, + raw_oa_author_id: str | None = None, + raw_oa_institution_id: str | None = None, +) -> bool: + """Returns True if the user associated with the provided access token is allowed to fetch GDPR-relevant data for the specified OpenAlex author ID and institution ID, based on their effective institution ID. + + Args: + access_token (AccessTokenMetadata): The access token for the user. + raw_oa_author_id (str | None, optional): The OpenAlex author ID for which to check access. Defaults to None. + raw_oa_institution_id (str | None, optional): The OpenAlex institution ID for which to check access. Defaults to None. + + Returns: + bool: True if the user is allowed to fetch GDPR-relevant data for the specified IDs, False otherwise. + """ + + logger.debug( + "Checking if user with effective institution ID %s can fetch GDPR-relevant data for author ID %s and institution ID %s", + access_token.effective_institution_id, + raw_oa_author_id, + raw_oa_institution_id, + ) + + if not raw_oa_author_id and not raw_oa_institution_id: + logger.debug("No OpenAlex author ID or institution ID provided") + return False + + effective_institution_id = access_token.effective_institution_id + # Current user does not belong to any institution + if not effective_institution_id: + logger.debug( + "Current user does not belong to any institution, cannot fetch GDPR-relevant data" + ) + return False + + # Current user belongs to an institution, but the request is for a different institution + if ( + raw_oa_institution_id + and effective_institution_id + and raw_oa_institution_id != effective_institution_id + ): + logger.debug( + "Current user belongs to institution %s, but request is for institution %s, cannot fetch GDPR-relevant data", + effective_institution_id, + raw_oa_institution_id, + ) + return False + + # Current user belongs to an institution, but request is for author not belonging to that institution + if raw_oa_author_id: + author_belongs_to_institution = ( + await authors_service.author_currently_belongs_to_institution( + raw_oa_author_id or "", effective_institution_id + ) + ) + logger.debug( + "Author %s belongs to institution %s: %s", + raw_oa_author_id, + effective_institution_id, + author_belongs_to_institution, + ) + return author_belongs_to_institution + + return True diff --git a/webapp/src/app/api/api/auth.service.ts b/webapp/src/app/api/api/auth.service.ts index a906d12f..a53f4427 100644 --- a/webapp/src/app/api/api/auth.service.ts +++ b/webapp/src/app/api/api/auth.service.ts @@ -65,6 +65,71 @@ export class AuthService extends BaseService { super(basePath, configuration); } + /** + * Check if user can fetch GDPR-relevant data + * Check if the authenticated user can fetch GDPR-relevant data for a given author and institution. + * @endpoint get /api/auth/v2/can-fetch-gdpr-relevant-data + * @param rawOaAuthorId OpenAlex author ID to check access for + * @param rawOaInstitutionId OpenAlex institution ID to check access for + * @param secureFgpAcc + * @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 canFetchGdprRelevantData(rawOaAuthorId?: string, rawOaInstitutionId?: string, secureFgpAcc?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public canFetchGdprRelevantData(rawOaAuthorId?: string, rawOaInstitutionId?: string, secureFgpAcc?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public canFetchGdprRelevantData(rawOaAuthorId?: string, rawOaInstitutionId?: string, secureFgpAcc?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public canFetchGdprRelevantData(rawOaAuthorId?: string, rawOaInstitutionId?: string, secureFgpAcc?: string, 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, + rawOaAuthorId, 'raw_oa_author_id'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + rawOaInstitutionId, 'raw_oa_institution_id'); + + let localVarHeaders = this.defaultHeaders; + + // authentication (HTTPBearer) required + localVarHeaders = this.configuration.addCredentialToHeaders('HTTPBearer', 'Authorization', localVarHeaders, 'Bearer '); + + 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/auth/v2/can-fetch-gdpr-relevant-data`; + 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 + } + ); + } + /** * Change Password * Change the user\'s password and invalidate existing tokens. diff --git a/webapp/src/app/app.routes.ts b/webapp/src/app/app.routes.ts index d193f63e..de54257f 100644 --- a/webapp/src/app/app.routes.ts +++ b/webapp/src/app/app.routes.ts @@ -6,7 +6,6 @@ import { personPatentsResolver } from './resolvers/person-patents.resolver'; 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, RESOLVING_PROJECT_PAGE_FOR, @@ -65,6 +64,7 @@ import { topicQueryParamKeys, } from './resolvers/topic-page.resolver'; import { topicResolver } from './resolvers/topic.resolver'; +import { canFetchGdprRelevantDataResolver } from './resolvers/can-fetch-gdpr-relevant-data.resolver'; export const routes: Routes = [ { path: '', @@ -493,6 +493,7 @@ export const routes: Routes = [ personData: personResolver, personBio: personBioResolver, personPatents: personPatentsResolver, + canFetchGdprRelevantData: canFetchGdprRelevantDataResolver, }, runGuardsAndResolvers: (from, to) => from.params['id'] !== to.params['id'], children: [ @@ -658,7 +659,10 @@ export const routes: Routes = [ import('./modules/institution/institution.component').then( (mod) => mod.InstitutionComponent, ), - resolve: { institution: institutionResolver }, + resolve: { + institution: institutionResolver, + canFetchGdprRelevantData: canFetchGdprRelevantDataResolver, + }, children: [ { path: '', pathMatch: 'full', redirectTo: 'overview' }, { diff --git a/webapp/src/app/modules/institution/institution.component.html b/webapp/src/app/modules/institution/institution.component.html index 2024c855..ef072421 100644 --- a/webapp/src/app/modules/institution/institution.component.html +++ b/webapp/src/app/modules/institution/institution.component.html @@ -1,15 +1,15 @@
-

{{ institution.display_name }}

+

{{ institution().display_name }}

-

{{ institution.homepage_url }}

-

{{ institution.display_name_alternatives }}

+

{{ institution().homepage_url }}

+

{{ institution().display_name_alternatives }}

And many more useful details...

- + @if (this.links()) { + + } } @else { ; - disabled: boolean; -}; +import { + LinkTabNavBarComponent, + LinkTabNavBarItem, +} from '../../shared/ui/link-tab-nav-bar/link-tab-nav-bar.component'; +import { + COMPANY_CONNECTION_ICON, + FUNDING_ICON, + NETWORK_ICON, + NEWS_ICON, + OVERVIEW_ICON, + PATENT_ICON, + PROJECT_ICON, + PUBLICATION_ICON, +} from '../../shared/ui/icons'; @Component({ selector: 'app-person', @@ -55,6 +62,7 @@ type PersonLink = { LoadingComponent, CountryFlagComponent, CareerStageChipComponent, + LinkTabNavBarComponent, ], templateUrl: './person.component.html', styleUrl: './person.component.scss', @@ -69,6 +77,11 @@ export class PersonComponent { canFetchGdprRelevantData = input.required(); + protected readonly navBar = viewChild('navBar'); + protected readonly activeLink = computed( + () => this.navBar()?.activeLink() ?? null, + ); + constructor() { this.bookmarkService .load() @@ -236,11 +249,12 @@ export class PersonComponent { { initialValue: [] }, ); - readonly links = computed(() => { + readonly links = computed(() => { const links = [ { label: 'Übersicht', description: 'Übersicht über die Person', + icon: OVERVIEW_ICON, path: 'overview', disabled: false, }, @@ -249,6 +263,7 @@ export class PersonComponent { { label: 'Projekte', description: 'Übersicht der durchgeführten Projekte der Person', + icon: PROJECT_ICON, path: 'projects', queryParams: { page: 0, @@ -264,12 +279,13 @@ export class PersonComponent { { label: 'Publikationen', description: 'Übersicht der Publikationen der Person', + icon: PUBLICATION_ICON, path: 'publications', - disabled: false, }, { label: 'Netzwerk', description: 'Kooperationsnetzwerk der Person', + icon: NETWORK_ICON, path: 'network', disabled: false, queryParams: { @@ -284,6 +300,7 @@ export class PersonComponent { { label: 'Unternehmen', description: 'Unternehmen, mit denen die Person verbunden ist', + icon: COMPANY_CONNECTION_ICON, path: 'company-connections', disabled: false, }, @@ -292,18 +309,21 @@ export class PersonComponent { { label: 'Förderungen', description: 'Übersicht der Förderungen der Person', + icon: FUNDING_ICON, path: 'funding', disabled: false, }, { label: 'Nachrichten', description: 'Nachrichten über die Person', + icon: NEWS_ICON, path: 'news', disabled: false, }, { label: 'Patente', description: 'Patente der Person', + icon: PATENT_ICON, path: 'patents', disabled: false, }, @@ -311,25 +331,25 @@ export class PersonComponent { return links; }); - readonly activeLink = computed(() => { - const currentUrl = this.currentUrl(); - if (!currentUrl) { - return null; - } + // readonly activeLink = computed(() => { + // const currentUrl = this.currentUrl(); + // if (!currentUrl) { + // return null; + // } - for (const link of this.links()) { - const linkUrl = this.router - .createUrlTree([link.path], { - relativeTo: this.activatedRoute, - }) - .toString(); + // for (const link of this.links()) { + // const linkUrl = this.router + // .createUrlTree([link.path], { + // relativeTo: this.activatedRoute, + // }) + // .toString(); - if (linkUrl.startsWith(currentUrl) || currentUrl.startsWith(linkUrl)) { - return link; - } - } - return null; - }); + // if (linkUrl.startsWith(currentUrl) || currentUrl.startsWith(linkUrl)) { + // return link; + // } + // } + // return null; + // }); onInterestingTagClick(selection: { id: string; diff --git a/webapp/src/app/shared/ui/app-menu/app-menu.component.ts b/webapp/src/app/shared/ui/app-menu/app-menu.component.ts index fa0072f3..52d86a73 100644 --- a/webapp/src/app/shared/ui/app-menu/app-menu.component.ts +++ b/webapp/src/app/shared/ui/app-menu/app-menu.component.ts @@ -17,6 +17,21 @@ import { topicQueryParamKeys } from '../../../resolvers/topic-page.resolver'; import { SortDirection, TopicSortBy, WorkSortBy } from '../../../api'; import { workQueryParamKeys } from '../../../resolvers/work-page.resolver'; import { MatMenuModule } from '@angular/material/menu'; +import { + BOOKMARKS_ICON, + DASHBOARD_ICON, + INSTITUTION_ICON, + JOBS_ICON, + KEYWORDS_ICON, + MANAGE_ACCOUNTS_ICON, + NEWS_ICON, + ORGANIZATIONS_ICON, + PATENT_ICON, + PERSONS_ICON, + PROJECT_ICON, + PUBLICATION_ICON, + TOPIC_ICON, +} from '../icons'; type NavItem = { label: string; @@ -71,13 +86,13 @@ export class AppMenuComponent { const items: NavItem[] = [ { label: 'Dashboard', - icon: 'dashboard', + icon: DASHBOARD_ICON, route: '/dashboard', disabled: false, }, { label: 'Personen', - icon: 'groups', + icon: PERSONS_ICON, route: '/persons', queryParams: activeInstitutionPersonListQueryParams( this.credentialService.effectiveInstitutionId(), @@ -87,19 +102,19 @@ export class AppMenuComponent { }, { label: 'Bookmarks', - icon: 'bookmarks', + icon: BOOKMARKS_ICON, route: '/bookmarks', disabled: false, }, { label: 'News', - icon: 'newspaper', + icon: NEWS_ICON, route: '/news', disabled: false, }, { label: 'Institutionen', - icon: 'apartment', + icon: INSTITUTION_ICON, route: '/institutions', disabled: false, queryParams: { @@ -112,7 +127,7 @@ export class AppMenuComponent { }, { label: 'Publikationen', - icon: 'menu_book', + icon: PUBLICATION_ICON, route: '/publications', disabled: false, queryParams: { @@ -125,7 +140,7 @@ export class AppMenuComponent { }, { label: 'Themen', - icon: 'topic', + icon: TOPIC_ICON, route: '/topics', disabled: false, queryParams: { @@ -138,7 +153,7 @@ export class AppMenuComponent { }, { label: 'Projekte', - icon: 'work', + icon: PROJECT_ICON, route: '/projects', disabled: false, queryParams: { @@ -152,13 +167,13 @@ export class AppMenuComponent { }, { label: 'Patente', - icon: 'workspace_premium', + icon: PATENT_ICON, route: '/patents', disabled: false, }, { label: 'Keywords', - icon: 'join_left', + icon: KEYWORDS_ICON, route: '/keywords', disabled: false, queryParams: { @@ -167,21 +182,21 @@ export class AppMenuComponent { }, { label: 'Accounts', - icon: 'manage_accounts', + icon: MANAGE_ACCOUNTS_ICON, route: '/accounts', disabled: false, managerOrAdminOnly: true, }, { label: 'Organisationen', - icon: 'domain', + icon: ORGANIZATIONS_ICON, route: '/organizations', disabled: false, superAdminOnly: true, }, { label: 'Jobs', - icon: 'sync', + icon: JOBS_ICON, route: '/jobs', disabled: false, superAdminOnly: true, diff --git a/webapp/src/app/shared/ui/icons.ts b/webapp/src/app/shared/ui/icons.ts new file mode 100644 index 00000000..ed81f570 --- /dev/null +++ b/webapp/src/app/shared/ui/icons.ts @@ -0,0 +1,18 @@ +export const BOOKMARKS_ICON = "bookmarks" as const; +export const COMPANY_CONNECTION_ICON = 'business' as const; +export const DASHBOARD_ICON = 'dashboard' as const; +export const FUNDING_ICON = 'account_balance' as const; +export const INSTITUTION_ICON = 'school' as const; +export const JOBS_ICON = "sync" as const; +export const KEYWORDS_ICON = 'join_left' as const; +export const MANAGE_ACCOUNTS_ICON = 'manage_accounts' as const; +export const NETWORK_ICON = 'share' as const; +export const NEWS_ICON = 'newspaper' as const; +export const ORGANIZATIONS_ICON = 'domain' as const; +export const OVERVIEW_ICON = 'visibility' as const; +export const PATENT_ICON = 'workspace_premium' as const; +export const PERSONS_ICON = 'groups' as const; +export const PERSON_ICON = 'person' as const; +export const PROJECT_ICON = 'work' as const; +export const PUBLICATION_ICON = 'menu_book' as const; +export const TOPIC_ICON = 'topic' as const; \ No newline at end of file diff --git a/webapp/src/app/shared/ui/link-tab-nav-bar/link-tab-nav-bar.component.html b/webapp/src/app/shared/ui/link-tab-nav-bar/link-tab-nav-bar.component.html new file mode 100644 index 00000000..fa54da5b --- /dev/null +++ b/webapp/src/app/shared/ui/link-tab-nav-bar/link-tab-nav-bar.component.html @@ -0,0 +1,19 @@ + diff --git a/webapp/src/app/shared/ui/link-tab-nav-bar/link-tab-nav-bar.component.scss b/webapp/src/app/shared/ui/link-tab-nav-bar/link-tab-nav-bar.component.scss new file mode 100644 index 00000000..aaa131c5 --- /dev/null +++ b/webapp/src/app/shared/ui/link-tab-nav-bar/link-tab-nav-bar.component.scss @@ -0,0 +1,5 @@ +.link-tab-nav-bar-item { + display: flex; + align-items: center; + gap: 0.25rem; +} \ No newline at end of file diff --git a/webapp/src/app/shared/ui/link-tab-nav-bar/link-tab-nav-bar.component.ts b/webapp/src/app/shared/ui/link-tab-nav-bar/link-tab-nav-bar.component.ts new file mode 100644 index 00000000..3f87669d --- /dev/null +++ b/webapp/src/app/shared/ui/link-tab-nav-bar/link-tab-nav-bar.component.ts @@ -0,0 +1,50 @@ +import { Component, computed, inject, input } from '@angular/core'; +import { MatTabNavPanel, MatTabsModule } from '@angular/material/tabs'; +import { + ActivatedRoute, + isActive, + Router, + RouterModule, +} from '@angular/router'; +import { MatIconModule } from '@angular/material/icon'; + +export type LinkTabNavBarItem = { + label: string; + path: string; + icon?: string; + description?: string; + queryParams?: Record; + disabled?: boolean; +}; + +@Component({ + selector: 'app-link-tab-nav-bar', + imports: [MatTabsModule, RouterModule, MatIconModule], + templateUrl: './link-tab-nav-bar.component.html', + styleUrl: './link-tab-nav-bar.component.scss', +}) +export class LinkTabNavBarComponent { + private readonly router = inject(Router); + private readonly activatedRoute = inject(ActivatedRoute); + + links = input.required(); + tabPanel = input(); + + activeLink = computed(() => { + for (const link of this.links()) { + const linkUrlTree = this.router.createUrlTree([link.path], { + relativeTo: this.activatedRoute, + }); + + if ( + isActive(linkUrlTree, this.router, { + paths: 'subset', + queryParams: 'ignored', + })() + ) { + return link; + } + } + return null; + }); +} diff --git a/webapp/src/styles.scss b/webapp/src/styles.scss index fdcaec2f..95a45697 100644 --- a/webapp/src/styles.scss +++ b/webapp/src/styles.scss @@ -2,12 +2,11 @@ // For more information: https://material.angular.io/guide/theming @use '@angular/material' as mat; @use 'm3-theme' as m3; +@import url('https://fonts.googleapis.com/css2?family=Material+Symbols+Outlined:opsz,wght,FILL,GRAD@20..48,200..700,0..1,-50..200'); @include mat.elevation-classes(); @include mat.app-background(); -@import url('https://fonts.googleapis.com/css2?family=Material+Symbols+Outlined:opsz,wght,FILL,GRAD@20..48,200..700,0..1,-50..200'); - @font-face { font-display: swap; font-family: 'Montserrat'; From 6c55493acb9c382f4869cc597f62889883dd4fdd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mats=20Paul=20Ton=C4=8Dik?= Date: Tue, 4 Aug 2026 15:30:34 +0200 Subject: [PATCH 046/114] feat(topic, institution): reused generic link tab nav bar --- .../institution/institution.component.html | 36 +++++---------- .../institution/institution.component.scss | 12 +++-- .../institution/institution.component.ts | 45 +++++++++++-------- .../app/modules/topic/topic.component.html | 15 +------ .../src/app/modules/topic/topic.component.ts | 9 +++- 5 files changed, 56 insertions(+), 61 deletions(-) diff --git a/webapp/src/app/modules/institution/institution.component.html b/webapp/src/app/modules/institution/institution.component.html index ef072421..4b53e760 100644 --- a/webapp/src/app/modules/institution/institution.component.html +++ b/webapp/src/app/modules/institution/institution.component.html @@ -1,27 +1,15 @@ -
-

{{ institution().display_name }}

- - -

{{ institution().homepage_url }}

-

{{ institution().display_name_alternatives }}

-

And many more useful details...

-
-
- - +
+
+

{{ institution().display_name }}

+ + +

{{ institution().homepage_url }}

+

{{ institution().display_name_alternatives }}

+

And many more useful details...

+
+
+
+
diff --git a/webapp/src/app/modules/institution/institution.component.scss b/webapp/src/app/modules/institution/institution.component.scss index 2521fee5..0aae5047 100644 --- a/webapp/src/app/modules/institution/institution.component.scss +++ b/webapp/src/app/modules/institution/institution.component.scss @@ -1,6 +1,12 @@ -.content { - padding: 16px; +.container { display: flex; flex-direction: column; - gap: 16px; + gap: 1rem; +} + +.content { + display: flex; + flex-direction: column; + gap: 1rem; + margin: 0 1rem; } diff --git a/webapp/src/app/modules/institution/institution.component.ts b/webapp/src/app/modules/institution/institution.component.ts index 124b4f13..0edce91b 100644 --- a/webapp/src/app/modules/institution/institution.component.ts +++ b/webapp/src/app/modules/institution/institution.component.ts @@ -1,25 +1,21 @@ import { Component, computed, input } from '@angular/core'; -import { RouterLink, RouterOutlet, RouterLinkActive } from '@angular/router'; +import { RouterModule } from '@angular/router'; import { Institution } from '../../api'; import { MatCardModule } from '@angular/material/card'; import { MatTabsModule } from '@angular/material/tabs'; - -type TabLink = { - label: string; - path: string; - disabled: boolean; - queryParams?: Record; -}; +import { + LinkTabNavBarComponent, + LinkTabNavBarItem, +} from '../../shared/ui/link-tab-nav-bar/link-tab-nav-bar.component'; +import { + PATENT_ICON, + PROJECT_ICON, + PUBLICATION_ICON, +} from '../../shared/ui/icons'; @Component({ selector: 'app-institution', - imports: [ - MatCardModule, - MatTabsModule, - RouterLink, - RouterOutlet, - RouterLinkActive, - ], + imports: [MatCardModule, MatTabsModule, RouterModule, LinkTabNavBarComponent], templateUrl: './institution.component.html', styleUrl: './institution.component.scss', }) @@ -27,14 +23,20 @@ export class InstitutionComponent { institution = input.required(); canFetchGdprRelevantData = input.required(); - _links = computed(() => { - const links: TabLink[] = [ - { label: 'Publikationen', path: 'publications', disabled: false }, + _links = computed(() => { + const links: LinkTabNavBarItem[] = [ + { + label: 'Publikationen', + icon: PUBLICATION_ICON, + path: 'publications', + disabled: false, + }, ]; if (this.canFetchGdprRelevantData()) { links.push( { label: 'Projekte', + icon: PROJECT_ICON, path: 'projects', disabled: false, queryParams: { @@ -46,7 +48,12 @@ export class InstitutionComponent { sort_direction: 'asc', }, }, - { label: 'Patente', path: 'patents', disabled: false }, + { + label: 'Patente', + icon: PATENT_ICON, + path: 'patents', + disabled: false, + }, ); } return links; diff --git a/webapp/src/app/modules/topic/topic.component.html b/webapp/src/app/modules/topic/topic.component.html index fb4bc779..d75b8c70 100644 --- a/webapp/src/app/modules/topic/topic.component.html +++ b/webapp/src/app/modules/topic/topic.component.html @@ -31,21 +31,8 @@
+ -
diff --git a/webapp/src/app/modules/topic/topic.component.ts b/webapp/src/app/modules/topic/topic.component.ts index 38c102f6..306cbcb8 100644 --- a/webapp/src/app/modules/topic/topic.component.ts +++ b/webapp/src/app/modules/topic/topic.component.ts @@ -6,6 +6,11 @@ import { MatDividerModule } from '@angular/material/divider'; import { MatIconModule } from '@angular/material/icon'; import { DecimalPipe } from '@angular/common'; import { topicHierarchyColor } from '../../resolvers/utils/topic-colors'; +import { PUBLICATION_ICON } from '../../shared/ui/icons'; +import { + LinkTabNavBarComponent, + LinkTabNavBarItem, +} from '../../shared/ui/link-tab-nav-bar/link-tab-nav-bar.component'; @Component({ host: { @@ -18,6 +23,7 @@ import { topicHierarchyColor } from '../../resolvers/utils/topic-colors'; MatDividerModule, MatIconModule, DecimalPipe, + LinkTabNavBarComponent, ], templateUrl: './topic.component.html', styleUrl: './topic.component.scss', @@ -25,9 +31,10 @@ import { topicHierarchyColor } from '../../resolvers/utils/topic-colors'; export class TopicComponent { topic = input.required(); - links = [ + links: LinkTabNavBarItem[] = [ { label: 'Publikationen', + icon: PUBLICATION_ICON, path: 'publications', disabled: false, queryParams: { From 1d7a54c8663b3853c13eb648f53aa10b148fa3cb Mon Sep 17 00:00:00 2001 From: genja Date: Tue, 4 Aug 2026 19:29:17 +0200 Subject: [PATCH 047/114] institutes: fixed total results for publications table --- service/src/main/inse/works/v2/service.py | 1 + 1 file changed, 1 insertion(+) diff --git a/service/src/main/inse/works/v2/service.py b/service/src/main/inse/works/v2/service.py index f1fa10d2..20e139a8 100644 --- a/service/src/main/inse/works/v2/service.py +++ b/service/src/main/inse/works/v2/service.py @@ -654,6 +654,7 @@ async def _search_works( size=size, offset=page * size, sort=sort, + track_total_hits=True ) hits_block = response.get("hits", {}) From 7628f219e271261ed34eee309472537363c76dad Mon Sep 17 00:00:00 2001 From: genja Date: Tue, 4 Aug 2026 19:30:55 +0200 Subject: [PATCH 048/114] institutions: moved the fundings chart and projects table into exandable accordions --- .../institution-projects.component.html | 76 ++++++++++++------- .../institution-projects.component.scss | 34 +++++---- .../institution-projects.component.ts | 10 +-- 3 files changed, 70 insertions(+), 50 deletions(-) diff --git a/webapp/src/app/modules/institution-projects/institution-projects.component.html b/webapp/src/app/modules/institution-projects/institution-projects.component.html index 66a1bc1b..b5e22762 100644 --- a/webapp/src/app/modules/institution-projects/institution-projects.component.html +++ b/webapp/src/app/modules/institution-projects/institution-projects.component.html @@ -1,30 +1,15 @@
-

Projekte

+
+
Projekte
+

Übersicht der Projekte, die von der Institution durchgeführt werden.

+
-
-
- + + + + Förderung über Zeit + - - -
@@ -56,15 +41,48 @@ | currency: 'EUR' : 'symbol' : '1.0-0' : 'de') ?? undefined " />
-
-
+ + + + + Projektliste + + +
+ + + + + +
+
+ {{ row.funding_start | date: 'dd.MM.yyyy' }} @@ -79,8 +97,8 @@ open_in_new - + + Date: Tue, 4 Aug 2026 19:33:28 +0200 Subject: [PATCH 049/114] adjusted the description for publications table expansion panel --- .../institution-publications.component.html | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/webapp/src/app/modules/institution-publications/institution-publications.component.html b/webapp/src/app/modules/institution-publications/institution-publications.component.html index 864afd0b..6228de7e 100644 --- a/webapp/src/app/modules/institution-publications/institution-publications.component.html +++ b/webapp/src/app/modules/institution-publications/institution-publications.component.html @@ -16,8 +16,7 @@ Publikationsliste - {{ total() >= 10000 ? 'mehr als' : '' }} + {{ total() }} Publikationen From 62f0812aae459f506995e2d1e3b0e1000d3b616c Mon Sep 17 00:00:00 2001 From: genja Date: Tue, 4 Aug 2026 19:34:25 +0200 Subject: [PATCH 050/114] added optional disable/enable fitlers logic into resolvers, disabled filters for BUND und EU fundings --- webapp/src/app/app.routes.ts | 16 +-- .../bund-projects-funding.resolver.ts | 15 +++ .../cordis-eu-projects-funding.resolver.ts | 124 +++++++++++------- 3 files changed, 94 insertions(+), 61 deletions(-) diff --git a/webapp/src/app/app.routes.ts b/webapp/src/app/app.routes.ts index 40deb417..0f4bec64 100644 --- a/webapp/src/app/app.routes.ts +++ b/webapp/src/app/app.routes.ts @@ -693,7 +693,9 @@ export const routes: Routes = [ bundProjectsFunding: bundProjectsFundingResolver, cordisEuProjectsFunding: cordisEuProjectsFundingResolver, }, - runGuardsAndResolvers: 'always', + data: { + enableFilters: false, + }, children: [ { path: '', @@ -743,18 +745,6 @@ export const routes: Routes = [ }, }, ], - // resolve: { - // bundProjectPage: bundProjectPageResolver, - // bundProjectsFunding: bundProjectsFundingResolver, - // cordisEuProjectPage: euCordisProjectsResolver, - // cordisEuProjectsFunding: cordisEuProjectsFundingResolver, - // }, - // runGuardsAndResolvers: (from, to) => { - // const keys = ['page', 'size', 'sort_by', 'sort_direction', 'search']; - // return keys.some( - // (key) => from.queryParamMap.get(key) !== to.queryParamMap.get(key), - // ); - // }, }, { path: 'patents', diff --git a/webapp/src/app/resolvers/bund-projects-funding.resolver.ts b/webapp/src/app/resolvers/bund-projects-funding.resolver.ts index df29c79d..3f501c67 100644 --- a/webapp/src/app/resolvers/bund-projects-funding.resolver.ts +++ b/webapp/src/app/resolvers/bund-projects-funding.resolver.ts @@ -15,7 +15,22 @@ export const bundProjectsFundingResolver: ResolveFn< 'Institution ID is required to resolve BUND projects funding', ); } + const filtersEnabled = route.data['enableFilters'] ?? false; + if (!filtersEnabled) { + return inject(ProjectsService).getInstitutionBundProjectsFundingOverTime( + institutionId, + [], + [], + undefined, + [], + [], + [], + [], + [], + undefined, + ); + } const fundingStartYears = route.queryParamMap.getAll( bundProjectQueryParamKeys.funding_start, ); diff --git a/webapp/src/app/resolvers/cordis-eu-projects-funding.resolver.ts b/webapp/src/app/resolvers/cordis-eu-projects-funding.resolver.ts index 0e60a95b..0ea05f87 100644 --- a/webapp/src/app/resolvers/cordis-eu-projects-funding.resolver.ts +++ b/webapp/src/app/resolvers/cordis-eu-projects-funding.resolver.ts @@ -15,62 +15,90 @@ export const cordisEuProjectsFundingResolver: ResolveFn< 'Institution ID is required to resolve Cordis EU projects funding', ); } + const filtersEnabled = route.data['enableFilters'] ?? false; + if (!filtersEnabled) { + return inject( + ProjectsService, + ).getInstitutionCordisEuProjectsFundingOverTime( + institutionId, + undefined, // authorId (single) - institution view doesn't use this + [], + [], + [], + [], + undefined, + [], + [], + [], + [], + [], + [], + [], + [], + [], + undefined, + ); + } else { + const searchTerm = + route.queryParamMap.get(euProjectQueryParamKeys.title) ?? undefined; - const searchTerm = - route.queryParamMap.get(euProjectQueryParamKeys.title) ?? undefined; + const fundingStart = route.queryParamMap.getAll( + euProjectQueryParamKeys.funding_start, + ); + const fundingEnd = route.queryParamMap.getAll( + euProjectQueryParamKeys.funding_end, + ); - const fundingStart = route.queryParamMap.getAll( - euProjectQueryParamKeys.funding_start, - ); - const fundingEnd = route.queryParamMap.getAll( - euProjectQueryParamKeys.funding_end, - ); + const filteredTopicIds = route.queryParamMap.getAll( + euProjectQueryParamKeys.topicId, + ); - const filteredTopicIds = route.queryParamMap.getAll( - euProjectQueryParamKeys.topicId, - ); + const projectTypes = route.queryParamMap.getAll( + euProjectQueryParamKeys.projectType, + ); - const projectTypes = route.queryParamMap.getAll( - euProjectQueryParamKeys.projectType, - ); + const organizationIds = route.queryParamMap.getAll( + euProjectQueryParamKeys.institutionId, + ); - const organizationIds = route.queryParamMap.getAll( - euProjectQueryParamKeys.institutionId, - ); + const authorIds = route.queryParamMap + .getAll(euProjectQueryParamKeys.authorId) + .map((id) => id.split('/').pop() || id); - const authorIds = route.queryParamMap - .getAll(euProjectQueryParamKeys.authorId) - .map((id) => id.split('/').pop() || id); + const countries = route.queryParamMap.getAll( + euProjectQueryParamKeys.country, + ); - const countries = route.queryParamMap.getAll(euProjectQueryParamKeys.country); + const frameworkProgrammes = route.queryParamMap.getAll( + euProjectQueryParamKeys.frameworkProgramme, + ); - const frameworkProgrammes = route.queryParamMap.getAll( - euProjectQueryParamKeys.frameworkProgramme, - ); + const fundingSchemes = route.queryParamMap.getAll( + euProjectQueryParamKeys.fundingScheme, + ); - const fundingSchemes = route.queryParamMap.getAll( - euProjectQueryParamKeys.fundingScheme, - ); + const statuses = route.queryParamMap.getAll(euProjectQueryParamKeys.status); - const statuses = route.queryParamMap.getAll(euProjectQueryParamKeys.status); - - return inject(ProjectsService).getInstitutionCordisEuProjectsFundingOverTime( - institutionId, - undefined, // authorId (single) - institution view doesn't use this - authorIds, - organizationIds, - [], // organizationNames - projectTypes as any, - searchTerm, - [], // keywords - institution view doesn't use free-text keywords - [], // topicIds (fuzzy) - institution view doesn't use fuzzy topic search - filteredTopicIds, - fundingStart, - fundingEnd, - countries, - frameworkProgrammes, - fundingSchemes, - statuses, - false, // fuzzy - ); + return inject( + ProjectsService, + ).getInstitutionCordisEuProjectsFundingOverTime( + institutionId, + undefined, // authorId (single) - institution view doesn't use this + authorIds, + organizationIds, + [], // organizationNames + projectTypes as any, + searchTerm, + [], // keywords - institution view doesn't use free-text keywords + [], // topicIds (fuzzy) - institution view doesn't use fuzzy topic search + filteredTopicIds, + fundingStart, + fundingEnd, + countries, + frameworkProgrammes, + fundingSchemes, + statuses, + false, // fuzzy + ); + } }; From d06c1954a50e219a0fc19a5e267bec68b4dc8aa8 Mon Sep 17 00:00:00 2001 From: Khuder Khalti Date: Tue, 4 Aug 2026 20:36:33 +0200 Subject: [PATCH 051/114] feat(person-funding, person-patents, institution-patents, keywords-patents): add sortable column headers and refine inventor/assignee chip styling --- .../institution-patents.component.html | 137 ++++++++++++++++-- .../institution-patents.component.scss | 86 +++++++++-- .../institution-patents.component.ts | 114 +++++++++++---- .../keywords-patents.component.html | 122 ++++++++++++++-- .../keywords-patents.component.scss | 106 +++++++++----- .../keywords-patents.component.ts | 88 ++++++++--- .../person-funding.component.html | 71 +++++++-- .../person-funding.component.scss | 35 +++-- .../person-funding.component.ts | 80 +++++++--- .../person-patents.component.html | 114 +++++++++++++-- .../person-patents.component.scss | 90 ++++++++++-- .../person-patents.component.ts | 95 +++++++++--- 12 files changed, 942 insertions(+), 196 deletions(-) diff --git a/webapp/src/app/modules/institution-patents/institution-patents.component.html b/webapp/src/app/modules/institution-patents/institution-patents.component.html index 290cf522..fbb05df2 100644 --- a/webapp/src/app/modules/institution-patents/institution-patents.component.html +++ b/webapp/src/app/modules/institution-patents/institution-patents.component.html @@ -54,11 +54,13 @@ subscriptSizing="dynamic"> + [value]="sortColumn" + (selectionChange)="setSort($event.value)"> Sortieren nach - Datum + Jahr Titel + Quelle + Match-Typ
@@ -67,11 +69,41 @@ Patent - Quelle - Jahr + + Quelle + @if (sortColumn === 'source') { + {{ + sortDirection === 'asc' ? 'arrow_upward' : 'arrow_downward' + }} + } + + + Jahr + @if (sortColumn === 'year') { + {{ + sortDirection === 'asc' ? 'arrow_upward' : 'arrow_downward' + }} + } + Erfinder Applicant/Assignee - Match-Typ + + Match-Typ + @if (sortColumn === 'matchType') { + {{ + sortDirection === 'asc' ? 'arrow_upward' : 'arrow_downward' + }} + } + Personen @@ -94,9 +126,86 @@ {{ patent.source }} - {{ patent.publication_year ?? '-' }} - {{ getInventorsPreview(patent) }} - {{ getAssigneesPreview(patent) }} + + @if (patent.publication_year) { + {{ + patent.publication_year + }} + } @else { + - + } + + + @if (patent.inventors && patent.inventors.length) { +
+ @for ( + inventor of patent.inventors.slice(0, 2); + track inventor + ) { + + person + {{ inventor }} + + } + @if (patent.inventors.length > 2) { + + + person + {{ patent.inventors[2] }} + + @if (patent.inventors.length > 3) { + +{{ patent.inventors.length - 3 }} + } + + } +
+ } @else { + - + } + + + @if (patent.assignees && patent.assignees.length) { +
+ @for ( + assignee of patent.assignees.slice(0, 2); + track assignee + ) { + + {{ + isAssigneeLikelyPerson(assignee, patent) + ? 'person' + : 'apartment' + }} + {{ assignee }} + + } + @if (patent.assignees.length > 2) { + + + {{ + isAssigneeLikelyPerson( + patent.assignees[2], + patent + ) + ? 'person' + : 'apartment' + }} + {{ patent.assignees[2] }} + + @if (patent.assignees.length > 3) { + +{{ patent.assignees.length - 3 }} + } + + } +
+ } @else { + - + } + @@ -118,6 +227,10 @@ '/person', author.openalex_author_id, ]" + [appComponentTooltip]="AuthorTooltipComponent" + [tooltipInputs]="{ + authorId: author.openalex_author_id, + }" (click)="$event.stopPropagation()"> {{ author.author_name }}
@@ -197,7 +310,11 @@
  • + [routerLink]="['/person', author.openalex_author_id]" + [appComponentTooltip]="AuthorTooltipComponent" + [tooltipInputs]="{ + authorId: author.openalex_author_id, + }"> {{ author.author_name }}
  • diff --git a/webapp/src/app/modules/institution-patents/institution-patents.component.scss b/webapp/src/app/modules/institution-patents/institution-patents.component.scss index 4b3fdb39..c0827596 100644 --- a/webapp/src/app/modules/institution-patents/institution-patents.component.scss +++ b/webapp/src/app/modules/institution-patents/institution-patents.component.scss @@ -66,9 +66,24 @@ app-query-param-paginator { text-align: left; padding: 12px 16px; border-bottom: 1px solid var(--sg-border); - font-size: 13px; - font-weight: 600; + font-size: 12px; + font-weight: 700; color: var(--sg-text-muted); + + &.sortable { + display: table-cell; + cursor: pointer; + -webkit-user-select: none; + user-select: none; + } + + .sort-icon { + vertical-align: middle; + margin-left: 2px; + width: 14px; + height: 14px; + font-size: 14px; + } } tr { @@ -101,13 +116,8 @@ app-query-param-paginator { word-break: break-word; } - .cell-preview { - max-width: 160px; - white-space: nowrap; - overflow: hidden; - text-overflow: ellipsis; - color: var(--sg-text-muted); - font-size: 13px; + .patent-people { + max-width: 220px; } .cell-authors { @@ -119,6 +129,64 @@ app-query-param-paginator { } } +.year-badge { + display: inline-flex; + align-items: center; + justify-content: center; + min-width: 26px; + padding: 2px 10px; + border-radius: 999px; + border: 1px solid var(--sg-border); + color: var(--sg-text); + font-size: 0.8rem; + font-weight: 600; +} + +.person-chips { + display: flex; + flex-direction: column; + align-items: flex-start; + gap: 4px; +} + +.person-chip-row { + display: flex; + flex-direction: row; + align-items: center; + flex-wrap: wrap; + gap: 4px; +} + +.person-chip { + display: inline-flex; + align-items: center; + gap: 4px; + max-width: 100%; + padding: 2px 8px; + border: 1px solid var(--sg-border); + border-radius: var(--sg-radius-sm); + background: var(--sg-surface-soft); + color: var(--sg-text); + font-size: 0.75rem; + line-height: 1.4; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; + + mat-icon { + flex-shrink: 0; + width: 14px; + height: 14px; + font-size: 14px; + color: var(--sg-text-soft); + } + + &--more { + color: var(--sg-text-muted); + font-weight: 600; + } +} + .match-badge { display: inline-flex; align-items: center; diff --git a/webapp/src/app/modules/institution-patents/institution-patents.component.ts b/webapp/src/app/modules/institution-patents/institution-patents.component.ts index 196200d0..ea75813b 100644 --- a/webapp/src/app/modules/institution-patents/institution-patents.component.ts +++ b/webapp/src/app/modules/institution-patents/institution-patents.component.ts @@ -13,8 +13,11 @@ import { import { LoadingComponent } from '../../shared/ui/loading/loading.component'; import { PageEvent } from '@angular/material/paginator'; import { QueryParamPaginatorComponent } from '../../shared/ui/query-param-paginator/query-param-paginator.component'; +import { ComponentTooltipDirective } from '../../directives/component-tooltip.directive'; +import { AppAuthorTooltipComponent } from '../../shared/ui/app-author-tooltip/app-author-tooltip.component'; -type SortMode = 'date' | 'title'; +type SortColumn = 'title' | 'year' | 'source' | 'matchType'; +type SortDirection = 'asc' | 'desc'; type SourceFilter = 'all' | 'EPO' | 'USPTO'; type OrgPatentMatchTypeFilter = 'all' | 'institution' | 'name' | 'both'; @@ -28,11 +31,13 @@ type OrgPatentMatchTypeFilter = 'all' | 'institution' | 'name' | 'both'; MatSelectModule, MatIconModule, QueryParamPaginatorComponent, + ComponentTooltipDirective, ], templateUrl: './institution-patents.component.html', styleUrl: './institution-patents.component.scss', }) export class InstitutionPatentsComponent implements OnInit { + readonly AuthorTooltipComponent = AppAuthorTooltipComponent; private route = inject(ActivatedRoute); private router = inject(Router); private patentsApi = inject(PatentsService); @@ -48,7 +53,8 @@ export class InstitutionPatentsComponent implements OnInit { activeFilter: SourceFilter = 'all'; activeMatchType: OrgPatentMatchTypeFilter = 'all'; - sortMode: SortMode = 'date'; + sortColumn: SortColumn = 'year'; + sortDirection: SortDirection = 'desc'; pageIndex = 0; pageSize = 20; @@ -59,7 +65,8 @@ export class InstitutionPatentsComponent implements OnInit { const institutionId = params.get('institutionId') ?? ''; const filterFromUrl = this.route.snapshot.queryParamMap.get('filter'); - const sortFromUrl = this.route.snapshot.queryParamMap.get('sortBy'); + const sortByFromUrl = this.route.snapshot.queryParamMap.get('sortBy'); + const sortDirFromUrl = this.route.snapshot.queryParamMap.get('sortDir'); const matchTypeFromUrl = this.route.snapshot.queryParamMap.get('matchType'); this.pageIndex = this.parsePageIndexParam( @@ -72,8 +79,11 @@ export class InstitutionPatentsComponent implements OnInit { if (this.isValidFilter(filterFromUrl)) { this.activeFilter = filterFromUrl; } - if (this.isValidSortMode(sortFromUrl)) { - this.sortMode = sortFromUrl; + if (this.isValidSortColumn(sortByFromUrl)) { + this.sortColumn = sortByFromUrl; + } + if (this.isValidSortDirection(sortDirFromUrl)) { + this.sortDirection = sortDirFromUrl; } if (this.isValidMatchType(matchTypeFromUrl)) { this.activeMatchType = matchTypeFromUrl; @@ -101,8 +111,13 @@ export class InstitutionPatentsComponent implements OnInit { this.reloadPatents(); } - setSortMode(sortMode: SortMode): void { - this.sortMode = sortMode; + setSort(column: SortColumn): void { + if (this.sortColumn === column) { + this.sortDirection = this.sortDirection === 'asc' ? 'desc' : 'asc'; + } else { + this.sortColumn = column; + this.sortDirection = column === 'year' ? 'desc' : 'asc'; + } this.filteredPatents = this.sortPatents(this.patents); this.updateQueryParams(); } @@ -168,14 +183,27 @@ export class InstitutionPatentsComponent implements OnInit { } private sortPatents(patents: OrgPatentEntry[]): OrgPatentEntry[] { - if (this.sortMode === 'title') { - return [...patents].sort((a, b) => - (a.title ?? '').localeCompare(b.title ?? '', 'de', { - sensitivity: 'base', - }), - ); - } - return [...patents]; + const direction = this.sortDirection === 'asc' ? 1 : -1; + return [...patents].sort((a, b) => { + switch (this.sortColumn) { + case 'year': { + const yearA = a.publication_date ?? String(a.publication_year ?? ''); + const yearB = b.publication_date ?? String(b.publication_year ?? ''); + return direction * yearA.localeCompare(yearB); + } + case 'source': + return direction * a.source.localeCompare(b.source); + case 'matchType': + return direction * a.match_type.localeCompare(b.match_type); + default: + return ( + direction * + (a.title ?? '').localeCompare(b.title ?? '', 'de', { + sensitivity: 'base', + }) + ); + } + }); } private updateQueryParams(): void { @@ -183,7 +211,8 @@ export class InstitutionPatentsComponent implements OnInit { relativeTo: this.route, queryParams: { filter: this.activeFilter, - sortBy: this.sortMode, + sortBy: this.sortColumn, + sortDir: this.sortDirection, matchType: this.activeMatchType, page: this.pageIndex, size: this.pageSize, @@ -207,8 +236,17 @@ export class InstitutionPatentsComponent implements OnInit { return value === 'all' || value === 'EPO' || value === 'USPTO'; } - private isValidSortMode(value: string | null): value is SortMode { - return value === 'date' || value === 'title'; + private isValidSortColumn(value: string | null): value is SortColumn { + return ( + value === 'title' || + value === 'year' || + value === 'source' || + value === 'matchType' + ); + } + + private isValidSortDirection(value: string | null): value is SortDirection { + return value === 'asc' || value === 'desc'; } private isValidMatchType( @@ -287,18 +325,40 @@ export class InstitutionPatentsComponent implements OnInit { } } - getInventorsPreview(patent: OrgPatentEntry): string { - if (!patent.inventors?.length) { - return '-'; - } - return patent.inventors.slice(0, 2).join(', '); + private static readonly ORG_SUFFIX_PATTERN = + /\b(Inc|Ltd|LLC|LLP|GmbH|Corp(oration)?|Co|KG|AG|SE|S\.?A\.?|N\.?V\.?|B\.?V\.?|PLC|Universit(y|ät|é)|Institut(e)?|Foundation|Laborator(y|ies)|Labs?|Group|Holdings?|Company|Gesellschaft)\b\.?/i; + private static readonly PERSON_SUFFIX_PATTERN = + /\b(Dr|Prof|PhD|Ph\.D|M\.D|Jr|Sr)\b\.?/i; + + private normalizeNameForComparison(name: string): string { + return name + .normalize('NFD') + .replace(/[̀-ͯ]/g, '') + .replace(/[.,]/g, '') + .toUpperCase() + .split(/\s+/) + .filter(Boolean) + .sort() + .join(' '); } - getAssigneesPreview(patent: OrgPatentEntry): string { - if (!patent.assignees?.length) { - return '-'; + isAssigneeLikelyPerson(assignee: string, patent: OrgPatentEntry): boolean { + if (InstitutionPatentsComponent.ORG_SUFFIX_PATTERN.test(assignee)) { + return false; } - return patent.assignees.slice(0, 2).join(', '); + + const normalizedAssignee = this.normalizeNameForComparison( + assignee.replace(InstitutionPatentsComponent.PERSON_SUFFIX_PATTERN, ''), + ); + const matchesInventor = (patent.inventors ?? []).some( + (inventor) => + this.normalizeNameForComparison(inventor) === normalizedAssignee, + ); + if (matchesInventor) { + return true; + } + + return InstitutionPatentsComponent.PERSON_SUFFIX_PATTERN.test(assignee); } getMatchedAuthorsPreview(patent: OrgPatentEntry): string { diff --git a/webapp/src/app/modules/keywords-search/keywords-patents/keywords-patents.component.html b/webapp/src/app/modules/keywords-search/keywords-patents/keywords-patents.component.html index 20d2eef7..838a42ad 100644 --- a/webapp/src/app/modules/keywords-search/keywords-patents/keywords-patents.component.html +++ b/webapp/src/app/modules/keywords-search/keywords-patents/keywords-patents.component.html @@ -31,11 +31,12 @@ subscriptSizing="dynamic"> + [value]="sortColumn()" + (selectionChange)="setSort($event.value)"> Sortieren nach - Datum + Jahr Titel + Quelle @@ -44,8 +45,32 @@ Patent - Quelle - Jahr + + Quelle + @if (sortColumn() === 'source') { + {{ + sortDirection() === 'asc' + ? 'arrow_upward' + : 'arrow_downward' + }} + } + + + Jahr + @if (sortColumn() === 'year') { + {{ + sortDirection() === 'asc' + ? 'arrow_upward' + : 'arrow_downward' + }} + } + Erfinder Anmelder @@ -66,16 +91,85 @@ {{ item.patent.source }} - {{ item.patent.publication_year ?? '-' }} - - {{ getInventorsLabel(item.patent) }} + + @if (item.patent.publication_year) { + {{ + item.patent.publication_year + }} + } @else { + - + } - - {{ getAssigneesLabel(item.patent) }} + + @if (item.patent.inventors && item.patent.inventors.length) { +
    + @for ( + inventor of item.patent.inventors.slice(0, 2); + track inventor + ) { + + person + {{ inventor }} + + } + @if (item.patent.inventors.length > 2) { + + + person + {{ item.patent.inventors[2] }} + + @if (item.patent.inventors.length > 3) { + +{{ item.patent.inventors.length - 3 }} + } + + } +
    + } @else { + - + } + + + @if (item.patent.assignees && item.patent.assignees.length) { +
    + @for ( + assignee of item.patent.assignees.slice(0, 2); + track assignee + ) { + + {{ + isAssigneeLikelyPerson(assignee, item.patent) + ? 'person' + : 'apartment' + }} + {{ assignee }} + + } + @if (item.patent.assignees.length > 2) { + + + {{ + isAssigneeLikelyPerson( + item.patent.assignees[2], + item.patent + ) + ? 'person' + : 'apartment' + }} + {{ item.patent.assignees[2] }} + + @if (item.patent.assignees.length > 3) { + +{{ item.patent.assignees.length - 3 }} + } + + } +
    + } @else { + - + } } diff --git a/webapp/src/app/modules/keywords-search/keywords-patents/keywords-patents.component.scss b/webapp/src/app/modules/keywords-search/keywords-patents/keywords-patents.component.scss index a8ddbb74..75c648eb 100644 --- a/webapp/src/app/modules/keywords-search/keywords-patents/keywords-patents.component.scss +++ b/webapp/src/app/modules/keywords-search/keywords-patents/keywords-patents.component.scss @@ -97,9 +97,24 @@ app-query-param-paginator { text-align: left; padding: 12px 16px; border-bottom: 1px solid var(--sg-border); - font-size: 13px; - font-weight: 600; + font-size: 12px; + font-weight: 700; color: var(--sg-text-muted); + + &.sortable { + display: table-cell; + cursor: pointer; + -webkit-user-select: none; + user-select: none; + } + + .sort-icon { + vertical-align: middle; + margin-left: 2px; + width: 14px; + height: 14px; + font-size: 14px; + } } tr { @@ -133,41 +148,66 @@ app-query-param-paginator { .patent-people { max-width: 220px; - color: var(--sg-text-muted); - white-space: nowrap; - overflow: hidden; - text-overflow: ellipsis; } } - - th { - text-align: left; - padding: 10px 12px; - border-bottom: 2px solid var(--sg-border); - color: var(--sg-text); - } - - tr { - cursor: pointer; - color: var(--sg-text); - - &:hover { - background: var(--sg-surface-soft); - } - - &.selected { - background: var(--sg-surface-muted); - } - } - - td { - padding: 10px 12px; - border-bottom: 1px solid var(--sg-border); - } } -.patent-title { - font-weight: 500; +.year-badge { + display: inline-flex; + align-items: center; + justify-content: center; + min-width: 26px; + padding: 2px 10px; + border-radius: 999px; + border: 1px solid var(--sg-border); + color: var(--sg-text); + font-size: 0.8rem; + font-weight: 600; +} + +.person-chips { + display: flex; + flex-direction: column; + align-items: flex-start; + gap: 4px; +} + +.person-chip-row { + display: flex; + flex-direction: row; + align-items: center; + flex-wrap: wrap; + gap: 4px; +} + +.person-chip { + display: inline-flex; + align-items: center; + gap: 4px; + max-width: 100%; + padding: 2px 8px; + border: 1px solid var(--sg-border); + border-radius: var(--sg-radius-sm); + background: var(--sg-surface-soft); + color: var(--sg-text); + font-size: 0.75rem; + line-height: 1.4; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; + + mat-icon { + flex-shrink: 0; + width: 14px; + height: 14px; + font-size: 14px; + color: var(--sg-text-soft); + } + + &--more { + color: var(--sg-text-muted); + font-weight: 600; + } } .source-badge { diff --git a/webapp/src/app/modules/keywords-search/keywords-patents/keywords-patents.component.ts b/webapp/src/app/modules/keywords-search/keywords-patents/keywords-patents.component.ts index 4a636af1..4674b509 100644 --- a/webapp/src/app/modules/keywords-search/keywords-patents/keywords-patents.component.ts +++ b/webapp/src/app/modules/keywords-search/keywords-patents/keywords-patents.component.ts @@ -16,7 +16,8 @@ import { import { KeywordPatentMappingStatus } from '../../../api'; type SourceFilter = 'all' | 'EPO' | 'USPTO'; -type SortMode = 'date' | 'title'; +type SortColumn = 'title' | 'year' | 'source'; +type SortDirection = 'asc' | 'desc'; @Component({ selector: 'app-keywords-patents', @@ -44,7 +45,8 @@ export class KeywordsPatentsComponent { readonly reload = output(); activeFilter = signal('all'); - sortMode = signal('date'); + sortColumn = signal('year'); + sortDirection = signal('desc'); selectedMatch = signal(null); readonly pageIndex = computed(() => { @@ -86,12 +88,53 @@ export class KeywordsPatentsComponent { this.resetPage(); } - setSortMode(sortMode: SortMode): void { - this.sortMode.set(sortMode); + setSort(column: SortColumn): void { + if (this.sortColumn() === column) { + this.sortDirection.set(this.sortDirection() === 'asc' ? 'desc' : 'asc'); + } else { + this.sortColumn.set(column); + this.sortDirection.set(column === 'year' ? 'desc' : 'asc'); + } this.selectedMatch.set(null); this.resetPage(); } + isAssigneeLikelyPerson(assignee: string, patent: PatentEntry): boolean { + if (KeywordsPatentsComponent.ORG_SUFFIX_PATTERN.test(assignee)) { + return false; + } + + const normalizedAssignee = this.normalizeNameForComparison( + assignee.replace(KeywordsPatentsComponent.PERSON_SUFFIX_PATTERN, ''), + ); + const matchesInventor = (patent.inventors ?? []).some( + (inventor) => + this.normalizeNameForComparison(inventor) === normalizedAssignee, + ); + if (matchesInventor) { + return true; + } + + return KeywordsPatentsComponent.PERSON_SUFFIX_PATTERN.test(assignee); + } + + private static readonly ORG_SUFFIX_PATTERN = + /\b(Inc|Ltd|LLC|LLP|GmbH|Corp(oration)?|Co|KG|AG|SE|S\.?A\.?|N\.?V\.?|B\.?V\.?|PLC|Universit(y|ät|é)|Institut(e)?|Foundation|Laborator(y|ies)|Labs?|Group|Holdings?|Company|Gesellschaft)\b\.?/i; + private static readonly PERSON_SUFFIX_PATTERN = + /\b(Dr|Prof|PhD|Ph\.D|M\.D|Jr|Sr)\b\.?/i; + + private normalizeNameForComparison(name: string): string { + return name + .normalize('NFD') + .replace(/[̀-ͯ]/g, '') + .replace(/[.,]/g, '') + .toUpperCase() + .split(/\s+/) + .filter(Boolean) + .sort() + .join(' '); + } + onPatentPageChange(_event: PageEvent): void { this.selectedMatch.set(null); } @@ -124,14 +167,6 @@ export class KeywordsPatentsComponent { .length; } - getInventorsLabel(patent: PatentEntry): string { - return patent.inventors?.length ? patent.inventors.join(', ') : '-'; - } - - getAssigneesLabel(patent: PatentEntry): string { - return patent.assignees?.length ? patent.assignees.join(', ') : '-'; - } - formatDate(date: string | null | undefined): string { return formatPatentDate(date); } @@ -163,16 +198,29 @@ export class KeywordsPatentsComponent { } private sortMatches(items: KeywordPatentMatch[]): KeywordPatentMatch[] { - const mode = this.sortMode(); + const column = this.sortColumn(); + const direction = this.sortDirection() === 'asc' ? 1 : -1; return [...items].sort((a, b) => { - if (mode === 'date') { - return (b.patent.publication_date ?? '').localeCompare( - a.patent.publication_date ?? '', - ); + switch (column) { + case 'year': { + const yearA = + a.patent.publication_date ?? + String(a.patent.publication_year ?? ''); + const yearB = + b.patent.publication_date ?? + String(b.patent.publication_year ?? ''); + return direction * yearA.localeCompare(yearB); + } + case 'source': + return direction * a.patent.source.localeCompare(b.patent.source); + default: + return ( + direction * + (a.patent.title ?? '').localeCompare(b.patent.title ?? '', 'de', { + sensitivity: 'base', + }) + ); } - return (a.patent.title ?? '').localeCompare(b.patent.title ?? '', 'de', { - sensitivity: 'base', - }); }); } } diff --git a/webapp/src/app/modules/person-funding/person-funding.component.html b/webapp/src/app/modules/person-funding/person-funding.component.html index 85a34c96..70bec121 100644 --- a/webapp/src/app/modules/person-funding/person-funding.component.html +++ b/webapp/src/app/modules/person-funding/person-funding.component.html @@ -33,22 +33,75 @@ subscriptSizing="dynamic"> + [value]="sortColumn" + (selectionChange)="setSort($event.value)"> Sortieren nach - Name - Top Förderer + Förderer + Publikationen + Erstautor + Mitautor + Letztautor - - - - - + + + + + diff --git a/webapp/src/app/modules/person-funding/person-funding.component.scss b/webapp/src/app/modules/person-funding/person-funding.component.scss index 282f90e9..079c6a46 100644 --- a/webapp/src/app/modules/person-funding/person-funding.component.scss +++ b/webapp/src/app/modules/person-funding/person-funding.component.scss @@ -45,9 +45,24 @@ app-query-param-paginator { text-align: left; padding: 12px 16px; border-bottom: 1px solid var(--sg-border); - font-size: 13px; - font-weight: 600; + font-size: 12px; + font-weight: 700; color: var(--sg-text-muted); + + &.sortable { + display: table-cell; + cursor: pointer; + -webkit-user-select: none; + user-select: none; + } + + .sort-icon { + vertical-align: middle; + margin-left: 2px; + width: 14px; + height: 14px; + font-size: 14px; + } } tr { @@ -86,8 +101,11 @@ app-query-param-paginator { display: inline-flex; align-items: center; justify-content: center; - min-width: 20px; - font-size: 13px; + min-width: 26px; + padding: 2px 10px; + border-radius: 999px; + border: 1px solid var(--sg-border); + font-size: 0.8rem; font-weight: 700; &--first { @@ -157,9 +175,6 @@ app-query-param-paginator { } &.stat-first { - background: var(--sg-success-soft); - border-color: var(--sg-success); - .stat-label, .stat-value { color: var(--sg-success); @@ -167,9 +182,6 @@ app-query-param-paginator { } &.stat-middle { - background: var(--sg-warning-soft); - border-color: var(--sg-warning); - .stat-label, .stat-value { color: var(--sg-warning); @@ -177,9 +189,6 @@ app-query-param-paginator { } &.stat-last { - background: var(--sg-error-soft); - border-color: var(--sg-error); - .stat-label, .stat-value { color: var(--sg-error); diff --git a/webapp/src/app/modules/person-funding/person-funding.component.ts b/webapp/src/app/modules/person-funding/person-funding.component.ts index b6e5c211..7a5bac13 100644 --- a/webapp/src/app/modules/person-funding/person-funding.component.ts +++ b/webapp/src/app/modules/person-funding/person-funding.component.ts @@ -10,7 +10,8 @@ import { FundingService } from '../../api'; import { LoadingComponent } from '../../shared/ui/loading/loading.component'; import { QueryParamPaginatorComponent } from '../../shared/ui/query-param-paginator/query-param-paginator.component'; -type SortMode = 'name' | 'top'; +type SortColumn = 'name' | 'publications' | 'first' | 'middle' | 'last'; +type SortDirection = 'asc' | 'desc'; type AuthorPosition = 'first' | 'middle' | 'last' | 'unknown'; type FundingPublicationDetail = { @@ -53,7 +54,8 @@ export class PersonFundingComponent implements OnInit { publicationPageIndex = 0; publicationPageSize = 10; activeFilter: 'all' | 'first' | 'middle' | 'last' = 'all'; - sortMode: SortMode = 'name'; + sortColumn: SortColumn = 'name'; + sortDirection: SortDirection = 'asc'; loading = true; error = false; @@ -61,7 +63,8 @@ export class PersonFundingComponent implements OnInit { this.route.parent?.paramMap.subscribe((params) => { const authorId = params.get('id') ?? ''; const filterFromUrl = this.route.snapshot.queryParamMap.get('filter'); - const sortFromUrl = this.route.snapshot.queryParamMap.get('sortBy'); + const sortByFromUrl = this.route.snapshot.queryParamMap.get('sortBy'); + const sortDirFromUrl = this.route.snapshot.queryParamMap.get('sortDir'); this.initialSelectedFunderKey = this.route.snapshot.queryParamMap.get('funder'); this.initialFunderPageIndex = this.parsePageIndexParam( @@ -79,8 +82,11 @@ export class PersonFundingComponent implements OnInit { if (this.isValidFilter(filterFromUrl)) { this.activeFilter = filterFromUrl; } - if (this.isValidSortMode(sortFromUrl)) { - this.sortMode = sortFromUrl; + if (this.isValidSortColumn(sortByFromUrl)) { + this.sortColumn = sortByFromUrl; + } + if (this.isValidSortDirection(sortDirFromUrl)) { + this.sortDirection = sortDirFromUrl; } if (authorId) { @@ -118,8 +124,13 @@ export class PersonFundingComponent implements OnInit { this.updateQueryParams(); } - setSortMode(sortMode: SortMode): void { - this.sortMode = sortMode; + setSort(column: SortColumn): void { + if (this.sortColumn === column) { + this.sortDirection = this.sortDirection === 'asc' ? 'desc' : 'asc'; + } else { + this.sortColumn = column; + this.sortDirection = column === 'name' ? 'asc' : 'desc'; + } this.applyFilter(); this.updateQueryParams(); } @@ -185,7 +196,8 @@ export class PersonFundingComponent implements OnInit { relativeTo: this.route, queryParams: { filter: this.activeFilter, - sortBy: this.sortMode, + sortBy: this.sortColumn, + sortDir: this.sortDirection, funder: this.selectedFunder ? this.getFunderKey(this.selectedFunder) : null, @@ -214,8 +226,18 @@ export class PersonFundingComponent implements OnInit { ); } - private isValidSortMode(value: string | null): value is SortMode { - return value === 'name' || value === 'top'; + private isValidSortColumn(value: string | null): value is SortColumn { + return ( + value === 'name' || + value === 'publications' || + value === 'first' || + value === 'middle' || + value === 'last' + ); + } + + private isValidSortDirection(value: string | null): value is SortDirection { + return value === 'asc' || value === 'desc'; } getPublicationCount(funder: any): number { @@ -294,24 +316,44 @@ export class PersonFundingComponent implements OnInit { } private sortFunders(funders: any[]): any[] { + const direction = this.sortDirection === 'asc' ? 1 : -1; const sortedFunders = [...funders]; return sortedFunders.sort((first, second) => { - if (this.sortMode === 'top') { - const publicationCountDifference = - this.getPublicationCount(second) - this.getPublicationCount(first); - if (publicationCountDifference !== 0) { - return publicationCountDifference; + if (this.sortColumn !== 'name') { + const valueDifference = + direction * + (this.getSortColumnValue(first) - this.getSortColumnValue(second)); + if (valueDifference !== 0) { + return valueDifference; } } - return this.getSortableFunderName(first).localeCompare( - this.getSortableFunderName(second), - 'de', - { sensitivity: 'base' }, + return ( + direction * + this.getSortableFunderName(first).localeCompare( + this.getSortableFunderName(second), + 'de', + { sensitivity: 'base' }, + ) ); }); } + private getSortColumnValue(funder: any): number { + switch (this.sortColumn) { + case 'publications': + return this.getPublicationCount(funder); + case 'first': + return funder.author_position_count?.first ?? 0; + case 'middle': + return funder.author_position_count?.middle ?? 0; + case 'last': + return funder.author_position_count?.last ?? 0; + default: + return 0; + } + } + private getSortableFunderName(funder: any): string { return funder.funder_name ?? ''; } diff --git a/webapp/src/app/modules/person-patents/person-patents.component.html b/webapp/src/app/modules/person-patents/person-patents.component.html index 398004ef..b32185a7 100644 --- a/webapp/src/app/modules/person-patents/person-patents.component.html +++ b/webapp/src/app/modules/person-patents/person-patents.component.html @@ -31,11 +31,12 @@ subscriptSizing="dynamic"> + [value]="sortColumn" + (selectionChange)="setSort($event.value)"> Sortieren nach - Datum + Jahr Titel + Quelle @@ -44,8 +45,28 @@ - - + + @@ -69,12 +90,85 @@ {{ patent.source }} - - - + } diff --git a/webapp/src/app/modules/person-patents/person-patents.component.scss b/webapp/src/app/modules/person-patents/person-patents.component.scss index 6bed2a07..9c9c1410 100644 --- a/webapp/src/app/modules/person-patents/person-patents.component.scss +++ b/webapp/src/app/modules/person-patents/person-patents.component.scss @@ -50,9 +50,24 @@ app-query-param-paginator { text-align: left; padding: 12px 16px; border-bottom: 1px solid var(--sg-border); - font-size: 13px; - font-weight: 600; + font-size: 12px; + font-weight: 700; color: var(--sg-text-muted); + + &.sortable { + display: table-cell; + cursor: pointer; + -webkit-user-select: none; + user-select: none; + } + + .sort-icon { + vertical-align: middle; + margin-left: 2px; + width: 14px; + height: 14px; + font-size: 14px; + } } tr { @@ -80,22 +95,75 @@ app-query-param-paginator { .patent-title { color: var(--sg-text); font-weight: 600; - max-width: 400px; - white-space: nowrap; - overflow: hidden; - text-overflow: ellipsis; + max-width: 320px; + white-space: normal; + word-break: break-word; } .patent-people { - max-width: 220px; - color: var(--sg-text-muted); - white-space: nowrap; - overflow: hidden; - text-overflow: ellipsis; + max-width: 260px; } } } +.year-badge { + display: inline-flex; + align-items: center; + justify-content: center; + min-width: 26px; + padding: 2px 10px; + border-radius: 999px; + border: 1px solid var(--sg-border); + color: var(--sg-text); + font-size: 0.8rem; + font-weight: 600; +} + +.person-chips { + display: flex; + flex-direction: column; + align-items: flex-start; + gap: 4px; +} + +.person-chip-row { + display: flex; + flex-direction: row; + align-items: center; + flex-wrap: wrap; + gap: 4px; +} + +.person-chip { + display: inline-flex; + align-items: center; + gap: 4px; + max-width: 100%; + padding: 2px 8px; + border: 1px solid var(--sg-border); + border-radius: var(--sg-radius-sm); + background: var(--sg-surface-soft); + color: var(--sg-text); + font-size: 0.75rem; + line-height: 1.4; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; + + mat-icon { + flex-shrink: 0; + width: 14px; + height: 14px; + font-size: 14px; + color: var(--sg-text-soft); + } + + &--more { + color: var(--sg-text-muted); + font-weight: 600; + } +} + .match-badges { display: flex; flex-wrap: wrap; diff --git a/webapp/src/app/modules/person-patents/person-patents.component.ts b/webapp/src/app/modules/person-patents/person-patents.component.ts index ece9c4dd..508f41ed 100644 --- a/webapp/src/app/modules/person-patents/person-patents.component.ts +++ b/webapp/src/app/modules/person-patents/person-patents.component.ts @@ -16,7 +16,8 @@ import { LoadingComponent } from '../../shared/ui/loading/loading.component'; import { PageEvent } from '@angular/material/paginator'; import { QueryParamPaginatorComponent } from '../../shared/ui/query-param-paginator/query-param-paginator.component'; -type SortMode = 'date' | 'title'; +type SortColumn = 'title' | 'year' | 'source'; +type SortDirection = 'asc' | 'desc'; type SourceFilter = 'all' | 'EPO' | 'USPTO'; @Component({ @@ -46,14 +47,16 @@ export class PersonPatentsComponent { error = false; activeFilter: SourceFilter = 'all'; - sortMode: SortMode = 'date'; + sortColumn: SortColumn = 'year'; + sortDirection: SortDirection = 'desc'; pageIndex = 0; pageSize = 10; constructor() { const filterFromUrl = this.route.snapshot.queryParamMap.get('filter'); - const sortFromUrl = this.route.snapshot.queryParamMap.get('sortBy'); + const sortByFromUrl = this.route.snapshot.queryParamMap.get('sortBy'); + const sortDirFromUrl = this.route.snapshot.queryParamMap.get('sortDir'); this.pageIndex = this.parsePageIndexParam( this.route.snapshot.queryParamMap.get('page'), ); @@ -64,8 +67,11 @@ export class PersonPatentsComponent { if (this.isValidFilter(filterFromUrl)) { this.activeFilter = filterFromUrl; } - if (this.isValidSortMode(sortFromUrl)) { - this.sortMode = sortFromUrl; + if (this.isValidSortColumn(sortByFromUrl)) { + this.sortColumn = sortByFromUrl; + } + if (this.isValidSortDirection(sortDirFromUrl)) { + this.sortDirection = sortDirFromUrl; } this.route.parent?.data @@ -113,8 +119,13 @@ export class PersonPatentsComponent { this.pageSize = event.pageSize; } - setSortMode(sortMode: SortMode): void { - this.sortMode = sortMode; + setSort(column: SortColumn): void { + if (this.sortColumn === column) { + this.sortDirection = this.sortDirection === 'asc' ? 'desc' : 'asc'; + } else { + this.sortColumn = column; + this.sortDirection = column === 'year' ? 'desc' : 'asc'; + } this.applyFilter(); this.updateQueryParams(); } @@ -140,15 +151,24 @@ export class PersonPatentsComponent { } private sortPatents(patents: PatentEntry[]): PatentEntry[] { + const direction = this.sortDirection === 'asc' ? 1 : -1; return [...patents].sort((a, b) => { - if (this.sortMode === 'date') { - return (b.publication_date ?? '').localeCompare( - a.publication_date ?? '', - ); + switch (this.sortColumn) { + case 'year': { + const yearA = a.publication_date ?? String(a.publication_year ?? ''); + const yearB = b.publication_date ?? String(b.publication_year ?? ''); + return direction * yearA.localeCompare(yearB); + } + case 'source': + return direction * a.source.localeCompare(b.source); + default: + return ( + direction * + (a.title ?? '').localeCompare(b.title ?? '', 'de', { + sensitivity: 'base', + }) + ); } - return (a.title ?? '').localeCompare(b.title ?? '', 'de', { - sensitivity: 'base', - }); }); } @@ -157,7 +177,8 @@ export class PersonPatentsComponent { relativeTo: this.route, queryParams: { filter: this.activeFilter, - sortBy: this.sortMode, + sortBy: this.sortColumn, + sortDir: this.sortDirection, page: this.pageIndex, size: this.pageSize, }, @@ -180,8 +201,12 @@ export class PersonPatentsComponent { return value === 'all' || value === 'EPO' || value === 'USPTO'; } - private isValidSortMode(value: string | null): value is SortMode { - return value === 'date' || value === 'title'; + private isValidSortColumn(value: string | null): value is SortColumn { + return value === 'title' || value === 'year' || value === 'source'; + } + + private isValidSortDirection(value: string | null): value is SortDirection { + return value === 'asc' || value === 'desc'; } getPagedPatents(): PatentEntry[] { @@ -189,12 +214,40 @@ export class PersonPatentsComponent { return this.filteredPatents.slice(start, start + this.pageSize); } - getInventorsLabel(patent: PatentEntry): string { - return patent.inventors?.length ? patent.inventors.join(', ') : '-'; + private static readonly ORG_SUFFIX_PATTERN = + /\b(Inc|Ltd|LLC|LLP|GmbH|Corp(oration)?|Co|KG|AG|SE|S\.?A\.?|N\.?V\.?|B\.?V\.?|PLC|Universit(y|ät|é)|Institut(e)?|Foundation|Laborator(y|ies)|Labs?|Group|Holdings?|Company|Gesellschaft)\b\.?/i; + private static readonly PERSON_SUFFIX_PATTERN = + /\b(Dr|Prof|PhD|Ph\.D|M\.D|Jr|Sr)\b\.?/i; + + private normalizeNameForComparison(name: string): string { + return name + .normalize('NFD') + .replace(/[̀-ͯ]/g, '') + .replace(/[.,]/g, '') + .toUpperCase() + .split(/\s+/) + .filter(Boolean) + .sort() + .join(' '); } - getAssigneesLabel(patent: PatentEntry): string { - return patent.assignees?.length ? patent.assignees.join(', ') : '-'; + isAssigneeLikelyPerson(assignee: string, patent: PatentEntry): boolean { + if (PersonPatentsComponent.ORG_SUFFIX_PATTERN.test(assignee)) { + return false; + } + + const normalizedAssignee = this.normalizeNameForComparison( + assignee.replace(PersonPatentsComponent.PERSON_SUFFIX_PATTERN, ''), + ); + const matchesInventor = (patent.inventors ?? []).some( + (inventor) => + this.normalizeNameForComparison(inventor) === normalizedAssignee, + ); + if (matchesInventor) { + return true; + } + + return PersonPatentsComponent.PERSON_SUFFIX_PATTERN.test(assignee); } formatDate(date: string | null | undefined): string { From 98a742f024653960c4584076d539e35d354cb1fa Mon Sep 17 00:00:00 2001 From: spsaefan <117728614+spsaefan@users.noreply.github.com> Date: Tue, 4 Aug 2026 22:59:36 +0200 Subject: [PATCH 052/114] Match dashboard publications with publications page --- service/src/main/inse/dashboard/service.py | 116 ++++++----- .../src/main/inse/dashboard/test_service.py | 194 +++++++++++++++--- 2 files changed, 236 insertions(+), 74 deletions(-) diff --git a/service/src/main/inse/dashboard/service.py b/service/src/main/inse/dashboard/service.py index 4f1fe83d..babb8b5b 100644 --- a/service/src/main/inse/dashboard/service.py +++ b/service/src/main/inse/dashboard/service.py @@ -30,6 +30,7 @@ from inse.projects.model import ( ProjectsFilteringProperties, ProjectType, ) +from inse.works.v2 import service as works_v2_service from .institute_helper import get_openalex_institution from .model import ( @@ -241,28 +242,34 @@ async def get_dashboard_publications( ) -> DashboardStatisticValue: normalized_id = _normalize_institution_id(institution_id) period = _dashboard_period(from_year, to_year) - institution = await institutions_v2_service.get_institution_by_id_or_raise( - raw_oa_institution_id=_raw_institution_id(normalized_id), - source=["id", "works_count", "counts_by_year"], + must = [ + works_v2_service._institutions_nested_query([normalized_id]), + ] + if publication_years := _dashboard_publication_years(period): + must.append({"terms": {"publication_year": publication_years}}) + response = await elasticsearch.search( + index=ESIndex.OPENALEX_WORKS_WILDCARD, + body={ + "size": 0, + "track_total_hits": True, + "query": {"bool": {"must": must}}, + }, + cluster=ESCluster.NES, ) - if period == (None, None): - value = int(institution.works_count or 0) - else: - value = sum( - int(entry.works_count or 0) - for entry in institution.counts_by_year or [] - if ( - (period[0] is None or int(entry.year or 0) >= period[0]) - and (period[1] is None or int(entry.year or 0) <= period[1]) - ) - ) return DashboardStatisticValue( institution_id=normalized_id, organization_name=organization_name, - value=value, + value=_total(response), ) +def _dashboard_publication_years(period: DashboardPeriod) -> list[int] | None: + from_year, to_year = period + if from_year is None and to_year is None: + return None + return list(range(from_year or 1900, (to_year or 2100) + 1)) + + async def get_dashboard_persons( institution_id: str, organization_name: str, @@ -1183,7 +1190,10 @@ async def get_top_authors( to_year = datetime.now().year period = _dashboard_period(from_year, to_year) authors = await _safe_institution_authors(normalized_id) - works = _top_work_authors(authors, period) + works = await _safe_top_authors( + "works", + _top_work_authors(normalized_id, period), + ) projects = await _safe_top_authors( "projects", _top_project_authors( @@ -1595,51 +1605,59 @@ def _short_author_id(value: str) -> str: return value.replace("https://openalex.org/", "").strip().upper() -def _top_work_authors( - authors: list[dict[str, Any]], +async def _top_work_authors( + institution_id: str, period: DashboardPeriod, ) -> list[TopAuthor]: - if period != (None, None): - ranked_authors = sorted( - ( - { - **author, - "selected_works_count": _works_count_in_period(author, period), - } - for author in authors - ), - key=lambda author: author["selected_works_count"], - reverse=True, - ) - else: - ranked_authors = [ - {**author, "selected_works_count": author["works_count"]} - for author in authors - ] + must = [works_v2_service._institutions_nested_query([institution_id])] + if publication_years := _dashboard_publication_years(period): + must.append({"terms": {"publication_year": publication_years}}) + author_counts: dict[str, int] = defaultdict(int) + author_names: dict[str, str] = {} + async for hit in elasticsearch.scan( + index=str(ESIndex.OPENALEX_WORKS_WILDCARD), + query={"bool": {"must": must}}, + source=["id", "authorships.author.id", "authorships.author.display_name"], + page_size=1000, + cluster=ESCluster.NES, + ): + hit_author_ids: set[str] = set() + for authorship in hit.get("_source", {}).get("authorships", []): + author = authorship.get("author") or {} + author_id = author.get("id") + if not author_id: + continue + author_id = str(author_id) + hit_author_ids.add(author_id) + if author.get("display_name"): + author_names.setdefault(author_id, str(author["display_name"])) + for author_id in hit_author_ids: + author_counts[author_id] += 1 + + ranked_authors = sorted( + ( + { + "id": author_id, + "name": author_names.get(author_id, author_id), + "count": count, + } + for author_id, count in author_counts.items() + ), + key=lambda author: author["count"], + reverse=True, + ) return [ TopAuthor( id=_short_author_id(author["id"]), name=author["name"], - count=author["selected_works_count"], + count=author["count"], ) for author in ranked_authors[:TOP_AUTHOR_LIMIT] - if author["selected_works_count"] > 0 + if author["count"] > 0 ] -def _works_count_in_period(author: dict[str, Any], period: DashboardPeriod) -> int: - from_year, to_year = period - return sum( - int(item.get("works_count", 0) or 0) - for item in author.get("counts_by_year", []) - if ( - (from_year is None or int(item.get("year", 0) or 0) >= from_year) - and (to_year is None or int(item.get("year", 0) or 0) <= to_year) - ) - ) - - async def _safe_institution_authors(institution_id: str) -> list[dict[str, Any]]: try: return await _institution_authors(institution_id) diff --git a/service/src/main/inse/dashboard/test_service.py b/service/src/main/inse/dashboard/test_service.py index 630f8121..1429e267 100644 --- a/service/src/main/inse/dashboard/test_service.py +++ b/service/src/main/inse/dashboard/test_service.py @@ -24,7 +24,6 @@ from inse.dashboard.service import ( get_topic_word_cloud, ) from inse.model import ESCluster, ESIndex -from inse.models.openalex.author_counts_by_year_inner import AuthorCountsByYearInner from inse.models.openalex.institution import Institution from inse.models.openalex.meta import Meta from inse.persons.model import CustomAuthorsListResponse @@ -188,21 +187,16 @@ async def test_dashboard_statistics_counts_organization_data_and_all_projects(): } @pytest.mark.anyio -async def test_dashboard_publications_uses_institutions_v2_counts(): - institution = Institution( - id=ORG_INSTITUTION_ID, - works_count=250, - counts_by_year=[ - AuthorCountsByYearInner(year=2021, works_count=10), - AuthorCountsByYearInner(year=2022, works_count=12), - AuthorCountsByYearInner(year=2023, works_count=14), - ], - ) - +async def test_dashboard_publications_counts_matching_openalex_works(): with patch( - "inse.dashboard.service.institutions_v2_service.get_institution_by_id_or_raise", - new=AsyncMock(return_value=institution), - ) as mocked_get_institution: + "inse.dashboard.service.elasticsearch.search", + new=AsyncMock( + side_effect=[ + {"hits": {"total": {"value": 250}}}, + {"hits": {"total": {"value": 22}}}, + ] + ), + ) as mocked_search: all_time = await get_dashboard_publications( ORG_INSTITUTION_ID, "Example Org", @@ -216,10 +210,33 @@ async def test_dashboard_publications_uses_institutions_v2_counts(): assert all_time.value == 250 assert selected_period.value == 22 - assert mocked_get_institution.await_args_list[0].kwargs == { - "raw_oa_institution_id": "I123", - "source": ["id", "works_count", "counts_by_year"], - } + all_time_body = mocked_search.await_args_list[0].kwargs["body"] + selected_period_body = mocked_search.await_args_list[1].kwargs["body"] + assert mocked_search.await_args_list[0].kwargs["index"] == ( + ESIndex.OPENALEX_WORKS_WILDCARD + ) + assert all_time_body["track_total_hits"] is True + assert all_time_body["query"]["bool"]["must"] == [ + { + "nested": { + "path": "authorships", + "query": { + "nested": { + "path": "authorships.institutions", + "query": { + "terms": { + "authorships.institutions.id": [ORG_INSTITUTION_ID] + } + }, + } + }, + } + } + ] + assert selected_period_body["query"]["bool"]["must"] == [ + all_time_body["query"]["bool"]["must"][0], + {"terms": {"publication_year": [2021, 2022]}}, + ] @pytest.mark.anyio @@ -438,6 +455,45 @@ async def test_top_authors_maps_works_patents_news_and_eu_projects(): return {"aggregations": {"people": {"buckets": []}}} + scan_calls = [] + + async def scan(**kwargs): + scan_calls.append(kwargs) + yield { + "_id": "W1", + "_source": { + "id": "https://openalex.org/W1", + "authorships": [ + { + "author": { + "id": "https://openalex.org/A1", + "display_name": "Ada Example", + }, + }, + { + "author": { + "id": "https://openalex.org/A2", + "display_name": "Grace Example", + }, + }, + ], + }, + } + yield { + "_id": "W2", + "_source": { + "id": "https://openalex.org/W2", + "authorships": [ + { + "author": { + "id": "https://openalex.org/A1", + "display_name": "Ada Example", + }, + } + ], + }, + } + async def eu_projects(**kwargs): if kwargs.get("raw_oa_institution_id"): return EuCordisProjectSearchPage( @@ -461,6 +517,9 @@ async def test_top_authors_maps_works_patents_news_and_eu_projects(): "inse.dashboard.service.elasticsearch.search", new=AsyncMock(side_effect=search), ) as mocked_search, patch( + "inse.dashboard.service.elasticsearch.scan", + new=scan, + ), patch( "inse.dashboard.service.InstitutionsSearchClient.get_institution_aliases_by_oa_institution_id", new=AsyncMock(return_value=["Example University"]), ), patch( @@ -482,7 +541,7 @@ async def test_top_authors_maps_works_patents_news_and_eu_projects(): assert result.works[0].model_dump() == { "id": "A1", "name": "Ada Example", - "count": 42, + "count": 2, } assert result.patents[0].model_dump() == { "id": "A1", @@ -523,18 +582,43 @@ async def test_top_authors_maps_works_patents_news_and_eu_projects(): assert eu_body["_source"] == ["projectID", "qaProcessedDoi"] assert "aggs" not in eu_body - works_calls = [ + assert len(scan_calls) == 1 + assert scan_calls[0]["index"] == str(ESIndex.OPENALEX_WORKS_WILDCARD) + assert scan_calls[0]["query"]["bool"]["must"] == [ + { + "nested": { + "path": "authorships", + "query": { + "nested": { + "path": "authorships.institutions", + "query": { + "terms": { + "authorships.institutions.id": [ORG_INSTITUTION_ID] + } + }, + } + }, + } + } + ] + assert scan_calls[0]["source"] == [ + "id", + "authorships.author.id", + "authorships.author.display_name", + ] + + eu_work_calls = [ call for call in mocked_search.await_args_list if call.kwargs["index"] == "openalex-works" ] - assert len(works_calls) == 1 - works_body = works_calls[0].kwargs["body"] - assert works_body["query"]["bool"]["filter"][0]["terms"]["doi"] == [ + assert len(eu_work_calls) == 1 + eu_works_body = eu_work_calls[0].kwargs["body"] + assert eu_works_body["query"]["bool"]["filter"][0]["terms"]["doi"] == [ "https://doi.org/10.1234/p1", "https://doi.org/10.1234/p2", ] - assert works_body["_source"] == [ + assert eu_works_body["_source"] == [ "doi", "authorships.author.id", "authorships.author.display_name", @@ -813,9 +897,28 @@ async def test_top_authors_returns_partial_response_when_one_source_fails(): raise RuntimeError("projects unavailable") + async def scan(**kwargs): + yield { + "_id": "W1", + "_source": { + "id": "https://openalex.org/W1", + "authorships": [ + { + "author": { + "id": "https://openalex.org/A1", + "display_name": "Ada Example", + } + } + ], + }, + } + with patch( "inse.dashboard.service.elasticsearch.search", new=AsyncMock(side_effect=search), + ), patch( + "inse.dashboard.service.elasticsearch.scan", + new=scan, ), patch( "inse.dashboard.service.InstitutionsSearchClient.get_institution_aliases_by_oa_institution_id", new=AsyncMock(return_value=["Example University"]), @@ -879,9 +982,45 @@ async def test_top_authors_can_rank_works_by_last_five_years(): } return {"aggregations": {"people": {"buckets": []}}} + scan_calls = [] + + async def scan(**kwargs): + scan_calls.append(kwargs) + for index in range(16): + yield { + "_id": f"W-grace-{index}", + "_source": { + "authorships": [ + { + "author": { + "id": "https://openalex.org/A2", + "display_name": "Grace Example", + } + } + ] + }, + } + for index in range(2): + yield { + "_id": f"W-ada-{index}", + "_source": { + "authorships": [ + { + "author": { + "id": "https://openalex.org/A1", + "display_name": "Ada Example", + } + } + ] + }, + } + with patch( "inse.dashboard.service.elasticsearch.search", new=AsyncMock(side_effect=search), + ) as mocked_search, patch( + "inse.dashboard.service.elasticsearch.scan", + new=scan, ), patch( "inse.dashboard.service.InstitutionsSearchClient.get_institution_aliases_by_oa_institution_id", new=AsyncMock(return_value=["Example University"]), @@ -909,6 +1048,11 @@ async def test_top_authors_can_rank_works_by_last_five_years(): "count": 2, } + assert len(scan_calls) == 1 + assert scan_calls[0]["query"]["bool"]["must"][1] == { + "terms": {"publication_year": list(range(current_year - 4, current_year + 1))} + } + @pytest.mark.anyio async def test_topic_heatmap_maps_field_year_counts_and_shares(): From c054cf99fea77bb0b990962a903c361de69ac20a Mon Sep 17 00:00:00 2001 From: spsaefan <117728614+spsaefan@users.noreply.github.com> Date: Tue, 4 Aug 2026 23:19:50 +0200 Subject: [PATCH 053/114] Fix all time slider --- .../modules/dashboard/dashboard.component.ts | 25 +++++++++++-------- 1 file changed, 15 insertions(+), 10 deletions(-) diff --git a/webapp/src/app/modules/dashboard/dashboard.component.ts b/webapp/src/app/modules/dashboard/dashboard.component.ts index cb9982c5..d1e70970 100644 --- a/webapp/src/app/modules/dashboard/dashboard.component.ts +++ b/webapp/src/app/modules/dashboard/dashboard.component.ts @@ -108,7 +108,7 @@ export class DashboardComponent implements OnInit { readonly topicTreemapMinYear = 1900; readonly topicTreemapMaxYear = new Date().getFullYear(); dashboardPeriodMode: DashboardPeriodMode = 'all_time'; - dashboardFromYear = this.topicTreemapMaxYear - 4; + dashboardFromYear = this.topicTreemapMinYear; dashboardToYear = this.topicTreemapMaxYear; selectedTopicTreemapNode?: string; selectedDfgTopicTreemapNode?: string; @@ -406,14 +406,16 @@ export class DashboardComponent implements OnInit { this.dashboardPeriodMode = mode; } this.applyPresetPeriod(); - this.dashboardFromYear = this.parseDashboardYear( - params.get('fromYear'), - this.dashboardFromYear, - ); - this.dashboardToYear = this.parseDashboardYear( - params.get('toYear'), - this.dashboardToYear, - ); + if (this.dashboardPeriodMode !== 'all_time') { + this.dashboardFromYear = this.parseDashboardYear( + params.get('fromYear'), + this.dashboardFromYear, + ); + this.dashboardToYear = this.parseDashboardYear( + params.get('toYear'), + this.dashboardToYear, + ); + } if (this.dashboardFromYear > this.dashboardToYear) { this.dashboardFromYear = this.dashboardToYear; } @@ -422,7 +424,10 @@ export class DashboardComponent implements OnInit { private applyPresetPeriod(): void { const currentYear = this.topicTreemapMaxYear; - if (this.dashboardPeriodMode === 'last_10_years') { + if (this.dashboardPeriodMode === 'all_time') { + this.dashboardFromYear = this.topicTreemapMinYear; + this.dashboardToYear = currentYear; + } else if (this.dashboardPeriodMode === 'last_10_years') { this.dashboardFromYear = currentYear - 9; this.dashboardToYear = currentYear; } else if (this.dashboardPeriodMode === 'last_5_years') { From 71b075b36535527a7bb319a1687dc42347bcbbf2 Mon Sep 17 00:00:00 2001 From: genja Date: Tue, 4 Aug 2026 23:25:37 +0200 Subject: [PATCH 054/114] Merge branch 'dev' of nes.uni-due.de:lbs/smartguide into feature/keywords-analysis --- .../shared/ui/link-tab-nav-bar/link-tab-nav-bar.component.html | 1 + .../app/shared/ui/link-tab-nav-bar/link-tab-nav-bar.component.ts | 1 + 2 files changed, 2 insertions(+) diff --git a/webapp/src/app/shared/ui/link-tab-nav-bar/link-tab-nav-bar.component.html b/webapp/src/app/shared/ui/link-tab-nav-bar/link-tab-nav-bar.component.html index fa54da5b..88075208 100644 --- a/webapp/src/app/shared/ui/link-tab-nav-bar/link-tab-nav-bar.component.html +++ b/webapp/src/app/shared/ui/link-tab-nav-bar/link-tab-nav-bar.component.html @@ -4,6 +4,7 @@ mat-tab-link [routerLink]="link.path" [queryParams]="link.queryParams" + [queryParamsHandling]="link.queryParamsHandling" routerLinkActive #rla="routerLinkActive" [active]="rla.isActive" diff --git a/webapp/src/app/shared/ui/link-tab-nav-bar/link-tab-nav-bar.component.ts b/webapp/src/app/shared/ui/link-tab-nav-bar/link-tab-nav-bar.component.ts index 3f87669d..d62cd205 100644 --- a/webapp/src/app/shared/ui/link-tab-nav-bar/link-tab-nav-bar.component.ts +++ b/webapp/src/app/shared/ui/link-tab-nav-bar/link-tab-nav-bar.component.ts @@ -14,6 +14,7 @@ export type LinkTabNavBarItem = { icon?: string; description?: string; queryParams?: Record; + queryParamsHandling?: 'merge' | 'preserve' | 'replace'; disabled?: boolean; }; From ae7d1a54cb5b37b38b370755b9395c69611ca95c Mon Sep 17 00:00:00 2001 From: genja Date: Tue, 4 Aug 2026 23:25:59 +0200 Subject: [PATCH 055/114] fixed EU matching bug --- .../projects/eu_cordis_projects_client.py | 66 ------------------- .../inse/projects/projects_search_client.py | 15 +++-- 2 files changed, 8 insertions(+), 73 deletions(-) diff --git a/service/src/main/inse/projects/eu_cordis_projects_client.py b/service/src/main/inse/projects/eu_cordis_projects_client.py index 8f0af70f..731cd699 100644 --- a/service/src/main/inse/projects/eu_cordis_projects_client.py +++ b/service/src/main/inse/projects/eu_cordis_projects_client.py @@ -1133,10 +1133,6 @@ async def get_eu_cordis_projects_funding_data( "track_total_hits": False, "_source": ["id", "startDate", "endDate", "ecMaxContribution"], "query": query, - # "id" is unique per project and used elsewhere as a term-filter - # field, so it's mapped as keyword - safe + deterministic sort - # key for search_after pagination across an arbitrarily large - # result set. "sort": [{"id": {"order": "asc", "unmapped_type": "keyword"}}], } if search_after is not None: @@ -1256,68 +1252,6 @@ async def get_openalex_author_ids_by_dois( 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]], diff --git a/service/src/main/inse/projects/projects_search_client.py b/service/src/main/inse/projects/projects_search_client.py index 3b80b959..f3b2f1e2 100644 --- a/service/src/main/inse/projects/projects_search_client.py +++ b/service/src/main/inse/projects/projects_search_client.py @@ -195,7 +195,7 @@ async def get_cordis_eu_publications_by_dois(dois: list[str]): _type_: The retrieved publications. """ - query_dois = list({ + query_dois = set({ variant for doi in dois for variant in ( @@ -211,8 +211,8 @@ async def get_cordis_eu_publications_by_dois(dois: list[str]): { "bool": { "should": [ - {"terms": {"doi": query_dois}}, - {"terms": {"qaProcessedDoi": query_dois}}, + {"terms": {"doi": list(query_dois)}}, + {"terms": {"qaProcessedDoi": list(query_dois)}}, ], "minimum_should_match": 1, } @@ -223,6 +223,7 @@ async def get_cordis_eu_publications_by_dois(dois: list[str]): response = await elasticsearch.search( query=query, + size=10000, index=ESIndex.CORDIS_EU_PUBLICATIONS_WILDCARD, cluster=ESCluster.INSE, ) @@ -264,7 +265,7 @@ async def get_dfg_publications_by_dois(dois: list[str]): _type_: The retrieved publications. """ - query_dois = list({ + query_dois = set({ variant for doi in dois for variant in ( @@ -281,7 +282,7 @@ async def get_dfg_publications_by_dois(dois: list[str]): "query": { "terms": { "publications.doi": - query_dois + list(query_dois) } } } @@ -291,7 +292,7 @@ async def get_dfg_publications_by_dois(dois: list[str]): } response = await elasticsearch.search( - size=1000, + size=10000, query=query, index=ESIndex.DFG_PROJECTS, cluster=ESCluster.INSE, @@ -318,7 +319,7 @@ async def get_dfg_project_ids_by_names(names: list[str]) -> list[str]: response = await elasticsearch.search( source=["projects.project_id"], - size=1000, + size=10000, query=query, index=ESIndex.DFG_PERSONS, cluster=ESCluster.INSE, From 57f221868d43bcdce7067b0aad4eb2326c6c5c6a Mon Sep 17 00:00:00 2001 From: genja Date: Tue, 4 Aug 2026 23:26:24 +0200 Subject: [PATCH 056/114] robust handling of wrong query params added --- .../app/resolvers/dfg-projects.resolver.ts | 53 ++++++++++++++++--- 1 file changed, 45 insertions(+), 8 deletions(-) diff --git a/webapp/src/app/resolvers/dfg-projects.resolver.ts b/webapp/src/app/resolvers/dfg-projects.resolver.ts index 1391bd49..365a4214 100644 --- a/webapp/src/app/resolvers/dfg-projects.resolver.ts +++ b/webapp/src/app/resolvers/dfg-projects.resolver.ts @@ -1,5 +1,6 @@ import { inject } from '@angular/core'; import { ResolveFn } from '@angular/router'; +import { of } from 'rxjs'; import { DfgProjectPage, ProjectsService } from '../api'; export const dfgProjectQueryParamKeys = { @@ -24,6 +25,34 @@ export const RESOLVING_PROJECT_PAGE_FOR = { KEYWORDS_SEARCH: 'KEYWORDS_SEARCH', } as const; +// Empty page returned whenever a required numeric param fails to parse. +const EMPTY_DFG_PROJECT_PAGE: DfgProjectPage = { + page: 0, + size: 0, + total: 0, + elements: [], +} as DfgProjectPage; + +function toNumberOrNull(value: unknown): number | null { + if (value === undefined || value === null || value === '') { + return null; + } + const parsed = Number(value); + return Number.isFinite(parsed) ? parsed : null; +} + +function toNumberArrayOrNull(values: string[]): number[] | null { + const result: number[] = []; + for (const value of values) { + const parsed = toNumberOrNull(value); + if (parsed === null) { + return null; + } + result.push(parsed); + } + return result; +} + export const dfgProjectsResolver: ResolveFn = ( route, state, @@ -40,9 +69,12 @@ export const dfgProjectsResolver: ResolveFn = ( ); const page = - Number(route.queryParamMap.get(dfgProjectQueryParamKeys.page)) || 0; + toNumberOrNull(route.queryParamMap.get(dfgProjectQueryParamKeys.page)) ?? 0; + const size = - Number(route.queryParamMap.get(dfgProjectQueryParamKeys.size)) || 10; + toNumberOrNull(route.queryParamMap.get(dfgProjectQueryParamKeys.size)) ?? + 10; + const searchTerm = route.queryParamMap.get(dfgProjectQueryParamKeys.title) ?? undefined; const sortBy = @@ -59,12 +91,16 @@ export const dfgProjectsResolver: ResolveFn = ( const filteredTopicIds = route.queryParamMap.getAll( dfgProjectQueryParamKeys.topicId, ); - const institutionIds = route.queryParamMap - .getAll(dfgProjectQueryParamKeys.institutionId) - .map((id) => Number(id)); - const authorIds = route.queryParamMap - .getAll(dfgProjectQueryParamKeys.authorId) - .map((id) => Number(id)); + + const institutionIds = toNumberArrayOrNull( + route.queryParamMap.getAll(dfgProjectQueryParamKeys.institutionId), + ); + const authorIds = toNumberArrayOrNull( + route.queryParamMap.getAll(dfgProjectQueryParamKeys.authorId), + ); + if (institutionIds === null || authorIds === null) { + return of(EMPTY_DFG_PROJECT_PAGE); + } if (resolvingFor === RESOLVING_PROJECT_PAGE_FOR.PERSON) { const rawAuthorId = route.parent?.parent?.params['id']; @@ -108,6 +144,7 @@ export const dfgProjectsResolver: ResolveFn = ( ); } else if (resolvingFor === RESOLVING_PROJECT_PAGE_FOR.INSTITUTION) { const oaInstitutionId = route.parent?.parent?.params['institutionId']; + console.log( 'Resolving project page for institution', oaInstitutionId, From e9fdf7d538bfc997dffe1dd8804fa65f647e4742 Mon Sep 17 00:00:00 2001 From: genja Date: Tue, 4 Aug 2026 23:28:28 +0200 Subject: [PATCH 057/114] replaced projects navs with generic navbar --- .../institution-projects.component.html | 23 ++------ .../institution-projects.component.ts | 27 +++++++++- .../projects-results.component.html | 21 ++------ .../projects-results.component.ts | 53 +++++++++++-------- .../person-projects.component.html | 21 ++------ .../person-projects.component.ts | 40 +++++++------- 6 files changed, 89 insertions(+), 96 deletions(-) diff --git a/webapp/src/app/modules/institution-projects/institution-projects.component.html b/webapp/src/app/modules/institution-projects/institution-projects.component.html index b5e22762..d6c902db 100644 --- a/webapp/src/app/modules/institution-projects/institution-projects.component.html +++ b/webapp/src/app/modules/institution-projects/institution-projects.component.html @@ -58,24 +58,11 @@
    - + @if (resultTabPanel) { + + } diff --git a/webapp/src/app/modules/institution-projects/institution-projects.component.ts b/webapp/src/app/modules/institution-projects/institution-projects.component.ts index ddad7159..fa7061ee 100644 --- a/webapp/src/app/modules/institution-projects/institution-projects.component.ts +++ b/webapp/src/app/modules/institution-projects/institution-projects.component.ts @@ -28,7 +28,10 @@ import { MatIconModule } from '@angular/material/icon'; import { MatButtonModule } from '@angular/material/button'; import { InstitutionProjectsFundingGraphComponent } from '../institution-projects-funding-graph/institution-projects-funding-graph.component'; import { AppInfoCardComponent } from '../../shared/ui/app-info-card/app-info-card.component'; - +import { + LinkTabNavBarComponent, + LinkTabNavBarItem, +} from '../../shared/ui/link-tab-nav-bar/link-tab-nav-bar.component'; type BundProjectRow = { id: string; topic: string; @@ -61,6 +64,7 @@ type EuProjectRow = { MatButtonModule, InstitutionProjectsFundingGraphComponent, AppInfoCardComponent, + LinkTabNavBarComponent, RouterModule, ], templateUrl: './institution-projects.component.html', @@ -124,6 +128,27 @@ export class InstitutionProjectsComponent implements OnInit { label: 'BUND-Projekte', }, ]; + + _links = computed(() => { + const links: LinkTabNavBarItem[] = [ + { + label: 'DFG-Projekte', + path: 'dfg', + disabled: false, + }, + { + label: 'EU-Projekte', + path: 'eu', + disabled: false, + }, + { + label: 'BUND-Projekte', + path: 'bund', + disabled: false, + }, + ]; + return links; + }); constructor( private readonly activatedRoute: ActivatedRoute, private readonly router: Router, 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 4ff6ee31..2270f628 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 @@ -4,24 +4,9 @@

    Übersicht der durchgeführten Projekte.

    - + @if (resultTabPanel) { + + } 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 224b934f..9adbcbc6 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 @@ -6,16 +6,13 @@ import { MatTabsModule } from '@angular/material/tabs'; import { OnInit, computed } from '@angular/core'; import { ActivatedRoute, Router } from '@angular/router'; import { toSignal } from '@angular/core/rxjs-interop'; - +import { + LinkTabNavBarComponent, + LinkTabNavBarItem, +} from '../../../../shared/ui/link-tab-nav-bar/link-tab-nav-bar.component'; @Component({ selector: 'app-projects-results', - imports: [ - MatCardModule, - MatTabsModule, - RouterLink, - RouterLinkActive, - RouterOutlet, - ], + imports: [MatCardModule, MatTabsModule, RouterOutlet, LinkTabNavBarComponent], templateUrl: './projects-results.component.html', styleUrl: './projects-results.component.scss', }) @@ -32,18 +29,30 @@ export class KeywordsToProjectsResultsComponent { () => this.queryParamMap().get('fuzzy') === 'true', ); - readonly childRoutes = [ - { - path: 'dfg', - label: 'DFG-Projekte', - }, - { - path: 'eu', - label: 'EU-Projekte', - }, - { - path: 'bund', - label: 'BUND-Projekte', - }, - ]; + _links = computed(() => { + const links: LinkTabNavBarItem[] = [ + { + label: 'DFG-Projekte', + path: 'dfg', + queryParams: { authorId: null, institutionId: null, agency: null }, + queryParamsHandling: 'merge', + disabled: false, + }, + { + label: 'EU-Projekte', + path: 'eu', + queryParams: { authorId: null, institutionId: null, agency: null }, + queryParamsHandling: 'merge', + disabled: false, + }, + { + label: 'BUND-Projekte', + path: 'bund', + queryParams: { authorId: null, institutionId: null, agency: null }, + queryParamsHandling: 'merge', + disabled: false, + }, + ]; + return links; + }); } 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 958f8daa..16b344e7 100644 --- a/webapp/src/app/modules/person-projects/person-projects.component.html +++ b/webapp/src/app/modules/person-projects/person-projects.component.html @@ -1,22 +1,7 @@
    - + @if (resultTabPanel) { + + } 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 359a9d9c..519b28af 100644 --- a/webapp/src/app/modules/person-projects/person-projects.component.ts +++ b/webapp/src/app/modules/person-projects/person-projects.component.ts @@ -1,31 +1,33 @@ -import { Component } from '@angular/core'; +import { Component, computed } from '@angular/core'; import { RouterLink, RouterLinkActive, RouterOutlet } from '@angular/router'; import { MatCardModule } from '@angular/material/card'; import { MatTabsModule } from '@angular/material/tabs'; - +import { + LinkTabNavBarComponent, + LinkTabNavBarItem, +} from '../../shared/ui/link-tab-nav-bar/link-tab-nav-bar.component'; @Component({ selector: 'app-person-projects', standalone: true, - imports: [ - MatCardModule, - MatTabsModule, - RouterOutlet, - RouterLink, - RouterLinkActive, - ], + imports: [MatCardModule, MatTabsModule, RouterOutlet, LinkTabNavBarComponent], templateUrl: './person-projects.component.html', styleUrl: './person-projects.component.scss', }) export class PersonProjectsComponent { - readonly childRoutes = [ - { - path: 'dfg', - label: 'DFG-Projekte', - }, - { - path: 'eu', - label: 'EU-Projekte', - }, - ]; + _links = computed(() => { + const links: LinkTabNavBarItem[] = [ + { + label: 'DFG-Projekte', + path: 'dfg', + disabled: false, + }, + { + label: 'EU-Projekte', + path: 'eu', + disabled: false, + }, + ]; + return links; + }); } From de880fb9f06f121ffda0db00549a1c0407365fa2 Mon Sep 17 00:00:00 2001 From: Farajollahi Date: Wed, 5 Aug 2026 10:17:28 +0200 Subject: [PATCH 058/114] fix publications --- service/src/main/inse/dashboard/service.py | 72 ++++++++----------- .../src/main/inse/dashboard/test_service.py | 37 +++++----- 2 files changed, 47 insertions(+), 62 deletions(-) diff --git a/service/src/main/inse/dashboard/service.py b/service/src/main/inse/dashboard/service.py index 7351245f..ff80d646 100644 --- a/service/src/main/inse/dashboard/service.py +++ b/service/src/main/inse/dashboard/service.py @@ -30,6 +30,7 @@ from inse.projects.model import ( ProjectsFilteringProperties, ProjectType, ) +from inse.works.v2 import service as works_v2_service from .institute_helper import get_openalex_institution from .model import ( @@ -241,25 +242,32 @@ async def get_dashboard_publications( ) -> DashboardStatisticValue: normalized_id = _normalize_institution_id(institution_id) period = _dashboard_period(from_year, to_year) - institution = await institutions_v2_service.get_institution_by_id_or_raise( - raw_oa_institution_id=_raw_institution_id(normalized_id), - source=["id", "works_count", "counts_by_year"], - ) if period == (None, None): - value = int(institution.works_count or 0) - else: - value = sum( - int(entry.works_count or 0) - for entry in institution.counts_by_year or [] - if ( - (period[0] is None or int(entry.year or 0) >= period[0]) - and (period[1] is None or int(entry.year or 0) <= period[1]) - ) + institution = await institutions_v2_service.get_institution_by_id_or_raise( + raw_oa_institution_id=_raw_institution_id(normalized_id), + source=["id", "works_count"], ) + return DashboardStatisticValue( + institution_id=normalized_id, + organization_name=organization_name, + value=int(institution.works_count or 0), + ) + + first_year = period[0] if period[0] is not None else 1900 + last_year = period[1] if period[1] is not None else 2100 + publication_years = list(range(first_year, last_year + 1)) + + works = await works_v2_service.get_institution_works( + raw_oa_institution_id=_raw_institution_id(normalized_id), + page=0, + size=1, + publication_years=publication_years, + ) + return DashboardStatisticValue( institution_id=normalized_id, organization_name=organization_name, - value=value, + value=works.total, ) @@ -339,16 +347,8 @@ async def get_dashboard_eu_projects( topic_ids=None, filter_topic_ids=None, title=None, - funding_start_years=( - [str(year) for year in range(1900, period[1] + 1)] - if period[1] is not None - else None - ), - funding_end_years=( - [str(year) for year in range(period[0], 2101)] - if period[0] is not None - else None - ), + funding_start_years=[str(period[0])] if period[0] is not None else None, + funding_end_years=[str(period[1])] if period[1] is not None else None, countries=None, framework_programmes=None, funding_schemes=None, @@ -515,16 +515,8 @@ async def get_dashboard_bmbf_projects( funding_arts=None, topic_ids=None, filter_topic_ids=None, - funding_start_years=( - [str(year) for year in range(1900, period[1] + 1)] - if period[1] is not None - else None - ), - funding_end_years=( - [str(year) for year in range(period[0], 2101)] - if period[0] is not None - else None - ), + funding_start_years=[str(period[0])] if period[0] is not None else None, + funding_end_years=[str(period[1])] if period[1] is not None else None, countries=None, page=0, size=1, @@ -632,16 +624,8 @@ async def get_dashboard_dfg_projects( topic_ids=None, filter_topic_ids=None, title=None, - funding_start_years=( - [str(year) for year in range(1900, period[1] + 1)] - if period[1] is not None - else None - ), - funding_end_years=( - [str(year) for year in range(period[0], 2101)] - if period[0] is not None - else None - ), + funding_start_years=[str(period[0])] if period[0] is not None else None, + funding_end_years=[str(period[1])] if period[1] is not None else None, page=0, size=1, sort_by="id", diff --git a/service/src/main/inse/dashboard/test_service.py b/service/src/main/inse/dashboard/test_service.py index c3dae57f..305a27de 100644 --- a/service/src/main/inse/dashboard/test_service.py +++ b/service/src/main/inse/dashboard/test_service.py @@ -25,7 +25,6 @@ from inse.dashboard.service import ( get_topic_word_cloud, ) from inse.model import ESCluster, ESIndex -from inse.models.openalex.author_counts_by_year_inner import AuthorCountsByYearInner from inse.models.openalex.institution import Institution from inse.models.openalex.meta import Meta from inse.persons.model import CustomAuthorsListResponse @@ -229,22 +228,18 @@ async def test_dashboard_statistics_counts_organization_data_and_all_projects(): "bmbf_projects": 5, } -@pytest.mark.anyio -async def test_dashboard_publications_uses_institutions_v2_counts(): - institution = Institution( - id=ORG_INSTITUTION_ID, - works_count=250, - counts_by_year=[ - AuthorCountsByYearInner(year=2021, works_count=10), - AuthorCountsByYearInner(year=2022, works_count=12), - AuthorCountsByYearInner(year=2023, works_count=14), - ], - ) +@pytest.mark.anyio +async def test_dashboard_publications_uses_works_v2_only_for_period(): with patch( "inse.dashboard.service.institutions_v2_service.get_institution_by_id_or_raise", - new=AsyncMock(return_value=institution), - ) as mocked_get_institution: + new=AsyncMock( + return_value=Institution(id=ORG_INSTITUTION_ID, works_count=250) + ), + ) as mocked_get_institution, patch( + "inse.dashboard.service.works_v2_service.get_institution_works", + new=AsyncMock(return_value=SimpleNamespace(elements=[], total=22)), + ) as mocked_get_works: all_time = await get_dashboard_publications( ORG_INSTITUTION_ID, "Example Org", @@ -258,9 +253,15 @@ async def test_dashboard_publications_uses_institutions_v2_counts(): assert all_time.value == 250 assert selected_period.value == 22 - assert mocked_get_institution.await_args_list[0].kwargs == { + mocked_get_institution.assert_awaited_once_with( + raw_oa_institution_id="I123", + source=["id", "works_count"], + ) + assert mocked_get_works.await_args_list[0].kwargs == { "raw_oa_institution_id": "I123", - "source": ["id", "works_count", "counts_by_year"], + "page": 0, + "size": 1, + "publication_years": [2021, 2022], } @@ -362,8 +363,8 @@ async def test_dashboard_eu_projects_uses_projects_service_total(): mocked_get_projects.assert_awaited_once() call = mocked_get_projects.await_args assert call.kwargs["raw_oa_institution_id"] == "I123" - assert call.kwargs["funding_start_years"][-1] == "2021" - assert call.kwargs["funding_end_years"][0] == "2019" + assert call.kwargs["funding_start_years"] == ["2019"] + assert call.kwargs["funding_end_years"] == ["2021"] assert call.kwargs["project_types"] == list(EuCordisProjectType) assert call.kwargs["page"] == 0 assert call.kwargs["size"] == 1 From 727c3fde671af118c0ed2ad7bc4807d8c77ff253 Mon Sep 17 00:00:00 2001 From: Farajollahi Date: Wed, 5 Aug 2026 10:44:09 +0200 Subject: [PATCH 059/114] fix counts --- service/src/main/inse/dashboard/service.py | 98 ++++++++++++++----- .../src/main/inse/dashboard/test_service.py | 63 +++++++++--- .../inse/projects/projects_search_client.py | 5 +- .../main/inse/projects/test_projects_dfg.py | 30 ++++++ 4 files changed, 159 insertions(+), 37 deletions(-) diff --git a/service/src/main/inse/dashboard/service.py b/service/src/main/inse/dashboard/service.py index ff80d646..ec1a9b8f 100644 --- a/service/src/main/inse/dashboard/service.py +++ b/service/src/main/inse/dashboard/service.py @@ -30,7 +30,6 @@ from inse.projects.model import ( ProjectsFilteringProperties, ProjectType, ) -from inse.works.v2 import service as works_v2_service from .institute_helper import get_openalex_institution from .model import ( @@ -177,17 +176,48 @@ def _project_overlap_filter( return {"bool": {"filter": filters}} if filters else None -def _date_period(period: DashboardPeriod, date_format: str) -> DashboardPeriod: +def _project_boundary_year_filter( + start_field: str, + end_field: str, + period: DashboardPeriod, + date_format: Literal["iso", "de", "year"], +) -> dict[str, Any] | None: from_year, to_year = period - if date_format == "iso": - return ( - f"{from_year}-01-01" if from_year is not None else None, - f"{to_year}-12-31" if to_year is not None else None, - ) - return ( - f"01.01.{from_year}" if from_year is not None else None, - f"31.12.{to_year}" if to_year is not None else None, - ) + filters: list[dict[str, Any]] = [] + + if from_year is not None: + if date_format == "year": + filters.append({"term": {start_field: from_year}}) + else: + first_day = ( + f"{from_year}-01-01" + if date_format == "iso" + else f"01.01.{from_year}" + ) + last_day = ( + f"{from_year}-12-31" + if date_format == "iso" + else f"31.12.{from_year}" + ) + filters.append( + {"range": {start_field: {"gte": first_day, "lte": last_day}}} + ) + + if to_year is not None: + if date_format == "year": + filters.append({"term": {end_field: to_year}}) + else: + first_day = ( + f"{to_year}-01-01" if date_format == "iso" else f"01.01.{to_year}" + ) + last_day = ( + f"{to_year}-12-31" if date_format == "iso" else f"31.12.{to_year}" + ) + filters.append( + {"range": {end_field: {"gte": first_day, "lte": last_day}}} + ) + + return {"bool": {"filter": filters}} if filters else None def get_dashboard_organization( @@ -257,17 +287,36 @@ async def get_dashboard_publications( last_year = period[1] if period[1] is not None else 2100 publication_years = list(range(first_year, last_year + 1)) - works = await works_v2_service.get_institution_works( - raw_oa_institution_id=_raw_institution_id(normalized_id), - page=0, - size=1, - publication_years=publication_years, + value = await elasticsearch.count( + index=ESIndex.OPENALEX_WORKS_WILDCARD, + query={ + "bool": { + "filter": [ + { + "nested": { + "path": "authorships", + "query": { + "nested": { + "path": "authorships.institutions", + "query": { + "term": { + "authorships.institutions.id": normalized_id + } + }, + } + }, + } + }, + {"terms": {"publication_year": publication_years}}, + ] + } + }, ) return DashboardStatisticValue( institution_id=normalized_id, organization_name=organization_name, - value=works.total, + value=value, ) @@ -396,10 +445,11 @@ async def get_dashboard_eu_project_statuses( today = datetime.now().date().isoformat() period = _dashboard_period(from_year, to_year) filters: list[dict[str, Any]] = [{"terms": {"id": sorted(project_ids)}}] - if period_filter := _project_overlap_filter( + if period_filter := _project_boundary_year_filter( "startDate", "endDate", - _date_period(period, "iso"), + period, + "iso", ): filters.append(period_filter) query = ( @@ -541,10 +591,11 @@ async def get_dashboard_bmbf_project_statuses( aliases = await _institution_aliases(normalized_id, organization_name) period = _dashboard_period(from_year, to_year) filters = [_alias_match_query("Zuwendungsempfänger", aliases)] - if period_filter := _project_overlap_filter( + if period_filter := _project_boundary_year_filter( "funding_start", "funding_end", - _date_period(period, "de"), + period, + "de", ): filters.append(period_filter) today = datetime.now().strftime("%d.%m.%Y") @@ -631,6 +682,7 @@ async def get_dashboard_dfg_projects( sort_by="id", sort_direction="asc", fuzzy=False, + skip_enrichment=True, ) return DashboardStatisticValue( institution_id=normalized_id, @@ -676,11 +728,11 @@ async def get_dashboard_dfg_project_statuses( } } ] - if period_filter := _project_overlap_filter( + if period_filter := _project_boundary_year_filter( "projects.funding_start", "projects.funding_end", period, - missing_end_is_ongoing=True, + "year", ): selected_project_filters.append(period_filter) diff --git a/service/src/main/inse/dashboard/test_service.py b/service/src/main/inse/dashboard/test_service.py index 305a27de..74be4583 100644 --- a/service/src/main/inse/dashboard/test_service.py +++ b/service/src/main/inse/dashboard/test_service.py @@ -9,8 +9,9 @@ from sqlmodel import Session, SQLModel, create_engine from inse import config from inse.auth.model import AccessToken, Organization, UserRole from inse.dashboard.service import ( - _openalex_work_authors_by_eu_projects, _get_dfg_project_ids_from_projects_service, + _openalex_work_authors_by_eu_projects, + _project_boundary_year_filter, _reconcile_project_status_counts, _top_news_authors, get_dashboard_bmbf_projects, @@ -50,6 +51,40 @@ def test_project_status_counts_match_authoritative_total(): assert _reconcile_project_status_counts(7, 4, 2, 3) == (2, 2, 3) +def test_project_status_period_uses_exact_boundary_years(): + assert _project_boundary_year_filter( + "startDate", "endDate", (2022, 2026), "iso" + ) == { + "bool": { + "filter": [ + { + "range": { + "startDate": {"gte": "2022-01-01", "lte": "2022-12-31"} + } + }, + { + "range": { + "endDate": {"gte": "2026-01-01", "lte": "2026-12-31"} + } + }, + ] + } + } + assert _project_boundary_year_filter( + "projects.funding_start", + "projects.funding_end", + (2022, 2026), + "year", + ) == { + "bool": { + "filter": [ + {"term": {"projects.funding_start": 2022}}, + {"term": {"projects.funding_end": 2026}}, + ] + } + } + + @pytest.mark.anyio async def test_top_news_authors_applies_dashboard_period(): response = { @@ -230,16 +265,16 @@ async def test_dashboard_statistics_counts_organization_data_and_all_projects(): @pytest.mark.anyio -async def test_dashboard_publications_uses_works_v2_only_for_period(): +async def test_dashboard_publications_uses_exact_es_count_for_period(): with patch( "inse.dashboard.service.institutions_v2_service.get_institution_by_id_or_raise", new=AsyncMock( return_value=Institution(id=ORG_INSTITUTION_ID, works_count=250) ), ) as mocked_get_institution, patch( - "inse.dashboard.service.works_v2_service.get_institution_works", - new=AsyncMock(return_value=SimpleNamespace(elements=[], total=22)), - ) as mocked_get_works: + "inse.dashboard.service.elasticsearch.count", + new=AsyncMock(return_value=22), + ) as mocked_count: all_time = await get_dashboard_publications( ORG_INSTITUTION_ID, "Example Org", @@ -257,12 +292,15 @@ async def test_dashboard_publications_uses_works_v2_only_for_period(): raw_oa_institution_id="I123", source=["id", "works_count"], ) - assert mocked_get_works.await_args_list[0].kwargs == { - "raw_oa_institution_id": "I123", - "page": 0, - "size": 1, - "publication_years": [2021, 2022], + mocked_count.assert_awaited_once() + count_call = mocked_count.await_args.kwargs + assert count_call["index"] == ESIndex.OPENALEX_WORKS_WILDCARD + filters = count_call["query"]["bool"]["filter"] + assert filters[0]["nested"]["path"] == "authorships" + assert filters[0]["nested"]["query"]["nested"]["query"] == { + "term": {"authorships.institutions.id": ORG_INSTITUTION_ID} } + assert filters[1] == {"terms": {"publication_year": [2021, 2022]}} @pytest.mark.anyio @@ -311,8 +349,9 @@ async def test_dashboard_dfg_projects_uses_projects_service_total(): mocked_get_projects.assert_awaited_once() call = mocked_get_projects.await_args assert call.kwargs["raw_oa_institution_id"] == "I123" - assert call.kwargs["funding_start_years"][-1] == "2022" - assert call.kwargs["funding_end_years"][0] == "2020" + assert call.kwargs["funding_start_years"] == ["2020"] + assert call.kwargs["funding_end_years"] == ["2022"] + assert call.kwargs["skip_enrichment"] is True assert call.kwargs["page"] == 0 assert call.kwargs["size"] == 1 diff --git a/service/src/main/inse/projects/projects_search_client.py b/service/src/main/inse/projects/projects_search_client.py index 3b80b959..05911790 100644 --- a/service/src/main/inse/projects/projects_search_client.py +++ b/service/src/main/inse/projects/projects_search_client.py @@ -599,7 +599,6 @@ async def search_dfg_projects( body["sort"] = [sort_config] # print(f"Executing DFG project search with body: {json.dumps(body, indent=2)}") # === Execute Search === - print(f"Executing DFG project search with body: {json.dumps(body, indent=2)}") response = await elasticsearch.search( index=ESIndex.DFG_PROJECTS, body=body, @@ -611,6 +610,9 @@ async def search_dfg_projects( if skip_enrichment: return _complete_response_to_dfg_project_page(response, page, size) + if not hits: + return _complete_response_to_dfg_project_page(response, page, size) + project_ids = [hit["_source"]["id"] for hit in hits] topic_lookup = await get_openalex_topics_for_dfg_projects(project_ids=project_ids) @@ -647,7 +649,6 @@ async def search_dfg_projects( # 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") - print("ENRIECHED",source.get("institutions", [])) return _complete_response_to_dfg_project_page(response, page, size) def _complete_response_to_dfg_project_page( diff --git a/service/src/main/inse/projects/test_projects_dfg.py b/service/src/main/inse/projects/test_projects_dfg.py index f9eb82b9..bc331c62 100644 --- a/service/src/main/inse/projects/test_projects_dfg.py +++ b/service/src/main/inse/projects/test_projects_dfg.py @@ -1,4 +1,7 @@ +from unittest.mock import AsyncMock, patch + import pytest + from inse.projects import projects_search_client @@ -20,6 +23,33 @@ async def test_search_dfg_projects(): for name in element.names ) + +@pytest.mark.anyio +async def test_search_dfg_projects_returns_empty_page_without_enrichment_crash(): + response = { + "hits": { + "total": {"value": 0}, + "hits": [], + } + } + with patch( + "inse.projects.projects_search_client.elasticsearch.search", + new=AsyncMock(return_value=response), + ) as mocked_search: + result = await projects_search_client.search_dfg_projects( + page=0, + size=1, + funding_start_years=["2022"], + funding_end_years=["2026"], + ) + + assert result.total == 0 + assert result.elements == [] + query = mocked_search.await_args.kwargs["body"]["query"] + assert {"terms": {"funding_start": ["2022"]}} in query["bool"]["must"] + assert {"terms": {"funding_end": ["2026"]}} in query["bool"]["must"] + + @pytest.mark.anyio async def test_get_dfg_project_by_id(): # Get by ID of the project we found or a known one From 3b1ffda3b280d79eac677a07fa43b2a6780de578 Mon Sep 17 00:00:00 2001 From: genja Date: Thu, 6 Aug 2026 01:41:20 +0200 Subject: [PATCH 060/114] added HTTP 403 Forbidden for project access requests from unauthorized institutions --- service/src/main/inse/projects/logic.py | 38 +++- service/src/main/inse/projects/router.py | 205 +++++++++++---------- service/src/main/inse/projects/service.py | 35 +++- webapp/src/app/api/api/projects.service.ts | 40 ++-- 4 files changed, 204 insertions(+), 114 deletions(-) diff --git a/service/src/main/inse/projects/logic.py b/service/src/main/inse/projects/logic.py index ef96aec4..5683280a 100644 --- a/service/src/main/inse/projects/logic.py +++ b/service/src/main/inse/projects/logic.py @@ -1,13 +1,49 @@ import logging from collections import defaultdict from typing import Any - +import inse.authors.v2.service as author_service +from inse.auth.model import AccessTokenMetadata from inse.integrations import elasticsearch from inse.model import ESCluster, ESIndex from inse.projects.model import EuCordisProjectType logger = logging.getLogger(__name__) + +async def is_projects_access_forbidden( + access_token_metadata: AccessTokenMetadata, + raw_oa_institution_id: str | None, + raw_oa_author_id: str | None, +) -> bool: + """ + Determines if access to projects is forbidden based on the provided access token metadata + and the raw OpenAlex institution and author IDs. + + Args: + access_token_metadata (AccessTokenMetadata): Metadata from the access token. + raw_oa_institution_id (str | None): The raw OpenAlex institution ID. + raw_oa_author_id (str | None): The raw OpenAlex author ID. + + Returns: + bool: True if access is forbidden, False otherwise. + """ + effective_institution_id = access_token_metadata.effective_institution_id + + if raw_oa_institution_id and effective_institution_id != raw_oa_institution_id: + return True + + if raw_oa_author_id: + authors_profile = await author_service.get_author_by_id(raw_oa_author_id) + if not authors_profile: + return True # Author not found, access forbidden + + authors_last_known_institution_ids = [inst.id.split("/")[-1] for inst in authors_profile.last_known_institutions] + print(f"Author's last known institution IDs: {authors_last_known_institution_ids}") + if effective_institution_id not in authors_last_known_institution_ids: + return True # Effective institution ID does not match any of the author's last known institutions + + return False + async def get_dfg_author_names_by_ids(author_ids: list[int]) -> list[str] | None: try: body = { diff --git a/service/src/main/inse/projects/router.py b/service/src/main/inse/projects/router.py index 5c7c426f..71e44778 100644 --- a/service/src/main/inse/projects/router.py +++ b/service/src/main/inse/projects/router.py @@ -2,6 +2,8 @@ import logging from typing import Annotated from fastapi import APIRouter, Body, Depends, Path, Query, status +from inse.auth.model import AccessTokenMetadata +from inse.auth.service import CurrentUserAccessTokenPayloadDep from inse.institutions.institutions_search_client import ( InstitutionsSearchClient, ) @@ -63,6 +65,105 @@ async def search_bund_projects( ) +@router.get( + "/dfg/search", + summary="Get DFG projects.", + description="Returns a page of DFG projects based on the provided pagination parameters and optional institution filter.", + operation_id="getDfgProjects", + responses={ + status.HTTP_200_OK: { + "description": "Successful Response", + "model": DfgProjectPage, + }, + status.HTTP_404_NOT_FOUND: {"description": "Institution not found"}, + status.HTTP_403_FORBIDDEN: {"description": "Access denied for the provided institution ID"}, + }, + response_model_by_alias=False, +) +async def get_dfg_projects( + access_token_metadata: Annotated[AccessTokenMetadata, CurrentUserAccessTokenPayloadDep], + institutions_search_client: Annotated[ + InstitutionsSearchClient, Depends(get_institutions_search_client) + ], + raw_oa_institution_id: Annotated[ + str | None, Query(description="The openalex institution ID to filter by.") + ] = None, + author_id: Annotated[str | None, Query(description="The openalex author ID to filter by.")] = None, + author_filter_ids: Annotated[list[int] | None, Query(description="The dfg author IDs to filter by.")] = None, + institution_ids: Annotated[ + list[int] | None, Query(description="The institution IDs to filter by.") + ] = None, + title: Annotated[ + str | None, Query(description="The title to filter by.") + ] = None, + keywords: Annotated[ + list[str] | None, Query(description="Raw keywords to search in title/abstract/subject fields.") + ] = None, + topic_ids: Annotated[ + list[str] | None, Query(description="The openalex topic IDs to filter by.") + ] = None, + filter_topic_ids: Annotated[ + list[str] | None, + 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[list[str] | None, Query(description="The funding start years to filter by.")] = None, + funding_end_years: Annotated[list[str] | None, 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, " + "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, + institution_ids, + keywords, + topic_ids, + filter_topic_ids, + title, + funding_start_years, + funding_end_years, + page, + size, + sort_by, + sort_direction, + fuzzy, + ) + return await projects_service.get_dfg_projects_by_author_id( + access_token_metadata=access_token_metadata, + institutions_search_client=institutions_search_client, + raw_oa_institution_id=raw_oa_institution_id, + author_id=author_id, + author_filter_ids=author_filter_ids, + institution_ids=institution_ids, + funding_start_years=funding_start_years, + funding_end_years=funding_end_years, + title=title, + 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( "/dfg/{id}", summary="Get a single DFG project.", @@ -96,10 +197,13 @@ async def get_single_dfg_project( "description": "Successful Response", "model": BundProjectPage, }, + status.HTTP_404_NOT_FOUND: {"description": "Institution not found"}, + status.HTTP_403_FORBIDDEN: {"description": "Access denied for the provided institution ID"}, }, response_model_by_alias=False, ) async def search_bund_projects( + access_token_metadata: Annotated[AccessTokenMetadata, CurrentUserAccessTokenPayloadDep], institutions_search_client: Annotated[ InstitutionsSearchClient, Depends(get_institutions_search_client) ], @@ -156,6 +260,7 @@ async def search_bund_projects( ] = False, ) -> BundProjectPage: return await projects_service.search_bund_projects_with_filters( + access_token_metadata=access_token_metadata, institutions_search_client=institutions_search_client, executing_agency=executing_agency, funding_arts=funding_arts, @@ -217,10 +322,12 @@ from inse.projects.service import search_eu_cordis_projects "model": EuCordisProjectSearchPage, }, status.HTTP_404_NOT_FOUND: {"description": "Institution not found"}, + status.HTTP_403_FORBIDDEN: {"description": "Access denied for the provided institution ID"}, }, response_model_by_alias=False, ) async def search_eu_cordis_projects_endpoint( + access_token_metadata: Annotated[AccessTokenMetadata, CurrentUserAccessTokenPayloadDep], institutions_search_client: Annotated[ InstitutionsSearchClient, Depends(get_institutions_search_client) ], @@ -299,6 +406,7 @@ async def search_eu_cordis_projects_endpoint( bool, Query(description="Use OpenAlex topic-id resolution if true, otherwise raw keyword search."), ] = False, + ) -> EuCordisProjectSearchPage: logger.debug( "Received EU CORDIS search request: raw_oa_institution_id=%s, " @@ -332,6 +440,7 @@ async def search_eu_cordis_projects_endpoint( ) return await search_eu_cordis_projects( + access_token_metadata=access_token_metadata, institutions_search_client=institutions_search_client, raw_oa_institution_id=raw_oa_institution_id, author_id=author_id, @@ -629,102 +738,6 @@ async def get_institution_cordis_eu_projects_funding_over_time( ) -@router.get( - "/person/dfg/search", - summary="Get DFG projects.", - description="Returns a page of DFG projects based on the provided pagination parameters and optional institution filter.", - operation_id="getDfgProjects", - responses={ - status.HTTP_200_OK: { - "description": "Successful Response", - "model": DfgProjectPage, - }, - status.HTTP_404_NOT_FOUND: {"description": "Institution not found"}, - }, - response_model_by_alias=False, -) -async def get_dfg_projects( - institutions_search_client: Annotated[ - InstitutionsSearchClient, Depends(get_institutions_search_client) - ], - raw_oa_institution_id: Annotated[ - str | None, Query(description="The openalex institution ID to filter by.") - ] = None, - author_id: Annotated[str | None, Query(description="The openalex author ID to filter by.")] = None, - author_filter_ids: Annotated[list[int] | None, Query(description="The dfg author IDs to filter by.")] = None, - institution_ids: Annotated[ - list[int] | None, Query(description="The institution IDs to filter by.") - ] = None, - title: Annotated[ - str | None, Query(description="The title to filter by.") - ] = None, - keywords: Annotated[ - list[str] | None, Query(description="Raw keywords to search in title/abstract/subject fields.") - ] = None, - topic_ids: Annotated[ - list[str] | None, Query(description="The openalex topic IDs to filter by.") - ] = None, - filter_topic_ids: Annotated[ - list[str] | None, - 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[list[str] | None, Query(description="The funding start years to filter by.")] = None, - funding_end_years: Annotated[list[str] | None, 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, " - "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, - institution_ids, - keywords, - topic_ids, - filter_topic_ids, - title, - funding_start_years, - funding_end_years, - page, - size, - sort_by, - sort_direction, - fuzzy, - ) - return await projects_service.get_dfg_projects_by_author_id( - institutions_search_client=institutions_search_client, - raw_oa_institution_id=raw_oa_institution_id, - author_id=author_id, - author_filter_ids=author_filter_ids, - institution_ids=institution_ids, - funding_start_years=funding_start_years, - funding_end_years=funding_end_years, - title=title, - 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 ab5fa644..dc5b92ca 100644 --- a/service/src/main/inse/projects/service.py +++ b/service/src/main/inse/projects/service.py @@ -3,6 +3,7 @@ import logging from typing import Any from inse.exceptions import NotFoundException +from inse.auth.model import AccessTokenMetadata from inse.institutions.institutions_search_client import ( InstitutionsSearchClient, ) @@ -27,7 +28,7 @@ from inse.projects.eu_cordis_projects_client import ( search_eu_cordis_projects as _search_eu_cordis_projects_es, ) from inse.projects.logic import ( - get_dfg_author_names_by_ids, + get_dfg_author_names_by_ids, is_projects_access_forbidden ) from inse.projects.model import ( BundProjectPage, @@ -42,7 +43,7 @@ from inse.projects.model import ( SortDirection, ) from inse.works.logic import get_publication_dois_of_author - +from fastapi import HTTPException as HttpException logger = logging.getLogger(__name__) @@ -158,6 +159,7 @@ async def _get_dfg_project_ids_for_openalex_authors( return list(set.intersection(*project_sets)) async def get_dfg_projects_by_author_id( + access_token_metadata: AccessTokenMetadata, institutions_search_client: InstitutionsSearchClient, raw_oa_institution_id: str | None, author_id: str | None, @@ -198,6 +200,12 @@ async def get_dfg_projects_by_author_id( ) filter_names = [] author_project_ids = [] + is_forbidden = await is_projects_access_forbidden(access_token_metadata, raw_oa_institution_id, author_id) + if is_forbidden: + raise HttpException( + status_code=403, + detail="Access denied for the provided author ID or institution ID", + ) if author_id: author_project_ids = await _get_dfg_project_ids_for_openalex_authors([author_id]) logger.info("Author project IDs for author_id:%s: %s", author_id, author_project_ids) @@ -221,6 +229,10 @@ async def get_dfg_projects_by_author_id( ) institution_aliases = [] if raw_oa_institution_id: + if institutions_search_client is None: + raise ValueError( + "institutions_search_client must be provided when raw_oa_institution_id is set" + ) institution_aliases = ( await institutions_search_client.get_institution_aliases_by_oa_institution_id( raw_oa_institution_id @@ -409,6 +421,7 @@ async def get_institution_bund_projects_funding_over_time( #Bund async def search_bund_projects_with_filters( + access_token_metadata: AccessTokenMetadata, institutions_search_client: InstitutionsSearchClient, executing_agency: str | None, raw_oa_institution_id: str | None, @@ -426,8 +439,18 @@ async def search_bund_projects_with_filters( sort_direction: str = "asc", fuzzy: bool = False, ) -> BundProjectPage: + is_forbidden = await is_projects_access_forbidden(access_token_metadata, raw_oa_institution_id, None) + if is_forbidden: + raise HttpException( + status_code=403, + detail="Access denied for the provided author ID or institution ID", + ) institution_aliases = [] if raw_oa_institution_id: + if institutions_search_client is None: + raise ValueError( + "institutions_search_client must be provided when raw_oa_institution_id is set" + ) institution_aliases = ( await institutions_search_client.get_institution_aliases_by_oa_institution_id( raw_oa_institution_id @@ -603,6 +626,7 @@ async def _get_eu_project_ids_for_openalex_authors( async def search_eu_cordis_projects( + access_token_metadata: AccessTokenMetadata, page: int, size: int, project_types: list[EuCordisProjectType] | None = None, @@ -641,8 +665,13 @@ async def search_eu_cordis_projects( funding scheme, status, funding years, country) are ANDed together as in eu_cordis_projects_client.search_eu_cordis_projects. """ + is_forbidden = await is_projects_access_forbidden(access_token_metadata, raw_oa_institution_id, author_id) + if is_forbidden: + raise HttpException( + status_code=403, + detail="Access denied for the provided author ID or institution ID", + ) resolved_organization_names: list[str] = list(organization_names or []) - if raw_oa_institution_id: if institutions_search_client is None: raise ValueError( diff --git a/webapp/src/app/api/api/projects.service.ts b/webapp/src/app/api/api/projects.service.ts index a5095f5b..0db7818b 100644 --- a/webapp/src/app/api/api/projects.service.ts +++ b/webapp/src/app/api/api/projects.service.ts @@ -66,7 +66,7 @@ export class ProjectsService extends BaseService { /** * Get DFG projects. * Returns a page of DFG projects based on the provided pagination parameters and optional institution filter. - * @endpoint get /api/projects/person/dfg/search + * @endpoint get /api/projects/dfg/search * @param rawOaInstitutionId The openalex institution ID to filter by. * @param authorId The openalex author ID to filter by. * @param authorFilterIds The dfg author IDs to filter by. @@ -82,13 +82,14 @@ export class ProjectsService extends BaseService { * @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 secureFgpAcc * @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(rawOaInstitutionId?: string, authorId?: string, authorFilterIds?: Array, institutionIds?: Array, title?: string, keywords?: Array, topicIds?: Array, filterTopicIds?: Array, fundingStartYears?: Array, fundingEndYears?: Array, page?: number, size?: number, sortBy?: string, sortDirection?: string, fuzzy?: boolean, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; - public getDfgProjects(rawOaInstitutionId?: string, authorId?: string, authorFilterIds?: Array, institutionIds?: Array, title?: string, keywords?: Array, topicIds?: Array, filterTopicIds?: Array, fundingStartYears?: Array, fundingEndYears?: Array, page?: number, size?: number, sortBy?: string, sortDirection?: string, fuzzy?: boolean, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public getDfgProjects(rawOaInstitutionId?: string, authorId?: string, authorFilterIds?: Array, institutionIds?: Array, title?: string, keywords?: Array, topicIds?: Array, filterTopicIds?: Array, fundingStartYears?: Array, fundingEndYears?: Array, page?: number, size?: number, sortBy?: string, sortDirection?: string, fuzzy?: boolean, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public getDfgProjects(rawOaInstitutionId?: string, authorId?: string, authorFilterIds?: Array, institutionIds?: Array, title?: string, keywords?: Array, topicIds?: Array, filterTopicIds?: Array, fundingStartYears?: Array, fundingEndYears?: Array, page?: number, size?: number, sortBy?: string, sortDirection?: string, fuzzy?: boolean, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + public getDfgProjects(rawOaInstitutionId?: string, authorId?: string, authorFilterIds?: Array, institutionIds?: Array, title?: string, keywords?: Array, topicIds?: Array, filterTopicIds?: Array, fundingStartYears?: Array, fundingEndYears?: Array, page?: number, size?: number, sortBy?: string, sortDirection?: string, fuzzy?: boolean, secureFgpAcc?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public getDfgProjects(rawOaInstitutionId?: string, authorId?: string, authorFilterIds?: Array, institutionIds?: Array, title?: string, keywords?: Array, topicIds?: Array, filterTopicIds?: Array, fundingStartYears?: Array, fundingEndYears?: Array, page?: number, size?: number, sortBy?: string, sortDirection?: string, fuzzy?: boolean, secureFgpAcc?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getDfgProjects(rawOaInstitutionId?: string, authorId?: string, authorFilterIds?: Array, institutionIds?: Array, title?: string, keywords?: Array, topicIds?: Array, filterTopicIds?: Array, fundingStartYears?: Array, fundingEndYears?: Array, page?: number, size?: number, sortBy?: string, sortDirection?: string, fuzzy?: boolean, secureFgpAcc?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getDfgProjects(rawOaInstitutionId?: string, authorId?: string, authorFilterIds?: Array, institutionIds?: Array, title?: string, keywords?: Array, topicIds?: Array, filterTopicIds?: Array, fundingStartYears?: Array, fundingEndYears?: Array, page?: number, size?: number, sortBy?: string, sortDirection?: string, fuzzy?: boolean, secureFgpAcc?: string, 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, @@ -152,6 +153,9 @@ export class ProjectsService extends BaseService { let localVarHeaders = this.defaultHeaders; + // authentication (HTTPBearer) required + localVarHeaders = this.configuration.addCredentialToHeaders('HTTPBearer', 'Authorization', localVarHeaders, 'Bearer '); + const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([ 'application/json' ]); @@ -175,7 +179,7 @@ export class ProjectsService extends BaseService { } } - let localVarPath = `/api/projects/person/dfg/search`; + let localVarPath = `/api/projects/dfg/search`; const { basePath, withCredentials } = this.configuration; return this.httpClient.request('get', `${basePath}${localVarPath}`, { @@ -846,13 +850,14 @@ export class ProjectsService extends BaseService { * @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 secureFgpAcc * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public searchBundProjectsWithFilters(executingAgency?: Array, fundingArts?: Array, title?: string, keywords?: Array, topicIds?: Array, filterTopicIds?: Array, fundingStartYears?: Array, fundingEndYears?: Array, countries?: Array, rawOaInstitutionId?: string, page?: number, size?: number, sortBy?: string, sortDirection?: string, fuzzy?: boolean, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; - public searchBundProjectsWithFilters(executingAgency?: Array, fundingArts?: Array, title?: string, keywords?: Array, topicIds?: Array, filterTopicIds?: Array, fundingStartYears?: Array, fundingEndYears?: Array, countries?: Array, rawOaInstitutionId?: string, page?: number, size?: number, sortBy?: string, sortDirection?: string, fuzzy?: boolean, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public searchBundProjectsWithFilters(executingAgency?: Array, fundingArts?: Array, title?: string, keywords?: Array, topicIds?: Array, filterTopicIds?: Array, fundingStartYears?: Array, fundingEndYears?: Array, countries?: Array, rawOaInstitutionId?: string, page?: number, size?: number, sortBy?: string, sortDirection?: string, fuzzy?: boolean, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public searchBundProjectsWithFilters(executingAgency?: Array, fundingArts?: Array, title?: string, keywords?: Array, topicIds?: Array, filterTopicIds?: Array, fundingStartYears?: Array, fundingEndYears?: Array, countries?: Array, rawOaInstitutionId?: string, page?: number, size?: number, sortBy?: string, sortDirection?: string, fuzzy?: boolean, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + public searchBundProjectsWithFilters(executingAgency?: Array, fundingArts?: Array, title?: string, keywords?: Array, topicIds?: Array, filterTopicIds?: Array, fundingStartYears?: Array, fundingEndYears?: Array, countries?: Array, rawOaInstitutionId?: string, page?: number, size?: number, sortBy?: string, sortDirection?: string, fuzzy?: boolean, secureFgpAcc?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public searchBundProjectsWithFilters(executingAgency?: Array, fundingArts?: Array, title?: string, keywords?: Array, topicIds?: Array, filterTopicIds?: Array, fundingStartYears?: Array, fundingEndYears?: Array, countries?: Array, rawOaInstitutionId?: string, page?: number, size?: number, sortBy?: string, sortDirection?: string, fuzzy?: boolean, secureFgpAcc?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public searchBundProjectsWithFilters(executingAgency?: Array, fundingArts?: Array, title?: string, keywords?: Array, topicIds?: Array, filterTopicIds?: Array, fundingStartYears?: Array, fundingEndYears?: Array, countries?: Array, rawOaInstitutionId?: string, page?: number, size?: number, sortBy?: string, sortDirection?: string, fuzzy?: boolean, secureFgpAcc?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public searchBundProjectsWithFilters(executingAgency?: Array, fundingArts?: Array, title?: string, keywords?: Array, topicIds?: Array, filterTopicIds?: Array, fundingStartYears?: Array, fundingEndYears?: Array, countries?: Array, rawOaInstitutionId?: string, page?: number, size?: number, sortBy?: string, sortDirection?: string, fuzzy?: boolean, secureFgpAcc?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { let localVarQueryParameters = new HttpParams({encoder: this.encoder}); if (executingAgency) { @@ -920,6 +925,9 @@ export class ProjectsService extends BaseService { let localVarHeaders = this.defaultHeaders; + // authentication (HTTPBearer) required + localVarHeaders = this.configuration.addCredentialToHeaders('HTTPBearer', 'Authorization', localVarHeaders, 'Bearer '); + const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([ 'application/json' ]); @@ -984,13 +992,14 @@ export class ProjectsService extends BaseService { * @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 secureFgpAcc * @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 searchEuCordisProjects(rawOaInstitutionId?: string, authorId?: string, authorIds?: Array, organizationIds?: Array, organizationNames?: Array, projectTypes?: Array, title?: string, keywords?: Array, topicIds?: Array, filterTopicIds?: Array, fundingStartYears?: Array, fundingEndYears?: Array, countries?: Array, frameworkProgrammes?: Array, fundingSchemes?: Array, statuses?: Array, page?: number, size?: number, sortBy?: string, sortDirection?: string, fuzzy?: boolean, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; - public searchEuCordisProjects(rawOaInstitutionId?: string, authorId?: string, authorIds?: Array, organizationIds?: Array, organizationNames?: Array, projectTypes?: Array, title?: string, keywords?: Array, topicIds?: Array, filterTopicIds?: Array, fundingStartYears?: Array, fundingEndYears?: Array, countries?: Array, frameworkProgrammes?: Array, fundingSchemes?: Array, statuses?: Array, page?: number, size?: number, sortBy?: string, sortDirection?: string, fuzzy?: boolean, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public searchEuCordisProjects(rawOaInstitutionId?: string, authorId?: string, authorIds?: Array, organizationIds?: Array, organizationNames?: Array, projectTypes?: Array, title?: string, keywords?: Array, topicIds?: Array, filterTopicIds?: Array, fundingStartYears?: Array, fundingEndYears?: Array, countries?: Array, frameworkProgrammes?: Array, fundingSchemes?: Array, statuses?: Array, page?: number, size?: number, sortBy?: string, sortDirection?: string, fuzzy?: boolean, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public searchEuCordisProjects(rawOaInstitutionId?: string, authorId?: string, authorIds?: Array, organizationIds?: Array, organizationNames?: Array, projectTypes?: Array, title?: string, keywords?: Array, topicIds?: Array, filterTopicIds?: Array, fundingStartYears?: Array, fundingEndYears?: Array, countries?: Array, frameworkProgrammes?: Array, fundingSchemes?: Array, statuses?: Array, page?: number, size?: number, sortBy?: string, sortDirection?: string, fuzzy?: boolean, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + public searchEuCordisProjects(rawOaInstitutionId?: string, authorId?: string, authorIds?: Array, organizationIds?: Array, organizationNames?: Array, projectTypes?: Array, title?: string, keywords?: Array, topicIds?: Array, filterTopicIds?: Array, fundingStartYears?: Array, fundingEndYears?: Array, countries?: Array, frameworkProgrammes?: Array, fundingSchemes?: Array, statuses?: Array, page?: number, size?: number, sortBy?: string, sortDirection?: string, fuzzy?: boolean, secureFgpAcc?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public searchEuCordisProjects(rawOaInstitutionId?: string, authorId?: string, authorIds?: Array, organizationIds?: Array, organizationNames?: Array, projectTypes?: Array, title?: string, keywords?: Array, topicIds?: Array, filterTopicIds?: Array, fundingStartYears?: Array, fundingEndYears?: Array, countries?: Array, frameworkProgrammes?: Array, fundingSchemes?: Array, statuses?: Array, page?: number, size?: number, sortBy?: string, sortDirection?: string, fuzzy?: boolean, secureFgpAcc?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public searchEuCordisProjects(rawOaInstitutionId?: string, authorId?: string, authorIds?: Array, organizationIds?: Array, organizationNames?: Array, projectTypes?: Array, title?: string, keywords?: Array, topicIds?: Array, filterTopicIds?: Array, fundingStartYears?: Array, fundingEndYears?: Array, countries?: Array, frameworkProgrammes?: Array, fundingSchemes?: Array, statuses?: Array, page?: number, size?: number, sortBy?: string, sortDirection?: string, fuzzy?: boolean, secureFgpAcc?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public searchEuCordisProjects(rawOaInstitutionId?: string, authorId?: string, authorIds?: Array, organizationIds?: Array, organizationNames?: Array, projectTypes?: Array, title?: string, keywords?: Array, topicIds?: Array, filterTopicIds?: Array, fundingStartYears?: Array, fundingEndYears?: Array, countries?: Array, frameworkProgrammes?: Array, fundingSchemes?: Array, statuses?: Array, page?: number, size?: number, sortBy?: string, sortDirection?: string, fuzzy?: boolean, secureFgpAcc?: string, 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, @@ -1090,6 +1099,9 @@ export class ProjectsService extends BaseService { let localVarHeaders = this.defaultHeaders; + // authentication (HTTPBearer) required + localVarHeaders = this.configuration.addCredentialToHeaders('HTTPBearer', 'Authorization', localVarHeaders, 'Bearer '); + const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([ 'application/json' ]); From b21d8d3e88b624802ca44087ad986d647574430c Mon Sep 17 00:00:00 2001 From: Farajollahi Date: Thu, 6 Aug 2026 11:32:05 +0200 Subject: [PATCH 061/114] revert period filters on dashboard --- service/src/main/inse/dashboard/service.py | 84 ++++++++----------- .../src/main/inse/dashboard/test_service.py | 42 +++++----- .../projects/eu_cordis_projects_client.py | 18 ++++ .../inse/projects/projects_search_client.py | 18 ++++ service/src/main/inse/projects/service.py | 14 +++- .../projects/test_eu_cordis_search_client.py | 17 +++- 6 files changed, 122 insertions(+), 71 deletions(-) diff --git a/service/src/main/inse/dashboard/service.py b/service/src/main/inse/dashboard/service.py index ec1a9b8f..a0f15733 100644 --- a/service/src/main/inse/dashboard/service.py +++ b/service/src/main/inse/dashboard/service.py @@ -185,37 +185,27 @@ def _project_boundary_year_filter( from_year, to_year = period filters: list[dict[str, Any]] = [] + # A project overlaps the selected interval if it begins no later than the + # interval end and finishes no earlier than the interval start. + if to_year is not None: + if date_format == "year": + filters.append({"range": {start_field: {"lte": to_year}}}) + else: + last_day = ( + f"{to_year}-12-31" if date_format == "iso" else f"31.12.{to_year}" + ) + filters.append({"range": {start_field: {"lte": last_day}}}) + if from_year is not None: if date_format == "year": - filters.append({"term": {start_field: from_year}}) + filters.append({"range": {end_field: {"gte": from_year}}}) else: first_day = ( f"{from_year}-01-01" if date_format == "iso" else f"01.01.{from_year}" ) - last_day = ( - f"{from_year}-12-31" - if date_format == "iso" - else f"31.12.{from_year}" - ) - filters.append( - {"range": {start_field: {"gte": first_day, "lte": last_day}}} - ) - - if to_year is not None: - if date_format == "year": - filters.append({"term": {end_field: to_year}}) - else: - first_day = ( - f"{to_year}-01-01" if date_format == "iso" else f"01.01.{to_year}" - ) - last_day = ( - f"{to_year}-12-31" if date_format == "iso" else f"31.12.{to_year}" - ) - filters.append( - {"range": {end_field: {"gte": first_day, "lte": last_day}}} - ) + filters.append({"range": {end_field: {"gte": first_day}}}) return {"bool": {"filter": filters}} if filters else None @@ -396,8 +386,10 @@ async def get_dashboard_eu_projects( topic_ids=None, filter_topic_ids=None, title=None, - funding_start_years=[str(period[0])] if period[0] is not None else None, - funding_end_years=[str(period[1])] if period[1] is not None else None, + funding_start_years=None, + funding_end_years=None, + active_from_year=period[0], + active_to_year=period[1], countries=None, framework_programmes=None, funding_schemes=None, @@ -565,8 +557,10 @@ async def get_dashboard_bmbf_projects( funding_arts=None, topic_ids=None, filter_topic_ids=None, - funding_start_years=[str(period[0])] if period[0] is not None else None, - funding_end_years=[str(period[1])] if period[1] is not None else None, + funding_start_years=None, + funding_end_years=None, + active_from_year=period[0], + active_to_year=period[1], countries=None, page=0, size=1, @@ -675,8 +669,10 @@ async def get_dashboard_dfg_projects( topic_ids=None, filter_topic_ids=None, title=None, - funding_start_years=[str(period[0])] if period[0] is not None else None, - funding_end_years=[str(period[1])] if period[1] is not None else None, + funding_start_years=None, + funding_end_years=None, + active_from_year=period[0], + active_to_year=period[1], page=0, size=1, sort_by="id", @@ -2323,16 +2319,10 @@ async def _get_eu_project_ids_from_projects_service( topic_ids=None, filter_topic_ids=None, title=None, - funding_start_years=( - [str(year) for year in range(1900, period[1] + 1)] - if period[1] is not None - else None - ), - funding_end_years=( - [str(year) for year in range(period[0], 2101)] - if period[0] is not None - else None - ), + funding_start_years=None, + funding_end_years=None, + active_from_year=period[0], + active_to_year=period[1], countries=None, framework_programmes=None, funding_schemes=None, @@ -2438,7 +2428,7 @@ async def _person_eu_project_count( from_year: int | None = None, to_year: int | None = None, ) -> int: - """Uses the same author-only EU project search as the person detail page.""" + """Returns the same filtered EU project total as the person projects tab.""" period = _dashboard_period(from_year, to_year) projects = await projects_service.search_eu_cordis_projects( page=0, @@ -2454,16 +2444,10 @@ async def _person_eu_project_count( topic_ids=None, filter_topic_ids=None, title=None, - funding_start_years=( - [str(year) for year in range(1900, period[1] + 1)] - if period[1] is not None - else None - ), - funding_end_years=( - [str(year) for year in range(period[0], 2101)] - if period[0] is not None - else None - ), + funding_start_years=None, + funding_end_years=None, + active_from_year=period[0], + active_to_year=period[1], countries=None, framework_programmes=None, funding_schemes=None, diff --git a/service/src/main/inse/dashboard/test_service.py b/service/src/main/inse/dashboard/test_service.py index 74be4583..effb15c5 100644 --- a/service/src/main/inse/dashboard/test_service.py +++ b/service/src/main/inse/dashboard/test_service.py @@ -51,22 +51,14 @@ def test_project_status_counts_match_authoritative_total(): assert _reconcile_project_status_counts(7, 4, 2, 3) == (2, 2, 3) -def test_project_status_period_uses_exact_boundary_years(): +def test_project_status_period_uses_interval_overlap(): assert _project_boundary_year_filter( "startDate", "endDate", (2022, 2026), "iso" ) == { "bool": { "filter": [ - { - "range": { - "startDate": {"gte": "2022-01-01", "lte": "2022-12-31"} - } - }, - { - "range": { - "endDate": {"gte": "2026-01-01", "lte": "2026-12-31"} - } - }, + {"range": {"startDate": {"lte": "2026-12-31"}}}, + {"range": {"endDate": {"gte": "2022-01-01"}}}, ] } } @@ -78,8 +70,8 @@ def test_project_status_period_uses_exact_boundary_years(): ) == { "bool": { "filter": [ - {"term": {"projects.funding_start": 2022}}, - {"term": {"projects.funding_end": 2026}}, + {"range": {"projects.funding_start": {"lte": 2026}}}, + {"range": {"projects.funding_end": {"gte": 2022}}}, ] } } @@ -349,8 +341,10 @@ async def test_dashboard_dfg_projects_uses_projects_service_total(): mocked_get_projects.assert_awaited_once() call = mocked_get_projects.await_args assert call.kwargs["raw_oa_institution_id"] == "I123" - assert call.kwargs["funding_start_years"] == ["2020"] - assert call.kwargs["funding_end_years"] == ["2022"] + assert call.kwargs["funding_start_years"] is None + assert call.kwargs["funding_end_years"] is None + assert call.kwargs["active_from_year"] == 2020 + assert call.kwargs["active_to_year"] == 2022 assert call.kwargs["skip_enrichment"] is True assert call.kwargs["page"] == 0 assert call.kwargs["size"] == 1 @@ -375,8 +369,10 @@ async def test_dashboard_bmbf_projects_uses_projects_service_total(): mocked_get_projects.assert_awaited_once() call = mocked_get_projects.await_args assert call.kwargs["raw_oa_institution_id"] == "I123" - assert call.kwargs["funding_start_years"][-1] == "2020" - assert call.kwargs["funding_end_years"][0] == "2018" + assert call.kwargs["funding_start_years"] is None + assert call.kwargs["funding_end_years"] is None + assert call.kwargs["active_from_year"] == 2018 + assert call.kwargs["active_to_year"] == 2020 assert call.kwargs["page"] == 0 assert call.kwargs["size"] == 1 @@ -402,8 +398,10 @@ async def test_dashboard_eu_projects_uses_projects_service_total(): mocked_get_projects.assert_awaited_once() call = mocked_get_projects.await_args assert call.kwargs["raw_oa_institution_id"] == "I123" - assert call.kwargs["funding_start_years"] == ["2019"] - assert call.kwargs["funding_end_years"] == ["2021"] + assert call.kwargs["funding_start_years"] is None + assert call.kwargs["funding_end_years"] is None + assert call.kwargs["active_from_year"] == 2019 + assert call.kwargs["active_to_year"] == 2021 assert call.kwargs["project_types"] == list(EuCordisProjectType) assert call.kwargs["page"] == 0 assert call.kwargs["size"] == 1 @@ -833,6 +831,10 @@ async def test_top_eu_project_authors_count_filtered_projects_by_stable_author_i return {"aggregations": {"authors": {"buckets": []}}} async def eu_projects(**kwargs): + assert kwargs["funding_start_years"] is None + assert kwargs["funding_end_years"] is None + assert kwargs["active_from_year"] == 2020 + assert kwargs["active_to_year"] == 2022 if kwargs.get("raw_oa_institution_id"): return EuCordisProjectSearchPage( elements=[ @@ -866,6 +868,8 @@ async def test_top_eu_project_authors_count_filtered_projects_by_stable_author_i result = await get_top_authors( ORG_INSTITUTION_ID, "Example Org", + from_year=2020, + to_year=2022, ) assert [author.model_dump() for author in result.eu_projects] == [ diff --git a/service/src/main/inse/projects/eu_cordis_projects_client.py b/service/src/main/inse/projects/eu_cordis_projects_client.py index 8f0af70f..e6946f92 100644 --- a/service/src/main/inse/projects/eu_cordis_projects_client.py +++ b/service/src/main/inse/projects/eu_cordis_projects_client.py @@ -741,6 +741,8 @@ async def _build_eu_cordis_search_query( title: str | None = None, funding_start_years: list[str] | None = None, funding_end_years: list[str] | None = None, + active_from_year: int | None = None, + active_to_year: int | None = None, countries: list[str] | None = None, framework_programmes: list[str] | None = None, funding_schemes: list[str] | None = None, @@ -876,6 +878,18 @@ async def _build_eu_cordis_search_query( if funding_end_years: must_clauses.append(_eu_year_filters("endDate", funding_end_years)) + # Period-overlap filter: a project was active in the selected interval when + # it started no later than the interval end and ended no earlier than the + # interval start. This is intentionally separate from exact-year filters. + if active_to_year is not None: + must_clauses.append( + {"range": {"startDate": {"lte": f"{active_to_year}-12-31"}}} + ) + if active_from_year is not None: + must_clauses.append( + {"range": {"endDate": {"gte": f"{active_from_year}-01-01"}}} + ) + # === Project core filters === if framework_programmes: must_clauses.append({"terms": {"frameworkProgramme": framework_programmes}}) @@ -937,6 +951,8 @@ async def search_eu_cordis_projects( title: str | None = None, funding_start_years: list[str] | None = None, funding_end_years: list[str] | None = None, + active_from_year: int | None = None, + active_to_year: int | None = None, countries: list[str] | None = None, framework_programmes: list[str] | None = None, funding_schemes: list[str] | None = None, @@ -965,6 +981,8 @@ async def search_eu_cordis_projects( title=title, funding_start_years=funding_start_years, funding_end_years=funding_end_years, + active_from_year=active_from_year, + active_to_year=active_to_year, countries=countries, framework_programmes=framework_programmes, funding_schemes=funding_schemes, diff --git a/service/src/main/inse/projects/projects_search_client.py b/service/src/main/inse/projects/projects_search_client.py index 05911790..084689ff 100644 --- a/service/src/main/inse/projects/projects_search_client.py +++ b/service/src/main/inse/projects/projects_search_client.py @@ -368,6 +368,8 @@ async def search_dfg_projects( sort_direction: str = "asc", fuzzy: bool = False, skip_enrichment: bool = False, + active_from_year: int | None = None, + active_to_year: int | None = None, ) -> DfgProjectPage: """Searches for DFG projects based on the provided filtering and sorting criteria. @@ -488,6 +490,11 @@ async def search_dfg_projects( if funding_end_years: must_clauses.append({"terms": {"funding_end": funding_end_years}}) + if active_to_year is not None: + must_clauses.append({"range": {"funding_start": {"lte": str(active_to_year)}}}) + if active_from_year is not None: + must_clauses.append({"range": {"funding_end": {"gte": str(active_from_year)}}}) + if names: name_must_clauses = [] for full_name in names: @@ -858,6 +865,8 @@ async def search_bund_projects_with_filters( sort_direction: str = "asc", fuzzy: bool = False, skip_topic_enrichment: bool = False, + active_from_year: int | None = None, + active_to_year: int | None = None, ) -> BundProjectPage: """ Main search function for BUND projects, analogous to the DFG search. @@ -999,6 +1008,15 @@ async def search_bund_projects_with_filters( if funding_end_years: must_clauses.append(_bund_year_filters("funding_end", funding_end_years)) + if active_to_year is not None: + must_clauses.append( + {"range": {"funding_start": {"lte": f"31.12.{active_to_year}"}}} + ) + if active_from_year is not None: + must_clauses.append( + {"range": {"funding_end": {"gte": f"01.01.{active_from_year}"}}} + ) + body["query"] = {"bool": {"must": must_clauses}} if must_clauses else {"match_all": {}} # === Sorting === sort_by = sort_by.strip().lower() diff --git a/service/src/main/inse/projects/service.py b/service/src/main/inse/projects/service.py index ab5fa644..1ce656c5 100644 --- a/service/src/main/inse/projects/service.py +++ b/service/src/main/inse/projects/service.py @@ -175,6 +175,8 @@ async def get_dfg_projects_by_author_id( sort_direction: str = "asc", fuzzy: bool = False, skip_enrichment: bool = False, + active_from_year: int | None = None, + active_to_year: int | None = None, ) -> DfgProjectPage: logger.debug( "Fetching DFG projects for author_id=%s, author_filter_ids=%s, " @@ -250,6 +252,8 @@ async def get_dfg_projects_by_author_id( sort_direction=sort_direction, fuzzy=fuzzy, skip_enrichment=skip_enrichment, + active_from_year=active_from_year, + active_to_year=active_to_year, ) async def get_institution_cordis_eu_projects_funding_over_time( @@ -425,6 +429,8 @@ async def search_bund_projects_with_filters( sort_by: str = "title", sort_direction: str = "asc", fuzzy: bool = False, + active_from_year: int | None = None, + active_to_year: int | None = None, ) -> BundProjectPage: institution_aliases = [] if raw_oa_institution_id: @@ -456,7 +462,9 @@ async def search_bund_projects_with_filters( size=size, sort_by=sort_by, sort_direction=sort_direction, - fuzzy=fuzzy + fuzzy=fuzzy, + active_from_year=active_from_year, + active_to_year=active_to_year, ) def _calculate_funding_over_time( @@ -618,6 +626,8 @@ async def search_eu_cordis_projects( title: str | None = None, funding_start_years: list[str] | None = None, funding_end_years: list[str] | None = None, + active_from_year: int | None = None, + active_to_year: int | None = None, countries: list[str] | None = None, framework_programmes: list[str] | None = None, funding_schemes: list[str] | None = None, @@ -679,6 +689,8 @@ async def search_eu_cordis_projects( title=title, funding_start_years=funding_start_years, funding_end_years=funding_end_years, + active_from_year=active_from_year, + active_to_year=active_to_year, countries=countries, framework_programmes=framework_programmes, funding_schemes=funding_schemes, 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 index 342f383b..f6e7d5c3 100644 --- a/service/src/main/inse/projects/test_eu_cordis_search_client.py +++ b/service/src/main/inse/projects/test_eu_cordis_search_client.py @@ -2,6 +2,21 @@ import pytest from inse.projects import eu_cordis_projects_client as eu_cordis_search_client +@pytest.mark.anyio +async def test_active_period_filter_matches_projects_overlapping_interval(): + query, _, _ = await eu_cordis_search_client._build_eu_cordis_search_query( + active_from_year=2022, + active_to_year=2026, + ) + + assert {"range": {"startDate": {"lte": "2026-12-31"}}} in query["bool"][ + "must" + ] + assert {"range": {"endDate": {"gte": "2022-01-01"}}} in query["bool"][ + "must" + ] + + @pytest.mark.anyio async def test_search_eu_cordis_projects_by_title(): """Test searching EU CORDIS projects by title.""" @@ -362,4 +377,4 @@ async def test_search_eu_cordis_projects_with_fuzzy_topic_search(): # 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 + assert isinstance(res.elements, list) From 567b5ecd4fbbbdd5d9caef59fc1707e120292118 Mon Sep 17 00:00:00 2001 From: Farajollahi Date: Thu, 6 Aug 2026 12:16:49 +0200 Subject: [PATCH 062/114] implement Eu and Bund topics treemap --- service/src/main/inse/dashboard/model.py | 18 ++ service/src/main/inse/dashboard/router.py | 44 ++++ service/src/main/inse/dashboard/service.py | 244 ++++++++++++++++++ .../src/main/inse/dashboard/test_service.py | 153 +++++++++++ .../dashboard/dashboard-statistics.service.ts | 23 ++ .../dashboard/dashboard.component.html | 86 ++++++ .../modules/dashboard/dashboard.component.ts | 126 ++++++++- .../topic-wordcloud-dialog.component.ts | 2 +- 8 files changed, 687 insertions(+), 9 deletions(-) diff --git a/service/src/main/inse/dashboard/model.py b/service/src/main/inse/dashboard/model.py index eae2251a..ada6c020 100644 --- a/service/src/main/inse/dashboard/model.py +++ b/service/src/main/inse/dashboard/model.py @@ -54,6 +54,8 @@ class DfgProjectTopic(BaseModel): field: str | None = None domain: str | None = None project_count: int + field_project_count: int + subfield_project_count: int keywords: list[DfgProjectKeyword] @@ -65,6 +67,22 @@ class DfgProjectTopics(BaseModel): topics: list[DfgProjectTopic] +class EuProjectTopics(BaseModel): + institution_id: str + organization_name: str + project_count: int + matched_project_count: int + topics: list[DfgProjectTopic] + + +class BundProjectTopics(BaseModel): + institution_id: str + organization_name: str + project_count: int + matched_project_count: int + topics: list[DfgProjectTopic] + + class TopAuthor(BaseModel): id: str | None = None name: str diff --git a/service/src/main/inse/dashboard/router.py b/service/src/main/inse/dashboard/router.py index bd5ad49b..fb01a93a 100644 --- a/service/src/main/inse/dashboard/router.py +++ b/service/src/main/inse/dashboard/router.py @@ -10,10 +10,12 @@ from inse.tags import Tags from .model import ( BmbfProjectStatusStatistics, + BundProjectTopics, DashboardStatistics, DashboardStatisticValue, DfgProjectStatusStatistics, DfgProjectTopics, + EuProjectTopics, EuProjectStatusStatistics, TopAuthorStatistics, TopicHeatmap, @@ -22,9 +24,11 @@ from .model import ( from .service import ( get_dashboard_bmbf_project_statuses, get_dashboard_bmbf_projects, + get_dashboard_bund_topics, get_dashboard_dfg_project_statuses, get_dashboard_dfg_projects, get_dashboard_dfg_topics, + get_dashboard_eu_topics, get_dashboard_eu_project_statuses, get_dashboard_eu_projects, get_dashboard_organization, @@ -256,6 +260,46 @@ async def dashboard_dfg_project_topics( ) +@router.get( + "/projects/eu/topics", + operation_id="getDashboardEuProjectTopics", + response_model=EuProjectTopics, +) +async def dashboard_eu_project_topics( + from_year: int | None = Query(default=None, ge=1900, le=2100), + to_year: int | None = Query(default=None, ge=1900, le=2100), + session: Session = Depends(get_session), + access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep, +) -> EuProjectTopics: + organization = get_dashboard_organization(session, access_token) + return await get_dashboard_eu_topics( + organization.openalex_institution_id, + organization.name, + from_year=from_year, + to_year=to_year, + ) + + +@router.get( + "/projects/bund/topics", + operation_id="getDashboardBundProjectTopics", + response_model=BundProjectTopics, +) +async def dashboard_bund_project_topics( + from_year: int | None = Query(default=None, ge=1900, le=2100), + to_year: int | None = Query(default=None, ge=1900, le=2100), + session: Session = Depends(get_session), + access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep, +) -> BundProjectTopics: + organization = get_dashboard_organization(session, access_token) + return await get_dashboard_bund_topics( + organization.openalex_institution_id, + organization.name, + from_year=from_year, + to_year=to_year, + ) + + @router.get( "/top-authors", operation_id="getDashboardTopAuthors", diff --git a/service/src/main/inse/dashboard/service.py b/service/src/main/inse/dashboard/service.py index a0f15733..f09939ab 100644 --- a/service/src/main/inse/dashboard/service.py +++ b/service/src/main/inse/dashboard/service.py @@ -1,4 +1,5 @@ import asyncio +import hashlib import logging import re from collections import defaultdict @@ -34,12 +35,14 @@ from inse.projects.model import ( from .institute_helper import get_openalex_institution from .model import ( BmbfProjectStatusStatistics, + BundProjectTopics, DashboardStatistics, DfgProjectKeyword, DashboardStatisticValue, DfgProjectStatusStatistics, DfgProjectTopic, DfgProjectTopics, + EuProjectTopics, EuProjectStatusStatistics, TopAuthor, TopAuthorStatistics, @@ -860,6 +863,14 @@ async def get_dashboard_dfg_topics( if keyword: topic["keywords"].setdefault(keyword, set()).add(project_id) + field_project_ids: dict[str, set[str]] = defaultdict(set) + subfield_project_ids: dict[tuple[str, str], set[str]] = defaultdict(set) + for topic in topics.values(): + field_name = str(topic["field"] or "") + subfield_name = str(topic["subfield"] or "") + field_project_ids[field_name].update(topic["project_ids"]) + subfield_project_ids[(field_name, subfield_name)].update(topic["project_ids"]) + topic_list = [ DfgProjectTopic( id=topic["id"], @@ -868,6 +879,12 @@ async def get_dashboard_dfg_topics( field=topic["field"], domain=topic["domain"], project_count=len(topic["project_ids"]), + field_project_count=len(field_project_ids[str(topic["field"] or "")]), + subfield_project_count=len( + subfield_project_ids[ + (str(topic["field"] or ""), str(topic["subfield"] or "")) + ] + ), keywords=sorted( [ DfgProjectKeyword( @@ -891,6 +908,233 @@ async def get_dashboard_dfg_topics( ) +async def get_dashboard_eu_topics( + institution_id: str, + organization_name: str, + from_year: int | None = None, + to_year: int | None = None, +) -> EuProjectTopics: + normalized_id = _normalize_institution_id(institution_id) + project_ids = await _get_eu_project_ids_from_projects_service( + normalized_id, + from_year=from_year, + to_year=to_year, + ) + topics: dict[str, dict[str, Any]] = {} + matched_project_ids: set[str] = set() + + if project_ids: + mapping_indices = ( + ESIndex.PROJECTS_CORDIS_EU_FP7_TOPICS_MAPPING, + ESIndex.PROJECTS_CORDIS_EU_H2020_TOPICS, + ESIndex.PROJECTS_CORDIS_EU_HEUROPE_TOPICS, + ) + for mapping_index in mapping_indices: + async for hit in elasticsearch.scan( + index=str(mapping_index), + query={"terms": {"project_id": project_ids}}, + source=["project_id", "keyword", "topic_matches"], + page_size=1000, + cluster=ESCluster.INSE, + ): + source = hit.get("_source", {}) + project_id = str(source.get("project_id") or "") + if not project_id: + continue + keyword = str(source.get("keyword") or "").strip() + matched_project_ids.add(project_id) + for match in source.get("topic_matches", []): + topic_id = str(match.get("topic_id") or "") + if not topic_id: + continue + topic = topics.setdefault( + topic_id, + { + "id": topic_id, + "name": str(match.get("topic_display_name") or topic_id), + "subfield": match.get("subfield"), + "field": match.get("field"), + "domain": match.get("domain"), + "project_ids": set(), + "keywords": {}, + }, + ) + topic["project_ids"].add(project_id) + if keyword: + topic["keywords"].setdefault(keyword, set()).add(project_id) + + field_project_ids: dict[str, set[str]] = defaultdict(set) + subfield_project_ids: dict[tuple[str, str], set[str]] = defaultdict(set) + for topic in topics.values(): + field_name = str(topic["field"] or "") + subfield_name = str(topic["subfield"] or "") + field_project_ids[field_name].update(topic["project_ids"]) + subfield_project_ids[(field_name, subfield_name)].update(topic["project_ids"]) + + topic_list = [ + DfgProjectTopic( + id=topic["id"], + name=topic["name"], + subfield=topic["subfield"], + field=topic["field"], + domain=topic["domain"], + project_count=len(topic["project_ids"]), + field_project_count=len(field_project_ids[str(topic["field"] or "")]), + subfield_project_count=len( + subfield_project_ids[ + (str(topic["field"] or ""), str(topic["subfield"] or "")) + ] + ), + keywords=sorted( + [ + DfgProjectKeyword( + name=keyword, + project_count=len(keyword_project_ids), + ) + for keyword, keyword_project_ids in topic["keywords"].items() + ], + key=lambda entry: (-entry.project_count, entry.name), + ), + ) + for topic in topics.values() + ] + topic_list.sort(key=lambda topic: (-topic.project_count, topic.name, topic.id)) + return EuProjectTopics( + institution_id=normalized_id, + organization_name=organization_name, + project_count=len(project_ids), + matched_project_count=len(matched_project_ids), + topics=topic_list, + ) + + +async def get_dashboard_bund_topics( + institution_id: str, + organization_name: str, + from_year: int | None = None, + to_year: int | None = None, +) -> BundProjectTopics: + normalized_id = _normalize_institution_id(institution_id) + period = _dashboard_period(from_year, to_year) + page_size = 1000 + page_number = 0 + project_ids: set[str] = set() + + while True: + projects = await projects_service.search_bund_projects_with_filters( + institutions_search_client=InstitutionsSearchClient(), + executing_agency=None, + raw_oa_institution_id=_raw_institution_id(normalized_id), + title=None, + keywords=None, + funding_arts=None, + topic_ids=None, + filter_topic_ids=None, + funding_start_years=None, + funding_end_years=None, + active_from_year=period[0], + active_to_year=period[1], + countries=None, + page=page_number, + size=page_size, + sort_by="id", + sort_direction="asc", + fuzzy=False, + ) + project_ids.update( + project.funding_code + for project in projects.elements + if project.funding_code + ) + if len(project_ids) >= projects.total or not projects.elements: + break + page_number += 1 + + topics: dict[str, dict[str, Any]] = {} + matched_project_ids: set[str] = set() + if project_ids: + mapping_project_ids = sorted( + hashlib.sha256(project_id.encode("utf-8")).hexdigest() + for project_id in project_ids + ) + async for hit in elasticsearch.scan( + index=str(ESIndex.PROJECTS_BUND_TOPICS), + query={"terms": {"project_id": mapping_project_ids}}, + source=["project_id", "keyword", "topic_matches"], + page_size=1000, + cluster=ESCluster.INSE, + ): + source = hit.get("_source", {}) + project_id = str(source.get("project_id") or "") + if not project_id: + continue + keyword = str(source.get("keyword") or "").strip() + matched_project_ids.add(project_id) + for match in source.get("topic_matches", []): + topic_id = str(match.get("topic_id") or "") + if not topic_id: + continue + topic = topics.setdefault( + topic_id, + { + "id": topic_id, + "name": str(match.get("topic_display_name") or topic_id), + "subfield": match.get("subfield"), + "field": match.get("field"), + "domain": match.get("domain"), + "project_ids": set(), + "keywords": {}, + }, + ) + topic["project_ids"].add(project_id) + if keyword: + topic["keywords"].setdefault(keyword, set()).add(project_id) + + field_project_ids: dict[str, set[str]] = defaultdict(set) + subfield_project_ids: dict[tuple[str, str], set[str]] = defaultdict(set) + for topic in topics.values(): + field_name = str(topic["field"] or "") + subfield_name = str(topic["subfield"] or "") + field_project_ids[field_name].update(topic["project_ids"]) + subfield_project_ids[(field_name, subfield_name)].update(topic["project_ids"]) + + topic_list = [ + DfgProjectTopic( + id=topic["id"], + name=topic["name"], + subfield=topic["subfield"], + field=topic["field"], + domain=topic["domain"], + project_count=len(topic["project_ids"]), + field_project_count=len(field_project_ids[str(topic["field"] or "")]), + subfield_project_count=len( + subfield_project_ids[ + (str(topic["field"] or ""), str(topic["subfield"] or "")) + ] + ), + keywords=sorted( + [ + DfgProjectKeyword( + name=keyword, + project_count=len(keyword_project_ids), + ) + for keyword, keyword_project_ids in topic["keywords"].items() + ], + key=lambda entry: (-entry.project_count, entry.name), + ), + ) + for topic in topics.values() + ] + topic_list.sort(key=lambda topic: (-topic.project_count, topic.name, topic.id)) + return BundProjectTopics( + institution_id=normalized_id, + organization_name=organization_name, + project_count=len(project_ids), + matched_project_count=len(matched_project_ids), + topics=topic_list, + ) + + async def _get_dfg_project_ids_from_projects_service( institution_id: str, from_year: int | None = None, diff --git a/service/src/main/inse/dashboard/test_service.py b/service/src/main/inse/dashboard/test_service.py index effb15c5..4574fa80 100644 --- a/service/src/main/inse/dashboard/test_service.py +++ b/service/src/main/inse/dashboard/test_service.py @@ -1,4 +1,5 @@ from datetime import datetime +import hashlib from types import SimpleNamespace from unittest.mock import AsyncMock, patch @@ -15,8 +16,10 @@ from inse.dashboard.service import ( _reconcile_project_status_counts, _top_news_authors, get_dashboard_bmbf_projects, + get_dashboard_bund_topics, get_dashboard_dfg_projects, get_dashboard_eu_projects, + get_dashboard_eu_topics, get_dashboard_organization, get_dashboard_persons, get_dashboard_publications, @@ -31,6 +34,7 @@ from inse.models.openalex.meta import Meta from inse.persons.model import CustomAuthorsListResponse from inse.projects.model import ( BundProjectPage, + BundProjectSummary, DfgProjectPage, DfgProjectSummary, EuCordisProjectSearchPage, @@ -154,6 +158,155 @@ async def test_dfg_topic_project_ids_use_paginated_projects_service(): assert first_call.kwargs["funding_end_years"][0] == "2020" +@pytest.mark.anyio +async def test_eu_topics_scan_all_programme_indices_and_deduplicate_projects(): + scanned_indices: list[str] = [] + + async def scan(**kwargs): + scanned_indices.append(kwargs["index"]) + if kwargs["index"] == str(ESIndex.PROJECTS_CORDIS_EU_FP7_TOPICS_MAPPING): + yield { + "_source": { + "project_id": "P1", + "keyword": "AI", + "topic_matches": [ + { + "topic_id": "T1", + "topic_display_name": "Artificial Intelligence", + "field": "Computer Science", + "subfield": "AI", + "domain": "Physical Sciences", + } + ], + } + } + yield { + "_source": { + "project_id": "P1", + "keyword": "Robotics", + "topic_matches": [ + { + "topic_id": "T2", + "topic_display_name": "Robotics", + "field": "Computer Science", + "subfield": "Robotics", + "domain": "Physical Sciences", + } + ], + } + } + if kwargs["index"] == str(ESIndex.PROJECTS_CORDIS_EU_H2020_TOPICS): + yield { + "_source": { + "project_id": "P2", + "keyword": "AI", + "topic_matches": [ + { + "topic_id": "T1", + "topic_display_name": "Artificial Intelligence", + "field": "Computer Science", + "subfield": "AI", + "domain": "Physical Sciences", + } + ], + } + } + + with patch( + "inse.dashboard.service._get_eu_project_ids_from_projects_service", + new=AsyncMock(return_value=["P1", "P2", "P3"]), + ), patch("inse.dashboard.service.elasticsearch.scan", new=scan): + result = await get_dashboard_eu_topics( + ORG_INSTITUTION_ID, + "Example Org", + from_year=2022, + to_year=2026, + ) + + assert scanned_indices == [ + str(ESIndex.PROJECTS_CORDIS_EU_FP7_TOPICS_MAPPING), + str(ESIndex.PROJECTS_CORDIS_EU_H2020_TOPICS), + str(ESIndex.PROJECTS_CORDIS_EU_HEUROPE_TOPICS), + ] + assert result.project_count == 3 + assert result.matched_project_count == 2 + assert result.topics[0].project_count == 2 + assert result.topics[0].keywords[0].project_count == 2 + assert {topic.field_project_count for topic in result.topics} == {2} + assert {topic.name: topic.subfield_project_count for topic in result.topics} == { + "Artificial Intelligence": 2, + "Robotics": 1, + } + + +@pytest.mark.anyio +async def test_bund_topics_use_mapping_index_and_unique_hierarchy_counts(): + project_page = BundProjectPage( + elements=[ + BundProjectSummary(funding_code="B1"), + BundProjectSummary(funding_code="B2"), + ], + total=2, + page=0, + size=1000, + ) + + async def scan(**kwargs): + assert kwargs["index"] == str(ESIndex.PROJECTS_BUND_TOPICS) + mapping_ids = { + funding_code: hashlib.sha256(funding_code.encode("utf-8")).hexdigest() + for funding_code in ("B1", "B2") + } + assert kwargs["query"] == { + "terms": {"project_id": sorted(mapping_ids.values())} + } + for project_id, topic_id, topic_name, subfield in ( + (mapping_ids["B1"], "T1", "Artificial Intelligence", "AI"), + (mapping_ids["B1"], "T2", "Robotics", "Robotics"), + (mapping_ids["B2"], "T1", "Artificial Intelligence", "AI"), + ): + yield { + "_source": { + "project_id": project_id, + "keyword": topic_name, + "topic_matches": [ + { + "topic_id": topic_id, + "topic_display_name": topic_name, + "field": "Computer Science", + "subfield": subfield, + "domain": "Physical Sciences", + } + ], + } + } + + with patch( + "inse.dashboard.service.projects_service.search_bund_projects_with_filters", + new=AsyncMock(return_value=project_page), + ) as mocked_projects, patch( + "inse.dashboard.service.elasticsearch.scan", + new=scan, + ): + result = await get_dashboard_bund_topics( + ORG_INSTITUTION_ID, + "Example Org", + from_year=2022, + to_year=2026, + ) + + project_call = mocked_projects.await_args + assert project_call.kwargs["active_from_year"] == 2022 + assert project_call.kwargs["active_to_year"] == 2026 + assert result.project_count == 2 + assert result.matched_project_count == 2 + assert {topic.field_project_count for topic in result.topics} == {2} + assert {topic.name: topic.subfield_project_count for topic in result.topics} == { + "Artificial Intelligence": 2, + "Robotics": 1, + } + + @pytest.mark.anyio async def test_dashboard_statistics_counts_organization_data_and_all_projects(): async def search(**kwargs): diff --git a/webapp/src/app/modules/dashboard/dashboard-statistics.service.ts b/webapp/src/app/modules/dashboard/dashboard-statistics.service.ts index 6f406f0b..894da8a3 100644 --- a/webapp/src/app/modules/dashboard/dashboard-statistics.service.ts +++ b/webapp/src/app/modules/dashboard/dashboard-statistics.service.ts @@ -59,6 +59,8 @@ export interface DfgProjectTopic { field?: string | null; domain?: string | null; project_count: number; + field_project_count: number; + subfield_project_count: number; keywords: DfgProjectKeyword[]; } @@ -75,6 +77,9 @@ export interface DfgProjectTopics { topics: DfgProjectTopic[]; } +export interface EuProjectTopics extends DfgProjectTopics {} +export interface BundProjectTopics extends DfgProjectTopics {} + export interface TopAuthor { id?: string | null; name: string; @@ -202,6 +207,24 @@ export class DashboardStatisticsService { ); } + getEuProjectTopics( + period: DashboardPeriodBounds = {}, + ): Observable { + return this.httpClient.get( + `${this.apiConfiguration?.basePath ?? ''}/api/dashboard/projects/eu/topics`, + { params: this.periodParams(period) }, + ); + } + + getBundProjectTopics( + period: DashboardPeriodBounds = {}, + ): Observable { + return this.httpClient.get( + `${this.apiConfiguration?.basePath ?? ''}/api/dashboard/projects/bund/topics`, + { params: this.periodParams(period) }, + ); + } + getTopAuthors( period: DashboardPeriodBounds = {}, ): Observable { diff --git a/webapp/src/app/modules/dashboard/dashboard.component.html b/webapp/src/app/modules/dashboard/dashboard.component.html index 7cf8b2bc..5b95c4a7 100644 --- a/webapp/src/app/modules/dashboard/dashboard.component.html +++ b/webapp/src/app/modules/dashboard/dashboard.component.html @@ -317,6 +317,92 @@ } + @if (euTopicsLoading || euTopicsError || euProjectTopics) { +
    +
    +
    +

    EU-Projekt-Topics

    +

    + Gematchte EU-Projekte nach Field, Subfield und Topic. Ein Klick + auf ein Topic zeigt die zugehörigen Keywords. +

    +
    + @if (euProjectTopics) { +

    + {{ euProjectTopics.matched_project_count | number }} von + {{ euProjectTopics.project_count | number }} Projekten gematcht +

    + } +
    + + @if (euTopicsLoading) { +
    + +
    + } @else if (euTopicsError) { +

    + Die EU-Topic-Treemap konnte nicht geladen werden. +

    + } @else { + + + } +
    + } + + @if (bundTopicsLoading || bundTopicsError || bundProjectTopics) { +
    +
    +
    +

    BUND-Projekt-Topics

    +

    + Gematchte BUND-Projekte nach Field, Subfield und Topic. Ein Klick + auf ein Topic zeigt die zugehörigen Keywords. +

    +
    + @if (bundProjectTopics) { +

    + {{ bundProjectTopics.matched_project_count | number }} von + {{ bundProjectTopics.project_count | number }} Projekten gematcht +

    + } +
    + + @if (bundTopicsLoading) { +
    + +
    + } @else if (bundTopicsError) { +

    + Die BUND-Topic-Treemap konnte nicht geladen werden. +

    + } @else { + + + } +
    + } + @if (topAuthorsLoading || topAuthorsError || hasTopAuthorData()) {
    diff --git a/webapp/src/app/modules/dashboard/dashboard.component.ts b/webapp/src/app/modules/dashboard/dashboard.component.ts index cb9982c5..a2638a4b 100644 --- a/webapp/src/app/modules/dashboard/dashboard.component.ts +++ b/webapp/src/app/modules/dashboard/dashboard.component.ts @@ -18,6 +18,7 @@ import { } from './topic-wordcloud-dialog/topic-wordcloud-dialog.component'; import { BmbfProjectStatusStatistics, + BundProjectTopics, DashboardPeriodBounds, DashboardStatisticValue, DashboardStatistics, @@ -26,6 +27,7 @@ import { DfgProjectTopic, DfgProjectTopics, EuProjectStatusStatistics, + EuProjectTopics, TopAuthor, TopAuthorStatistics, } from './dashboard-statistics.service'; @@ -96,6 +98,14 @@ export class DashboardComponent implements OnInit { dfgTopicTreemap?: TopicTreemapData; dfgTopicsLoading = false; dfgTopicsError = false; + euProjectTopics?: EuProjectTopics; + euTopicTreemap?: TopicTreemapData; + euTopicsLoading = false; + euTopicsError = false; + bundProjectTopics?: BundProjectTopics; + bundTopicTreemap?: TopicTreemapData; + bundTopicsLoading = false; + bundTopicsError = false; euProjectStatuses?: EuProjectStatusStatistics; euProjectStatusesLoading = false; euProjectStatusesError = false; @@ -112,6 +122,8 @@ export class DashboardComponent implements OnInit { dashboardToYear = this.topicTreemapMaxYear; selectedTopicTreemapNode?: string; selectedDfgTopicTreemapNode?: string; + selectedEuTopicTreemapNode?: string; + selectedBundTopicTreemapNode?: string; private topicTreemapReloadQueued = false; private topicTreemapRequestId = 0; @@ -128,6 +140,8 @@ export class DashboardComponent implements OnInit { this.loadTopAuthors(); this.loadTopicTreemap(); this.loadDfgProjectTopics(); + this.loadEuProjectTopics(); + this.loadBundProjectTopics(); this.loadEuProjectStatuses(); this.loadBmbfProjectStatuses(); this.loadDfgProjectStatuses(); @@ -245,10 +259,12 @@ export class DashboardComponent implements OnInit { ([subfieldName, group]) => ({ id: `${fieldName}::${subfieldName}`, name: subfieldName, - total: group.topics.reduce( - (sum, topic) => sum + topic.project_count, - 0, - ), + total: + group.topics[0]?.subfield_project_count ?? + group.topics.reduce( + (sum, topic) => sum + topic.project_count, + 0, + ), values: [], topics: group.topics.map((topic) => ({ id: topic.id, @@ -261,10 +277,12 @@ export class DashboardComponent implements OnInit { return { id: fieldName, name: fieldName, - total: mappedSubfields.reduce( - (sum, subfield) => sum + subfield.total, - 0, - ), + total: + [...subfields.values()][0]?.topics[0]?.field_project_count ?? + mappedSubfields.reduce( + (sum, subfield) => sum + subfield.total, + 0, + ), values: [], subfields: mappedSubfields, }; @@ -378,6 +396,62 @@ export class DashboardComponent implements OnInit { ); } + onEuTopicTreemapNodeChange(nodeId: string | undefined): void { + this.selectedEuTopicTreemapNode = nodeId; + } + + onEuTopicTreemapTopicSelect(topic: TopicTreemapTopicSelect): void { + const euTopic = this.euProjectTopics?.topics.find( + (entry) => entry.id === topic.topicId, + ); + if (!euTopic) return; + + this.dialog.open( + TopicWordCloudDialogComponent, + { + width: '85vw', + maxWidth: '92vw', + data: { + ...topic, + source: 'eu', + words: euTopic.keywords.map((keyword) => ({ + id: keyword.name, + name: keyword.name, + count: keyword.project_count, + })), + }, + }, + ); + } + + onBundTopicTreemapNodeChange(nodeId: string | undefined): void { + this.selectedBundTopicTreemapNode = nodeId; + } + + onBundTopicTreemapTopicSelect(topic: TopicTreemapTopicSelect): void { + const bundTopic = this.bundProjectTopics?.topics.find( + (entry) => entry.id === topic.topicId, + ); + if (!bundTopic) return; + + this.dialog.open( + TopicWordCloudDialogComponent, + { + width: '85vw', + maxWidth: '92vw', + data: { + ...topic, + source: 'bund', + words: bundTopic.keywords.map((keyword) => ({ + id: keyword.name, + name: keyword.name, + count: keyword.project_count, + })), + }, + }, + ); + } + onTopicTreemapTopicSelect(topic: TopicTreemapTopicSelect): void { const period = this.selectedPeriodBounds(); this.dialog.open( @@ -469,6 +543,8 @@ export class DashboardComponent implements OnInit { this.loadTopAuthors(); this.loadTopicTreemap(); this.loadDfgProjectTopics(); + this.loadEuProjectTopics(); + this.loadBundProjectTopics(); this.loadEuProjectStatuses(); this.loadBmbfProjectStatuses(); this.loadDfgProjectStatuses(); @@ -552,6 +628,40 @@ export class DashboardComponent implements OnInit { }); } + private loadEuProjectTopics(): void { + this.euTopicsLoading = true; + this.euTopicsError = false; + this.statisticsService + .getEuProjectTopics(this.selectedPeriodBounds()) + .pipe(finalize(() => (this.euTopicsLoading = false))) + .subscribe({ + next: (topics) => { + this.euProjectTopics = topics; + this.euTopicTreemap = this.buildDfgTopicTreemapData(topics); + }, + error: () => { + this.euTopicsError = true; + }, + }); + } + + private loadBundProjectTopics(): void { + this.bundTopicsLoading = true; + this.bundTopicsError = false; + this.statisticsService + .getBundProjectTopics(this.selectedPeriodBounds()) + .pipe(finalize(() => (this.bundTopicsLoading = false))) + .subscribe({ + next: (topics) => { + this.bundProjectTopics = topics; + this.bundTopicTreemap = this.buildDfgTopicTreemapData(topics); + }, + error: () => { + this.bundTopicsError = true; + }, + }); + } + private loadEuProjectStatuses(): void { this.euProjectStatusesLoading = true; this.euProjectStatusesError = false; diff --git a/webapp/src/app/modules/dashboard/topic-wordcloud-dialog/topic-wordcloud-dialog.component.ts b/webapp/src/app/modules/dashboard/topic-wordcloud-dialog/topic-wordcloud-dialog.component.ts index 6639bbf4..a8b75dc0 100644 --- a/webapp/src/app/modules/dashboard/topic-wordcloud-dialog/topic-wordcloud-dialog.component.ts +++ b/webapp/src/app/modules/dashboard/topic-wordcloud-dialog/topic-wordcloud-dialog.component.ts @@ -23,7 +23,7 @@ export interface TopicWordCloudDialogData { fromYear?: number; toYear?: number; words?: TopicWordCloudWord[]; - source?: 'publications' | 'dfg'; + source?: 'publications' | 'dfg' | 'eu' | 'bund'; } interface DisplayWord extends TopicWordCloudWord { From 916af846513761424450ba6b95341eca0ff4a18a Mon Sep 17 00:00:00 2001 From: genja Date: Thu, 6 Aug 2026 13:56:25 +0200 Subject: [PATCH 063/114] fixed service function name --- service/src/main/inse/dashboard/service.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/service/src/main/inse/dashboard/service.py b/service/src/main/inse/dashboard/service.py index 4f1fe83d..ec065b45 100644 --- a/service/src/main/inse/dashboard/service.py +++ b/service/src/main/inse/dashboard/service.py @@ -622,7 +622,7 @@ async def get_dashboard_dfg_projects( ) -> DashboardStatisticValue: normalized_id = _normalize_institution_id(institution_id) period = _dashboard_period(from_year, to_year) - projects = await projects_service.get_dfg_projects_by_author_id( + projects = await projects_service.get_dfg_projects( institutions_search_client=InstitutionsSearchClient(), raw_oa_institution_id=_raw_institution_id(normalized_id), author_id=None, @@ -871,7 +871,7 @@ async def _get_dfg_project_ids_from_projects_service( project_ids: set[str] = set() while True: - projects = await projects_service.get_dfg_projects_by_author_id( + projects = await projects_service.get_dfg_projects( institutions_search_client=InstitutionsSearchClient(), raw_oa_institution_id=_raw_institution_id(institution_id), author_id=None, From be89e2986b46d26d9dfcd42e4fadf1922ee5de8d Mon Sep 17 00:00:00 2001 From: genja Date: Thu, 6 Aug 2026 13:56:52 +0200 Subject: [PATCH 064/114] check for 403 on the router, not in service! --- service/src/main/inse/projects/router.py | 27 +++++++++++++++++++---- service/src/main/inse/projects/service.py | 27 ++--------------------- 2 files changed, 25 insertions(+), 29 deletions(-) diff --git a/service/src/main/inse/projects/router.py b/service/src/main/inse/projects/router.py index 71e44778..7161b89a 100644 --- a/service/src/main/inse/projects/router.py +++ b/service/src/main/inse/projects/router.py @@ -7,6 +7,9 @@ from inse.auth.service import CurrentUserAccessTokenPayloadDep from inse.institutions.institutions_search_client import ( InstitutionsSearchClient, ) +from inse.projects.logic import ( + is_projects_access_forbidden +) from inse.institutions.router import get_institutions_search_client from inse.models.bund_project_details import BundProjectDetails from inse.models.dfg_project_details import DfgProjectDetails @@ -30,6 +33,7 @@ from inse.projects.model import ( SortDirection, ) from inse.tags import Tags +from fastapi import HTTPException as HttpException logger = logging.getLogger(__name__) @@ -144,8 +148,13 @@ async def get_dfg_projects( sort_direction, fuzzy, ) - return await projects_service.get_dfg_projects_by_author_id( - access_token_metadata=access_token_metadata, + is_forbidden = await is_projects_access_forbidden(access_token_metadata, raw_oa_institution_id, author_id) + if is_forbidden: + raise HttpException( + status_code=403, + detail="Access denied for the provided author ID or institution ID", + ) + return await projects_service.get_dfg_projects( institutions_search_client=institutions_search_client, raw_oa_institution_id=raw_oa_institution_id, author_id=author_id, @@ -259,6 +268,12 @@ async def search_bund_projects( Query(description="Use OpenAlex topic-id resolution if true, otherwise raw keyword search."), ] = False, ) -> BundProjectPage: + is_forbidden = await is_projects_access_forbidden(access_token_metadata, raw_oa_institution_id, None) + if is_forbidden: + raise HttpException( + status_code=403, + detail="Access denied for the provided author ID or institution ID", + ) return await projects_service.search_bund_projects_with_filters( access_token_metadata=access_token_metadata, institutions_search_client=institutions_search_client, @@ -438,9 +453,13 @@ async def search_eu_cordis_projects_endpoint( sort_direction, fuzzy, ) - + is_forbidden = await is_projects_access_forbidden(access_token_metadata, raw_oa_institution_id, author_id) + if is_forbidden: + raise HttpException( + status_code=403, + detail="Access denied for the provided author ID or institution ID", + ) return await search_eu_cordis_projects( - access_token_metadata=access_token_metadata, institutions_search_client=institutions_search_client, raw_oa_institution_id=raw_oa_institution_id, author_id=author_id, diff --git a/service/src/main/inse/projects/service.py b/service/src/main/inse/projects/service.py index dc5b92ca..813ff0e2 100644 --- a/service/src/main/inse/projects/service.py +++ b/service/src/main/inse/projects/service.py @@ -27,9 +27,7 @@ from inse.projects.eu_cordis_projects_client import ( from inse.projects.eu_cordis_projects_client import ( search_eu_cordis_projects as _search_eu_cordis_projects_es, ) -from inse.projects.logic import ( - get_dfg_author_names_by_ids, is_projects_access_forbidden -) + from inse.projects.model import ( BundProjectPage, DfgProjectPage, @@ -158,8 +156,7 @@ async def _get_dfg_project_ids_for_openalex_authors( return list(set.intersection(*project_sets)) -async def get_dfg_projects_by_author_id( - access_token_metadata: AccessTokenMetadata, +async def get_dfg_projects( institutions_search_client: InstitutionsSearchClient, raw_oa_institution_id: str | None, author_id: str | None, @@ -200,12 +197,6 @@ async def get_dfg_projects_by_author_id( ) filter_names = [] author_project_ids = [] - is_forbidden = await is_projects_access_forbidden(access_token_metadata, raw_oa_institution_id, author_id) - if is_forbidden: - raise HttpException( - status_code=403, - detail="Access denied for the provided author ID or institution ID", - ) if author_id: author_project_ids = await _get_dfg_project_ids_for_openalex_authors([author_id]) logger.info("Author project IDs for author_id:%s: %s", author_id, author_project_ids) @@ -421,7 +412,6 @@ async def get_institution_bund_projects_funding_over_time( #Bund async def search_bund_projects_with_filters( - access_token_metadata: AccessTokenMetadata, institutions_search_client: InstitutionsSearchClient, executing_agency: str | None, raw_oa_institution_id: str | None, @@ -439,12 +429,6 @@ async def search_bund_projects_with_filters( sort_direction: str = "asc", fuzzy: bool = False, ) -> BundProjectPage: - is_forbidden = await is_projects_access_forbidden(access_token_metadata, raw_oa_institution_id, None) - if is_forbidden: - raise HttpException( - status_code=403, - detail="Access denied for the provided author ID or institution ID", - ) institution_aliases = [] if raw_oa_institution_id: if institutions_search_client is None: @@ -626,7 +610,6 @@ async def _get_eu_project_ids_for_openalex_authors( async def search_eu_cordis_projects( - access_token_metadata: AccessTokenMetadata, page: int, size: int, project_types: list[EuCordisProjectType] | None = None, @@ -665,12 +648,6 @@ async def search_eu_cordis_projects( funding scheme, status, funding years, country) are ANDed together as in eu_cordis_projects_client.search_eu_cordis_projects. """ - is_forbidden = await is_projects_access_forbidden(access_token_metadata, raw_oa_institution_id, author_id) - if is_forbidden: - raise HttpException( - status_code=403, - detail="Access denied for the provided author ID or institution ID", - ) resolved_organization_names: list[str] = list(organization_names or []) if raw_oa_institution_id: if institutions_search_client is None: From d8eec59d5deb2c1cc7f7a2b977dd6afacab8bcea Mon Sep 17 00:00:00 2001 From: genja Date: Thu, 6 Aug 2026 14:18:46 +0200 Subject: [PATCH 065/114] moved filter ids validation to backend --- service/src/main/inse/projects/router.py | 6 +-- service/src/main/inse/projects/service.py | 47 +++++++++++++++---- webapp/src/app/api/api/projects.service.ts | 8 ++-- .../app/resolvers/dfg-projects.resolver.ts | 45 +++--------------- 4 files changed, 51 insertions(+), 55 deletions(-) diff --git a/service/src/main/inse/projects/router.py b/service/src/main/inse/projects/router.py index 7161b89a..6382f575 100644 --- a/service/src/main/inse/projects/router.py +++ b/service/src/main/inse/projects/router.py @@ -93,10 +93,8 @@ async def get_dfg_projects( str | None, Query(description="The openalex institution ID to filter by.") ] = None, author_id: Annotated[str | None, Query(description="The openalex author ID to filter by.")] = None, - author_filter_ids: Annotated[list[int] | None, Query(description="The dfg author IDs to filter by.")] = None, - institution_ids: Annotated[ - list[int] | None, Query(description="The institution IDs to filter by.") - ] = None, + author_filter_ids: Annotated[list[str] | None, Query(description="The dfg author IDs to filter by.")] = None, + institution_ids: Annotated[list[str] | None, Query(description="The institution IDs to filter by.")] = None, title: Annotated[ str | None, Query(description="The title to filter by.") ] = None, diff --git a/service/src/main/inse/projects/service.py b/service/src/main/inse/projects/service.py index 813ff0e2..f1abccf8 100644 --- a/service/src/main/inse/projects/service.py +++ b/service/src/main/inse/projects/service.py @@ -40,6 +40,7 @@ from inse.projects.model import ( ProjectType, SortDirection, ) +from inse.projects.logic import get_dfg_author_names_by_ids from inse.works.logic import get_publication_dois_of_author from fastapi import HTTPException as HttpException logger = logging.getLogger(__name__) @@ -156,12 +157,25 @@ async def _get_dfg_project_ids_for_openalex_authors( return list(set.intersection(*project_sets)) +def _is_number_list(values: list[str] | None) -> bool: + if not values: + return True # nothing to validate, treat as valid/empty + for value in values: + if value is None or value == "": + return False + try: + float(value) + except (TypeError, ValueError): + return False + return True + + async def get_dfg_projects( institutions_search_client: InstitutionsSearchClient, raw_oa_institution_id: str | None, author_id: str | None, - author_filter_ids: list[int] | None, - institution_ids: list[int] | None, + author_filter_ids: list[str] | None, + institution_ids: list[str] | None, keywords: list[str] | None, topic_ids: list[str] | None, filter_topic_ids: list[str] | None, @@ -195,6 +209,23 @@ async def get_dfg_projects( sort_direction, fuzzy, ) + + # Validate author_filter_ids / institution_ids. Return an empty page + if not _is_number_list(author_filter_ids) or not _is_number_list(institution_ids): + logger.debug( + "Invalid author_filter_ids=%s or institution_ids=%s, returning empty page", + author_filter_ids, + institution_ids, + ) + return DfgProjectPage(elements=[], page=page, size=size, total=0) + + author_filter_ids_int = ( + [int(float(v)) for v in author_filter_ids] if author_filter_ids else None + ) + institution_ids_int = ( + [int(float(v)) for v in institution_ids] if institution_ids else None + ) + filter_names = [] author_project_ids = [] if author_id: @@ -207,16 +238,16 @@ async def get_dfg_projects( size=size, total=0) - if author_filter_ids: + if author_filter_ids_int: filter_names = ( - await get_dfg_author_names_by_ids(author_ids=author_filter_ids) - if author_filter_ids + await get_dfg_author_names_by_ids(author_ids=author_filter_ids_int) + if author_filter_ids_int else [] ) - if author_filter_ids and not filter_names: + if author_filter_ids_int and not filter_names: logger.debug( "No author names found for author_filter_ids=%s", - author_filter_ids, + author_filter_ids_int, ) institution_aliases = [] if raw_oa_institution_id: @@ -242,7 +273,7 @@ async def get_dfg_projects( institution_aliases=institution_aliases, project_ids=author_project_ids, names=filter_names or [], - institution_ids=institution_ids, + institution_ids=institution_ids_int, keywords=keywords, topic_ids=topic_ids, filter_topic_ids=filter_topic_ids, diff --git a/webapp/src/app/api/api/projects.service.ts b/webapp/src/app/api/api/projects.service.ts index 0db7818b..938af152 100644 --- a/webapp/src/app/api/api/projects.service.ts +++ b/webapp/src/app/api/api/projects.service.ts @@ -86,10 +86,10 @@ export class ProjectsService extends BaseService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public getDfgProjects(rawOaInstitutionId?: string, authorId?: string, authorFilterIds?: Array, institutionIds?: Array, title?: string, keywords?: Array, topicIds?: Array, filterTopicIds?: Array, fundingStartYears?: Array, fundingEndYears?: Array, page?: number, size?: number, sortBy?: string, sortDirection?: string, fuzzy?: boolean, secureFgpAcc?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; - public getDfgProjects(rawOaInstitutionId?: string, authorId?: string, authorFilterIds?: Array, institutionIds?: Array, title?: string, keywords?: Array, topicIds?: Array, filterTopicIds?: Array, fundingStartYears?: Array, fundingEndYears?: Array, page?: number, size?: number, sortBy?: string, sortDirection?: string, fuzzy?: boolean, secureFgpAcc?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public getDfgProjects(rawOaInstitutionId?: string, authorId?: string, authorFilterIds?: Array, institutionIds?: Array, title?: string, keywords?: Array, topicIds?: Array, filterTopicIds?: Array, fundingStartYears?: Array, fundingEndYears?: Array, page?: number, size?: number, sortBy?: string, sortDirection?: string, fuzzy?: boolean, secureFgpAcc?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public getDfgProjects(rawOaInstitutionId?: string, authorId?: string, authorFilterIds?: Array, institutionIds?: Array, title?: string, keywords?: Array, topicIds?: Array, filterTopicIds?: Array, fundingStartYears?: Array, fundingEndYears?: Array, page?: number, size?: number, sortBy?: string, sortDirection?: string, fuzzy?: boolean, secureFgpAcc?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + public getDfgProjects(rawOaInstitutionId?: string, authorId?: string, authorFilterIds?: Array, institutionIds?: Array, title?: string, keywords?: Array, topicIds?: Array, filterTopicIds?: Array, fundingStartYears?: Array, fundingEndYears?: Array, page?: number, size?: number, sortBy?: string, sortDirection?: string, fuzzy?: boolean, secureFgpAcc?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public getDfgProjects(rawOaInstitutionId?: string, authorId?: string, authorFilterIds?: Array, institutionIds?: Array, title?: string, keywords?: Array, topicIds?: Array, filterTopicIds?: Array, fundingStartYears?: Array, fundingEndYears?: Array, page?: number, size?: number, sortBy?: string, sortDirection?: string, fuzzy?: boolean, secureFgpAcc?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getDfgProjects(rawOaInstitutionId?: string, authorId?: string, authorFilterIds?: Array, institutionIds?: Array, title?: string, keywords?: Array, topicIds?: Array, filterTopicIds?: Array, fundingStartYears?: Array, fundingEndYears?: Array, page?: number, size?: number, sortBy?: string, sortDirection?: string, fuzzy?: boolean, secureFgpAcc?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getDfgProjects(rawOaInstitutionId?: string, authorId?: string, authorFilterIds?: Array, institutionIds?: Array, title?: string, keywords?: Array, topicIds?: Array, filterTopicIds?: Array, fundingStartYears?: Array, fundingEndYears?: Array, page?: number, size?: number, sortBy?: string, sortDirection?: string, fuzzy?: boolean, secureFgpAcc?: string, 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, diff --git a/webapp/src/app/resolvers/dfg-projects.resolver.ts b/webapp/src/app/resolvers/dfg-projects.resolver.ts index 365a4214..102976f9 100644 --- a/webapp/src/app/resolvers/dfg-projects.resolver.ts +++ b/webapp/src/app/resolvers/dfg-projects.resolver.ts @@ -1,6 +1,5 @@ import { inject } from '@angular/core'; import { ResolveFn } from '@angular/router'; -import { of } from 'rxjs'; import { DfgProjectPage, ProjectsService } from '../api'; export const dfgProjectQueryParamKeys = { @@ -25,34 +24,6 @@ export const RESOLVING_PROJECT_PAGE_FOR = { KEYWORDS_SEARCH: 'KEYWORDS_SEARCH', } as const; -// Empty page returned whenever a required numeric param fails to parse. -const EMPTY_DFG_PROJECT_PAGE: DfgProjectPage = { - page: 0, - size: 0, - total: 0, - elements: [], -} as DfgProjectPage; - -function toNumberOrNull(value: unknown): number | null { - if (value === undefined || value === null || value === '') { - return null; - } - const parsed = Number(value); - return Number.isFinite(parsed) ? parsed : null; -} - -function toNumberArrayOrNull(values: string[]): number[] | null { - const result: number[] = []; - for (const value of values) { - const parsed = toNumberOrNull(value); - if (parsed === null) { - return null; - } - result.push(parsed); - } - return result; -} - export const dfgProjectsResolver: ResolveFn = ( route, state, @@ -69,11 +40,10 @@ export const dfgProjectsResolver: ResolveFn = ( ); const page = - toNumberOrNull(route.queryParamMap.get(dfgProjectQueryParamKeys.page)) ?? 0; + Number(route.queryParamMap.get(dfgProjectQueryParamKeys.page)) || 0; const size = - toNumberOrNull(route.queryParamMap.get(dfgProjectQueryParamKeys.size)) ?? - 10; + Number(route.queryParamMap.get(dfgProjectQueryParamKeys.size)) || 10; const searchTerm = route.queryParamMap.get(dfgProjectQueryParamKeys.title) ?? undefined; @@ -92,15 +62,12 @@ export const dfgProjectsResolver: ResolveFn = ( dfgProjectQueryParamKeys.topicId, ); - const institutionIds = toNumberArrayOrNull( - route.queryParamMap.getAll(dfgProjectQueryParamKeys.institutionId), + const institutionIds = route.queryParamMap.getAll( + dfgProjectQueryParamKeys.institutionId, ); - const authorIds = toNumberArrayOrNull( - route.queryParamMap.getAll(dfgProjectQueryParamKeys.authorId), + const authorIds = route.queryParamMap.getAll( + dfgProjectQueryParamKeys.authorId, ); - if (institutionIds === null || authorIds === null) { - return of(EMPTY_DFG_PROJECT_PAGE); - } if (resolvingFor === RESOLVING_PROJECT_PAGE_FOR.PERSON) { const rawAuthorId = route.parent?.parent?.params['id']; From 30cbb080b015b34fc415ce6a21067dd23470c085 Mon Sep 17 00:00:00 2001 From: genja Date: Thu, 6 Aug 2026 14:19:16 +0200 Subject: [PATCH 066/114] adjusted tests for new service function name --- service/src/main/inse/dashboard/test_service.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/service/src/main/inse/dashboard/test_service.py b/service/src/main/inse/dashboard/test_service.py index 630f8121..2de2ca6e 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_dfg_topic_project_ids_use_paginated_projects_service(): ] with patch( - "inse.dashboard.service.projects_service.get_dfg_projects_by_author_id", + "inse.dashboard.service.projects_service.get_dfg_projects", new=AsyncMock(side_effect=pages), ) as mocked_get_projects: project_ids = await _get_dfg_project_ids_from_projects_service( @@ -144,7 +144,7 @@ async def test_dashboard_statistics_counts_organization_data_and_all_projects(): ) ), ), patch( - "inse.dashboard.service.projects_service.get_dfg_projects_by_author_id", + "inse.dashboard.service.projects_service.get_dfg_projects", new=AsyncMock( return_value=DfgProjectPage(elements=[], total=3, page=0, size=1) ), @@ -254,7 +254,7 @@ async def test_dashboard_dfg_projects_uses_projects_service_total(): project_page = DfgProjectPage(elements=[], total=42, page=0, size=1) with patch( - "inse.dashboard.service.projects_service.get_dfg_projects_by_author_id", + "inse.dashboard.service.projects_service.get_dfg_projects", new=AsyncMock(return_value=project_page), ) as mocked_get_projects: result = await get_dashboard_dfg_projects( From c70a56651429fab872884c0c1caaf964c6869233 Mon Sep 17 00:00:00 2001 From: arzani Date: Thu, 6 Aug 2026 15:03:54 +0200 Subject: [PATCH 067/114] cc-news integration in keyword analysis via explicit non-fuzzy search --- .../main/inse/integrations/elasticsearch.py | 9 +- service/src/main/inse/model.py | 1 + .../university_ranking/trend_query_builder.py | 65 +++++++ .../university_ranking/trend_strategies.py | 181 ++++++++++++++---- .../university-ranking/models/trend.models.ts | 7 +- .../uni-trend-chart.component.ts | 20 +- .../uni-trend-parent.component.html | 39 ++-- .../uni-trend-parent.component.scss | 20 ++ .../uni-trend-parent.component.ts | 85 ++++++-- .../university-ranking/utils/trend.utils.ts | 58 +++--- .../src/app/resolvers/uni-trend.resolver.ts | 2 +- 11 files changed, 376 insertions(+), 111 deletions(-) diff --git a/service/src/main/inse/integrations/elasticsearch.py b/service/src/main/inse/integrations/elasticsearch.py index 0ad63956..c0553de1 100644 --- a/service/src/main/inse/integrations/elasticsearch.py +++ b/service/src/main/inse/integrations/elasticsearch.py @@ -96,6 +96,7 @@ def _index_to_cluster(index: ESIndex) -> ESCluster | None: ESIndex.OPENALEX_INSTITUTIONS, ESIndex.OPENALEX_PUBLICATIONS, ESIndex.WORK_CLASSIFICATIONS, + ESIndex.CC_NEWS_WILDCARD, }: return ESCluster.NES elif index in { @@ -439,12 +440,16 @@ async def count( async def msearch( searches: list[tuple[ESIndex | str | list[str], dict[str, Any]]], cluster: ESCluster = ESCluster.NES, + request_cache: bool = False, ) -> list[dict[str, Any]]: """Performs a multi-search request (_msearch) on Elasticsearch. Args: searches: A list of tuples, each containing (index, payload_dict). cluster: The Elasticsearch cluster to execute searches on. + request_cache: Whether to enable the shard request cache for each search. + Elasticsearch rejects `request_cache` as an _msearch URL parameter, so + it goes into the per-search header line instead. Returns: List[Dict[str, Any]]: List of response dictionaries for each search in order. @@ -464,7 +469,9 @@ async def msearch( idx_str = ",".join(str(i) for i in idx) else: idx_str = str(idx) - header_obj = {"index": idx_str} + header_obj: dict[str, Any] = {"index": idx_str} + if request_cache: + header_obj["request_cache"] = True lines.append(json.dumps(header_obj)) lines.append(json.dumps(body)) diff --git a/service/src/main/inse/model.py b/service/src/main/inse/model.py index e1f0d3aa..83c064c3 100644 --- a/service/src/main/inse/model.py +++ b/service/src/main/inse/model.py @@ -65,6 +65,7 @@ class ESIndex(StrEnum): AKTUELLES = "aktuell" AKTUELLES_POSTPROC = "aktuell_postproc" AKTUELLES_OPENALEX_TOPICS = "aktuell_openalex_topics" + CC_NEWS_WILDCARD = "cc-news-*" CORDIS_EU_ORGANIZATIONS_WILDCARD = "cordis_eu_*_organizations" diff --git a/service/src/main/inse/university_ranking/trend_query_builder.py b/service/src/main/inse/university_ranking/trend_query_builder.py index dc639132..10e4b805 100644 --- a/service/src/main/inse/university_ranking/trend_query_builder.py +++ b/service/src/main/inse/university_ranking/trend_query_builder.py @@ -1,5 +1,6 @@ import asyncio import logging +import re from typing import Any from inse.integrations import elasticsearch @@ -11,6 +12,17 @@ logger = logging.getLogger(__name__) DEFAULT_INSTITUTION_ID = "https://openalex.org/I62318514" DEFAULT_INSTITUTION_NAME = "University of Duisburg-Essen" +# Reserved characters and boolean operators of the Lucene query_string syntax +_LUCENE_SPECIAL_CHARS = re.compile(r'([+\-=&|> str: + """Escapes a free-text search term so it is safe inside a ``query_string`` query.""" + if not term: + return "" + escaped = _LUCENE_SPECIAL_CHARS.sub(r"\\\1", term) + return _LUCENE_BOOL_OPERATORS.sub(lambda m: f'"{m.group(1)}"', escaped) def clean_inst_id(id_str: str) -> str: @@ -407,6 +419,56 @@ class TrendQueryBuilder: } } + @staticmethod + def build_cc_news_year_agg_body( + term: str, + start_year: int, + end_year: int, + languages: list[str] | None = None, + ) -> dict[str, Any]: + """Builds a size=0 yearly-count aggregation over the Common Crawl News indices. Buckets + by year with a `date_histogram`, since cc-news has a real `content_date` date field rather than + the integer `date_year` of `aktuell`. + """ + return { + "size": 0, + "track_total_hits": False, + "_source": False, + "query": { + "bool": { + "filter": [ + { + "query_string": { + "query": escape_lucene_query(term), + "fields": CC_NEWS_SEARCH_FIELDS, + "default_operator": "AND", + } + }, + {"terms": {"language_code": languages or CC_NEWS_LANGUAGES}}, + { + "range": { + "content_date": { + "gte": f"{start_year}-01-01", + "lte": f"{end_year}-12-31", + "format": "yyyy-MM-dd", + } + } + }, + ] + } + }, + "aggs": { + "by_year": { + "date_histogram": { + "field": "content_date", + "calendar_interval": "year", + "format": "yyyy", + "min_doc_count": 0, + } + } + }, + } + @staticmethod def build_bund_receiver_clause(aliases: list[str]) -> dict[str, Any]: """Builds Zuwendungsempfänger matching clause for BUND projects.""" @@ -443,4 +505,7 @@ DFG_PROJECT_TEXT_FIELDS = [ CORDIS_PROJECT_TEXT_FIELDS = ["title", "objective"] AKTUELLES_SEARCH_FIELDS = ["main_content", "full_content", "maintitle", "subtitle", "intro_content"] +CC_NEWS_SEARCH_FIELDS = ["title", "body"] +CC_NEWS_LANGUAGES = ["de", "en"] +CC_NEWS_START_YEAR = 2017 diff --git a/service/src/main/inse/university_ranking/trend_strategies.py b/service/src/main/inse/university_ranking/trend_strategies.py index f46c6be2..c0badec6 100644 --- a/service/src/main/inse/university_ranking/trend_strategies.py +++ b/service/src/main/inse/university_ranking/trend_strategies.py @@ -16,11 +16,13 @@ from .model import ( ) from .trend_query_builder import ( AKTUELLES_SEARCH_FIELDS, + CC_NEWS_START_YEAR, DEFAULT_INSTITUTION_ID, DEFAULT_INSTITUTION_NAME, TrendMetadataResolver, TrendQueryBuilder, clean_inst_id, + escape_lucene_query, to_full_inst_url, ) @@ -47,6 +49,13 @@ EPO_PATENT_FIELDS = [ "openalex_topics.topic_id", ] +# Synthetic entity id prefixes for the news trend series. The webapp keys colouring, chip +# visibility and pie filtering off these, so keep them in sync with uni-trend-parent.component.ts. +NEWS_ENTITY_PREFIX = "news_topic_" +CC_NEWS_ENTITY_PREFIX = "ccnews_topic_" +# Entity id of the collapsed CC-News series in the cross-domain ("all") view. +CC_NEWS_COMPOSITE_ID = "ccnews" + DFG_INSTITUTION_FIELDS = [ "Antragstellende Institution", "Mitantragstellende Institution", @@ -1042,6 +1051,18 @@ class ProjectsTrendStrategy(TrendStrategy): class NewsTrendStrategy(TrendStrategy): + """Yearly news counts per topic. + + Produces one series per topic from the UDE-internal `aktuell` index (entity id + ``news_topic_``). When keyword matching is active (``fuzzy=False``) it additionally + produces an external Common Crawl News baseline per topic (``ccnews_topic_``) so the + internal coverage can be compared against the wider web. CC-News has no OpenAlex topic + mapping, so it is skipped entirely in topic-mapping mode. + """ + + def __init__(self, include_cc_news: bool = True): + self.include_cc_news = include_cc_news + async def get_trend( self, topics: list[str], @@ -1054,20 +1075,40 @@ class NewsTrendStrategy(TrendStrategy): ) -> TrendResponse: years_range = self._get_years_range() start_year, end_year = years_range[0], years_range[-1] + years_set = set(years_range) + + cc_news_enabled = self.include_cc_news and not fuzzy accumulated_data = { - f"news_topic_{t}": {top: {yr: (0, 1) for yr in years_range} for top in topics} + f"{NEWS_ENTITY_PREFIX}{t}": {top: {yr: (0, 1) for yr in years_range} for top in topics} for t in topics } + if cc_news_enabled: + accumulated_data.update({ + f"{CC_NEWS_ENTITY_PREFIX}{t}": {top: {yr: (0, 1) for yr in years_range} for top in topics} + for t in topics + }) STOP_WORDS = {"in", "and", "or", "und", "oder", "der", "die", "das", "von", "mit", "zu", "at", "by", "on", "for", "to", "a", "an", "the"} + def resolve_keyword_term(idx: int, t_name: str) -> str: + """Picks the raw keyword for a topic, falling back to the topic name itself.""" + if keywords and idx < len(keywords) and keywords[idx]: + raw_kw = keywords[idx] + term = raw_kw.split(",")[0].strip() if isinstance(raw_kw, str) else raw_kw + if term: + return term + return t_name + + def is_searchable_term(term: str) -> bool: + return bool(term) and term.lower() not in STOP_WORDS and len(term.strip()) > 1 + # Scan UDE news OpenAlex topics index to get matching news IDs without size limit cutoffs async def fetch_news_ids_for_term(idx: int, t_name: str) -> list[str]: news_ids: Set[str] = set() if fuzzy: term = t_name - es_query = {"term": {"topic_matches.topic_display_name.keyword": term}} + es_query = {"match_phrase": {"topic_matches.topic_display_name": term}} try: async for hit in elasticsearch.scan( index=ESIndex.AKTUELLES_OPENALEX_TOPICS.value, @@ -1081,20 +1122,14 @@ class NewsTrendStrategy(TrendStrategy): except Exception as e: logger.warning("Failed to scan UDE news OpenAlex topics index %s: %s", ESIndex.AKTUELLES_OPENALEX_TOPICS.value, e) else: - if keywords and idx < len(keywords) and keywords[idx]: - raw_kw = keywords[idx] - term = raw_kw.split(",")[0].strip() if isinstance(raw_kw, str) else raw_kw - if not term: - term = t_name - else: - term = t_name + term = resolve_keyword_term(idx, t_name) # If non-fuzzy keyword search, search article content fields in 'aktuell' index - if term and term.lower() not in STOP_WORDS and len(term.strip()) > 1: + if is_searchable_term(term): try: content_query = { "query_string": { - "query": term, + "query": escape_lucene_query(term), "fields": AKTUELLES_SEARCH_FIELDS, "default_operator": "AND", } @@ -1113,12 +1148,59 @@ class NewsTrendStrategy(TrendStrategy): return list(news_ids) - matching_ids_list = await asyncio.gather(*(fetch_news_ids_for_term(idx, t) for idx, t in enumerate(topics))) + async def fetch_cc_news_counts() -> dict[int, dict[int, int]]: + """Yearly CC-News counts per topic index, from a single _msearch over cc-news-*. + The year buckets are read straight off a size=0 date_histogram instead. + """ + searchable = [ + (idx, term) + for idx, t_name in enumerate(topics) + if is_searchable_term(term := resolve_keyword_term(idx, t_name)) + ] + if not searchable: + return {} + + searches = [ + ( + ESIndex.CC_NEWS_WILDCARD.value, + TrendQueryBuilder.build_cc_news_year_agg_body(term, CC_NEWS_START_YEAR, end_year), + ) + for _, term in searchable + ] + try: + responses = await elasticsearch.msearch( + searches, cluster=ESCluster.NES, request_cache=True + ) + except Exception as e: + logger.warning("Failed to aggregate CC-News years via msearch: %s", e) + return {} + + counts: dict[int, dict[int, int]] = {} + for (topic_idx, term), res in zip(searchable, responses): + if not isinstance(res, dict) or "error" in res: + logger.warning("CC-News msearch entry for %r failed: %s", term, (res or {}).get("error")) + continue + by_year: dict[int, int] = {} + for b in res.get("aggregations", {}).get("by_year", {}).get("buckets", []): + try: + yr = int(b.get("key_as_string")) + except (TypeError, ValueError): + continue + if yr in years_set: + by_year[yr] = int(b.get("doc_count", 0)) + counts[topic_idx] = by_year + return counts + + news_ids_future = asyncio.gather(*(fetch_news_ids_for_term(idx, t) for idx, t in enumerate(topics))) + if cc_news_enabled: + matching_ids_list, cc_news_counts = await asyncio.gather(news_ids_future, fetch_cc_news_counts()) + else: + matching_ids_list, cc_news_counts = await news_ids_future, {} async def count_by_year(t_name: str, news_ids: list[str]): if not news_ids: return - entity_key = f"news_topic_{t_name}" + entity_key = f"{NEWS_ENTITY_PREFIX}{t_name}" # Prepare multi-search payloads for chunks of news_ids to avoid payload limits chunk_queries = [] @@ -1164,13 +1246,15 @@ class NewsTrendStrategy(TrendStrategy): await asyncio.gather(*(count_by_year(t, ids) for t, ids in zip(topics, matching_ids_list))) + for topic_idx, t_name in enumerate(topics): + entity_key = f"{CC_NEWS_ENTITY_PREFIX}{t_name}" + for yr, count in cc_news_counts.get(topic_idx, {}).items(): + prev_count, _ = accumulated_data[entity_key][t_name][yr] + accumulated_data[entity_key][t_name][yr] = (prev_count + count, 1) + normalized_lookup = self._normalize_series(years_range, accumulated_data, topics) - series_list: list[TrendSeries] = [] - for t_name in topics: - entity_key = f"news_topic_{t_name}" - topic_data_map: dict[str, list[TopicYearlyData]] = {} - + def build_series(entity_key: str, t_name: str, entity_name: str) -> TrendSeries: lookup = normalized_lookup.get((entity_key, t_name), {}) norm_vals = lookup.get("normalized", [0.0] * len(years_range)) cum_vals = lookup.get("cumulative", [0.0] * len(years_range)) @@ -1188,16 +1272,22 @@ class NewsTrendStrategy(TrendStrategy): ) ) - for topic in topics: - topic_data_map[topic] = yearly_data_items + topic_data_map: dict[str, list[TopicYearlyData]] = {topic: yearly_data_items for topic in topics} - series_list.append( - TrendSeries( - entity_id=entity_key, - entity_name=t_name, - entity_type="institution", - topic_data=topic_data_map, - ) + return TrendSeries( + entity_id=entity_key, + entity_name=entity_name, + entity_type="institution", + topic_data=topic_data_map, + ) + + series_list: list[TrendSeries] = [ + build_series(f"{NEWS_ENTITY_PREFIX}{t_name}", t_name, t_name) for t_name in topics + ] + if cc_news_enabled: + series_list.extend( + build_series(f"{CC_NEWS_ENTITY_PREFIX}{t_name}", t_name, f"{t_name} (CC-News)") + for t_name in topics ) return TrendResponse(series=series_list, years=years_range) @@ -1269,25 +1359,40 @@ class AllTrendStrategy(TrendStrategy): add_composite(pat_series, "patents", "Patentanmeldungen") add_composite(proj_series, "projects", "Drittmittelförderung") - if is_ude and news_res: - merged_news_topic_data: dict[str, list[TopicYearlyData]] = {} + def merge_news_composite(prefix: str, c_id: str, c_name: str) -> bool: + """Collapses the per-topic news series of one source into a single composite. + + Returns False when the source produced no series at all. + """ + if not news_res or not any(s.entity_id.startswith(prefix) for s in news_res.series): + return False + + merged_topic_data: dict[str, list[TopicYearlyData]] = {} for topic in topics: - term_key = f"news_topic_{topic}" + term_key = f"{prefix}{topic}" matching_series = next((s for s in news_res.series if s.entity_id == term_key), None) if matching_series and topic in matching_series.topic_data: - merged_news_topic_data[topic] = matching_series.topic_data[topic] + merged_topic_data[topic] = matching_series.topic_data[topic] else: - merged_news_topic_data[topic] = [ + merged_topic_data[topic] = [ TopicYearlyData(year=yr, raw=0, normalized=0.0, cumulative=0.0, institutions_count=1) for yr in years_range ] - news_series = TrendSeries( - entity_id="news", - entity_name="UDE Campus Aktuell Beiträge", - entity_type="institution", - topic_data=merged_news_topic_data, + add_composite( + TrendSeries( + entity_id=c_id, + entity_name=c_name, + entity_type="institution", + topic_data=merged_topic_data, + ), + c_id, + c_name, ) - add_composite(news_series, "news", "UDE Campus Aktuell Beiträge") + return True + + if is_ude: + merge_news_composite(NEWS_ENTITY_PREFIX, "news", "UDE Campus Aktuell Beiträge") + merge_news_composite(CC_NEWS_ENTITY_PREFIX, CC_NEWS_COMPOSITE_ID, "Web-Nachrichten (CC-News)") return TrendResponse(series=composite_series, years=years_range) diff --git a/webapp/src/app/modules/university-ranking/models/trend.models.ts b/webapp/src/app/modules/university-ranking/models/trend.models.ts index 9e049604..e333c281 100644 --- a/webapp/src/app/modules/university-ranking/models/trend.models.ts +++ b/webapp/src/app/modules/university-ranking/models/trend.models.ts @@ -15,6 +15,11 @@ export interface TrendStrategyConfig { export type TrendSeriesWithVisibility = TrendSeries & { visible?: boolean }; +export const NEWS_ENTITY_PREFIX = 'news_topic_'; +export const CC_NEWS_ENTITY_PREFIX = 'ccnews_topic_'; +export const CC_NEWS_COMPOSITE_ID = 'ccnews'; +export const CC_NEWS_START_YEAR = 2017; + export const TREND_CONFIGS: Record = { publications: { showInstitutionSelector: true, @@ -49,7 +54,7 @@ export const TREND_CONFIGS: Record = { showLocationSelector: false, showAuthorSelector: false, yAxisLabel: 'Pressemitteilungen', - chartTitle: 'Nachrichtentrends', + chartTitle: 'Nachrichtentrends (UDE vs. CC-News)', }, all: { showInstitutionSelector: false, diff --git a/webapp/src/app/modules/university-ranking/uni-trend-chart/uni-trend-chart.component.ts b/webapp/src/app/modules/university-ranking/uni-trend-chart/uni-trend-chart.component.ts index 82061df7..b9b36dd5 100644 --- a/webapp/src/app/modules/university-ranking/uni-trend-chart/uni-trend-chart.component.ts +++ b/webapp/src/app/modules/university-ranking/uni-trend-chart/uni-trend-chart.component.ts @@ -10,6 +10,8 @@ import { NgxEchartsDirective } from 'ngx-echarts'; import { MatIconModule } from '@angular/material/icon'; import { TrendResponse, TrendSeries, TopicYearlyData } from '../../../api'; import { ChartThemeService } from '../../../shared/services/chart-theme.service'; +import { CC_NEWS_START_YEAR } from '../models/trend.models'; +import { isCcNewsSeries } from '../utils/trend.utils'; @Component({ selector: 'app-uni-trend-chart', @@ -111,8 +113,9 @@ export class UniTrendChartComponent { return; } const yrTopicData = entity.topic_data[selectedTopic] || []; - + const isCcNews = isCcNewsSeries(entity.entity_id); const lineData = years.map((year) => { + if (isCcNews && year < CC_NEWS_START_YEAR) return null; const yrData = yrTopicData.find((y) => y.year === year); if (!yrData) return 0; if (currentMode === 'cumulative') { @@ -126,13 +129,14 @@ export class UniTrendChartComponent { type: 'line', xAxisIndex: 0, yAxisIndex: 0, - areaStyle: { - opacity: 0.12, - }, + areaStyle: { opacity: isCcNews ? 0.3 : 0.12 }, data: lineData, smooth: true, + connectNulls: false, + showSymbol: !isCcNews, + z: isCcNews ? 1 : 2, lineStyle: { - width: 2.5, + width: isCcNews ? 1 : 2.5, color: color, }, itemStyle: { @@ -140,10 +144,14 @@ export class UniTrendChartComponent { }, emphasis: { focus: 'series', - lineStyle: { width: 3.5 }, + lineStyle: { width: isCcNews ? 2 : 3.5 }, }, }); + if (isCcNews) { + return; + } + const bars = years.map((year) => { const yrData = yrTopicData.find((y) => y.year === year); const val = yrData ? yrData.raw : 0; diff --git a/webapp/src/app/modules/university-ranking/uni-trend-parent/uni-trend-parent.component.html b/webapp/src/app/modules/university-ranking/uni-trend-parent/uni-trend-parent.component.html index 4183676e..6560cc05 100644 --- a/webapp/src/app/modules/university-ranking/uni-trend-parent/uni-trend-parent.component.html +++ b/webapp/src/app/modules/university-ranking/uni-trend-parent/uni-trend-parent.component.html @@ -36,7 +36,7 @@ [matTooltip]=" !isUde() ? 'News-Trends sind nur für die Universität Duisburg-Essen verfügbar' - : 'Zeigt Pressemitteilungstrends der UDE' + : 'Zeigt Pressemitteilungstrends der UDE im Vergleich zur Web-Berichterstattung (CC-News). Der CC-News-Vergleich erfordert deaktivierte Fuzzy-Suche.' " (click)="setSearchType('news')"> campaign News @@ -184,28 +184,27 @@

    Daten werden geladen...

    } + @if (selectedSearchType() === 'news' && !hasCcNewsSeries()) { +
    + info_outline + + Der CC-News-Vergleich (hinterlegte Fläche, ab 2017) ist aktuell nur bei + deaktivierter Fuzzy-Suche verfügbar, da für Web-Nachrichten kein + Themen-Mapping existiert. + +
    + } @if (selectedTrendTopics().length > 0) {
    @for (topic of selectedTrendTopics(); track $index) { - @if (selectedSearchType() === 'news') { - - - } @else { - - - } + + }
    } diff --git a/webapp/src/app/modules/university-ranking/uni-trend-parent/uni-trend-parent.component.scss b/webapp/src/app/modules/university-ranking/uni-trend-parent/uni-trend-parent.component.scss index 30951435..6f25eca7 100644 --- a/webapp/src/app/modules/university-ranking/uni-trend-parent/uni-trend-parent.component.scss +++ b/webapp/src/app/modules/university-ranking/uni-trend-parent/uni-trend-parent.component.scss @@ -164,6 +164,26 @@ border-bottom: 1px solid var(--sg-border); } +.cc-news-hint { + display: flex; + align-items: flex-start; + gap: 0.5rem; + padding: 0.75rem 1.25rem; + background: var(--sg-surface-muted); + border-bottom: 1px solid var(--sg-border); + color: var(--sg-text-muted); + font-size: 0.85rem; + line-height: 1.4; + + mat-icon { + flex: none; + font-size: 1.1rem; + width: 1.1rem; + height: 1.1rem; + color: var(--sg-primary); + } +} + .loader-overlay { position: absolute; top: 0; diff --git a/webapp/src/app/modules/university-ranking/uni-trend-parent/uni-trend-parent.component.ts b/webapp/src/app/modules/university-ranking/uni-trend-parent/uni-trend-parent.component.ts index b55c799f..f9dfc8e2 100644 --- a/webapp/src/app/modules/university-ranking/uni-trend-parent/uni-trend-parent.component.ts +++ b/webapp/src/app/modules/university-ranking/uni-trend-parent/uni-trend-parent.component.ts @@ -69,12 +69,19 @@ import { } from '../../../shared/ui/topic-treemap/topic-treemap.models'; import { TopicsService } from '../../../api/api/topics.service'; -import { CompareItem, TREND_CONFIGS } from '../models/trend.models'; +import { + CC_NEWS_COMPOSITE_ID, + CC_NEWS_ENTITY_PREFIX, + CompareItem, + NEWS_ENTITY_PREFIX, + TREND_CONFIGS, +} from '../models/trend.models'; import { cleanEntityId, isTopicEmptyForSeries, findFirstNonEmptyTopic, buildEntityColorIndex, + newsSourceColor, } from '../utils/trend.utils'; import { TrendDataService } from '../services/trend-data.service'; @@ -326,28 +333,37 @@ export class UniTrendParentComponent implements OnInit { readonly boundGetTopicColor = this.getTopicColor.bind(this); readonly newsSelectedTopicsPieData = computed(() => { - const data = this.trendResponse(); + const data = this.rawTrendResponse(); if (!data || !data.series || this.selectedSearchType() !== 'news') { return null; } const startYr = this.startYear(); const endYr = this.endYear(); - return data.series.map((s) => { - const topicName = s.entity_name; - const yearlyItems = - s.topic_data[topicName] || Object.values(s.topic_data)[0] || []; - const totalRaw = yearlyItems - .filter((y) => y.year >= startYr && y.year <= endYr) - .reduce((sum, item) => sum + (item.raw || 0), 0); + return data.series + .filter((s) => s.entity_id.startsWith(NEWS_ENTITY_PREFIX)) + .map((s) => { + const topicName = s.entity_name; + const yearlyItems = + s.topic_data[topicName] || Object.values(s.topic_data)[0] || []; + const totalRaw = yearlyItems + .filter((y) => y.year >= startYr && y.year <= endYr) + .reduce((sum, item) => sum + (item.raw || 0), 0); - return { - name: topicName, - value: totalRaw, - }; - }); + return { + name: topicName, + value: totalRaw, + }; + }); }); + readonly hasCcNewsSeries = computed( + () => + this.rawTrendResponse()?.series?.some((s) => + s.entity_id.startsWith(CC_NEWS_ENTITY_PREFIX), + ) ?? false, + ); + readonly activeTreemapData = computed(() => { const data = this.trendResponse(); const searchType = this.selectedSearchType(); @@ -530,9 +546,24 @@ export class UniTrendParentComponent implements OnInit { }; }); + seriesTopicName(entityId: string): string { + if (entityId.startsWith(NEWS_ENTITY_PREFIX)) { + return entityId.slice(NEWS_ENTITY_PREFIX.length); + } + if (entityId.startsWith(CC_NEWS_ENTITY_PREFIX)) { + return entityId.slice(CC_NEWS_ENTITY_PREFIX.length); + } + return entityId; + } + isTopicEmpty(topic: string): boolean { - const series = this.rawTrendResponse()?.series || []; - if (!series || series.length === 0) return true; + const allSeries = this.rawTrendResponse()?.series || []; + if (allSeries.length === 0) return true; + const series = + this.selectedSearchType() === 'news' + ? allSeries.filter((s) => this.seriesTopicName(s.entity_id) === topic) + : allSeries; + if (series.length === 0) return true; const mapped = this.getMappedTopic(topic); const startYr = this.startYear(); @@ -593,6 +624,7 @@ export class UniTrendParentComponent implements OnInit { patents: '#f59e0b', projects: '#10b981', news: '#ec4899', + [CC_NEWS_COMPOSITE_ID]: '#06b6d4', }; const cleanKey = entityId.toLowerCase().trim(); if (categoryColors[cleanKey]) { @@ -600,10 +632,7 @@ export class UniTrendParentComponent implements OnInit { } } if (this.selectedSearchType() === 'news') { - const topicName = entityId.startsWith('news_topic_') - ? entityId.slice('news_topic_'.length) - : entityId; - return this.getTopicColor(topicName); + return newsSourceColor(entityId); } const colorFn = buildEntityColorIndex( this.primaryInstitution(), @@ -739,7 +768,21 @@ export class UniTrendParentComponent implements OnInit { }; }; - if (type === 'news' || type === 'all' || type === 'patents') { + if (type === 'news') { + const active = this.activeChartTopic() || topics[0] || ''; + const wanted = new Set([ + NEWS_ENTITY_PREFIX + active, + CC_NEWS_ENTITY_PREFIX + active, + ]); + return { + ...raw, + series: raw.series + .filter((s) => wanted.has(s.entity_id)) + .map((s) => ({ ...normalizeTopicData(s), visible: true })), + }; + } + + if (type === 'all' || type === 'patents') { return { ...raw, series: raw.series.map((s) => ({ diff --git a/webapp/src/app/modules/university-ranking/utils/trend.utils.ts b/webapp/src/app/modules/university-ranking/utils/trend.utils.ts index b5f28f9e..d8e720ae 100644 --- a/webapp/src/app/modules/university-ranking/utils/trend.utils.ts +++ b/webapp/src/app/modules/university-ranking/utils/trend.utils.ts @@ -1,5 +1,9 @@ import { TrendSeries, TopicYearlyData } from '../../../api'; -import { CompareItem } from '../models/trend.models'; +import { + CC_NEWS_COMPOSITE_ID, + CC_NEWS_ENTITY_PREFIX, + CompareItem, +} from '../models/trend.models'; /** * Extracts short OpenAlex ID from full URL or string, ensuring uppercase ID prefix (e.g. I62318514, A50012345). @@ -53,9 +57,36 @@ export function findFirstNonEmptyTopic( return topics[0]; } -/** - * Builds deterministic entity color lookup map based on entity order and ID. - */ +const entityColors = [ + '#ec4899', // Pink (Primary UDE) + '#3b82f6', // Blue + '#10b981', // Emerald Green + '#f59e0b', // Amber/Yellow + '#8b5cf6', // Purple + '#06b6d4', // Cyan + '#6366f1', // Indigo + '#ef4444', // Red + '#14b8a6', // Teal + '#f97316', // Orange + '#d946ef', // Fuchsia + '#84cc16', // Lime + '#22c55e', // Green + '#a855f7', // Purple/Fuchsia + '#eab308', // Yellow + '#f43f5e', // Rose +]; + +export function isCcNewsSeries(entityId: string): boolean { + return ( + entityId === CC_NEWS_COMPOSITE_ID || + entityId.startsWith(CC_NEWS_ENTITY_PREFIX) + ); +} + +export function newsSourceColor(entityId: string): string { + return isCcNewsSeries(entityId) ? entityColors[1] : entityColors[0]; +} + export function buildEntityColorIndex( primaryId: string | null, institutions: CompareItem[], @@ -63,25 +94,6 @@ export function buildEntityColorIndex( regions: CompareItem[], authors: CompareItem[], ): (id: string) => string { - const entityColors = [ - '#ec4899', // Pink (Primary UDE) - '#3b82f6', // Blue - '#10b981', // Emerald Green - '#f59e0b', // Amber/Yellow - '#8b5cf6', // Purple - '#06b6d4', // Cyan - '#6366f1', // Indigo - '#ef4444', // Red - '#14b8a6', // Teal - '#f97316', // Orange - '#d946ef', // Fuchsia - '#84cc16', // Lime - '#22c55e', // Green - '#a855f7', // Purple/Fuchsia - '#eab308', // Yellow - '#f43f5e', // Rose - ]; - const colorMap = new Map(); let nextIdx = 0; diff --git a/webapp/src/app/resolvers/uni-trend.resolver.ts b/webapp/src/app/resolvers/uni-trend.resolver.ts index 679ac38a..60e54789 100644 --- a/webapp/src/app/resolvers/uni-trend.resolver.ts +++ b/webapp/src/app/resolvers/uni-trend.resolver.ts @@ -42,7 +42,7 @@ export const uniTrendResolver: ResolveFn = ( const trendDataService = inject(TrendDataService); const searchType = params.get('search_type') || 'publications'; - const fuzzy = params.get('fuzzy') !== 'false'; + const fuzzy = params.get('fuzzy') === 'true'; const treemapNode = params.get('treemapNode'); // Primary institution from user token / credential service From daa4f79ea08a0ad8f0fa0c1dad7a157c213e5c80 Mon Sep 17 00:00:00 2001 From: Kazgatari <56477241+Kazgatari@users.noreply.github.com> Date: Thu, 6 Aug 2026 16:30:28 +0200 Subject: [PATCH 068/114] fix: author prefetch did not work (moved away from excessive effect() usage, implemented additional methods to avoid missmatches) --- .../services/trend-data.service.ts | 223 +++++++------ .../uni-trend-parent.component.ts | 57 ++-- .../university-ranking/utils/trend.utils.ts | 44 ++- .../src/app/resolvers/uni-trend.resolver.ts | 312 ++++++++++-------- 4 files changed, 358 insertions(+), 278 deletions(-) diff --git a/webapp/src/app/modules/university-ranking/services/trend-data.service.ts b/webapp/src/app/modules/university-ranking/services/trend-data.service.ts index 626102f3..55e47938 100644 --- a/webapp/src/app/modules/university-ranking/services/trend-data.service.ts +++ b/webapp/src/app/modules/university-ranking/services/trend-data.service.ts @@ -1,4 +1,6 @@ import { Injectable, inject, signal } from '@angular/core'; +import { Subject, of } from 'rxjs'; +import { catchError, map, switchMap } from 'rxjs/operators'; import { UniversityRankingsService, PersonsService, @@ -42,6 +44,124 @@ export class TrendDataService { private readonly cacheMap = new Map(); + // RxJS Subjects for cancellation of pending requests + private readonly topTopicsSubject = new Subject<{ + cleanId: string; + entityType: string; + startYear: number; + endYear: number; + searchType: string; + }>(); + + private readonly instSuggestionsSubject = new Subject<{ + topic: string; + countryFilter?: string; + regionFilter?: string; + }>(); + + private readonly recAuthorsSubject = new Subject<{ + topic: string; + primaryInstId: string; + }>(); + + constructor() { + this.topTopicsSubject + .pipe( + switchMap((params) => { + if (!params.cleanId || params.searchType === 'all') { + this.isTopTopicsLoading.set(false); + this.topTopicsData.set([]); + return of([]); + } + return this.apiService + .getTopTopicsApiInseServiceUniversityRankingsTopTopicsGet( + params.cleanId, + params.entityType, + params.startYear, + params.endYear, + params.searchType, + ) + .pipe( + map((res) => + (res.items || []).map((item) => ({ + value: item.count, + name: item.name, + })), + ), + catchError((err) => { + console.error('Failed to load top topics:', err); + this.topTopicsError.set(true); + return of([]); + }), + ); + }), + ) + .subscribe((data) => { + this.topTopicsData.set(data); + this.isTopTopicsLoading.set(false); + }); + + this.instSuggestionsSubject + .pipe( + switchMap((params) => + this.apiService + .getTopInstitutionsApiInseServiceUniversityRankingsTopInstitutionsGet( + params.topic, + params.regionFilter, + params.countryFilter, + 6, + ) + .pipe(catchError(() => of([]))), + ), + ) + .subscribe((data: any) => { + this.topSuggestions.set(data || []); + this.isSuggestionsLoading.set(false); + }); + + this.recAuthorsSubject + .pipe( + switchMap((params) => { + const cleanInst = cleanEntityId(params.primaryInstId) || 'I62318514'; + return this.personsApiService + .searchPersonsList( + undefined, + cleanInst, + 'cited_by_count', + 'desc', + [params.topic], + 1, + 6, + undefined, + ) + .pipe( + switchMap((res) => { + if (res.results && res.results.length > 0) { + return of(res.results); + } + return this.personsApiService + .searchPersonsList( + undefined, + undefined, + 'cited_by_count', + 'desc', + [params.topic], + 1, + 6, + undefined, + ) + .pipe(map((gRes) => gRes.results || [])); + }), + catchError(() => of([])), + ); + }), + ) + .subscribe((authors) => { + this.recommendedAuthors.set(authors); + this.isSuggestionsLoading.set(false); + }); + } + private getCacheKey(params: TrendRequestParams): string { return JSON.stringify({ searchType: params.searchType, @@ -93,38 +213,19 @@ export class TrendDataService { ): void { if (!entityId || searchType === 'all') { this.topTopicsData.set([]); + this.isTopTopicsLoading.set(false); return; } this.isTopTopicsLoading.set(true); this.topTopicsError.set(false); - - const cleanId = cleanEntityId(entityId); - - this.apiService - .getTopTopicsApiInseServiceUniversityRankingsTopTopicsGet( - cleanId, - entityType, - startYear, - endYear, - searchType, - ) - .subscribe({ - next: (res) => { - const mapped = (res.items || []).map((item) => ({ - value: item.count, - name: item.name, - })); - this.topTopicsData.set(mapped); - this.isTopTopicsLoading.set(false); - }, - error: (err) => { - console.error('Failed to load top topics:', err); - this.topTopicsError.set(true); - this.isTopTopicsLoading.set(false); - this.topTopicsData.set([]); - }, - }); + this.topTopicsSubject.next({ + cleanId: cleanEntityId(entityId), + entityType, + startYear, + endYear, + searchType, + }); } /** @@ -136,24 +237,7 @@ export class TrendDataService { regionFilter?: string, ): void { this.isSuggestionsLoading.set(true); - - this.apiService - .getTopInstitutionsApiInseServiceUniversityRankingsTopInstitutionsGet( - topic, - regionFilter, - countryFilter, - 6, - ) - .subscribe({ - next: (res: any) => { - this.topSuggestions.set(res || []); - this.isSuggestionsLoading.set(false); - }, - error: () => { - this.topSuggestions.set([]); - this.isSuggestionsLoading.set(false); - }, - }); + this.instSuggestionsSubject.next({ topic, countryFilter, regionFilter }); } /** @@ -161,53 +245,6 @@ export class TrendDataService { */ loadRecommendedAuthors(topic: string, primaryInstId: string): void { this.isSuggestionsLoading.set(true); - const cleanInst = cleanEntityId(primaryInstId) || 'I62318514'; - - this.personsApiService - .searchPersonsList( - undefined, - cleanInst, - 'cited_by_count', - 'desc', - [topic], - 1, - 6, - undefined, - ) - .subscribe({ - next: (res) => { - if (res.results && res.results.length > 0) { - this.recommendedAuthors.set(res.results); - this.isSuggestionsLoading.set(false); - } else { - // Global fallback search across all institutions - this.personsApiService - .searchPersonsList( - undefined, - undefined, - 'cited_by_count', - 'desc', - [topic], - 1, - 6, - undefined, - ) - .subscribe({ - next: (globalRes) => { - this.recommendedAuthors.set(globalRes.results || []); - this.isSuggestionsLoading.set(false); - }, - error: () => { - this.recommendedAuthors.set([]); - this.isSuggestionsLoading.set(false); - }, - }); - } - }, - error: () => { - this.recommendedAuthors.set([]); - this.isSuggestionsLoading.set(false); - }, - }); + this.recAuthorsSubject.next({ topic, primaryInstId }); } } diff --git a/webapp/src/app/modules/university-ranking/uni-trend-parent/uni-trend-parent.component.ts b/webapp/src/app/modules/university-ranking/uni-trend-parent/uni-trend-parent.component.ts index f9dfc8e2..ef57e6dc 100644 --- a/webapp/src/app/modules/university-ranking/uni-trend-parent/uni-trend-parent.component.ts +++ b/webapp/src/app/modules/university-ranking/uni-trend-parent/uni-trend-parent.component.ts @@ -557,49 +557,33 @@ export class UniTrendParentComponent implements OnInit { } isTopicEmpty(topic: string): boolean { - const allSeries = this.rawTrendResponse()?.series || []; + const allSeries = + this.trendResponse()?.series || this.rawTrendResponse()?.series || []; if (allSeries.length === 0) return true; const series = this.selectedSearchType() === 'news' ? allSeries.filter((s) => this.seriesTopicName(s.entity_id) === topic) : allSeries; - if (series.length === 0) return true; - - const mapped = this.getMappedTopic(topic); - const startYr = this.startYear(); - const endYr = this.endYear(); - const cId = cleanEntityId(topic); - - for (const s of series) { - if (!s.topic_data) continue; - const keys = [ - topic, - mapped, - cId ? `https://openalex.org/${cId}` : '', - cId, - ].filter(Boolean); - - for (const k of keys) { - const topicItems = s.topic_data[k]; - if (topicItems && topicItems.length > 0) { - const sumRaw = topicItems - .filter((y) => y.year >= startYr && y.year <= endYr) - .reduce((acc, curr) => acc + (curr.raw || 0), 0); - if (sumRaw > 0) return false; - } - } - } - return true; + return isTopicEmptyForSeries( + topic, + series, + this.startYear(), + this.endYear(), + (t) => this.getMappedTopic(t), + ); } findFirstNonEmptyTopic(topics: string[]): string { + const allSeries = + this.trendResponse()?.series || this.rawTrendResponse()?.series || []; if (!topics || topics.length === 0) return ''; - for (const t of topics) { - if (!this.isTopicEmpty(t)) { - return t; - } - } - return topics[0]; + return findFirstNonEmptyTopic( + topics, + allSeries, + this.startYear(), + this.endYear(), + (t) => this.getMappedTopic(t), + ); } isVisible(id: string): boolean { @@ -903,6 +887,11 @@ export class UniTrendParentComponent implements OnInit { } if (resolved.authors && resolved.authors.length > 0) { this.comparisonAuthors.set(resolved.authors); + const currentUrlAuthors = + this.route.snapshot.queryParamMap.getAll('authors'); + if (currentUrlAuthors.length === 0 && type === 'authors') { + this.updateUrlParams(); + } } if (resolved.treemapNode !== undefined) { diff --git a/webapp/src/app/modules/university-ranking/utils/trend.utils.ts b/webapp/src/app/modules/university-ranking/utils/trend.utils.ts index d8e720ae..b0a30958 100644 --- a/webapp/src/app/modules/university-ranking/utils/trend.utils.ts +++ b/webapp/src/app/modules/university-ranking/utils/trend.utils.ts @@ -26,15 +26,42 @@ export function isTopicEmptyForSeries( seriesList: TrendSeries[], startYr: number, endYr: number, + getMappedTopicFn?: (topic: string) => string, ): boolean { if (!seriesList || seriesList.length === 0) return true; + const mapped = getMappedTopicFn ? getMappedTopicFn(topicName) : topicName; + const cleanId = cleanEntityId(topicName); + const cleanMappedId = cleanEntityId(mapped); + const topicLower = topicName.toLowerCase().trim(); + const mappedLower = mapped.toLowerCase().trim(); + for (const s of seriesList) { - const topicItems = s.topic_data?.[topicName] || []; - const filtered = topicItems.filter( - (y) => y.year >= startYr && y.year <= endYr, - ); - const sumRaw = filtered.reduce((acc, curr) => acc + (curr.raw || 0), 0); - if (sumRaw > 0) return false; + if (!s.topic_data) continue; + const entries = Object.entries(s.topic_data); + + for (const [key, topicItems] of entries) { + if (!topicItems || topicItems.length === 0) continue; + + const keyLower = key.toLowerCase().trim(); + const keyClean = cleanEntityId(key); + const revMapped = getMappedTopicFn + ? getMappedTopicFn(key).toLowerCase().trim() + : ''; + + const isMatch = + keyLower === topicLower || + keyLower === mappedLower || + (cleanId && keyClean === cleanId) || + (cleanMappedId && keyClean === cleanMappedId) || + (revMapped && (revMapped === topicLower || revMapped === mappedLower)); + + if (isMatch) { + const sumRaw = topicItems + .filter((y) => y.year >= startYr && y.year <= endYr) + .reduce((acc, curr) => acc + (curr.raw || 0), 0); + if (sumRaw > 0) return false; + } + } } return true; } @@ -47,10 +74,13 @@ export function findFirstNonEmptyTopic( seriesList: TrendSeries[], startYr: number, endYr: number, + getMappedTopicFn?: (topic: string) => string, ): string { if (!topics || topics.length === 0) return ''; for (const t of topics) { - if (!isTopicEmptyForSeries(t, seriesList, startYr, endYr)) { + if ( + !isTopicEmptyForSeries(t, seriesList, startYr, endYr, getMappedTopicFn) + ) { return t; } } diff --git a/webapp/src/app/resolvers/uni-trend.resolver.ts b/webapp/src/app/resolvers/uni-trend.resolver.ts index 60e54789..887f1bae 100644 --- a/webapp/src/app/resolvers/uni-trend.resolver.ts +++ b/webapp/src/app/resolvers/uni-trend.resolver.ts @@ -1,6 +1,6 @@ import { inject } from '@angular/core'; import { ResolveFn } from '@angular/router'; -import { catchError, of, Observable, map, forkJoin } from 'rxjs'; +import { catchError, of, Observable, map, forkJoin, switchMap } from 'rxjs'; import { TrendResponse, UniversityRankingsService, @@ -142,13 +142,6 @@ export const uniTrendResolver: ResolveFn = ( return { id: cleanId, name: parts[1] || parts[0] }; }); - const instIds = - parsedInstitutions.length > 0 - ? parsedInstitutions.map((i) => i.id) - : [primaryInstId]; - const countryIds = parsedCountries.map((c) => c.id); - const regionIds = parsedRegions.map((r) => r.id); - const authorIds = parsedAuthors.map((a) => a.id); const apiService = inject(UniversityRankingsService); const errorService = inject(ErrorService); const personsService = inject(PersonsService, { optional: true }); @@ -159,148 +152,179 @@ export const uniTrendResolver: ResolveFn = ( const regionFilter = parsedRegions.length > 0 ? parsedRegions[0].id : undefined; - const currentParams: TrendRequestParams = { - topics, - keywords, - fuzzy, - institutions: instIds, - countries: countryIds, - regions: regionIds, - authors: authorIds, - searchType, + const fetchTrendAndSuggestions = ( + authors: CompareItem[], + ): Observable => { + const instIds = + parsedInstitutions.length > 0 + ? parsedInstitutions.map((i) => i.id) + : [primaryInstId]; + const countryIds = parsedCountries.map((c) => c.id); + const regionIds = parsedRegions.map((r) => r.id); + const authorIds = authors.map((a) => a.id); + + const currentParams: TrendRequestParams = { + topics, + keywords, + fuzzy, + institutions: instIds, + countries: countryIds, + regions: regionIds, + authors: authorIds, + searchType, + }; + + let trendObs$: Observable; + if (trendDataService.canReuseCache(currentParams)) { + trendObs$ = of(trendDataService.getCachedResponse(currentParams)); + } else { + trendObs$ = apiService + .getTrendApiInseServiceUniversityRankingsTrendGet( + topics, + keywords, + fuzzy, + instIds, + countryIds, + regionIds, + authorIds, + searchType as any, + ) + .pipe( + map((res) => { + trendDataService.updateCache(res, currentParams); + return res; + }), + catchError((err) => { + errorService.setError({ + statusCode: err?.status || 500, + title: 'Visualisierungs-Fehler', + message: 'Trenddaten konnten nicht geladen werden.', + errorDetails: err?.message || String(err), + }); + return of(null); + }), + ); + } + + const topInstObs$ = + searchType !== 'authors' + ? apiService + .getTopInstitutionsApiInseServiceUniversityRankingsTopInstitutionsGet( + primaryTopic, + regionFilter, + countryFilter, + 6, + ) + .pipe(catchError(() => of([]))) + : of([]); + + const recAuthorsObs$ = + searchType === 'authors' && personsService + ? personsService + .searchPersonsList( + undefined, + primaryInstId, + 'cited_by_count', + 'desc', + [primaryTopic], + 1, + 6, + undefined, + ) + .pipe( + map((res: any) => res.results || []), + catchError(() => of([])), + ) + : of([]); + + return forkJoin({ + trendResponse: trendObs$, + topSuggestions: topInstObs$, + recommendedAuthors: recAuthorsObs$, + }).pipe( + map(({ trendResponse, topSuggestions, recommendedAuthors }) => { + let initialActiveTopic = primaryTopic; + if ( + trendResponse?.series && + trendResponse.series.length > 0 && + topics.length > 0 + ) { + const nonEmptyTopic = topics.find((t) => + trendResponse.series.some((s) => { + if (!s.topic_data) return false; + const tLower = t.toLowerCase().trim(); + const matchingKey = Object.keys(s.topic_data).find((key) => { + const kLower = key.toLowerCase().trim(); + return ( + kLower === tLower || + (kLower.startsWith('news_topic_') && + kLower.slice('news_topic_'.length) === tLower) + ); + }); + if (!matchingKey) return false; + const yearlyList = s.topic_data[matchingKey]; + if (!yearlyList || !Array.isArray(yearlyList)) return false; + const total = yearlyList.reduce( + (sum, item) => sum + (item.raw || 0), + 0, + ); + return total > 0; + }), + ); + if (nonEmptyTopic) { + initialActiveTopic = nonEmptyTopic; + } + } + + return { + trendResponse, + searchType, + topics, + keywords, + fuzzy, + institutions: parsedInstitutions, + countries: parsedCountries, + regions: parsedRegions, + authors, + initialActiveTopic, + topSuggestions: topSuggestions as any[], + recommendedAuthors: recommendedAuthors as any[], + treemapNode, + }; + }), + ); }; - // Check exact parameter keyed cache - let trendObs$: Observable; - if (trendDataService.canReuseCache(currentParams)) { - trendObs$ = of(trendDataService.getCachedResponse(currentParams)); - } else { - trendObs$ = apiService - .getTrendApiInseServiceUniversityRankingsTrendGet( - topics, - keywords, - fuzzy, - instIds, - countryIds, - regionIds, - authorIds, - searchType as any, + if ( + searchType === 'authors' && + parsedAuthors.length === 0 && + personsService + ) { + return personsService + .searchPersonsList( + undefined, + primaryInstId, + 'cited_by_count', + 'desc', + [primaryTopic], + 1, + 6, + undefined, ) .pipe( - map((res) => { - trendDataService.updateCache(res, currentParams); - return res; - }), - catchError((err) => { - errorService.setError({ - statusCode: err?.status || 500, - title: 'Visualisierungs-Fehler', - message: 'Trenddaten konnten nicht geladen werden.', - errorDetails: err?.message || String(err), - }); - return of(null); + map((res: any) => res.results || []), + catchError(() => of([])), + switchMap((recAuthors) => { + const defaultAuthors: CompareItem[] = recAuthors + .slice(0, 3) + .map((author: any) => ({ + id: cleanEntityId(author.id), + name: author.display_name || 'Unbekannt', + })); + return fetchTrendAndSuggestions(defaultAuthors); }), ); } - const topInstObs$ = - searchType !== 'authors' - ? apiService - .getTopInstitutionsApiInseServiceUniversityRankingsTopInstitutionsGet( - primaryTopic, - regionFilter, - countryFilter, - 6, - ) - .pipe(catchError(() => of([]))) - : of([]); - - const recAuthorsObs$ = - searchType === 'authors' && personsService - ? personsService - .searchPersonsList( - undefined, - primaryInstId, - 'cited_by_count', - 'desc', - [primaryTopic], - 1, - 6, - undefined, - ) - .pipe( - map((res: any) => res.results || []), - catchError(() => of([])), - ) - : of([]); - - return forkJoin({ - trendResponse: trendObs$, - topSuggestions: topInstObs$, - recommendedAuthors: recAuthorsObs$, - }).pipe( - map(({ trendResponse, topSuggestions, recommendedAuthors }) => { - let initialActiveTopic = primaryTopic; - if ( - trendResponse?.series && - trendResponse.series.length > 0 && - topics.length > 0 - ) { - const nonEmptyTopic = topics.find((t) => - trendResponse.series.some((s) => { - if (!s.topic_data) return false; - const tLower = t.toLowerCase().trim(); - const matchingKey = Object.keys(s.topic_data).find((key) => { - const kLower = key.toLowerCase().trim(); - return ( - kLower === tLower || - (kLower.startsWith('news_topic_') && - kLower.slice('news_topic_'.length) === tLower) - ); - }); - if (!matchingKey) return false; - const yearlyList = s.topic_data[matchingKey]; - if (!yearlyList || !Array.isArray(yearlyList)) return false; - const total = yearlyList.reduce( - (sum, item) => sum + (item.raw || 0), - 0, - ); - return total > 0; - }), - ); - if (nonEmptyTopic) { - initialActiveTopic = nonEmptyTopic; - } - } - - if ( - searchType === 'authors' && - parsedAuthors.length === 0 && - recommendedAuthors?.length - ) { - recommendedAuthors.slice(0, 3).forEach((author: any) => { - parsedAuthors.push({ - id: cleanEntityId(author.id), - name: author.display_name || 'Unbekannt', - }); - }); - } - - return { - trendResponse, - searchType, - topics, - keywords, - fuzzy, - institutions: parsedInstitutions, - countries: parsedCountries, - regions: parsedRegions, - authors: parsedAuthors, - initialActiveTopic, - topSuggestions: topSuggestions as any[], - recommendedAuthors: recommendedAuthors as any[], - treemapNode, - }; - }), - ); + return fetchTrendAndSuggestions(parsedAuthors); }; From d48435b948f794468480eeda3c3278f19b44186b Mon Sep 17 00:00:00 2001 From: Farajollahi Date: Thu, 6 Aug 2026 18:12:38 +0200 Subject: [PATCH 069/114] fix bug --- service/src/main/inse/dashboard/service.py | 26 +++++++++++++++++-- .../src/main/inse/dashboard/test_service.py | 14 +++++++--- 2 files changed, 35 insertions(+), 5 deletions(-) diff --git a/service/src/main/inse/dashboard/service.py b/service/src/main/inse/dashboard/service.py index babb8b5b..77b7db85 100644 --- a/service/src/main/inse/dashboard/service.py +++ b/service/src/main/inse/dashboard/service.py @@ -1192,7 +1192,7 @@ async def get_top_authors( authors = await _safe_institution_authors(normalized_id) works = await _safe_top_authors( "works", - _top_work_authors(normalized_id, period), + _top_work_authors(normalized_id, period, authors), ) projects = await _safe_top_authors( "projects", @@ -1608,7 +1608,16 @@ def _short_author_id(value: str) -> str: async def _top_work_authors( institution_id: str, period: DashboardPeriod, + institution_authors: list[dict[str, Any]], ) -> list[TopAuthor]: + institution_author_ids = { + _short_author_id(str(author["id"])) + for author in institution_authors + if author.get("id") + } + if not institution_author_ids: + return [] + must = [works_v2_service._institutions_nested_query([institution_id])] if publication_years := _dashboard_publication_years(period): must.append({"terms": {"publication_year": publication_years}}) @@ -1618,17 +1627,30 @@ async def _top_work_authors( async for hit in elasticsearch.scan( index=str(ESIndex.OPENALEX_WORKS_WILDCARD), query={"bool": {"must": must}}, - source=["id", "authorships.author.id", "authorships.author.display_name"], + source=[ + "id", + "authorships.author.id", + "authorships.author.display_name", + "authorships.institutions.id", + ], page_size=1000, cluster=ESCluster.NES, ): hit_author_ids: set[str] = set() for authorship in hit.get("_source", {}).get("authorships", []): + if not any( + _normalize_institution_id(institution.get("id")) == institution_id + for institution in authorship.get("institutions") or [] + if institution.get("id") + ): + continue author = authorship.get("author") or {} author_id = author.get("id") if not author_id: continue author_id = str(author_id) + if _short_author_id(author_id) not in institution_author_ids: + continue hit_author_ids.add(author_id) if author.get("display_name"): author_names.setdefault(author_id, str(author["display_name"])) diff --git a/service/src/main/inse/dashboard/test_service.py b/service/src/main/inse/dashboard/test_service.py index 1429e267..f845ad2e 100644 --- a/service/src/main/inse/dashboard/test_service.py +++ b/service/src/main/inse/dashboard/test_service.py @@ -469,12 +469,14 @@ async def test_top_authors_maps_works_patents_news_and_eu_projects(): "id": "https://openalex.org/A1", "display_name": "Ada Example", }, + "institutions": [{"id": ORG_INSTITUTION_ID}], }, { "author": { "id": "https://openalex.org/A2", "display_name": "Grace Example", }, + "institutions": [{"id": "https://openalex.org/I999"}], }, ], }, @@ -489,6 +491,7 @@ async def test_top_authors_maps_works_patents_news_and_eu_projects(): "id": "https://openalex.org/A1", "display_name": "Ada Example", }, + "institutions": [{"id": ORG_INSTITUTION_ID}], } ], }, @@ -543,6 +546,7 @@ async def test_top_authors_maps_works_patents_news_and_eu_projects(): "name": "Ada Example", "count": 2, } + assert len(result.works) == 1 assert result.patents[0].model_dump() == { "id": "A1", "name": "Ada Example", @@ -605,6 +609,7 @@ async def test_top_authors_maps_works_patents_news_and_eu_projects(): "id", "authorships.author.id", "authorships.author.display_name", + "authorships.institutions.id", ] eu_work_calls = [ @@ -907,7 +912,8 @@ async def test_top_authors_returns_partial_response_when_one_source_fails(): "author": { "id": "https://openalex.org/A1", "display_name": "Ada Example", - } + }, + "institutions": [{"id": ORG_INSTITUTION_ID}], } ], }, @@ -995,7 +1001,8 @@ async def test_top_authors_can_rank_works_by_last_five_years(): "author": { "id": "https://openalex.org/A2", "display_name": "Grace Example", - } + }, + "institutions": [{"id": ORG_INSTITUTION_ID}], } ] }, @@ -1009,7 +1016,8 @@ async def test_top_authors_can_rank_works_by_last_five_years(): "author": { "id": "https://openalex.org/A1", "display_name": "Ada Example", - } + }, + "institutions": [{"id": ORG_INSTITUTION_ID}], } ] }, From aed1f33935fd285e5d0d053ae6bba5f036de969c Mon Sep 17 00:00:00 2001 From: Farajollahi Date: Thu, 6 Aug 2026 18:31:52 +0200 Subject: [PATCH 070/114] Keep check-dashboard publication count after timeline merge --- service/src/main/inse/dashboard/service.py | 36 +++++++++----- .../src/main/inse/dashboard/test_service.py | 47 +++++++------------ 2 files changed, 40 insertions(+), 43 deletions(-) diff --git a/service/src/main/inse/dashboard/service.py b/service/src/main/inse/dashboard/service.py index 99878d13..640cfb7b 100644 --- a/service/src/main/inse/dashboard/service.py +++ b/service/src/main/inse/dashboard/service.py @@ -266,24 +266,36 @@ async def get_dashboard_publications( ) -> DashboardStatisticValue: normalized_id = _normalize_institution_id(institution_id) period = _dashboard_period(from_year, to_year) - must = [ - works_v2_service._institutions_nested_query([normalized_id]), - ] - if publication_years := _dashboard_publication_years(period): - must.append({"terms": {"publication_year": publication_years}}) - response = await elasticsearch.search( + if period == (None, None): + institution = await institutions_v2_service.get_institution_by_id_or_raise( + raw_oa_institution_id=_raw_institution_id(normalized_id), + source=["id", "works_count"], + ) + return DashboardStatisticValue( + institution_id=normalized_id, + organization_name=organization_name, + value=int(institution.works_count or 0), + ) + + first_year = period[0] if period[0] is not None else 1900 + last_year = period[1] if period[1] is not None else 2100 + publication_years = list(range(first_year, last_year + 1)) + + value = await elasticsearch.count( index=ESIndex.OPENALEX_WORKS_WILDCARD, - body={ - "size": 0, - "track_total_hits": True, - "query": {"bool": {"must": must}}, + query={ + "bool": { + "filter": [ + works_v2_service._institutions_nested_query([normalized_id]), + {"terms": {"publication_year": publication_years}}, + ] + } }, - cluster=ESCluster.NES, ) return DashboardStatisticValue( institution_id=normalized_id, organization_name=organization_name, - value=_total(response), + value=value, ) diff --git a/service/src/main/inse/dashboard/test_service.py b/service/src/main/inse/dashboard/test_service.py index 7ccee4b4..049a488c 100644 --- a/service/src/main/inse/dashboard/test_service.py +++ b/service/src/main/inse/dashboard/test_service.py @@ -41,6 +41,7 @@ from inse.projects.model import ( EuCordisProjectSummary, EuCordisProjectType, ) +from inse.works.v2 import service as works_v2_service ORG_INSTITUTION_ID = "https://openalex.org/I123" @@ -409,16 +410,16 @@ async def test_dashboard_statistics_counts_organization_data_and_all_projects(): } @pytest.mark.anyio -async def test_dashboard_publications_counts_matching_openalex_works(): +async def test_dashboard_publications_uses_exact_es_count_for_period(): with patch( - "inse.dashboard.service.elasticsearch.search", + "inse.dashboard.service.institutions_v2_service.get_institution_by_id_or_raise", new=AsyncMock( - side_effect=[ - {"hits": {"total": {"value": 250}}}, - {"hits": {"total": {"value": 22}}}, - ] + return_value=Institution(id=ORG_INSTITUTION_ID, works_count=250) ), - ) as mocked_search: + ) as mocked_get_institution, patch( + "inse.dashboard.service.elasticsearch.count", + new=AsyncMock(return_value=22), + ) as mocked_count: all_time = await get_dashboard_publications( ORG_INSTITUTION_ID, "Example Org", @@ -432,31 +433,15 @@ async def test_dashboard_publications_counts_matching_openalex_works(): assert all_time.value == 250 assert selected_period.value == 22 - all_time_body = mocked_search.await_args_list[0].kwargs["body"] - selected_period_body = mocked_search.await_args_list[1].kwargs["body"] - assert mocked_search.await_args_list[0].kwargs["index"] == ( - ESIndex.OPENALEX_WORKS_WILDCARD + mocked_get_institution.assert_awaited_once_with( + raw_oa_institution_id="I123", + source=["id", "works_count"], ) - assert all_time_body["track_total_hits"] is True - assert all_time_body["query"]["bool"]["must"] == [ - { - "nested": { - "path": "authorships", - "query": { - "nested": { - "path": "authorships.institutions", - "query": { - "terms": { - "authorships.institutions.id": [ORG_INSTITUTION_ID] - } - }, - } - }, - } - } - ] - assert selected_period_body["query"]["bool"]["must"] == [ - all_time_body["query"]["bool"]["must"][0], + mocked_count.assert_awaited_once() + count_call = mocked_count.await_args.kwargs + assert count_call["index"] == ESIndex.OPENALEX_WORKS_WILDCARD + assert count_call["query"]["bool"]["filter"] == [ + works_v2_service._institutions_nested_query([ORG_INSTITUTION_ID]), {"terms": {"publication_year": [2021, 2022]}}, ] From bfb3224684efb203bb14d94526e15e541f34e3a9 Mon Sep 17 00:00:00 2001 From: Farajollahi Date: Thu, 6 Aug 2026 18:38:35 +0200 Subject: [PATCH 071/114] Revert "fix bug" This reverts commit d48435b948f794468480eeda3c3278f19b44186b. --- service/src/main/inse/dashboard/service.py | 26 ++----------------- .../src/main/inse/dashboard/test_service.py | 14 +++------- 2 files changed, 5 insertions(+), 35 deletions(-) diff --git a/service/src/main/inse/dashboard/service.py b/service/src/main/inse/dashboard/service.py index 640cfb7b..c1f55565 100644 --- a/service/src/main/inse/dashboard/service.py +++ b/service/src/main/inse/dashboard/service.py @@ -1454,7 +1454,7 @@ async def get_top_authors( authors = await _safe_institution_authors(normalized_id) works = await _safe_top_authors( "works", - _top_work_authors(normalized_id, period, authors), + _top_work_authors(normalized_id, period), ) projects = await _safe_top_authors( "projects", @@ -1874,16 +1874,7 @@ def _short_author_id(value: str) -> str: async def _top_work_authors( institution_id: str, period: DashboardPeriod, - institution_authors: list[dict[str, Any]], ) -> list[TopAuthor]: - institution_author_ids = { - _short_author_id(str(author["id"])) - for author in institution_authors - if author.get("id") - } - if not institution_author_ids: - return [] - must = [works_v2_service._institutions_nested_query([institution_id])] if publication_years := _dashboard_publication_years(period): must.append({"terms": {"publication_year": publication_years}}) @@ -1893,30 +1884,17 @@ async def _top_work_authors( async for hit in elasticsearch.scan( index=str(ESIndex.OPENALEX_WORKS_WILDCARD), query={"bool": {"must": must}}, - source=[ - "id", - "authorships.author.id", - "authorships.author.display_name", - "authorships.institutions.id", - ], + source=["id", "authorships.author.id", "authorships.author.display_name"], page_size=1000, cluster=ESCluster.NES, ): hit_author_ids: set[str] = set() for authorship in hit.get("_source", {}).get("authorships", []): - if not any( - _normalize_institution_id(institution.get("id")) == institution_id - for institution in authorship.get("institutions") or [] - if institution.get("id") - ): - continue author = authorship.get("author") or {} author_id = author.get("id") if not author_id: continue author_id = str(author_id) - if _short_author_id(author_id) not in institution_author_ids: - continue hit_author_ids.add(author_id) if author.get("display_name"): author_names.setdefault(author_id, str(author["display_name"])) diff --git a/service/src/main/inse/dashboard/test_service.py b/service/src/main/inse/dashboard/test_service.py index 049a488c..85cc9c1a 100644 --- a/service/src/main/inse/dashboard/test_service.py +++ b/service/src/main/inse/dashboard/test_service.py @@ -683,14 +683,12 @@ async def test_top_authors_maps_works_patents_news_and_eu_projects(): "id": "https://openalex.org/A1", "display_name": "Ada Example", }, - "institutions": [{"id": ORG_INSTITUTION_ID}], }, { "author": { "id": "https://openalex.org/A2", "display_name": "Grace Example", }, - "institutions": [{"id": "https://openalex.org/I999"}], }, ], }, @@ -705,7 +703,6 @@ async def test_top_authors_maps_works_patents_news_and_eu_projects(): "id": "https://openalex.org/A1", "display_name": "Ada Example", }, - "institutions": [{"id": ORG_INSTITUTION_ID}], } ], }, @@ -760,7 +757,6 @@ async def test_top_authors_maps_works_patents_news_and_eu_projects(): "name": "Ada Example", "count": 2, } - assert len(result.works) == 1 assert result.patents[0].model_dump() == { "id": "A1", "name": "Ada Example", @@ -823,7 +819,6 @@ async def test_top_authors_maps_works_patents_news_and_eu_projects(): "id", "authorships.author.id", "authorships.author.display_name", - "authorships.institutions.id", ] eu_work_calls = [ @@ -1132,8 +1127,7 @@ async def test_top_authors_returns_partial_response_when_one_source_fails(): "author": { "id": "https://openalex.org/A1", "display_name": "Ada Example", - }, - "institutions": [{"id": ORG_INSTITUTION_ID}], + } } ], }, @@ -1221,8 +1215,7 @@ async def test_top_authors_can_rank_works_by_last_five_years(): "author": { "id": "https://openalex.org/A2", "display_name": "Grace Example", - }, - "institutions": [{"id": ORG_INSTITUTION_ID}], + } } ] }, @@ -1236,8 +1229,7 @@ async def test_top_authors_can_rank_works_by_last_five_years(): "author": { "id": "https://openalex.org/A1", "display_name": "Ada Example", - }, - "institutions": [{"id": ORG_INSTITUTION_ID}], + } } ] }, From 37e1f1811fcf226b98c13593a8d7ae93ce6ca294 Mon Sep 17 00:00:00 2001 From: genja Date: Mon, 10 Aug 2026 13:41:21 +0200 Subject: [PATCH 072/114] fixed wrong projects number displaying --- service/src/main/inse/projects/projects_search_client.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/service/src/main/inse/projects/projects_search_client.py b/service/src/main/inse/projects/projects_search_client.py index f3b2f1e2..454622aa 100644 --- a/service/src/main/inse/projects/projects_search_client.py +++ b/service/src/main/inse/projects/projects_search_client.py @@ -1151,11 +1151,13 @@ async def search_all_projects( page = projects_filtering_properties.page offset = page * size response = await elasticsearch.search( + index=index, size=size, offset=offset, query=query, sort=sort, + track_total_hits=True, ) return _response_to_funding_project_page(response=response, page=page, size=size) From 0015b9259147b138d8fe98f70da6678c172b689c Mon Sep 17 00:00:00 2001 From: genja Date: Mon, 10 Aug 2026 13:41:51 +0200 Subject: [PATCH 073/114] added all affiliations for 403 check at projects component --- service/src/main/inse/projects/logic.py | 9 +++++---- service/src/main/inse/projects/router.py | 1 - 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/service/src/main/inse/projects/logic.py b/service/src/main/inse/projects/logic.py index 5683280a..d224fc7f 100644 --- a/service/src/main/inse/projects/logic.py +++ b/service/src/main/inse/projects/logic.py @@ -36,10 +36,11 @@ async def is_projects_access_forbidden( authors_profile = await author_service.get_author_by_id(raw_oa_author_id) if not authors_profile: return True # Author not found, access forbidden - - authors_last_known_institution_ids = [inst.id.split("/")[-1] for inst in authors_profile.last_known_institutions] - print(f"Author's last known institution IDs: {authors_last_known_institution_ids}") - if effective_institution_id not in authors_last_known_institution_ids: + + authors_last_known_institution_ids = [inst.id.split("/")[-1] for inst in (authors_profile.last_known_institutions)] + authors_affiliation_institution_ids = [aff.institution.id.split("/")[-1] for aff in (authors_profile.affiliations)] + print(f"Author's last known institution IDs: {authors_last_known_institution_ids}, {authors_affiliation_institution_ids}") + if effective_institution_id not in authors_last_known_institution_ids and effective_institution_id not in authors_affiliation_institution_ids: return True # Effective institution ID does not match any of the author's last known institutions return False diff --git a/service/src/main/inse/projects/router.py b/service/src/main/inse/projects/router.py index 6382f575..d0430d63 100644 --- a/service/src/main/inse/projects/router.py +++ b/service/src/main/inse/projects/router.py @@ -273,7 +273,6 @@ async def search_bund_projects( detail="Access denied for the provided author ID or institution ID", ) return await projects_service.search_bund_projects_with_filters( - access_token_metadata=access_token_metadata, institutions_search_client=institutions_search_client, executing_agency=executing_agency, funding_arts=funding_arts, From f51b775fd99bb40ea28a3f888b06494bcc573cf9 Mon Sep 17 00:00:00 2001 From: genja Date: Mon, 10 Aug 2026 13:43:02 +0200 Subject: [PATCH 074/114] fixed skeleton for persons list while resolving --- .../custom-directives/sk-text.directive.ts | 116 ++++++++++-------- webapp/src/styles.scss | 47 ++++++- 2 files changed, 104 insertions(+), 59 deletions(-) diff --git a/webapp/src/app/custom-directives/sk-text.directive.ts b/webapp/src/app/custom-directives/sk-text.directive.ts index e7173238..14246539 100644 --- a/webapp/src/app/custom-directives/sk-text.directive.ts +++ b/webapp/src/app/custom-directives/sk-text.directive.ts @@ -1,76 +1,84 @@ import { Directive, - OnChanges, - Input, ElementRef, + Input, + OnChanges, Renderer2, + SimpleChanges, + effect, + inject, } from '@angular/core'; -import { SimpleChanges } from '@angular/core'; -@Directive({ selector: '[skText]', standalone: true }) +import { ResolverStateService } from '../../app/shared/services/resolver-state.service'; + +@Directive({ + selector: 'span, [skText]', + standalone: true, +}) export class SkTextDirective implements OnChanges { + /** + * Optional manual loading state. + * The directive also reacts to global route/resolver loading. + */ @Input() skText = false; - private originalText = ''; - private originalColor = ''; + private readonly el = inject(ElementRef); + private readonly renderer = inject(Renderer2); + private readonly resolverStateService = inject(ResolverStateService); - constructor( - private el: ElementRef, - private renderer: Renderer2, - ) {} + constructor() { + effect(() => { + const loading = this.skText || this.resolverStateService.isResolving(); - ngOnChanges(changes: SimpleChanges) { - const change = changes['skText']; - - // skip if value didn't actually change, or is undefined - if (!change) return; - - this.skText ? this.showSkeleton() : this.hideSkeleton(); + if (loading) { + this.showSkeleton(); + } else { + this.hideSkeleton(); + } + }); } - private showSkeleton() { - const el: HTMLElement = this.el.nativeElement; - this.originalText = el.textContent ?? ''; - this.originalColor = el.style.color; + ngOnChanges(changes: SimpleChanges): void { + if (!changes['skText']) { + return; + } - // measure natural width before blanking text - const width = Math.min(Math.max(this.originalText.length * 7.5, 48), 60); - const height = 20; - this.renderer.addClass(el, 'sk-text-loading'); - this.renderer.setStyle(el, 'color', 'transparent'); - this.renderer.setStyle( - el, - 'background', - 'linear-gradient(90deg, #e2e8f0 25%, #f8fafc 50%, #e2e8f0 75%)', - ); - this.renderer.setStyle(el, 'background-size', '600px 100%'); - this.renderer.setStyle(el, 'animation', 'sk-shimmer 1.6s infinite linear'); - this.renderer.setStyle(el, 'border-radius', '4px'); - this.renderer.setStyle(el, 'min-width', `${width}px`); - this.renderer.setStyle(el, 'max-height', `${height}px`); - this.renderer.setStyle(el, 'display', 'inline-block'); - this.renderer.setStyle(el, 'overflow', 'hidden'); - this.renderer.setStyle(el, 'pointer-events', 'none'); + if (this.skText || this.resolverStateService.isResolving()) { + this.showSkeleton(); + } else { + this.hideSkeleton(); + } + } - Array.from(el.children).forEach((child) => { + private showSkeleton(): void { + const element = this.el.nativeElement; + + if (element.classList.contains('sk-text-loading')) { + return; + } + + const text = element.textContent?.trim() ?? ''; + + // For ordinary text elements only. Table cells use CSS width naturally. + if (element.tagName.toLowerCase() !== 'td') { + this.renderer.setStyle(element, 'min-width', `${20}px`); + this.renderer.setStyle(element, 'height', '20px'); + } + + this.renderer.addClass(element, 'sk-text-loading'); + + Array.from(element.children).forEach((child) => { this.renderer.setStyle(child, 'visibility', 'hidden'); }); } - private hideSkeleton() { - const el: HTMLElement = this.el.nativeElement; - this.renderer.removeClass(el, 'sk-text-loading'); - this.renderer.removeStyle(el, 'color'); - this.renderer.removeStyle(el, 'background'); - this.renderer.removeStyle(el, 'background-size'); - this.renderer.removeStyle(el, 'animation'); - this.renderer.removeStyle(el, 'border-radius'); - this.renderer.removeStyle(el, 'min-width'); - this.renderer.removeStyle(el, 'max-height'); - this.renderer.removeStyle(el, 'display'); - this.renderer.removeStyle(el, 'overflow'); - this.renderer.removeStyle(el, 'pointer-events'); + private hideSkeleton(): void { + const element = this.el.nativeElement; - Array.from(el.children).forEach((child) => { + this.renderer.removeClass(element, 'sk-text-loading'); + this.renderer.removeStyle(element, 'min-width'); + this.renderer.removeStyle(element, 'height'); + + Array.from(element.children).forEach((child) => { this.renderer.removeStyle(child, 'visibility'); }); } diff --git a/webapp/src/styles.scss b/webapp/src/styles.scss index 95a45697..69543f81 100644 --- a/webapp/src/styles.scss +++ b/webapp/src/styles.scss @@ -104,6 +104,7 @@ body { /* Centralized Design Tokens (Semantic CSS Custom Properties) */ :root { /* Light Theme Palette */ + --sg-background: #ffffff; --sg-surface: #ffffff; --sg-surface-muted: #f7f9ff; @@ -146,7 +147,9 @@ body { --sg-banner-warning-text: #9a3412; --sg-option-hover: rgba(0, 0, 0, 0.04); --sg-avatar-gradient: linear-gradient(135deg, #dce8ff, #ffffff); - + /* Skeleton loading */ + --sg-skeleton-base: #e5ebf5; + --sg-skeleton-highlight: #f7f9ff; @include mat.button-toggle-overrides( ( shape: var(--sg-radius-sm), @@ -263,6 +266,9 @@ html.dark-theme { --sg-banner-warning-text: #ffb74d; --sg-option-hover: rgba(255, 255, 255, 0.06); --sg-avatar-gradient: linear-gradient(135deg, #1c2a4a, #131b2e); + /* Skeleton loading */ + --sg-skeleton-base: #202d49; + --sg-skeleton-highlight: #2b3b5d; } /* Theme-Based Scrollbars (W3C Standard & WebKit Engine) */ @@ -462,16 +468,47 @@ html.dark-theme { --mat-icon-button-icon-color: #ffffff; } +/* Theme-aware text skeleton */ +.sk-text-loading { + display: inline-block; + overflow: hidden; + min-height: 1em; + color: transparent !important; + pointer-events: none; + user-select: none; + border-radius: 4px; + vertical-align: middle; + + background: linear-gradient( + 90deg, + var(--sg-skeleton-base) 25%, + var(--sg-skeleton-highlight) 50%, + var(--sg-skeleton-base) 75% + ); + background-size: 600px 100%; + animation: sk-shimmer 1.6s infinite linear; +} + +.sk-text-loading > * { + visibility: hidden; +} + @keyframes sk-shimmer { - 0% { + from { background-position: -600px 0; } - 100% { + + to { background-position: 600px 0; } } -.cdk-overlay-pane { - color: var(--sg-text); + +/* Do not animate for users who request reduced motion */ +@media (prefers-reduced-motion: reduce) { + .sk-text-loading { + animation: none; + background: var(--sg-skeleton-base); + } } .topic-chip-tooltip, From 127f5ca28708798dabf125a34d18ec49caee0d64 Mon Sep 17 00:00:00 2001 From: genja Date: Mon, 10 Aug 2026 13:45:59 +0200 Subject: [PATCH 075/114] added skeleton loading for projects data table --- .../custom-directives/sk-text.directive.ts | 4 --- .../app-author-chip.component.ts | 9 ++++-- .../app-topic-chip.component.ts | 9 ++++-- .../bund-project-table.component.html | 30 ++++++++----------- .../bund-project-table.component.ts | 2 ++ .../ui/data-table/data-table.component.html | 2 +- .../ui/data-table/data-table.component.ts | 4 +-- .../dfg-project-table.component.html | 12 ++++---- .../dfg-project-table.component.ts | 2 ++ .../eu-project-table.component.html | 10 ++++--- .../eu-project-table.component.ts | 3 +- 11 files changed, 48 insertions(+), 39 deletions(-) diff --git a/webapp/src/app/custom-directives/sk-text.directive.ts b/webapp/src/app/custom-directives/sk-text.directive.ts index 14246539..07ef9d17 100644 --- a/webapp/src/app/custom-directives/sk-text.directive.ts +++ b/webapp/src/app/custom-directives/sk-text.directive.ts @@ -15,10 +15,6 @@ import { ResolverStateService } from '../../app/shared/services/resolver-state.s standalone: true, }) export class SkTextDirective implements OnChanges { - /** - * Optional manual loading state. - * The directive also reacts to global route/resolver loading. - */ @Input() skText = false; private readonly el = inject(ElementRef); diff --git a/webapp/src/app/shared/ui/app-author-chip/app-author-chip.component.ts b/webapp/src/app/shared/ui/app-author-chip/app-author-chip.component.ts index 60995687..58b4af86 100644 --- a/webapp/src/app/shared/ui/app-author-chip/app-author-chip.component.ts +++ b/webapp/src/app/shared/ui/app-author-chip/app-author-chip.component.ts @@ -12,7 +12,7 @@ import { AppAuthorTooltipComponent } from '../app-author-tooltip/app-author-tool import { MatIconModule } from '@angular/material/icon'; import { ComponentTooltipDirective } from '../../../directives/component-tooltip.directive'; import { MatChipsModule } from '@angular/material/chips'; - +import { SkTextDirective } from '../../../custom-directives/sk-text.directive'; @Component({ host: { '[style.--border-width]': 'isSelected() ? "2px" : "1px"', @@ -22,7 +22,12 @@ import { MatChipsModule } from '@angular/material/chips'; '[class.is-mini-size]': 'isMiniSize()', }, selector: 'app-author-chip', - imports: [MatIconModule, MatChipsModule, ComponentTooltipDirective], + imports: [ + MatIconModule, + MatChipsModule, + ComponentTooltipDirective, + SkTextDirective, + ], templateUrl: './app-author-chip.component.html', styleUrl: './app-author-chip.component.scss', }) diff --git a/webapp/src/app/shared/ui/app-topic-chip/app-topic-chip.component.ts b/webapp/src/app/shared/ui/app-topic-chip/app-topic-chip.component.ts index d0859901..51d5f3ca 100644 --- a/webapp/src/app/shared/ui/app-topic-chip/app-topic-chip.component.ts +++ b/webapp/src/app/shared/ui/app-topic-chip/app-topic-chip.component.ts @@ -13,7 +13,7 @@ import { ComponentTooltipDirective } from '../../../directives/component-tooltip import { topicHierarchyColor } from '../../../resolvers/utils/topic-colors'; import { MatIconModule } from '@angular/material/icon'; import { AppTopicTooltipComponent } from '../app-topic-tooltip/app-topic-tooltip.component'; - +import { SkTextDirective } from '../../../custom-directives/sk-text.directive'; @Component({ host: { '[style.--topic-color]': 'color()', @@ -23,7 +23,12 @@ import { AppTopicTooltipComponent } from '../app-topic-tooltip/app-topic-tooltip '[class.is-mini-size]': 'isMiniSize()', }, selector: 'app-topic-chip-2', - imports: [MatChipsModule, ComponentTooltipDirective, MatIconModule], + imports: [ + MatChipsModule, + ComponentTooltipDirective, + MatIconModule, + SkTextDirective, + ], templateUrl: './app-topic-chip.component.html', styleUrl: './app-topic-chip.component.scss', }) diff --git a/webapp/src/app/shared/ui/bund-project-table/bund-project-table.component.html b/webapp/src/app/shared/ui/bund-project-table/bund-project-table.component.html index b078bd8d..93a7982f 100644 --- a/webapp/src/app/shared/ui/bund-project-table/bund-project-table.component.html +++ b/webapp/src/app/shared/ui/bund-project-table/bund-project-table.component.html @@ -11,15 +11,23 @@ [pageSizeOptions]="[10, 25, 50]" /> - {{ getStartDate(element) | date: 'dd.MM.yyyy' }} + + {{ getStartDate(element) | date: 'dd.MM.yyyy' }} + - {{ getEndDate(element) | date: 'dd.MM.yyyy' }} + + {{ getEndDate(element) | date: 'dd.MM.yyyy' }} + - {{ getFundingAmount(element) | currency: 'EUR' : 'symbol' : '1.0-0' : 'de' }} + + {{ + getFundingAmount(element) | currency: 'EUR' : 'symbol' : '1.0-0' : 'de' + }} + @@ -31,20 +39,6 @@ open_in_new - -
    - @for (classification of element.subject_classifications; track $index) { -

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

    - } @empty { - - - } -
    -
    @let institutions = getProjectInstitutions(project); @@ -79,7 +73,7 @@ matTooltipPosition="above" (click)="toggleFundingTypeFilter(project.funding_type)"> - {{ project.funding_type }} + {{ project.funding_type }} } @else { diff --git a/webapp/src/app/shared/ui/bund-project-table/bund-project-table.component.ts b/webapp/src/app/shared/ui/bund-project-table/bund-project-table.component.ts index f5a333e5..46fbbfc9 100644 --- a/webapp/src/app/shared/ui/bund-project-table/bund-project-table.component.ts +++ b/webapp/src/app/shared/ui/bund-project-table/bund-project-table.component.ts @@ -25,6 +25,7 @@ import { ChipComponent } from '../chip/chip.component'; import { MatTooltip } from '@angular/material/tooltip'; import { topicHierarchyColor } from '../../../resolvers/utils/topic-colors'; import { bundProjectQueryParamKeys } from '../../../resolvers/bund-projects.resolver'; +import { SkTextDirective } from '../../../custom-directives/sk-text.directive'; @Component({ selector: 'app-bund-project-table', imports: [ @@ -38,6 +39,7 @@ import { bundProjectQueryParamKeys } from '../../../resolvers/bund-projects.reso DatePipe, ChipComponent, AppTopicChipComponent, + SkTextDirective, ], templateUrl: './bund-project-table.component.html', styleUrl: './bund-project-table.component.scss', diff --git a/webapp/src/app/shared/ui/data-table/data-table.component.html b/webapp/src/app/shared/ui/data-table/data-table.component.html index c7a62547..85b8df3f 100644 --- a/webapp/src/app/shared/ui/data-table/data-table.component.html +++ b/webapp/src/app/shared/ui/data-table/data-table.component.html @@ -30,7 +30,7 @@ context: { $implicit: row } "> } @else if (col.type === 'accessor') { - {{ row[col.accessorKey] }} + {{ row[col.accessorKey] }} } diff --git a/webapp/src/app/shared/ui/data-table/data-table.component.ts b/webapp/src/app/shared/ui/data-table/data-table.component.ts index 6be5c79e..092488b2 100644 --- a/webapp/src/app/shared/ui/data-table/data-table.component.ts +++ b/webapp/src/app/shared/ui/data-table/data-table.component.ts @@ -20,7 +20,7 @@ import { } from '@angular/material/sort'; import { MatTableDataSource, MatTableModule } from '@angular/material/table'; import { ActivatedRoute, Router } from '@angular/router'; - +import { SkTextDirective } from '../../../custom-directives/sk-text.directive'; export interface BaseColumn { id: string; header: string; @@ -43,7 +43,7 @@ export type GenericColumn = AccessorColumn | DisplayColumn; @Component({ selector: 'app-data-table', standalone: true, - imports: [MatTableModule, NgTemplateOutlet, MatSortModule], + imports: [MatTableModule, NgTemplateOutlet, MatSortModule, SkTextDirective], templateUrl: './data-table.component.html', styleUrl: './data-table.component.scss', }) diff --git a/webapp/src/app/shared/ui/dfg-project-table/dfg-project-table.component.html b/webapp/src/app/shared/ui/dfg-project-table/dfg-project-table.component.html index 9c86010c..12376734 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,11 +11,13 @@ [pageSizeOptions]="[10, 25, 50]" /> - {{ - element.funding_end == '2999' || element.funding_end == null - ? 'laufend' - : element.funding_end - }} + + {{ + element.funding_end == '2999' || element.funding_end == null + ? 'laufend' + : element.funding_end + }} 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 baa2ae18..cf1a8819 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 @@ -23,6 +23,7 @@ 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'; +import { SkTextDirective } from '../../../custom-directives/sk-text.directive'; @Component({ selector: 'app-dfg-project-table', imports: [ @@ -33,6 +34,7 @@ import { topicHierarchyColor } from '../../../resolvers/utils/topic-colors'; QueryParamPaginatorComponent, MatTooltip, AppTopicChipComponent, + SkTextDirective, ], templateUrl: './dfg-project-table.component.html', styleUrl: './dfg-project-table.component.scss', diff --git a/webapp/src/app/shared/ui/eu-project-table/eu-project-table.component.html b/webapp/src/app/shared/ui/eu-project-table/eu-project-table.component.html index 68ef7152..00b3ae95 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 @@ -20,7 +20,7 @@ matTooltipPosition="above" (click)="toggleTypeFilter(project.project_type)"> - {{ getProjectTypeLabel(project) }} + {{ getProjectTypeLabel(project) }} } @else { @@ -29,15 +29,17 @@ - {{ getStartDate(element) | date: 'dd.MM.yyyy' }} + {{ getStartDate(element) | date: 'dd.MM.yyyy' }} - {{ getEndDate(element) | date: 'dd.MM.yyyy' }} + {{ getEndDate(element) | date: 'dd.MM.yyyy' }} - {{ getFundingAmount(element) | currency: 'EUR' : 'symbol' : '1.0-0' : 'de' }} + {{ + getFundingAmount(element) | currency: 'EUR' : 'symbol' : '1.0-0' : 'de' + }} 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 0a3fca02..6b752e77 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 @@ -14,7 +14,7 @@ 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 { SkTextDirective } from '../../../custom-directives/sk-text.directive'; import { DataTableComponent, GenericColumn, @@ -46,6 +46,7 @@ import { AppAuthorChipComponent } from '../app-author-chip/app-author-chip.compo AppTopicChipComponent, ChipComponent, AppAuthorChipComponent, + SkTextDirective, ], templateUrl: './eu-project-table.component.html', styleUrl: './eu-project-table.component.scss', From 1e5d0c4517ea30caf35c622e1fabe531990bbc90 Mon Sep 17 00:00:00 2001 From: genja Date: Mon, 10 Aug 2026 13:59:34 +0200 Subject: [PATCH 076/114] enabled ALWAYS tracking total hits to avoid 10000 cuts on data count in elastic client --- service/src/main/inse/integrations/elasticsearch.py | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/service/src/main/inse/integrations/elasticsearch.py b/service/src/main/inse/integrations/elasticsearch.py index c0553de1..b48e6c78 100644 --- a/service/src/main/inse/integrations/elasticsearch.py +++ b/service/src/main/inse/integrations/elasticsearch.py @@ -261,11 +261,10 @@ async def search( payload["sort"] = sort if aggs is not None: payload["aggs"] = aggs - if track_total_hits: - payload["track_total_hits"] = True if highlight is not None: payload["highlight"] = highlight - + + payload["track_total_hits"] = True # always track total hits for accurate pagination and counts if len(payload) == 0: raise ValueError( "At least one of 'query', 'body', 'source', 'size', 'offset', 'sort', 'aggs' must be provided" From af0e326747ad2329cb34ec496844af08f7a83852 Mon Sep 17 00:00:00 2001 From: "noemi.kallweit" Date: Mon, 3 Aug 2026 22:42:33 +0200 Subject: [PATCH 077/114] feat(keyword-search): fill news tab --- service/src/main/inse/news/logic.py | 198 ++ service/src/main/inse/news/model.py | 23 +- service/src/main/inse/news/service.py | 62 + webapp/src/app/api/api/news.service.ts | 2056 ++++++++++++----- webapp/src/app/api/model/dfgProjectTopic.ts | 3 +- webapp/src/app/api/model/newsArticle.ts | 24 +- webapp/src/app/api/model/newsArticleDetail.ts | 30 +- webapp/src/app/app.routes.ts | 10 +- .../news-results/news-results.component.html | 156 +- .../news-results/news-results.component.scss | 190 +- .../news-results/news-results.component.ts | 335 ++- .../resolvers/keywords-news-page.resolver.ts | 76 + 12 files changed, 2456 insertions(+), 707 deletions(-) create mode 100644 webapp/src/app/resolvers/keywords-news-page.resolver.ts diff --git a/service/src/main/inse/news/logic.py b/service/src/main/inse/news/logic.py index 9e07315b..d8570f97 100644 --- a/service/src/main/inse/news/logic.py +++ b/service/src/main/inse/news/logic.py @@ -48,6 +48,10 @@ RELATED_BLOCK_SIZE = 5 RELATED_TOPIC_K = 1 EXACT_ID_CAP = 1000 +KEYWORD_SEARCH_FIELDS = ["maintitle^3", "intro_content^2", "tags^2", "full_content"] +KEYWORD_SEARCH_SCAN_CAP = 50000 +KEYWORD_SEARCH_ID_CAP = 2000 + async def get_news_page( page: int, @@ -127,6 +131,200 @@ async def search_news( return news_page +async def search_news_by_keywords( + keywords: list | None = None, + topic_ids: list | None = None, + filter_topic_ids: list | None = None, + fuzzy: bool = False, + page: int = 1, + page_size: int = 10, + year_from: int | None = None, + year_to: int | None = None, + relevance_values: list | None = None, + sort_order: str | None = None, +) -> NewsPage: + """Searches the news for the keywords of a keywords-search run. + + `fuzzy` resolves the keywords to OpenAlex topics (via the aktuell_openalex_topics index), + otherwise the raw keywords are matched as phrases against the article + text. The individual keywords are OR-ed rather than AND-ed. + An article carries at most KEYWORD_LIMIT keywords, so requiring all of them + would leave every multi-keyword search empty. + Articles matching more of them simply rank higher. + + By default results stay ranked by match strength (Elasticsearch's + `_score`). Passing `sort_order` ('asc'/'desc') overrides that with a + plain date sort, same as the plain news list. + """ + if fuzzy: + should = await _topic_id_should_clauses(topic_ids, filter_topic_ids) + else: + should = _keyword_should_clauses(keywords) + + if not should: + return _empty_page(page, page_size) + + clauses = await _filter_clauses(year_from, year_to, relevance_values) + query = { + "bool": { + "should": should, + "minimum_should_match": 1, + "filter": clauses, + } + } + + highlight = { + "fields": {"full_content": {"fragment_size": 200, "number_of_fragments": 1}}, + "pre_tags": [""], + "post_tags": [""], + "encoder": "html", + } + + sort = [{"date_full": sort_order}] if sort_order in ("asc", "desc") else None + + response = await _run_search( + query=query, + source=["date", "maintitle", "author", "url", "intro_content", "full_content"], + size=page_size, + offset=(page - 1) * page_size, + sort=sort, + highlight=highlight if not fuzzy else None, + ) + + news_page = await _build_page(response, page, page_size) + await _attach_topics(news_page.results) + + return news_page + + +def _keyword_should_clauses(keywords: list | None) -> list: + return [ + { + "multi_match": { + "query": keyword.strip(), + "fields": KEYWORD_SEARCH_FIELDS, + "type": "phrase", + } + } + for keyword in (keywords or []) + if keyword and keyword.strip() + ] + + +async def _topic_id_should_clauses( + topic_ids: list | None, filter_topic_ids: list | None +) -> list: + """Turns matched OpenAlex topics into id clauses, boosted by hit count. + + Articles that match several of the searched topics get a higher boost, so + Elasticsearch ranks them above articles that only match one. + """ + wanted = {tid for tid in (topic_ids or []) + (filter_topic_ids or []) if tid} + if not wanted: + return [] + + topics_per_article = await _news_ids_by_topic_ids(wanted) + if not topics_per_article: + return [] + + ranked = sorted(topics_per_article.items(), key=lambda item: -len(item[1])) + ids_by_hit_count: dict[int, list] = {} + for news_id, matched_topics in ranked[:KEYWORD_SEARCH_ID_CAP]: + ids_by_hit_count.setdefault(len(matched_topics), []).append(news_id) + + return [ + {"ids": {"values": news_ids, "boost": float(hit_count)}} + for hit_count, news_ids in ids_by_hit_count.items() + ] + + +async def _news_ids_by_topic_ids(topic_ids: set) -> dict: + """Returns news_id -> set of searched topic ids the article was mapped to.""" + query = {"terms": {"topic_matches.topic_id.keyword": sorted(topic_ids)}} + + topics_per_article: dict[str, set] = {} + scanned = 0 + try: + async for hit in elasticsearch.scan( + index=TOPICS_INDEX, + query=query, + source=["news_id", "topic_matches.topic_id"], + cluster="inse", + ): + scanned += 1 + source = hit.get("_source", {}) + news_id = source.get("news_id") + if news_id: + matched = topics_per_article.setdefault(news_id, set()) + for match in source.get("topic_matches") or []: + topic_id = match.get("topic_id") + if topic_id in topic_ids: + matched.add(topic_id) + if scanned >= KEYWORD_SEARCH_SCAN_CAP: + logger.warning( + f"Topic lookup hit the scan cap of {KEYWORD_SEARCH_SCAN_CAP} documents." + ) + break + except Exception: + logger.exception("Topic lookup for the keyword news search failed.") + return {} + + return {news_id: matched for news_id, matched in topics_per_article.items() if matched} + + +async def _attach_topics(articles: list) -> None: + news_ids = [article.id for article in articles if article.id] + if not news_ids: + return + + topics_per_article = await _topics_for_news_ids(news_ids) + for article in articles: + article.topics = topics_per_article.get(article.id, []) + + +async def _topics_for_news_ids(news_ids: list) -> dict: + """Batched variant of get_article_topics_from_index for a result page.""" + try: + response = await elasticsearch.search( + index=TOPICS_INDEX, + query={"terms": {"news_id.keyword": news_ids}}, + source=["news_id", "keyword", "topic_matches"], + size=min(len(news_ids) * KEYWORD_LIMIT, TOPICS_INDEX_MAX_PAIRS * 10), + cluster="inse", + ) + except Exception: + logger.exception("Batched topic lookup for the news result page failed.") + return {} + + topics_per_article: dict[str, list] = {} + seen_per_article: dict[str, set] = {} + for hit in response.get("hits", {}).get("hits", []): + source = hit.get("_source", {}) + news_id = source.get("news_id") + if not news_id: + continue + keyword = source.get("keyword") + matched = topics_per_article.setdefault(news_id, []) + seen_ids = seen_per_article.setdefault(news_id, set()) + for match in source.get("topic_matches") or []: + topic_id = match.get("topic_id") + if not topic_id or topic_id in seen_ids: + continue + seen_ids.add(topic_id) + matched.append( + MatchedTopic( + id=topic_id, + display_name=match.get("topic_display_name"), + subfield_name=match.get("subfield"), + field_name=match.get("field"), + domain_name=match.get("domain"), + source_keyword=keyword, + ) + ) + + return topics_per_article + + async def get_news_by_author( author_id: str, page: int = 1, diff --git a/service/src/main/inse/news/model.py b/service/src/main/inse/news/model.py index 8ce160de..dd688444 100644 --- a/service/src/main/inse/news/model.py +++ b/service/src/main/inse/news/model.py @@ -8,17 +8,6 @@ class NewsKeywords(BaseModel): keywords: list[str] = Field(description="The extracted keywords from the article.") -class NewsArticle(BaseModel): - id: str - date: str | None = None - maintitle: str | None = None - author: str | None = None - url: str | None = None - relevant: bool | None = None - snippet: str | None = None - related: bool | None = None - - class MentionedPerson(BaseModel): name: str is_ude: bool = False @@ -34,6 +23,18 @@ class MatchedTopic(BaseModel): source_keyword: str | None = None +class NewsArticle(BaseModel): + id: str + date: str | None = None + maintitle: str | None = None + author: str | None = None + url: str | None = None + relevant: bool | None = None + snippet: str | None = None + related: bool | None = None + topics: list[MatchedTopic] | None = None + + class NewsArticleDetail(NewsArticle): full_content: str | None = None relevant: bool | None = None diff --git a/service/src/main/inse/news/service.py b/service/src/main/inse/news/service.py index 74f300b9..eeeeb564 100644 --- a/service/src/main/inse/news/service.py +++ b/service/src/main/inse/news/service.py @@ -100,6 +100,68 @@ async def search_news( ) +@router.get( + "/keyword/search", + operation_id="getNewsByKeywords", + response_model=NewsPage, + response_model_exclude_none=True, + summary="Searches news articles by the keywords or matched topics of a keywords search.", + tags=[Tags.NEWS], +) +async def search_news_by_keywords( + keywords: Annotated[ + list[str] | None, Query(description="Raw keywords to match against title/content.") + ] = None, + topic_ids: Annotated[ + list[str] | None, + Query(alias="topicIds", description="OpenAlex topic ids the keywords resolved to."), + ] = None, + filter_topic_ids: Annotated[ + list[str] | None, + Query(alias="filterTopicIds", description="Additional topic ids to narrow the results by."), + ] = None, + fuzzy: Annotated[ + bool, + Query(description="Search by resolved topics if True, otherwise by raw keywords."), + ] = False, + page: Annotated[ + int, Query(description="Page number (1-based).", ge=1) + ] = 1, + page_size: Annotated[ + int, Query(alias="pageSize", description="Articles per page.", ge=1, le=100) + ] = 10, + relevance: Annotated[ + str | None, Query(description="Comma-separated relevance filter: 'relevant', 'not_relevant'.") + ] = None, + year_from: Annotated[ + int | None, Query(alias="yearFrom", description="Earliest publication year (inclusive).", ge=0) + ] = None, + year_to: Annotated[ + int | None, Query(alias="yearTo", description="Latest publication year (inclusive).", ge=0) + ] = None, + sort_order: Annotated[ + str | None, + Query( + alias="sortOrder", + description="Overrides relevance ranking with a date sort: 'desc' (newest first) or 'asc' (oldest first).", + pattern="^(asc|desc)$", + ), + ] = None, +): + return await logic.search_news_by_keywords( + keywords=keywords or [], + topic_ids=topic_ids or [], + filter_topic_ids=filter_topic_ids or [], + fuzzy=fuzzy, + page=page, + page_size=page_size, + sort_order=sort_order, + year_from=year_from, + year_to=year_to, + relevance_values=_parse_relevance(relevance), + ) + + @router.get( "/by-author", operation_id="getNewsByAuthor", diff --git a/webapp/src/app/api/api/news.service.ts b/webapp/src/app/api/api/news.service.ts index 8ff477cf..6d7a4c53 100644 --- a/webapp/src/app/api/api/news.service.ts +++ b/webapp/src/app/api/api/news.service.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,12 +9,18 @@ */ /* tslint:disable:no-unused-variable member-ordering */ -import { Inject, Injectable, Optional } from '@angular/core'; -import { HttpClient, HttpHeaders, HttpParams, - HttpResponse, HttpEvent, HttpParameterCodec, HttpContext - } from '@angular/common/http'; -import { CustomHttpParameterCodec } from '../encoder'; -import { Observable } from 'rxjs'; +import { Inject, Injectable, Optional } from '@angular/core'; +import { + HttpClient, + HttpHeaders, + HttpParams, + HttpResponse, + HttpEvent, + HttpParameterCodec, + HttpContext, +} from '@angular/common/http'; +import { CustomHttpParameterCodec } from '../encoder'; +import { Observable } from 'rxjs'; // @ts-ignore import { HTTPValidationError } from '../model/hTTPValidationError'; @@ -24,567 +30,1563 @@ import { NewsArticleDetail } from '../model/newsArticleDetail'; import { NewsPage } from '../model/newsPage'; // @ts-ignore -import { BASE_PATH, COLLECTION_FORMATS } from '../variables'; -import { Configuration } from '../configuration'; +import { BASE_PATH, COLLECTION_FORMATS } from '../variables'; +import { Configuration } from '../configuration'; import { BaseService } from '../api.base.service'; - - @Injectable({ - providedIn: 'root' + providedIn: 'root', }) export class NewsService extends BaseService { + constructor( + protected httpClient: HttpClient, + @Optional() @Inject(BASE_PATH) basePath: string | string[], + @Optional() configuration?: Configuration, + ) { + super(basePath, configuration); + } - constructor(protected httpClient: HttpClient, @Optional() @Inject(BASE_PATH) basePath: string|string[], @Optional() configuration?: Configuration) { - super(basePath, configuration); + /** + * Returns news articles in which the given person is mentioned. + * @endpoint get /api/news/by-author + * @param authorId OpenAlex author id, e.g. A5034365278. + * @param page Page number (1-based). + * @param pageSize Articles per page. + * @param sortOrder Sort order: \'desc\' (newest first) or \'asc\' (oldest first). + * @param query Optional search term, matched against title/author. + * @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 getNewsByAuthor( + authorId: string, + page?: number, + pageSize?: number, + sortOrder?: string, + query?: string, + observe?: 'body', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable; + public getNewsByAuthor( + authorId: string, + page?: number, + pageSize?: number, + sortOrder?: string, + query?: string, + observe?: 'response', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public getNewsByAuthor( + authorId: string, + page?: number, + pageSize?: number, + sortOrder?: string, + query?: string, + observe?: 'events', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public getNewsByAuthor( + authorId: string, + page?: number, + pageSize?: number, + sortOrder?: string, + query?: string, + observe: any = 'body', + reportProgress: boolean = false, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable { + if (authorId === null || authorId === undefined) { + throw new Error( + 'Required parameter authorId was null or undefined when calling getNewsByAuthor.', + ); } - /** - * Returns news articles in which the given person is mentioned. - * @endpoint get /api/news/by-author - * @param authorId OpenAlex author id, e.g. A5034365278. - * @param page Page number (1-based). - * @param pageSize Articles per page. - * @param sortOrder Sort order: \'desc\' (newest first) or \'asc\' (oldest first). - * @param query Optional search term, matched against title/author. - * @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 getNewsByAuthor(authorId: string, page?: number, pageSize?: number, sortOrder?: string, query?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; - public getNewsByAuthor(authorId: string, page?: number, pageSize?: number, sortOrder?: string, query?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public getNewsByAuthor(authorId: string, page?: number, pageSize?: number, sortOrder?: string, query?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public getNewsByAuthor(authorId: string, page?: number, pageSize?: number, sortOrder?: string, query?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { - if (authorId === null || authorId === undefined) { - throw new Error('Required parameter authorId was null or undefined when calling getNewsByAuthor.'); - } + let localVarQueryParameters = new HttpParams({ encoder: this.encoder }); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + authorId, + 'authorId', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + page, + 'page', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + pageSize, + 'pageSize', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + sortOrder, + 'sortOrder', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + query, + 'query', + ); - let localVarQueryParameters = new HttpParams({encoder: this.encoder}); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - authorId, 'authorId'); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - page, 'page'); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - pageSize, 'pageSize'); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - sortOrder, 'sortOrder'); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - query, 'query'); + let localVarHeaders = this.defaultHeaders; - let localVarHeaders = this.defaultHeaders; + const localVarHttpHeaderAcceptSelected: string | undefined = + options?.httpHeaderAccept ?? + this.configuration.selectHeaderAccept(['application/json']); + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set( + 'Accept', + localVarHttpHeaderAcceptSelected, + ); + } - 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 localVarHttpContext: HttpContext = options?.context ?? new HttpContext(); + const localVarTransferCache: boolean = options?.transferCache ?? true; - 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/news/by-author`; + 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, + }, + ); + } - 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'; - } - } + /** + * Returns news articles in which the given person is mentioned. + * @endpoint get /api/news/by-author + * @param authorId OpenAlex author id, e.g. A5034365278. + * @param page Page number (1-based). + * @param pageSize Articles per page. + * @param sortOrder Sort order: \'desc\' (newest first) or \'asc\' (oldest first). + * @param query Optional search term, matched against title/author. + * @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 getNewsByAuthor_1( + authorId: string, + page?: number, + pageSize?: number, + sortOrder?: string, + query?: string, + observe?: 'body', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable; + public getNewsByAuthor_1( + authorId: string, + page?: number, + pageSize?: number, + sortOrder?: string, + query?: string, + observe?: 'response', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public getNewsByAuthor_1( + authorId: string, + page?: number, + pageSize?: number, + sortOrder?: string, + query?: string, + observe?: 'events', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public getNewsByAuthor_1( + authorId: string, + page?: number, + pageSize?: number, + sortOrder?: string, + query?: string, + observe: any = 'body', + reportProgress: boolean = false, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable { + if (authorId === null || authorId === undefined) { + throw new Error( + 'Required parameter authorId was null or undefined when calling getNewsByAuthor_1.', + ); + } - let localVarPath = `/api/news/by-author`; - 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 - } + let localVarQueryParameters = new HttpParams({ encoder: this.encoder }); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + authorId, + 'authorId', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + page, + 'page', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + pageSize, + 'pageSize', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + sortOrder, + 'sortOrder', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + query, + 'query', + ); + + 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/news/by-author`; + 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 a single news article including its full content. + * @endpoint get /api/news/{news_id} + * @param newsId The unique id of the news article (Elasticsearch _id). + * @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 getNewsById( + newsId: string, + observe?: 'body', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable; + public getNewsById( + newsId: string, + observe?: 'response', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public getNewsById( + newsId: string, + observe?: 'events', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public getNewsById( + newsId: string, + observe: any = 'body', + reportProgress: boolean = false, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable { + if (newsId === null || newsId === undefined) { + throw new Error( + 'Required parameter newsId was null or undefined when calling getNewsById.', + ); + } + + 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/news/${this.configuration.encodeParam({ name: 'newsId', value: newsId, in: 'path', style: 'simple', explode: false, dataType: 'string', dataFormat: undefined })}`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request( + 'get', + `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined + ? { transferCache: localVarTransferCache } + : {}), + reportProgress: reportProgress, + }, + ); + } + + /** + * Returns a single news article including its full content. + * @endpoint get /api/news/{news_id} + * @param newsId The unique id of the news article (Elasticsearch _id). + * @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 getNewsById_2( + newsId: string, + observe?: 'body', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable; + public getNewsById_2( + newsId: string, + observe?: 'response', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public getNewsById_2( + newsId: string, + observe?: 'events', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public getNewsById_2( + newsId: string, + observe: any = 'body', + reportProgress: boolean = false, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable { + if (newsId === null || newsId === undefined) { + throw new Error( + 'Required parameter newsId was null or undefined when calling getNewsById_2.', + ); + } + + 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/news/${this.configuration.encodeParam({ name: 'newsId', value: newsId, in: 'path', style: 'simple', explode: false, dataType: 'string', dataFormat: undefined })}`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request( + 'get', + `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined + ? { transferCache: localVarTransferCache } + : {}), + reportProgress: reportProgress, + }, + ); + } + + /** + * Searches news articles by the keywords or matched topics of a keywords search. + * @endpoint get /api/news/keyword/search + * @param keywords Raw keywords to match against title/content. + * @param topicIds OpenAlex topic ids the keywords resolved to. + * @param filterTopicIds Additional topic ids to narrow the results by. + * @param fuzzy Search by resolved topics if True, otherwise by raw keywords. + * @param page Page number (1-based). + * @param pageSize Articles per page. + * @param relevance Comma-separated relevance filter: \'relevant\', \'not_relevant\'. + * @param yearFrom Earliest publication year (inclusive). + * @param yearTo Latest publication year (inclusive). + * @param sortOrder Overrides relevance ranking with a date sort: \'desc\' (newest first) or \'asc\' (oldest first). + * @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 getNewsByKeywords( + keywords?: Array, + topicIds?: Array, + filterTopicIds?: Array, + fuzzy?: boolean, + page?: number, + pageSize?: number, + relevance?: string, + yearFrom?: number, + yearTo?: number, + sortOrder?: string, + observe?: 'body', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable; + public getNewsByKeywords( + keywords?: Array, + topicIds?: Array, + filterTopicIds?: Array, + fuzzy?: boolean, + page?: number, + pageSize?: number, + relevance?: string, + yearFrom?: number, + yearTo?: number, + sortOrder?: string, + observe?: 'response', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public getNewsByKeywords( + keywords?: Array, + topicIds?: Array, + filterTopicIds?: Array, + fuzzy?: boolean, + page?: number, + pageSize?: number, + relevance?: string, + yearFrom?: number, + yearTo?: number, + sortOrder?: string, + observe?: 'events', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public getNewsByKeywords( + keywords?: Array, + topicIds?: Array, + filterTopicIds?: Array, + fuzzy?: boolean, + page?: number, + pageSize?: number, + relevance?: string, + yearFrom?: number, + yearTo?: number, + sortOrder?: string, + observe: any = 'body', + reportProgress: boolean = false, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable { + let localVarQueryParameters = new HttpParams({ encoder: this.encoder }); + if (keywords) { + keywords.forEach((element) => { + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + element, + 'keywords', ); + }); } - - /** - * Returns news articles in which the given person is mentioned. - * @endpoint get /api/news/by-author - * @param authorId OpenAlex author id, e.g. A5034365278. - * @param page Page number (1-based). - * @param pageSize Articles per page. - * @param sortOrder Sort order: \'desc\' (newest first) or \'asc\' (oldest first). - * @param query Optional search term, matched against title/author. - * @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 getNewsByAuthor_1(authorId: string, page?: number, pageSize?: number, sortOrder?: string, query?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; - public getNewsByAuthor_1(authorId: string, page?: number, pageSize?: number, sortOrder?: string, query?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public getNewsByAuthor_1(authorId: string, page?: number, pageSize?: number, sortOrder?: string, query?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public getNewsByAuthor_1(authorId: string, page?: number, pageSize?: number, sortOrder?: string, query?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { - if (authorId === null || authorId === undefined) { - throw new Error('Required parameter authorId was null or undefined when calling getNewsByAuthor_1.'); - } - - let localVarQueryParameters = new HttpParams({encoder: this.encoder}); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - authorId, 'authorId'); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - page, 'page'); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - pageSize, 'pageSize'); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - sortOrder, 'sortOrder'); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - query, 'query'); - - 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/news/by-author`; - 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 - } + if (topicIds) { + topicIds.forEach((element) => { + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + element, + 'topicIds', ); + }); } - - /** - * Returns a single news article including its full content. - * @endpoint get /api/news/{news_id} - * @param newsId The unique id of the news article (Elasticsearch _id). - * @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 getNewsById(newsId: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; - public getNewsById(newsId: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public getNewsById(newsId: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public getNewsById(newsId: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { - if (newsId === null || newsId === undefined) { - throw new Error('Required parameter newsId was null or undefined when calling getNewsById.'); - } - - 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/news/${this.configuration.encodeParam({name: "newsId", value: newsId, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: undefined})}`; - const { basePath, withCredentials } = this.configuration; - return this.httpClient.request('get', `${basePath}${localVarPath}`, - { - context: localVarHttpContext, - responseType: responseType_, - ...(withCredentials ? { withCredentials } : {}), - headers: localVarHeaders, - observe: observe, - ...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}), - reportProgress: reportProgress - } + if (filterTopicIds) { + filterTopicIds.forEach((element) => { + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + element, + 'filterTopicIds', ); + }); + } + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + fuzzy, + 'fuzzy', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + page, + 'page', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + pageSize, + 'pageSize', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + relevance, + 'relevance', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + yearFrom, + 'yearFrom', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + yearTo, + 'yearTo', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + sortOrder, + 'sortOrder', + ); + + let localVarHeaders = this.defaultHeaders; + + const localVarHttpHeaderAcceptSelected: string | undefined = + options?.httpHeaderAccept ?? + this.configuration.selectHeaderAccept(['application/json']); + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set( + 'Accept', + localVarHttpHeaderAcceptSelected, + ); } - /** - * Returns a single news article including its full content. - * @endpoint get /api/news/{news_id} - * @param newsId The unique id of the news article (Elasticsearch _id). - * @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 getNewsById_2(newsId: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; - public getNewsById_2(newsId: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public getNewsById_2(newsId: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public getNewsById_2(newsId: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { - if (newsId === null || newsId === undefined) { - throw new Error('Required parameter newsId was null or undefined when calling getNewsById_2.'); - } + const localVarHttpContext: HttpContext = + options?.context ?? new HttpContext(); - let localVarHeaders = this.defaultHeaders; + const localVarTransferCache: boolean = options?.transferCache ?? true; - const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([ - 'application/json' - ]); - if (localVarHttpHeaderAcceptSelected !== undefined) { - localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); - } + 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'; + } + } - const localVarHttpContext: HttpContext = options?.context ?? new HttpContext(); + let localVarPath = `/api/news/keyword/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, + }, + ); + } - 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/news/${this.configuration.encodeParam({name: "newsId", value: newsId, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: undefined})}`; - const { basePath, withCredentials } = this.configuration; - return this.httpClient.request('get', `${basePath}${localVarPath}`, - { - context: localVarHttpContext, - responseType: responseType_, - ...(withCredentials ? { withCredentials } : {}), - headers: localVarHeaders, - observe: observe, - ...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}), - reportProgress: reportProgress - } + /** + * Searches news articles by the keywords or matched topics of a keywords search. + * @endpoint get /api/news/keyword/search + * @param keywords Raw keywords to match against title/content. + * @param topicIds OpenAlex topic ids the keywords resolved to. + * @param filterTopicIds Additional topic ids to narrow the results by. + * @param fuzzy Search by resolved topics if True, otherwise by raw keywords. + * @param page Page number (1-based). + * @param pageSize Articles per page. + * @param relevance Comma-separated relevance filter: \'relevant\', \'not_relevant\'. + * @param yearFrom Earliest publication year (inclusive). + * @param yearTo Latest publication year (inclusive). + * @param sortOrder Overrides relevance ranking with a date sort: \'desc\' (newest first) or \'asc\' (oldest first). + * @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 getNewsByKeywords_3( + keywords?: Array, + topicIds?: Array, + filterTopicIds?: Array, + fuzzy?: boolean, + page?: number, + pageSize?: number, + relevance?: string, + yearFrom?: number, + yearTo?: number, + sortOrder?: string, + observe?: 'body', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable; + public getNewsByKeywords_3( + keywords?: Array, + topicIds?: Array, + filterTopicIds?: Array, + fuzzy?: boolean, + page?: number, + pageSize?: number, + relevance?: string, + yearFrom?: number, + yearTo?: number, + sortOrder?: string, + observe?: 'response', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public getNewsByKeywords_3( + keywords?: Array, + topicIds?: Array, + filterTopicIds?: Array, + fuzzy?: boolean, + page?: number, + pageSize?: number, + relevance?: string, + yearFrom?: number, + yearTo?: number, + sortOrder?: string, + observe?: 'events', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public getNewsByKeywords_3( + keywords?: Array, + topicIds?: Array, + filterTopicIds?: Array, + fuzzy?: boolean, + page?: number, + pageSize?: number, + relevance?: string, + yearFrom?: number, + yearTo?: number, + sortOrder?: string, + observe: any = 'body', + reportProgress: boolean = false, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable { + let localVarQueryParameters = new HttpParams({ encoder: this.encoder }); + if (keywords) { + keywords.forEach((element) => { + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + element, + 'keywords', ); + }); } - - /** - * Returns a page of news articles, newest first. - * @endpoint get /api/news - * @param page Page number (1-based). - * @param pageSize Articles per page. - * @param sortOrder Sort order: \'desc\' (newest first) or \'asc\' (oldest first). - * @param relevance Comma-separated relevance filter: \'relevant\', \'not_relevant\'. - * @param yearFrom Earliest publication year (inclusive). - * @param yearTo Latest publication year (inclusive). - * @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 listNews(page?: number, pageSize?: number, sortOrder?: string, relevance?: string, yearFrom?: number, yearTo?: number, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; - public listNews(page?: number, pageSize?: number, sortOrder?: string, relevance?: string, yearFrom?: number, yearTo?: number, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public listNews(page?: number, pageSize?: number, sortOrder?: string, relevance?: string, yearFrom?: number, yearTo?: number, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public listNews(page?: number, pageSize?: number, sortOrder?: string, relevance?: string, yearFrom?: number, yearTo?: 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, - page, 'page'); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - pageSize, 'pageSize'); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - sortOrder, 'sortOrder'); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - relevance, 'relevance'); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - yearFrom, 'yearFrom'); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - yearTo, 'yearTo'); - - 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/news`; - 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 - } + if (topicIds) { + topicIds.forEach((element) => { + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + element, + 'topicIds', ); + }); } - - /** - * Returns a page of news articles, newest first. - * @endpoint get /api/news - * @param page Page number (1-based). - * @param pageSize Articles per page. - * @param sortOrder Sort order: \'desc\' (newest first) or \'asc\' (oldest first). - * @param relevance Comma-separated relevance filter: \'relevant\', \'not_relevant\'. - * @param yearFrom Earliest publication year (inclusive). - * @param yearTo Latest publication year (inclusive). - * @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 listNews_3(page?: number, pageSize?: number, sortOrder?: string, relevance?: string, yearFrom?: number, yearTo?: number, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; - public listNews_3(page?: number, pageSize?: number, sortOrder?: string, relevance?: string, yearFrom?: number, yearTo?: number, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public listNews_3(page?: number, pageSize?: number, sortOrder?: string, relevance?: string, yearFrom?: number, yearTo?: number, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public listNews_3(page?: number, pageSize?: number, sortOrder?: string, relevance?: string, yearFrom?: number, yearTo?: 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, - page, 'page'); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - pageSize, 'pageSize'); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - sortOrder, 'sortOrder'); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - relevance, 'relevance'); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - yearFrom, 'yearFrom'); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - yearTo, 'yearTo'); - - 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/news`; - 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 - } + if (filterTopicIds) { + filterTopicIds.forEach((element) => { + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + element, + 'filterTopicIds', ); + }); + } + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + fuzzy, + 'fuzzy', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + page, + 'page', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + pageSize, + 'pageSize', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + relevance, + 'relevance', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + yearFrom, + 'yearFrom', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + yearTo, + 'yearTo', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + sortOrder, + 'sortOrder', + ); + + let localVarHeaders = this.defaultHeaders; + + const localVarHttpHeaderAcceptSelected: string | undefined = + options?.httpHeaderAccept ?? + this.configuration.selectHeaderAccept(['application/json']); + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set( + 'Accept', + localVarHttpHeaderAcceptSelected, + ); } - /** - * Searches news articles by full text (full_content). - * @endpoint get /api/news/search - * @param query Search term, matched against the full text (full_content). - * @param page Page number (1-based). - * @param pageSize Articles per page. - * @param relevance Comma-separated relevance filter: \'relevant\', \'not_relevant\'. - * @param yearFrom Earliest publication year (inclusive). - * @param yearTo Latest publication year (inclusive). - * @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 searchNews(query: string, page?: number, pageSize?: number, relevance?: string, yearFrom?: number, yearTo?: number, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; - public searchNews(query: string, page?: number, pageSize?: number, relevance?: string, yearFrom?: number, yearTo?: number, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public searchNews(query: string, page?: number, pageSize?: number, relevance?: string, yearFrom?: number, yearTo?: number, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public searchNews(query: string, page?: number, pageSize?: number, relevance?: string, yearFrom?: number, yearTo?: number, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { - if (query === null || query === undefined) { - throw new Error('Required parameter query was null or undefined when calling searchNews.'); - } + const localVarHttpContext: HttpContext = + options?.context ?? new HttpContext(); - let localVarQueryParameters = new HttpParams({encoder: this.encoder}); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - query, 'query'); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - page, 'page'); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - pageSize, 'pageSize'); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - relevance, 'relevance'); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - yearFrom, 'yearFrom'); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - yearTo, 'yearTo'); + const localVarTransferCache: boolean = options?.transferCache ?? true; - 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/news/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 - } - ); + 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'; + } } - /** - * Searches news articles by full text (full_content). - * @endpoint get /api/news/search - * @param query Search term, matched against the full text (full_content). - * @param page Page number (1-based). - * @param pageSize Articles per page. - * @param relevance Comma-separated relevance filter: \'relevant\', \'not_relevant\'. - * @param yearFrom Earliest publication year (inclusive). - * @param yearTo Latest publication year (inclusive). - * @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 searchNews_4(query: string, page?: number, pageSize?: number, relevance?: string, yearFrom?: number, yearTo?: number, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; - public searchNews_4(query: string, page?: number, pageSize?: number, relevance?: string, yearFrom?: number, yearTo?: number, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public searchNews_4(query: string, page?: number, pageSize?: number, relevance?: string, yearFrom?: number, yearTo?: number, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public searchNews_4(query: string, page?: number, pageSize?: number, relevance?: string, yearFrom?: number, yearTo?: number, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { - if (query === null || query === undefined) { - throw new Error('Required parameter query was null or undefined when calling searchNews_4.'); - } + let localVarPath = `/api/news/keyword/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, + }, + ); + } - let localVarQueryParameters = new HttpParams({encoder: this.encoder}); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - query, 'query'); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - page, 'page'); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - pageSize, 'pageSize'); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - relevance, 'relevance'); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - yearFrom, 'yearFrom'); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - yearTo, 'yearTo'); + /** + * Returns a page of news articles, newest first. + * @endpoint get /api/news + * @param page Page number (1-based). + * @param pageSize Articles per page. + * @param sortOrder Sort order: \'desc\' (newest first) or \'asc\' (oldest first). + * @param relevance Comma-separated relevance filter: \'relevant\', \'not_relevant\'. + * @param yearFrom Earliest publication year (inclusive). + * @param yearTo Latest publication year (inclusive). + * @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 listNews( + page?: number, + pageSize?: number, + sortOrder?: string, + relevance?: string, + yearFrom?: number, + yearTo?: number, + observe?: 'body', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable; + public listNews( + page?: number, + pageSize?: number, + sortOrder?: string, + relevance?: string, + yearFrom?: number, + yearTo?: number, + observe?: 'response', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public listNews( + page?: number, + pageSize?: number, + sortOrder?: string, + relevance?: string, + yearFrom?: number, + yearTo?: number, + observe?: 'events', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public listNews( + page?: number, + pageSize?: number, + sortOrder?: string, + relevance?: string, + yearFrom?: number, + yearTo?: 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, + page, + 'page', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + pageSize, + 'pageSize', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + sortOrder, + 'sortOrder', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + relevance, + 'relevance', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + yearFrom, + 'yearFrom', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + yearTo, + 'yearTo', + ); - let localVarHeaders = this.defaultHeaders; + 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/news/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 - } - ); + 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/news`; + 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 a page of news articles, newest first. + * @endpoint get /api/news + * @param page Page number (1-based). + * @param pageSize Articles per page. + * @param sortOrder Sort order: \'desc\' (newest first) or \'asc\' (oldest first). + * @param relevance Comma-separated relevance filter: \'relevant\', \'not_relevant\'. + * @param yearFrom Earliest publication year (inclusive). + * @param yearTo Latest publication year (inclusive). + * @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 listNews_4( + page?: number, + pageSize?: number, + sortOrder?: string, + relevance?: string, + yearFrom?: number, + yearTo?: number, + observe?: 'body', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable; + public listNews_4( + page?: number, + pageSize?: number, + sortOrder?: string, + relevance?: string, + yearFrom?: number, + yearTo?: number, + observe?: 'response', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public listNews_4( + page?: number, + pageSize?: number, + sortOrder?: string, + relevance?: string, + yearFrom?: number, + yearTo?: number, + observe?: 'events', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public listNews_4( + page?: number, + pageSize?: number, + sortOrder?: string, + relevance?: string, + yearFrom?: number, + yearTo?: 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, + page, + 'page', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + pageSize, + 'pageSize', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + sortOrder, + 'sortOrder', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + relevance, + 'relevance', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + yearFrom, + 'yearFrom', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + yearTo, + 'yearTo', + ); + + 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/news`; + 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, + }, + ); + } + + /** + * Searches news articles by full text (full_content). + * @endpoint get /api/news/search + * @param query Search term, matched against the full text (full_content). + * @param page Page number (1-based). + * @param pageSize Articles per page. + * @param relevance Comma-separated relevance filter: \'relevant\', \'not_relevant\'. + * @param yearFrom Earliest publication year (inclusive). + * @param yearTo Latest publication year (inclusive). + * @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 searchNews( + query: string, + page?: number, + pageSize?: number, + relevance?: string, + yearFrom?: number, + yearTo?: number, + observe?: 'body', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable; + public searchNews( + query: string, + page?: number, + pageSize?: number, + relevance?: string, + yearFrom?: number, + yearTo?: number, + observe?: 'response', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public searchNews( + query: string, + page?: number, + pageSize?: number, + relevance?: string, + yearFrom?: number, + yearTo?: number, + observe?: 'events', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public searchNews( + query: string, + page?: number, + pageSize?: number, + relevance?: string, + yearFrom?: number, + yearTo?: number, + observe: any = 'body', + reportProgress: boolean = false, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable { + if (query === null || query === undefined) { + throw new Error( + 'Required parameter query was null or undefined when calling searchNews.', + ); + } + + let localVarQueryParameters = new HttpParams({ encoder: this.encoder }); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + query, + 'query', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + page, + 'page', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + pageSize, + 'pageSize', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + relevance, + 'relevance', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + yearFrom, + 'yearFrom', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + yearTo, + 'yearTo', + ); + + 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/news/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, + }, + ); + } + + /** + * Searches news articles by full text (full_content). + * @endpoint get /api/news/search + * @param query Search term, matched against the full text (full_content). + * @param page Page number (1-based). + * @param pageSize Articles per page. + * @param relevance Comma-separated relevance filter: \'relevant\', \'not_relevant\'. + * @param yearFrom Earliest publication year (inclusive). + * @param yearTo Latest publication year (inclusive). + * @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 searchNews_5( + query: string, + page?: number, + pageSize?: number, + relevance?: string, + yearFrom?: number, + yearTo?: number, + observe?: 'body', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable; + public searchNews_5( + query: string, + page?: number, + pageSize?: number, + relevance?: string, + yearFrom?: number, + yearTo?: number, + observe?: 'response', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public searchNews_5( + query: string, + page?: number, + pageSize?: number, + relevance?: string, + yearFrom?: number, + yearTo?: number, + observe?: 'events', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public searchNews_5( + query: string, + page?: number, + pageSize?: number, + relevance?: string, + yearFrom?: number, + yearTo?: number, + observe: any = 'body', + reportProgress: boolean = false, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable { + if (query === null || query === undefined) { + throw new Error( + 'Required parameter query was null or undefined when calling searchNews_5.', + ); + } + + let localVarQueryParameters = new HttpParams({ encoder: this.encoder }); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + query, + 'query', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + page, + 'page', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + pageSize, + 'pageSize', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + relevance, + 'relevance', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + yearFrom, + 'yearFrom', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + yearTo, + 'yearTo', + ); + + 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/news/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, + }, + ); + } } diff --git a/webapp/src/app/api/model/dfgProjectTopic.ts b/webapp/src/app/api/model/dfgProjectTopic.ts index 4b99c034..bde1b7f2 100644 --- a/webapp/src/app/api/model/dfgProjectTopic.ts +++ b/webapp/src/app/api/model/dfgProjectTopic.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 @@ -19,4 +19,3 @@ export interface DfgProjectTopic { project_count: number; keywords: Array; } - diff --git a/webapp/src/app/api/model/newsArticle.ts b/webapp/src/app/api/model/newsArticle.ts index ab48810d..2ed72b5b 100644 --- a/webapp/src/app/api/model/newsArticle.ts +++ b/webapp/src/app/api/model/newsArticle.ts @@ -1,22 +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. */ +import { MatchedTopic } from './matchedTopic'; - -export interface NewsArticle { - id: string; - date?: string | null; - maintitle?: string | null; - author?: string | null; - url?: string | null; - relevant?: boolean | null; - snippet?: string | null; - related?: boolean | null; +export interface NewsArticle { + id: string; + date?: string | null; + maintitle?: string | null; + author?: string | null; + url?: string | null; + relevant?: boolean | null; + snippet?: string | null; + related?: boolean | null; + topics?: Array | null; } - diff --git a/webapp/src/app/api/model/newsArticleDetail.ts b/webapp/src/app/api/model/newsArticleDetail.ts index 171a14ff..0e1ffe47 100644 --- a/webapp/src/app/api/model/newsArticleDetail.ts +++ b/webapp/src/app/api/model/newsArticleDetail.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 @@ -10,19 +10,17 @@ import { MatchedTopic } from './matchedTopic'; import { MentionedPerson } from './mentionedPerson'; - -export interface NewsArticleDetail { - id: string; - date?: string | null; - maintitle?: string | null; - author?: string | null; - url?: string | null; - relevant?: boolean | null; - snippet?: string | null; - related?: boolean | null; - full_content?: string | null; - authors?: Array; - keywords?: Array; - topics?: Array; +export interface NewsArticleDetail { + id: string; + date?: string | null; + maintitle?: string | null; + author?: string | null; + url?: string | null; + relevant?: boolean | null; + snippet?: string | null; + related?: boolean | null; + topics?: Array; + full_content?: string | null; + authors?: Array; + keywords?: Array; } - diff --git a/webapp/src/app/app.routes.ts b/webapp/src/app/app.routes.ts index 0f4bec64..a69daf52 100644 --- a/webapp/src/app/app.routes.ts +++ b/webapp/src/app/app.routes.ts @@ -36,6 +36,7 @@ import { workPageResolver, workQueryParamKeys, } from './resolvers/work-page.resolver'; +import { keywordsNewsPageResolver } from './resolvers/keywords-news-page.resolver'; import { selectedTopicsResolver } from './resolvers/selected-topics.resolver'; import { selectedInstitutionsResolver } from './resolvers/selected-institutions.resolver'; import { selectedBundInstitutionsResolver } from './resolvers/selected-bund-institutions.resolver'; @@ -273,7 +274,14 @@ export const routes: Routes = [ resolvingFor: RESOLVING_WORK_PAGE_FOR.KEYWORDS_SEARCH, }, }, - { path: 'news', component: KeywordsToNewsResultsComponent }, + { + path: 'news', + component: KeywordsToNewsResultsComponent, + runGuardsAndResolvers: 'always', + resolve: { + newsPage: keywordsNewsPageResolver, + }, + }, { path: 'trends', component: UniTrendParentComponent, diff --git a/webapp/src/app/modules/keywords-search/search-results/news-results/news-results.component.html b/webapp/src/app/modules/keywords-search/search-results/news-results/news-results.component.html index c33f8834..2209b4aa 100644 --- a/webapp/src/app/modules/keywords-search/search-results/news-results/news-results.component.html +++ b/webapp/src/app/modules/keywords-search/search-results/news-results/news-results.component.html @@ -1,31 +1,129 @@ -
    - - - groups -

    Newsliste

    -

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

    -
    -
    +
    +
    + + + Relevant + Nicht relevant + + - - - - - + + + + + + @if (hasActiveFilters()) { + + } +
    + + +
    + + {{ article.maintitle || 'Kein Titel' }} + + @if (article.snippet) { + + } +
    +
    + + + @if (article.date) { + {{ article.date }} + } @else { + - + } + + + + @if (article.relevant === true) { + + check_circle + Relevant + + } @else if (article.relevant === false) { + + cancel + Nicht relevant + + } @else { + + help + Nicht bestimmt + + } + + + + @let topics = article.topics ?? []; +
    + @for (topic of topics; track topic.id ?? topic.display_name) { + + } @empty { + - + } +
    +
    + + + + open_in_new + + + + @if (!hasSearchInput()) { +
    + @if (fuzzySearch()) { + + Keines der gewählten Keywords konnte einem Thema zugeordnet werden. + + } @else { + Keine Keywords ausgewählt. + } +
    + } @else { +
    + +
    + + + }
    diff --git a/webapp/src/app/modules/keywords-search/search-results/news-results/news-results.component.scss b/webapp/src/app/modules/keywords-search/search-results/news-results/news-results.component.scss index aeffa51c..6c6b9fc5 100644 --- a/webapp/src/app/modules/keywords-search/search-results/news-results/news-results.component.scss +++ b/webapp/src/app/modules/keywords-search/search-results/news-results/news-results.component.scss @@ -1,29 +1,175 @@ +.content { + display: flex; + flex-direction: column; + gap: 1rem; +} + /* ============================================================ - RESULT LAYOUT + FILTERS ============================================================ */ -.result-layout { - display: grid; - grid-template-columns: minmax(300px, 420px) 1fr; - grid-template-areas: 'summary results'; +.filters { + display: flex; + flex-wrap: wrap; + align-items: center; gap: 0.75rem; - align-items: start; -} -.search-summary-card { - grid-area: summary; -} + .relevance-field { + min-width: 200px; + } -.results-card { - grid-area: results; -} - -.search-summary-card, -.results-card { - background: var(--sg-surface); - border: 1px solid var(--sg-border); - box-shadow: none; - - .mat-mdc-card-content { - padding: 0.75rem; + .sort-order-field { + min-width: 180px; } } + +.reset-filter-btn { + display: flex; + align-items: center; + gap: 0.25rem; + height: 40px; +} + +/* ============================================================ + TABLE + ============================================================ */ +.table-wrap { + position: relative; + overflow-x: auto; +} + +::ng-deep .table-wrap table { + width: 100%; + min-width: 960px; + border-collapse: separate; + border-spacing: 0 10px; + box-shadow: none; + background: transparent; +} + +::ng-deep .table-wrap .mat-mdc-header-cell { + color: var(--sg-text-muted); + font-size: 12px; + font-weight: 700; +} + +::ng-deep .table-wrap .mat-mdc-row { + height: 86px; +} + +::ng-deep .table-wrap .mat-mdc-cell { + color: var(--sg-text); + border-bottom-color: var(--sg-border); + font-size: 13px; +} + +::ng-deep .table-wrap { + .mat-column-date, + .mat-column-relevant, + .mat-mdc-header-cell { + text-align: center; + } + + .mat-column-topics { + overflow: visible; + } +} + +/* ============================================================ + TABLE CELLS + ============================================================ */ +.title-cell { + display: flex; + flex-direction: column; + gap: 0.25rem; + padding: 0.5rem 0; + max-width: 32rem; +} + +.title { + display: inline-block; + max-width: 520px; + line-height: 1.35; + color: var(--sg-text); + font-size: 14px; + font-weight: 700; + text-decoration: none; + + &:hover { + color: var(--sg-text); + text-decoration: underline; + } +} + +.snippet { + font-size: 12.5px; + line-height: 1.5; + color: var(--sg-text-secondary); + overflow-wrap: anywhere; + + ::ng-deep em { + font-style: normal; + font-weight: 700; + color: var(--sg-blue-highlight); + } +} + +.date-text { + white-space: nowrap; +} + +.empty-text { + color: var(--sg-text-muted); +} + +.relevance-badge { + display: inline-flex; + align-items: center; + gap: 6px; + padding: 5px 12px; + border-radius: 999px; + font-size: 13px; + font-weight: 600; + line-height: 1; + white-space: nowrap; + + mat-icon { + font-size: 16px; + width: 16px; + height: 16px; + } + + &.is-relevant { + background: var(--sg-success-soft); + border: 1px solid var(--sg-success); + color: var(--sg-success); + } + + &.not-relevant { + background: var(--sg-surface-muted); + border: 1px solid var(--sg-border); + color: var(--sg-text-muted); + } + + &.undetermined { + background: var(--sg-warning-soft); + border: 1px solid var(--sg-warning); + color: var(--sg-warning); + cursor: help; + } +} + +.topic-chips { + display: flex; + flex-wrap: wrap; + gap: 0.25rem; + align-items: flex-start; + padding: 0.5rem 0; + max-width: 350px; +} + +.no-results { + display: flex; + justify-content: center; + padding: 2rem; + color: var(--sg-text-muted); +} diff --git a/webapp/src/app/modules/keywords-search/search-results/news-results/news-results.component.ts b/webapp/src/app/modules/keywords-search/search-results/news-results/news-results.component.ts index 6c904810..35116440 100644 --- a/webapp/src/app/modules/keywords-search/search-results/news-results/news-results.component.ts +++ b/webapp/src/app/modules/keywords-search/search-results/news-results/news-results.component.ts @@ -1,115 +1,276 @@ -import { Component, inject, signal } from '@angular/core'; - -import { MatCardModule } from '@angular/material/card'; -import { MatIconModule } from '@angular/material/icon'; - import { - WeightMap, - WeightSliderOption, - WeightsSlidersComponent, - WeightsSlidersValue, -} from '../../../../shared/ui/weights-sliders/weights-sliders.component'; + Component, + DestroyRef, + computed, + inject, + input, + signal, + TemplateRef, + viewChild, +} from '@angular/core'; +import { ActivatedRoute, Router, RouterModule } from '@angular/router'; +import { takeUntilDestroyed, toSignal } from '@angular/core/rxjs-interop'; +import { FormControl, ReactiveFormsModule } from '@angular/forms'; +import { debounceTime } from 'rxjs'; +import { MatButtonModule } from '@angular/material/button'; +import { MatFormFieldModule } from '@angular/material/form-field'; +import { MatIconModule } from '@angular/material/icon'; +import { MatSelectModule } from '@angular/material/select'; +import { MatTooltipModule } from '@angular/material/tooltip'; + +import { MatchedTopic, NewsPage, Topic } from '../../../../api'; +import { + DataTableComponent, + GenericColumn, +} from '../../../../shared/ui/data-table/data-table.component'; +import { QueryParamPaginatorComponent } from '../../../../shared/ui/query-param-paginator/query-param-paginator.component'; +import { AppTopicChipComponent } from '../../../../shared/ui/app-topic-chip/app-topic-chip.component'; +import { + QueryParamSelectorComponent, + SelectorOption, +} from '../../../../shared/ui/query-param-selector/query-param-selector.component'; +import { NEWS_MIN_YEAR } from '../../../../shared/ui/news-card/news-card.component'; +import { keywordsNewsQueryParamKeys } from '../../../../resolvers/keywords-news-page.resolver'; import { SearchResultsStateService } from '../search-results-state.service'; +import { YearRangeSliderComponent } from '../../../../shared/ui/year-range-slider/year-range-slider.component'; + +type NewsResult = NewsPage['results'][number]; + +const RELEVANCE_VALUES = ['relevant', 'not_relevant']; @Component({ selector: 'app-news-results', - imports: [MatCardModule, MatIconModule, WeightsSlidersComponent], + imports: [ + ReactiveFormsModule, + RouterModule, + MatButtonModule, + MatFormFieldModule, + MatIconModule, + MatSelectModule, + MatTooltipModule, + DataTableComponent, + AppTopicChipComponent, + QueryParamPaginatorComponent, + QueryParamSelectorComponent, + YearRangeSliderComponent, + ], templateUrl: './news-results.component.html', styleUrl: './news-results.component.scss', }) export class KeywordsToNewsResultsComponent { - // injects the state set by the parent route — no duplicate parsing here + protected readonly keywordsNewsQueryParamKeys = keywordsNewsQueryParamKeys; + private readonly state = inject(SearchResultsStateService); + private readonly route = inject(ActivatedRoute); + private readonly router = inject(Router); + private readonly destroyRef = inject(DestroyRef); - readonly defaultWeights: WeightMap = { - param1: 0.33, - param2: 0.33, - param3: 0.34, - }; + newsPage = 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', - }, + readonly minYear = NEWS_MIN_YEAR; + readonly maxYear = new Date().getFullYear(); + + readonly relevanceHelp = + 'Ein Artikel gilt als relevant, wenn er für Gründungsforschende interessante Inhalte enthält.'; + + readonly sortOrderOptions: SelectorOption[] = [ + { value: 'desc', display_name: 'Neueste zuerst' }, + { value: 'asc', display_name: 'Älteste zuerst' }, ]; - readonly currentWeights = signal({ - raw: this.defaultWeights, - normalized: { - param1: 0.33, - param2: 0.33, - param3: 0.34, - }, - rawSum: 2.5, - normalizedSum: 1, - valid: true, + readonly relevanceFilter = new FormControl([], { + nonNullable: true, }); - readonly projects = signal([]); // placeholder until the results service lands + readonly yearFrom = signal(this.minYear); + readonly yearTo = signal(this.maxYear); + + private readonly queryParamMap = toSignal(this.route.queryParamMap, { + initialValue: this.route.snapshot.queryParamMap, + }); + + readonly total = computed(() => this.newsPage().total ?? 0); + readonly elements = computed(() => this.newsPage().results ?? []); + readonly fuzzySearch = computed( + () => this.queryParamMap().get('fuzzy') === 'true', + ); + + readonly hasSearchInput = computed(() => + this.fuzzySearch() + ? this.state.topicIds().length > 0 + : this.state.keywords().length > 0, + ); + + readonly selectedTopicIds = computed(() => + this.queryParamMap().getAll(keywordsNewsQueryParamKeys.topicId), + ); + + readonly hasActiveFilters = computed(() => { + const params = this.queryParamMap(); + return ( + !!params.get(keywordsNewsQueryParamKeys.relevance) || + !!params.get(keywordsNewsQueryParamKeys.yearFrom) || + !!params.get(keywordsNewsQueryParamKeys.yearTo) || + !!params.get(keywordsNewsQueryParamKeys.sortOrder) || + this.selectedTopicIds().length > 0 + ); + }); + + titleTmp = viewChild.required>('titleTmp'); + dateTmp = viewChild.required>('dateTmp'); + relevanceTmp = viewChild.required>('relevanceTmp'); + topicsTmp = viewChild.required>('topicsTmp'); + actionsTmp = viewChild.required>('actionsTmp'); + + readonly columns = computed[]>(() => [ + { + id: 'maintitle', + header: 'Titel', + type: 'display', + cellTemplate: this.titleTmp(), + }, + { + id: 'date', + header: 'Datum', + type: 'display', + cellTemplate: this.dateTmp(), + }, + { + id: 'relevant', + header: 'Relevanz', + type: 'display', + cellTemplate: this.relevanceTmp(), + }, + { + id: 'topics', + header: 'Themen', + type: 'display', + cellTemplate: this.topicsTmp(), + }, + { + id: 'actions', + header: 'Aktionen', + type: 'display', + cellTemplate: this.actionsTmp(), + }, + ]); - private hasLoadedInitial = false; constructor() { - console.log('check', this.state.payload()); - } - onWeightsChange(value: WeightsSlidersValue): void { - this.currentWeights.set(value); + this.route.queryParamMap + .pipe(takeUntilDestroyed(this.destroyRef)) + .subscribe((params) => { + this.relevanceFilter.setValue( + this.parseRelevance(params.get(keywordsNewsQueryParamKeys.relevance)), + { emitEvent: false }, + ); - // fires once with the query-param-aware initial state — use it to load - if (!this.hasLoadedInitial) { - this.hasLoadedInitial = true; - this.loadprojects(); - } + this.yearFrom.set( + this.parseYear(params.get(keywordsNewsQueryParamKeys.yearFrom)) ?? + this.minYear, + ); + this.yearTo.set( + this.parseYear(params.get(keywordsNewsQueryParamKeys.yearTo)) ?? + this.maxYear, + ); + }); + + this.relevanceFilter.valueChanges + .pipe(debounceTime(300), takeUntilDestroyed(this.destroyRef)) + .subscribe(() => this.applyRelevanceFilter()); } - 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, + applyYearFilter(): void { + this.router.navigate([], { + relativeTo: this.route, + queryParams: { + [keywordsNewsQueryParamKeys.yearFrom]: + this.yearFrom() > this.minYear ? this.yearFrom() : null, + [keywordsNewsQueryParamKeys.yearTo]: + this.yearTo() < this.maxYear ? this.yearTo() : null, + [keywordsNewsQueryParamKeys.page]: 0, }, + queryParamsHandling: 'merge', + }); + } + + toTopic(matched: MatchedTopic): Topic { + return { + id: matched.id, + display_name: matched.display_name, + subfield: matched.subfield_name + ? { display_name: matched.subfield_name } + : null, + field: matched.field_name ? { display_name: matched.field_name } : null, + domain: matched.domain_name + ? { display_name: matched.domain_name } + : null, }; + } - console.log(requestPayload); + isTopicActive(topic: MatchedTopic): boolean { + return !!topic.id && this.selectedTopicIds().includes(topic.id); + } - /** - * TODO: - * this.projectsService.searchprojects(requestPayload).subscribe({ - * next: results => this.projects.set(results), - * error: error => console.error(error), - * }); - */ + toggleTopicFilter(topic: Topic): void { + if (!topic.id || !this.fuzzySearch()) { + return; + } + + const selected = this.selectedTopicIds(); + const next = selected.includes(topic.id) + ? selected.filter((id) => id !== topic.id) + : [...selected, topic.id]; + + this.router.navigate([], { + relativeTo: this.route, + queryParams: { + [keywordsNewsQueryParamKeys.topicId]: next.length ? next : null, + [keywordsNewsQueryParamKeys.page]: 0, + }, + queryParamsHandling: 'merge', + }); + } + + resetFilters(): void { + this.router.navigate([], { + relativeTo: this.route, + queryParams: { + [keywordsNewsQueryParamKeys.relevance]: null, + [keywordsNewsQueryParamKeys.yearFrom]: null, + [keywordsNewsQueryParamKeys.yearTo]: null, + [keywordsNewsQueryParamKeys.topicId]: null, + [keywordsNewsQueryParamKeys.sortOrder]: null, + [keywordsNewsQueryParamKeys.page]: 0, + }, + queryParamsHandling: 'merge', + }); + } + + private applyRelevanceFilter(): void { + this.router.navigate([], { + relativeTo: this.route, + queryParams: { + [keywordsNewsQueryParamKeys.relevance]: + this.relevanceFilter.value.length > 0 + ? this.relevanceFilter.value.join(',') + : null, + [keywordsNewsQueryParamKeys.page]: 0, + }, + queryParamsHandling: 'merge', + }); + } + + private parseRelevance(raw: string | null): string[] { + if (!raw) return []; + return raw + .split(',') + .map((entry) => entry.trim()) + .filter((entry) => RELEVANCE_VALUES.includes(entry)); + } + + private parseYear(raw: string | null): number | null { + const year = Number.parseInt(raw ?? '', 10); + return Number.isNaN(year) ? null : year; } } diff --git a/webapp/src/app/resolvers/keywords-news-page.resolver.ts b/webapp/src/app/resolvers/keywords-news-page.resolver.ts new file mode 100644 index 00000000..12ea788c --- /dev/null +++ b/webapp/src/app/resolvers/keywords-news-page.resolver.ts @@ -0,0 +1,76 @@ +import { ResolveFn } from '@angular/router'; +import { inject } from '@angular/core'; +import { of } from 'rxjs'; + +import { NewsPage, NewsService } from '../api'; + +export const keywordsNewsQueryParamKeys = { + page: 'page', + size: 'size', + relevance: 'relevance', + yearFrom: 'yearFrom', + yearTo: 'yearTo', + topicId: 'topicId', + sortOrder: 'sorting_order', +} as const; + +const emptyPage = (page: number, pageSize: number): NewsPage => ({ + total: 0, + page, + page_size: pageSize, + results: [], +}); + +export const keywordsNewsPageResolver: ResolveFn = (route) => { + const params = route.queryParamMap; + + const page = Number(params.get(keywordsNewsQueryParamKeys.page)) || 0; + const size = Number(params.get(keywordsNewsQueryParamKeys.size)) || 10; + + const keywords = splitList(params.get('keywords')); + const topicIds = splitList(params.get('topics')); + const filterTopicIds = params.getAll(keywordsNewsQueryParamKeys.topicId); + const fuzzy = params.get('fuzzy') === 'true'; + + if (fuzzy ? topicIds.length === 0 : keywords.length === 0) { + return of(emptyPage(page + 1, size)); + } + + const relevance = + params.get(keywordsNewsQueryParamKeys.relevance) || undefined; + const yearFrom = parseYear(params.get(keywordsNewsQueryParamKeys.yearFrom)); + const yearTo = parseYear(params.get(keywordsNewsQueryParamKeys.yearTo)); + const sortOrder = parseSortOrder( + params.get(keywordsNewsQueryParamKeys.sortOrder), + ); + + return inject(NewsService).getNewsByKeywords( + keywords, + topicIds, + filterTopicIds, + fuzzy, + page + 1, + size, + relevance, + yearFrom, + yearTo, + sortOrder, + ); +}; + +function splitList(raw: string | null): string[] { + if (!raw) return []; + return raw + .split(',') + .map((value) => value.trim()) + .filter(Boolean); +} + +function parseYear(raw: string | null): number | undefined { + const year = Number.parseInt(raw ?? '', 10); + return Number.isNaN(year) ? undefined : year; +} + +function parseSortOrder(raw: string | null): string | undefined { + return raw === 'asc' || raw === 'desc' ? raw : undefined; +} From c1692535a58b1f9d9462eafa7e9fbe726e191489 Mon Sep 17 00:00:00 2001 From: "noemi.kallweit" Date: Mon, 10 Aug 2026 14:28:09 +0200 Subject: [PATCH 078/114] refactor(keyword-search): extract 'more' toggle into a shared component --- service/src/main/inse/news/logic.py | 3 +- .../news-results/news-results.component.html | 13 ++++- .../news-results/news-results.component.ts | 25 +++++++++ .../publications-table.component.html | 11 ++-- .../publications-table.component.scss | 23 -------- .../publications-table.component.ts | 2 + .../bund-project-table.component.html | 11 ++-- .../bund-project-table.component.scss | 24 -------- .../bund-project-table.component.ts | 2 + .../chip-overflow-toggle.component.html | 7 +++ .../chip-overflow-toggle.component.scss | 27 +++++++++ .../chip-overflow-toggle.component.ts | 14 +++++ .../dfg-project-table.component.html | 55 ++++++------------- .../dfg-project-table.component.scss | 24 -------- .../dfg-project-table.component.ts | 2 + .../eu-project-table.component.html | 33 ++++------- .../eu-project-table.component.scss | 24 -------- .../eu-project-table.component.ts | 2 + .../publication-table.component.html | 26 +++------ .../publication-table.component.scss | 29 ---------- .../publication-table.component.ts | 2 + 21 files changed, 141 insertions(+), 218 deletions(-) create mode 100644 webapp/src/app/shared/ui/chip-overflow-toggle/chip-overflow-toggle.component.html create mode 100644 webapp/src/app/shared/ui/chip-overflow-toggle/chip-overflow-toggle.component.scss create mode 100644 webapp/src/app/shared/ui/chip-overflow-toggle/chip-overflow-toggle.component.ts diff --git a/service/src/main/inse/news/logic.py b/service/src/main/inse/news/logic.py index d8570f97..f46417e5 100644 --- a/service/src/main/inse/news/logic.py +++ b/service/src/main/inse/news/logic.py @@ -51,6 +51,7 @@ EXACT_ID_CAP = 1000 KEYWORD_SEARCH_FIELDS = ["maintitle^3", "intro_content^2", "tags^2", "full_content"] KEYWORD_SEARCH_SCAN_CAP = 50000 KEYWORD_SEARCH_ID_CAP = 2000 +TOPIC_DOCS_PER_ARTICLE = 25 async def get_news_page( @@ -289,7 +290,7 @@ async def _topics_for_news_ids(news_ids: list) -> dict: index=TOPICS_INDEX, query={"terms": {"news_id.keyword": news_ids}}, source=["news_id", "keyword", "topic_matches"], - size=min(len(news_ids) * KEYWORD_LIMIT, TOPICS_INDEX_MAX_PAIRS * 10), + size=min(len(news_ids) * TOPIC_DOCS_PER_ARTICLE, 10000), cluster="inse", ) except Exception: diff --git a/webapp/src/app/modules/keywords-search/search-results/news-results/news-results.component.html b/webapp/src/app/modules/keywords-search/search-results/news-results/news-results.component.html index 2209b4aa..24c82696 100644 --- a/webapp/src/app/modules/keywords-search/search-results/news-results/news-results.component.html +++ b/webapp/src/app/modules/keywords-search/search-results/news-results/news-results.component.html @@ -81,8 +81,12 @@ @let topics = article.topics ?? []; + @let topicsExpanded = isTopicsExpanded(article); + @let visibleTopics = + topicsExpanded ? topics : topics.slice(0, topicPreviewCount); +
    - @for (topic of topics; track topic.id ?? topic.display_name) { + @for (topic of visibleTopics; track topic.id ?? topic.display_name) { - } + + @if (topics.length > topicPreviewCount) { + + }
    diff --git a/webapp/src/app/modules/keywords-search/search-results/news-results/news-results.component.ts b/webapp/src/app/modules/keywords-search/search-results/news-results/news-results.component.ts index 35116440..a191135f 100644 --- a/webapp/src/app/modules/keywords-search/search-results/news-results/news-results.component.ts +++ b/webapp/src/app/modules/keywords-search/search-results/news-results/news-results.component.ts @@ -26,6 +26,7 @@ import { } from '../../../../shared/ui/data-table/data-table.component'; import { QueryParamPaginatorComponent } from '../../../../shared/ui/query-param-paginator/query-param-paginator.component'; import { AppTopicChipComponent } from '../../../../shared/ui/app-topic-chip/app-topic-chip.component'; +import { ChipOverflowToggleComponent } from '../../../../shared/ui/chip-overflow-toggle/chip-overflow-toggle.component'; import { QueryParamSelectorComponent, SelectorOption, @@ -51,6 +52,7 @@ const RELEVANCE_VALUES = ['relevant', 'not_relevant']; MatTooltipModule, DataTableComponent, AppTopicChipComponent, + ChipOverflowToggleComponent, QueryParamPaginatorComponent, QueryParamSelectorComponent, YearRangeSliderComponent, @@ -86,6 +88,9 @@ export class KeywordsToNewsResultsComponent { readonly yearFrom = signal(this.minYear); readonly yearTo = signal(this.maxYear); + protected readonly topicPreviewCount = 3; + private readonly expandedTopicsIds = signal>(new Set()); + private readonly queryParamMap = toSignal(this.route.queryParamMap, { initialValue: this.route.snapshot.queryParamMap, }); @@ -212,6 +217,26 @@ export class KeywordsToNewsResultsComponent { return !!topic.id && this.selectedTopicIds().includes(topic.id); } + isTopicsExpanded(article: NewsResult): boolean { + return this.expandedTopicsIds().has(article.id); + } + + toggleTopicsExpansion(article: NewsResult): void { + if (!article.id) { + return; + } + + this.expandedTopicsIds.update((ids) => { + const next = new Set(ids); + if (next.has(article.id)) { + next.delete(article.id); + } else { + next.add(article.id); + } + return next; + }); + } + toggleTopicFilter(topic: Topic): void { if (!topic.id || !this.fuzzySearch()) { return; diff --git a/webapp/src/app/modules/projects/eu-cordis-details/publications-table/publications-table.component.html b/webapp/src/app/modules/projects/eu-cordis-details/publications-table/publications-table.component.html index 8f444995..0a3d5296 100644 --- a/webapp/src/app/modules/projects/eu-cordis-details/publications-table/publications-table.component.html +++ b/webapp/src/app/modules/projects/eu-cordis-details/publications-table/publications-table.component.html @@ -40,13 +40,10 @@ } @if (authorList.length > 3) { - + }
    } @else { diff --git a/webapp/src/app/modules/projects/eu-cordis-details/publications-table/publications-table.component.scss b/webapp/src/app/modules/projects/eu-cordis-details/publications-table/publications-table.component.scss index c60fa1a1..18be839d 100644 --- a/webapp/src/app/modules/projects/eu-cordis-details/publications-table/publications-table.component.scss +++ b/webapp/src/app/modules/projects/eu-cordis-details/publications-table/publications-table.component.scss @@ -6,29 +6,6 @@ background: var(--sg-card-bg); border: 1px solid var(--sg-border); } - .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: var(--sg-surface); - color: var(--sg-text-muted); - font-family: inherit; - font-size: 11px; - line-height: 1.2; - cursor: pointer; - transition: all 0.2s ease; - - &:hover, - &:focus-visible { - border-color: var(--sg-primary); - color: var(--sg-primary); - background: var(--sg-surface-soft); - outline: none; - } - } .section-header { display: flex; align-items: center; diff --git a/webapp/src/app/modules/projects/eu-cordis-details/publications-table/publications-table.component.ts b/webapp/src/app/modules/projects/eu-cordis-details/publications-table/publications-table.component.ts index bf71247b..840fe398 100644 --- a/webapp/src/app/modules/projects/eu-cordis-details/publications-table/publications-table.component.ts +++ b/webapp/src/app/modules/projects/eu-cordis-details/publications-table/publications-table.component.ts @@ -20,10 +20,12 @@ import { DataTableComponent, GenericColumn, } from '../../../../shared/ui/data-table/data-table.component'; +import { ChipOverflowToggleComponent } from '../../../../shared/ui/chip-overflow-toggle/chip-overflow-toggle.component'; @Component({ selector: 'app-publications-table', imports: [ + ChipOverflowToggleComponent, CommonModule, MatIcon, MatCard, diff --git a/webapp/src/app/shared/ui/bund-project-table/bund-project-table.component.html b/webapp/src/app/shared/ui/bund-project-table/bund-project-table.component.html index b078bd8d..b9f076ad 100644 --- a/webapp/src/app/shared/ui/bund-project-table/bund-project-table.component.html +++ b/webapp/src/app/shared/ui/bund-project-table/bund-project-table.component.html @@ -105,13 +105,10 @@ - } @if (projectTopics.length > 3) { - + }
    diff --git a/webapp/src/app/shared/ui/bund-project-table/bund-project-table.component.scss b/webapp/src/app/shared/ui/bund-project-table/bund-project-table.component.scss index 9df1a881..57b73879 100644 --- a/webapp/src/app/shared/ui/bund-project-table/bund-project-table.component.scss +++ b/webapp/src/app/shared/ui/bund-project-table/bund-project-table.component.scss @@ -121,30 +121,6 @@ } } -.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: var(--sg-surface); - 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 // ------------------------ diff --git a/webapp/src/app/shared/ui/bund-project-table/bund-project-table.component.ts b/webapp/src/app/shared/ui/bund-project-table/bund-project-table.component.ts index f5a333e5..8b2424ce 100644 --- a/webapp/src/app/shared/ui/bund-project-table/bund-project-table.component.ts +++ b/webapp/src/app/shared/ui/bund-project-table/bund-project-table.component.ts @@ -25,9 +25,11 @@ import { ChipComponent } from '../chip/chip.component'; import { MatTooltip } from '@angular/material/tooltip'; import { topicHierarchyColor } from '../../../resolvers/utils/topic-colors'; import { bundProjectQueryParamKeys } from '../../../resolvers/bund-projects.resolver'; +import { ChipOverflowToggleComponent } from '../chip-overflow-toggle/chip-overflow-toggle.component'; @Component({ selector: 'app-bund-project-table', imports: [ + ChipOverflowToggleComponent, DataTableComponent, RouterModule, MatIconModule, diff --git a/webapp/src/app/shared/ui/chip-overflow-toggle/chip-overflow-toggle.component.html b/webapp/src/app/shared/ui/chip-overflow-toggle/chip-overflow-toggle.component.html new file mode 100644 index 00000000..d9c834d5 --- /dev/null +++ b/webapp/src/app/shared/ui/chip-overflow-toggle/chip-overflow-toggle.component.html @@ -0,0 +1,7 @@ + diff --git a/webapp/src/app/shared/ui/chip-overflow-toggle/chip-overflow-toggle.component.scss b/webapp/src/app/shared/ui/chip-overflow-toggle/chip-overflow-toggle.component.scss new file mode 100644 index 00000000..5157006b --- /dev/null +++ b/webapp/src/app/shared/ui/chip-overflow-toggle/chip-overflow-toggle.component.scss @@ -0,0 +1,27 @@ +:host { + display: inline-flex; +} + +.chip-overflow-toggle { + 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: var(--sg-surface); + 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; + } +} diff --git a/webapp/src/app/shared/ui/chip-overflow-toggle/chip-overflow-toggle.component.ts b/webapp/src/app/shared/ui/chip-overflow-toggle/chip-overflow-toggle.component.ts new file mode 100644 index 00000000..6beff800 --- /dev/null +++ b/webapp/src/app/shared/ui/chip-overflow-toggle/chip-overflow-toggle.component.ts @@ -0,0 +1,14 @@ +import { Component, input, output } from '@angular/core'; + +@Component({ + selector: 'app-chip-overflow-toggle', + standalone: true, + templateUrl: './chip-overflow-toggle.component.html', + styleUrl: './chip-overflow-toggle.component.scss', +}) +export class ChipOverflowToggleComponent { + expanded = input(false); + hiddenCount = input(0); + + toggle = output(); +} 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 9c86010c..6b9ad817 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 @@ -51,17 +51,10 @@ - } @if (classifications.length > 3) { - + }
    @@ -88,17 +81,10 @@ - } @if (projectAuthors.length > 3) { - + } @@ -133,16 +119,10 @@ - } @if (institutions.length > 3) { - + } @@ -165,13 +145,10 @@ - } @if (projectTopics.length > 3) { - + } 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 82987ff1..0698910b 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 @@ -100,30 +100,6 @@ } } -.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: var(--sg-surface); - 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 // ------------------------ 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 baa2ae18..df6b97e5 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 @@ -23,9 +23,11 @@ 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'; +import { ChipOverflowToggleComponent } from '../chip-overflow-toggle/chip-overflow-toggle.component'; @Component({ selector: 'app-dfg-project-table', imports: [ + ChipOverflowToggleComponent, DataTableComponent, RouterModule, MatIconModule, 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 68ef7152..a0a9fc26 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 @@ -60,13 +60,10 @@ } @if (projectAuthors.length > 3) { - + } @@ -103,13 +100,10 @@ } @if (organizations.length > 3) { - + } @@ -133,13 +127,10 @@ } @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 8a4f0644..39334f9f 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 @@ -100,30 +100,6 @@ } } -.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: var(--sg-surface); - 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 // ------------------------ 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 0a3fca02..54f87520 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 @@ -32,9 +32,11 @@ import { euProjectQueryParamKeys } from '../../../resolvers/eu-cordis-projects.r import { topicHierarchyColor } from '../../../resolvers/utils/topic-colors'; import { ChipComponent } from '../chip/chip.component'; import { AppAuthorChipComponent } from '../app-author-chip/app-author-chip.component'; +import { ChipOverflowToggleComponent } from '../chip-overflow-toggle/chip-overflow-toggle.component'; @Component({ selector: 'app-eu-project-table', imports: [ + ChipOverflowToggleComponent, DataTableComponent, RouterModule, MatIconModule, diff --git a/webapp/src/app/shared/ui/publication-table/publication-table.component.html b/webapp/src/app/shared/ui/publication-table/publication-table.component.html index a54e65a6..611bfb21 100644 --- a/webapp/src/app/shared/ui/publication-table/publication-table.component.html +++ b/webapp/src/app/shared/ui/publication-table/publication-table.component.html @@ -94,17 +94,10 @@ - } @if (publicationInstitutions.length > 3) { - + } @@ -130,13 +123,10 @@ - } @if (workAuthors.length > 3) { - + } diff --git a/webapp/src/app/shared/ui/publication-table/publication-table.component.scss b/webapp/src/app/shared/ui/publication-table/publication-table.component.scss index 830f3c3b..6df1e4e9 100644 --- a/webapp/src/app/shared/ui/publication-table/publication-table.component.scss +++ b/webapp/src/app/shared/ui/publication-table/publication-table.component.scss @@ -444,35 +444,6 @@ table.is-hidden { max-width: 280px; } -.publication-institution-more, -.publication-topic-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: var(--sg-surface); - 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; - } -} - -.publication-topic-more { - max-width: 180px; -} - ::ng-deep .mat-mdc-header-cell { color: var(--sg-text-muted); font-size: 12px; diff --git a/webapp/src/app/shared/ui/publication-table/publication-table.component.ts b/webapp/src/app/shared/ui/publication-table/publication-table.component.ts index 57cf16bf..98a365b2 100644 --- a/webapp/src/app/shared/ui/publication-table/publication-table.component.ts +++ b/webapp/src/app/shared/ui/publication-table/publication-table.component.ts @@ -36,10 +36,12 @@ import { TopicTooltipComponent } from '../topic-tooltip/topic-tooltip.component' import { AppTopicChipComponent } from '../app-topic-chip/app-topic-chip.component'; import { AppAuthorChipComponent } from '../app-author-chip/app-author-chip.component'; import { AppInstitutionChipComponent } from '../app-institution-chip/app-institution-chip.component'; +import { ChipOverflowToggleComponent } from '../chip-overflow-toggle/chip-overflow-toggle.component'; @Component({ selector: 'app-publication-table', imports: [ + ChipOverflowToggleComponent, MatIconModule, MatTooltipModule, MatButtonModule, From d8b7d8bc2eb00bc96ec5a74ac7cb81ea2a76502e Mon Sep 17 00:00:00 2001 From: "noemi.kallweit" Date: Mon, 10 Aug 2026 15:06:39 +0200 Subject: [PATCH 079/114] fix(keyword-search): add fuzzy search fallback for news --- service/src/main/inse/news/logic.py | 28 +++++++++++-------- .../news-results/news-results.component.html | 19 ++++++++++--- .../news-results/news-results.component.scss | 12 +++++++- .../news-results/news-results.component.ts | 22 ++++++++++++++- .../resolvers/keywords-news-page.resolver.ts | 6 +++- 5 files changed, 69 insertions(+), 18 deletions(-) diff --git a/service/src/main/inse/news/logic.py b/service/src/main/inse/news/logic.py index f46417e5..7e24f020 100644 --- a/service/src/main/inse/news/logic.py +++ b/service/src/main/inse/news/logic.py @@ -153,12 +153,24 @@ async def search_news_by_keywords( would leave every multi-keyword search empty. Articles matching more of them simply rank higher. + A fuzzy search without any resolved topic ids falls back to the raw + keywords. Once there are topic ids the fallback is off: a topic search that matches no article + stays empty instead of silently returning keyword hits. + By default results stay ranked by match strength (Elasticsearch's `_score`). Passing `sort_order` ('asc'/'desc') overrides that with a plain date sort, same as the plain news list. """ + wanted_topic_ids: set = set() if fuzzy: - should = await _topic_id_should_clauses(topic_ids, filter_topic_ids) + wanted_topic_ids = { + topic_id + for topic_id in (topic_ids or []) + (filter_topic_ids or []) + if topic_id + } + + if wanted_topic_ids: + should = await _topic_id_should_clauses(wanted_topic_ids) else: should = _keyword_should_clauses(keywords) @@ -189,7 +201,7 @@ async def search_news_by_keywords( size=page_size, offset=(page - 1) * page_size, sort=sort, - highlight=highlight if not fuzzy else None, + highlight=None if wanted_topic_ids else highlight, ) news_page = await _build_page(response, page, page_size) @@ -212,19 +224,13 @@ def _keyword_should_clauses(keywords: list | None) -> list: ] -async def _topic_id_should_clauses( - topic_ids: list | None, filter_topic_ids: list | None -) -> list: +async def _topic_id_should_clauses(topic_ids: set) -> list: """Turns matched OpenAlex topics into id clauses, boosted by hit count. Articles that match several of the searched topics get a higher boost, so Elasticsearch ranks them above articles that only match one. """ - wanted = {tid for tid in (topic_ids or []) + (filter_topic_ids or []) if tid} - if not wanted: - return [] - - topics_per_article = await _news_ids_by_topic_ids(wanted) + topics_per_article = await _news_ids_by_topic_ids(topic_ids) if not topics_per_article: return [] @@ -715,7 +721,7 @@ async def _get_postproc_labels(news_id: str) -> tuple[bool | None, list, list, s return relevant, authors, keywords, hit.get("_id") -async def _run_search(query: dict, source: list, size: int, offset: int, sort, highlight: dict = None) -> dict: +async def _run_search(query: dict, source: list, size: int, offset: int, sort, highlight: dict | None = None) -> dict: try: return await elasticsearch.search( index="aktuell", diff --git a/webapp/src/app/modules/keywords-search/search-results/news-results/news-results.component.html b/webapp/src/app/modules/keywords-search/search-results/news-results/news-results.component.html index 24c82696..2e594732 100644 --- a/webapp/src/app/modules/keywords-search/search-results/news-results/news-results.component.html +++ b/webapp/src/app/modules/keywords-search/search-results/news-results/news-results.component.html @@ -119,12 +119,23 @@ @if (!hasSearchInput()) {
    - @if (fuzzySearch()) { - - Keines der gewählten Keywords konnte einem Thema zugeordnet werden. + Keine Keywords ausgewählt. +
    + } @else if (total() === 0) { +
    + @if (hasNarrowingFilters()) { + Keine Nachrichten für die aktuellen Filter. + + Setzen Sie die Filter zurück, um mehr Ergebnisse zu sehen. + + } @else if (searchedByTopics()) { + Zu diesen Themen gibt es keine Nachrichten. + + Campus Aktuell deckt nicht jedes Forschungsthema ab. Schalten Sie die + Fuzzy Search aus, um direkt nach den Keywords zu suchen. } @else { - Keine Keywords ausgewählt. + Keine Nachrichten zu diesen Keywords gefunden. }
    } @else { diff --git a/webapp/src/app/modules/keywords-search/search-results/news-results/news-results.component.scss b/webapp/src/app/modules/keywords-search/search-results/news-results/news-results.component.scss index 6c6b9fc5..0fd9f342 100644 --- a/webapp/src/app/modules/keywords-search/search-results/news-results/news-results.component.scss +++ b/webapp/src/app/modules/keywords-search/search-results/news-results/news-results.component.scss @@ -169,7 +169,17 @@ .no-results { display: flex; - justify-content: center; + flex-direction: column; + align-items: center; + gap: 0.5rem; padding: 2rem; color: var(--sg-text-muted); + text-align: center; + + &__hint { + max-width: 34rem; + color: var(--sg-text-soft); + font-size: 0.8125rem; + line-height: 1.5; + } } diff --git a/webapp/src/app/modules/keywords-search/search-results/news-results/news-results.component.ts b/webapp/src/app/modules/keywords-search/search-results/news-results/news-results.component.ts index a191135f..2bc16551 100644 --- a/webapp/src/app/modules/keywords-search/search-results/news-results/news-results.component.ts +++ b/webapp/src/app/modules/keywords-search/search-results/news-results/news-results.component.ts @@ -103,7 +103,7 @@ export class KeywordsToNewsResultsComponent { readonly hasSearchInput = computed(() => this.fuzzySearch() - ? this.state.topicIds().length > 0 + ? this.state.topicIds().length > 0 || this.state.keywords().length > 0 : this.state.keywords().length > 0, ); @@ -122,6 +122,26 @@ export class KeywordsToNewsResultsComponent { ); }); + readonly hasNarrowingFilters = computed(() => { + const params = this.queryParamMap(); + return ( + !!params.get(keywordsNewsQueryParamKeys.relevance) || + !!params.get(keywordsNewsQueryParamKeys.yearFrom) || + !!params.get(keywordsNewsQueryParamKeys.yearTo) || + this.selectedTopicIds().length > 0 + ); + }); + + readonly searchedByTopics = computed(() => { + if (!this.fuzzySearch()) { + return false; + } + const baseTopicIds = (this.queryParamMap().get('topics') ?? '') + .split(',') + .filter((value) => value.trim()); + return baseTopicIds.length > 0 || this.selectedTopicIds().length > 0; + }); + titleTmp = viewChild.required>('titleTmp'); dateTmp = viewChild.required>('dateTmp'); relevanceTmp = viewChild.required>('relevanceTmp'); diff --git a/webapp/src/app/resolvers/keywords-news-page.resolver.ts b/webapp/src/app/resolvers/keywords-news-page.resolver.ts index 12ea788c..a347122c 100644 --- a/webapp/src/app/resolvers/keywords-news-page.resolver.ts +++ b/webapp/src/app/resolvers/keywords-news-page.resolver.ts @@ -32,7 +32,11 @@ export const keywordsNewsPageResolver: ResolveFn = (route) => { const filterTopicIds = params.getAll(keywordsNewsQueryParamKeys.topicId); const fuzzy = params.get('fuzzy') === 'true'; - if (fuzzy ? topicIds.length === 0 : keywords.length === 0) { + const canSearch = fuzzy + ? topicIds.length > 0 || keywords.length > 0 + : keywords.length > 0; + + if (!canSearch) { return of(emptyPage(page + 1, size)); } From 882ad3b8cf8e31dc5b97cacf8799e4454596d089 Mon Sep 17 00:00:00 2001 From: "noemi.kallweit" Date: Mon, 10 Aug 2026 15:30:18 +0200 Subject: [PATCH 080/114] refactor(news): deduplicate topic reading logic --- service/src/main/inse/news/logic.py | 45 +++-------------------------- 1 file changed, 4 insertions(+), 41 deletions(-) diff --git a/service/src/main/inse/news/logic.py b/service/src/main/inse/news/logic.py index 7e24f020..da4ca3eb 100644 --- a/service/src/main/inse/news/logic.py +++ b/service/src/main/inse/news/logic.py @@ -27,7 +27,6 @@ TOPIC_NUM_CANDIDATES = 100 TOPIC_SIMILARITY = 0.5 TOPICS_INDEX = "aktuell_openalex_topics" -TOPICS_INDEX_MAX_PAIRS = 100 _SESSION_TOPIC_CACHE: dict[str, list] = {} @@ -289,8 +288,8 @@ async def _attach_topics(articles: list) -> None: article.topics = topics_per_article.get(article.id, []) -async def _topics_for_news_ids(news_ids: list) -> dict: - """Batched variant of get_article_topics_from_index for a result page.""" +async def _topics_for_news_ids(news_ids: list) -> dict[str, list[MatchedTopic]]: + """Reads the indexed OpenAlex topic matches for the given articles.""" try: response = await elasticsearch.search( index=TOPICS_INDEX, @@ -303,7 +302,7 @@ async def _topics_for_news_ids(news_ids: list) -> dict: logger.exception("Batched topic lookup for the news result page failed.") return {} - topics_per_article: dict[str, list] = {} + topics_per_article: dict[str, list[MatchedTopic]] = {} seen_per_article: dict[str, set] = {} for hit in response.get("hits", {}).get("hits", []): source = hit.get("_source", {}) @@ -526,7 +525,7 @@ async def _get_article_keywords( async def _get_article_topics(news_id: str, keywords: list) -> list: - indexed = await get_article_topics_from_index(news_id) + indexed = (await _topics_for_news_ids([news_id])).get(news_id, []) if indexed: return indexed @@ -541,42 +540,6 @@ async def _get_article_topics(news_id: str, keywords: list) -> list: return topics -async def get_article_topics_from_index(news_id: str) -> list: - try: - response = await elasticsearch.search( - index=TOPICS_INDEX, - query={"term": {"news_id.keyword": news_id}}, - source=["keyword", "topic_matches"], - size=TOPICS_INDEX_MAX_PAIRS, - cluster="inse", - ) - except Exception: - logger.exception(f"Topic-index lookup for {news_id} failed.") - return [] - - matched = [] - seen_ids = set() - for hit in response.get("hits", {}).get("hits", []): - source = hit.get("_source", {}) - keyword = source.get("keyword") - for match in source.get("topic_matches") or []: - topic_id = match.get("topic_id") - if not topic_id or topic_id in seen_ids: - continue - seen_ids.add(topic_id) - matched.append( - MatchedTopic( - id=topic_id, - display_name=match.get("topic_display_name"), - subfield_name=match.get("subfield"), - field_name=match.get("field"), - domain_name=match.get("domain"), - source_keyword=keyword, - ) - ) - return matched - - def _normalize_keywords(candidates: list) -> list: """Trims, dedups (case-insensitive) and caps the keywords from the LLM.""" seen = set() From 21f3f490782089f1d740e9dd8a4866dff455a0e3 Mon Sep 17 00:00:00 2001 From: "noemi.kallweit" Date: Mon, 10 Aug 2026 16:07:01 +0200 Subject: [PATCH 081/114] refactor(keyword-search, news, accounts): use shared selector for news relevance filter and reset to first page on filter change --- .../news-results/news-results.component.html | 19 +++-- .../news-results/news-results.component.scss | 7 +- .../news-results/news-results.component.ts | 47 ++---------- .../query-param-selector.component.html | 7 +- .../query-param-selector.component.ts | 71 ++++++++++++++++--- 5 files changed, 86 insertions(+), 65 deletions(-) diff --git a/webapp/src/app/modules/keywords-search/search-results/news-results/news-results.component.html b/webapp/src/app/modules/keywords-search/search-results/news-results/news-results.component.html index 2e594732..a2edb88e 100644 --- a/webapp/src/app/modules/keywords-search/search-results/news-results/news-results.component.html +++ b/webapp/src/app/modules/keywords-search/search-results/news-results/news-results.component.html @@ -1,20 +1,19 @@
    - - - Relevant - Nicht relevant - - + + label="Sortierung" + icon="sort" /> ([], { - nonNullable: true, - }); + readonly relevanceOptions: SelectorOption[] = [ + { value: 'relevant', display_name: 'Relevant' }, + { value: 'not_relevant', display_name: 'Nicht relevant' }, + ]; readonly yearFrom = signal(this.minYear); readonly yearTo = signal(this.maxYear); @@ -185,11 +177,6 @@ export class KeywordsToNewsResultsComponent { this.route.queryParamMap .pipe(takeUntilDestroyed(this.destroyRef)) .subscribe((params) => { - this.relevanceFilter.setValue( - this.parseRelevance(params.get(keywordsNewsQueryParamKeys.relevance)), - { emitEvent: false }, - ); - this.yearFrom.set( this.parseYear(params.get(keywordsNewsQueryParamKeys.yearFrom)) ?? this.minYear, @@ -199,10 +186,6 @@ export class KeywordsToNewsResultsComponent { this.maxYear, ); }); - - this.relevanceFilter.valueChanges - .pipe(debounceTime(300), takeUntilDestroyed(this.destroyRef)) - .subscribe(() => this.applyRelevanceFilter()); } applyYearFilter(): void { @@ -292,28 +275,6 @@ export class KeywordsToNewsResultsComponent { }); } - private applyRelevanceFilter(): void { - this.router.navigate([], { - relativeTo: this.route, - queryParams: { - [keywordsNewsQueryParamKeys.relevance]: - this.relevanceFilter.value.length > 0 - ? this.relevanceFilter.value.join(',') - : null, - [keywordsNewsQueryParamKeys.page]: 0, - }, - queryParamsHandling: 'merge', - }); - } - - private parseRelevance(raw: string | null): string[] { - if (!raw) return []; - return raw - .split(',') - .map((entry) => entry.trim()) - .filter((entry) => RELEVANCE_VALUES.includes(entry)); - } - private parseYear(raw: string | null): number | null { const year = Number.parseInt(raw ?? '', 10); return Number.isNaN(year) ? null : year; diff --git a/webapp/src/app/shared/ui/query-param-selector/query-param-selector.component.html b/webapp/src/app/shared/ui/query-param-selector/query-param-selector.component.html index 2ce167fe..77129614 100644 --- a/webapp/src/app/shared/ui/query-param-selector/query-param-selector.component.html +++ b/webapp/src/app/shared/ui/query-param-selector/query-param-selector.component.html @@ -2,9 +2,14 @@ @if (label()) { {{ label() }} } + @if (icon()) { + + } + (openedChange)="_handleOpenedChange($event)" + [multiple]="multiple()" + [value]="_value()"> @for (option of _options(); track $index) { {{ option.display_name }} } diff --git a/webapp/src/app/shared/ui/query-param-selector/query-param-selector.component.ts b/webapp/src/app/shared/ui/query-param-selector/query-param-selector.component.ts index 2b51fdd4..b82698f0 100644 --- a/webapp/src/app/shared/ui/query-param-selector/query-param-selector.component.ts +++ b/webapp/src/app/shared/ui/query-param-selector/query-param-selector.component.ts @@ -1,6 +1,14 @@ -import { Component, computed, inject, input, output } from '@angular/core'; +import { + Component, + computed, + inject, + input, + output, + signal, +} from '@angular/core'; import { takeUntilDestroyed, toSignal } from '@angular/core/rxjs-interop'; import { FormsModule } from '@angular/forms'; +import { MatIconModule } from '@angular/material/icon'; import { MatSelectChange, MatSelectModule } from '@angular/material/select'; import { ActivatedRoute, Router } from '@angular/router'; @@ -11,7 +19,7 @@ export type SelectorOption = { @Component({ selector: 'app-query-param-selector', - imports: [FormsModule, MatSelectModule], + imports: [FormsModule, MatIconModule, MatSelectModule], templateUrl: './query-param-selector.component.html', styleUrl: './query-param-selector.component.scss', }) @@ -21,6 +29,13 @@ export class QueryParamSelectorComponent { handleSelectionChange = output(); allowEmptyValue = input(false); label = input(''); + icon = input(''); + + multiple = input(false); + + pageQueryParamKey = input('page'); + + private readonly pendingValues = signal(null); _options = computed(() => { const options = this.options(); @@ -50,14 +65,54 @@ export class QueryParamSelectorComponent { return params && key ? params[key] || '' : ''; }); + _urlValues = computed(() => { + const raw = this._urlValue(); + return raw + ? raw + .split(',') + .map((value) => value.trim()) + .filter(Boolean) + : []; + }); + + _value = computed(() => + this.multiple() + ? (this.pendingValues() ?? this._urlValues()) + : this._urlValue(), + ); + _handleSelectionChange(event: MatSelectChange): void { - const newValue = event.value; - - this.router.navigate([], { - queryParams: { [this.queryParamKey()]: newValue }, - queryParamsHandling: 'merge', - }); + if (this.multiple()) { + this.pendingValues.set(event.value ?? []); + return; + } + this.commit(event.value || null); this.handleSelectionChange.emit(event); } + + _handleOpenedChange(opened: boolean): void { + if (opened || !this.multiple()) { + return; + } + + const pending = this.pendingValues(); + this.pendingValues.set(null); + + if (pending !== null) { + this.commit(pending.length > 0 ? pending.join(',') : null); + } + } + + private commit(value: string | null): void { + const pageKey = this.pageQueryParamKey(); + + this.router.navigate([], { + queryParams: { + [this.queryParamKey()]: value, + ...(pageKey ? { [pageKey]: 0 } : {}), + }, + queryParamsHandling: 'merge', + }); + } } From 328ef2938c04f29f52d8eb77ce24fc42c8845788 Mon Sep 17 00:00:00 2001 From: "noemi.kallweit" Date: Mon, 10 Aug 2026 16:27:42 +0200 Subject: [PATCH 082/114] feat(keyword-search): add wrapper to news filters --- .../news-results/news-results.component.html | 28 ++++++++++--------- .../news-results/news-results.component.scss | 15 +++++++++- .../news-results/news-results.component.ts | 2 ++ .../ui/filter-card/filter-card.component.html | 1 + .../ui/filter-card/filter-card.component.scss | 10 +++++++ .../ui/filter-card/filter-card.component.ts | 9 ++++++ 6 files changed, 51 insertions(+), 14 deletions(-) create mode 100644 webapp/src/app/shared/ui/filter-card/filter-card.component.html create mode 100644 webapp/src/app/shared/ui/filter-card/filter-card.component.scss create mode 100644 webapp/src/app/shared/ui/filter-card/filter-card.component.ts diff --git a/webapp/src/app/modules/keywords-search/search-results/news-results/news-results.component.html b/webapp/src/app/modules/keywords-search/search-results/news-results/news-results.component.html index a2edb88e..fa8728fe 100644 --- a/webapp/src/app/modules/keywords-search/search-results/news-results/news-results.component.html +++ b/webapp/src/app/modules/keywords-search/search-results/news-results/news-results.component.html @@ -1,19 +1,21 @@
    - + + - + + diff --git a/webapp/src/app/shared/ui/filter-card/filter-card.component.scss b/webapp/src/app/shared/ui/filter-card/filter-card.component.scss new file mode 100644 index 00000000..1bec30f6 --- /dev/null +++ b/webapp/src/app/shared/ui/filter-card/filter-card.component.scss @@ -0,0 +1,10 @@ +:host { + display: flex; + align-items: center; + gap: 0.75rem; + padding: 8px 12px; + border: 1px solid var(--sg-border); + border-radius: 10px; + background: var(--sg-surface); + box-sizing: border-box; +} diff --git a/webapp/src/app/shared/ui/filter-card/filter-card.component.ts b/webapp/src/app/shared/ui/filter-card/filter-card.component.ts new file mode 100644 index 00000000..7ef6a7a0 --- /dev/null +++ b/webapp/src/app/shared/ui/filter-card/filter-card.component.ts @@ -0,0 +1,9 @@ +import { Component } from '@angular/core'; + +@Component({ + selector: 'app-filter-card', + standalone: true, + templateUrl: './filter-card.component.html', + styleUrl: './filter-card.component.scss', +}) +export class FilterCardComponent {} From 98a1214a4d19ef5541f4af23805e1466f6d8bd46 Mon Sep 17 00:00:00 2001 From: "noemi.kallweit" Date: Mon, 27 Jul 2026 21:49:18 +0200 Subject: [PATCH 083/114] feat(news-details): remove highlighting of orphaned keywords --- .../news-detail/news-detail.component.html | 3 +- .../news-detail/news-detail.component.ts | 43 +++++++------------ 2 files changed, 16 insertions(+), 30 deletions(-) diff --git a/webapp/src/app/modules/news-detail/news-detail.component.html b/webapp/src/app/modules/news-detail/news-detail.component.html index 4f7a14b7..64ab14dd 100644 --- a/webapp/src/app/modules/news-detail/news-detail.component.html +++ b/webapp/src/app/modules/news-detail/news-detail.component.html @@ -230,8 +230,7 @@ »{{ topic.source_keyword }}«

    - Im Artikel hervorgehoben · klicken zum Suche zu - öffnen + Im Artikel hervorgehoben - klicken zum Springen

    } @else {

    diff --git a/webapp/src/app/modules/news-detail/news-detail.component.ts b/webapp/src/app/modules/news-detail/news-detail.component.ts index 707f191f..dd3e4b99 100644 --- a/webapp/src/app/modules/news-detail/news-detail.component.ts +++ b/webapp/src/app/modules/news-detail/news-detail.component.ts @@ -200,36 +200,23 @@ export class NewsDetailComponent implements OnInit { ); } } - const orphanColors = [ - 'var(--sg-primary)', - 'var(--sg-blue-highlight)', - 'var(--sg-success)', - 'var(--sg-warning)', - 'var(--sg-error)', - ]; - let orphanIdx = 0; let html = this.escapeHtml(text); - if (keywords.length) { - [...keywords] - .sort((a, b) => b.length - a.length) - .forEach((kw) => { - let color = keywordColorMap.get(kw.toLowerCase()); - if (!color) { - color = orphanColors[orphanIdx % orphanColors.length]; - orphanIdx++; - } - const kwHtml = this.escapeHtml(kw); - const re = new RegExp( - `(${this.escapeRegex(kwHtml)}[\\w\\u00C0-\\u024F]*)`, - 'gi', - ); - html = html.replace( - re, - `$1`, - ); - }); - } + [...keywords] + .sort((a, b) => b.length - a.length) + .forEach((kw) => { + const color = keywordColorMap.get(kw.toLowerCase()); + if (!color) return; + const kwHtml = this.escapeHtml(kw); + const re = new RegExp( + `(${this.escapeRegex(kwHtml)}[\\w\\u00C0-\\u024F]*)`, + 'gi', + ); + html = html.replace( + re, + `$1`, + ); + }); return this.sanitizer.bypassSecurityTrustHtml(html); } From a511c16fb1701f0197288bfa7a1b7e571b62c6b0 Mon Sep 17 00:00:00 2001 From: "noemi.kallweit" Date: Mon, 27 Jul 2026 22:04:28 +0200 Subject: [PATCH 084/114] fix(news-details): change topic highlight text --- webapp/src/app/modules/news-detail/news-detail.component.html | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/webapp/src/app/modules/news-detail/news-detail.component.html b/webapp/src/app/modules/news-detail/news-detail.component.html index 64ab14dd..24307372 100644 --- a/webapp/src/app/modules/news-detail/news-detail.component.html +++ b/webapp/src/app/modules/news-detail/news-detail.component.html @@ -230,7 +230,8 @@ »{{ topic.source_keyword }}«

    - Im Artikel hervorgehoben - klicken zum Springen + Im Artikel hervorgehoben - klicken, um zum + ersten Vorkommen zu springen.

    } @else {

    From 79dad5dfb010a9f3bc683f6808e6441f1ee23fcc Mon Sep 17 00:00:00 2001 From: "noemi.kallweit" Date: Mon, 27 Jul 2026 22:19:13 +0200 Subject: [PATCH 085/114] fix(news-details): change navigation to always go back to news list --- webapp/src/app/modules/news-detail/news-detail.component.ts | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/webapp/src/app/modules/news-detail/news-detail.component.ts b/webapp/src/app/modules/news-detail/news-detail.component.ts index dd3e4b99..8d9448a1 100644 --- a/webapp/src/app/modules/news-detail/news-detail.component.ts +++ b/webapp/src/app/modules/news-detail/news-detail.component.ts @@ -6,7 +6,6 @@ import { ViewChild, inject, } from '@angular/core'; -import { Location } from '@angular/common'; import { HttpClient } from '@angular/common/http'; import { ActivatedRoute, Router, RouterLink } from '@angular/router'; import { MatButtonModule } from '@angular/material/button'; @@ -66,7 +65,6 @@ export class NewsDetailComponent implements OnInit { private readonly route = inject(ActivatedRoute); private readonly httpClient = inject(HttpClient); private readonly worksService = inject(WorksService); - private readonly location = inject(Location); private readonly sanitizer = inject(DomSanitizer); article: NewsArticleDetail | null = null; @@ -150,7 +148,7 @@ export class NewsDetailComponent implements OnInit { } navigateBack(): void { - this.location.back(); + this.router.navigate(['/news']); } formatDate(dateStr?: string | null): string { From e5284a79c985044db1d2be09d377a5e0e93f4459 Mon Sep 17 00:00:00 2001 From: "noemi.kallweit" Date: Mon, 27 Jul 2026 22:28:15 +0200 Subject: [PATCH 086/114] fix(news-details): prevent keyword acronyms from highlighting unrelated words --- .../src/app/modules/news-detail/news-detail.component.ts | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/webapp/src/app/modules/news-detail/news-detail.component.ts b/webapp/src/app/modules/news-detail/news-detail.component.ts index 8d9448a1..fdbb74f9 100644 --- a/webapp/src/app/modules/news-detail/news-detail.component.ts +++ b/webapp/src/app/modules/news-detail/news-detail.component.ts @@ -206,8 +206,15 @@ export class NewsDetailComponent implements OnInit { const color = keywordColorMap.get(kw.toLowerCase()); if (!color) return; const kwHtml = this.escapeHtml(kw); + const escaped = this.escapeRegex(kwHtml); + const before = '(? Date: Mon, 27 Jul 2026 22:31:00 +0200 Subject: [PATCH 087/114] feat(sidebar): change 'News' to 'Nachrichten' --- webapp/src/app/shared/ui/app-menu/app-menu.component.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/webapp/src/app/shared/ui/app-menu/app-menu.component.ts b/webapp/src/app/shared/ui/app-menu/app-menu.component.ts index 52d86a73..40d4bfb6 100644 --- a/webapp/src/app/shared/ui/app-menu/app-menu.component.ts +++ b/webapp/src/app/shared/ui/app-menu/app-menu.component.ts @@ -107,7 +107,7 @@ export class AppMenuComponent { disabled: false, }, { - label: 'News', + label: 'Nachrichten', icon: NEWS_ICON, route: '/news', disabled: false, From e2ae0c660a7ebc48f248af366a14423405bd4d80 Mon Sep 17 00:00:00 2001 From: "noemi.kallweit" Date: Mon, 10 Aug 2026 17:50:11 +0200 Subject: [PATCH 088/114] refactor(news-list): re-style search bar and filters to improve alignment --- .../src/app/modules/news/news.component.html | 32 +++++++++-------- .../src/app/modules/news/news.component.scss | 36 +++++++++++++------ webapp/src/app/modules/news/news.component.ts | 25 +++++++------ 3 files changed, 58 insertions(+), 35 deletions(-) diff --git a/webapp/src/app/modules/news/news.component.html b/webapp/src/app/modules/news/news.component.html index c5fcd597..e0848c56 100644 --- a/webapp/src/app/modules/news/news.component.html +++ b/webapp/src/app/modules/news/news.component.html @@ -18,18 +18,24 @@

    - - - Relevant - Nicht relevant - - + + + + @if (!isSearching()) { + + } +
    diff --git a/webapp/src/app/modules/news/news.component.scss b/webapp/src/app/modules/news/news.component.scss index d668b89a..14ecda37 100644 --- a/webapp/src/app/modules/news/news.component.scss +++ b/webapp/src/app/modules/news/news.component.scss @@ -44,20 +44,36 @@ color: var(--sg-text-muted); } +$card-min-width: 380px; + .additional-filters { - display: flex; - align-items: center; - flex-wrap: wrap; - gap: 40px; + display: grid; + grid-template-columns: repeat(auto-fill, minmax($card-min-width, 1fr)); + align-items: stretch; + gap: 1.5rem; padding: 0 1rem 1rem; + + app-year-range-slider { + display: flex; + } + + ::ng-deep app-year-range-slider .year-filter { + height: 100%; + } + + ::ng-deep .mat-mdc-form-field-subscript-wrapper { + display: none; + } + + ::ng-deep .mat-mdc-form-field-icon-prefix { + padding: 0 4px 0 10px; + } } -.relevance-field { - width: 180px; -} - -.year-field { - min-width: 280px; +.relevance-field, +.sort-order-field { + flex: 1; + min-width: 0; } @media (max-width: 600px) { diff --git a/webapp/src/app/modules/news/news.component.ts b/webapp/src/app/modules/news/news.component.ts index 9d916390..13b99041 100644 --- a/webapp/src/app/modules/news/news.component.ts +++ b/webapp/src/app/modules/news/news.component.ts @@ -7,12 +7,10 @@ import { signal, } from '@angular/core'; import { HttpClient, HttpParams } from '@angular/common/http'; -import { FormControl, ReactiveFormsModule } from '@angular/forms'; +import { FormControl } from '@angular/forms'; import { ActivatedRoute, Router } from '@angular/router'; import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; import { debounceTime, merge } from 'rxjs'; -import { MatFormFieldModule } from '@angular/material/form-field'; -import { MatSelectModule } from '@angular/material/select'; import { WorksService } from '../../api'; import { @@ -24,7 +22,11 @@ import { NewsCardComponent, NEWS_MIN_YEAR, } from '../../shared/ui/news-card/news-card.component'; -import { SelectorOption } from '../../shared/ui/query-param-selector/query-param-selector.component'; +import { + QueryParamSelectorComponent, + SelectorOption, +} from '../../shared/ui/query-param-selector/query-param-selector.component'; +import { FilterCardComponent } from '../../shared/ui/filter-card/filter-card.component'; import { YearRangeSliderComponent } from '../../shared/ui/year-range-slider/year-range-slider.component'; interface NewsArticle extends NewsArticleBase { @@ -44,11 +46,10 @@ type SortOrder = 'desc' | 'asc'; @Component({ selector: 'app-news', imports: [ - ReactiveFormsModule, - MatFormFieldModule, - MatSelectModule, CardSearchComponent, NewsCardComponent, + FilterCardComponent, + QueryParamSelectorComponent, YearRangeSliderComponent, ], templateUrl: './news.component.html', @@ -64,11 +65,16 @@ export class NewsComponent implements OnInit { readonly minYear = NEWS_MIN_YEAR; readonly maxYear = new Date().getFullYear(); - private readonly sortingDirectionOptionsAll: SelectorOption[] = [ + readonly sortingDirectionOptionsAll: SelectorOption[] = [ { value: 'desc', display_name: 'Neueste zuerst' }, { value: 'asc', display_name: 'Älteste zuerst' }, ]; + readonly relevanceOptions: SelectorOption[] = [ + { value: 'relevant', display_name: 'Relevant' }, + { value: 'not_relevant', display_name: 'Nicht relevant' }, + ]; + readonly relevanceFilter = new FormControl([], { nonNullable: true, }); @@ -85,9 +91,6 @@ export class NewsComponent implements OnInit { readonly searchQuery = signal(''); readonly isSearching = computed(() => this.searchQuery().trim().length > 0); - readonly sortingDirectionOptions = computed(() => - this.isSearching() ? [] : this.sortingDirectionOptionsAll, - ); readonly page = computed(() => ({ page: this.currentPage, From fe5e816551527e2930c47034a08409297c7e4337 Mon Sep 17 00:00:00 2001 From: "noemi.kallweit" Date: Mon, 10 Aug 2026 18:22:48 +0200 Subject: [PATCH 089/114] refactor(wordcloud): extract wordcloud into its own component --- .../research-wordcloud.component.html | 27 +++ .../research-wordcloud.component.scss | 50 ++++++ .../research-wordcloud.component.ts | 163 ++++++++++++++++++ .../person-overview.component.html | 31 +--- .../person-overview.component.scss | 51 ------ .../person-overview.component.ts | 137 +++------------ 6 files changed, 266 insertions(+), 193 deletions(-) create mode 100644 webapp/src/app/modules/person-overview/components/research-wordcloud/research-wordcloud.component.html create mode 100644 webapp/src/app/modules/person-overview/components/research-wordcloud/research-wordcloud.component.scss create mode 100644 webapp/src/app/modules/person-overview/components/research-wordcloud/research-wordcloud.component.ts diff --git a/webapp/src/app/modules/person-overview/components/research-wordcloud/research-wordcloud.component.html b/webapp/src/app/modules/person-overview/components/research-wordcloud/research-wordcloud.component.html new file mode 100644 index 00000000..b83e601c --- /dev/null +++ b/webapp/src/app/modules/person-overview/components/research-wordcloud/research-wordcloud.component.html @@ -0,0 +1,27 @@ +@if (loading) { +
    Forschungsthemen werden geladen ...
    +} @else if (loadFailed) { +
    + Forschungsthemen konnten nicht geladen werden. +
    +} @else if (words.length) { +
    + @for (word of words; track word.name) { + + } +
    +} @else { +

    Keine Forschungsthemen gefunden.

    +} diff --git a/webapp/src/app/modules/person-overview/components/research-wordcloud/research-wordcloud.component.scss b/webapp/src/app/modules/person-overview/components/research-wordcloud/research-wordcloud.component.scss new file mode 100644 index 00000000..b4fc014a --- /dev/null +++ b/webapp/src/app/modules/person-overview/components/research-wordcloud/research-wordcloud.component.scss @@ -0,0 +1,50 @@ +:host { + display: block; + min-height: 420px; +} + +.word-cloud-chart { + width: 100%; + min-height: 420px; + display: flex; + flex-wrap: wrap; + align-content: center; + align-items: baseline; + justify-content: center; + gap: 0.35em 1em; + padding: 1.5rem 1rem; + box-sizing: border-box; +} + +.word-cloud-word { + appearance: none; + border: none; + background: none; + padding: 0; + margin: 0; + font-family: 'Open Sans', Arial, sans-serif; + line-height: 1.1; + cursor: pointer; + transition: transform 0.15s ease; + + &:hover:not(:disabled), + &:focus-visible { + transform: scale(1.08); + outline: none; + } + + &:disabled { + cursor: default; + } +} + +.word-cloud-state { + margin: 0; + min-height: 420px; + display: flex; + align-items: center; + justify-content: center; + color: var(--sg-text-muted); + font-size: 14px; + text-align: center; +} diff --git a/webapp/src/app/modules/person-overview/components/research-wordcloud/research-wordcloud.component.ts b/webapp/src/app/modules/person-overview/components/research-wordcloud/research-wordcloud.component.ts new file mode 100644 index 00000000..77f1ddc4 --- /dev/null +++ b/webapp/src/app/modules/person-overview/components/research-wordcloud/research-wordcloud.component.ts @@ -0,0 +1,163 @@ +import { Component, EventEmitter, Input, Output } from '@angular/core'; +import { MatTooltipModule } from '@angular/material/tooltip'; + +import { topicHierarchyColor } from '../../../../resolvers/utils/topic-colors'; +import { TopicLegendTopic } from '../../../../resolvers/utils/topic-legend'; +import { buildTopicHierarchyTooltip } from '../../../../resolvers/utils/topic-tooltip'; + +export interface WordCloudTopicOccurrence { + name: string; + topicId: string; + year: number | undefined; + fieldId: string | undefined; + fieldName: string | undefined; + domainId: string | undefined; + domainName: string | undefined; + subfieldId: string | undefined; + subfieldName: string | undefined; +} + +export interface WordCloudWord { + name: string; + topicId: string; + color: string; + fontSize: number; + fontWeight: number; + tooltip: string; +} + +export interface ResearchWordcloud { + words: WordCloudWord[]; + legendTopics: TopicLegendTopic[]; +} + +const displayedWordLimit = 30; +const minimumFontSize = 12; +const maximumFontSize = 32; + +export function buildResearchWordcloud( + occurrences: WordCloudTopicOccurrence[], + startYear: number | undefined, + endYear: number | undefined, +): ResearchWordcloud { + const counts = new Map(); + const legendTopicsByName = new Map(); + + for (const occurrence of occurrences) { + if (!isWithinYearRange(occurrence.year, startYear, endYear)) { + continue; + } + + counts.set(occurrence.name, (counts.get(occurrence.name) ?? 0) + 1); + + if (!legendTopicsByName.has(occurrence.name)) { + legendTopicsByName.set(occurrence.name, { + id: occurrence.topicId, + name: occurrence.name, + field_id: occurrence.fieldId, + field_name: occurrence.fieldName, + domain_id: occurrence.domainId, + domain_name: occurrence.domainName, + subfield_id: occurrence.subfieldId, + subfield_name: occurrence.subfieldName, + }); + } + } + + if (counts.size === 0) { + return { words: [], legendTopics: [] }; + } + + const values = Array.from(counts.values()); + const minimumValue = Math.min(...values); + const maximumValue = Math.max(...values); + const intensity = (value: number): number => + maximumValue === minimumValue + ? 1 + : (value - minimumValue) / (maximumValue - minimumValue); + + const displayed = Array.from(counts.entries()) + .sort((left, right) => right[1] - left[1]) + .slice(0, displayedWordLimit); + + const legendTopics = displayed + .map(([name]) => legendTopicsByName.get(name)) + .filter((topic): topic is TopicLegendTopic => Boolean(topic)); + + const words = displayed.map(([name, value]): WordCloudWord => { + const legendTopic = legendTopicsByName.get(name); + const scale = intensity(value); + + return { + name, + topicId: legendTopic?.id ?? '', + color: topicHierarchyColor(legendTopic), + fontSize: Math.round( + minimumFontSize + scale * (maximumFontSize - minimumFontSize), + ), + fontWeight: scale > 0.66 ? 800 : scale > 0.33 ? 600 : 400, + tooltip: buildTopicHierarchyTooltip({ + topicName: name, + subfieldName: legendTopic?.subfield_name, + fieldName: legendTopic?.field_name, + domainName: legendTopic?.domain_name, + }), + }; + }); + + return { words: centreWords(words), legendTopics }; +} + +function isWithinYearRange( + year: number | undefined, + startYear: number | undefined, + endYear: number | undefined, +): boolean { + if (startYear !== undefined && (year === undefined || year < startYear)) { + return false; + } + + if (endYear !== undefined && (year === undefined || year > endYear)) { + return false; + } + + return true; +} + +function centreWords(words: WordCloudWord[]): WordCloudWord[] { + const centred: WordCloudWord[] = []; + + words.forEach((word, index) => { + if (index % 2 === 0) { + centred.push(word); + return; + } + + centred.unshift(word); + }); + + return centred; +} + +@Component({ + selector: 'app-research-wordcloud', + standalone: true, + imports: [MatTooltipModule], + templateUrl: './research-wordcloud.component.html', + styleUrl: './research-wordcloud.component.scss', +}) +export class ResearchWordcloudComponent { + @Input() words: WordCloudWord[] = []; + @Input() loading = false; + @Input() loadFailed = false; + + @Output() wordSelect = new EventEmitter(); + + selectWord(word: WordCloudWord): void { + if (!word.topicId) { + return; + } + + this.wordSelect.emit(word); + } +} diff --git a/webapp/src/app/modules/person-overview/person-overview.component.html b/webapp/src/app/modules/person-overview/person-overview.component.html index 7b4404b9..09009f29 100644 --- a/webapp/src/app/modules/person-overview/person-overview.component.html +++ b/webapp/src/app/modules/person-overview/person-overview.component.html @@ -19,30 +19,11 @@ (topicSelect)="onTimelineTopicSelect($event)" (yearSelect)="onTimelineYearSelect($event)" (loadEarlierYears)="onTimelineLoadEarlierYears()"> -
    - @if (loadingWordCloud) { -
    Forschungsthemen werden geladen ...
    - } @else if (wordCloudWords.length) { -
    - @for (word of wordCloudWords; track word.name) { - - } -
    - } @else if (wordCloudEmpty) { -

    Keine Forschungsthemen gefunden.

    - } -
    + diff --git a/webapp/src/app/modules/person-overview/person-overview.component.scss b/webapp/src/app/modules/person-overview/person-overview.component.scss index 02d0ba58..740a7e09 100644 --- a/webapp/src/app/modules/person-overview/person-overview.component.scss +++ b/webapp/src/app/modules/person-overview/person-overview.component.scss @@ -3,54 +3,3 @@ display: block; box-sizing: border-box; } - -.word-cloud-view { - min-height: 420px; -} - -.word-cloud-chart { - width: 100%; - min-height: 420px; - display: flex; - flex-wrap: wrap; - align-content: center; - align-items: baseline; - justify-content: center; - gap: 0.35em 1em; - padding: 1.5rem 1rem; - box-sizing: border-box; -} - -.word-cloud-word { - appearance: none; - border: none; - background: none; - padding: 0; - margin: 0; - font-family: 'Open Sans', Arial, sans-serif; - line-height: 1.1; - cursor: pointer; - transition: transform 0.15s ease; - - &:hover:not(:disabled), - &:focus-visible { - transform: scale(1.08); - outline: none; - } - - &:disabled { - cursor: default; - } -} - -.word-cloud-state, -.word-cloud-empty { - margin: 0; - min-height: 420px; - display: flex; - align-items: center; - justify-content: center; - color: var(--sg-text-muted); - font-size: 14px; - text-align: center; -} diff --git a/webapp/src/app/modules/person-overview/person-overview.component.ts b/webapp/src/app/modules/person-overview/person-overview.component.ts index ff8821fd..53f97bfa 100644 --- a/webapp/src/app/modules/person-overview/person-overview.component.ts +++ b/webapp/src/app/modules/person-overview/person-overview.component.ts @@ -1,8 +1,6 @@ -import { CommonModule } from '@angular/common'; import { Component, DestroyRef, OnInit, inject } from '@angular/core'; import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; import { ActivatedRoute, ParamMap, Router } from '@angular/router'; -import { MatTooltipModule } from '@angular/material/tooltip'; import { combineLatest, distinctUntilChanged, map } from 'rxjs'; import { TopicCount, TopicsByYear, WorksService } from '../../api'; @@ -14,27 +12,19 @@ import { TopicTimelineElement, TopicTimelineTopic, } from './components/research-timeline/research-timeline.component'; +import { + buildResearchWordcloud, + ResearchWordcloudComponent, + WordCloudTopicOccurrence, + WordCloudWord, +} from './components/research-wordcloud/research-wordcloud.component'; import { workQueryParamKeys } from '../../resolvers/work-page.resolver'; import { TopicLegendTopic } from '../../resolvers/utils/topic-legend'; -import { topicHierarchyColor } from '../../resolvers/utils/topic-colors'; -import { buildTopicHierarchyTooltip } from '../../resolvers/utils/topic-tooltip'; - -export interface WordCloudWord { - name: string; - value: number; - topicId: string | undefined; - fieldName: string | undefined; - domainName: string | undefined; - color: string; - fontSize: number; - fontWeight: number; - tooltip: string; -} @Component({ selector: 'app-person-overview', standalone: true, - imports: [CommonModule, ResearchTimelineComponent, MatTooltipModule], + imports: [ResearchTimelineComponent, ResearchWordcloudComponent], templateUrl: './person-overview.component.html', styleUrl: './person-overview.component.scss', }) @@ -73,19 +63,9 @@ export class PersonOverviewComponent implements OnInit { wordCloudWords: WordCloudWord[] = []; wordCloudLegendTopics: TopicLegendTopic[] = []; loadingWordCloud = false; - wordCloudEmpty = false; + wordCloudLoadFailed = false; - private rawTopicOccurrences: Array<{ - name: string; - topicId: string; - year: number | undefined; - fieldId: string | undefined; - fieldName: string | undefined; - domainId: string | undefined; - domainName: string | undefined; - subfieldId: string | undefined; - subfieldName: string | undefined; - }> = []; + private rawTopicOccurrences: WordCloudTopicOccurrence[] = []; ngOnInit(): void { combineLatest(this.route.pathFromRoot.map((route) => route.paramMap)) @@ -351,14 +331,14 @@ export class PersonOverviewComponent implements OnInit { if (!authorId || authorId === '0') { this.wordCloudWords = []; this.wordCloudLegendTopics = []; - this.wordCloudEmpty = false; + this.wordCloudLoadFailed = false; this.loadingWordCloud = false; this.rawTopicOccurrences = []; return; } this.loadingWordCloud = true; - this.wordCloudEmpty = false; + this.wordCloudLoadFailed = false; this.wordCloudWords = []; this.wordCloudLegendTopics = []; @@ -389,104 +369,27 @@ export class PersonOverviewComponent implements OnInit { this.loadingWordCloud = false; - if (this.rawTopicOccurrences.length === 0) { - this.wordCloudLegendTopics = []; - this.wordCloudEmpty = true; - return; - } - setTimeout(() => this.rebuildWordCloud()); }, error: (error) => { console.error('Word cloud could not be loaded.', error); this.loadingWordCloud = false; + this.rawTopicOccurrences = []; this.wordCloudLegendTopics = []; - this.wordCloudEmpty = true; + this.wordCloudLoadFailed = true; }, }); } private rebuildWordCloud(): void { - const start = this.timelineStartYear; - const end = this.timelineEndYear; - const counts = new Map(); - const nameToId = new Map(); - const nameToColorInput = new Map(); + const wordCloud = buildResearchWordcloud( + this.rawTopicOccurrences, + this.timelineStartYear, + this.timelineEndYear, + ); - for (const occ of this.rawTopicOccurrences) { - if (start !== undefined && (occ.year === undefined || occ.year < start)) - continue; - if (end !== undefined && (occ.year === undefined || occ.year > end)) - continue; - counts.set(occ.name, (counts.get(occ.name) ?? 0) + 1); - if (!nameToId.has(occ.name)) { - nameToId.set(occ.name, occ.topicId); - nameToColorInput.set(occ.name, { - id: occ.topicId, - name: occ.name, - field_id: occ.fieldId, - field_name: occ.fieldName, - domain_id: occ.domainId, - domain_name: occ.domainName, - subfield_id: occ.subfieldId, - subfield_name: occ.subfieldName, - }); - } - } - - if (counts.size === 0) { - this.wordCloudWords = []; - this.wordCloudLegendTopics = []; - this.wordCloudEmpty = true; - return; - } - - this.wordCloudEmpty = false; - - const allValues = Array.from(counts.values()); - const minVal = Math.min(...allValues); - const maxVal = Math.max(...allValues); - const intensity = (v: number): number => - maxVal === minVal ? 1 : (v - minVal) / (maxVal - minVal); - - const sorted = Array.from(counts.entries()).sort((a, b) => b[1] - a[1]); - const topNames = sorted.slice(0, 30).map(([name]) => name); - - this.wordCloudLegendTopics = topNames - .map((name) => nameToColorInput.get(name)) - .filter((topic): topic is TopicLegendTopic => Boolean(topic)); - - const words = sorted.slice(0, 30).map(([name, value]): WordCloudWord => { - const t = intensity(value); - const colorInput = nameToColorInput.get(name); - return { - name, - value, - topicId: nameToId.get(name), - fieldName: colorInput?.field_name ?? undefined, - domainName: colorInput?.domain_name ?? undefined, - color: topicHierarchyColor(colorInput), - fontSize: Math.round(12 + t * (32 - 12)), - fontWeight: t > 0.66 ? 800 : t > 0.33 ? 600 : 400, - tooltip: buildTopicHierarchyTooltip({ - topicName: name, - subfieldName: colorInput?.subfield_name, - fieldName: colorInput?.field_name, - domainName: colorInput?.domain_name, - }), - }; - }); - - const centred: WordCloudWord[] = []; - words.forEach((word, i) => { - if (i % 2 === 0) { - centred.push(word); - } else { - centred.unshift(word); - } - }); - - this.wordCloudWords = centred; + this.wordCloudWords = wordCloud.words; + this.wordCloudLegendTopics = wordCloud.legendTopics; } private mapTimelineElements( From b6871b36182909af8b51b855976e89108eecf789 Mon Sep 17 00:00:00 2001 From: "noemi.kallweit" Date: Mon, 10 Aug 2026 18:38:40 +0200 Subject: [PATCH 090/114] refactor(wordcloud): use shared tooltip component --- .../research-wordcloud.component.html | 7 ++++--- .../research-wordcloud.component.ts | 21 ++++++++++--------- 2 files changed, 15 insertions(+), 13 deletions(-) diff --git a/webapp/src/app/modules/person-overview/components/research-wordcloud/research-wordcloud.component.html b/webapp/src/app/modules/person-overview/components/research-wordcloud/research-wordcloud.component.html index b83e601c..5c60ff3a 100644 --- a/webapp/src/app/modules/person-overview/components/research-wordcloud/research-wordcloud.component.html +++ b/webapp/src/app/modules/person-overview/components/research-wordcloud/research-wordcloud.component.html @@ -14,9 +14,10 @@ [style.fontSize.px]="word.fontSize" [style.fontWeight]="word.fontWeight" [disabled]="!word.topicId" - [matTooltip]="word.tooltip" - [matTooltipDisabled]="!word.tooltip" - matTooltipClass="topic-chip-tooltip" + [appComponentTooltip]="AppTopicTooltipComponent" + [tooltipInputs]="{ topicId: word.rawTopicId }" + [tooltipDisabled]="!word.rawTopicId" + [tooltipMaxWidth]="'500px'" (click)="selectWord(word)"> {{ word.name }} diff --git a/webapp/src/app/modules/person-overview/components/research-wordcloud/research-wordcloud.component.ts b/webapp/src/app/modules/person-overview/components/research-wordcloud/research-wordcloud.component.ts index 77f1ddc4..0b9f3e6b 100644 --- a/webapp/src/app/modules/person-overview/components/research-wordcloud/research-wordcloud.component.ts +++ b/webapp/src/app/modules/person-overview/components/research-wordcloud/research-wordcloud.component.ts @@ -1,9 +1,9 @@ import { Component, EventEmitter, Input, Output } from '@angular/core'; -import { MatTooltipModule } from '@angular/material/tooltip'; +import { ComponentTooltipDirective } from '../../../../directives/component-tooltip.directive'; +import { AppTopicTooltipComponent } from '../../../../shared/ui/app-topic-tooltip/app-topic-tooltip.component'; import { topicHierarchyColor } from '../../../../resolvers/utils/topic-colors'; import { TopicLegendTopic } from '../../../../resolvers/utils/topic-legend'; -import { buildTopicHierarchyTooltip } from '../../../../resolvers/utils/topic-tooltip'; export interface WordCloudTopicOccurrence { name: string; @@ -20,10 +20,10 @@ export interface WordCloudTopicOccurrence { export interface WordCloudWord { name: string; topicId: string; + rawTopicId: string; color: string; fontSize: number; fontWeight: number; - tooltip: string; } export interface ResearchWordcloud { @@ -91,17 +91,12 @@ export function buildResearchWordcloud( return { name, topicId: legendTopic?.id ?? '', + rawTopicId: stripOpenAlexId(legendTopic?.id), color: topicHierarchyColor(legendTopic), fontSize: Math.round( minimumFontSize + scale * (maximumFontSize - minimumFontSize), ), fontWeight: scale > 0.66 ? 800 : scale > 0.33 ? 600 : 400, - tooltip: buildTopicHierarchyTooltip({ - topicName: name, - subfieldName: legendTopic?.subfield_name, - fieldName: legendTopic?.field_name, - domainName: legendTopic?.domain_name, - }), }; }); @@ -139,14 +134,20 @@ function centreWords(words: WordCloudWord[]): WordCloudWord[] { return centred; } +function stripOpenAlexId(id: string | null | undefined): string { + return (id ?? '').replace('https://openalex.org/', ''); +} + @Component({ selector: 'app-research-wordcloud', standalone: true, - imports: [MatTooltipModule], + imports: [ComponentTooltipDirective], templateUrl: './research-wordcloud.component.html', styleUrl: './research-wordcloud.component.scss', }) export class ResearchWordcloudComponent { + readonly AppTopicTooltipComponent = AppTopicTooltipComponent; + @Input() words: WordCloudWord[] = []; @Input() loading = false; @Input() loadFailed = false; From aa22fad67db2226c89b927a1e58afa7a7bf6e53a Mon Sep 17 00:00:00 2001 From: genja Date: Mon, 10 Aug 2026 20:43:17 +0200 Subject: [PATCH 091/114] added external link button --- .../projects/dfg-details/dfg-details.component.html | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/webapp/src/app/modules/projects/dfg-details/dfg-details.component.html b/webapp/src/app/modules/projects/dfg-details/dfg-details.component.html index c9b6c1e9..8d6c9db9 100644 --- a/webapp/src/app/modules/projects/dfg-details/dfg-details.component.html +++ b/webapp/src/app/modules/projects/dfg-details/dfg-details.component.html @@ -37,8 +37,11 @@ circle {{ getStatusDisplay(dfgProject.funding_end) }}
    - @if (dfgProject.link) { - + @if (dfgProject.page_url) { + open_in_new Zum Projekt @@ -218,10 +221,7 @@
    @if (getInstitutionsList().length > 0) {
    - @for ( - institution of getInstitutionsList(); - track institution.institute_id + (institution.role_key || '') - ) { + @for (institution of getInstitutionsList(); track $index) {
    @for (keyword of keywords; track keyword.llm_keyword.keyword) { 0) { @for (tag of tags(); track tag.label) { + [appComponentTooltip]="AppTopicTooltipComponent" + [tooltipInputs]="getFilterTopicInputs(filter.value)" + [tooltipMaxWidth]="'500px'"> label {{ filter.value diff --git a/webapp/src/app/modules/person-list/person-list.component.ts b/webapp/src/app/modules/person-list/person-list.component.ts index 43b342ec..4eac968f 100644 --- a/webapp/src/app/modules/person-list/person-list.component.ts +++ b/webapp/src/app/modules/person-list/person-list.component.ts @@ -46,6 +46,9 @@ import { import { SkTextDirective } from '../../custom-directives/sk-text.directive'; import { BookmarkService } from '../../shared/services/bookmark.service'; +import { ComponentTooltipDirective } from '../../directives/component-tooltip.directive'; +import { AppTopicTooltipComponent } from '../../shared/ui/app-topic-tooltip/app-topic-tooltip.component'; + type InstitutionYearFilterMode = 'in' | 'from' | 'between'; @Component({ @@ -62,17 +65,19 @@ type InstitutionYearFilterMode = 'in' | 'from' | 'between'; MatCheckboxModule, MatRadioModule, MatTooltipModule, + MatAutocompleteModule, TopicHierarchyComponent, PersonCardComponent, - SkTextDirective, - MatAutocompleteModule, CountryFlagComponent, + SkTextDirective, + ComponentTooltipDirective, ], templateUrl: './person-list.component.html', styleUrl: './person-list.component.scss', standalone: true, }) export class PersonListComponent { + readonly AppTopicTooltipComponent = AppTopicTooltipComponent; private readonly router = inject(Router); private readonly route = inject(ActivatedRoute); private readonly personsService = inject(PersonsService); @@ -477,6 +482,28 @@ export class PersonListComponent { }); } + getFilterTopicInputs(topicName: string): { topicId?: string; topic?: any } { + const topic = this.findPersonTopic(topicName); + if (topic?.id) { + return { topicId: topic.id }; + } + return { + topic: { + display_name: topicName, + description: this.getFilterTopicDescription(topicName) ?? undefined, + subfield: this.getFilterTopicSubfieldName(topicName) + ? { display_name: this.getFilterTopicSubfieldName(topicName)! } + : undefined, + field: this.getFilterTopicFieldName(topicName) + ? { display_name: this.getFilterTopicFieldName(topicName)! } + : undefined, + domain: this.getFilterTopicDomainName(topicName) + ? { display_name: this.getFilterTopicDomainName(topicName)! } + : undefined, + }, + }; + } + clearAllFilters(): void { this.selectedTopics.set(new Set()); this.institutionControl.setValue('', { emitEvent: false }); diff --git a/webapp/src/app/modules/person-overview/components/research-timeline/research-timeline.component.html b/webapp/src/app/modules/person-overview/components/research-timeline/research-timeline.component.html index 89bc937d..15ae9a94 100644 --- a/webapp/src/app/modules/person-overview/components/research-timeline/research-timeline.component.html +++ b/webapp/src/app/modules/person-overview/components/research-timeline/research-timeline.component.html @@ -171,11 +171,9 @@ type="button" class="main-topic-button" [disabled]="!getMainTopicItem(item)?.id" - [matTooltip]="getTopicTooltip(getMainTopicItem(item))" - matTooltipClass="topic-chip-tooltip" - [matTooltipDisabled]=" - !hasTopicTooltip(getMainTopicItem(item)) - " + [appComponentTooltip]="AppTopicTooltipComponent" + [tooltipInputs]="{ topicId: getMainTopicItem(item)?.id }" + [tooltipMaxWidth]="'500px'" (click)=" selectTopic(getMainTopicItem(item), [item.year]) "> @@ -208,6 +206,7 @@ trackBy: trackByTopic " class="timeline-topic-chip" + [topicId]="topic.id" [label]="topic.name" [count]="topic.count" [description]="getTopicDescription(topic)" @@ -289,11 +288,9 @@ type="button" class="main-topic-button" [disabled]="!phase.primaryTopic.id" - [matTooltip]="getTopicTooltip(phase.primaryTopic)" - matTooltipClass="topic-chip-tooltip" - [matTooltipDisabled]=" - !hasTopicTooltip(phase.primaryTopic) - " + [appComponentTooltip]="AppTopicTooltipComponent" + [tooltipInputs]="{ topicId: phase.primaryTopic.id }" + [tooltipMaxWidth]="'500px'" (click)=" selectTopic(phase.primaryTopic, getPhaseYears(phase)) "> @@ -309,6 +306,7 @@ ; @Input() elements: TopicTimelineElement[] = []; diff --git a/webapp/src/app/modules/projects/eu-cordis-details/eu-details.component.html b/webapp/src/app/modules/projects/eu-cordis-details/eu-details.component.html index 57049a65..8340ff10 100644 --- a/webapp/src/app/modules/projects/eu-cordis-details/eu-details.component.html +++ b/webapp/src/app/modules/projects/eu-cordis-details/eu-details.component.html @@ -245,6 +245,7 @@ track keyword.id || keyword.label ) { @for (topic of publication.topics; track topic.id) { info_outline - Der CC-News-Vergleich (hinterlegte Fläche, ab 2017) ist aktuell nur bei - deaktivierter Fuzzy-Suche verfügbar, da für Web-Nachrichten kein - Themen-Mapping existiert. + Der CC-News-Vergleich (hinterlegte Fläche, ab 2017) ist aktuell + nur bei deaktivierter Fuzzy-Suche verfügbar, da für + Web-Nachrichten kein Themen-Mapping existiert.
    } @@ -198,11 +198,11 @@
    @for (topic of selectedTrendTopics(); track $index) { } diff --git a/webapp/src/app/shared/ui/app-topic-tooltip/app-topic-tooltip.component.ts b/webapp/src/app/shared/ui/app-topic-tooltip/app-topic-tooltip.component.ts index f86a6750..7e6b8e6e 100644 --- a/webapp/src/app/shared/ui/app-topic-tooltip/app-topic-tooltip.component.ts +++ b/webapp/src/app/shared/ui/app-topic-tooltip/app-topic-tooltip.component.ts @@ -11,22 +11,36 @@ import { AppTopicCardComponent } from '../app-topic-card/app-topic-card.componen export class AppTopicTooltipComponent { private readonly topicsService = inject(TopicsV2Service); - topicId = input.required(); + topicId = input(undefined); + topic = input(undefined); _topic = signal(undefined); - _isLoading = signal(false); + constructor() { effect(() => { + const topicObj = this.topic(); const topicId = this.topicId(); - if (!topicId) { - this._topic.set(undefined); - } - this._isLoading.set(true); - this.topicsService.getTopicById(topicId).subscribe((topic) => { - this._topic.set(topic); + + if (topicObj) { + this._topic.set(topicObj); this._isLoading.set(false); - }); + } else if (topicId) { + const cleanId = topicId.replace('https://openalex.org/', ''); + this._isLoading.set(true); + this.topicsService.getTopicById(cleanId).subscribe({ + next: (fetchedTopic) => { + this._topic.set(fetchedTopic); + this._isLoading.set(false); + }, + error: () => { + this._isLoading.set(false); + }, + }); + } else { + this._topic.set(undefined); + this._isLoading.set(false); + } }); } } diff --git a/webapp/src/app/shared/ui/project-oa-topics/project-oa-topics.component.html b/webapp/src/app/shared/ui/project-oa-topics/project-oa-topics.component.html index 733594eb..857b5ed4 100644 --- a/webapp/src/app/shared/ui/project-oa-topics/project-oa-topics.component.html +++ b/webapp/src/app/shared/ui/project-oa-topics/project-oa-topics.component.html @@ -7,6 +7,8 @@
    @for (topic of getUniqueOATopics(); track $index) { - - {{ label }} + + {{ label() }} - @if (hasCount) { + @if (hasCount()) { - {{ count }} - @if (countIconName) { - {{ countIconName }} + [matTooltip]="normalizedCountTooltip()" + [matTooltipDisabled]="!normalizedCountTooltip()"> + {{ count() }} + @if (countIconName()) { + {{ + countIconName() + }} } } From aec735e09eb74274a58142315c0d64810b39a9c9 Mon Sep 17 00:00:00 2001 From: Kazgatari <56477241+Kazgatari@users.noreply.github.com> Date: Mon, 10 Aug 2026 23:01:20 +0200 Subject: [PATCH 094/114] fix: topic tooltip clipping --- .../app-topic-tooltip.component.ts | 22 ++++++++++++++++--- .../ui/topic-chip/topic-chip.component.ts | 19 +++++++++------- 2 files changed, 30 insertions(+), 11 deletions(-) diff --git a/webapp/src/app/shared/ui/app-topic-tooltip/app-topic-tooltip.component.ts b/webapp/src/app/shared/ui/app-topic-tooltip/app-topic-tooltip.component.ts index 7e6b8e6e..67c6b20e 100644 --- a/webapp/src/app/shared/ui/app-topic-tooltip/app-topic-tooltip.component.ts +++ b/webapp/src/app/shared/ui/app-topic-tooltip/app-topic-tooltip.component.ts @@ -20,23 +20,39 @@ export class AppTopicTooltipComponent { constructor() { effect(() => { const topicObj = this.topic(); - const topicId = this.topicId(); + const topicId = this.topicId() ?? topicObj?.id; - if (topicObj) { + const hasCompleteMetrics = Boolean( + topicObj && + (topicObj.description || + topicObj.works_count !== undefined || + topicObj.cited_by_count !== undefined), + ); + + if (hasCompleteMetrics && topicObj) { this._topic.set(topicObj); this._isLoading.set(false); } else if (topicId) { const cleanId = topicId.replace('https://openalex.org/', ''); + if (topicObj) { + this._topic.set(topicObj); + } this._isLoading.set(true); this.topicsService.getTopicById(cleanId).subscribe({ next: (fetchedTopic) => { - this._topic.set(fetchedTopic); + this._topic.set({ + ...topicObj, + ...fetchedTopic, + }); this._isLoading.set(false); }, error: () => { this._isLoading.set(false); }, }); + } else if (topicObj) { + this._topic.set(topicObj); + this._isLoading.set(false); } else { this._topic.set(undefined); this._isLoading.set(false); diff --git a/webapp/src/app/shared/ui/topic-chip/topic-chip.component.ts b/webapp/src/app/shared/ui/topic-chip/topic-chip.component.ts index 079d0990..06e85d5b 100644 --- a/webapp/src/app/shared/ui/topic-chip/topic-chip.component.ts +++ b/webapp/src/app/shared/ui/topic-chip/topic-chip.component.ts @@ -163,16 +163,13 @@ export class TopicChipComponent { return (this.countIcon() ?? '').trim(); }); - tooltipInputs = computed(() => { + readonly topicObject = computed(() => { const t = this.topic(); - const id = this.topicId(); if (t) { - return { topic: t }; + return t; } - if (id) { - return { topicId: id }; - } - const fallbackTopic: Topic = { + return { + id: this.topicId() ?? undefined, display_name: this.label(), description: this.description() ?? undefined, subfield: this.subfieldName() @@ -185,7 +182,13 @@ export class TopicChipComponent { ? { display_name: this.domainName() ?? undefined } : undefined, }; - return { topic: fallbackTopic }; + }); + + tooltipInputs = computed(() => { + return { + topic: this.topicObject(), + topicId: this.topicId() ?? this.topic()?.id ?? undefined, + }; }); handleClick(): void { From 0a465bc7e10c60f56ead53cbdc5633963d75fd33 Mon Sep 17 00:00:00 2001 From: Kazgatari <56477241+Kazgatari@users.noreply.github.com> Date: Mon, 10 Aug 2026 23:18:39 +0200 Subject: [PATCH 095/114] changed author and institution chips as well --- .../app-author-chip.component.html | 2 +- .../app-author-tooltip.component.ts | 37 ++++++++++++++----- .../app-institution-chip.component.html | 5 ++- .../app-institution-tooltip.component.ts | 37 ++++++++++++++----- 4 files changed, 60 insertions(+), 21 deletions(-) diff --git a/webapp/src/app/shared/ui/app-author-chip/app-author-chip.component.html b/webapp/src/app/shared/ui/app-author-chip/app-author-chip.component.html index f7f171da..9bf69e9f 100644 --- a/webapp/src/app/shared/ui/app-author-chip/app-author-chip.component.html +++ b/webapp/src/app/shared/ui/app-author-chip/app-author-chip.component.html @@ -1,7 +1,7 @@ diff --git a/webapp/src/app/shared/ui/app-author-tooltip/app-author-tooltip.component.ts b/webapp/src/app/shared/ui/app-author-tooltip/app-author-tooltip.component.ts index 5b428fcb..2afd0614 100644 --- a/webapp/src/app/shared/ui/app-author-tooltip/app-author-tooltip.component.ts +++ b/webapp/src/app/shared/ui/app-author-tooltip/app-author-tooltip.component.ts @@ -23,7 +23,8 @@ import { AppAuthorCardComponent } from '../app-author-card/app-author-card.compo export class AppAuthorTooltipComponent { private readonly authorsService = inject(AuthorsV2Service); - authorId = input.required(); + authorId = input(undefined); + author = input(undefined); _author = signal(undefined); @@ -31,15 +32,33 @@ export class AppAuthorTooltipComponent { constructor() { effect(() => { - const authorId = this.authorId(); - if (!authorId) { - this._author.set(undefined); - } - this._isLoading.set(true); - this.authorsService.getAuthorById(authorId).subscribe((author) => { - this._author.set(author); + const authorObj = this.author(); + const authorId = this.authorId() ?? authorObj?.id; + + if (authorObj) { + this._author.set(authorObj); this._isLoading.set(false); - }); + } + + if (authorId) { + const cleanId = authorId.replace('https://openalex.org/', ''); + this._isLoading.set(true); + this.authorsService.getAuthorById(cleanId).subscribe({ + next: (fetchedAuthor) => { + this._author.set({ + ...authorObj, + ...fetchedAuthor, + }); + this._isLoading.set(false); + }, + error: () => { + this._isLoading.set(false); + }, + }); + } else if (!authorObj) { + this._author.set(undefined); + this._isLoading.set(false); + } }); } } diff --git a/webapp/src/app/shared/ui/app-institution-chip/app-institution-chip.component.html b/webapp/src/app/shared/ui/app-institution-chip/app-institution-chip.component.html index b643580c..17139d66 100644 --- a/webapp/src/app/shared/ui/app-institution-chip/app-institution-chip.component.html +++ b/webapp/src/app/shared/ui/app-institution-chip/app-institution-chip.component.html @@ -1,7 +1,10 @@ diff --git a/webapp/src/app/shared/ui/app-institution-tooltip/app-institution-tooltip.component.ts b/webapp/src/app/shared/ui/app-institution-tooltip/app-institution-tooltip.component.ts index 2204746e..0f4e5deb 100644 --- a/webapp/src/app/shared/ui/app-institution-tooltip/app-institution-tooltip.component.ts +++ b/webapp/src/app/shared/ui/app-institution-tooltip/app-institution-tooltip.component.ts @@ -11,7 +11,8 @@ import { AppInstitutionCardComponent } from '../app-institution-card/app-institu export class AppInstitutionTooltipComponent { private readonly institutionsService = inject(InstitutionsV2Service); - institutionId = input.required(); + institutionId = input(undefined); + institution = input(undefined); _institution = signal(undefined); @@ -19,17 +20,33 @@ export class AppInstitutionTooltipComponent { constructor() { effect(() => { - const institutionId = this.institutionId(); - if (!institutionId) { - this._institution.set(undefined); + const institutionObj = this.institution(); + const institutionId = this.institutionId() ?? institutionObj?.id; + + if (institutionObj) { + this._institution.set(institutionObj); + this._isLoading.set(false); } - this._isLoading.set(true); - this.institutionsService - .getInstitutionById2(institutionId) - .subscribe((institution) => { - this._institution.set(institution); - this._isLoading.set(false); + + if (institutionId) { + const cleanId = institutionId.replace('https://openalex.org/', ''); + this._isLoading.set(true); + this.institutionsService.getInstitutionById2(cleanId).subscribe({ + next: (fetchedInst) => { + this._institution.set({ + ...institutionObj, + ...fetchedInst, + }); + this._isLoading.set(false); + }, + error: () => { + this._isLoading.set(false); + }, }); + } else if (!institutionObj) { + this._institution.set(undefined); + this._isLoading.set(false); + } }); } } From af9f9a25da532500f101a38b2c439a0a5bbe7da7 Mon Sep 17 00:00:00 2001 From: Kazgatari <56477241+Kazgatari@users.noreply.github.com> Date: Mon, 10 Aug 2026 23:21:42 +0200 Subject: [PATCH 096/114] added screen padding --- webapp/src/app/directives/component-tooltip.directive.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/webapp/src/app/directives/component-tooltip.directive.ts b/webapp/src/app/directives/component-tooltip.directive.ts index 9a945510..daccfa52 100644 --- a/webapp/src/app/directives/component-tooltip.directive.ts +++ b/webapp/src/app/directives/component-tooltip.directive.ts @@ -130,12 +130,14 @@ export class ComponentTooltipDirective implements OnDestroy { .flexibleConnectedTo(this.elementRef) .withPositions(positions) .withFlexibleDimensions(false) + .withViewportMargin(12) .withPush(true); this.overlayRef = this.overlay.create({ positionStrategy, scrollStrategy: this.overlay.scrollStrategies.reposition(), panelClass: 'app-tooltip-panel', + maxWidth: this.tooltipMaxWidth() ?? 'calc(100vw - 24px)', }); const portal = new ComponentPortal(this.component(), null, this.injector); From e4b3d0a9a9577d657cf3de52093c7255775631e4 Mon Sep 17 00:00:00 2001 From: genja Date: Tue, 11 Aug 2026 08:53:25 +0200 Subject: [PATCH 097/114] replaced the is_forbidden function with check function from auth --- service/src/main/inse/projects/logic.py | 36 ------------------------ service/src/main/inse/projects/router.py | 16 +++++------ 2 files changed, 7 insertions(+), 45 deletions(-) diff --git a/service/src/main/inse/projects/logic.py b/service/src/main/inse/projects/logic.py index d224fc7f..69c99c61 100644 --- a/service/src/main/inse/projects/logic.py +++ b/service/src/main/inse/projects/logic.py @@ -9,42 +9,6 @@ from inse.projects.model import EuCordisProjectType logger = logging.getLogger(__name__) - -async def is_projects_access_forbidden( - access_token_metadata: AccessTokenMetadata, - raw_oa_institution_id: str | None, - raw_oa_author_id: str | None, -) -> bool: - """ - Determines if access to projects is forbidden based on the provided access token metadata - and the raw OpenAlex institution and author IDs. - - Args: - access_token_metadata (AccessTokenMetadata): Metadata from the access token. - raw_oa_institution_id (str | None): The raw OpenAlex institution ID. - raw_oa_author_id (str | None): The raw OpenAlex author ID. - - Returns: - bool: True if access is forbidden, False otherwise. - """ - effective_institution_id = access_token_metadata.effective_institution_id - - if raw_oa_institution_id and effective_institution_id != raw_oa_institution_id: - return True - - if raw_oa_author_id: - authors_profile = await author_service.get_author_by_id(raw_oa_author_id) - if not authors_profile: - return True # Author not found, access forbidden - - authors_last_known_institution_ids = [inst.id.split("/")[-1] for inst in (authors_profile.last_known_institutions)] - authors_affiliation_institution_ids = [aff.institution.id.split("/")[-1] for aff in (authors_profile.affiliations)] - print(f"Author's last known institution IDs: {authors_last_known_institution_ids}, {authors_affiliation_institution_ids}") - if effective_institution_id not in authors_last_known_institution_ids and effective_institution_id not in authors_affiliation_institution_ids: - return True # Effective institution ID does not match any of the author's last known institutions - - return False - async def get_dfg_author_names_by_ids(author_ids: list[int]) -> list[str] | None: try: body = { diff --git a/service/src/main/inse/projects/router.py b/service/src/main/inse/projects/router.py index d0430d63..0a7a5fae 100644 --- a/service/src/main/inse/projects/router.py +++ b/service/src/main/inse/projects/router.py @@ -7,9 +7,6 @@ from inse.auth.service import CurrentUserAccessTokenPayloadDep from inse.institutions.institutions_search_client import ( InstitutionsSearchClient, ) -from inse.projects.logic import ( - is_projects_access_forbidden -) from inse.institutions.router import get_institutions_search_client from inse.models.bund_project_details import BundProjectDetails from inse.models.dfg_project_details import DfgProjectDetails @@ -33,6 +30,7 @@ from inse.projects.model import ( SortDirection, ) from inse.tags import Tags +from inse.auth.service import can_fetch_gdpr_relevant_data from fastapi import HTTPException as HttpException logger = logging.getLogger(__name__) @@ -146,8 +144,8 @@ async def get_dfg_projects( sort_direction, fuzzy, ) - is_forbidden = await is_projects_access_forbidden(access_token_metadata, raw_oa_institution_id, author_id) - if is_forbidden: + is_allowed = await can_fetch_gdpr_relevant_data(access_token = access_token_metadata, raw_oa_author_id = author_id, raw_oa_institution_id = raw_oa_institution_id) + if not is_allowed: raise HttpException( status_code=403, detail="Access denied for the provided author ID or institution ID", @@ -266,8 +264,8 @@ async def search_bund_projects( Query(description="Use OpenAlex topic-id resolution if true, otherwise raw keyword search."), ] = False, ) -> BundProjectPage: - is_forbidden = await is_projects_access_forbidden(access_token_metadata, raw_oa_institution_id, None) - if is_forbidden: + is_allowed = await can_fetch_gdpr_relevant_data(access_token = access_token_metadata, raw_oa_author_id = None, raw_oa_institution_id = raw_oa_institution_id) + if not is_allowed: raise HttpException( status_code=403, detail="Access denied for the provided author ID or institution ID", @@ -450,8 +448,8 @@ async def search_eu_cordis_projects_endpoint( sort_direction, fuzzy, ) - is_forbidden = await is_projects_access_forbidden(access_token_metadata, raw_oa_institution_id, author_id) - if is_forbidden: + is_allowed = await can_fetch_gdpr_relevant_data(access_token = access_token_metadata, raw_oa_author_id = author_id, raw_oa_institution_id = raw_oa_institution_id) + if not is_allowed: raise HttpException( status_code=403, detail="Access denied for the provided author ID or institution ID", From b0dd0e509d9a5bd3f2c32b42a9bcb0c7e1433353 Mon Sep 17 00:00:00 2001 From: louis-19041904 Date: Tue, 11 Aug 2026 09:03:54 +0200 Subject: [PATCH 098/114] add legend tooltip component --- .../legend-tooltip.component.html | 10 ++++ .../legend-tooltip.component.scss | 46 +++++++++++++++++++ .../legend-tooltip.component.ts | 23 ++++++++++ .../topic-legend/topic-legend.component.html | 26 +++++++---- .../ui/topic-legend/topic-legend.component.ts | 10 +++- 5 files changed, 106 insertions(+), 9 deletions(-) create mode 100644 webapp/src/app/shared/ui/legend-tooltip/legend-tooltip.component.html create mode 100644 webapp/src/app/shared/ui/legend-tooltip/legend-tooltip.component.scss create mode 100644 webapp/src/app/shared/ui/legend-tooltip/legend-tooltip.component.ts diff --git a/webapp/src/app/shared/ui/legend-tooltip/legend-tooltip.component.html b/webapp/src/app/shared/ui/legend-tooltip/legend-tooltip.component.html new file mode 100644 index 00000000..2ed8354f --- /dev/null +++ b/webapp/src/app/shared/ui/legend-tooltip/legend-tooltip.component.html @@ -0,0 +1,10 @@ +
    +
    {{ name() }}
    + @if (hierarchy()) { +
    {{ hierarchy() }}
    + } + @if (description()) { +
    +

    {{ description() }}

    + } +
    diff --git a/webapp/src/app/shared/ui/legend-tooltip/legend-tooltip.component.scss b/webapp/src/app/shared/ui/legend-tooltip/legend-tooltip.component.scss new file mode 100644 index 00000000..a6ab156e --- /dev/null +++ b/webapp/src/app/shared/ui/legend-tooltip/legend-tooltip.component.scss @@ -0,0 +1,46 @@ +:host { + --topic-border: color-mix( + in srgb, + hsl(var(--topic-color)) 72%, + var(--sg-color-mix-base) + ); + --topic-background: color-mix( + in srgb, + hsl(var(--topic-color)) 8%, + var(--sg-color-mix-base) + ); +} + +.legend-tooltip-card { + display: flex; + flex-direction: column; + gap: 0.5rem; + padding: 1rem; + border-radius: var(--sg-radius-sm); + background-color: var(--topic-background); + border: 1px solid var(--topic-border); + color: var(--sg-text); +} + +.legend-tooltip-title { + font-weight: 600; + font-size: 1rem; +} + +.legend-tooltip-hierarchy { + color: var(--sg-text-muted); + font-size: 0.875rem; +} + +.legend-tooltip-divider { + margin: 0; + border: none; + border-top: 1px solid var(--topic-border); +} + +.legend-tooltip-description { + margin: 0; + color: var(--sg-text); + font-size: 0.875rem; + line-height: 1.4; +} diff --git a/webapp/src/app/shared/ui/legend-tooltip/legend-tooltip.component.ts b/webapp/src/app/shared/ui/legend-tooltip/legend-tooltip.component.ts new file mode 100644 index 00000000..76390e98 --- /dev/null +++ b/webapp/src/app/shared/ui/legend-tooltip/legend-tooltip.component.ts @@ -0,0 +1,23 @@ +import { Component, computed, input } from '@angular/core'; + +@Component({ + host: { + '[style.--topic-color]': 'topicColorVar()', + }, + selector: 'app-legend-tooltip', + standalone: true, + templateUrl: './legend-tooltip.component.html', + styleUrl: './legend-tooltip.component.scss', +}) +export class LegendTooltipComponent { + readonly name = input.required(); + readonly hierarchy = input(null); + readonly description = input(null); + readonly color = input(null); + + readonly topicColorVar = computed(() => { + const color = this.color(); + if (!color) return ''; + return color.replace('hsl(', '').replace(')', ''); + }); +} diff --git a/webapp/src/app/shared/ui/topic-legend/topic-legend.component.html b/webapp/src/app/shared/ui/topic-legend/topic-legend.component.html index 330ccc2b..d86fe307 100644 --- a/webapp/src/app/shared/ui/topic-legend/topic-legend.component.html +++ b/webapp/src/app/shared/ui/topic-legend/topic-legend.component.html @@ -54,10 +54,15 @@ class="topic-legend-field" [class.topic-legend-entry-active]="isFieldActive(group)" [attr.aria-pressed]="selectable ? isFieldActive(group) : null" - [matTooltip]="group.tooltip" - [matTooltipDisabled]="!group.tooltip" - matTooltipClass="topic-chip-tooltip" - matTooltipPosition="above" + [appComponentTooltip]="LegendTooltipComponent" + [tooltipInputs]="{ + name: group.name, + hierarchy: group.domainName, + description: group.description, + color: group.color, + }" + [tooltipDisabled]="!group.description" + [tooltipMaxWidth]="'420px'" (click)="toggleField(group)"> {{ item.name }} diff --git a/webapp/src/app/shared/ui/topic-legend/topic-legend.component.ts b/webapp/src/app/shared/ui/topic-legend/topic-legend.component.ts index ec776260..1d835d70 100644 --- a/webapp/src/app/shared/ui/topic-legend/topic-legend.component.ts +++ b/webapp/src/app/shared/ui/topic-legend/topic-legend.component.ts @@ -2,6 +2,8 @@ import { CommonModule } from '@angular/common'; import { Component, EventEmitter, Input, Output } from '@angular/core'; import { MatIconModule } from '@angular/material/icon'; import { MatTooltipModule } from '@angular/material/tooltip'; +import { ComponentTooltipDirective } from '../../../directives/component-tooltip.directive'; +import { LegendTooltipComponent } from '../legend-tooltip/legend-tooltip.component'; import { TopicLegendGroup, TopicLegendItem, @@ -13,11 +15,17 @@ export type TopicLegendVariant = 'default' | 'compact'; @Component({ selector: 'app-topic-legend', standalone: true, - imports: [CommonModule, MatIconModule, MatTooltipModule], + imports: [ + CommonModule, + MatIconModule, + MatTooltipModule, + ComponentTooltipDirective, + ], templateUrl: './topic-legend.component.html', styleUrl: './topic-legend.component.scss', }) export class TopicLegendComponent { + readonly LegendTooltipComponent = LegendTooltipComponent; @Input() groups: TopicLegendGroup[] = []; @Input() title = 'Farben nach Fachgebiet'; @Input() infoTooltip = From c66fcff9061116c00516cefbb8fba14e820a066f Mon Sep 17 00:00:00 2001 From: genja Date: Tue, 11 Aug 2026 09:14:33 +0200 Subject: [PATCH 099/114] hot-fix: check for 403 only if author or institution id is persistent --- service/src/main/inse/projects/router.py | 39 +++++++++++++----------- 1 file changed, 21 insertions(+), 18 deletions(-) diff --git a/service/src/main/inse/projects/router.py b/service/src/main/inse/projects/router.py index 0a7a5fae..3c3f2c97 100644 --- a/service/src/main/inse/projects/router.py +++ b/service/src/main/inse/projects/router.py @@ -144,12 +144,13 @@ async def get_dfg_projects( sort_direction, fuzzy, ) - is_allowed = await can_fetch_gdpr_relevant_data(access_token = access_token_metadata, raw_oa_author_id = author_id, raw_oa_institution_id = raw_oa_institution_id) - if not is_allowed: - raise HttpException( - status_code=403, - detail="Access denied for the provided author ID or institution ID", - ) + if (author_id or raw_oa_institution_id): + is_allowed = await can_fetch_gdpr_relevant_data(access_token = access_token_metadata, raw_oa_author_id = author_id, raw_oa_institution_id = raw_oa_institution_id) + if not is_allowed: + raise HttpException( + status_code=403, + detail="Access denied for the provided author ID or institution ID", + ) return await projects_service.get_dfg_projects( institutions_search_client=institutions_search_client, raw_oa_institution_id=raw_oa_institution_id, @@ -264,12 +265,13 @@ async def search_bund_projects( Query(description="Use OpenAlex topic-id resolution if true, otherwise raw keyword search."), ] = False, ) -> BundProjectPage: - is_allowed = await can_fetch_gdpr_relevant_data(access_token = access_token_metadata, raw_oa_author_id = None, raw_oa_institution_id = raw_oa_institution_id) - if not is_allowed: - raise HttpException( - status_code=403, - detail="Access denied for the provided author ID or institution ID", - ) + if (raw_oa_institution_id): + is_allowed = await can_fetch_gdpr_relevant_data(access_token = access_token_metadata, raw_oa_author_id = None, raw_oa_institution_id = raw_oa_institution_id) + if not is_allowed: + raise HttpException( + status_code=403, + detail="Access denied for the provided author ID or institution ID", + ) return await projects_service.search_bund_projects_with_filters( institutions_search_client=institutions_search_client, executing_agency=executing_agency, @@ -448,12 +450,13 @@ async def search_eu_cordis_projects_endpoint( sort_direction, fuzzy, ) - is_allowed = await can_fetch_gdpr_relevant_data(access_token = access_token_metadata, raw_oa_author_id = author_id, raw_oa_institution_id = raw_oa_institution_id) - if not is_allowed: - raise HttpException( - status_code=403, - detail="Access denied for the provided author ID or institution ID", - ) + if (author_id or raw_oa_institution_id): + is_allowed = await can_fetch_gdpr_relevant_data(access_token = access_token_metadata, raw_oa_author_id = author_id, raw_oa_institution_id = raw_oa_institution_id) + if not is_allowed: + raise HttpException( + status_code=403, + detail="Access denied for the provided author ID or institution ID", + ) return await search_eu_cordis_projects( institutions_search_client=institutions_search_client, raw_oa_institution_id=raw_oa_institution_id, From 3d092b02f3b0fe64df5ad1e53ee9e6d159d4ff88 Mon Sep 17 00:00:00 2001 From: Farajollahi Date: Tue, 11 Aug 2026 10:16:25 +0200 Subject: [PATCH 100/114] refactor(dashboard): split dashboard logic into dedicated services - add separate services for top authors, project statuses and topic treemaps - extract shared project ID and statistics logic - move common period and institution helpers into common module - add individual top-author API routes - load top-author analyses independently in the frontend - remove unused dashboard code and helper functions - reduce the main dashboard service to general statistics and topic visualizations --- .../inse/dashboard/bund_topics_service.py | 142 + service/src/main/inse/dashboard/common.py | 92 + .../main/inse/dashboard/dfg_topics_service.py | 103 + .../main/inse/dashboard/eu_topics_service.py | 109 + service/src/main/inse/dashboard/model.py | 5 + .../inse/dashboard/project_ids_service.py | 102 + .../dashboard/project_statistics_service.py | 122 + .../inse/dashboard/project_status_service.py | 513 ++++ service/src/main/inse/dashboard/router.py | 120 +- service/src/main/inse/dashboard/service.py | 2312 +---------------- .../src/main/inse/dashboard/test_service.py | 403 +-- .../inse/dashboard/top_authors_service.py | 1100 ++++++++ .../dashboard/dashboard-statistics.service.ts | 42 +- 13 files changed, 2681 insertions(+), 2484 deletions(-) create mode 100644 service/src/main/inse/dashboard/bund_topics_service.py create mode 100644 service/src/main/inse/dashboard/common.py create mode 100644 service/src/main/inse/dashboard/dfg_topics_service.py create mode 100644 service/src/main/inse/dashboard/eu_topics_service.py create mode 100644 service/src/main/inse/dashboard/project_ids_service.py create mode 100644 service/src/main/inse/dashboard/project_statistics_service.py create mode 100644 service/src/main/inse/dashboard/project_status_service.py create mode 100644 service/src/main/inse/dashboard/top_authors_service.py diff --git a/service/src/main/inse/dashboard/bund_topics_service.py b/service/src/main/inse/dashboard/bund_topics_service.py new file mode 100644 index 00000000..5a241c49 --- /dev/null +++ b/service/src/main/inse/dashboard/bund_topics_service.py @@ -0,0 +1,142 @@ +import hashlib +from collections import defaultdict +from typing import Any + +from inse.institutions.institutions_search_client import InstitutionsSearchClient +from inse.integrations import elasticsearch +from inse.model import ESCluster, ESIndex +from inse.projects import service as projects_service + +from .model import BundProjectTopics, DfgProjectKeyword, DfgProjectTopic +from .common import ( + dashboard_period as _dashboard_period, + normalize_institution_id as _normalize_institution_id, + raw_institution_id as _raw_institution_id, +) + + +async def get_dashboard_bund_topics( + institution_id: str, + organization_name: str, + from_year: int | None = None, + to_year: int | None = None, +) -> BundProjectTopics: + normalized_id = _normalize_institution_id(institution_id) + period = _dashboard_period(from_year, to_year) + page_size = 1000 + page_number = 0 + project_ids: set[str] = set() + + while True: + projects = await projects_service.search_bund_projects_with_filters( + institutions_search_client=InstitutionsSearchClient(), + executing_agency=None, + raw_oa_institution_id=_raw_institution_id(normalized_id), + title=None, + keywords=None, + funding_arts=None, + topic_ids=None, + filter_topic_ids=None, + funding_start_years=None, + funding_end_years=None, + active_from_year=period[0], + active_to_year=period[1], + countries=None, + page=page_number, + size=page_size, + sort_by="id", + sort_direction="asc", + fuzzy=False, + ) + project_ids.update( + project.funding_code + for project in projects.elements + if project.funding_code + ) + if len(project_ids) >= projects.total or not projects.elements: + break + page_number += 1 + + topics: dict[str, dict[str, Any]] = {} + matched_project_ids: set[str] = set() + if project_ids: + mapping_project_ids = sorted( + hashlib.sha256(project_id.encode("utf-8")).hexdigest() + for project_id in project_ids + ) + async for hit in elasticsearch.scan( + index=str(ESIndex.PROJECTS_BUND_TOPICS), + query={"terms": {"project_id": mapping_project_ids}}, + source=["project_id", "keyword", "topic_matches"], + page_size=1000, + cluster=ESCluster.INSE, + ): + source = hit.get("_source", {}) + project_id = str(source.get("project_id") or "") + if not project_id: + continue + keyword = str(source.get("keyword") or "").strip() + matched_project_ids.add(project_id) + for match in source.get("topic_matches", []): + topic_id = str(match.get("topic_id") or "") + if not topic_id: + continue + topic = topics.setdefault( + topic_id, + { + "id": topic_id, + "name": str(match.get("topic_display_name") or topic_id), + "subfield": match.get("subfield"), + "field": match.get("field"), + "domain": match.get("domain"), + "project_ids": set(), + "keywords": {}, + }, + ) + topic["project_ids"].add(project_id) + if keyword: + topic["keywords"].setdefault(keyword, set()).add(project_id) + + field_project_ids: dict[str, set[str]] = defaultdict(set) + subfield_project_ids: dict[tuple[str, str], set[str]] = defaultdict(set) + for topic in topics.values(): + field_name = str(topic["field"] or "") + subfield_name = str(topic["subfield"] or "") + field_project_ids[field_name].update(topic["project_ids"]) + subfield_project_ids[(field_name, subfield_name)].update(topic["project_ids"]) + + topic_list = [ + DfgProjectTopic( + id=topic["id"], + name=topic["name"], + subfield=topic["subfield"], + field=topic["field"], + domain=topic["domain"], + project_count=len(topic["project_ids"]), + field_project_count=len(field_project_ids[str(topic["field"] or "")]), + subfield_project_count=len( + subfield_project_ids[ + (str(topic["field"] or ""), str(topic["subfield"] or "")) + ] + ), + keywords=sorted( + [ + DfgProjectKeyword( + name=keyword, + project_count=len(keyword_project_ids), + ) + for keyword, keyword_project_ids in topic["keywords"].items() + ], + key=lambda entry: (-entry.project_count, entry.name), + ), + ) + for topic in topics.values() + ] + topic_list.sort(key=lambda topic: (-topic.project_count, topic.name, topic.id)) + return BundProjectTopics( + institution_id=normalized_id, + organization_name=organization_name, + project_count=len(project_ids), + matched_project_count=len(matched_project_ids), + topics=topic_list, + ) diff --git a/service/src/main/inse/dashboard/common.py b/service/src/main/inse/dashboard/common.py new file mode 100644 index 00000000..e670b2f7 --- /dev/null +++ b/service/src/main/inse/dashboard/common.py @@ -0,0 +1,92 @@ +from typing import Any, Literal + +from fastapi import HTTPException, status + +DashboardPeriod = tuple[int | None, int | None] + + +def dashboard_period( + from_year: int | None = None, + to_year: int | None = None, +) -> DashboardPeriod: + if from_year is not None and to_year is not None and from_year > to_year: + raise HTTPException( + status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, + detail="from_year must be less than or equal to to_year.", + ) + return from_year, to_year + + +def project_overlap_filter( + start_field: str, + end_field: str, + period: DashboardPeriod, + *, + missing_end_is_ongoing: bool = False, +) -> dict[str, Any] | None: + from_year, to_year = period + filters: list[dict[str, Any]] = [] + if to_year is not None: + filters.append({"range": {start_field: {"lte": to_year}}}) + if from_year is not None: + end_filter: dict[str, Any] = {"range": {end_field: {"gte": from_year}}} + if missing_end_is_ongoing: + end_filter = { + "bool": { + "should": [ + end_filter, + {"bool": {"must_not": {"exists": {"field": end_field}}}}, + ], + "minimum_should_match": 1, + } + } + filters.append(end_filter) + return {"bool": {"filter": filters}} if filters else None + + +def project_boundary_year_filter( + start_field: str, + end_field: str, + period: DashboardPeriod, + date_format: Literal["iso", "de", "year"], +) -> dict[str, Any] | None: + from_year, to_year = period + filters: list[dict[str, Any]] = [] + if to_year is not None: + if date_format == "year": + filters.append({"range": {start_field: {"lte": to_year}}}) + else: + last_day = ( + f"{to_year}-12-31" if date_format == "iso" else f"31.12.{to_year}" + ) + filters.append({"range": {start_field: {"lte": last_day}}}) + if from_year is not None: + if date_format == "year": + filters.append({"range": {end_field: {"gte": from_year}}}) + else: + first_day = ( + f"{from_year}-01-01" if date_format == "iso" else f"01.01.{from_year}" + ) + filters.append({"range": {end_field: {"gte": first_day}}}) + return {"bool": {"filter": filters}} if filters else None + + +def normalize_institution_id(value: str) -> str: + return ( + value + if value.startswith("https://openalex.org/") + else f"https://openalex.org/{value}" + ) + + +def raw_institution_id(value: str) -> str: + return normalize_institution_id(value).removeprefix("https://openalex.org/") + + +def institution_works_query(institution_id: str) -> dict[str, Any]: + return { + "nested": { + "path": "authorships.institutions", + "query": {"term": {"authorships.institutions.id": institution_id}}, + } + } diff --git a/service/src/main/inse/dashboard/dfg_topics_service.py b/service/src/main/inse/dashboard/dfg_topics_service.py new file mode 100644 index 00000000..2332c809 --- /dev/null +++ b/service/src/main/inse/dashboard/dfg_topics_service.py @@ -0,0 +1,103 @@ +from collections import defaultdict +from typing import Any + +from inse.integrations import elasticsearch +from inse.model import ESCluster, ESIndex + +from .model import DfgProjectKeyword, DfgProjectTopic, DfgProjectTopics +from .common import normalize_institution_id as _normalize_institution_id +from .project_ids_service import _get_dfg_project_ids_from_projects_service + + +async def get_dashboard_dfg_topics( + institution_id: str, + organization_name: str, + from_year: int | None = None, + to_year: int | None = None, +) -> DfgProjectTopics: + normalized_id = _normalize_institution_id(institution_id) + project_ids = await _get_dfg_project_ids_from_projects_service( + normalized_id, + from_year=from_year, + to_year=to_year, + ) + topics: dict[str, dict[str, Any]] = {} + matched_project_ids: set[str] = set() + + if project_ids: + async for hit in elasticsearch.scan( + index=str(ESIndex.PROJECTS_DFG_OPENALEX_TOPICS), + query={"terms": {"project_id": project_ids}}, + source=["project_id", "keyword", "topic_matches"], + page_size=1000, + cluster=ESCluster.INSE, + ): + source = hit.get("_source", {}) + project_id = str(source.get("project_id") or "") + if not project_id: + continue + keyword = str(source.get("keyword") or "").strip() + matched_project_ids.add(project_id) + for match in source.get("topic_matches", []): + topic_id = str(match.get("topic_id") or "") + if not topic_id: + continue + topic = topics.setdefault( + topic_id, + { + "id": topic_id, + "name": str(match.get("topic_display_name") or topic_id), + "subfield": match.get("subfield"), + "field": match.get("field"), + "domain": match.get("domain"), + "project_ids": set(), + "keywords": {}, + }, + ) + topic["project_ids"].add(project_id) + if keyword: + topic["keywords"].setdefault(keyword, set()).add(project_id) + + field_project_ids: dict[str, set[str]] = defaultdict(set) + subfield_project_ids: dict[tuple[str, str], set[str]] = defaultdict(set) + for topic in topics.values(): + field_name = str(topic["field"] or "") + subfield_name = str(topic["subfield"] or "") + field_project_ids[field_name].update(topic["project_ids"]) + subfield_project_ids[(field_name, subfield_name)].update(topic["project_ids"]) + + topic_list = [ + DfgProjectTopic( + id=topic["id"], + name=topic["name"], + subfield=topic["subfield"], + field=topic["field"], + domain=topic["domain"], + project_count=len(topic["project_ids"]), + field_project_count=len(field_project_ids[str(topic["field"] or "")]), + subfield_project_count=len( + subfield_project_ids[ + (str(topic["field"] or ""), str(topic["subfield"] or "")) + ] + ), + keywords=sorted( + [ + DfgProjectKeyword( + name=keyword, + project_count=len(keyword_project_ids), + ) + for keyword, keyword_project_ids in topic["keywords"].items() + ], + key=lambda entry: (-entry.project_count, entry.name), + ), + ) + for topic in topics.values() + ] + topic_list.sort(key=lambda topic: (-topic.project_count, topic.name, topic.id)) + return DfgProjectTopics( + institution_id=normalized_id, + organization_name=organization_name, + project_count=len(project_ids), + matched_project_count=len(matched_project_ids), + topics=topic_list, + ) diff --git a/service/src/main/inse/dashboard/eu_topics_service.py b/service/src/main/inse/dashboard/eu_topics_service.py new file mode 100644 index 00000000..a4cbeaee --- /dev/null +++ b/service/src/main/inse/dashboard/eu_topics_service.py @@ -0,0 +1,109 @@ +from collections import defaultdict +from typing import Any + +from inse.integrations import elasticsearch +from inse.model import ESCluster, ESIndex + +from .model import DfgProjectKeyword, DfgProjectTopic, EuProjectTopics +from .common import normalize_institution_id as _normalize_institution_id +from .project_ids_service import _get_eu_project_ids_from_projects_service + + +async def get_dashboard_eu_topics( + institution_id: str, + organization_name: str, + from_year: int | None = None, + to_year: int | None = None, +) -> EuProjectTopics: + normalized_id = _normalize_institution_id(institution_id) + project_ids = await _get_eu_project_ids_from_projects_service( + normalized_id, + from_year=from_year, + to_year=to_year, + ) + topics: dict[str, dict[str, Any]] = {} + matched_project_ids: set[str] = set() + + if project_ids: + mapping_indices = ( + ESIndex.PROJECTS_CORDIS_EU_FP7_TOPICS_MAPPING, + ESIndex.PROJECTS_CORDIS_EU_H2020_TOPICS, + ESIndex.PROJECTS_CORDIS_EU_HEUROPE_TOPICS, + ) + for mapping_index in mapping_indices: + async for hit in elasticsearch.scan( + index=str(mapping_index), + query={"terms": {"project_id": project_ids}}, + source=["project_id", "keyword", "topic_matches"], + page_size=1000, + cluster=ESCluster.INSE, + ): + source = hit.get("_source", {}) + project_id = str(source.get("project_id") or "") + if not project_id: + continue + keyword = str(source.get("keyword") or "").strip() + matched_project_ids.add(project_id) + for match in source.get("topic_matches", []): + topic_id = str(match.get("topic_id") or "") + if not topic_id: + continue + topic = topics.setdefault( + topic_id, + { + "id": topic_id, + "name": str(match.get("topic_display_name") or topic_id), + "subfield": match.get("subfield"), + "field": match.get("field"), + "domain": match.get("domain"), + "project_ids": set(), + "keywords": {}, + }, + ) + topic["project_ids"].add(project_id) + if keyword: + topic["keywords"].setdefault(keyword, set()).add(project_id) + + field_project_ids: dict[str, set[str]] = defaultdict(set) + subfield_project_ids: dict[tuple[str, str], set[str]] = defaultdict(set) + for topic in topics.values(): + field_name = str(topic["field"] or "") + subfield_name = str(topic["subfield"] or "") + field_project_ids[field_name].update(topic["project_ids"]) + subfield_project_ids[(field_name, subfield_name)].update(topic["project_ids"]) + + topic_list = [ + DfgProjectTopic( + id=topic["id"], + name=topic["name"], + subfield=topic["subfield"], + field=topic["field"], + domain=topic["domain"], + project_count=len(topic["project_ids"]), + field_project_count=len(field_project_ids[str(topic["field"] or "")]), + subfield_project_count=len( + subfield_project_ids[ + (str(topic["field"] or ""), str(topic["subfield"] or "")) + ] + ), + keywords=sorted( + [ + DfgProjectKeyword( + name=keyword, + project_count=len(keyword_project_ids), + ) + for keyword, keyword_project_ids in topic["keywords"].items() + ], + key=lambda entry: (-entry.project_count, entry.name), + ), + ) + for topic in topics.values() + ] + topic_list.sort(key=lambda topic: (-topic.project_count, topic.name, topic.id)) + return EuProjectTopics( + institution_id=normalized_id, + organization_name=organization_name, + project_count=len(project_ids), + matched_project_count=len(matched_project_ids), + topics=topic_list, + ) diff --git a/service/src/main/inse/dashboard/model.py b/service/src/main/inse/dashboard/model.py index ada6c020..bbc047db 100644 --- a/service/src/main/inse/dashboard/model.py +++ b/service/src/main/inse/dashboard/model.py @@ -98,6 +98,11 @@ class TopAuthorStatistics(BaseModel): news: list[TopAuthor] +class TopAuthorAnalysis(BaseModel): + institution_id: str + authors: list[TopAuthor] + + class TopicHeatmapValue(BaseModel): year: int count: int diff --git a/service/src/main/inse/dashboard/project_ids_service.py b/service/src/main/inse/dashboard/project_ids_service.py new file mode 100644 index 00000000..e5bbb37d --- /dev/null +++ b/service/src/main/inse/dashboard/project_ids_service.py @@ -0,0 +1,102 @@ +from inse.institutions.institutions_search_client import InstitutionsSearchClient +from inse.projects import service as projects_service +from inse.projects.model import EuCordisProjectType + +from .common import ( + dashboard_period as _dashboard_period, + raw_institution_id as _raw_institution_id, +) + + +async def _get_dfg_project_ids_from_projects_service( + institution_id: str, + from_year: int | None = None, + to_year: int | None = None, +) -> list[str]: + """Returns every matching DFG project ID through the canonical project service.""" + period = _dashboard_period(from_year, to_year) + page_size = 1000 + page_number = 0 + project_ids: set[str] = set() + + while True: + projects = await projects_service.get_dfg_projects( + institutions_search_client=InstitutionsSearchClient(), + raw_oa_institution_id=_raw_institution_id(institution_id), + author_id=None, + author_filter_ids=None, + institution_ids=None, + keywords=None, + topic_ids=None, + filter_topic_ids=None, + title=None, + funding_start_years=( + [str(year) for year in range(1900, period[1] + 1)] + if period[1] is not None + else None + ), + funding_end_years=( + [str(year) for year in range(period[0], 2101)] + if period[0] is not None + else None + ), + page=page_number, + size=page_size, + sort_by="id", + sort_direction="asc", + fuzzy=False, + skip_enrichment=True, + ) + project_ids.update(project.id for project in projects.elements if project.id) + if len(project_ids) >= projects.total or not projects.elements: + break + page_number += 1 + + return sorted(project_ids) + + +async def _get_eu_project_ids_from_projects_service( + institution_id: str, + from_year: int | None = None, + to_year: int | None = None, +) -> list[str]: + """Loads all organization EU project IDs from the canonical project service.""" + period = _dashboard_period(from_year, to_year) + page_size = 1000 + page_number = 0 + project_ids: set[str] = set() + + while True: + projects = await projects_service.search_eu_cordis_projects( + institutions_search_client=InstitutionsSearchClient(), + raw_oa_institution_id=_raw_institution_id(institution_id), + author_id=None, + author_ids=None, + organization_ids=None, + organization_names=None, + project_types=list(EuCordisProjectType), + keywords=None, + topic_ids=None, + filter_topic_ids=None, + title=None, + funding_start_years=None, + funding_end_years=None, + active_from_year=period[0], + active_to_year=period[1], + countries=None, + framework_programmes=None, + funding_schemes=None, + statuses=None, + page=page_number, + size=page_size, + sort_by="id", + sort_direction="asc", + fuzzy=False, + skip_enrichment=True, + ) + project_ids.update(project.id for project in projects.elements if project.id) + if len(project_ids) >= projects.total or not projects.elements: + break + page_number += 1 + + return sorted(project_ids) diff --git a/service/src/main/inse/dashboard/project_statistics_service.py b/service/src/main/inse/dashboard/project_statistics_service.py new file mode 100644 index 00000000..10f68bde --- /dev/null +++ b/service/src/main/inse/dashboard/project_statistics_service.py @@ -0,0 +1,122 @@ +from inse.institutions.institutions_search_client import InstitutionsSearchClient +from inse.projects import service as projects_service +from inse.projects.model import EuCordisProjectType + +from .common import ( + dashboard_period as _dashboard_period, + normalize_institution_id as _normalize_institution_id, + raw_institution_id as _raw_institution_id, +) +from .model import DashboardStatisticValue + + +async def get_dashboard_eu_projects( + institution_id: str, + organization_name: str, + from_year: int | None = None, + to_year: int | None = None, +) -> DashboardStatisticValue: + normalized_id = _normalize_institution_id(institution_id) + period = _dashboard_period(from_year, to_year) + projects = await projects_service.search_eu_cordis_projects( + institutions_search_client=InstitutionsSearchClient(), + raw_oa_institution_id=_raw_institution_id(normalized_id), + author_id=None, + author_ids=None, + organization_ids=None, + organization_names=None, + project_types=list(EuCordisProjectType), + keywords=None, + topic_ids=None, + filter_topic_ids=None, + title=None, + funding_start_years=None, + funding_end_years=None, + active_from_year=period[0], + active_to_year=period[1], + countries=None, + framework_programmes=None, + funding_schemes=None, + statuses=None, + page=0, + size=1, + sort_by="id", + sort_direction="asc", + fuzzy=False, + ) + return DashboardStatisticValue( + institution_id=normalized_id, + organization_name=organization_name, + value=projects.total, + ) + + +async def get_dashboard_bmbf_projects( + institution_id: str, + organization_name: str, + from_year: int | None = None, + to_year: int | None = None, +) -> DashboardStatisticValue: + normalized_id = _normalize_institution_id(institution_id) + period = _dashboard_period(from_year, to_year) + projects = await projects_service.search_bund_projects_with_filters( + institutions_search_client=InstitutionsSearchClient(), + executing_agency=None, + raw_oa_institution_id=_raw_institution_id(normalized_id), + title=None, + keywords=None, + funding_arts=None, + topic_ids=None, + filter_topic_ids=None, + funding_start_years=None, + funding_end_years=None, + active_from_year=period[0], + active_to_year=period[1], + countries=None, + page=0, + size=1, + sort_by="id", + sort_direction="asc", + fuzzy=False, + ) + return DashboardStatisticValue( + institution_id=normalized_id, + organization_name=organization_name, + value=projects.total, + ) + + +async def get_dashboard_dfg_projects( + institution_id: str, + organization_name: str, + from_year: int | None = None, + to_year: int | None = None, +) -> DashboardStatisticValue: + normalized_id = _normalize_institution_id(institution_id) + period = _dashboard_period(from_year, to_year) + projects = await projects_service.get_dfg_projects( + institutions_search_client=InstitutionsSearchClient(), + raw_oa_institution_id=_raw_institution_id(normalized_id), + author_id=None, + author_filter_ids=None, + institution_ids=None, + keywords=None, + topic_ids=None, + filter_topic_ids=None, + title=None, + funding_start_years=None, + funding_end_years=None, + active_from_year=period[0], + active_to_year=period[1], + page=0, + size=1, + sort_by="id", + sort_direction="asc", + fuzzy=False, + skip_enrichment=True, + ) + return DashboardStatisticValue( + institution_id=normalized_id, + organization_name=organization_name, + value=projects.total, + ) diff --git a/service/src/main/inse/dashboard/project_status_service.py b/service/src/main/inse/dashboard/project_status_service.py new file mode 100644 index 00000000..4c32b94b --- /dev/null +++ b/service/src/main/inse/dashboard/project_status_service.py @@ -0,0 +1,513 @@ +from datetime import datetime +from typing import Any + +from inse.institutions.institutions_search_client import InstitutionsSearchClient + +from inse.integrations import elasticsearch +from inse.model import ESCluster, ESIndex + +from .common import ( + DashboardPeriod, + dashboard_period as _dashboard_period, + normalize_institution_id as _normalize_institution_id, + project_boundary_year_filter as _project_boundary_year_filter, + project_overlap_filter as _project_overlap_filter, + raw_institution_id as _raw_institution_id, +) +from .institute_helper import get_openalex_institution +from .model import ( + BmbfProjectStatusStatistics, + DfgProjectStatusStatistics, + EuProjectStatusStatistics, +) +from .project_statistics_service import ( + get_dashboard_bmbf_projects, + get_dashboard_dfg_projects, + get_dashboard_eu_projects, +) + + +def _status_count(aggregations: dict[str, Any], status_name: str) -> int: + return int(aggregations.get(status_name, {}).get("projects", {}).get("value", 0)) + + +def reconcile_status_counts( + total: int, ongoing: int, upcoming: int, completed: int +) -> tuple[int, int, int]: + """Make status buckets add up to the authoritative project-service total.""" + counts = [max(0, ongoing), max(0, upcoming), max(0, completed)] + difference = total - sum(counts) + if difference >= 0: + counts[0] += difference + return counts[0], counts[1], counts[2] + + excess = -difference + for index in (0, 1, 2): + reduction = min(counts[index], excess) + counts[index] -= reduction + excess -= reduction + if excess == 0: + break + return counts[0], counts[1], counts[2] + + +def _status_filter_aggregations( + start_field: str, end_field: str, today: str +) -> dict[str, Any]: + return { + "ongoing": { + "filter": { + "bool": { + "filter": [ + {"range": {start_field: {"lte": today}}}, + {"range": {end_field: {"gte": today}}}, + ] + } + } + }, + "upcoming": {"filter": {"range": {start_field: {"gt": today}}}}, + "completed": {"filter": {"range": {end_field: {"lt": today}}}}, + } + + +async def get_dashboard_eu_project_statuses( + institution_id: str, + organization_name: str, + from_year: int | None = None, + to_year: int | None = None, +) -> EuProjectStatusStatistics: + normalized_id = _normalize_institution_id(institution_id) + aliases = await _institution_aliases(normalized_id, organization_name) + project_ids = await _eu_project_ids_for_aliases(aliases) + total = ( + await get_dashboard_eu_projects( + normalized_id, organization_name, from_year=from_year, to_year=to_year + ) + ).value + if not project_ids: + return EuProjectStatusStatistics( + institution_id=normalized_id, + organization_name=organization_name, + ongoing=total, + upcoming=0, + completed=0, + ) + + today = datetime.now().date().isoformat() + period = _dashboard_period(from_year, to_year) + filters: list[dict[str, Any]] = [{"terms": {"id": sorted(project_ids)}}] + if period_filter := _project_boundary_year_filter( + "startDate", "endDate", period, "iso" + ): + filters.append(period_filter) + response = await elasticsearch.search( + index=ESIndex.CORDIS_EU_PROJECTS_WILDCARD, + body={ + "size": 0, + "query": filters[0] if len(filters) == 1 else {"bool": {"filter": filters}}, + "aggs": { + "ongoing": { + "filter": { + "bool": { + "filter": [ + {"range": {"startDate": {"lte": today}}}, + {"range": {"endDate": {"gte": today}}}, + ] + } + }, + "aggs": {"projects": {"cardinality": {"field": "id"}}}, + }, + "upcoming": { + "filter": {"range": {"startDate": {"gt": today}}}, + "aggs": {"projects": {"cardinality": {"field": "id"}}}, + }, + "completed": { + "filter": {"range": {"endDate": {"lt": today}}}, + "aggs": {"projects": {"cardinality": {"field": "id"}}}, + }, + }, + }, + cluster=ESCluster.INSE, + ) + aggregations = response.get("aggregations", {}) + ongoing, upcoming, completed = reconcile_status_counts( + total, + _status_count(aggregations, "ongoing"), + _status_count(aggregations, "upcoming"), + _status_count(aggregations, "completed"), + ) + return EuProjectStatusStatistics( + institution_id=normalized_id, + organization_name=organization_name, + ongoing=ongoing, + upcoming=upcoming, + completed=completed, + ) + + +async def get_dashboard_bmbf_project_statuses( + institution_id: str, + organization_name: str, + from_year: int | None = None, + to_year: int | None = None, +) -> BmbfProjectStatusStatistics: + normalized_id = _normalize_institution_id(institution_id) + aliases = await _institution_aliases(normalized_id, organization_name) + period = _dashboard_period(from_year, to_year) + filters = [_alias_match_query("Zuwendungsempfänger", aliases)] + if period_filter := _project_boundary_year_filter( + "funding_start", "funding_end", period, "de" + ): + filters.append(period_filter) + response = await elasticsearch.search( + index=ESIndex.PROJECTS_BUND_V1, + body={ + "size": 0, + "query": filters[0] if len(filters) == 1 else {"bool": {"filter": filters}}, + "aggs": _status_filter_aggregations( + "funding_start", "funding_end", datetime.now().strftime("%d.%m.%Y") + ), + }, + cluster=ESCluster.INSE, + ) + aggregations = response.get("aggregations", {}) + total = ( + await get_dashboard_bmbf_projects( + normalized_id, organization_name, from_year=from_year, to_year=to_year + ) + ).value + ongoing, upcoming, completed = reconcile_status_counts( + total, + int(aggregations.get("ongoing", {}).get("doc_count", 0)), + int(aggregations.get("upcoming", {}).get("doc_count", 0)), + int(aggregations.get("completed", {}).get("doc_count", 0)), + ) + return BmbfProjectStatusStatistics( + institution_id=normalized_id, + organization_name=organization_name, + ongoing=ongoing, + upcoming=upcoming, + completed=completed, + ) + + +async def get_dashboard_dfg_project_statuses( + institution_id: str, + organization_name: str, + from_year: int | None = None, + to_year: int | None = None, +) -> DfgProjectStatusStatistics: + normalized_id = _normalize_institution_id(institution_id) + period = _dashboard_period(from_year, to_year) + project_ids = await _get_dfg_project_ids_for_institution(normalized_id) + total = ( + await get_dashboard_dfg_projects( + normalized_id, organization_name, from_year=from_year, to_year=to_year + ) + ).value + if not project_ids: + return DfgProjectStatusStatistics( + institution_id=normalized_id, + organization_name=organization_name, + ongoing=total, + upcoming=0, + completed=0, + ) + + filters: list[dict[str, Any]] = [ + { + "terms": { + "projects.project_id": [int(project_id) for project_id in project_ids] + } + } + ] + if period_filter := _project_boundary_year_filter( + "projects.funding_start", "projects.funding_end", period, "year" + ): + filters.append(period_filter) + response = await elasticsearch.search( + index=ESIndex.DFG_INSTITUTES_V2, + body={ + "size": 0, + "aggs": { + "projects_nested": { + "nested": {"path": "projects"}, + "aggs": { + "selected_projects": { + "filter": filters[0] + if len(filters) == 1 + else {"bool": {"filter": filters}}, + "aggs": { + "ongoing": { + "filter": { + "match_phrase": { + "projects.status_de": "laufend" + } + }, + "aggs": { + "projects": { + "cardinality": { + "field": "projects.project_id" + } + } + }, + }, + "completed": { + "filter": { + "match_phrase": { + "projects.status_de": "abgeschlossen" + } + }, + "aggs": { + "projects": { + "cardinality": { + "field": "projects.project_id" + } + } + }, + }, + }, + } + }, + } + }, + }, + cluster=ESCluster.INSE, + ) + aggregations = ( + response.get("aggregations", {}) + .get("projects_nested", {}) + .get("selected_projects", {}) + ) + ongoing, upcoming, completed = reconcile_status_counts( + total, + _status_count(aggregations, "ongoing"), + 0, + _status_count(aggregations, "completed"), + ) + return DfgProjectStatusStatistics( + institution_id=normalized_id, + organization_name=organization_name, + ongoing=ongoing, + upcoming=upcoming, + completed=completed, + ) + + +async def _get_dfg_project_ids_for_institution( + institution_id: str, + from_year: int | None = None, + to_year: int | None = None, +) -> list[str]: + period = _dashboard_period(from_year, to_year) + institution = await get_openalex_institution(institution_id) + institution_names = _openalex_institution_names(institution) + + institutes_response = await elasticsearch.search( + index=ESIndex.DFG_INSTITUTES_V2, + body={ + "size": 0, + "query": _dfg_institute_name_query(institution_names), + "aggs": { + "institute_ids": {"terms": {"field": "institute_id", "size": 1000}} + }, + }, + cluster=ESCluster.INSE, + ) + institute_ids = [ + bucket["key"] + for bucket in ( + institutes_response.get("aggregations", {}) + .get("institute_ids", {}) + .get("buckets", []) + ) + if bucket.get("key") is not None + ] + if not institute_ids: + return [] + + projects_response = await elasticsearch.search( + index=ESIndex.DFG_INSTITUTES_V2, + body={ + "size": 0, + "query": {"terms": {"institute_id": institute_ids}}, + "aggs": { + "projects_nested": { + "nested": {"path": "projects"}, + "aggs": { + "project_ids": { + "filter": { + "terms": {"projects.institute_ref_id": institute_ids} + }, + "aggs": { + "values": { + "terms": { + "field": "projects.project_id", + "size": 10000, + } + } + }, + } + }, + } + }, + }, + cluster=ESCluster.INSE, + ) + project_ids = [ + str(bucket["key"]) + for bucket in ( + projects_response.get("aggregations", {}) + .get("projects_nested", {}) + .get("project_ids", {}) + .get("values", {}) + .get("buckets", []) + ) + if bucket.get("key") is not None + ] + return await _filter_dfg_project_ids_by_period(project_ids, period) + + +async def _eu_project_ids_for_aliases(aliases: list[str]) -> set[str]: + project_ids: set[str] = set() + async for hit in elasticsearch.scan( + index=str(ESIndex.CORDIS_EU_ORGANIZATIONS_WILDCARD), + query=_eu_organization_query(aliases), + source=["projectID"], + page_size=1000, + cluster=ESCluster.INSE, + ): + project_id = hit.get("_source", {}).get("projectID") + if project_id is not None: + project_ids.add(str(project_id)) + return project_ids + + +async def _filter_dfg_project_ids_by_period( + project_ids: list[str], + period: DashboardPeriod, +) -> list[str]: + period_filter = _project_overlap_filter( + "funding_start", + "funding_end", + period, + missing_end_is_ongoing=True, + ) + if not project_ids or not period_filter: + return project_ids + + numeric_project_ids = [ + int(project_id) for project_id in project_ids if str(project_id).isdigit() + ] + if not numeric_project_ids: + return [] + + response = await elasticsearch.search( + index=ESIndex.DFG_PROJECTS, + body={ + "size": 0, + "query": { + "bool": { + "filter": [ + {"terms": {"id": numeric_project_ids}}, + period_filter, + ] + } + }, + "aggs": { + "project_ids": { + "terms": { + "field": "id", + "size": len(numeric_project_ids), + } + } + }, + }, + cluster=ESCluster.INSE, + ) + return [ + str(bucket["key"]) + for bucket in ( + response.get("aggregations", {}).get("project_ids", {}).get("buckets", []) + ) + if bucket.get("key") is not None + ] + + +async def _institution_aliases( + institution_id: str, + organization_name: str, +) -> list[str]: + aliases = ( + await InstitutionsSearchClient().get_institution_aliases_by_oa_institution_id( + _raw_institution_id(institution_id) + ) + ) + return sorted( + { + alias.strip() + for alias in [organization_name, *aliases] + if alias and alias.strip() + } + ) + + +def _eu_organization_query(aliases: list[str]) -> dict[str, Any]: + return { + "terms": { + "name.keyword": [alias.upper() for alias in aliases], + } + } + + +def _alias_match_query(field: str, aliases: list[str]) -> dict[str, Any]: + return { + "bool": { + "should": [ + { + "match": { + field: { + "query": alias, + "operator": "and", + } + } + } + for alias in aliases + ], + "minimum_should_match": 1, + } + } + + +def _openalex_institution_names(institution: Any) -> list[str]: + return sorted( + { + name.strip() + for name in [ + institution.display_name, + *(institution.display_name_alternatives or []), + *(institution.display_name_acronyms or []), + ] + if name and name.strip() + } + ) + + +def _dfg_institute_name_query(institution_names: list[str]) -> dict[str, Any]: + return { + "bool": { + "should": [ + { + "terms": { + "institute_name_de.keyword": institution_names, + } + }, + { + "terms": { + "institute_name_en.keyword": institution_names, + } + }, + ], + "minimum_should_match": 1, + } + } diff --git a/service/src/main/inse/dashboard/router.py b/service/src/main/inse/dashboard/router.py index fb01a93a..a0d0de82 100644 --- a/service/src/main/inse/dashboard/router.py +++ b/service/src/main/inse/dashboard/router.py @@ -18,28 +18,40 @@ from .model import ( EuProjectTopics, EuProjectStatusStatistics, TopAuthorStatistics, + TopAuthorAnalysis, TopicHeatmap, TopicWordCloud, ) from .service import ( - get_dashboard_bmbf_project_statuses, - get_dashboard_bmbf_projects, - get_dashboard_bund_topics, - get_dashboard_dfg_project_statuses, - get_dashboard_dfg_projects, - get_dashboard_dfg_topics, - get_dashboard_eu_topics, - get_dashboard_eu_project_statuses, - get_dashboard_eu_projects, get_dashboard_organization, get_dashboard_patents, get_dashboard_persons, get_dashboard_publications, get_dashboard_statistics, - get_top_authors, get_topic_heatmap, get_topic_word_cloud, ) +from .project_statistics_service import ( + get_dashboard_bmbf_projects, + get_dashboard_dfg_projects, + get_dashboard_eu_projects, +) +from .bund_topics_service import get_dashboard_bund_topics +from .dfg_topics_service import get_dashboard_dfg_topics +from .eu_topics_service import get_dashboard_eu_topics +from .project_status_service import ( + get_dashboard_bmbf_project_statuses, + get_dashboard_dfg_project_statuses, + get_dashboard_eu_project_statuses, +) +from .top_authors_service import ( + get_top_authors, + get_top_eu_project_authors, + get_top_news_authors, + get_top_patent_authors, + get_top_project_authors, + get_top_work_authors, +) router = APIRouter(prefix="/api/dashboard", tags=[Tags.DASHBOARD]) @@ -325,6 +337,94 @@ async def dashboard_top_authors( ) +@router.get( + "/top-authors/works", + operation_id="getDashboardTopWorkAuthors", + response_model=TopAuthorAnalysis, +) +async def dashboard_top_work_authors( + works_period: Literal["all_time", "last_5_years"] = Query( + default="all_time", pattern="^(all_time|last_5_years)$" + ), + from_year: int | None = Query(default=None, ge=1900, le=2100), + to_year: int | None = Query(default=None, ge=1900, le=2100), + session: Session = Depends(get_session), + access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep, +) -> TopAuthorAnalysis: + organization = get_dashboard_organization(session, access_token) + return await get_top_work_authors( + organization.openalex_institution_id, works_period, from_year, to_year + ) + + +@router.get( + "/top-authors/projects", + operation_id="getDashboardTopProjectAuthors", + response_model=TopAuthorAnalysis, +) +async def dashboard_top_project_authors( + from_year: int | None = Query(default=None, ge=1900, le=2100), + to_year: int | None = Query(default=None, ge=1900, le=2100), + session: Session = Depends(get_session), + access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep, +) -> TopAuthorAnalysis: + organization = get_dashboard_organization(session, access_token) + return await get_top_project_authors( + organization.openalex_institution_id, organization.name, from_year, to_year + ) + + +@router.get( + "/top-authors/eu-projects", + operation_id="getDashboardTopEuProjectAuthors", + response_model=TopAuthorAnalysis, +) +async def dashboard_top_eu_project_authors( + from_year: int | None = Query(default=None, ge=1900, le=2100), + to_year: int | None = Query(default=None, ge=1900, le=2100), + session: Session = Depends(get_session), + access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep, +) -> TopAuthorAnalysis: + organization = get_dashboard_organization(session, access_token) + return await get_top_eu_project_authors( + organization.openalex_institution_id, from_year, to_year + ) + + +@router.get( + "/top-authors/patents", + operation_id="getDashboardTopPatentAuthors", + response_model=TopAuthorAnalysis, +) +async def dashboard_top_patent_authors( + from_year: int | None = Query(default=None, ge=1900, le=2100), + to_year: int | None = Query(default=None, ge=1900, le=2100), + session: Session = Depends(get_session), + access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep, +) -> TopAuthorAnalysis: + organization = get_dashboard_organization(session, access_token) + return await get_top_patent_authors( + organization.openalex_institution_id, from_year, to_year + ) + + +@router.get( + "/top-authors/news", + operation_id="getDashboardTopNewsAuthors", + response_model=TopAuthorAnalysis, +) +async def dashboard_top_news_authors( + from_year: int | None = Query(default=None, ge=1900, le=2100), + to_year: int | None = Query(default=None, ge=1900, le=2100), + session: Session = Depends(get_session), + access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep, +) -> TopAuthorAnalysis: + organization = get_dashboard_organization(session, access_token) + return await get_top_news_authors( + organization.openalex_institution_id, from_year, to_year + ) + + @router.get( "/topic-heatmap", operation_id="getDashboardTopicHeatmap", diff --git a/service/src/main/inse/dashboard/service.py b/service/src/main/inse/dashboard/service.py index c2a5fad2..a162da74 100644 --- a/service/src/main/inse/dashboard/service.py +++ b/service/src/main/inse/dashboard/service.py @@ -1,52 +1,29 @@ import asyncio -import hashlib import logging -import re -from collections import defaultdict -from datetime import datetime -from types import SimpleNamespace -from typing import Any, Literal +from typing import Any from fastapi import HTTPException, status from sqlmodel import Session from inse import config from inse.auth.model import AccessToken, Organization -from inse.institutions.institutions_search_client import InstitutionsSearchClient from inse.institutions.v2 import service as institutions_v2_service from inse.integrations import elasticsearch from inse.model import ESCluster, ESIndex from inse.patents.org.elastic_search_client import OrgPatentsSearchClient from inse.persons import service as persons_service -from inse.projects import service as projects_service -from inse.projects.dfg_institutions.service import ( - autocomplete_institutions_for_selector, -) -from inse.projects.eu_cordis_projects_client import ( - get_eu_project_ids_by_organization_filters, -) -from inse.projects.logic import get_person_ids_by_institution_ids -from inse.projects.model import ( - EuCordisProjectType, - ProjectsFilteringProperties, - ProjectType, -) from inse.works.v2 import service as works_v2_service -from .institute_helper import get_openalex_institution +from .common import ( + DashboardPeriod, + dashboard_period as _dashboard_period, + institution_works_query as _institution_works_query, + normalize_institution_id as _normalize_institution_id, + raw_institution_id as _raw_institution_id, +) from .model import ( - BmbfProjectStatusStatistics, - BundProjectTopics, DashboardStatistics, - DfgProjectKeyword, DashboardStatisticValue, - DfgProjectStatusStatistics, - DfgProjectTopic, - DfgProjectTopics, - EuProjectTopics, - EuProjectStatusStatistics, - TopAuthor, - TopAuthorStatistics, TopicHeatmap, TopicHeatmapField, TopicHeatmapSubfield, @@ -55,94 +32,19 @@ from .model import ( TopicWordCloud, TopicWordCloudWord, ) +from .project_statistics_service import ( + get_dashboard_bmbf_projects, + get_dashboard_dfg_projects, + get_dashboard_eu_projects, +) -TOP_AUTHOR_LIMIT = 10 TOPIC_HEATMAP_LIMIT = 25 TOPIC_HEATMAP_SUBFIELD_LIMIT = 100 TOPIC_HEATMAP_TOPIC_LIMIT = 100 TOPIC_WORD_CLOUD_LIMIT = 30 -WorksPeriod = Literal["all_time", "last_5_years"] -DashboardPeriod = tuple[int | None, int | None] logger = logging.getLogger(__name__) -async def get_eu_organization_project_contributions( - organization_names: list[str], - projects_filtering_properties: ProjectsFilteringProperties, -) -> SimpleNamespace: - project_ids_by_type = await get_eu_project_ids_by_organization_filters( - project_types=list(EuCordisProjectType), - organization_names=organization_names, - ) - project_ids = { - str(project_id) - for ids in project_ids_by_type.values() - for project_id in ids - } - return SimpleNamespace( - elements=[ - SimpleNamespace(project_id=project_id) - for project_id in sorted(project_ids) - ], - total=len(project_ids), - page=projects_filtering_properties.page, - size=projects_filtering_properties.size, - ) - - -ACADEMIC_TITLE_RE = re.compile( - r"^(?:(?:professor(?:in)?|prof|dr)(?:\.-[a-z]+)?\.?|rer\.|nat\.|med\.|ing\.)\s+", - re.IGNORECASE, -) - - -def _normalize_person_name(name: str) -> str: - normalized = " ".join(name.strip().casefold().split()) - while True: - without_title = ACADEMIC_TITLE_RE.sub("", normalized).strip() - if without_title == normalized: - return without_title - normalized = without_title - - -def _is_initial_surname_match(full_name: str, initial_name: str) -> bool: - full_parts = _normalize_person_name(full_name).split() - initial_parts = _normalize_person_name(initial_name).replace(".", "").split() - if len(full_parts) < 2 or len(initial_parts) < 2: - return False - return ( - len(initial_parts[0]) == 1 - and full_parts[0].startswith(initial_parts[0]) - and full_parts[-1] == initial_parts[-1] - ) - - -def _is_supported_name_variant(full_name: str, candidate_name: str) -> bool: - return ( - _normalize_person_name(full_name) == _normalize_person_name(candidate_name) - or _is_initial_surname_match(full_name, candidate_name) - ) - - -def _total(response: dict[str, Any]) -> int: - total = response.get("hits", {}).get("total", 0) - if isinstance(total, dict): - return int(total.get("value", 0)) - return int(total or 0) - - -def _dashboard_period( - from_year: int | None = None, - to_year: int | None = None, -) -> DashboardPeriod: - if from_year is not None and to_year is not None and from_year > to_year: - raise HTTPException( - status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, - detail="from_year must be less than or equal to to_year.", - ) - return from_year, to_year - - def _publication_year_filter(period: DashboardPeriod) -> dict[str, Any] | None: from_year, to_year = period year_range: dict[str, int] = {} @@ -153,67 +55,6 @@ def _publication_year_filter(period: DashboardPeriod) -> dict[str, Any] | None: return {"range": {"publication_year": year_range}} if year_range else None -def _project_overlap_filter( - start_field: str, - end_field: str, - period: DashboardPeriod, - *, - missing_end_is_ongoing: bool = False, -) -> dict[str, Any] | None: - from_year, to_year = period - filters: list[dict[str, Any]] = [] - if to_year is not None: - filters.append({"range": {start_field: {"lte": to_year}}}) - if from_year is not None: - end_filter: dict[str, Any] = {"range": {end_field: {"gte": from_year}}} - if missing_end_is_ongoing: - end_filter = { - "bool": { - "should": [ - end_filter, - {"bool": {"must_not": {"exists": {"field": end_field}}}}, - ], - "minimum_should_match": 1, - } - } - filters.append(end_filter) - return {"bool": {"filter": filters}} if filters else None - - -def _project_boundary_year_filter( - start_field: str, - end_field: str, - period: DashboardPeriod, - date_format: Literal["iso", "de", "year"], -) -> dict[str, Any] | None: - from_year, to_year = period - filters: list[dict[str, Any]] = [] - - # A project overlaps the selected interval if it begins no later than the - # interval end and finishes no earlier than the interval start. - if to_year is not None: - if date_format == "year": - filters.append({"range": {start_field: {"lte": to_year}}}) - else: - last_day = ( - f"{to_year}-12-31" if date_format == "iso" else f"31.12.{to_year}" - ) - filters.append({"range": {start_field: {"lte": last_day}}}) - - if from_year is not None: - if date_format == "year": - filters.append({"range": {end_field: {"gte": from_year}}}) - else: - first_day = ( - f"{from_year}-01-01" - if date_format == "iso" - else f"01.01.{from_year}" - ) - filters.append({"range": {end_field: {"gte": first_day}}}) - - return {"bool": {"filter": filters}} if filters else None - - def get_dashboard_organization( session: Session, access_token: AccessToken, @@ -237,14 +78,18 @@ async def get_dashboard_statistics( organization_name: str, ) -> DashboardStatistics: normalized_id = _normalize_institution_id(institution_id) - publications, persons, eu_projects, bmbf_projects, dfg_projects = ( - await asyncio.gather( - get_dashboard_publications(institution_id, organization_name), - get_dashboard_persons(institution_id, organization_name), - get_dashboard_eu_projects(institution_id, organization_name), - get_dashboard_bmbf_projects(institution_id, organization_name), - get_dashboard_dfg_projects(institution_id, organization_name), - ) + ( + publications, + persons, + eu_projects, + bmbf_projects, + dfg_projects, + ) = await asyncio.gather( + get_dashboard_publications(institution_id, organization_name), + get_dashboard_persons(institution_id, organization_name), + get_dashboard_eu_projects(institution_id, organization_name), + get_dashboard_bmbf_projects(institution_id, organization_name), + get_dashboard_dfg_projects(institution_id, organization_name), ) return DashboardStatistics( institution_id=normalized_id, @@ -299,13 +144,6 @@ async def get_dashboard_publications( ) -def _dashboard_publication_years(period: DashboardPeriod) -> list[int] | None: - from_year, to_year = period - if from_year is None and to_year is None: - return None - return list(range(from_year or 1900, (to_year or 2100) + 1)) - - async def get_dashboard_persons( institution_id: str, organization_name: str, @@ -362,1147 +200,6 @@ async def get_dashboard_patents( ) -async def get_dashboard_eu_projects( - institution_id: str, - organization_name: str, - from_year: int | None = None, - to_year: int | None = None, -) -> DashboardStatisticValue: - normalized_id = _normalize_institution_id(institution_id) - period = _dashboard_period(from_year, to_year) - projects = await projects_service.search_eu_cordis_projects( - institutions_search_client=InstitutionsSearchClient(), - raw_oa_institution_id=_raw_institution_id(normalized_id), - author_id=None, - author_ids=None, - organization_ids=None, - organization_names=None, - project_types=list(EuCordisProjectType), - keywords=None, - topic_ids=None, - filter_topic_ids=None, - title=None, - funding_start_years=None, - funding_end_years=None, - active_from_year=period[0], - active_to_year=period[1], - countries=None, - framework_programmes=None, - funding_schemes=None, - statuses=None, - page=0, - size=1, - sort_by="id", - sort_direction="asc", - fuzzy=False, - ) - return DashboardStatisticValue( - institution_id=normalized_id, - organization_name=organization_name, - value=projects.total, - ) - - -async def get_dashboard_eu_project_statuses( - institution_id: str, - organization_name: str, - from_year: int | None = None, - to_year: int | None = None, -) -> EuProjectStatusStatistics: - normalized_id = _normalize_institution_id(institution_id) - aliases = await _institution_aliases(normalized_id, organization_name) - project_ids = await _eu_project_ids_for_aliases(aliases) - - if not project_ids: - total = ( - await get_dashboard_eu_projects( - normalized_id, - organization_name, - from_year=from_year, - to_year=to_year, - ) - ).value - return EuProjectStatusStatistics( - institution_id=normalized_id, - organization_name=organization_name, - ongoing=total, - upcoming=0, - completed=0, - ) - - today = datetime.now().date().isoformat() - period = _dashboard_period(from_year, to_year) - filters: list[dict[str, Any]] = [{"terms": {"id": sorted(project_ids)}}] - if period_filter := _project_boundary_year_filter( - "startDate", - "endDate", - period, - "iso", - ): - filters.append(period_filter) - query = ( - {"terms": {"id": sorted(project_ids)}} - if len(filters) == 1 - else {"bool": {"filter": filters}} - ) - response = await elasticsearch.search( - index=ESIndex.CORDIS_EU_PROJECTS_WILDCARD, - body={ - "size": 0, - "query": query, - "aggs": { - "ongoing": { - "filter": { - "bool": { - "filter": [ - {"range": {"startDate": {"lte": today}}}, - {"range": {"endDate": {"gte": today}}}, - ] - } - }, - "aggs": { - "projects": {"cardinality": {"field": "id"}} - }, - }, - "upcoming": { - "filter": {"range": {"startDate": {"gt": today}}}, - "aggs": { - "projects": {"cardinality": {"field": "id"}} - }, - }, - "completed": { - "filter": {"range": {"endDate": {"lt": today}}}, - "aggs": { - "projects": {"cardinality": {"field": "id"}} - }, - }, - }, - }, - cluster=ESCluster.INSE, - ) - aggregations = response.get("aggregations", {}) - total = ( - await get_dashboard_eu_projects( - normalized_id, - organization_name, - from_year=from_year, - to_year=to_year, - ) - ).value - ongoing, upcoming, completed = _reconcile_project_status_counts( - total, - _project_status_count(aggregations, "ongoing"), - _project_status_count(aggregations, "upcoming"), - _project_status_count(aggregations, "completed"), - ) - return EuProjectStatusStatistics( - institution_id=normalized_id, - organization_name=organization_name, - ongoing=ongoing, - upcoming=upcoming, - completed=completed, - ) - - -def _project_status_count(aggregations: dict[str, Any], status_name: str) -> int: - return int( - aggregations.get(status_name, {}).get("projects", {}).get("value", 0) - ) - - -def _reconcile_project_status_counts( - total: int, - ongoing: int, - upcoming: int, - completed: int, -) -> tuple[int, int, int]: - """Makes status buckets add up to the authoritative project-service total.""" - counts = [max(0, ongoing), max(0, upcoming), max(0, completed)] - difference = total - sum(counts) - if difference >= 0: - counts[0] += difference - return counts[0], counts[1], counts[2] - - # Defensive fallback for stale/duplicated status documents: reduce buckets - # without ever returning negative values, preferring the inferred ongoing - # bucket before changing explicit upcoming/completed classifications. - excess = -difference - for index in (0, 1, 2): - reduction = min(counts[index], excess) - counts[index] -= reduction - excess -= reduction - if excess == 0: - break - return counts[0], counts[1], counts[2] - - -async def get_dashboard_bmbf_projects( - institution_id: str, - organization_name: str, - from_year: int | None = None, - to_year: int | None = None, -) -> DashboardStatisticValue: - normalized_id = _normalize_institution_id(institution_id) - period = _dashboard_period(from_year, to_year) - projects = await projects_service.search_bund_projects_with_filters( - institutions_search_client=InstitutionsSearchClient(), - executing_agency=None, - raw_oa_institution_id=_raw_institution_id(normalized_id), - title=None, - keywords=None, - funding_arts=None, - topic_ids=None, - filter_topic_ids=None, - funding_start_years=None, - funding_end_years=None, - active_from_year=period[0], - active_to_year=period[1], - countries=None, - page=0, - size=1, - sort_by="id", - sort_direction="asc", - fuzzy=False, - ) - return DashboardStatisticValue( - institution_id=normalized_id, - organization_name=organization_name, - value=projects.total, - ) - - -async def get_dashboard_bmbf_project_statuses( - institution_id: str, - organization_name: str, - from_year: int | None = None, - to_year: int | None = None, -) -> BmbfProjectStatusStatistics: - normalized_id = _normalize_institution_id(institution_id) - aliases = await _institution_aliases(normalized_id, organization_name) - period = _dashboard_period(from_year, to_year) - filters = [_alias_match_query("Zuwendungsempfänger", aliases)] - if period_filter := _project_boundary_year_filter( - "funding_start", - "funding_end", - period, - "de", - ): - filters.append(period_filter) - today = datetime.now().strftime("%d.%m.%Y") - response = await elasticsearch.search( - index=ESIndex.PROJECTS_BUND_V1, - body={ - "size": 0, - "query": filters[0] if len(filters) == 1 else {"bool": {"filter": filters}}, - "aggs": _project_status_filter_aggregations( - start_field="funding_start", - end_field="funding_end", - today=today, - ), - }, - cluster=ESCluster.INSE, - ) - aggregations = response.get("aggregations", {}) - total = ( - await get_dashboard_bmbf_projects( - normalized_id, - organization_name, - from_year=from_year, - to_year=to_year, - ) - ).value - ongoing, upcoming, completed = _reconcile_project_status_counts( - total, - int(aggregations.get("ongoing", {}).get("doc_count", 0)), - int(aggregations.get("upcoming", {}).get("doc_count", 0)), - int(aggregations.get("completed", {}).get("doc_count", 0)), - ) - return BmbfProjectStatusStatistics( - institution_id=normalized_id, - organization_name=organization_name, - ongoing=ongoing, - upcoming=upcoming, - completed=completed, - ) - - -def _project_status_filter_aggregations( - start_field: str, - end_field: str, - today: str, -) -> dict[str, Any]: - return { - "ongoing": { - "filter": { - "bool": { - "filter": [ - {"range": {start_field: {"lte": today}}}, - {"range": {end_field: {"gte": today}}}, - ] - } - } - }, - "upcoming": {"filter": {"range": {start_field: {"gt": today}}}}, - "completed": {"filter": {"range": {end_field: {"lt": today}}}}, - } - - -async def get_dashboard_dfg_projects( - institution_id: str, - organization_name: str, - from_year: int | None = None, - to_year: int | None = None, -) -> DashboardStatisticValue: - normalized_id = _normalize_institution_id(institution_id) - period = _dashboard_period(from_year, to_year) - projects = await projects_service.get_dfg_projects( - institutions_search_client=InstitutionsSearchClient(), - raw_oa_institution_id=_raw_institution_id(normalized_id), - author_id=None, - author_filter_ids=None, - institution_ids=None, - keywords=None, - topic_ids=None, - filter_topic_ids=None, - title=None, - funding_start_years=None, - funding_end_years=None, - active_from_year=period[0], - active_to_year=period[1], - page=0, - size=1, - sort_by="id", - sort_direction="asc", - fuzzy=False, - skip_enrichment=True, - ) - return DashboardStatisticValue( - institution_id=normalized_id, - organization_name=organization_name, - value=projects.total, - ) - - -async def get_dashboard_dfg_project_statuses( - institution_id: str, - organization_name: str, - from_year: int | None = None, - to_year: int | None = None, -) -> DfgProjectStatusStatistics: - normalized_id = _normalize_institution_id(institution_id) - period = _dashboard_period(from_year, to_year) - project_ids = await _get_dfg_project_ids_for_institution( - normalized_id, - ) - if not project_ids: - total = ( - await get_dashboard_dfg_projects( - normalized_id, - organization_name, - from_year=from_year, - to_year=to_year, - ) - ).value - return DfgProjectStatusStatistics( - institution_id=normalized_id, - organization_name=organization_name, - ongoing=total, - upcoming=0, - completed=0, - ) - - selected_project_filters: list[dict[str, Any]] = [ - { - "terms": { - "projects.project_id": [ - int(project_id) for project_id in project_ids - ] - } - } - ] - if period_filter := _project_boundary_year_filter( - "projects.funding_start", - "projects.funding_end", - period, - "year", - ): - selected_project_filters.append(period_filter) - - response = await elasticsearch.search( - index=ESIndex.DFG_INSTITUTES_V2, - body={ - "size": 0, - "aggs": { - "projects_nested": { - "nested": {"path": "projects"}, - "aggs": { - "selected_projects": { - "filter": ( - selected_project_filters[0] - if len(selected_project_filters) == 1 - else {"bool": {"filter": selected_project_filters}} - ), - "aggs": { - "ongoing": { - "filter": { - "match_phrase": { - "projects.status_de": "laufend" - } - }, - "aggs": { - "projects": { - "cardinality": { - "field": "projects.project_id" - } - } - }, - }, - "completed": { - "filter": { - "match_phrase": { - "projects.status_de": "abgeschlossen" - } - }, - "aggs": { - "projects": { - "cardinality": { - "field": "projects.project_id" - } - } - }, - }, - }, - } - }, - } - }, - }, - cluster=ESCluster.INSE, - ) - aggregations = ( - response.get("aggregations", {}) - .get("projects_nested", {}) - .get("selected_projects", {}) - ) - total = ( - await get_dashboard_dfg_projects( - normalized_id, - organization_name, - from_year=from_year, - to_year=to_year, - ) - ).value - ongoing, upcoming, completed = _reconcile_project_status_counts( - total, - _project_status_count(aggregations, "ongoing"), - 0, - _project_status_count(aggregations, "completed"), - ) - return DfgProjectStatusStatistics( - institution_id=normalized_id, - organization_name=organization_name, - ongoing=ongoing, - upcoming=upcoming, - completed=completed, - ) - - -async def get_dashboard_dfg_topics( - institution_id: str, - organization_name: str, - from_year: int | None = None, - to_year: int | None = None, -) -> DfgProjectTopics: - normalized_id = _normalize_institution_id(institution_id) - project_ids = await _get_dfg_project_ids_from_projects_service( - normalized_id, - from_year=from_year, - to_year=to_year, - ) - topics: dict[str, dict[str, Any]] = {} - matched_project_ids: set[str] = set() - - if project_ids: - async for hit in elasticsearch.scan( - index=str(ESIndex.PROJECTS_DFG_OPENALEX_TOPICS), - query={"terms": {"project_id": project_ids}}, - source=["project_id", "keyword", "topic_matches"], - page_size=1000, - cluster=ESCluster.INSE, - ): - source = hit.get("_source", {}) - project_id = str(source.get("project_id") or "") - if not project_id: - continue - keyword = str(source.get("keyword") or "").strip() - matched_project_ids.add(project_id) - for match in source.get("topic_matches", []): - topic_id = str(match.get("topic_id") or "") - if not topic_id: - continue - topic = topics.setdefault( - topic_id, - { - "id": topic_id, - "name": str(match.get("topic_display_name") or topic_id), - "subfield": match.get("subfield"), - "field": match.get("field"), - "domain": match.get("domain"), - "project_ids": set(), - "keywords": {}, - }, - ) - topic["project_ids"].add(project_id) - if keyword: - topic["keywords"].setdefault(keyword, set()).add(project_id) - - field_project_ids: dict[str, set[str]] = defaultdict(set) - subfield_project_ids: dict[tuple[str, str], set[str]] = defaultdict(set) - for topic in topics.values(): - field_name = str(topic["field"] or "") - subfield_name = str(topic["subfield"] or "") - field_project_ids[field_name].update(topic["project_ids"]) - subfield_project_ids[(field_name, subfield_name)].update(topic["project_ids"]) - - topic_list = [ - DfgProjectTopic( - id=topic["id"], - name=topic["name"], - subfield=topic["subfield"], - field=topic["field"], - domain=topic["domain"], - project_count=len(topic["project_ids"]), - field_project_count=len(field_project_ids[str(topic["field"] or "")]), - subfield_project_count=len( - subfield_project_ids[ - (str(topic["field"] or ""), str(topic["subfield"] or "")) - ] - ), - keywords=sorted( - [ - DfgProjectKeyword( - name=keyword, - project_count=len(keyword_project_ids), - ) - for keyword, keyword_project_ids in topic["keywords"].items() - ], - key=lambda entry: (-entry.project_count, entry.name), - ), - ) - for topic in topics.values() - ] - topic_list.sort(key=lambda topic: (-topic.project_count, topic.name, topic.id)) - return DfgProjectTopics( - institution_id=normalized_id, - organization_name=organization_name, - project_count=len(project_ids), - matched_project_count=len(matched_project_ids), - topics=topic_list, - ) - - -async def get_dashboard_eu_topics( - institution_id: str, - organization_name: str, - from_year: int | None = None, - to_year: int | None = None, -) -> EuProjectTopics: - normalized_id = _normalize_institution_id(institution_id) - project_ids = await _get_eu_project_ids_from_projects_service( - normalized_id, - from_year=from_year, - to_year=to_year, - ) - topics: dict[str, dict[str, Any]] = {} - matched_project_ids: set[str] = set() - - if project_ids: - mapping_indices = ( - ESIndex.PROJECTS_CORDIS_EU_FP7_TOPICS_MAPPING, - ESIndex.PROJECTS_CORDIS_EU_H2020_TOPICS, - ESIndex.PROJECTS_CORDIS_EU_HEUROPE_TOPICS, - ) - for mapping_index in mapping_indices: - async for hit in elasticsearch.scan( - index=str(mapping_index), - query={"terms": {"project_id": project_ids}}, - source=["project_id", "keyword", "topic_matches"], - page_size=1000, - cluster=ESCluster.INSE, - ): - source = hit.get("_source", {}) - project_id = str(source.get("project_id") or "") - if not project_id: - continue - keyword = str(source.get("keyword") or "").strip() - matched_project_ids.add(project_id) - for match in source.get("topic_matches", []): - topic_id = str(match.get("topic_id") or "") - if not topic_id: - continue - topic = topics.setdefault( - topic_id, - { - "id": topic_id, - "name": str(match.get("topic_display_name") or topic_id), - "subfield": match.get("subfield"), - "field": match.get("field"), - "domain": match.get("domain"), - "project_ids": set(), - "keywords": {}, - }, - ) - topic["project_ids"].add(project_id) - if keyword: - topic["keywords"].setdefault(keyword, set()).add(project_id) - - field_project_ids: dict[str, set[str]] = defaultdict(set) - subfield_project_ids: dict[tuple[str, str], set[str]] = defaultdict(set) - for topic in topics.values(): - field_name = str(topic["field"] or "") - subfield_name = str(topic["subfield"] or "") - field_project_ids[field_name].update(topic["project_ids"]) - subfield_project_ids[(field_name, subfield_name)].update(topic["project_ids"]) - - topic_list = [ - DfgProjectTopic( - id=topic["id"], - name=topic["name"], - subfield=topic["subfield"], - field=topic["field"], - domain=topic["domain"], - project_count=len(topic["project_ids"]), - field_project_count=len(field_project_ids[str(topic["field"] or "")]), - subfield_project_count=len( - subfield_project_ids[ - (str(topic["field"] or ""), str(topic["subfield"] or "")) - ] - ), - keywords=sorted( - [ - DfgProjectKeyword( - name=keyword, - project_count=len(keyword_project_ids), - ) - for keyword, keyword_project_ids in topic["keywords"].items() - ], - key=lambda entry: (-entry.project_count, entry.name), - ), - ) - for topic in topics.values() - ] - topic_list.sort(key=lambda topic: (-topic.project_count, topic.name, topic.id)) - return EuProjectTopics( - institution_id=normalized_id, - organization_name=organization_name, - project_count=len(project_ids), - matched_project_count=len(matched_project_ids), - topics=topic_list, - ) - - -async def get_dashboard_bund_topics( - institution_id: str, - organization_name: str, - from_year: int | None = None, - to_year: int | None = None, -) -> BundProjectTopics: - normalized_id = _normalize_institution_id(institution_id) - period = _dashboard_period(from_year, to_year) - page_size = 1000 - page_number = 0 - project_ids: set[str] = set() - - while True: - projects = await projects_service.search_bund_projects_with_filters( - institutions_search_client=InstitutionsSearchClient(), - executing_agency=None, - raw_oa_institution_id=_raw_institution_id(normalized_id), - title=None, - keywords=None, - funding_arts=None, - topic_ids=None, - filter_topic_ids=None, - funding_start_years=None, - funding_end_years=None, - active_from_year=period[0], - active_to_year=period[1], - countries=None, - page=page_number, - size=page_size, - sort_by="id", - sort_direction="asc", - fuzzy=False, - ) - project_ids.update( - project.funding_code - for project in projects.elements - if project.funding_code - ) - if len(project_ids) >= projects.total or not projects.elements: - break - page_number += 1 - - topics: dict[str, dict[str, Any]] = {} - matched_project_ids: set[str] = set() - if project_ids: - mapping_project_ids = sorted( - hashlib.sha256(project_id.encode("utf-8")).hexdigest() - for project_id in project_ids - ) - async for hit in elasticsearch.scan( - index=str(ESIndex.PROJECTS_BUND_TOPICS), - query={"terms": {"project_id": mapping_project_ids}}, - source=["project_id", "keyword", "topic_matches"], - page_size=1000, - cluster=ESCluster.INSE, - ): - source = hit.get("_source", {}) - project_id = str(source.get("project_id") or "") - if not project_id: - continue - keyword = str(source.get("keyword") or "").strip() - matched_project_ids.add(project_id) - for match in source.get("topic_matches", []): - topic_id = str(match.get("topic_id") or "") - if not topic_id: - continue - topic = topics.setdefault( - topic_id, - { - "id": topic_id, - "name": str(match.get("topic_display_name") or topic_id), - "subfield": match.get("subfield"), - "field": match.get("field"), - "domain": match.get("domain"), - "project_ids": set(), - "keywords": {}, - }, - ) - topic["project_ids"].add(project_id) - if keyword: - topic["keywords"].setdefault(keyword, set()).add(project_id) - - field_project_ids: dict[str, set[str]] = defaultdict(set) - subfield_project_ids: dict[tuple[str, str], set[str]] = defaultdict(set) - for topic in topics.values(): - field_name = str(topic["field"] or "") - subfield_name = str(topic["subfield"] or "") - field_project_ids[field_name].update(topic["project_ids"]) - subfield_project_ids[(field_name, subfield_name)].update(topic["project_ids"]) - - topic_list = [ - DfgProjectTopic( - id=topic["id"], - name=topic["name"], - subfield=topic["subfield"], - field=topic["field"], - domain=topic["domain"], - project_count=len(topic["project_ids"]), - field_project_count=len(field_project_ids[str(topic["field"] or "")]), - subfield_project_count=len( - subfield_project_ids[ - (str(topic["field"] or ""), str(topic["subfield"] or "")) - ] - ), - keywords=sorted( - [ - DfgProjectKeyword( - name=keyword, - project_count=len(keyword_project_ids), - ) - for keyword, keyword_project_ids in topic["keywords"].items() - ], - key=lambda entry: (-entry.project_count, entry.name), - ), - ) - for topic in topics.values() - ] - topic_list.sort(key=lambda topic: (-topic.project_count, topic.name, topic.id)) - return BundProjectTopics( - institution_id=normalized_id, - organization_name=organization_name, - project_count=len(project_ids), - matched_project_count=len(matched_project_ids), - topics=topic_list, - ) - - -async def _get_dfg_project_ids_from_projects_service( - institution_id: str, - from_year: int | None = None, - to_year: int | None = None, -) -> list[str]: - """Returns every matching DFG project ID through the canonical project service.""" - period = _dashboard_period(from_year, to_year) - page_size = 1000 - page_number = 0 - project_ids: set[str] = set() - - while True: - projects = await projects_service.get_dfg_projects( - institutions_search_client=InstitutionsSearchClient(), - raw_oa_institution_id=_raw_institution_id(institution_id), - author_id=None, - author_filter_ids=None, - institution_ids=None, - keywords=None, - topic_ids=None, - filter_topic_ids=None, - title=None, - funding_start_years=( - [str(year) for year in range(1900, period[1] + 1)] - if period[1] is not None - else None - ), - funding_end_years=( - [str(year) for year in range(period[0], 2101)] - if period[0] is not None - else None - ), - page=page_number, - size=page_size, - sort_by="id", - sort_direction="asc", - fuzzy=False, - skip_enrichment=True, - ) - project_ids.update(project.id for project in projects.elements if project.id) - if len(project_ids) >= projects.total or not projects.elements: - break - page_number += 1 - - return sorted(project_ids) - - -async def _get_dfg_project_ids_for_institution( - institution_id: str, - from_year: int | None = None, - to_year: int | None = None, -) -> list[str]: - period = _dashboard_period(from_year, to_year) - institution = await get_openalex_institution(institution_id) - institution_names = _openalex_institution_names(institution) - - institutes_response = await elasticsearch.search( - index=ESIndex.DFG_INSTITUTES_V2, - body={ - "size": 0, - "query": _dfg_institute_name_query(institution_names), - "aggs": { - "institute_ids": { - "terms": {"field": "institute_id", "size": 1000} - } - }, - }, - cluster=ESCluster.INSE, - ) - institute_ids = [ - bucket["key"] - for bucket in ( - institutes_response.get("aggregations", {}) - .get("institute_ids", {}) - .get("buckets", []) - ) - if bucket.get("key") is not None - ] - if not institute_ids: - return [] - - projects_response = await elasticsearch.search( - index=ESIndex.DFG_INSTITUTES_V2, - body={ - "size": 0, - "query": {"terms": {"institute_id": institute_ids}}, - "aggs": { - "projects_nested": { - "nested": {"path": "projects"}, - "aggs": { - "project_ids": { - "filter": { - "terms": {"projects.institute_ref_id": institute_ids} - }, - "aggs": { - "values": { - "terms": { - "field": "projects.project_id", - "size": 10000, - } - } - }, - } - }, - } - }, - }, - cluster=ESCluster.INSE, - ) - project_ids = [ - str(bucket["key"]) - for bucket in ( - projects_response.get("aggregations", {}) - .get("projects_nested", {}) - .get("project_ids", {}) - .get("values", {}) - .get("buckets", []) - ) - if bucket.get("key") is not None - ] - return await _filter_dfg_project_ids_by_period(project_ids, period) - - -async def _eu_project_ids_for_aliases(aliases: list[str]) -> set[str]: - project_ids: set[str] = set() - async for hit in elasticsearch.scan( - index=str(ESIndex.CORDIS_EU_ORGANIZATIONS_WILDCARD), - query=_eu_organization_query(aliases), - source=["projectID"], - page_size=1000, - cluster=ESCluster.INSE, - ): - project_id = hit.get("_source", {}).get("projectID") - if project_id is not None: - project_ids.add(str(project_id)) - return project_ids - - -async def _count_eu_projects_in_period( - project_ids: set[str], - period_filter: dict[str, Any], -) -> int: - if not project_ids: - return 0 - response = await elasticsearch.search( - index=ESIndex.CORDIS_EU_PROJECTS_WILDCARD, - body={ - "size": 0, - "query": { - "bool": { - "filter": [ - {"terms": {"id": sorted(project_ids)}}, - period_filter, - ] - } - }, - "aggs": {"projects": {"cardinality": {"field": "id"}}}, - }, - cluster=ESCluster.INSE, - ) - return int( - response.get("aggregations", {}) - .get("projects", {}) - .get("value", 0) - ) - - -async def _filter_dfg_project_ids_by_period( - project_ids: list[str], - period: DashboardPeriod, -) -> list[str]: - period_filter = _project_overlap_filter( - "funding_start", - "funding_end", - period, - missing_end_is_ongoing=True, - ) - if not project_ids or not period_filter: - return project_ids - - numeric_project_ids = [ - int(project_id) - for project_id in project_ids - if str(project_id).isdigit() - ] - if not numeric_project_ids: - return [] - - response = await elasticsearch.search( - index=ESIndex.DFG_PROJECTS, - body={ - "size": 0, - "query": { - "bool": { - "filter": [ - {"terms": {"id": numeric_project_ids}}, - period_filter, - ] - } - }, - "aggs": { - "project_ids": { - "terms": { - "field": "id", - "size": len(numeric_project_ids), - } - } - }, - }, - cluster=ESCluster.INSE, - ) - return [ - str(bucket["key"]) - for bucket in ( - response.get("aggregations", {}) - .get("project_ids", {}) - .get("buckets", []) - ) - if bucket.get("key") is not None - ] - - -def _dashboard_statistic_value( - institution_id: str, - organization_name: str, - response: dict[str, Any], -) -> DashboardStatisticValue: - return DashboardStatisticValue( - institution_id=institution_id, - organization_name=organization_name, - value=_total(response), - ) - - -async def _institution_aliases( - institution_id: str, - organization_name: str, -) -> list[str]: - aliases = await InstitutionsSearchClient().get_institution_aliases_by_oa_institution_id( - _raw_institution_id(institution_id) - ) - return sorted( - { - alias.strip() - for alias in [organization_name, *aliases] - if alias and alias.strip() - } - ) - - -def _eu_organization_query(aliases: list[str]) -> dict[str, Any]: - return { - "terms": { - "name.keyword": [alias.upper() for alias in aliases], - } - } - - -def _alias_match_query(field: str, aliases: list[str]) -> dict[str, Any]: - return { - "bool": { - "should": [ - { - "match": { - field: { - "query": alias, - "operator": "and", - } - } - } - for alias in aliases - ], - "minimum_should_match": 1, - } - } - - -def _openalex_institution_names(institution: Any) -> list[str]: - return sorted( - { - name.strip() - for name in [ - institution.display_name, - *(institution.display_name_alternatives or []), - *(institution.display_name_acronyms or []), - ] - if name and name.strip() - } - ) - - -def _dfg_institute_name_query(institution_names: list[str]) -> dict[str, Any]: - return { - "bool": { - "should": [ - { - "terms": { - "institute_name_de.keyword": institution_names, - } - }, - { - "terms": { - "institute_name_en.keyword": institution_names, - } - }, - ], - "minimum_should_match": 1, - } - } - - -async def get_top_authors( - institution_id: str, - organization_name: str, - works_period: WorksPeriod = "all_time", - from_year: int | None = None, - to_year: int | None = None, -) -> TopAuthorStatistics: - normalized_id = _normalize_institution_id(institution_id) - if from_year is None and to_year is None and works_period == "last_5_years": - from_year = datetime.now().year - 4 - to_year = datetime.now().year - period = _dashboard_period(from_year, to_year) - authors = await _safe_institution_authors(normalized_id) - works = await _safe_top_authors( - "works", - _top_work_authors(normalized_id, period), - ) - projects = await _safe_top_authors( - "projects", - _top_project_authors( - authors=authors, - organization_name=organization_name, - from_year=period[0], - to_year=period[1], - ), - ) - eu_projects = await _safe_top_authors( - "eu_projects", - _top_eu_project_publication_authors( - normalized_id, - authors, - from_year=period[0], - to_year=period[1], - ), - ) - - patents = await _safe_top_authors( - "patents", - _top_patent_authors( - normalized_id, - from_year=period[0], - to_year=period[1], - ), - ) - - news = await _safe_top_authors( - "news", - _top_news_authors( - authors, - from_year=period[0], - to_year=period[1], - ), - ) - - return TopAuthorStatistics( - institution_id=normalized_id, - works=works, - projects=projects, - eu_projects=eu_projects, - patents=patents, - news=news, - ) - - async def get_topic_heatmap( institution_id: str, organization_name: str, @@ -1721,39 +418,9 @@ async def get_topic_word_cloud( return TopicWordCloud(topic_id=topic_id, words=words) -async def _safe_top_authors( - source: str, operation: Any -) -> list[TopAuthor]: - try: - return await operation - except Exception: - logger.exception("Dashboard top-author aggregation failed for %s.", source) - return [] - - -def _normalize_institution_id(value: str) -> str: - short_id = value.replace("https://openalex.org/", "").strip().upper() - return f"https://openalex.org/{short_id}" - - -def _raw_institution_id(value: str) -> str: - return value.replace("https://openalex.org/", "").strip().upper() - - -def _institution_works_query(institution_id: str) -> dict[str, Any]: - return { - "nested": { - "path": "authorships.institutions", - "query": {"term": {"authorships.institutions.id": institution_id}}, - } - } - - def _year_totals(response: dict[str, Any]) -> dict[int, int]: buckets = ( - response.get("aggregations", {}) - .get("publication_years", {}) - .get("buckets", []) + response.get("aggregations", {}).get("publication_years", {}).get("buckets", []) ) return { int(bucket["key"]): int(bucket.get("doc_count", 0)) @@ -1781,8 +448,7 @@ async def _field_names(field_ids: list[str | None]) -> dict[str, str]: return { source["id"]: source["display_name"] for hit in response.get("hits", {}).get("hits", []) - if (source := hit.get("_source", {})).get("id") - and source.get("display_name") + if (source := hit.get("_source", {})).get("id") and source.get("display_name") } @@ -1858,930 +524,8 @@ def _field_name(bucket: dict[str, Any], fallback: str) -> str: return _aggregation_name(bucket, "field_name", fallback) -def _aggregation_name( - bucket: dict[str, Any], aggregation: str, fallback: str -) -> str: +def _aggregation_name(bucket: dict[str, Any], aggregation: str, fallback: str) -> str: name_buckets = bucket.get(aggregation, {}).get("buckets", []) if name_buckets and name_buckets[0].get("key"): return str(name_buckets[0]["key"]) return fallback - - -def _short_author_id(value: str) -> str: - return value.replace("https://openalex.org/", "").strip().upper() - - -async def _top_work_authors( - institution_id: str, - period: DashboardPeriod, -) -> list[TopAuthor]: - must = [works_v2_service._institutions_nested_query([institution_id])] - if publication_years := _dashboard_publication_years(period): - must.append({"terms": {"publication_year": publication_years}}) - - author_counts: dict[str, int] = defaultdict(int) - author_names: dict[str, str] = {} - async for hit in elasticsearch.scan( - index=str(ESIndex.OPENALEX_WORKS_WILDCARD), - query={"bool": {"must": must}}, - source=["id", "authorships.author.id", "authorships.author.display_name"], - page_size=1000, - cluster=ESCluster.NES, - ): - hit_author_ids: set[str] = set() - for authorship in hit.get("_source", {}).get("authorships", []): - author = authorship.get("author") or {} - author_id = author.get("id") - if not author_id: - continue - author_id = str(author_id) - hit_author_ids.add(author_id) - if author.get("display_name"): - author_names.setdefault(author_id, str(author["display_name"])) - for author_id in hit_author_ids: - author_counts[author_id] += 1 - - ranked_authors = sorted( - ( - { - "id": author_id, - "name": author_names.get(author_id, author_id), - "count": count, - } - for author_id, count in author_counts.items() - ), - key=lambda author: author["count"], - reverse=True, - ) - return [ - TopAuthor( - id=_short_author_id(author["id"]), - name=author["name"], - count=author["count"], - ) - for author in ranked_authors[:TOP_AUTHOR_LIMIT] - if author["count"] > 0 - ] - - -async def _safe_institution_authors(institution_id: str) -> list[dict[str, Any]]: - try: - return await _institution_authors(institution_id) - except Exception: - logger.exception("Could not load authors for institution %s.", institution_id) - return [] - - -async def _institution_authors(institution_id: str) -> list[dict[str, Any]]: - response = await elasticsearch.search( - index=ESIndex.OPENALEX_AUTHORS, - query={ - "nested": { - "path": "last_known_institutions", - "query": {"term": {"last_known_institutions.id": institution_id}}, - } - }, - source=["id", "display_name", "works_count", "counts_by_year"], - size=10000, - sort=[{"works_count": {"order": "desc", "missing": "_last"}}], - cluster=ESCluster.NES, - ) - return [ - { - "id": str(source["id"]), - "name": str(source["display_name"]), - "works_count": int(source.get("works_count", 0)), - "counts_by_year": source.get("counts_by_year", []) or [], - } - for hit in response.get("hits", {}).get("hits", []) - if (source := hit.get("_source", {})).get("id") - and source.get("display_name") - ] - - -async def _top_project_authors( - authors: list[dict[str, Any]], - organization_name: str, - from_year: int | None = None, - to_year: int | None = None, -) -> list[TopAuthor]: - period = _dashboard_period(from_year, to_year) - institution_ids = await _dfg_institution_ids_for_organization( - organization_name=organization_name, - ) - - logger.info( - "DFG institution IDs for %s: %s", - organization_name, - institution_ids, - ) - - if not institution_ids: - logger.warning( - "No DFG institution IDs found for organization %s.", - organization_name, - ) - return [] - - selected_person_ids = set( - await get_person_ids_by_institution_ids(institution_ids=institution_ids) - ) - - logger.info( - "Found %s DFG persons for organization %s.", - len(selected_person_ids), - organization_name, - ) - - if not selected_person_ids: - return [] - - project_ids_by_person: dict[int, set[str]] = {} - names: dict[int, str] = {} - - page = 0 - size = 10000 - processed = 0 - - while True: - project_hits, total = await _dfg_project_author_hits( - page=page, - size=size, - person_ids=selected_person_ids, - period=period, - ) - - if not project_hits: - break - - for project in project_hits: - project_id = _dfg_project_id(project) - if not project_id: - continue - - persons = project.get("persons", []) - if not isinstance(persons, list): - continue - - for person in persons: - if not isinstance(person, dict): - continue - - person_id = person.get("person_id") - full_name = person.get("full_name") - if person_id is None or not full_name: - continue - - try: - normalized_person_id = int(person_id) - except (TypeError, ValueError): - continue - - if normalized_person_id not in selected_person_ids: - continue - - project_ids_by_person.setdefault(normalized_person_id, set()).add( - project_id - ) - names[normalized_person_id] = str(full_name).strip() - - processed += len(project_hits) - if processed >= total: - break - - page += 1 - - institution_authors: dict[str, list[dict[str, Any]]] = {} - for author in authors: - if author.get("name"): - institution_authors.setdefault( - _normalize_person_name(author["name"]), - [], - ).append(author) - - ranked = sorted( - ( - (person_id, project_ids) - for person_id, project_ids in project_ids_by_person.items() - if project_ids and names.get(person_id) - ), - key=lambda item: ( - -len(item[1]), - names[item[0]].casefold(), - ), - ) - - ranked_person_ids = [person_id for person_id, _ in ranked[:TOP_AUTHOR_LIMIT]] - dfg_orcids = await _dfg_person_orcids(ranked_person_ids) - - result: list[TopAuthor] = [] - - for person_id, project_ids in ranked[:TOP_AUTHOR_LIMIT]: - dfg_name = names[person_id] - matched_author = _single_author_match( - institution_authors.get(_normalize_person_name(dfg_name), []) - ) - - if matched_author is None and (orcid := dfg_orcids.get(person_id)): - matched_author = await _openalex_author_by_orcid(orcid) - - if matched_author is None: - matched_author = await _openalex_author_by_dfg_publication_evidence( - dfg_name=dfg_name, - project_ids=project_ids, - ) - - if matched_author is None: - logger.info( - "No exact OpenAlex match for DFG author '%s' (person_id=%s).", - dfg_name, - person_id, - ) - - result.append( - TopAuthor( - id=( - _short_author_id(matched_author["id"]) - if matched_author - else None - ), - name=matched_author["name"] if matched_author else dfg_name, - count=len(project_ids), - ) - ) - - logger.info( - "DFG top authors for %s: %s", - organization_name, - [ - { - "name": author.name, - "count": author.count, - "id": author.id, - } - for author in result - ], - ) - - return result - - -def _single_author_match(authors: list[dict[str, Any]]) -> dict[str, Any] | None: - return authors[0] if len(authors) == 1 else None - - -async def _dfg_person_orcids(person_ids: list[int]) -> dict[int, str]: - if not person_ids: - return {} - - try: - response = await elasticsearch.search( - index=ESIndex.DFG_PERSONS, - body={ - "size": len(person_ids), - "_source": ["person_id", "orcid_id"], - "query": {"terms": {"person_id": person_ids}}, - }, - cluster=ESCluster.INSE, - ) - except Exception: - logger.exception("Could not load DFG ORCIDs for top project authors.") - return {} - - result: dict[int, str] = {} - for hit in response.get("hits", {}).get("hits", []): - source = hit.get("_source", {}) - person_id = source.get("person_id") - orcid = source.get("orcid_id") - if person_id is None or not orcid: - continue - try: - result[int(person_id)] = str(orcid) - except (TypeError, ValueError): - continue - return result - - -async def _openalex_author_by_orcid(orcid: str) -> dict[str, Any] | None: - normalized_orcid = orcid.replace("https://orcid.org/", "").strip() - if not normalized_orcid: - return None - - prefixed_orcid = f"https://orcid.org/{normalized_orcid}" - try: - response = await elasticsearch.search( - index=ESIndex.OPENALEX_AUTHORS, - body={ - "size": 2, - "_source": ["id", "display_name"], - "query": { - "bool": { - "should": [ - {"term": {"orcid.keyword": normalized_orcid}}, - {"term": {"orcid.keyword": prefixed_orcid}}, - {"term": {"ids.orcid.keyword": normalized_orcid}}, - {"term": {"ids.orcid.keyword": prefixed_orcid}}, - {"term": {"orcid": normalized_orcid}}, - {"term": {"orcid": prefixed_orcid}}, - {"term": {"ids.orcid": normalized_orcid}}, - {"term": {"ids.orcid": prefixed_orcid}}, - ], - "minimum_should_match": 1, - } - }, - }, - cluster=ESCluster.NES, - track_total_hits=True, - ) - except Exception: - logger.exception("Could not resolve OpenAlex author by ORCID %s.", orcid) - return None - - hits = response.get("hits", {}).get("hits", []) - if len(hits) != 1: - logger.info( - "OpenAlex ORCID lookup for %s returned %s hits.", - orcid, - len(hits), - ) - return None - - source = hits[0].get("_source", {}) - if not source.get("id") or not source.get("display_name"): - return None - return { - "id": str(source["id"]), - "name": str(source["display_name"]), - } - - -async def _openalex_author_by_dfg_publication_evidence( - dfg_name: str, - project_ids: set[str], -) -> dict[str, Any] | None: - dois = await _dfg_project_publication_dois(project_ids) - if not dois: - return None - - try: - response = await elasticsearch.search( - index=config.settings.openalex_works_search_index, - body={ - "size": 10000, - "_source": [ - "doi", - "authorships.author.id", - "authorships.author.display_name", - ], - "query": {"terms": {"doi": sorted(_doi_variants(dois))}}, - }, - cluster=ESCluster.NES, - ) - except Exception: - logger.exception( - "Could not resolve OpenAlex author from DFG publication DOIs for %s.", - dfg_name, - ) - return None - - candidates: dict[str, dict[str, Any]] = {} - for hit in response.get("hits", {}).get("hits", []): - source = hit.get("_source", {}) - doi = source.get("doi") - if not doi: - continue - for authorship in source.get("authorships", []) or []: - author = authorship.get("author", {}) if isinstance(authorship, dict) else {} - author_id = author.get("id") - display_name = author.get("display_name") - if not author_id or not display_name: - continue - if not _is_supported_name_variant(dfg_name, str(display_name)): - continue - candidate = candidates.setdefault( - str(author_id), - { - "id": str(author_id), - "name": str(display_name), - "dois": set(), - }, - ) - candidate["dois"].add(str(doi)) - - supported_candidates = [ - candidate - for candidate in candidates.values() - if len(candidate["dois"]) >= 2 - ] - if len(supported_candidates) != 1: - if supported_candidates: - logger.info( - "DFG publication DOI lookup for %s returned %s candidates.", - dfg_name, - len(supported_candidates), - ) - return None - - candidate = supported_candidates[0] - return { - "id": candidate["id"], - "name": candidate["name"], - } - - -async def _dfg_project_publication_dois(project_ids: set[str]) -> set[str]: - if not project_ids: - return set() - - numeric_project_ids = [ - int(project_id) - for project_id in project_ids - if str(project_id).isdigit() - ] - if not numeric_project_ids: - return set() - - try: - response = await elasticsearch.search( - index=ESIndex.DFG_PROJECTS, - body={ - "size": len(numeric_project_ids), - "_source": ["publications.doi"], - "query": {"terms": {"id": numeric_project_ids}}, - }, - cluster=ESCluster.INSE, - ) - except Exception: - logger.exception("Could not load DFG publication DOIs.") - return set() - - dois: set[str] = set() - for hit in response.get("hits", {}).get("hits", []): - for publication in hit.get("_source", {}).get("publications", []) or []: - doi = publication.get("doi") if isinstance(publication, dict) else None - if doi: - dois.add(str(doi).strip()) - return {doi for doi in dois if doi} - - -def _doi_variants(dois: set[str]) -> set[str]: - variants: set[str] = set() - for doi in dois: - normalized = doi.strip() - if not normalized: - continue - raw = normalized - for prefix in ("https://doi.org/", "http://dx.doi.org/"): - if raw.casefold().startswith(prefix): - raw = raw[len(prefix):] - break - variants.update( - { - normalized, - normalized.lower(), - f"https://doi.org/{raw}", - f"https://doi.org/{raw.lower()}", - } - ) - return variants - - -async def _dfg_institution_ids_for_organization(organization_name: str) -> list[int]: - page = await autocomplete_institutions_for_selector( - query=organization_name, - page=0, - size=10000, - ) - return [institution.id for institution in page.elements if institution.id is not None] - - -async def _dfg_project_author_hits( - page: int, - size: int, - person_ids: set[int], - period: DashboardPeriod = (None, None), -) -> tuple[list[dict[str, Any]], int]: - person_query = { - "nested": { - "path": "persons", - "query": {"terms": {"persons.person_id": sorted(person_ids)}}, - }, - } - period_filter = _project_overlap_filter( - "funding_start", - "funding_end", - period, - missing_end_is_ongoing=True, - ) - query = ( - {"bool": {"filter": [person_query, period_filter]}} - if period_filter - else person_query - ) - response = await elasticsearch.search( - index=ESIndex.DFG_PROJECTS, - body={ - "size": size, - "from": page * size, - "_source": [ - "id", - "project_id", - "persons", - ], - "query": query, - "sort": [ - { - "id": { - "order": "asc", - "missing": "_last", - } - } - ], - }, - cluster=ESCluster.INSE, - track_total_hits=True, - ) - - hits_block = response.get("hits", {}) - total_value = hits_block.get("total", 0) - - if isinstance(total_value, dict): - total = int(total_value.get("value", 0)) - else: - total = int(total_value or 0) - - hits = [ - hit.get("_source", {}) - for hit in hits_block.get("hits", []) - if isinstance(hit.get("_source"), dict) - ] - - logger.info( - "Loaded %s of %s matching DFG projects on page %s.", - len(hits), - total, - page, - ) - - return hits, total - - -def _dfg_project_id(project: dict[str, Any]) -> str | None: - project_id = project.get("id") - if project_id is None: - project_id = project.get("project_id") - return str(project_id) if project_id is not None else None - - -async def _top_patent_authors( - institution_id: str, - from_year: int | None = None, - to_year: int | None = None, -) -> list[TopAuthor]: - client = OrgPatentsSearchClient() - authors = await client.top_authors_by_institution( - institution_id=institution_id, - size=TOP_AUTHOR_LIMIT, - from_year=from_year, - to_year=to_year, - ) - return [ - TopAuthor( - id=_short_author_id(author["id"]), - name=author["name"], - count=author["count"], - ) - for author in authors - ] - - -async def _top_eu_project_publication_authors( - institution_id: str, - institution_authors: list[dict[str, Any]], - from_year: int | None = None, - to_year: int | None = None, -) -> list[TopAuthor]: - institution_author_ids = { - author_id - for author in institution_authors - if (author_id := _normalize_author_id(author.get("id"))) - } - if not institution_author_ids: - return [] - - project_ids = await _get_eu_project_ids_from_projects_service( - institution_id, - from_year=from_year, - to_year=to_year, - ) - - if not project_ids: - return [] - - publication_response = await elasticsearch.search( - index=ESIndex.CORDIS_EU_PUBLICATIONS_WILDCARD, - body={ - "size": 10000, - "_source": ["projectID", "qaProcessedDoi"], - "query": {"terms": {"projectID": project_ids}}, - }, - cluster=ESCluster.INSE, - ) - - doi_project_ids = _cordis_publication_doi_project_ids( - publication_response, - set(project_ids), - ) - if not doi_project_ids: - return [] - - works_response = await elasticsearch.search( - index="openalex-works", - body={ - "size": 10000, - "_source": [ - "doi", - "authorships.author.id", - "authorships.author.display_name", - "authorships.institutions.id", - ], - "query": { - "bool": { - "filter": [ - {"terms": {"doi": sorted(doi_project_ids)}}, - _institution_works_query(institution_id), - ] - } - }, - }, - cluster=ESCluster.NES, - ) - - candidates = _openalex_work_authors_by_eu_projects( - works_response, - doi_project_ids, - institution_id, - institution_author_ids, - limit=None, - ) - counts = await asyncio.gather( - *( - _person_eu_project_count( - candidate.id, - from_year=from_year, - to_year=to_year, - ) - for candidate in candidates - if candidate.id - ) - ) - ranked = [ - TopAuthor(id=candidate.id, name=candidate.name, count=count) - for candidate, count in zip(candidates, counts, strict=True) - ] - ranked.sort(key=lambda author: (-author.count, author.name, author.id or "")) - return ranked[:TOP_AUTHOR_LIMIT] - - -async def _get_eu_project_ids_from_projects_service( - institution_id: str, - from_year: int | None = None, - to_year: int | None = None, -) -> list[str]: - """Loads all organization EU project IDs from the canonical project service.""" - period = _dashboard_period(from_year, to_year) - page_size = 1000 - page_number = 0 - project_ids: set[str] = set() - - while True: - projects = await projects_service.search_eu_cordis_projects( - institutions_search_client=InstitutionsSearchClient(), - raw_oa_institution_id=_raw_institution_id(institution_id), - author_id=None, - author_ids=None, - organization_ids=None, - organization_names=None, - project_types=list(EuCordisProjectType), - keywords=None, - topic_ids=None, - filter_topic_ids=None, - title=None, - funding_start_years=None, - funding_end_years=None, - active_from_year=period[0], - active_to_year=period[1], - countries=None, - framework_programmes=None, - funding_schemes=None, - statuses=None, - page=page_number, - size=page_size, - sort_by="id", - sort_direction="asc", - fuzzy=False, - skip_enrichment=True, - ) - project_ids.update(project.id for project in projects.elements if project.id) - if len(project_ids) >= projects.total or not projects.elements: - break - page_number += 1 - - return sorted(project_ids) - - -def _cordis_publication_doi_project_ids( - response: dict[str, Any], - allowed_project_ids: set[str], -) -> dict[str, set[str]]: - doi_project_ids: dict[str, set[str]] = defaultdict(set) - for hit in response.get("hits", {}).get("hits", []): - source = hit.get("_source", {}) - project_id = str(source.get("projectID") or "").strip() - if not project_id or project_id not in allowed_project_ids: - continue - doi = _normalize_doi(source.get("qaProcessedDoi")) - if doi: - doi_project_ids[doi].add(project_id) - return dict(doi_project_ids) - - -def _normalize_doi(value: Any) -> str | None: - if not isinstance(value, str) or not value.strip(): - return None - doi = value.strip().lower() - if doi.startswith("https://doi.org/"): - return doi - if doi.startswith("http://doi.org/"): - return "https://" + doi.removeprefix("http://") - if doi.startswith("doi.org/"): - return f"https://{doi}" - return f"https://doi.org/{doi}" - - -def _openalex_work_authors_by_eu_projects( - response: dict[str, Any], - doi_project_ids: dict[str, set[str]], - institution_id: str, - institution_author_ids: set[str], - limit: int | None = TOP_AUTHOR_LIMIT, -) -> list[TopAuthor]: - # Count unique CORDIS projects per author, not publications. Multiple works - # (and therefore multiple DOIs) can belong to the same project ID. - author_project_ids: dict[str, set[str]] = defaultdict(set) - author_names: dict[str, str] = {} - - for hit in response.get("hits", {}).get("hits", []): - source = hit.get("_source", {}) - project_ids = doi_project_ids.get(_normalize_doi(source.get("doi")) or "") - if not project_ids: - continue - - for authorship in source.get("authorships") or []: - if not any( - institution.get("id") == institution_id - for institution in authorship.get("institutions") or [] - ): - continue - author = authorship.get("author") or {} - author_id = _normalize_author_id(author.get("id")) - author_name = str(author.get("display_name") or "").strip() - if ( - not author_id - or author_id not in institution_author_ids - or not author_name - ): - continue - author_project_ids[author_id].update(project_ids) - author_names.setdefault(author_id, author_name) - - ranked_authors = sorted( - author_project_ids.items(), - key=lambda item: (-len(item[1]), author_names.get(item[0], ""), item[0]), - ) - - authors = [ - TopAuthor( - id=_short_author_id(author_id), - name=author_names[author_id], - count=len(project_ids), - ) - for author_id, project_ids in ranked_authors - ] - return authors[:limit] if limit is not None else authors - - -async def _person_eu_project_count( - author_id: str, - from_year: int | None = None, - to_year: int | None = None, -) -> int: - """Returns the same filtered EU project total as the person projects tab.""" - period = _dashboard_period(from_year, to_year) - projects = await projects_service.search_eu_cordis_projects( - page=0, - size=1, - project_types=None, - raw_oa_institution_id=None, - institutions_search_client=None, - author_id=_short_author_id(author_id), - author_ids=None, - organization_ids=None, - organization_names=None, - keywords=None, - topic_ids=None, - filter_topic_ids=None, - title=None, - funding_start_years=None, - funding_end_years=None, - active_from_year=period[0], - active_to_year=period[1], - countries=None, - framework_programmes=None, - funding_schemes=None, - statuses=None, - sort_by="title", - sort_direction="asc", - fuzzy=False, - skip_enrichment=True, - ) - return projects.total - - -def _normalize_author_id(value: Any) -> str | None: - if not isinstance(value, str) or not value.strip(): - return None - short_id = value.replace("https://openalex.org/", "").strip().upper() - return f"https://openalex.org/{short_id}" - - -async def _top_news_authors( - authors: list[dict[str, Any]], - from_year: int | None = None, - to_year: int | None = None, -) -> list[TopAuthor]: - if not authors: - return [] - - period = _dashboard_period(from_year, to_year) - author_names = [author["name"] for author in authors] - filters: list[dict[str, Any]] = [ - {"terms": {"authors.keyword": author_names}} - ] - if period != (None, None): - date_range: dict[str, int] = {} - if period[0] is not None: - date_range["gte"] = period[0] - if period[1] is not None: - date_range["lte"] = period[1] - news_ids = [ - str(hit["_id"]) - async for hit in elasticsearch.scan( - index=str(ESIndex.AKTUELLES), - query={"range": {"date_year": date_range}}, - source=False, - page_size=1000, - cluster=ESCluster.INSE, - ) - if hit.get("_id") - ] - if not news_ids: - return [] - filters.append({"terms": {"news_id.keyword": news_ids}}) - - response = await elasticsearch.search( - index="aktuell_postproc", - body={ - "size": 0, - "query": ( - filters[0] - if len(filters) == 1 - else {"bool": {"filter": filters}} - ), - "aggs": { - "authors": { - "terms": { - "field": "authors.keyword", - "size": 10000, - "order": [ - {"_count": "desc"}, - {"_key": "asc"}, - ], - } - } - }, - }, - cluster=ESCluster.INSE, - ) - buckets = response.get("aggregations", {}).get("authors", {}).get("buckets", []) - institution_authors = {author["name"].casefold(): author for author in authors} - - return [ - TopAuthor( - id=_short_author_id(institution_authors[str(bucket["key"]).casefold()]["id"]), - name=institution_authors[str(bucket["key"]).casefold()]["name"], - count=int(bucket.get("doc_count", 0)), - ) - for bucket in buckets - if str(bucket.get("key", "")).casefold() in institution_authors - ][:TOP_AUTHOR_LIMIT] diff --git a/service/src/main/inse/dashboard/test_service.py b/service/src/main/inse/dashboard/test_service.py index 648097f6..2e8cc6c0 100644 --- a/service/src/main/inse/dashboard/test_service.py +++ b/service/src/main/inse/dashboard/test_service.py @@ -1,6 +1,5 @@ from datetime import datetime import hashlib -from types import SimpleNamespace from unittest.mock import AsyncMock, patch import pytest @@ -10,25 +9,33 @@ from sqlmodel import Session, SQLModel, create_engine from inse import config from inse.auth.model import AccessToken, Organization, UserRole from inse.dashboard.service import ( - _get_dfg_project_ids_from_projects_service, - _openalex_work_authors_by_eu_projects, - _project_boundary_year_filter, - _reconcile_project_status_counts, - _top_news_authors, - get_dashboard_bmbf_projects, - get_dashboard_bund_topics, - get_dashboard_dfg_projects, - get_dashboard_eu_projects, - get_dashboard_eu_topics, get_dashboard_organization, get_dashboard_persons, get_dashboard_publications, get_dashboard_statistics, - get_top_authors, get_topic_heatmap, get_topic_word_cloud, ) -from inse.model import ESCluster, ESIndex +from inse.dashboard.common import ( + project_boundary_year_filter as _project_boundary_year_filter, +) +from inse.dashboard.bund_topics_service import get_dashboard_bund_topics +from inse.dashboard.eu_topics_service import get_dashboard_eu_topics +from inse.dashboard.project_status_service import reconcile_status_counts +from inse.dashboard.project_ids_service import ( + _get_dfg_project_ids_from_projects_service, +) +from inse.dashboard.project_statistics_service import ( + get_dashboard_bmbf_projects, + get_dashboard_dfg_projects, + get_dashboard_eu_projects, +) +from inse.dashboard.top_authors_service import ( + _openalex_work_authors_by_eu_projects, + _top_news_authors, + get_top_authors, +) +from inse.model import ESIndex from inse.models.openalex.institution import Institution from inse.models.openalex.meta import Meta from inse.persons.model import CustomAuthorsListResponse @@ -52,8 +59,8 @@ def anyio_backend(): def test_project_status_counts_match_authoritative_total(): - assert _reconcile_project_status_counts(12, 4, 1, 5) == (6, 1, 5) - assert _reconcile_project_status_counts(7, 4, 2, 3) == (2, 2, 3) + assert reconcile_status_counts(12, 4, 1, 5) == (6, 1, 5) + assert reconcile_status_counts(7, 4, 2, 3) == (2, 2, 3) def test_project_status_period_uses_interval_overlap(): @@ -86,25 +93,25 @@ def test_project_status_period_uses_interval_overlap(): async def test_top_news_authors_applies_dashboard_period(): response = { "aggregations": { - "authors": { - "buckets": [{"key": "Ada Example", "doc_count": 3}] - } + "authors": {"buckets": [{"key": "Ada Example", "doc_count": 3}]} } } + async def scan(**kwargs): assert kwargs["index"] == str(ESIndex.AKTUELLES) - assert kwargs["query"] == { - "range": {"date_year": {"gte": 2020, "lte": 2023}} - } + assert kwargs["query"] == {"range": {"date_year": {"gte": 2020, "lte": 2023}}} yield {"_id": "N1"} yield {"_id": "N2"} - with patch( - "inse.dashboard.service.elasticsearch.search", - new=AsyncMock(return_value=response), - ) as mocked_search, patch( - "inse.dashboard.service.elasticsearch.scan", - new=scan, + with ( + patch( + "inse.integrations.elasticsearch.search", + new=AsyncMock(return_value=response), + ) as mocked_search, + patch( + "inse.integrations.elasticsearch.scan", + new=scan, + ), ): result = await _top_news_authors( [{"id": "https://openalex.org/A1", "name": "Ada Example"}], @@ -141,7 +148,7 @@ async def test_dfg_topic_project_ids_use_paginated_projects_service(): ] with patch( - "inse.dashboard.service.projects_service.get_dfg_projects", + "inse.projects.service.get_dfg_projects", new=AsyncMock(side_effect=pages), ) as mocked_get_projects: project_ids = await _get_dfg_project_ids_from_projects_service( @@ -213,10 +220,13 @@ async def test_eu_topics_scan_all_programme_indices_and_deduplicate_projects(): } } - with patch( - "inse.dashboard.service._get_eu_project_ids_from_projects_service", - new=AsyncMock(return_value=["P1", "P2", "P3"]), - ), patch("inse.dashboard.service.elasticsearch.scan", new=scan): + with ( + patch( + "inse.dashboard.eu_topics_service._get_eu_project_ids_from_projects_service", + new=AsyncMock(return_value=["P1", "P2", "P3"]), + ), + patch("inse.integrations.elasticsearch.scan", new=scan), + ): result = await get_dashboard_eu_topics( ORG_INSTITUTION_ID, "Example Org", @@ -282,12 +292,15 @@ async def test_bund_topics_use_mapping_index_and_unique_hierarchy_counts(): } } - with patch( - "inse.dashboard.service.projects_service.search_bund_projects_with_filters", - new=AsyncMock(return_value=project_page), - ) as mocked_projects, patch( - "inse.dashboard.service.elasticsearch.scan", - new=scan, + with ( + patch( + "inse.projects.service.search_bund_projects_with_filters", + new=AsyncMock(return_value=project_page), + ) as mocked_projects, + patch( + "inse.integrations.elasticsearch.scan", + new=scan, + ), ): result = await get_dashboard_bund_topics( ORG_INSTITUTION_ID, @@ -328,9 +341,7 @@ async def test_dashboard_statistics_counts_organization_data_and_all_projects(): if index == ESIndex.DFG_INSTITUTES_V2: if "institute_ids" in kwargs["body"].get("aggs", {}): return { - "aggregations": { - "institute_ids": {"buckets": [{"key": 10210}]} - } + "aggregations": {"institute_ids": {"buckets": [{"key": 10210}]}} } return { "aggregations": { @@ -350,48 +361,59 @@ async def test_dashboard_statistics_counts_organization_data_and_all_projects(): return {"hits": {"total": {"value": 3}}} - with patch( - "inse.dashboard.service.elasticsearch.search", - new=AsyncMock(side_effect=search), - ) as mocked_search, patch( - "inse.dashboard.service.InstitutionsSearchClient.get_institution_aliases_by_oa_institution_id", - new=AsyncMock(return_value=["Example University", "Example Uni"]), - ), patch( - "inse.dashboard.service.get_openalex_institution", - new=AsyncMock( - return_value=Institution( - id=ORG_INSTITUTION_ID, - display_name="Example University", - display_name_alternatives=["Example Universität"], - ) + with ( + patch( + "inse.integrations.elasticsearch.search", + new=AsyncMock(side_effect=search), ), - ), patch( - "inse.dashboard.service.projects_service.get_dfg_projects", - new=AsyncMock( - return_value=DfgProjectPage(elements=[], total=3, page=0, size=1) + patch( + "inse.institutions.institutions_search_client.InstitutionsSearchClient.get_institution_aliases_by_oa_institution_id", + new=AsyncMock(return_value=["Example University", "Example Uni"]), ), - ), patch( - "inse.dashboard.service.projects_service.search_eu_cordis_projects", - new=AsyncMock( - return_value=EuCordisProjectSearchPage( - elements=[], total=10, page=0, size=1 - ) + patch( + "inse.dashboard.project_status_service.get_openalex_institution", + new=AsyncMock( + return_value=Institution( + id=ORG_INSTITUTION_ID, + display_name="Example University", + display_name_alternatives=["Example Universität"], + ) + ), ), - ), patch( - "inse.dashboard.service.projects_service.search_bund_projects_with_filters", - new=AsyncMock( - return_value=BundProjectPage(elements=[], total=5, page=0, size=1) + patch( + "inse.projects.service.get_dfg_projects", + new=AsyncMock( + return_value=DfgProjectPage(elements=[], total=3, page=0, size=1) + ), ), - ), patch( - "inse.dashboard.service.persons_service.search_persons_list", - new=AsyncMock( - return_value=CustomAuthorsListResponse( - results=[], meta=Meta(count=35, page=1, per_page=1) - ) + patch( + "inse.projects.service.search_eu_cordis_projects", + new=AsyncMock( + return_value=EuCordisProjectSearchPage( + elements=[], total=10, page=0, size=1 + ) + ), + ), + patch( + "inse.projects.service.search_bund_projects_with_filters", + new=AsyncMock( + return_value=BundProjectPage(elements=[], total=5, page=0, size=1) + ), + ), + patch( + "inse.dashboard.service.persons_service.search_persons_list", + new=AsyncMock( + return_value=CustomAuthorsListResponse( + results=[], meta=Meta(count=35, page=1, per_page=1) + ) + ), + ), + patch( + "inse.dashboard.service.institutions_v2_service.get_institution_by_id_or_raise", + new=AsyncMock( + return_value=Institution(id=ORG_INSTITUTION_ID, works_count=120) + ), ), - ), patch( - "inse.dashboard.service.institutions_v2_service.get_institution_by_id_or_raise", - new=AsyncMock(return_value=Institution(id=ORG_INSTITUTION_ID, works_count=120)), ): result = await get_dashboard_statistics( ORG_INSTITUTION_ID, @@ -409,17 +431,21 @@ async def test_dashboard_statistics_counts_organization_data_and_all_projects(): "bmbf_projects": 5, } + @pytest.mark.anyio async def test_dashboard_publications_uses_exact_es_count_for_period(): - with patch( - "inse.dashboard.service.institutions_v2_service.get_institution_by_id_or_raise", - new=AsyncMock( - return_value=Institution(id=ORG_INSTITUTION_ID, works_count=250) - ), - ) as mocked_get_institution, patch( - "inse.dashboard.service.elasticsearch.count", - new=AsyncMock(return_value=22), - ) as mocked_count: + with ( + patch( + "inse.dashboard.service.institutions_v2_service.get_institution_by_id_or_raise", + new=AsyncMock( + return_value=Institution(id=ORG_INSTITUTION_ID, works_count=250) + ), + ) as mocked_get_institution, + patch( + "inse.integrations.elasticsearch.count", + new=AsyncMock(return_value=22), + ) as mocked_count, + ): all_time = await get_dashboard_publications( ORG_INSTITUTION_ID, "Example Org", @@ -478,7 +504,7 @@ async def test_dashboard_dfg_projects_uses_projects_service_total(): project_page = DfgProjectPage(elements=[], total=42, page=0, size=1) with patch( - "inse.dashboard.service.projects_service.get_dfg_projects", + "inse.projects.service.get_dfg_projects", new=AsyncMock(return_value=project_page), ) as mocked_get_projects: result = await get_dashboard_dfg_projects( @@ -506,7 +532,7 @@ async def test_dashboard_bmbf_projects_uses_projects_service_total(): project_page = BundProjectPage(elements=[], total=29, page=0, size=1) with patch( - "inse.dashboard.service.projects_service.search_bund_projects_with_filters", + "inse.projects.service.search_bund_projects_with_filters", new=AsyncMock(return_value=project_page), ) as mocked_get_projects: result = await get_dashboard_bmbf_projects( @@ -530,12 +556,10 @@ async def test_dashboard_bmbf_projects_uses_projects_service_total(): @pytest.mark.anyio async def test_dashboard_eu_projects_uses_projects_service_total(): - project_page = EuCordisProjectSearchPage( - elements=[], total=37, page=0, size=1 - ) + project_page = EuCordisProjectSearchPage(elements=[], total=37, page=0, size=1) with patch( - "inse.dashboard.service.projects_service.search_eu_cordis_projects", + "inse.projects.service.search_eu_cordis_projects", new=AsyncMock(return_value=project_page), ) as mocked_get_projects: result = await get_dashboard_eu_projects( @@ -588,11 +612,7 @@ async def test_top_authors_maps_works_patents_news_and_eu_projects(): if kwargs["index"] == "aktuell_postproc": return { "aggregations": { - "authors": { - "buckets": [ - {"key": "Ada Example", "doc_count": 6} - ] - } + "authors": {"buckets": [{"key": "Ada Example", "doc_count": 6}]} } } if kwargs["index"] == ESIndex.CORDIS_EU_PUBLICATIONS_WILDCARD: @@ -618,9 +638,7 @@ async def test_top_authors_maps_works_patents_news_and_eu_projects(): if kwargs["index"] == ESIndex.DFG_PROJECTS: return { "aggregations": { - "people": { - "buckets": [{"key": "Grace Example", "doc_count": 3}] - } + "people": {"buckets": [{"key": "Grace Example", "doc_count": 3}]} } } @@ -712,9 +730,15 @@ async def test_top_authors_maps_works_patents_news_and_eu_projects(): if kwargs.get("raw_oa_institution_id"): return EuCordisProjectSearchPage( elements=[ - EuCordisProjectSummary(id="P1", project_type=EuCordisProjectType.FP7), - EuCordisProjectSummary(id="P2", project_type=EuCordisProjectType.H2020), - EuCordisProjectSummary(id="P3", project_type=EuCordisProjectType.HEU), + EuCordisProjectSummary( + id="P1", project_type=EuCordisProjectType.FP7 + ), + EuCordisProjectSummary( + id="P2", project_type=EuCordisProjectType.H2020 + ), + EuCordisProjectSummary( + id="P3", project_type=EuCordisProjectType.HEU + ), ], total=3, page=0, @@ -727,24 +751,30 @@ async def test_top_authors_maps_works_patents_news_and_eu_projects(): size=1, ) - with patch( - "inse.dashboard.service.elasticsearch.search", - new=AsyncMock(side_effect=search), - ) as mocked_search, patch( - "inse.dashboard.service.elasticsearch.scan", - new=scan, - ), patch( - "inse.dashboard.service.InstitutionsSearchClient.get_institution_aliases_by_oa_institution_id", - new=AsyncMock(return_value=["Example University"]), - ), patch( - "inse.dashboard.service.projects_service.search_eu_cordis_projects", - new=AsyncMock(side_effect=eu_projects), - ), patch( - "inse.dashboard.service.OrgPatentsSearchClient.top_authors_by_institution", - new=AsyncMock( - return_value=[ - {"id": "A1", "name": "Ada Example", "count": 4}, - ] + with ( + patch( + "inse.integrations.elasticsearch.search", + new=AsyncMock(side_effect=search), + ) as mocked_search, + patch( + "inse.integrations.elasticsearch.scan", + new=scan, + ), + patch( + "inse.institutions.institutions_search_client.InstitutionsSearchClient.get_institution_aliases_by_oa_institution_id", + new=AsyncMock(return_value=["Example University"]), + ), + patch( + "inse.projects.service.search_eu_cordis_projects", + new=AsyncMock(side_effect=eu_projects), + ), + patch( + "inse.dashboard.service.OrgPatentsSearchClient.top_authors_by_institution", + new=AsyncMock( + return_value=[ + {"id": "A1", "name": "Ada Example", "count": 4}, + ] + ), ), ): result = await get_top_authors( @@ -775,8 +805,7 @@ async def test_top_authors_maps_works_patents_news_and_eu_projects(): project_calls = [ call for call in mocked_search.await_args_list - if call.kwargs["index"] - in {ESIndex.DFG_PROJECTS, ESIndex.PROJECTS_BUND_V1} + if call.kwargs["index"] in {ESIndex.DFG_PROJECTS, ESIndex.PROJECTS_BUND_V1} ] assert project_calls == [] @@ -926,9 +955,7 @@ async def test_top_eu_project_authors_count_filtered_projects_by_stable_author_i } } if kwargs["index"] == ESIndex.CORDIS_EU_PUBLICATIONS_WILDCARD: - assert kwargs["body"]["query"] == { - "terms": {"projectID": ["P1", "P2"]} - } + assert kwargs["body"]["query"] == {"terms": {"projectID": ["P1", "P2"]}} return { "hits": { "hits": [ @@ -1056,8 +1083,12 @@ async def test_top_eu_project_authors_count_filtered_projects_by_stable_author_i if kwargs.get("raw_oa_institution_id"): return EuCordisProjectSearchPage( elements=[ - EuCordisProjectSummary(id="P1", project_type=EuCordisProjectType.FP7), - EuCordisProjectSummary(id="P2", project_type=EuCordisProjectType.H2020), + EuCordisProjectSummary( + id="P1", project_type=EuCordisProjectType.FP7 + ), + EuCordisProjectSummary( + id="P2", project_type=EuCordisProjectType.H2020 + ), ], total=2, page=0, @@ -1070,18 +1101,23 @@ async def test_top_eu_project_authors_count_filtered_projects_by_stable_author_i size=1, ) - with patch( - "inse.dashboard.service.elasticsearch.search", - new=AsyncMock(side_effect=search), - ), patch( - "inse.dashboard.service.InstitutionsSearchClient.get_institution_aliases_by_oa_institution_id", - new=AsyncMock(return_value=["Example University"]), - ), patch( - "inse.dashboard.service.projects_service.search_eu_cordis_projects", - new=AsyncMock(side_effect=eu_projects), - ), patch( - "inse.dashboard.service.OrgPatentsSearchClient.top_authors_by_institution", - new=AsyncMock(return_value=[]), + with ( + patch( + "inse.integrations.elasticsearch.search", + new=AsyncMock(side_effect=search), + ), + patch( + "inse.institutions.institutions_search_client.InstitutionsSearchClient.get_institution_aliases_by_oa_institution_id", + new=AsyncMock(return_value=["Example University"]), + ), + patch( + "inse.projects.service.search_eu_cordis_projects", + new=AsyncMock(side_effect=eu_projects), + ), + patch( + "inse.dashboard.service.OrgPatentsSearchClient.top_authors_by_institution", + new=AsyncMock(return_value=[]), + ), ): result = await get_top_authors( ORG_INSTITUTION_ID, @@ -1133,27 +1169,23 @@ async def test_top_authors_returns_partial_response_when_one_source_fails(): }, } - with patch( - "inse.dashboard.service.elasticsearch.search", - new=AsyncMock(side_effect=search), - ), patch( - "inse.dashboard.service.elasticsearch.scan", - new=scan, - ), patch( - "inse.dashboard.service.InstitutionsSearchClient.get_institution_aliases_by_oa_institution_id", - new=AsyncMock(return_value=["Example University"]), - ), patch( - "inse.dashboard.service.get_eu_organization_project_contributions", - new=AsyncMock( - return_value=SimpleNamespace( - elements=[ - SimpleNamespace(project_id="P1"), - ], - ) + with ( + patch( + "inse.integrations.elasticsearch.search", + new=AsyncMock(side_effect=search), + ), + patch( + "inse.integrations.elasticsearch.scan", + new=scan, + ), + patch( + "inse.institutions.institutions_search_client.InstitutionsSearchClient.get_institution_aliases_by_oa_institution_id", + new=AsyncMock(return_value=["Example University"]), + ), + patch( + "inse.dashboard.service.OrgPatentsSearchClient.top_authors_by_institution", + new=AsyncMock(return_value=[]), ), - ), patch( - "inse.dashboard.service.OrgPatentsSearchClient.top_authors_by_institution", - new=AsyncMock(return_value=[]), ): result = await get_top_authors( ORG_INSTITUTION_ID, @@ -1235,21 +1267,23 @@ async def test_top_authors_can_rank_works_by_last_five_years(): }, } - with patch( - "inse.dashboard.service.elasticsearch.search", - new=AsyncMock(side_effect=search), - ) as mocked_search, patch( - "inse.dashboard.service.elasticsearch.scan", - new=scan, - ), patch( - "inse.dashboard.service.InstitutionsSearchClient.get_institution_aliases_by_oa_institution_id", - new=AsyncMock(return_value=["Example University"]), - ), patch( - "inse.dashboard.service.get_eu_organization_project_contributions", - new=AsyncMock(return_value=SimpleNamespace(elements=[])), - ), patch( - "inse.dashboard.service.OrgPatentsSearchClient.top_authors_by_institution", - new=AsyncMock(return_value=[]), + with ( + patch( + "inse.integrations.elasticsearch.search", + new=AsyncMock(side_effect=search), + ), + patch( + "inse.integrations.elasticsearch.scan", + new=scan, + ), + patch( + "inse.institutions.institutions_search_client.InstitutionsSearchClient.get_institution_aliases_by_oa_institution_id", + new=AsyncMock(return_value=["Example University"]), + ), + patch( + "inse.dashboard.service.OrgPatentsSearchClient.top_authors_by_institution", + new=AsyncMock(return_value=[]), + ), ): result = await get_top_authors( ORG_INSTITUTION_ID, @@ -1369,7 +1403,7 @@ async def test_topic_heatmap_maps_field_year_counts_and_shares(): } with patch( - "inse.dashboard.service.elasticsearch.search", + "inse.integrations.elasticsearch.search", new=AsyncMock(side_effect=search), ) as mocked_search: result = await get_topic_heatmap( @@ -1423,17 +1457,14 @@ async def test_topic_heatmap_maps_field_year_counts_and_shares(): == "topics.subfield.id" ) assert ( - body["aggs"]["topics_nested"]["aggs"]["fields"]["aggs"]["subfields"][ - "aggs" - ]["topics"]["terms"]["field"] + body["aggs"]["topics_nested"]["aggs"]["fields"]["aggs"]["subfields"]["aggs"][ + "topics" + ]["terms"]["field"] == "topics.id" ) subfield_aggs = body["aggs"]["topics_nested"]["aggs"]["fields"]["aggs"] assert "aggs" not in subfield_aggs["subfields"]["aggs"]["works"] - assert ( - "aggs" - not in subfield_aggs["subfields"]["aggs"]["topics"]["aggs"]["works"] - ) + assert "aggs" not in subfield_aggs["subfields"]["aggs"]["topics"]["aggs"]["works"] @pytest.mark.anyio @@ -1449,7 +1480,7 @@ async def test_topic_heatmap_defaults_to_all_time(): return {"hits": {"hits": []}} with patch( - "inse.dashboard.service.elasticsearch.search", + "inse.integrations.elasticsearch.search", new=AsyncMock(side_effect=search), ) as mocked_search: result = await get_topic_heatmap( @@ -1485,7 +1516,7 @@ async def test_topic_word_cloud_maps_related_topics_and_excludes_selected_topic( } } with patch( - "inse.dashboard.service.elasticsearch.search", + "inse.integrations.elasticsearch.search", new=AsyncMock(return_value=response), ) as mocked_search: result = await get_topic_word_cloud( diff --git a/service/src/main/inse/dashboard/top_authors_service.py b/service/src/main/inse/dashboard/top_authors_service.py new file mode 100644 index 00000000..a8e62560 --- /dev/null +++ b/service/src/main/inse/dashboard/top_authors_service.py @@ -0,0 +1,1100 @@ +import asyncio +import logging +import re +from collections import defaultdict +from datetime import datetime +from typing import Any, Literal + +from inse import config +from inse.integrations import elasticsearch +from inse.model import ESCluster, ESIndex +from inse.patents.org.elastic_search_client import OrgPatentsSearchClient +from inse.projects import service as projects_service +from inse.projects.dfg_institutions.service import ( + autocomplete_institutions_for_selector, +) +from inse.projects.logic import get_person_ids_by_institution_ids +from inse.works.v2 import service as works_v2_service + +from .common import ( + DashboardPeriod, + dashboard_period as _dashboard_period, + institution_works_query as _institution_works_query, + normalize_institution_id as _normalize_institution_id, + project_overlap_filter as _project_overlap_filter, +) +from .model import TopAuthor, TopAuthorAnalysis, TopAuthorStatistics +from .project_ids_service import _get_eu_project_ids_from_projects_service + +TOP_AUTHOR_LIMIT = 10 +logger = logging.getLogger(__name__) +ACADEMIC_TITLE_RE = re.compile( + r"^(?:(?:professor(?:in)?|prof|dr)(?:\\.-[a-z]+)?\\.?|rer\\.|nat\\.|med\\.|ing\\.)\\s+", + re.IGNORECASE, +) + + +WorksPeriod = Literal["all_time", "last_5_years"] + + +def _period( + works_period: WorksPeriod = "all_time", + from_year: int | None = None, + to_year: int | None = None, +) -> DashboardPeriod: + if from_year is None and to_year is None and works_period == "last_5_years": + from_year = datetime.now().year - 4 + to_year = datetime.now().year + return _dashboard_period(from_year, to_year) + + +async def get_top_authors( + institution_id: str, + organization_name: str, + works_period: WorksPeriod = "all_time", + from_year: int | None = None, + to_year: int | None = None, +) -> TopAuthorStatistics: + normalized_id = _normalize_institution_id(institution_id) + period = _period(works_period, from_year, to_year) + authors = await _safe_institution_authors(normalized_id) + + works = await _safe_top_authors("works", _top_work_authors(normalized_id, period)) + projects = await _safe_top_authors( + "projects", + _top_project_authors( + authors=authors, + organization_name=organization_name, + from_year=period[0], + to_year=period[1], + ), + ) + eu_projects = await _safe_top_authors( + "eu_projects", + _top_eu_project_publication_authors( + normalized_id, + authors, + from_year=period[0], + to_year=period[1], + ), + ) + patents = await _safe_top_authors( + "patents", + _top_patent_authors( + normalized_id, + from_year=period[0], + to_year=period[1], + ), + ) + news = await _safe_top_authors( + "news", + _top_news_authors( + authors, + from_year=period[0], + to_year=period[1], + ), + ) + + return TopAuthorStatistics( + institution_id=normalized_id, + works=works, + projects=projects, + eu_projects=eu_projects, + patents=patents, + news=news, + ) + + +async def get_top_work_authors( + institution_id: str, + works_period: WorksPeriod = "all_time", + from_year: int | None = None, + to_year: int | None = None, +) -> TopAuthorAnalysis: + normalized_id = _normalize_institution_id(institution_id) + return TopAuthorAnalysis( + institution_id=normalized_id, + authors=await _top_work_authors( + normalized_id, _period(works_period, from_year, to_year) + ), + ) + + +async def get_top_project_authors( + institution_id: str, + organization_name: str, + from_year: int | None = None, + to_year: int | None = None, +) -> TopAuthorAnalysis: + normalized_id = _normalize_institution_id(institution_id) + period = _period(from_year=from_year, to_year=to_year) + return TopAuthorAnalysis( + institution_id=normalized_id, + authors=await _top_project_authors( + authors=await _safe_institution_authors(normalized_id), + organization_name=organization_name, + from_year=period[0], + to_year=period[1], + ), + ) + + +async def get_top_eu_project_authors( + institution_id: str, + from_year: int | None = None, + to_year: int | None = None, +) -> TopAuthorAnalysis: + normalized_id = _normalize_institution_id(institution_id) + period = _period(from_year=from_year, to_year=to_year) + authors = await _safe_institution_authors(normalized_id) + return TopAuthorAnalysis( + institution_id=normalized_id, + authors=await _top_eu_project_publication_authors( + normalized_id, + authors, + from_year=period[0], + to_year=period[1], + ), + ) + + +async def get_top_patent_authors( + institution_id: str, + from_year: int | None = None, + to_year: int | None = None, +) -> TopAuthorAnalysis: + normalized_id = _normalize_institution_id(institution_id) + period = _period(from_year=from_year, to_year=to_year) + return TopAuthorAnalysis( + institution_id=normalized_id, + authors=await _top_patent_authors( + normalized_id, + from_year=period[0], + to_year=period[1], + ), + ) + + +async def get_top_news_authors( + institution_id: str, + from_year: int | None = None, + to_year: int | None = None, +) -> TopAuthorAnalysis: + normalized_id = _normalize_institution_id(institution_id) + period = _period(from_year=from_year, to_year=to_year) + return TopAuthorAnalysis( + institution_id=normalized_id, + authors=await _top_news_authors( + await _safe_institution_authors(normalized_id), + from_year=period[0], + to_year=period[1], + ), + ) + + +def _normalize_person_name(name: str) -> str: + normalized = " ".join(name.strip().casefold().split()) + while True: + without_title = ACADEMIC_TITLE_RE.sub("", normalized).strip() + if without_title == normalized: + return without_title + normalized = without_title + + +def _is_initial_surname_match(full_name: str, initial_name: str) -> bool: + full_parts = _normalize_person_name(full_name).split() + initial_parts = _normalize_person_name(initial_name).replace(".", "").split() + if len(full_parts) < 2 or len(initial_parts) < 2: + return False + return ( + len(initial_parts[0]) == 1 + and full_parts[0].startswith(initial_parts[0]) + and full_parts[-1] == initial_parts[-1] + ) + + +def _is_supported_name_variant(full_name: str, candidate_name: str) -> bool: + return _normalize_person_name(full_name) == _normalize_person_name( + candidate_name + ) or _is_initial_surname_match(full_name, candidate_name) + + +def _dashboard_publication_years(period: DashboardPeriod) -> list[int] | None: + from_year, to_year = period + if from_year is None and to_year is None: + return None + return list(range(from_year or 1900, (to_year or 2100) + 1)) + + +async def _safe_top_authors(source: str, operation: Any) -> list[TopAuthor]: + try: + return await operation + except Exception: + logger.exception("Dashboard top-author aggregation failed for %s.", source) + return [] + + +def _short_author_id(value: str) -> str: + return value.replace("https://openalex.org/", "").strip().upper() + + +async def _top_work_authors( + institution_id: str, + period: DashboardPeriod, +) -> list[TopAuthor]: + must = [works_v2_service._institutions_nested_query([institution_id])] + if publication_years := _dashboard_publication_years(period): + must.append({"terms": {"publication_year": publication_years}}) + + author_counts: dict[str, int] = defaultdict(int) + author_names: dict[str, str] = {} + async for hit in elasticsearch.scan( + index=str(ESIndex.OPENALEX_WORKS_WILDCARD), + query={"bool": {"must": must}}, + source=["id", "authorships.author.id", "authorships.author.display_name"], + page_size=1000, + cluster=ESCluster.NES, + ): + hit_author_ids: set[str] = set() + for authorship in hit.get("_source", {}).get("authorships", []): + author = authorship.get("author") or {} + author_id = author.get("id") + if not author_id: + continue + author_id = str(author_id) + hit_author_ids.add(author_id) + if author.get("display_name"): + author_names.setdefault(author_id, str(author["display_name"])) + for author_id in hit_author_ids: + author_counts[author_id] += 1 + + ranked_authors = sorted( + ( + { + "id": author_id, + "name": author_names.get(author_id, author_id), + "count": count, + } + for author_id, count in author_counts.items() + ), + key=lambda author: author["count"], + reverse=True, + ) + return [ + TopAuthor( + id=_short_author_id(author["id"]), + name=author["name"], + count=author["count"], + ) + for author in ranked_authors[:TOP_AUTHOR_LIMIT] + if author["count"] > 0 + ] + + +async def _safe_institution_authors(institution_id: str) -> list[dict[str, Any]]: + try: + return await _institution_authors(institution_id) + except Exception: + logger.exception("Could not load authors for institution %s.", institution_id) + return [] + + +async def _institution_authors(institution_id: str) -> list[dict[str, Any]]: + response = await elasticsearch.search( + index=ESIndex.OPENALEX_AUTHORS, + query={ + "nested": { + "path": "last_known_institutions", + "query": {"term": {"last_known_institutions.id": institution_id}}, + } + }, + source=["id", "display_name", "works_count", "counts_by_year"], + size=10000, + sort=[{"works_count": {"order": "desc", "missing": "_last"}}], + cluster=ESCluster.NES, + ) + return [ + { + "id": str(source["id"]), + "name": str(source["display_name"]), + "works_count": int(source.get("works_count", 0)), + "counts_by_year": source.get("counts_by_year", []) or [], + } + for hit in response.get("hits", {}).get("hits", []) + if (source := hit.get("_source", {})).get("id") and source.get("display_name") + ] + + +async def _top_project_authors( + authors: list[dict[str, Any]], + organization_name: str, + from_year: int | None = None, + to_year: int | None = None, +) -> list[TopAuthor]: + period = _dashboard_period(from_year, to_year) + institution_ids = await _dfg_institution_ids_for_organization( + organization_name=organization_name, + ) + + logger.info( + "DFG institution IDs for %s: %s", + organization_name, + institution_ids, + ) + + if not institution_ids: + logger.warning( + "No DFG institution IDs found for organization %s.", + organization_name, + ) + return [] + + selected_person_ids = set( + await get_person_ids_by_institution_ids(institution_ids=institution_ids) + ) + + logger.info( + "Found %s DFG persons for organization %s.", + len(selected_person_ids), + organization_name, + ) + + if not selected_person_ids: + return [] + + project_ids_by_person: dict[int, set[str]] = {} + names: dict[int, str] = {} + + page = 0 + size = 10000 + processed = 0 + + while True: + project_hits, total = await _dfg_project_author_hits( + page=page, + size=size, + person_ids=selected_person_ids, + period=period, + ) + + if not project_hits: + break + + for project in project_hits: + project_id = _dfg_project_id(project) + if not project_id: + continue + + persons = project.get("persons", []) + if not isinstance(persons, list): + continue + + for person in persons: + if not isinstance(person, dict): + continue + + person_id = person.get("person_id") + full_name = person.get("full_name") + if person_id is None or not full_name: + continue + + try: + normalized_person_id = int(person_id) + except (TypeError, ValueError): + continue + + if normalized_person_id not in selected_person_ids: + continue + + project_ids_by_person.setdefault(normalized_person_id, set()).add( + project_id + ) + names[normalized_person_id] = str(full_name).strip() + + processed += len(project_hits) + if processed >= total: + break + + page += 1 + + institution_authors: dict[str, list[dict[str, Any]]] = {} + for author in authors: + if author.get("name"): + institution_authors.setdefault( + _normalize_person_name(author["name"]), + [], + ).append(author) + + ranked = sorted( + ( + (person_id, project_ids) + for person_id, project_ids in project_ids_by_person.items() + if project_ids and names.get(person_id) + ), + key=lambda item: ( + -len(item[1]), + names[item[0]].casefold(), + ), + ) + + ranked_person_ids = [person_id for person_id, _ in ranked[:TOP_AUTHOR_LIMIT]] + dfg_orcids = await _dfg_person_orcids(ranked_person_ids) + + result: list[TopAuthor] = [] + + for person_id, project_ids in ranked[:TOP_AUTHOR_LIMIT]: + dfg_name = names[person_id] + matched_author = _single_author_match( + institution_authors.get(_normalize_person_name(dfg_name), []) + ) + + if matched_author is None and (orcid := dfg_orcids.get(person_id)): + matched_author = await _openalex_author_by_orcid(orcid) + + if matched_author is None: + matched_author = await _openalex_author_by_dfg_publication_evidence( + dfg_name=dfg_name, + project_ids=project_ids, + ) + + if matched_author is None: + logger.info( + "No exact OpenAlex match for DFG author '%s' (person_id=%s).", + dfg_name, + person_id, + ) + + result.append( + TopAuthor( + id=(_short_author_id(matched_author["id"]) if matched_author else None), + name=matched_author["name"] if matched_author else dfg_name, + count=len(project_ids), + ) + ) + + logger.info( + "DFG top authors for %s: %s", + organization_name, + [ + { + "name": author.name, + "count": author.count, + "id": author.id, + } + for author in result + ], + ) + + return result + + +def _single_author_match(authors: list[dict[str, Any]]) -> dict[str, Any] | None: + return authors[0] if len(authors) == 1 else None + + +async def _dfg_person_orcids(person_ids: list[int]) -> dict[int, str]: + if not person_ids: + return {} + + try: + response = await elasticsearch.search( + index=ESIndex.DFG_PERSONS, + body={ + "size": len(person_ids), + "_source": ["person_id", "orcid_id"], + "query": {"terms": {"person_id": person_ids}}, + }, + cluster=ESCluster.INSE, + ) + except Exception: + logger.exception("Could not load DFG ORCIDs for top project authors.") + return {} + + result: dict[int, str] = {} + for hit in response.get("hits", {}).get("hits", []): + source = hit.get("_source", {}) + person_id = source.get("person_id") + orcid = source.get("orcid_id") + if person_id is None or not orcid: + continue + try: + result[int(person_id)] = str(orcid) + except (TypeError, ValueError): + continue + return result + + +async def _openalex_author_by_orcid(orcid: str) -> dict[str, Any] | None: + normalized_orcid = orcid.replace("https://orcid.org/", "").strip() + if not normalized_orcid: + return None + + prefixed_orcid = f"https://orcid.org/{normalized_orcid}" + try: + response = await elasticsearch.search( + index=ESIndex.OPENALEX_AUTHORS, + body={ + "size": 2, + "_source": ["id", "display_name"], + "query": { + "bool": { + "should": [ + {"term": {"orcid.keyword": normalized_orcid}}, + {"term": {"orcid.keyword": prefixed_orcid}}, + {"term": {"ids.orcid.keyword": normalized_orcid}}, + {"term": {"ids.orcid.keyword": prefixed_orcid}}, + {"term": {"orcid": normalized_orcid}}, + {"term": {"orcid": prefixed_orcid}}, + {"term": {"ids.orcid": normalized_orcid}}, + {"term": {"ids.orcid": prefixed_orcid}}, + ], + "minimum_should_match": 1, + } + }, + }, + cluster=ESCluster.NES, + track_total_hits=True, + ) + except Exception: + logger.exception("Could not resolve OpenAlex author by ORCID %s.", orcid) + return None + + hits = response.get("hits", {}).get("hits", []) + if len(hits) != 1: + logger.info( + "OpenAlex ORCID lookup for %s returned %s hits.", + orcid, + len(hits), + ) + return None + + source = hits[0].get("_source", {}) + if not source.get("id") or not source.get("display_name"): + return None + return { + "id": str(source["id"]), + "name": str(source["display_name"]), + } + + +async def _openalex_author_by_dfg_publication_evidence( + dfg_name: str, + project_ids: set[str], +) -> dict[str, Any] | None: + dois = await _dfg_project_publication_dois(project_ids) + if not dois: + return None + + try: + response = await elasticsearch.search( + index=config.settings.openalex_works_search_index, + body={ + "size": 10000, + "_source": [ + "doi", + "authorships.author.id", + "authorships.author.display_name", + ], + "query": {"terms": {"doi": sorted(_doi_variants(dois))}}, + }, + cluster=ESCluster.NES, + ) + except Exception: + logger.exception( + "Could not resolve OpenAlex author from DFG publication DOIs for %s.", + dfg_name, + ) + return None + + candidates: dict[str, dict[str, Any]] = {} + for hit in response.get("hits", {}).get("hits", []): + source = hit.get("_source", {}) + doi = source.get("doi") + if not doi: + continue + for authorship in source.get("authorships", []) or []: + author = ( + authorship.get("author", {}) if isinstance(authorship, dict) else {} + ) + author_id = author.get("id") + display_name = author.get("display_name") + if not author_id or not display_name: + continue + if not _is_supported_name_variant(dfg_name, str(display_name)): + continue + candidate = candidates.setdefault( + str(author_id), + { + "id": str(author_id), + "name": str(display_name), + "dois": set(), + }, + ) + candidate["dois"].add(str(doi)) + + supported_candidates = [ + candidate for candidate in candidates.values() if len(candidate["dois"]) >= 2 + ] + if len(supported_candidates) != 1: + if supported_candidates: + logger.info( + "DFG publication DOI lookup for %s returned %s candidates.", + dfg_name, + len(supported_candidates), + ) + return None + + candidate = supported_candidates[0] + return { + "id": candidate["id"], + "name": candidate["name"], + } + + +async def _dfg_project_publication_dois(project_ids: set[str]) -> set[str]: + if not project_ids: + return set() + + numeric_project_ids = [ + int(project_id) for project_id in project_ids if str(project_id).isdigit() + ] + if not numeric_project_ids: + return set() + + try: + response = await elasticsearch.search( + index=ESIndex.DFG_PROJECTS, + body={ + "size": len(numeric_project_ids), + "_source": ["publications.doi"], + "query": {"terms": {"id": numeric_project_ids}}, + }, + cluster=ESCluster.INSE, + ) + except Exception: + logger.exception("Could not load DFG publication DOIs.") + return set() + + dois: set[str] = set() + for hit in response.get("hits", {}).get("hits", []): + for publication in hit.get("_source", {}).get("publications", []) or []: + doi = publication.get("doi") if isinstance(publication, dict) else None + if doi: + dois.add(str(doi).strip()) + return {doi for doi in dois if doi} + + +def _doi_variants(dois: set[str]) -> set[str]: + variants: set[str] = set() + for doi in dois: + normalized = doi.strip() + if not normalized: + continue + raw = normalized + for prefix in ("https://doi.org/", "http://dx.doi.org/"): + if raw.casefold().startswith(prefix): + raw = raw[len(prefix) :] + break + variants.update( + { + normalized, + normalized.lower(), + f"https://doi.org/{raw}", + f"https://doi.org/{raw.lower()}", + } + ) + return variants + + +async def _dfg_institution_ids_for_organization(organization_name: str) -> list[int]: + page = await autocomplete_institutions_for_selector( + query=organization_name, + page=0, + size=10000, + ) + return [ + institution.id for institution in page.elements if institution.id is not None + ] + + +async def _dfg_project_author_hits( + page: int, + size: int, + person_ids: set[int], + period: DashboardPeriod = (None, None), +) -> tuple[list[dict[str, Any]], int]: + person_query = { + "nested": { + "path": "persons", + "query": {"terms": {"persons.person_id": sorted(person_ids)}}, + }, + } + period_filter = _project_overlap_filter( + "funding_start", + "funding_end", + period, + missing_end_is_ongoing=True, + ) + query = ( + {"bool": {"filter": [person_query, period_filter]}} + if period_filter + else person_query + ) + response = await elasticsearch.search( + index=ESIndex.DFG_PROJECTS, + body={ + "size": size, + "from": page * size, + "_source": [ + "id", + "project_id", + "persons", + ], + "query": query, + "sort": [ + { + "id": { + "order": "asc", + "missing": "_last", + } + } + ], + }, + cluster=ESCluster.INSE, + track_total_hits=True, + ) + + hits_block = response.get("hits", {}) + total_value = hits_block.get("total", 0) + + if isinstance(total_value, dict): + total = int(total_value.get("value", 0)) + else: + total = int(total_value or 0) + + hits = [ + hit.get("_source", {}) + for hit in hits_block.get("hits", []) + if isinstance(hit.get("_source"), dict) + ] + + logger.info( + "Loaded %s of %s matching DFG projects on page %s.", + len(hits), + total, + page, + ) + + return hits, total + + +def _dfg_project_id(project: dict[str, Any]) -> str | None: + project_id = project.get("id") + if project_id is None: + project_id = project.get("project_id") + return str(project_id) if project_id is not None else None + + +async def _top_patent_authors( + institution_id: str, + from_year: int | None = None, + to_year: int | None = None, +) -> list[TopAuthor]: + client = OrgPatentsSearchClient() + authors = await client.top_authors_by_institution( + institution_id=institution_id, + size=TOP_AUTHOR_LIMIT, + from_year=from_year, + to_year=to_year, + ) + return [ + TopAuthor( + id=_short_author_id(author["id"]), + name=author["name"], + count=author["count"], + ) + for author in authors + ] + + +async def _top_eu_project_publication_authors( + institution_id: str, + institution_authors: list[dict[str, Any]], + from_year: int | None = None, + to_year: int | None = None, +) -> list[TopAuthor]: + institution_author_ids = { + author_id + for author in institution_authors + if (author_id := _normalize_author_id(author.get("id"))) + } + if not institution_author_ids: + return [] + + project_ids = await _get_eu_project_ids_from_projects_service( + institution_id, + from_year=from_year, + to_year=to_year, + ) + + if not project_ids: + return [] + + publication_response = await elasticsearch.search( + index=ESIndex.CORDIS_EU_PUBLICATIONS_WILDCARD, + body={ + "size": 10000, + "_source": ["projectID", "qaProcessedDoi"], + "query": {"terms": {"projectID": project_ids}}, + }, + cluster=ESCluster.INSE, + ) + + doi_project_ids = _cordis_publication_doi_project_ids( + publication_response, + set(project_ids), + ) + if not doi_project_ids: + return [] + + works_response = await elasticsearch.search( + index="openalex-works", + body={ + "size": 10000, + "_source": [ + "doi", + "authorships.author.id", + "authorships.author.display_name", + "authorships.institutions.id", + ], + "query": { + "bool": { + "filter": [ + {"terms": {"doi": sorted(doi_project_ids)}}, + _institution_works_query(institution_id), + ] + } + }, + }, + cluster=ESCluster.NES, + ) + + candidates = _openalex_work_authors_by_eu_projects( + works_response, + doi_project_ids, + institution_id, + institution_author_ids, + limit=None, + ) + counts = await asyncio.gather( + *( + _person_eu_project_count( + candidate.id, + from_year=from_year, + to_year=to_year, + ) + for candidate in candidates + if candidate.id + ) + ) + ranked = [ + TopAuthor(id=candidate.id, name=candidate.name, count=count) + for candidate, count in zip(candidates, counts, strict=True) + ] + ranked.sort(key=lambda author: (-author.count, author.name, author.id or "")) + return ranked[:TOP_AUTHOR_LIMIT] + + +def _cordis_publication_doi_project_ids( + response: dict[str, Any], + allowed_project_ids: set[str], +) -> dict[str, set[str]]: + doi_project_ids: dict[str, set[str]] = defaultdict(set) + for hit in response.get("hits", {}).get("hits", []): + source = hit.get("_source", {}) + project_id = str(source.get("projectID") or "").strip() + if not project_id or project_id not in allowed_project_ids: + continue + doi = _normalize_doi(source.get("qaProcessedDoi")) + if doi: + doi_project_ids[doi].add(project_id) + return dict(doi_project_ids) + + +def _normalize_doi(value: Any) -> str | None: + if not isinstance(value, str) or not value.strip(): + return None + doi = value.strip().lower() + if doi.startswith("https://doi.org/"): + return doi + if doi.startswith("http://doi.org/"): + return "https://" + doi.removeprefix("http://") + if doi.startswith("doi.org/"): + return f"https://{doi}" + return f"https://doi.org/{doi}" + + +def _openalex_work_authors_by_eu_projects( + response: dict[str, Any], + doi_project_ids: dict[str, set[str]], + institution_id: str, + institution_author_ids: set[str], + limit: int | None = TOP_AUTHOR_LIMIT, +) -> list[TopAuthor]: + # Count unique CORDIS projects per author, not publications. Multiple works + # (and therefore multiple DOIs) can belong to the same project ID. + author_project_ids: dict[str, set[str]] = defaultdict(set) + author_names: dict[str, str] = {} + + for hit in response.get("hits", {}).get("hits", []): + source = hit.get("_source", {}) + project_ids = doi_project_ids.get(_normalize_doi(source.get("doi")) or "") + if not project_ids: + continue + + for authorship in source.get("authorships") or []: + if not any( + institution.get("id") == institution_id + for institution in authorship.get("institutions") or [] + ): + continue + author = authorship.get("author") or {} + author_id = _normalize_author_id(author.get("id")) + author_name = str(author.get("display_name") or "").strip() + if ( + not author_id + or author_id not in institution_author_ids + or not author_name + ): + continue + author_project_ids[author_id].update(project_ids) + author_names.setdefault(author_id, author_name) + + ranked_authors = sorted( + author_project_ids.items(), + key=lambda item: (-len(item[1]), author_names.get(item[0], ""), item[0]), + ) + + authors = [ + TopAuthor( + id=_short_author_id(author_id), + name=author_names[author_id], + count=len(project_ids), + ) + for author_id, project_ids in ranked_authors + ] + return authors[:limit] if limit is not None else authors + + +async def _person_eu_project_count( + author_id: str, + from_year: int | None = None, + to_year: int | None = None, +) -> int: + """Returns the same filtered EU project total as the person projects tab.""" + period = _dashboard_period(from_year, to_year) + projects = await projects_service.search_eu_cordis_projects( + page=0, + size=1, + project_types=None, + raw_oa_institution_id=None, + institutions_search_client=None, + author_id=_short_author_id(author_id), + author_ids=None, + organization_ids=None, + organization_names=None, + keywords=None, + topic_ids=None, + filter_topic_ids=None, + title=None, + funding_start_years=None, + funding_end_years=None, + active_from_year=period[0], + active_to_year=period[1], + countries=None, + framework_programmes=None, + funding_schemes=None, + statuses=None, + sort_by="title", + sort_direction="asc", + fuzzy=False, + skip_enrichment=True, + ) + return projects.total + + +def _normalize_author_id(value: Any) -> str | None: + if not isinstance(value, str) or not value.strip(): + return None + short_id = value.replace("https://openalex.org/", "").strip().upper() + return f"https://openalex.org/{short_id}" + + +async def _top_news_authors( + authors: list[dict[str, Any]], + from_year: int | None = None, + to_year: int | None = None, +) -> list[TopAuthor]: + if not authors: + return [] + + period = _dashboard_period(from_year, to_year) + author_names = [author["name"] for author in authors] + filters: list[dict[str, Any]] = [{"terms": {"authors.keyword": author_names}}] + if period != (None, None): + date_range: dict[str, int] = {} + if period[0] is not None: + date_range["gte"] = period[0] + if period[1] is not None: + date_range["lte"] = period[1] + news_ids = [ + str(hit["_id"]) + async for hit in elasticsearch.scan( + index=str(ESIndex.AKTUELLES), + query={"range": {"date_year": date_range}}, + source=False, + page_size=1000, + cluster=ESCluster.INSE, + ) + if hit.get("_id") + ] + if not news_ids: + return [] + filters.append({"terms": {"news_id.keyword": news_ids}}) + + response = await elasticsearch.search( + index="aktuell_postproc", + body={ + "size": 0, + "query": ( + filters[0] if len(filters) == 1 else {"bool": {"filter": filters}} + ), + "aggs": { + "authors": { + "terms": { + "field": "authors.keyword", + "size": 10000, + "order": [ + {"_count": "desc"}, + {"_key": "asc"}, + ], + } + } + }, + }, + cluster=ESCluster.INSE, + ) + buckets = response.get("aggregations", {}).get("authors", {}).get("buckets", []) + institution_authors = {author["name"].casefold(): author for author in authors} + + return [ + TopAuthor( + id=_short_author_id( + institution_authors[str(bucket["key"]).casefold()]["id"] + ), + name=institution_authors[str(bucket["key"]).casefold()]["name"], + count=int(bucket.get("doc_count", 0)), + ) + for bucket in buckets + if str(bucket.get("key", "")).casefold() in institution_authors + ][:TOP_AUTHOR_LIMIT] diff --git a/webapp/src/app/modules/dashboard/dashboard-statistics.service.ts b/webapp/src/app/modules/dashboard/dashboard-statistics.service.ts index 894da8a3..629cb31d 100644 --- a/webapp/src/app/modules/dashboard/dashboard-statistics.service.ts +++ b/webapp/src/app/modules/dashboard/dashboard-statistics.service.ts @@ -1,6 +1,6 @@ import { HttpClient } from '@angular/common/http'; import { Injectable, inject } from '@angular/core'; -import { Observable } from 'rxjs'; +import { Observable, catchError, forkJoin, map, of } from 'rxjs'; import { Configuration } from '../../api'; import { TopicTreemapData } from '../../shared/ui/topic-treemap/topic-treemap.models'; @@ -95,6 +95,11 @@ export interface TopAuthorStatistics { news: TopAuthor[]; } +export interface TopAuthorAnalysis { + institution_id: string; + authors: TopAuthor[]; +} + export interface TopicWordCloudWord { id: string; name: string; @@ -228,9 +233,38 @@ export class DashboardStatisticsService { getTopAuthors( period: DashboardPeriodBounds = {}, ): Observable { - return this.httpClient.get( - `${this.apiConfiguration?.basePath ?? ''}/api/dashboard/top-authors`, - { params: this.periodParams(period) }, + const analysis = (source: string) => + this.httpClient + .get( + `${this.apiConfiguration?.basePath ?? ''}/api/dashboard/top-authors/${source}`, + { params: this.periodParams(period) }, + ) + .pipe(catchError(() => of(null))); + + return forkJoin({ + works: analysis('works'), + projects: analysis('projects'), + euProjects: analysis('eu-projects'), + patents: analysis('patents'), + news: analysis('news'), + }).pipe( + map((responses) => { + const successfulResponse = Object.values(responses).find( + (response) => response !== null, + ); + if (!successfulResponse) { + throw new Error('All top-author analyses failed.'); + } + + return { + institution_id: successfulResponse.institution_id, + works: responses.works?.authors ?? [], + projects: responses.projects?.authors ?? [], + eu_projects: responses.euProjects?.authors ?? [], + patents: responses.patents?.authors ?? [], + news: responses.news?.authors ?? [], + }; + }), ); } From 07ce24143bc244e7c18ce530c3ac9b2056b79e5b Mon Sep 17 00:00:00 2001 From: genja Date: Tue, 11 Aug 2026 10:23:57 +0200 Subject: [PATCH 101/114] 500 bug fix --- service/src/main/inse/projects/projects_search_client.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/service/src/main/inse/projects/projects_search_client.py b/service/src/main/inse/projects/projects_search_client.py index 454622aa..0c8d126d 100644 --- a/service/src/main/inse/projects/projects_search_client.py +++ b/service/src/main/inse/projects/projects_search_client.py @@ -648,7 +648,7 @@ async def search_dfg_projects( # 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") - print("ENRIECHED",source.get("institutions", [])) + return _complete_response_to_dfg_project_page(response, page, size) def _complete_response_to_dfg_project_page( From f8e5cd90a53d2482bf64d4ce3072323c585a19d2 Mon Sep 17 00:00:00 2001 From: Farajollahi Date: Tue, 11 Aug 2026 10:37:24 +0200 Subject: [PATCH 102/114] feat(dashboard): improve filters, tooltips and treemap state - add detailed tooltips to dashboard statistic cards - show author details on hover in top-10 person analyses - align patent icon with the sidebar - resize and right-align the dashboard period slider - persist DFG, EU and Bund treemap selections in URL parameters --- .../dashboard/dashboard.component.html | 28 ++++++++++++++----- .../dashboard/dashboard.component.scss | 11 +++++++- .../modules/dashboard/dashboard.component.ts | 20 +++++++++++++ 3 files changed, 51 insertions(+), 8 deletions(-) diff --git a/webapp/src/app/modules/dashboard/dashboard.component.html b/webapp/src/app/modules/dashboard/dashboard.component.html index 5b95c4a7..75bceafa 100644 --- a/webapp/src/app/modules/dashboard/dashboard.component.html +++ b/webapp/src/app/modules/dashboard/dashboard.component.html @@ -40,7 +40,9 @@ [attr.aria-disabled]="!institutionRouteId()" [attr.aria-label]=" 'Publikationen von ' + organizationName() + ' anzeigen' - "> + " + matTooltip="Anzahl der Publikationen im ausgewählten Zeitraum" + matTooltipPosition="above">
    menu_book
    @@ -60,7 +62,9 @@ class="statistics-card" routerLink="/persons" [queryParams]="personListQueryParams()" - [attr.aria-label]="'Personen von ' + organizationName() + ' anzeigen'"> + [attr.aria-label]="'Personen von ' + organizationName() + ' anzeigen'" + matTooltip="Anzahl der Personen im ausgewählten Zeitraum" + matTooltipPosition="above">
    groups
    @@ -81,9 +85,11 @@ [routerLink]="['/institution', institutionRouteId(), 'patents']" [class.disabled]="!institutionRouteId()" [attr.aria-disabled]="!institutionRouteId()" - [attr.aria-label]="'Patente von ' + organizationName() + ' anzeigen'"> + [attr.aria-label]="'Patente von ' + organizationName() + ' anzeigen'" + matTooltip="Anzahl der Patente im ausgewählten Zeitraum" + matTooltipPosition="above">
    - description + {{ patentIcon }}
    Patente @@ -101,7 +107,9 @@ class="statistics-card" routerLink="/projects" [queryParams]="{ selected_project_types: 'eu' }" - aria-label="EU-Projekte anzeigen"> + aria-label="EU-Projekte anzeigen" + matTooltip="Anzahl der laufenden, abgeschlossenen und kommenden EU-Projekte im ausgewählten Zeitraum" + matTooltipPosition="above">
    public
    @@ -121,7 +129,9 @@ class="statistics-card" routerLink="/projects" [queryParams]="{ selected_project_types: 'bund' }" - aria-label="Bund-Projekte anzeigen"> + aria-label="Bund-Projekte anzeigen" + matTooltip="Anzahl der laufenden, abgeschlossenen und kommenden Bund-Projekte im ausgewählten Zeitraum" + matTooltipPosition="above">
    account_balance
    @@ -141,7 +151,9 @@ class="statistics-card" routerLink="/projects" [queryParams]="{ selected_project_types: 'dfg' }" - aria-label="DFG-Projekte anzeigen"> + aria-label="DFG-Projekte anzeigen" + matTooltip="Anzahl der laufenden, abgeschlossenen und kommenden DFG-Projekte im ausgewählten Zeitraum" + matTooltipPosition="above">
    science
    @@ -441,6 +453,8 @@ class="author-name author-link" [routerLink]="authorLink(dataset, entry)" [queryParams]="authorQueryParams(dataset, entry)" + [appComponentTooltip]="AuthorTooltipComponent" + [tooltipInputs]="{ authorId: entry.id }" [title]="authorDisplayName(dataset, entry)"> {{ authorDisplayName(dataset, entry) }} diff --git a/webapp/src/app/modules/dashboard/dashboard.component.scss b/webapp/src/app/modules/dashboard/dashboard.component.scss index 034a1e76..68839065 100644 --- a/webapp/src/app/modules/dashboard/dashboard.component.scss +++ b/webapp/src/app/modules/dashboard/dashboard.component.scss @@ -39,7 +39,16 @@ } .dashboard-period-slider { - width: min(100%, 34rem); + width: 280px; + max-width: 100%; + margin-left: auto; + } + + @media (max-width: 720px) { + .dashboard-period-slider { + width: 100%; + margin-left: 0; + } } .statistics-grid { diff --git a/webapp/src/app/modules/dashboard/dashboard.component.ts b/webapp/src/app/modules/dashboard/dashboard.component.ts index 694cee72..14fadca4 100644 --- a/webapp/src/app/modules/dashboard/dashboard.component.ts +++ b/webapp/src/app/modules/dashboard/dashboard.component.ts @@ -1,9 +1,13 @@ import { Component, OnInit } from '@angular/core'; import { DecimalPipe } from '@angular/common'; import { MatIconModule } from '@angular/material/icon'; +import { MatTooltipModule } from '@angular/material/tooltip'; import { Observable, finalize } from 'rxjs'; import { ActivatedRoute, Router, RouterLink } from '@angular/router'; import { MatDialog } from '@angular/material/dialog'; +import { ComponentTooltipDirective } from '../../directives/component-tooltip.directive'; +import { AppAuthorTooltipComponent } from '../../shared/ui/app-author-tooltip/app-author-tooltip.component'; +import { PATENT_ICON } from '../../shared/ui/icons'; import { EuProjectStatusChartComponent } from './eu-project-status-chart/eu-project-status-chart.component'; import { YearRangeSliderComponent } from '../../shared/ui/year-range-slider/year-range-slider.component'; import { LoadingComponent } from '../../shared/ui/loading/loading.component'; @@ -58,6 +62,8 @@ type DashboardPeriodMode = imports: [ DecimalPipe, MatIconModule, + MatTooltipModule, + ComponentTooltipDirective, RouterLink, LoadingComponent, EuProjectStatusChartComponent, @@ -68,6 +74,8 @@ type DashboardPeriodMode = styleUrl: './dashboard.component.scss', }) export class DashboardComponent implements OnInit { + readonly AuthorTooltipComponent = AppAuthorTooltipComponent; + readonly patentIcon = PATENT_ICON; statistics?: Partial; statisticsLoading = false; statisticsError = false; @@ -370,6 +378,7 @@ export class DashboardComponent implements OnInit { onDfgTopicTreemapNodeChange(nodeId: string | undefined): void { this.selectedDfgTopicTreemapNode = nodeId; + this.updateDashboardPeriodUrl(); } onDfgTopicTreemapTopicSelect(topic: TopicTreemapTopicSelect): void { @@ -398,6 +407,7 @@ export class DashboardComponent implements OnInit { onEuTopicTreemapNodeChange(nodeId: string | undefined): void { this.selectedEuTopicTreemapNode = nodeId; + this.updateDashboardPeriodUrl(); } onEuTopicTreemapTopicSelect(topic: TopicTreemapTopicSelect): void { @@ -426,6 +436,7 @@ export class DashboardComponent implements OnInit { onBundTopicTreemapNodeChange(nodeId: string | undefined): void { this.selectedBundTopicTreemapNode = nodeId; + this.updateDashboardPeriodUrl(); } onBundTopicTreemapTopicSelect(topic: TopicTreemapTopicSelect): void { @@ -494,6 +505,12 @@ export class DashboardComponent implements OnInit { this.dashboardFromYear = this.dashboardToYear; } this.selectedTopicTreemapNode = params.get('treemapNode') ?? undefined; + this.selectedDfgTopicTreemapNode = + params.get('dfgTreemapNode') ?? undefined; + this.selectedEuTopicTreemapNode = + params.get('euTreemapNode') ?? undefined; + this.selectedBundTopicTreemapNode = + params.get('bundTreemapNode') ?? undefined; } private applyPresetPeriod(): void { @@ -519,6 +536,9 @@ export class DashboardComponent implements OnInit { fromYear: period.fromYear ?? null, toYear: period.toYear ?? null, treemapNode: this.selectedTopicTreemapNode ?? null, + dfgTreemapNode: this.selectedDfgTopicTreemapNode ?? null, + euTreemapNode: this.selectedEuTopicTreemapNode ?? null, + bundTreemapNode: this.selectedBundTopicTreemapNode ?? null, }, queryParamsHandling: 'merge', replaceUrl: true, From e8e0decc6c2fb1a2b574cff260137c1a3afe5805 Mon Sep 17 00:00:00 2001 From: louis-19041904 Date: Tue, 11 Aug 2026 10:47:38 +0200 Subject: [PATCH 103/114] add domain/field/subfield lookup endpoints --- service/src/main/inse/model.py | 3 + service/src/main/inse/topics/v2/router.py | 45 + service/src/main/inse/topics/v2/service.py | 114 ++ webapp/src/app/api/api/topicsV2.service.ts | 996 ++++++++++++++---- webapp/src/app/api/model/domain.ts | 29 + webapp/src/app/api/model/domainFieldsInner.ts | 17 + webapp/src/app/api/model/domainIds.ts | 18 + webapp/src/app/api/model/modelField.ts | 31 + webapp/src/app/api/model/models.ts | 7 + webapp/src/app/api/model/subfield.ts | 33 + webapp/src/app/api/model/subfieldDomain.ts | 17 + webapp/src/app/api/model/subfieldField.ts | 17 + 12 files changed, 1094 insertions(+), 233 deletions(-) create mode 100644 webapp/src/app/api/model/domain.ts create mode 100644 webapp/src/app/api/model/domainFieldsInner.ts create mode 100644 webapp/src/app/api/model/domainIds.ts create mode 100644 webapp/src/app/api/model/modelField.ts create mode 100644 webapp/src/app/api/model/subfield.ts create mode 100644 webapp/src/app/api/model/subfieldDomain.ts create mode 100644 webapp/src/app/api/model/subfieldField.ts diff --git a/service/src/main/inse/model.py b/service/src/main/inse/model.py index 83c064c3..882338ad 100644 --- a/service/src/main/inse/model.py +++ b/service/src/main/inse/model.py @@ -52,6 +52,9 @@ class ESIndex(StrEnum): OPENALEX_CONTINENTS = "openalex-continents" OPENALEX_TOPICS = "openalex-topics" OPENALEX_TOPIC_VECTORS = "topicvectors" + OPENALEX_DOMAINS = "openalex-domains" + OPENALEX_FIELDS = "openalex-fields" + OPENALEX_SUBFIELDS = "openalex-subfields" EPO_INDEX = "epo_index_1.0" USPTO_INDEX = "uspto_patents_3.0" diff --git a/service/src/main/inse/topics/v2/router.py b/service/src/main/inse/topics/v2/router.py index f382d5a0..0a7fe43a 100644 --- a/service/src/main/inse/topics/v2/router.py +++ b/service/src/main/inse/topics/v2/router.py @@ -4,6 +4,9 @@ from typing import Annotated import inse.topics.v2.service as topics_service from fastapi import APIRouter, Path, Query from inse.model import SortDirection +from inse.models.openalex.domain import Domain +from inse.models.openalex.model_field import ModelField +from inse.models.openalex.subfield import Subfield from inse.models.openalex.topic import Topic from inse.router_prefixes import RouterPrefixes from inse.tags import Tags @@ -78,6 +81,48 @@ async def get_topic_by_id( ) +@router.get( + "/domains/single/{domain_id}", + operation_id="getDomainById", + summary="Returns a domain for a given domain ID.", +) +async def get_domain_by_id( + domain_id: Annotated[ + str, + Path(description="The ID of the domain to retrieve."), + ], +) -> Domain: + return await topics_service.get_domain_by_id_or_raise(domain_id=domain_id) + + +@router.get( + "/fields/single/{field_id}", + operation_id="getFieldById", + summary="Returns a field for a given field ID.", +) +async def get_field_by_id( + field_id: Annotated[ + str, + Path(description="The ID of the field to retrieve."), + ], +) -> ModelField: + return await topics_service.get_field_by_id_or_raise(field_id=field_id) + + +@router.get( + "/subfields/single/{subfield_id}", + operation_id="getSubfieldById", + summary="Returns a subfield for a given subfield ID.", +) +async def get_subfield_by_id( + subfield_id: Annotated[ + str, + Path(description="The ID of the subfield to retrieve."), + ], +) -> Subfield: + return await topics_service.get_subfield_by_id_or_raise(subfield_id=subfield_id) + + @router.get( "/topics/id", operation_id="getTopicsByIds", diff --git a/service/src/main/inse/topics/v2/service.py b/service/src/main/inse/topics/v2/service.py index b73379d8..b10c7d60 100644 --- a/service/src/main/inse/topics/v2/service.py +++ b/service/src/main/inse/topics/v2/service.py @@ -1,6 +1,9 @@ from inse.exceptions import NotFoundException from inse.integrations import elasticsearch from inse.model import ESIndex, SortDirection +from inse.models.openalex.domain import Domain +from inse.models.openalex.model_field import ModelField +from inse.models.openalex.subfield import Subfield from inse.models.openalex.topic import Topic from inse.topics.v2.model import TopicPageV2, TopicSortBy @@ -184,6 +187,117 @@ async def get_topic_by_id_or_raise(raw_oa_topic_id: str) -> Topic: return topic +async def get_domain_by_id(domain_id: str) -> Domain | None: + """Retrieves a domain based on its ID. + + Args: + domain_id (str): The numeric OpenAlex ID of the domain to retrieve (e.g. "4"). + + Returns: + Domain | None: The domain matching the provided ID, or None if not found. + """ + response = await elasticsearch.get( + index=ESIndex.OPENALEX_DOMAINS, + doc_id=domain_id, + source=["id", "display_name", "description"], + ) + if response.get("found"): + return Domain.from_dict(response.get("_source", {})) + return None + + +async def get_domain_by_id_or_raise(domain_id: str) -> Domain: + """Retrieves a domain based on its ID, raising an exception if not found. + + Args: + domain_id (str): The ID of the domain to retrieve. + + Raises: + NotFoundException: If the domain with the specified ID is not found. + + Returns: + Domain: The domain matching the provided ID. + """ + domain = await get_domain_by_id(domain_id) + if domain is None: + raise NotFoundException(f"Domain with ID {domain_id} not found.") + return domain + + +async def get_field_by_id(field_id: str) -> ModelField | None: + """Retrieves a field based on its ID. + + Args: + field_id (str): The numeric OpenAlex ID of the field to retrieve (e.g. "27"). + + Returns: + ModelField | None: The field matching the provided ID, or None if not found. + """ + response = await elasticsearch.get( + index=ESIndex.OPENALEX_FIELDS, + doc_id=field_id, + source=["id", "display_name", "description"], + ) + if response.get("found"): + return ModelField.from_dict(response.get("_source", {})) + return None + + +async def get_field_by_id_or_raise(field_id: str) -> ModelField: + """Retrieves a field based on its ID, raising an exception if not found. + + Args: + field_id (str): The ID of the field to retrieve. + + Raises: + NotFoundException: If the field with the specified ID is not found. + + Returns: + ModelField: The field matching the provided ID. + """ + field = await get_field_by_id(field_id) + if field is None: + raise NotFoundException(f"Field with ID {field_id} not found.") + return field + + +async def get_subfield_by_id(subfield_id: str) -> Subfield | None: + """Retrieves a subfield based on its ID. + + Args: + subfield_id (str): The numeric OpenAlex ID of the subfield to retrieve (e.g. "2743"). + + Returns: + Subfield | None: The subfield matching the provided ID, or None if not found. + """ + response = await elasticsearch.get( + index=ESIndex.OPENALEX_SUBFIELDS, + doc_id=subfield_id, + source=["id", "display_name", "description"], + ) + if response.get("found"): + return Subfield.from_dict(response.get("_source", {})) + return None + + +async def get_subfield_by_id_or_raise(subfield_id: str) -> Subfield: + """Retrieves a subfield based on its ID, raising an exception if not found. + + Args: + subfield_id (str): The ID of the subfield to retrieve. + + Raises: + NotFoundException: If the subfield with the specified ID is not found. + + Returns: + Subfield: The subfield matching the provided ID. + """ + subfield = await get_subfield_by_id(subfield_id) + if subfield is None: + raise NotFoundException(f"Subfield with ID {subfield_id} not found.") + return subfield + + async def get_topics_by_ids(topic_ids: list[str]) -> TopicPageV2: """Retrieves topics based on a list of topic IDs. diff --git a/webapp/src/app/api/api/topicsV2.service.ts b/webapp/src/app/api/api/topicsV2.service.ts index 674c4906..4f378585 100644 --- a/webapp/src/app/api/api/topicsV2.service.ts +++ b/webapp/src/app/api/api/topicsV2.service.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,18 +9,30 @@ */ /* tslint:disable:no-unused-variable member-ordering */ -import { Inject, Injectable, Optional } from '@angular/core'; -import { HttpClient, HttpHeaders, HttpParams, - HttpResponse, HttpEvent, HttpParameterCodec, HttpContext - } from '@angular/common/http'; -import { CustomHttpParameterCodec } from '../encoder'; -import { Observable } from 'rxjs'; +import { Inject, Injectable, Optional } from '@angular/core'; +import { + HttpClient, + HttpHeaders, + HttpParams, + HttpResponse, + HttpEvent, + HttpParameterCodec, + HttpContext, +} from '@angular/common/http'; +import { CustomHttpParameterCodec } from '../encoder'; +import { Observable } from 'rxjs'; +// @ts-ignore +import { Domain } from '../model/domain'; // @ts-ignore import { HTTPValidationError } from '../model/hTTPValidationError'; // @ts-ignore +import { ModelField } from '../model/modelField'; +// @ts-ignore import { SortDirection } from '../model/sortDirection'; // @ts-ignore +import { Subfield } from '../model/subfield'; +// @ts-ignore import { Topic } from '../model/topic'; // @ts-ignore import { TopicPageV2 } from '../model/topicPageV2'; @@ -28,261 +40,779 @@ import { TopicPageV2 } from '../model/topicPageV2'; import { TopicSortBy } from '../model/topicSortBy'; // @ts-ignore -import { BASE_PATH, COLLECTION_FORMATS } from '../variables'; -import { Configuration } from '../configuration'; +import { BASE_PATH, COLLECTION_FORMATS } from '../variables'; +import { Configuration } from '../configuration'; import { BaseService } from '../api.base.service'; - - @Injectable({ - providedIn: 'root' + providedIn: 'root', }) export class TopicsV2Service extends BaseService { + constructor( + protected httpClient: HttpClient, + @Optional() @Inject(BASE_PATH) basePath: string | string[], + @Optional() configuration?: Configuration, + ) { + super(basePath, configuration); + } - constructor(protected httpClient: HttpClient, @Optional() @Inject(BASE_PATH) basePath: string|string[], @Optional() configuration?: Configuration) { - super(basePath, configuration); + /** + * Returns a paginated list of topics for a given search term based on their display name. + * @endpoint get /api/topics/v2/autocomplete/selector + * @param query A search term to filter topics by (partial matches allowed). + * @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 autocompleteTopicsForSelector( + query?: string, + observe?: 'body', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable; + public autocompleteTopicsForSelector( + query?: string, + observe?: 'response', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public autocompleteTopicsForSelector( + query?: string, + observe?: 'events', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public autocompleteTopicsForSelector( + query?: string, + 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', + ); + + let localVarHeaders = this.defaultHeaders; + + const localVarHttpHeaderAcceptSelected: string | undefined = + options?.httpHeaderAccept ?? + this.configuration.selectHeaderAccept(['application/json']); + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set( + 'Accept', + localVarHttpHeaderAcceptSelected, + ); } - /** - * Returns a paginated list of topics for a given search term based on their display name. - * @endpoint get /api/topics/v2/autocomplete/selector - * @param query A search term to filter topics by (partial matches allowed). - * @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 autocompleteTopicsForSelector(query?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; - public autocompleteTopicsForSelector(query?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public autocompleteTopicsForSelector(query?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public autocompleteTopicsForSelector(query?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + const localVarHttpContext: HttpContext = + options?.context ?? new HttpContext(); - let localVarQueryParameters = new HttpParams({encoder: this.encoder}); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - query, 'query'); + const localVarTransferCache: boolean = options?.transferCache ?? true; - let localVarHeaders = this.defaultHeaders; + 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'; + } + } - const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([ - 'application/json' - ]); - if (localVarHttpHeaderAcceptSelected !== undefined) { - localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); - } + let localVarPath = `/api/topics/v2/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, + }, + ); + } - const localVarHttpContext: HttpContext = options?.context ?? new HttpContext(); + /** + * Returns a domain for a given domain ID. + * @endpoint get /api/topics/v2/domains/single/{domain_id} + * @param domainId The ID of the domain 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 getDomainById( + domainId: string, + observe?: 'body', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable; + public getDomainById( + domainId: string, + observe?: 'response', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public getDomainById( + domainId: string, + observe?: 'events', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public getDomainById( + domainId: string, + observe: any = 'body', + reportProgress: boolean = false, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable { + if (domainId === null || domainId === undefined) { + throw new Error( + 'Required parameter domainId was null or undefined when calling getDomainById.', + ); + } - const localVarTransferCache: boolean = options?.transferCache ?? true; + let localVarHeaders = this.defaultHeaders; + const localVarHttpHeaderAcceptSelected: string | undefined = + options?.httpHeaderAccept ?? + this.configuration.selectHeaderAccept(['application/json']); + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set( + 'Accept', + localVarHttpHeaderAcceptSelected, + ); + } - 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'; - } - } + const localVarHttpContext: HttpContext = + options?.context ?? new HttpContext(); - let localVarPath = `/api/topics/v2/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 - } + 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/topics/v2/domains/single/${this.configuration.encodeParam({ name: 'domainId', value: domainId, in: 'path', style: 'simple', explode: false, dataType: 'string', dataFormat: undefined })}`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request( + 'get', + `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined + ? { transferCache: localVarTransferCache } + : {}), + reportProgress: reportProgress, + }, + ); + } + + /** + * Returns a field for a given field ID. + * @endpoint get /api/topics/v2/fields/single/{field_id} + * @param fieldId The ID of the field 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 getFieldById( + fieldId: string, + observe?: 'body', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable; + public getFieldById( + fieldId: string, + observe?: 'response', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public getFieldById( + fieldId: string, + observe?: 'events', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public getFieldById( + fieldId: string, + observe: any = 'body', + reportProgress: boolean = false, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable { + if (fieldId === null || fieldId === undefined) { + throw new Error( + 'Required parameter fieldId was null or undefined when calling getFieldById.', + ); + } + + 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/topics/v2/fields/single/${this.configuration.encodeParam({ name: 'fieldId', value: fieldId, in: 'path', style: 'simple', explode: false, dataType: 'string', dataFormat: undefined })}`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request( + 'get', + `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined + ? { transferCache: localVarTransferCache } + : {}), + reportProgress: reportProgress, + }, + ); + } + + /** + * Returns a subfield for a given subfield ID. + * @endpoint get /api/topics/v2/subfields/single/{subfield_id} + * @param subfieldId The ID of the subfield 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 getSubfieldById( + subfieldId: string, + observe?: 'body', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable; + public getSubfieldById( + subfieldId: string, + observe?: 'response', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public getSubfieldById( + subfieldId: string, + observe?: 'events', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public getSubfieldById( + subfieldId: string, + observe: any = 'body', + reportProgress: boolean = false, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable { + if (subfieldId === null || subfieldId === undefined) { + throw new Error( + 'Required parameter subfieldId was null or undefined when calling getSubfieldById.', + ); + } + + 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/topics/v2/subfields/single/${this.configuration.encodeParam({ name: 'subfieldId', value: subfieldId, in: 'path', style: 'simple', explode: false, dataType: 'string', dataFormat: undefined })}`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request( + 'get', + `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined + ? { transferCache: localVarTransferCache } + : {}), + reportProgress: reportProgress, + }, + ); + } + + /** + * Returns a topic for a given topic ID. + * @endpoint get /api/topics/v2/single/{raw_oa_topic_id} + * @param rawOaTopicId The ID of the topic 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 getTopicById( + rawOaTopicId: string, + observe?: 'body', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable; + public getTopicById( + rawOaTopicId: string, + observe?: 'response', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public getTopicById( + rawOaTopicId: string, + observe?: 'events', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public getTopicById( + rawOaTopicId: string, + observe: any = 'body', + reportProgress: boolean = false, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable { + if (rawOaTopicId === null || rawOaTopicId === undefined) { + throw new Error( + 'Required parameter rawOaTopicId was null or undefined when calling getTopicById.', + ); + } + + 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/topics/v2/single/${this.configuration.encodeParam({ name: 'rawOaTopicId', value: rawOaTopicId, in: 'path', style: 'simple', explode: false, dataType: 'string', dataFormat: undefined })}`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request('get', `${basePath}${localVarPath}`, { + context: localVarHttpContext, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined + ? { transferCache: localVarTransferCache } + : {}), + reportProgress: reportProgress, + }); + } + + /** + * Returns a paginated list of topics for a given list of topic IDs. + * @endpoint get /api/topics/v2/topics/id + * @param topicIds A list of topic 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 getTopicsByIds( + topicIds?: Array, + observe?: 'body', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable; + public getTopicsByIds( + topicIds?: Array, + observe?: 'response', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public getTopicsByIds( + topicIds?: Array, + observe?: 'events', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public getTopicsByIds( + topicIds?: Array, + observe: any = 'body', + reportProgress: boolean = false, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable { + let localVarQueryParameters = new HttpParams({ encoder: this.encoder }); + if (topicIds) { + topicIds.forEach((element) => { + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + element, + 'topic_ids', ); + }); } - /** - * Returns a topic for a given topic ID. - * @endpoint get /api/topics/v2/single/{raw_oa_topic_id} - * @param rawOaTopicId The ID of the topic 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 getTopicById(rawOaTopicId: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; - public getTopicById(rawOaTopicId: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public getTopicById(rawOaTopicId: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public getTopicById(rawOaTopicId: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { - if (rawOaTopicId === null || rawOaTopicId === undefined) { - throw new Error('Required parameter rawOaTopicId was null or undefined when calling getTopicById.'); - } + let localVarHeaders = this.defaultHeaders; - 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/topics/v2/single/${this.configuration.encodeParam({name: "rawOaTopicId", value: rawOaTopicId, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: undefined})}`; - const { basePath, withCredentials } = this.configuration; - return this.httpClient.request('get', `${basePath}${localVarPath}`, - { - context: localVarHttpContext, - responseType: responseType_, - ...(withCredentials ? { withCredentials } : {}), - headers: localVarHeaders, - observe: observe, - ...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}), - reportProgress: reportProgress - } - ); + const localVarHttpHeaderAcceptSelected: string | undefined = + options?.httpHeaderAccept ?? + this.configuration.selectHeaderAccept(['application/json']); + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set( + 'Accept', + localVarHttpHeaderAcceptSelected, + ); } - /** - * Returns a paginated list of topics for a given list of topic IDs. - * @endpoint get /api/topics/v2/topics/id - * @param topicIds A list of topic 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 getTopicsByIds(topicIds?: Array, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; - public getTopicsByIds(topicIds?: Array, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public getTopicsByIds(topicIds?: Array, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public getTopicsByIds(topicIds?: Array, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + const localVarHttpContext: HttpContext = + options?.context ?? new HttpContext(); - let localVarQueryParameters = new HttpParams({encoder: this.encoder}); - if (topicIds) { - topicIds.forEach((element) => { - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - element, 'topic_ids'); - }) - } + const localVarTransferCache: boolean = options?.transferCache ?? true; - 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/topics/v2/topics/id`; - 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 - } - ); + 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'; + } } - /** - * Searches for topics based on the provided criteria. - * @endpoint get /api/topics/v2/search - * @param searchTerm The term to search for in topic display names. - * @param page The page number to retrieve. - * @param size The number of topics to retrieve per page. - * @param sortBy The field to sort by. - * @param sortDirection The direction to sort. - * @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 searchTopics(searchTerm?: string, page?: number, size?: number, sortBy?: TopicSortBy, sortDirection?: SortDirection, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; - public searchTopics(searchTerm?: string, page?: number, size?: number, sortBy?: TopicSortBy, sortDirection?: SortDirection, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public searchTopics(searchTerm?: string, page?: number, size?: number, sortBy?: TopicSortBy, sortDirection?: SortDirection, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public searchTopics(searchTerm?: string, page?: number, size?: number, sortBy?: TopicSortBy, sortDirection?: SortDirection, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + let localVarPath = `/api/topics/v2/topics/id`; + 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, + }, + ); + } - let localVarQueryParameters = new HttpParams({encoder: this.encoder}); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - searchTerm, 'search_term'); - 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'); + /** + * Searches for topics based on the provided criteria. + * @endpoint get /api/topics/v2/search + * @param searchTerm The term to search for in topic display names. + * @param page The page number to retrieve. + * @param size The number of topics to retrieve per page. + * @param sortBy The field to sort by. + * @param sortDirection The direction to sort. + * @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 searchTopics( + searchTerm?: string, + page?: number, + size?: number, + sortBy?: TopicSortBy, + sortDirection?: SortDirection, + observe?: 'body', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable; + public searchTopics( + searchTerm?: string, + page?: number, + size?: number, + sortBy?: TopicSortBy, + sortDirection?: SortDirection, + observe?: 'response', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public searchTopics( + searchTerm?: string, + page?: number, + size?: number, + sortBy?: TopicSortBy, + sortDirection?: SortDirection, + observe?: 'events', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public searchTopics( + searchTerm?: string, + page?: number, + size?: number, + sortBy?: TopicSortBy, + sortDirection?: SortDirection, + 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, + searchTerm, + 'search_term', + ); + 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', + ); - let localVarHeaders = this.defaultHeaders; + 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/topics/v2/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 - } - ); + 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/topics/v2/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, + }, + ); + } } diff --git a/webapp/src/app/api/model/domain.ts b/webapp/src/app/api/model/domain.ts new file mode 100644 index 00000000..3a6c6b03 --- /dev/null +++ b/webapp/src/app/api/model/domain.ts @@ -0,0 +1,29 @@ +/** + * Innovation Search Engine API + * + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ +import { DomainFieldsInner } from './domainFieldsInner'; +import { DomainIds } from './domainIds'; + +/** + * Top-level category in the topic hierarchy (4 total) + */ +export interface Domain { + id?: string | null; + display_name?: string | null; + description?: string | null; + display_name_alternatives?: Array | null; + fields?: Array | null; + siblings?: Array | null; + ids?: DomainIds | null; + works_count?: number | null; + cited_by_count?: number | null; + works_api_url?: string | null; + created_date?: string | null; + updated_date?: string | null; +} diff --git a/webapp/src/app/api/model/domainFieldsInner.ts b/webapp/src/app/api/model/domainFieldsInner.ts new file mode 100644 index 00000000..302feae8 --- /dev/null +++ b/webapp/src/app/api/model/domainFieldsInner.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. + */ + +/** + * DomainFieldsInner + */ +export interface DomainFieldsInner { + id?: string | null; + display_name?: string | null; +} diff --git a/webapp/src/app/api/model/domainIds.ts b/webapp/src/app/api/model/domainIds.ts new file mode 100644 index 00000000..da44d258 --- /dev/null +++ b/webapp/src/app/api/model/domainIds.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. + */ + +/** + * External identifiers: + */ +export interface DomainIds { + openalex?: string | null; + wikidata?: string | null; + wikipedia?: string | null; +} diff --git a/webapp/src/app/api/model/modelField.ts b/webapp/src/app/api/model/modelField.ts new file mode 100644 index 00000000..f0aa2203 --- /dev/null +++ b/webapp/src/app/api/model/modelField.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 { DomainFieldsInner } from './domainFieldsInner'; +import { DomainIds } from './domainIds'; +import { WorkTopicDomain } from './workTopicDomain'; + +/** + * Second-level category in the topic hierarchy (26 total) + */ +export interface ModelField { + id?: string | null; + display_name?: string | null; + description?: string | null; + display_name_alternatives?: Array | null; + domain?: WorkTopicDomain | null; + subfields?: Array | null; + siblings?: Array | null; + ids?: DomainIds | null; + works_count?: number | null; + cited_by_count?: number | null; + works_api_url?: string | null; + created_date?: string | null; + updated_date?: string | null; +} diff --git a/webapp/src/app/api/model/models.ts b/webapp/src/app/api/model/models.ts index afed834d..ada7aabd 100644 --- a/webapp/src/app/api/model/models.ts +++ b/webapp/src/app/api/model/models.ts @@ -78,6 +78,9 @@ export * from './dfgProjectSummary'; export * from './dfgProjectTopic'; export * from './dfgProjectTopics'; export * from './dockerHealth'; +export * from './domain'; +export * from './domainFieldsInner'; +export * from './domainIds'; export * from './edge'; export * from './euCordisEurosciVocSummary'; export * from './euCordisOrganizationSelectorPage'; @@ -172,6 +175,7 @@ export * from './matchedTopic'; export * from './mentionedPerson'; export * from './meta'; export * from './model2YrMeanCitedness'; +export * from './modelField'; export * from './newsArticle'; export * from './newsArticleDetail'; export * from './newsPage'; @@ -206,6 +210,9 @@ export * from './score'; export * from './selectedAuthorsRequest'; export * from './sortDirection'; export * from './startCollaborationGraphResponse'; +export * from './subfield'; +export * from './subfieldDomain'; +export * from './subfieldField'; export * from './subfieldShare'; export * from './timespan'; export * from './tokenType'; diff --git a/webapp/src/app/api/model/subfield.ts b/webapp/src/app/api/model/subfield.ts new file mode 100644 index 00000000..ef678f6a --- /dev/null +++ b/webapp/src/app/api/model/subfield.ts @@ -0,0 +1,33 @@ +/** + * 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 { DomainFieldsInner } from './domainFieldsInner'; +import { DomainIds } from './domainIds'; +import { SubfieldDomain } from './subfieldDomain'; +import { SubfieldField } from './subfieldField'; + +/** + * Third-level category in the topic hierarchy (254 total) + */ +export interface Subfield { + id?: string | null; + display_name?: string | null; + description?: string | null; + display_name_alternatives?: Array | null; + field?: SubfieldField | null; + domain?: SubfieldDomain | null; + topics?: Array | null; + siblings?: Array | null; + ids?: DomainIds | null; + works_count?: number | null; + cited_by_count?: number | null; + works_api_url?: string | null; + created_date?: string | null; + updated_date?: string | null; +} diff --git a/webapp/src/app/api/model/subfieldDomain.ts b/webapp/src/app/api/model/subfieldDomain.ts new file mode 100644 index 00000000..b2228d75 --- /dev/null +++ b/webapp/src/app/api/model/subfieldDomain.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. + */ + +/** + * The domain containing this subfield (top level of hierarchy). + */ +export interface SubfieldDomain { + id?: string | null; + display_name?: string | null; +} diff --git a/webapp/src/app/api/model/subfieldField.ts b/webapp/src/app/api/model/subfieldField.ts new file mode 100644 index 00000000..8aff75ea --- /dev/null +++ b/webapp/src/app/api/model/subfieldField.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. + */ + +/** + * The field containing this subfield (parent level). + */ +export interface SubfieldField { + id?: string | null; + display_name?: string | null; +} From 89f45082fb43b45d8f645188b2a8c98980b9cff3 Mon Sep 17 00:00:00 2001 From: louis-19041904 Date: Tue, 11 Aug 2026 10:48:05 +0200 Subject: [PATCH 104/114] fetch field/subfield descriptions on hover in legend tooltip --- .../legend-tooltip.component.html | 4 +- .../legend-tooltip.component.ts | 55 ++++++++++++++++++- .../topic-legend/topic-legend.component.html | 6 +- .../ui/topic-legend/topic-legend.component.ts | 4 ++ 4 files changed, 64 insertions(+), 5 deletions(-) diff --git a/webapp/src/app/shared/ui/legend-tooltip/legend-tooltip.component.html b/webapp/src/app/shared/ui/legend-tooltip/legend-tooltip.component.html index 2ed8354f..01060734 100644 --- a/webapp/src/app/shared/ui/legend-tooltip/legend-tooltip.component.html +++ b/webapp/src/app/shared/ui/legend-tooltip/legend-tooltip.component.html @@ -3,8 +3,8 @@ @if (hierarchy()) {
    {{ hierarchy() }}
    } - @if (description()) { + @if (_description()) {
    -

    {{ description() }}

    +

    {{ _description() }}

    }
    diff --git a/webapp/src/app/shared/ui/legend-tooltip/legend-tooltip.component.ts b/webapp/src/app/shared/ui/legend-tooltip/legend-tooltip.component.ts index 76390e98..c415af24 100644 --- a/webapp/src/app/shared/ui/legend-tooltip/legend-tooltip.component.ts +++ b/webapp/src/app/shared/ui/legend-tooltip/legend-tooltip.component.ts @@ -1,4 +1,12 @@ -import { Component, computed, input } from '@angular/core'; +import { + Component, + computed, + effect, + inject, + input, + signal, +} from '@angular/core'; +import { TopicsV2Service } from '../../../api'; @Component({ host: { @@ -10,14 +18,59 @@ import { Component, computed, input } from '@angular/core'; styleUrl: './legend-tooltip.component.scss', }) export class LegendTooltipComponent { + private readonly topicsService = inject(TopicsV2Service); + readonly name = input.required(); readonly hierarchy = input(null); readonly description = input(null); + readonly fieldId = input(null); + readonly subfieldId = input(null); readonly color = input(null); + readonly _description = signal(undefined); + readonly topicColorVar = computed(() => { const color = this.color(); if (!color) return ''; return color.replace('hsl(', '').replace(')', ''); }); + + constructor() { + effect(() => { + const description = this.description(); + if (description) { + this._description.set(description); + return; + } + + const rawSubfieldId = this.extractOpenAlexShortId(this.subfieldId()); + if (rawSubfieldId) { + this.topicsService.getSubfieldById(rawSubfieldId).subscribe({ + next: (subfield) => this._description.set(subfield.description), + error: () => this._description.set(undefined), + }); + return; + } + + const rawFieldId = this.extractOpenAlexShortId(this.fieldId()); + if (rawFieldId) { + this.topicsService.getFieldById(rawFieldId).subscribe({ + next: (field) => this._description.set(field.description), + error: () => this._description.set(undefined), + }); + return; + } + + this._description.set(undefined); + }); + } + + private extractOpenAlexShortId( + id: string | null | undefined, + ): string | undefined { + if (!id || !id.includes('openalex.org')) { + return undefined; + } + return id.split('/').pop() || undefined; + } } diff --git a/webapp/src/app/shared/ui/topic-legend/topic-legend.component.html b/webapp/src/app/shared/ui/topic-legend/topic-legend.component.html index d86fe307..83598c47 100644 --- a/webapp/src/app/shared/ui/topic-legend/topic-legend.component.html +++ b/webapp/src/app/shared/ui/topic-legend/topic-legend.component.html @@ -59,9 +59,10 @@ name: group.name, hierarchy: group.domainName, description: group.description, + fieldId: group.id, color: group.color, }" - [tooltipDisabled]="!group.description" + [tooltipDisabled]="!hasTooltipContent(group.description, group.id)" [tooltipMaxWidth]="'420px'" (click)="toggleField(group)"> {{ item.name }} diff --git a/webapp/src/app/shared/ui/topic-legend/topic-legend.component.ts b/webapp/src/app/shared/ui/topic-legend/topic-legend.component.ts index 1d835d70..b28d3e90 100644 --- a/webapp/src/app/shared/ui/topic-legend/topic-legend.component.ts +++ b/webapp/src/app/shared/ui/topic-legend/topic-legend.component.ts @@ -115,6 +115,10 @@ export class TopicLegendComponent { return item.id; } + hasTooltipContent(description: string, id: string): boolean { + return Boolean(description) || id.includes('openalex.org'); + } + private isActiveLegendId( activeIds: ReadonlySet | readonly string[], id: string, From f1a6c32e0c945e7c4e318a7bc77bd6e43eb24686 Mon Sep 17 00:00:00 2001 From: louis-19041904 Date: Tue, 11 Aug 2026 11:12:48 +0200 Subject: [PATCH 105/114] fix: prevent undefined hierarchy and missing metrics in topic tooltip --- .../app-topic-card.component.html | 28 ++++++++++--------- .../app-topic-card.component.ts | 8 +++++- .../app-topic-tooltip.component.ts | 9 ++++-- 3 files changed, 28 insertions(+), 17 deletions(-) diff --git a/webapp/src/app/shared/ui/app-topic-card/app-topic-card.component.html b/webapp/src/app/shared/ui/app-topic-card/app-topic-card.component.html index 60f5625b..e1439308 100644 --- a/webapp/src/app/shared/ui/app-topic-card/app-topic-card.component.html +++ b/webapp/src/app/shared/ui/app-topic-card/app-topic-card.component.html @@ -35,18 +35,20 @@
    - + @if (topic.id) { + - - - - menu_book - Publikationen - - - + + + + menu_book + Publikationen + + + + } diff --git a/webapp/src/app/shared/ui/app-topic-card/app-topic-card.component.ts b/webapp/src/app/shared/ui/app-topic-card/app-topic-card.component.ts index ecf8affe..f6e204c9 100644 --- a/webapp/src/app/shared/ui/app-topic-card/app-topic-card.component.ts +++ b/webapp/src/app/shared/ui/app-topic-card/app-topic-card.component.ts @@ -35,7 +35,13 @@ export class AppTopicCardComponent { } subtitle = computed(() => { - return `${this.topic().subfield?.display_name} - ${this.topic().field?.display_name} - ${this.topic().domain?.display_name}`; + return [ + this.topic().subfield?.display_name, + this.topic().field?.display_name, + this.topic().domain?.display_name, + ] + .filter((part) => Boolean(part)) + .join(' - '); }); description = computed(() => { diff --git a/webapp/src/app/shared/ui/app-topic-tooltip/app-topic-tooltip.component.ts b/webapp/src/app/shared/ui/app-topic-tooltip/app-topic-tooltip.component.ts index 67c6b20e..2315bad7 100644 --- a/webapp/src/app/shared/ui/app-topic-tooltip/app-topic-tooltip.component.ts +++ b/webapp/src/app/shared/ui/app-topic-tooltip/app-topic-tooltip.component.ts @@ -24,9 +24,12 @@ export class AppTopicTooltipComponent { const hasCompleteMetrics = Boolean( topicObj && - (topicObj.description || - topicObj.works_count !== undefined || - topicObj.cited_by_count !== undefined), + topicObj.description && + topicObj.works_count !== undefined && + topicObj.cited_by_count !== undefined && + topicObj.subfield && + topicObj.field && + topicObj.domain, ); if (hasCompleteMetrics && topicObj) { From e1b3318e68c232a63e52e7db4c19d7a0887fd6de Mon Sep 17 00:00:00 2001 From: Farajollahi Date: Tue, 11 Aug 2026 11:37:30 +0200 Subject: [PATCH 106/114] fix eu --- .../src/main/inse/dashboard/test_service.py | 61 ++++++++++++++- .../inse/dashboard/top_authors_service.py | 78 ++++++++++++++----- 2 files changed, 115 insertions(+), 24 deletions(-) diff --git a/service/src/main/inse/dashboard/test_service.py b/service/src/main/inse/dashboard/test_service.py index 2e8cc6c0..6d438e0f 100644 --- a/service/src/main/inse/dashboard/test_service.py +++ b/service/src/main/inse/dashboard/test_service.py @@ -1,3 +1,4 @@ +import asyncio from datetime import datetime import hashlib from unittest.mock import AsyncMock, patch @@ -21,6 +22,7 @@ from inse.dashboard.common import ( ) from inse.dashboard.bund_topics_service import get_dashboard_bund_topics from inse.dashboard.eu_topics_service import get_dashboard_eu_topics +from inse.dashboard.model import TopAuthor from inse.dashboard.project_status_service import reconcile_status_counts from inse.dashboard.project_ids_service import ( _get_dfg_project_ids_from_projects_service, @@ -31,10 +33,12 @@ from inse.dashboard.project_statistics_service import ( get_dashboard_eu_projects, ) from inse.dashboard.top_authors_service import ( + _count_eu_projects_for_candidates, _openalex_work_authors_by_eu_projects, _top_news_authors, get_top_authors, ) +from inse.exceptions import ElasticsearchException from inse.model import ESIndex from inse.models.openalex.institution import Institution from inse.models.openalex.meta import Meta @@ -53,6 +57,54 @@ from inse.works.v2 import service as works_v2_service ORG_INSTITUTION_ID = "https://openalex.org/I123" +@pytest.mark.anyio +async def test_eu_project_counts_are_bounded_retried_and_isolated(): + attempts: dict[str, int] = {} + active_requests = 0 + maximum_active_requests = 0 + + async def count_projects(author_id: str, **kwargs) -> int: + nonlocal active_requests, maximum_active_requests + attempts[author_id] = attempts.get(author_id, 0) + 1 + active_requests += 1 + maximum_active_requests = max(maximum_active_requests, active_requests) + await asyncio.sleep(0.001) + active_requests -= 1 + if author_id == "A0" and attempts[author_id] < 3: + raise ElasticsearchException("temporary") + if author_id == "A1": + raise ElasticsearchException("unavailable") + return int(author_id.removeprefix("A")) + + candidates = [ + TopAuthor(id=f"A{index}", name=f"Author {index}", count=0) for index in range(8) + ] + with ( + patch( + "inse.dashboard.top_authors_service._person_eu_project_count", + new=count_projects, + ), + patch( + "inse.dashboard.top_authors_service.EU_PROJECT_COUNT_RETRY_DELAY_SECONDS", + 0, + ), + ): + result = await _count_eu_projects_for_candidates(candidates) + + assert maximum_active_requests <= 5 + assert attempts["A0"] == 3 + assert attempts["A1"] == 3 + assert [author.id for author in result] == [ + "A0", + "A2", + "A3", + "A4", + "A5", + "A6", + "A7", + ] + + @pytest.fixture def anyio_backend(): return "asyncio" @@ -1078,9 +1130,9 @@ async def test_top_eu_project_authors_count_filtered_projects_by_stable_author_i async def eu_projects(**kwargs): assert kwargs["funding_start_years"] is None assert kwargs["funding_end_years"] is None - assert kwargs["active_from_year"] == 2020 - assert kwargs["active_to_year"] == 2022 if kwargs.get("raw_oa_institution_id"): + assert kwargs["active_from_year"] is None + assert kwargs["active_to_year"] is None return EuCordisProjectSearchPage( elements=[ EuCordisProjectSummary( @@ -1094,9 +1146,11 @@ async def test_top_eu_project_authors_count_filtered_projects_by_stable_author_i page=0, size=1000, ) + assert kwargs["active_from_year"] == 2020 + assert kwargs["active_to_year"] == 2022 return EuCordisProjectSearchPage( elements=[], - total={"A1": 4, "A2": 1}[kwargs["author_id"]], + total={"A1": 4, "A2": 0}[kwargs["author_id"]], page=0, size=1, ) @@ -1128,7 +1182,6 @@ async def test_top_eu_project_authors_count_filtered_projects_by_stable_author_i assert [author.model_dump() for author in result.eu_projects] == [ {"id": "A1", "name": "Ada Example", "count": 4}, - {"id": "A2", "name": "Grace Example", "count": 1}, ] diff --git a/service/src/main/inse/dashboard/top_authors_service.py b/service/src/main/inse/dashboard/top_authors_service.py index a8e62560..72a8c1e2 100644 --- a/service/src/main/inse/dashboard/top_authors_service.py +++ b/service/src/main/inse/dashboard/top_authors_service.py @@ -5,7 +5,10 @@ from collections import defaultdict from datetime import datetime from typing import Any, Literal +from fastapi import HTTPException + from inse import config +from inse.exceptions import ElasticsearchException, UpstreamAPIException from inse.integrations import elasticsearch from inse.model import ESCluster, ESIndex from inse.patents.org.elastic_search_client import OrgPatentsSearchClient @@ -27,9 +30,12 @@ from .model import TopAuthor, TopAuthorAnalysis, TopAuthorStatistics from .project_ids_service import _get_eu_project_ids_from_projects_service TOP_AUTHOR_LIMIT = 10 +EU_PROJECT_COUNT_CONCURRENCY = 5 +EU_PROJECT_COUNT_MAX_ATTEMPTS = 3 +EU_PROJECT_COUNT_RETRY_DELAY_SECONDS = 0.5 logger = logging.getLogger(__name__) ACADEMIC_TITLE_RE = re.compile( - r"^(?:(?:professor(?:in)?|prof|dr)(?:\\.-[a-z]+)?\\.?|rer\\.|nat\\.|med\\.|ing\\.)\\s+", + r"^(?:(?:professor(?:in)?|prof|dr)(?:\.-[a-z]+)?\.?|rer\.|nat\.|med\.|ing\.)\s+", re.IGNORECASE, ) @@ -831,11 +837,11 @@ async def _top_eu_project_publication_authors( if not institution_author_ids: return [] - project_ids = await _get_eu_project_ids_from_projects_service( - institution_id, - from_year=from_year, - to_year=to_year, - ) + # Candidate discovery is deliberately all-time. The selected period is + # applied to each person's authoritative project count below. Otherwise a + # person can disappear merely because their recent projects have no linked + # CORDIS publication/DOI, despite having projects in the selected period. + project_ids = await _get_eu_project_ids_from_projects_service(institution_id) if not project_ids: return [] @@ -886,25 +892,57 @@ async def _top_eu_project_publication_authors( institution_author_ids, limit=None, ) - counts = await asyncio.gather( - *( - _person_eu_project_count( - candidate.id, - from_year=from_year, - to_year=to_year, - ) - for candidate in candidates - if candidate.id - ) + ranked = await _count_eu_projects_for_candidates( + candidates, + from_year=from_year, + to_year=to_year, ) - ranked = [ - TopAuthor(id=candidate.id, name=candidate.name, count=count) - for candidate, count in zip(candidates, counts, strict=True) - ] + ranked = [author for author in ranked if author.count > 0] ranked.sort(key=lambda author: (-author.count, author.name, author.id or "")) return ranked[:TOP_AUTHOR_LIMIT] +async def _count_eu_projects_for_candidates( + candidates: list[TopAuthor], + from_year: int | None = None, + to_year: int | None = None, +) -> list[TopAuthor]: + semaphore = asyncio.Semaphore(EU_PROJECT_COUNT_CONCURRENCY) + + async def load(candidate: TopAuthor) -> TopAuthor | None: + if not candidate.id: + return None + + for attempt in range(1, EU_PROJECT_COUNT_MAX_ATTEMPTS + 1): + try: + async with semaphore: + count = await _person_eu_project_count( + candidate.id, + from_year=from_year, + to_year=to_year, + ) + return TopAuthor(id=candidate.id, name=candidate.name, count=count) + except (ElasticsearchException, UpstreamAPIException, HTTPException) as exc: + is_retryable = ( + not isinstance(exc, (HTTPException, UpstreamAPIException)) + or exc.status_code >= 500 + ) + if not is_retryable or attempt == EU_PROJECT_COUNT_MAX_ATTEMPTS: + logger.warning( + "Could not load EU project count for author %s after %s attempt(s).", + candidate.id, + attempt, + exc_info=True, + ) + return None + await asyncio.sleep(EU_PROJECT_COUNT_RETRY_DELAY_SECONDS * attempt) + + return None + + results = await asyncio.gather(*(load(candidate) for candidate in candidates)) + return [result for result in results if result is not None] + + def _cordis_publication_doi_project_ids( response: dict[str, Any], allowed_project_ids: set[str], From 5e7f9688088f6448650e71bf09e272fe3153dafe Mon Sep 17 00:00:00 2001 From: genja Date: Tue, 11 Aug 2026 11:45:24 +0200 Subject: [PATCH 107/114] centralized the error handling in error.service --- webapp/src/app/app.config.ts | 26 +++----- .../src/app/shared/services/error.service.ts | 63 +++++++++++++++++-- 2 files changed, 68 insertions(+), 21 deletions(-) diff --git a/webapp/src/app/app.config.ts b/webapp/src/app/app.config.ts index 0d7f746c..d3f941bf 100644 --- a/webapp/src/app/app.config.ts +++ b/webapp/src/app/app.config.ts @@ -42,11 +42,10 @@ export const appConfig: ApplicationConfig = { withNavigationErrorHandler((navigationError: NavigationError) => { const router = inject(Router); const errorService = inject(ErrorService); + const targetUrl = navigationError.url; - if ( - router.url.includes('/error') || - router.currentNavigation()?.extractedUrl.toString().includes('/error') - ) { + // Prevent an endless loop if navigation to /error itself fails. + if (targetUrl.startsWith('/error')) { console.error( 'Kritischer Fehler beim Laden der Fehlerseite selbst:', navigationError, @@ -56,21 +55,14 @@ export const appConfig: ApplicationConfig = { console.error('Fehler beim Navigieren:', navigationError); - const error = navigationError.error; - let errorMessage: string = 'Unbekannter Fehler'; - if (error instanceof HttpErrorResponse) { - errorMessage = error.error?.message || 'Unbekannter HTTP-Fehler'; - } - - errorService.setError({ - statusCode: error.status || 500, - title: 'Daten-Fehler', - message: 'Die Daten für diese Ansicht konnten nicht geladen werden.', - errorDetails: errorMessage, + errorService.report(navigationError.error, { + title: 'Daten konnten nicht geladen werden', + message: + 'Die Daten für diese Ansicht konnten nicht geladen werden. Bitte versuchen Sie es später erneut.', }); - setTimeout(() => { - router.navigate(['/error'], { replaceUrl: true }); + void router.navigate(['/error'], { + replaceUrl: true, }); }), ), diff --git a/webapp/src/app/shared/services/error.service.ts b/webapp/src/app/shared/services/error.service.ts index 04eb0e40..b0d64d08 100644 --- a/webapp/src/app/shared/services/error.service.ts +++ b/webapp/src/app/shared/services/error.service.ts @@ -1,27 +1,82 @@ +import { HttpErrorResponse } from '@angular/common/http'; import { Injectable, signal } from '@angular/core'; export interface ErrorState { statusCode: number; title: string; message: string; + referenceId?: string; errorDetails?: string; } +export interface ErrorOptions { + title?: string; + message?: string; + referenceId?: string; +} + @Injectable({ providedIn: 'root', }) export class ErrorService { private readonly errorSignal = signal(null); - setError(error: ErrorState): void { - this.errorSignal.set(error); + readonly error = this.errorSignal.asReadonly(); + + report(error: unknown, options: ErrorOptions = {}): ErrorState { + const state: ErrorState = { + statusCode: this.getStatusCode(error), + title: options.title ?? 'Da ist was schiefgelaufen', + message: + options.message ?? + 'Ein unerwarteter Fehler ist aufgetreten. Bitte versuchen Sie es später erneut.', + referenceId: options.referenceId, + errorDetails: this.getDebugDetails(error) || undefined, + }; + + this.errorSignal.set(state); + return state; + } + + consumeError(): ErrorState | null { + const error = this.errorSignal(); + this.errorSignal.set(null); + return error; } clearError(): void { this.errorSignal.set(null); } - getError(): ErrorState | null { - return this.errorSignal(); + private getStatusCode(error: unknown): number { + if (error instanceof HttpErrorResponse) { + return error.status >= 400 && error.status <= 599 ? error.status : 500; + } + + return 500; + } + + private getDebugDetails(error: unknown): string { + if (error instanceof HttpErrorResponse) { + const apiDetail = + typeof error.error === 'object' && + error.error !== null && + 'detail' in error.error && + typeof error.error.detail === 'string' + ? error.error.detail + : undefined; + + return apiDetail ?? error.message; + } + + if (error instanceof Error) { + return error.stack ?? error.message; + } + + try { + return JSON.stringify(error, null, 2); + } catch { + return String(error); + } } } From f8678af87e47e5fef569c478254d7c094a4d6ed9 Mon Sep 17 00:00:00 2001 From: genja Date: Tue, 11 Aug 2026 11:45:48 +0200 Subject: [PATCH 108/114] updated UI for error component, status, details, etc. --- .../error-page/error-page.component.html | 62 ++++++++++---- .../error-page/error-page.component.ts | 83 +++++++++++-------- 2 files changed, 94 insertions(+), 51 deletions(-) diff --git a/webapp/src/app/modules/error-page/error-page.component.html b/webapp/src/app/modules/error-page/error-page.component.html index 126ea4fb..d19a6b48 100644 --- a/webapp/src/app/modules/error-page/error-page.component.html +++ b/webapp/src/app/modules/error-page/error-page.component.html @@ -1,35 +1,63 @@
    - + -
    + - Fehler {{ statusCode() }} -

    {{ title() }}

    -

    {{ message() }}

    + Fehler {{ error().statusCode }} - +

    + {{ error().title }} +

    - @if (errorDetails()) { +

    + {{ error().message }} +

    + + @if (error().referenceId; as referenceId) { +

    + Referenznummer: + {{ referenceId }} +

    + } + +
    + + + + + Startseite + +
    + + @if (error().errorDetails; as details) { + appearance="outlined" + (opened)="isDetailsOpen.set(true)" + (closed)="isDetailsOpen.set(false)"> - ERWEITERTE DIAGNOSE + Erweiterte Diagnose -
    {{ errorDetails() }}
    +
    {{ details }}
    } diff --git a/webapp/src/app/modules/error-page/error-page.component.ts b/webapp/src/app/modules/error-page/error-page.component.ts index 1315396c..20737936 100644 --- a/webapp/src/app/modules/error-page/error-page.component.ts +++ b/webapp/src/app/modules/error-page/error-page.component.ts @@ -1,56 +1,71 @@ -import { Component, input, OnInit, signal, inject } from '@angular/core'; +import { + Component, + computed, + inject, + input, + numberAttribute, + signal, +} from '@angular/core'; +import { Location } from '@angular/common'; +import { Router } from '@angular/router'; import { MatButtonModule } from '@angular/material/button'; import { MatCardModule } from '@angular/material/card'; import { MatExpansionModule } from '@angular/material/expansion'; import { MatIconModule } from '@angular/material/icon'; -import { ErrorService } from '../../shared/services/error.service'; - +import { ErrorService, ErrorState } from '../../shared/services/error.service'; +import { RouterLink } from '@angular/router'; @Component({ selector: 'app-error-page', standalone: true, - imports: [MatButtonModule, MatCardModule, MatIconModule, MatExpansionModule], + imports: [ + MatButtonModule, + MatCardModule, + MatIconModule, + MatExpansionModule, + RouterLink, + ], templateUrl: './error-page.component.html', styleUrl: './error-page.component.scss', }) -export class ErrorPageComponent implements OnInit { - routeStatusCode = input(500); - routeTitle = input('Da ist was schiefgelaufen'); - routeMessage = input( +export class ErrorPageComponent { + readonly routeStatusCode = input(500, { transform: numberAttribute }); + readonly routeTitle = input('Da ist was schiefgelaufen'); + readonly routeMessage = input( 'Ein unerwarteter Fehler ist aufgetreten. Bitte versuchen Sie es später erneut.', ); - routeErrorDetails = input(undefined); + readonly routeErrorDetails = input(); - statusCode = signal(500); - title = signal(''); - message = signal(''); - errorDetails = signal(undefined); - - isDetailsOpen = signal(false); + readonly isDetailsOpen = signal(false); private readonly errorService = inject(ErrorService); + private readonly location = inject(Location); + private readonly router = inject(Router); - ngOnInit() { - const savedError = this.errorService.getError(); + readonly error = signal( + this.errorService.consumeError() ?? { + statusCode: 500, + title: 'Da ist was schiefgelaufen', + message: + 'Ein unerwarteter Fehler ist aufgetreten. Bitte versuchen Sie es später erneut.', + }, + ); + readonly routeError = computed(() => ({ + statusCode: this.routeStatusCode(), + title: this.routeTitle(), + message: this.routeMessage(), + errorDetails: this.routeErrorDetails(), + })); - if (savedError) { - this.statusCode.set(savedError.statusCode); - this.title.set(savedError.title); - this.message.set(savedError.message); - this.errorDetails.set(savedError.errorDetails); - this.errorService.clearError(); // Speicher aufräumen - } else { - this.statusCode.set(this.routeStatusCode()); - this.title.set(this.routeTitle()); - this.message.set(this.routeMessage()); - this.errorDetails.set(this.routeErrorDetails()); - } - } - - toggleDetails() { + toggleDetails(): void { this.isDetailsOpen.update((isOpen) => !isOpen); } - goBack() { - window.history.back(); + goBack(): void { + if (history.length > 1) { + this.location.back(); + return; + } + + void this.router.navigateByUrl('/'); } } From 0dd2a5743d20340bdcfc5475a3635753aee7562e Mon Sep 17 00:00:00 2001 From: genja Date: Tue, 11 Aug 2026 11:46:08 +0200 Subject: [PATCH 109/114] bound the new error propagation to uni trend resolver --- webapp/src/app/resolvers/uni-trend.resolver.ts | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/webapp/src/app/resolvers/uni-trend.resolver.ts b/webapp/src/app/resolvers/uni-trend.resolver.ts index 887f1bae..729eb66f 100644 --- a/webapp/src/app/resolvers/uni-trend.resolver.ts +++ b/webapp/src/app/resolvers/uni-trend.resolver.ts @@ -195,11 +195,9 @@ export const uniTrendResolver: ResolveFn = ( return res; }), catchError((err) => { - errorService.setError({ - statusCode: err?.status || 500, + errorService.report(err, { title: 'Visualisierungs-Fehler', message: 'Trenddaten konnten nicht geladen werden.', - errorDetails: err?.message || String(err), }); return of(null); }), From e6e9628837b309d529753f6d6bf4caa2eb2e1f6f Mon Sep 17 00:00:00 2001 From: Roman Date: Tue, 11 Aug 2026 11:48:18 +0200 Subject: [PATCH 110/114] organization-feature --- service/src/main/inse/auth/model.py | 19 + service/src/main/inse/auth/service.py | 18 +- service/src/main/inse/database.py | 24 + .../inse/organization_management/model.py | 18 + .../inse/organization_management/router.py | 13 + .../inse/organization_management/service.py | 273 +++++- .../organization_management/test_service.py | 181 +++- webapp/src/app/api/.openapi-generator/FILES | 2 + .../src/app/api/api/organization.service.ts | 911 +++++++++++++----- .../api/model/createOrganizationRequest.ts | 11 +- ...ationManagementModelOrganizationProfile.ts | 17 +- .../app/api/model/institutionAssociation.ts | 23 + .../model/institutionAssociationsResponse.ts | 16 + webapp/src/app/api/model/models.ts | 2 + .../api/model/updateOrganizationRequest.ts | 13 +- .../modules/accounts/accounts.component.html | 27 +- .../modules/accounts/accounts.component.scss | 35 + .../institution-removal-dialog.component.ts | 65 ++ .../organization-dialog.component.html | 90 +- .../organization-dialog.component.scss | 96 +- .../organization-dialog.component.ts | 286 +++++- .../organizations.component.html | 51 +- .../organizations.component.scss | 15 +- .../organizations/organizations.component.ts | 78 +- .../organizations-organizations.resolver.ts | 106 +- .../query-param-selector.component.html | 2 +- webapp/src/styles.scss | 5 +- 27 files changed, 2012 insertions(+), 385 deletions(-) create mode 100644 webapp/src/app/api/model/institutionAssociation.ts create mode 100644 webapp/src/app/api/model/institutionAssociationsResponse.ts create mode 100644 webapp/src/app/modules/organizations/organization-dialog/institution-removal-dialog.component.ts diff --git a/service/src/main/inse/auth/model.py b/service/src/main/inse/auth/model.py index d78caf5b..b0b5c346 100644 --- a/service/src/main/inse/auth/model.py +++ b/service/src/main/inse/auth/model.py @@ -88,6 +88,25 @@ class Organization(Durable, table=True): accounts: list["Account"] = Relationship(back_populates="organization") +class OrganizationInstitution(SQLModel, table=True): + __tablename__ = "organization_institution" + __table_args__ = ( + UniqueConstraint( + "organization_id", + "position", + name="uq_organization_institution_position", + ), + ) + + organization_id: uuid.UUID = Field( + foreign_key="organization.id", + primary_key=True, + index=True, + ) + openalex_institution_id: str = Field(primary_key=True, index=True) + position: int = Field(nullable=False) + + class Account(Durable, table=True): @model_validator(mode="before") @classmethod diff --git a/service/src/main/inse/auth/service.py b/service/src/main/inse/auth/service.py index 4898ebef..1b271e67 100644 --- a/service/src/main/inse/auth/service.py +++ b/service/src/main/inse/auth/service.py @@ -22,6 +22,7 @@ from inse.auth.model import ( IdTokenMetadata, LoginResponse, Organization, + OrganizationInstitution, OtkResponse, RefreshTokenMetadata, Secret, @@ -98,9 +99,12 @@ def create_predefined_accounts(session: Session, file_path: str): with open(file_path, "r") as file: data: dict[str, Any] = json.loads(file.read()) for organization_data in data.get("organizations", []): - organization_id = organization_data.get("id") - if organization_id is not None: - organization_id = uuid.UUID(organization_id) + organization_id_value = organization_data.get("id") + organization_id = ( + uuid.UUID(organization_id_value) + if organization_id_value is not None + else uuid.uuid4() + ) organization_name = organization_data["name"] openalex_institution_id = organization_data.get( "openalex_institution_id" @@ -113,6 +117,14 @@ def create_predefined_accounts(session: Session, file_path: str): openalex_institution_id=openalex_institution_id, ) session.add(organization) + if openalex_institution_id: + session.add( + OrganizationInstitution( + organization_id=organization.id, + openalex_institution_id=openalex_institution_id, + position=0, + ) + ) for account_data in data.get("accounts", []): organization_id = uuid.UUID(account_data["organization_id"]) roles = normalize_roles( diff --git a/service/src/main/inse/database.py b/service/src/main/inse/database.py index 4fd5a269..5f4a75c9 100644 --- a/service/src/main/inse/database.py +++ b/service/src/main/inse/database.py @@ -107,6 +107,30 @@ def create_db_and_tables(): ) ) + # Preserve the former single institution as the first manually selected + # institution. + # The legacy column remains synchronized for portal sections that have not yet + # been migrated to organization-wide institution lists. + with engine.begin() as connection: + connection.execute( + text( + """ + INSERT INTO organization_institution ( + organization_id, openalex_institution_id, position + ) + SELECT id, openalex_institution_id, 0 + FROM organization + WHERE openalex_institution_id IS NOT NULL + AND TRIM(openalex_institution_id) != '' + AND NOT EXISTS ( + SELECT 1 + FROM organization_institution oi + WHERE oi.organization_id = organization.id + ) + """ + ) + ) + def get_session(): """Yields a database session for use in FastAPI endpoints. diff --git a/service/src/main/inse/organization_management/model.py b/service/src/main/inse/organization_management/model.py index 8357daa9..e4de2f2e 100644 --- a/service/src/main/inse/organization_management/model.py +++ b/service/src/main/inse/organization_management/model.py @@ -1,4 +1,5 @@ import uuid +from typing import Literal from pydantic import BaseModel, Field @@ -7,6 +8,7 @@ class OrganizationProfile(BaseModel): id: uuid.UUID name: str other_inst_id: str | None = None + selected_openalex_institution_ids: list[str] = Field(default_factory=list) deleted: bool member_count: int @@ -21,9 +23,25 @@ class OrganizationPage(BaseModel): class CreateOrganizationRequest(BaseModel): name: str = Field(min_length=1) other_inst_id: str | None = None + selected_openalex_institution_ids: list[str] | None = None class UpdateOrganizationRequest(BaseModel): name: str | None = Field(default=None, min_length=1) other_inst_id: str | None = None + selected_openalex_institution_ids: list[str] | None = None deleted: bool | None = None + + +class InstitutionAssociation(BaseModel): + id: str + display_name: str + relationship: Literal["child", "related"] + + +class InstitutionAssociationsResponse(BaseModel): + id: str + display_name: str + associated_institutions: list[InstitutionAssociation] = Field( + default_factory=list + ) diff --git a/service/src/main/inse/organization_management/router.py b/service/src/main/inse/organization_management/router.py index 5232ca66..32086e0e 100644 --- a/service/src/main/inse/organization_management/router.py +++ b/service/src/main/inse/organization_management/router.py @@ -11,6 +11,7 @@ from inse.tags import Tags from . import service from .model import ( CreateOrganizationRequest, + InstitutionAssociationsResponse, OrganizationPage, OrganizationProfile, UpdateOrganizationRequest, @@ -19,6 +20,18 @@ from .model import ( router = APIRouter(prefix="/api/organizations", tags=[Tags.ORGANIZATION]) +@router.get( + "/institutions/associations", + operation_id="getOrganizationInstitutionAssociations", + response_model=list[InstitutionAssociationsResponse], +) +async def get_organization_institution_associations( + institution_ids: list[str] = Query(), + access_token: AccessTokenMetadata = auth_service.CurrentUserAccessTokenPayloadDep, +) -> list[InstitutionAssociationsResponse]: + return await service.get_institution_associations(access_token, institution_ids) + + @router.get("", operation_id="getOrganisations", response_model=OrganizationPage) async def get_organizations( page: int = Query(default=0, ge=0), diff --git a/service/src/main/inse/organization_management/service.py b/service/src/main/inse/organization_management/service.py index dcb06c30..072db92a 100644 --- a/service/src/main/inse/organization_management/service.py +++ b/service/src/main/inse/organization_management/service.py @@ -1,18 +1,43 @@ +import logging +import re import uuid from fastapi import HTTPException, status from sqlmodel import Session, func, select -from inse.auth.model import AccessTokenMetadata, Account, Organization, UserRole +from inse.auth.model import ( + AccessTokenMetadata, + Account, + Organization, + OrganizationInstitution, + UserRole, +) +from inse.integrations import elasticsearch +from inse.model import ESIndex from .model import ( CreateOrganizationRequest, + InstitutionAssociation, + InstitutionAssociationsResponse, OrganizationPage, OrganizationProfile, UpdateOrganizationRequest, ) +logger = logging.getLogger(__name__) +OPENALEX_INSTITUTION_ID_PATTERN = re.compile( + r"^(?:https?://openalex\.org/)?(I\d+)/?$", re.IGNORECASE +) +KNOWN_ASSOCIATION_TYPES = { + "parent", + "child", + "related", + "predecessor", + "successor", +} + + def _require_super_admin(access_token: AccessTokenMetadata) -> None: if access_token.effective_role != UserRole.SUPER_ADMIN: raise HTTPException( @@ -31,6 +56,27 @@ def _normalize_name(name: str) -> str: return normalized_name +def _normalize_institution_id(institution_id: str) -> str: + match = OPENALEX_INSTITUTION_ID_PATTERN.fullmatch(institution_id.strip()) + if match is None: + raise HTTPException( + status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, + detail=f"Invalid OpenAlex institution ID: {institution_id}", + ) + return f"I{match.group(1)[1:]}" + + +def _normalize_institution_ids(institution_ids: list[str]) -> list[str]: + normalized: list[str] = [] + seen: set[str] = set() + for institution_id in institution_ids: + clean_id = _normalize_institution_id(institution_id) + if clean_id not in seen: + normalized.append(clean_id) + seen.add(clean_id) + return normalized + + def _ensure_name_available( session: Session, name: str, @@ -79,18 +125,76 @@ def _member_counts( return {organization_id: count for organization_id, count in rows} +def _institution_data( + session: Session, organization_ids: list[uuid.UUID] +) -> dict[uuid.UUID, list[str]]: + ids_by_organization: dict[uuid.UUID, list[str]] = { + organization_id: [] for organization_id in organization_ids + } + if not organization_ids: + return ids_by_organization + + institution_rows = session.exec( + select(OrganizationInstitution) + .where(OrganizationInstitution.organization_id.in_(organization_ids)) + .order_by( + OrganizationInstitution.organization_id, + OrganizationInstitution.position, + ) + ).all() + for row in institution_rows: + ids_by_organization[row.organization_id].append( + row.openalex_institution_id + ) + + return ids_by_organization + + def _to_profile( - organization: Organization, member_count: int + organization: Organization, + member_count: int, + institution_ids: list[str], ) -> OrganizationProfile: + if not institution_ids and organization.openalex_institution_id: + legacy_id = _normalize_institution_id(organization.openalex_institution_id) + institution_ids = [legacy_id] return OrganizationProfile( id=organization.id, name=organization.name, - other_inst_id=organization.openalex_institution_id, + other_inst_id=institution_ids[0] if institution_ids else None, + selected_openalex_institution_ids=institution_ids, deleted=organization.deleted, member_count=member_count, ) +def _replace_organization_institutions( + session: Session, + organization: Organization, + institution_ids: list[str], +) -> None: + normalized_ids = _normalize_institution_ids(institution_ids) + for row in session.exec( + select(OrganizationInstitution).where( + OrganizationInstitution.organization_id == organization.id + ) + ).all(): + session.delete(row) + session.flush() + + for position, institution_id in enumerate(normalized_ids): + session.add( + OrganizationInstitution( + organization_id=organization.id, + openalex_institution_id=institution_id, + position=position, + ) + ) + organization.openalex_institution_id = ( + normalized_ids[0] if normalized_ids else None + ) + + def _deactivate_organization_accounts( session: Session, organization_id: uuid.UUID ) -> None: @@ -106,6 +210,27 @@ def _deactivate_organization_accounts( session.add(account) +def _ensure_not_current_organization( + session: Session, + access_token: AccessTokenMetadata, + organization_id: uuid.UUID, +) -> None: + protected_organization_ids = {access_token.effective_organization_id} + if access_token.real_account_id is not None: + real_account = session.get(Account, access_token.real_account_id) + if real_account is not None: + protected_organization_ids.add(real_account.organization_id) + + if organization_id in protected_organization_ids: + raise HTTPException( + status_code=status.HTTP_409_CONFLICT, + detail=( + "The organization of the real or effective account " + "cannot be deleted." + ), + ) + + def get_organizations( session: Session, access_token: AccessTokenMetadata, @@ -130,10 +255,15 @@ def get_organizations( ).all() organization_ids = [organization.id for organization in organizations] counts = _member_counts(session, organization_ids) + institution_ids = _institution_data(session, organization_ids) return OrganizationPage( items=[ - _to_profile(organization, counts.get(organization.id, 0)) + _to_profile( + organization, + counts.get(organization.id, 0), + institution_ids.get(organization.id, []), + ) for organization in organizations ], total=total, @@ -153,12 +283,25 @@ def create_organization( organization = Organization( name=name, - openalex_institution_id=(payload.other_inst_id or '').strip() or None, ) session.add(organization) + session.flush() + requested_ids = payload.selected_openalex_institution_ids + if requested_ids is None: + requested_ids = [payload.other_inst_id] if payload.other_inst_id else [] + _replace_organization_institutions( + session, + organization, + requested_ids, + ) session.commit() session.refresh(organization) - return _to_profile(organization, 0) + institution_ids = _institution_data(session, [organization.id]) + return _to_profile( + organization, + 0, + institution_ids[organization.id], + ) def update_organization( @@ -174,10 +317,21 @@ def update_organization( name = _normalize_name(payload.name) _ensure_name_available(session, name, organization.id) organization.name = name - if payload.other_inst_id is not None: - organization.openalex_institution_id = payload.other_inst_id.strip() or None + if payload.selected_openalex_institution_ids is not None: + _replace_organization_institutions( + session, + organization, + payload.selected_openalex_institution_ids, + ) + elif payload.other_inst_id is not None: + _replace_organization_institutions( + session, + organization, + [payload.other_inst_id] if payload.other_inst_id.strip() else [], + ) if payload.deleted is not None: if payload.deleted and not organization.deleted: + _ensure_not_current_organization(session, access_token, organization.id) _deactivate_organization_accounts(session, organization.id) organization.deleted = payload.deleted @@ -185,7 +339,107 @@ def update_organization( session.commit() session.refresh(organization) counts = _member_counts(session, [organization.id]) - return _to_profile(organization, counts.get(organization.id, 0)) + institution_ids = _institution_data(session, [organization.id]) + return _to_profile( + organization, + counts.get(organization.id, 0), + institution_ids[organization.id], + ) + + +async def get_institution_associations( + access_token: AccessTokenMetadata, + institution_ids: list[str], +) -> list[InstitutionAssociationsResponse]: + _require_super_admin(access_token) + clean_ids = _normalize_institution_ids(institution_ids) + if not clean_ids: + return [] + + response = await elasticsearch.search( + index=ESIndex.OPENALEX_INSTITUTIONS, + query={ + "terms": { + "id": [ + f"https://openalex.org/{institution_id}" + for institution_id in clean_ids + ] + } + }, + source=["id", "display_name", "associated_institutions"], + size=len(clean_ids), + ) + sources_by_id: dict[str, dict] = {} + for hit in response.get("hits", {}).get("hits", []): + source = hit.get("_source") or {} + raw_id = source.get("id") + if isinstance(raw_id, str): + sources_by_id[_normalize_institution_id(raw_id)] = source + + missing_id = next( + ( + institution_id + for institution_id in clean_ids + if institution_id not in sources_by_id + ), + None, + ) + if missing_id is not None: + raise HTTPException( + status_code=status.HTTP_404_NOT_FOUND, + detail=f"OpenAlex institution {missing_id} not found.", + ) + + results: list[InstitutionAssociationsResponse] = [] + for clean_id in clean_ids: + source = sources_by_id[clean_id] + display_name = source.get("display_name") + if not isinstance(display_name, str) or not display_name.strip(): + raise HTTPException( + status_code=status.HTTP_502_BAD_GATEWAY, + detail=f"OpenAlex institution {clean_id} has no display name.", + ) + + associations_by_id: dict[str, InstitutionAssociation] = {} + for association in source.get("associated_institutions") or []: + if not isinstance(association, dict): + continue + relationship = str(association.get("relationship") or "").lower() + if relationship not in KNOWN_ASSOCIATION_TYPES: + logger.warning( + "Ignoring unknown OpenAlex institution relationship %r for %s", + relationship, + clean_id, + ) + continue + if relationship not in {"child", "related"}: + continue + raw_association_id = association.get("id") + association_name = association.get("display_name") + if not isinstance(raw_association_id, str) or not isinstance( + association_name, str + ): + continue + associated_id = _normalize_institution_id(raw_association_id) + candidate = InstitutionAssociation( + id=associated_id, + display_name=association_name, + relationship=relationship, + ) + existing = associations_by_id.get(associated_id) + if existing is None or ( + existing.relationship == "related" and relationship == "child" + ): + associations_by_id[associated_id] = candidate + + results.append( + InstitutionAssociationsResponse( + id=clean_id, + display_name=display_name, + associated_institutions=list(associations_by_id.values()), + ) + ) + return results def delete_organization( @@ -196,6 +450,7 @@ def delete_organization( _require_super_admin(access_token) organization = _get_organization_or_404(session, organization_id) if not organization.deleted: + _ensure_not_current_organization(session, access_token, organization.id) _deactivate_organization_accounts(session, organization.id) organization.deleted = True session.add(organization) diff --git a/service/src/main/inse/organization_management/test_service.py b/service/src/main/inse/organization_management/test_service.py index a7ce6ff6..cd4ccdef 100644 --- a/service/src/main/inse/organization_management/test_service.py +++ b/service/src/main/inse/organization_management/test_service.py @@ -1,10 +1,16 @@ +import asyncio from types import SimpleNamespace import pytest from fastapi import HTTPException -from sqlmodel import Session, SQLModel, create_engine +from sqlmodel import Session, SQLModel, create_engine, select -from inse.auth.model import Account, Organization, UserRole +from inse.auth.model import ( + Account, + Organization, + OrganizationInstitution, + UserRole, +) from inse.organization_management import service from inse.organization_management.model import ( CreateOrganizationRequest, @@ -22,10 +28,11 @@ def session(): yield database_session -def token(role: UserRole, organization_id): +def token(role: UserRole, organization_id, real_account_id=None): return SimpleNamespace( effective_role=role, effective_organization_id=organization_id, + real_account_id=real_account_id, ) @@ -105,8 +112,115 @@ def test_superadmin_can_create_update_and_soft_delete(session): assert session.get(Organization, created.id).deleted is True +def test_organization_stores_ordered_selected_institution_ids(session): + scope = Organization(name="Scope") + session.add(scope) + session.commit() + + created = service.create_organization( + session, + token(UserRole.SUPER_ADMIN, scope.id), + CreateOrganizationRequest( + name="Institution list", + selected_openalex_institution_ids=[ + "https://openalex.org/I123", + "I456", + "I123", + ], + ), + ) + + assert created.selected_openalex_institution_ids == ["I123", "I456"] + assert created.other_inst_id == "I123" + assert session.get(Organization, created.id).openalex_institution_id == "I123" + rows = session.exec( + select(OrganizationInstitution) + .where(OrganizationInstitution.organization_id == created.id) + .order_by(OrganizationInstitution.position) + ).all() + assert [row.openalex_institution_id for row in rows] == ["I123", "I456"] + + +def test_empty_institution_list_clears_legacy_primary_institution(session): + organization = Organization(name="Organization", openalex_institution_id="I123") + session.add(organization) + session.commit() + + updated = service.update_organization( + session, + token(UserRole.SUPER_ADMIN, organization.id), + organization.id, + UpdateOrganizationRequest(selected_openalex_institution_ids=[]), + ) + + assert updated.selected_openalex_institution_ids == [] + assert updated.other_inst_id is None + assert session.get(Organization, organization.id).openalex_institution_id is None + + +def test_association_expansion_adds_only_child_and_related_with_child_priority( + monkeypatch, +): + async def fake_search(**kwargs): + return { + "hits": { + "hits": [ + { + "_source": { + "id": "https://openalex.org/I100", + "display_name": "Selected institution", + "associated_institutions": [ + { + "id": "https://openalex.org/I200", + "display_name": "Duplicate", + "relationship": "related", + }, + { + "id": "https://openalex.org/I200", + "display_name": "Duplicate", + "relationship": "child", + }, + { + "id": "https://openalex.org/I300", + "display_name": "Related", + "relationship": "related", + }, + { + "id": "https://openalex.org/I400", + "display_name": "Parent", + "relationship": "parent", + }, + { + "id": "https://openalex.org/I500", + "display_name": "Successor", + "relationship": "successor", + }, + ], + }, + } + ], + }, + } + + monkeypatch.setattr(service.elasticsearch, "search", fake_search) + + result = asyncio.run( + service.get_institution_associations( + token(UserRole.SUPER_ADMIN, None), ["https://openalex.org/I100"] + ) + ) + + assert result[0].id == "I100" + assert [ + (association.id, association.relationship) + for association in result[0].associated_institutions + ] == [("I200", "child"), ("I300", "related")] + + def test_deleting_organization_deactivates_all_its_accounts(session): + admin_scope = Organization(name="Admin scope for delete") organization = Organization(name="Organization to delete") + session.add(admin_scope) session.add(organization) session.flush() active_account = Account( @@ -129,7 +243,7 @@ def test_deleting_organization_deactivates_all_its_accounts(session): session.commit() service.delete_organization( - session, token(UserRole.SUPER_ADMIN, organization.id), organization.id + session, token(UserRole.SUPER_ADMIN, admin_scope.id), organization.id ) session.refresh(active_account) @@ -141,7 +255,9 @@ def test_deleting_organization_deactivates_all_its_accounts(session): def test_marking_organization_deleted_deactivates_its_accounts(session): + admin_scope = Organization(name="Admin scope for update") organization = Organization(name="Organization to update") + session.add(admin_scope) session.add(organization) session.flush() account = Account( @@ -155,7 +271,7 @@ def test_marking_organization_deleted_deactivates_its_accounts(session): service.update_organization( session, - token(UserRole.SUPER_ADMIN, organization.id), + token(UserRole.SUPER_ADMIN, admin_scope.id), organization.id, UpdateOrganizationRequest(deleted=True), ) @@ -165,6 +281,61 @@ def test_marking_organization_deleted_deactivates_its_accounts(session): assert account.epoch == 1 +@pytest.mark.parametrize("delete_via_update", [False, True]) +def test_current_organization_cannot_be_deleted(session, delete_via_update): + organization = Organization(name="Current organization") + session.add(organization) + session.commit() + access_token = token(UserRole.SUPER_ADMIN, organization.id) + + with pytest.raises(HTTPException) as error: + if delete_via_update: + service.update_organization( + session, + access_token, + organization.id, + UpdateOrganizationRequest(deleted=True), + ) + else: + service.delete_organization(session, access_token, organization.id) + + assert error.value.status_code == 409 + assert session.get(Organization, organization.id).deleted is False + + +def test_real_account_organization_cannot_be_deleted_while_impersonating(session): + real_organization = Organization(name="Real organization") + effective_organization = Organization(name="Effective organization") + session.add(real_organization) + session.add(effective_organization) + session.flush() + real_account = Account( + email="real-superadmin@example.org", + name="Real superadmin", + password_hash="hash", + organization_id=real_organization.id, + roles=[UserRole.SUPER_ADMIN], + ) + session.add(real_account) + session.commit() + + access_token = token( + UserRole.SUPER_ADMIN, + effective_organization.id, + real_account.id, + ) + with pytest.raises(HTTPException) as error: + service.delete_organization( + session, + access_token, + real_organization.id, + ) + + assert error.value.status_code == 409 + assert session.get(Organization, real_organization.id).deleted is False + assert session.get(Account, real_account.id).activated is True + + @pytest.mark.parametrize("role", [UserRole.ADMIN, UserRole.MANAGER, UserRole.USER]) def test_only_superadmin_can_create_organizations(session, role): organization = Organization(name="Scope") diff --git a/webapp/src/app/api/.openapi-generator/FILES b/webapp/src/app/api/.openapi-generator/FILES index 3c0e087f..d1763419 100644 --- a/webapp/src/app/api/.openapi-generator/FILES +++ b/webapp/src/app/api/.openapi-generator/FILES @@ -169,6 +169,8 @@ model/idTokenMetadata.ts model/inseAccountManagementModelOrganizationProfile.ts model/inseOrganizationManagementModelOrganizationProfile.ts model/institution.ts +model/institutionAssociation.ts +model/institutionAssociationsResponse.ts model/institutionFunderSummary.ts model/institutionGeo.ts model/institutionIds.ts diff --git a/webapp/src/app/api/api/organization.service.ts b/webapp/src/app/api/api/organization.service.ts index 14fb942d..1d3c7319 100644 --- a/webapp/src/app/api/api/organization.service.ts +++ b/webapp/src/app/api/api/organization.service.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,12 +9,18 @@ */ /* tslint:disable:no-unused-variable member-ordering */ -import { Inject, Injectable, Optional } from '@angular/core'; -import { HttpClient, HttpHeaders, HttpParams, - HttpResponse, HttpEvent, HttpParameterCodec, HttpContext - } from '@angular/common/http'; -import { CustomHttpParameterCodec } from '../encoder'; -import { Observable } from 'rxjs'; +import { Inject, Injectable, Optional } from '@angular/core'; +import { + HttpClient, + HttpHeaders, + HttpParams, + HttpResponse, + HttpEvent, + HttpParameterCodec, + HttpContext, +} from '@angular/common/http'; +import { CustomHttpParameterCodec } from '../encoder'; +import { Observable } from 'rxjs'; // @ts-ignore import { CreateOrganizationRequest } from '../model/createOrganizationRequest'; @@ -23,292 +29,679 @@ import { HTTPValidationError } from '../model/hTTPValidationError'; // @ts-ignore import { InseOrganizationManagementModelOrganizationProfile } from '../model/inseOrganizationManagementModelOrganizationProfile'; // @ts-ignore +import { InstitutionAssociationsResponse } from '../model/institutionAssociationsResponse'; +// @ts-ignore import { OrganizationPage } from '../model/organizationPage'; // @ts-ignore import { UpdateOrganizationRequest } from '../model/updateOrganizationRequest'; // @ts-ignore -import { BASE_PATH, COLLECTION_FORMATS } from '../variables'; -import { Configuration } from '../configuration'; +import { BASE_PATH, COLLECTION_FORMATS } from '../variables'; +import { Configuration } from '../configuration'; import { BaseService } from '../api.base.service'; - - @Injectable({ - providedIn: 'root' + providedIn: 'root', }) export class OrganizationService extends BaseService { + constructor( + protected httpClient: HttpClient, + @Optional() @Inject(BASE_PATH) basePath: string | string[], + @Optional() configuration?: Configuration, + ) { + super(basePath, configuration); + } - constructor(protected httpClient: HttpClient, @Optional() @Inject(BASE_PATH) basePath: string|string[], @Optional() configuration?: Configuration) { - super(basePath, configuration); + /** + * Create Organization + * @endpoint post /api/organizations + * @param createOrganizationRequest + * @param secureFgpAcc + * @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 createOrganisation( + createOrganizationRequest: CreateOrganizationRequest, + secureFgpAcc?: string, + observe?: 'body', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable; + public createOrganisation( + createOrganizationRequest: CreateOrganizationRequest, + secureFgpAcc?: string, + observe?: 'response', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable< + HttpResponse + >; + public createOrganisation( + createOrganizationRequest: CreateOrganizationRequest, + secureFgpAcc?: string, + observe?: 'events', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public createOrganisation( + createOrganizationRequest: CreateOrganizationRequest, + secureFgpAcc?: string, + observe: any = 'body', + reportProgress: boolean = false, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable { + if ( + createOrganizationRequest === null || + createOrganizationRequest === undefined + ) { + throw new Error( + 'Required parameter createOrganizationRequest was null or undefined when calling createOrganisation.', + ); } - /** - * Create Organization - * @endpoint post /api/organizations - * @param createOrganizationRequest - * @param secureFgpAcc - * @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 createOrganisation(createOrganizationRequest: CreateOrganizationRequest, secureFgpAcc?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; - public createOrganisation(createOrganizationRequest: CreateOrganizationRequest, secureFgpAcc?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public createOrganisation(createOrganizationRequest: CreateOrganizationRequest, secureFgpAcc?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public createOrganisation(createOrganizationRequest: CreateOrganizationRequest, secureFgpAcc?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { - if (createOrganizationRequest === null || createOrganizationRequest === undefined) { - throw new Error('Required parameter createOrganizationRequest was null or undefined when calling createOrganisation.'); - } + let localVarHeaders = this.defaultHeaders; - let localVarHeaders = this.defaultHeaders; + // authentication (HTTPBearer) required + localVarHeaders = this.configuration.addCredentialToHeaders( + 'HTTPBearer', + 'Authorization', + localVarHeaders, + 'Bearer ', + ); - // authentication (HTTPBearer) required - localVarHeaders = this.configuration.addCredentialToHeaders('HTTPBearer', 'Authorization', localVarHeaders, 'Bearer '); + const localVarHttpHeaderAcceptSelected: string | undefined = + options?.httpHeaderAccept ?? + this.configuration.selectHeaderAccept(['application/json']); + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set( + 'Accept', + localVarHttpHeaderAcceptSelected, + ); + } - 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 localVarHttpContext: HttpContext = options?.context ?? new HttpContext(); + const localVarTransferCache: boolean = options?.transferCache ?? true; - const localVarTransferCache: boolean = options?.transferCache ?? true; + // to determine the Content-Type header + const consumes: string[] = ['application/json']; + const httpContentTypeSelected: string | undefined = + this.configuration.selectHeaderContentType(consumes); + if (httpContentTypeSelected !== undefined) { + localVarHeaders = localVarHeaders.set( + 'Content-Type', + httpContentTypeSelected, + ); + } + 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'; + } + } - // to determine the Content-Type header - const consumes: string[] = [ - 'application/json' - ]; - const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes); - if (httpContentTypeSelected !== undefined) { - localVarHeaders = localVarHeaders.set('Content-Type', httpContentTypeSelected); - } + let localVarPath = `/api/organizations`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request( + 'post', + `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + body: createOrganizationRequest, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined + ? { transferCache: localVarTransferCache } + : {}), + reportProgress: reportProgress, + }, + ); + } - 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'; - } - } + /** + * Delete Organization + * @endpoint delete /api/organizations/{organization_id} + * @param organizationId + * @param secureFgpAcc + * @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 deleteOrganisation( + organizationId: string, + secureFgpAcc?: string, + observe?: 'body', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable; + public deleteOrganisation( + organizationId: string, + secureFgpAcc?: string, + observe?: 'response', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public deleteOrganisation( + organizationId: string, + secureFgpAcc?: string, + observe?: 'events', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public deleteOrganisation( + organizationId: string, + secureFgpAcc?: string, + observe: any = 'body', + reportProgress: boolean = false, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable { + if (organizationId === null || organizationId === undefined) { + throw new Error( + 'Required parameter organizationId was null or undefined when calling deleteOrganisation.', + ); + } - let localVarPath = `/api/organizations`; - const { basePath, withCredentials } = this.configuration; - return this.httpClient.request('post', `${basePath}${localVarPath}`, - { - context: localVarHttpContext, - body: createOrganizationRequest, - responseType: responseType_, - ...(withCredentials ? { withCredentials } : {}), - headers: localVarHeaders, - observe: observe, - ...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}), - reportProgress: reportProgress - } + let localVarHeaders = this.defaultHeaders; + + // authentication (HTTPBearer) required + localVarHeaders = this.configuration.addCredentialToHeaders( + 'HTTPBearer', + 'Authorization', + localVarHeaders, + 'Bearer ', + ); + + 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/organizations/${this.configuration.encodeParam({ name: 'organizationId', value: organizationId, in: 'path', style: 'simple', explode: false, dataType: 'string', dataFormat: 'uuid' })}`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request( + 'delete', + `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined + ? { transferCache: localVarTransferCache } + : {}), + reportProgress: reportProgress, + }, + ); + } + + /** + * Get Organizations + * @endpoint get /api/organizations + * @param page + * @param pageSize + * @param offset + * @param secureFgpAcc + * @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 getOrganisations( + page?: number, + pageSize?: number, + offset?: number, + secureFgpAcc?: string, + observe?: 'body', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable; + public getOrganisations( + page?: number, + pageSize?: number, + offset?: number, + secureFgpAcc?: string, + observe?: 'response', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public getOrganisations( + page?: number, + pageSize?: number, + offset?: number, + secureFgpAcc?: string, + observe?: 'events', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public getOrganisations( + page?: number, + pageSize?: number, + offset?: number, + secureFgpAcc?: string, + 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, + page, + 'page', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + pageSize, + 'page_size', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + offset, + 'offset', + ); + + let localVarHeaders = this.defaultHeaders; + + // authentication (HTTPBearer) required + localVarHeaders = this.configuration.addCredentialToHeaders( + 'HTTPBearer', + 'Authorization', + localVarHeaders, + 'Bearer ', + ); + + 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/organizations`; + 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 Organization Institution Associations + * @endpoint get /api/organizations/institutions/associations + * @param institutionIds + * @param secureFgpAcc + * @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 getOrganizationInstitutionAssociations( + institutionIds: Array, + secureFgpAcc?: string, + observe?: 'body', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public getOrganizationInstitutionAssociations( + institutionIds: Array, + secureFgpAcc?: string, + observe?: 'response', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>>; + public getOrganizationInstitutionAssociations( + institutionIds: Array, + secureFgpAcc?: string, + observe?: 'events', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>>; + public getOrganizationInstitutionAssociations( + institutionIds: Array, + secureFgpAcc?: string, + observe: any = 'body', + reportProgress: boolean = false, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable { + if (institutionIds === null || institutionIds === undefined) { + throw new Error( + 'Required parameter institutionIds was null or undefined when calling getOrganizationInstitutionAssociations.', + ); + } + + let localVarQueryParameters = new HttpParams({ encoder: this.encoder }); + if (institutionIds) { + institutionIds.forEach((element) => { + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + element, + 'institution_ids', ); + }); } - /** - * Delete Organization - * @endpoint delete /api/organizations/{organization_id} - * @param organizationId - * @param secureFgpAcc - * @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 deleteOrganisation(organizationId: string, secureFgpAcc?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; - public deleteOrganisation(organizationId: string, secureFgpAcc?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public deleteOrganisation(organizationId: string, secureFgpAcc?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public deleteOrganisation(organizationId: string, secureFgpAcc?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { - if (organizationId === null || organizationId === undefined) { - throw new Error('Required parameter organizationId was null or undefined when calling deleteOrganisation.'); - } + let localVarHeaders = this.defaultHeaders; - let localVarHeaders = this.defaultHeaders; + // authentication (HTTPBearer) required + localVarHeaders = this.configuration.addCredentialToHeaders( + 'HTTPBearer', + 'Authorization', + localVarHeaders, + 'Bearer ', + ); - // authentication (HTTPBearer) required - localVarHeaders = this.configuration.addCredentialToHeaders('HTTPBearer', 'Authorization', localVarHeaders, 'Bearer '); - - 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/organizations/${this.configuration.encodeParam({name: "organizationId", value: organizationId, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: "uuid"})}`; - const { basePath, withCredentials } = this.configuration; - return this.httpClient.request('delete', `${basePath}${localVarPath}`, - { - context: localVarHttpContext, - responseType: responseType_, - ...(withCredentials ? { withCredentials } : {}), - headers: localVarHeaders, - observe: observe, - ...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}), - reportProgress: reportProgress - } - ); + const localVarHttpHeaderAcceptSelected: string | undefined = + options?.httpHeaderAccept ?? + this.configuration.selectHeaderAccept(['application/json']); + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set( + 'Accept', + localVarHttpHeaderAcceptSelected, + ); } - /** - * Get Organizations - * @endpoint get /api/organizations - * @param page - * @param pageSize - * @param offset - * @param secureFgpAcc - * @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 getOrganisations(page?: number, pageSize?: number, offset?: number, secureFgpAcc?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; - public getOrganisations(page?: number, pageSize?: number, offset?: number, secureFgpAcc?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public getOrganisations(page?: number, pageSize?: number, offset?: number, secureFgpAcc?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public getOrganisations(page?: number, pageSize?: number, offset?: number, secureFgpAcc?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + const localVarHttpContext: HttpContext = + options?.context ?? new HttpContext(); - let localVarQueryParameters = new HttpParams({encoder: this.encoder}); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - page, 'page'); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - pageSize, 'page_size'); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - offset, 'offset'); + const localVarTransferCache: boolean = options?.transferCache ?? true; - let localVarHeaders = this.defaultHeaders; - - // authentication (HTTPBearer) required - localVarHeaders = this.configuration.addCredentialToHeaders('HTTPBearer', 'Authorization', localVarHeaders, 'Bearer '); - - 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/organizations`; - 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 - } - ); + 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'; + } } - /** - * Update Organization - * @endpoint put /api/organizations/{organization_id} - * @param organizationId - * @param updateOrganizationRequest - * @param secureFgpAcc - * @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 updateOrganisation(organizationId: string, updateOrganizationRequest: UpdateOrganizationRequest, secureFgpAcc?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; - public updateOrganisation(organizationId: string, updateOrganizationRequest: UpdateOrganizationRequest, secureFgpAcc?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public updateOrganisation(organizationId: string, updateOrganizationRequest: UpdateOrganizationRequest, secureFgpAcc?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public updateOrganisation(organizationId: string, updateOrganizationRequest: UpdateOrganizationRequest, secureFgpAcc?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { - if (organizationId === null || organizationId === undefined) { - throw new Error('Required parameter organizationId was null or undefined when calling updateOrganisation.'); - } - if (updateOrganizationRequest === null || updateOrganizationRequest === undefined) { - throw new Error('Required parameter updateOrganizationRequest was null or undefined when calling updateOrganisation.'); - } + let localVarPath = `/api/organizations/institutions/associations`; + 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, + }, + ); + } - let localVarHeaders = this.defaultHeaders; - - // authentication (HTTPBearer) required - localVarHeaders = this.configuration.addCredentialToHeaders('HTTPBearer', 'Authorization', localVarHeaders, 'Bearer '); - - 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; - - - // to determine the Content-Type header - const consumes: string[] = [ - 'application/json' - ]; - const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes); - if (httpContentTypeSelected !== undefined) { - localVarHeaders = localVarHeaders.set('Content-Type', httpContentTypeSelected); - } - - 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/organizations/${this.configuration.encodeParam({name: "organizationId", value: organizationId, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: "uuid"})}`; - const { basePath, withCredentials } = this.configuration; - return this.httpClient.request('put', `${basePath}${localVarPath}`, - { - context: localVarHttpContext, - body: updateOrganizationRequest, - responseType: responseType_, - ...(withCredentials ? { withCredentials } : {}), - headers: localVarHeaders, - observe: observe, - ...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}), - reportProgress: reportProgress - } - ); + /** + * Update Organization + * @endpoint put /api/organizations/{organization_id} + * @param organizationId + * @param updateOrganizationRequest + * @param secureFgpAcc + * @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 updateOrganisation( + organizationId: string, + updateOrganizationRequest: UpdateOrganizationRequest, + secureFgpAcc?: string, + observe?: 'body', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable; + public updateOrganisation( + organizationId: string, + updateOrganizationRequest: UpdateOrganizationRequest, + secureFgpAcc?: string, + observe?: 'response', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable< + HttpResponse + >; + public updateOrganisation( + organizationId: string, + updateOrganizationRequest: UpdateOrganizationRequest, + secureFgpAcc?: string, + observe?: 'events', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public updateOrganisation( + organizationId: string, + updateOrganizationRequest: UpdateOrganizationRequest, + secureFgpAcc?: string, + observe: any = 'body', + reportProgress: boolean = false, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable { + if (organizationId === null || organizationId === undefined) { + throw new Error( + 'Required parameter organizationId was null or undefined when calling updateOrganisation.', + ); + } + if ( + updateOrganizationRequest === null || + updateOrganizationRequest === undefined + ) { + throw new Error( + 'Required parameter updateOrganizationRequest was null or undefined when calling updateOrganisation.', + ); } + let localVarHeaders = this.defaultHeaders; + + // authentication (HTTPBearer) required + localVarHeaders = this.configuration.addCredentialToHeaders( + 'HTTPBearer', + 'Authorization', + localVarHeaders, + 'Bearer ', + ); + + 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; + + // to determine the Content-Type header + const consumes: string[] = ['application/json']; + const httpContentTypeSelected: string | undefined = + this.configuration.selectHeaderContentType(consumes); + if (httpContentTypeSelected !== undefined) { + localVarHeaders = localVarHeaders.set( + 'Content-Type', + httpContentTypeSelected, + ); + } + + 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/organizations/${this.configuration.encodeParam({ name: 'organizationId', value: organizationId, in: 'path', style: 'simple', explode: false, dataType: 'string', dataFormat: 'uuid' })}`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request( + 'put', + `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + body: updateOrganizationRequest, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined + ? { transferCache: localVarTransferCache } + : {}), + reportProgress: reportProgress, + }, + ); + } } diff --git a/webapp/src/app/api/model/createOrganizationRequest.ts b/webapp/src/app/api/model/createOrganizationRequest.ts index fffb5457..d59b0c3f 100644 --- a/webapp/src/app/api/model/createOrganizationRequest.ts +++ b/webapp/src/app/api/model/createOrganizationRequest.ts @@ -1,16 +1,15 @@ /** * 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 CreateOrganizationRequest { - name: string; - other_inst_id?: string | null; +export interface CreateOrganizationRequest { + name: string; + other_inst_id?: string | null; + selected_openalex_institution_ids?: Array | null; } - diff --git a/webapp/src/app/api/model/inseOrganizationManagementModelOrganizationProfile.ts b/webapp/src/app/api/model/inseOrganizationManagementModelOrganizationProfile.ts index 404df0f9..2b6e1e7c 100644 --- a/webapp/src/app/api/model/inseOrganizationManagementModelOrganizationProfile.ts +++ b/webapp/src/app/api/model/inseOrganizationManagementModelOrganizationProfile.ts @@ -1,19 +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 InseOrganizationManagementModelOrganizationProfile { - id: string; - name: string; - other_inst_id?: string | null; - deleted: boolean; - member_count: number; +export interface InseOrganizationManagementModelOrganizationProfile { + id: string; + name: string; + other_inst_id?: string | null; + selected_openalex_institution_ids?: Array; + deleted: boolean; + member_count: number; } - diff --git a/webapp/src/app/api/model/institutionAssociation.ts b/webapp/src/app/api/model/institutionAssociation.ts new file mode 100644 index 00000000..11b0b37e --- /dev/null +++ b/webapp/src/app/api/model/institutionAssociation.ts @@ -0,0 +1,23 @@ +/** + * 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 InstitutionAssociation { + id: string; + display_name: string; + relationship: InstitutionAssociation.RelationshipEnum; +} +export namespace InstitutionAssociation { + export const RelationshipEnum = { + Child: 'child', + Related: 'related', + } as const; + export type RelationshipEnum = + (typeof RelationshipEnum)[keyof typeof RelationshipEnum]; +} diff --git a/webapp/src/app/api/model/institutionAssociationsResponse.ts b/webapp/src/app/api/model/institutionAssociationsResponse.ts new file mode 100644 index 00000000..6bcd3c56 --- /dev/null +++ b/webapp/src/app/api/model/institutionAssociationsResponse.ts @@ -0,0 +1,16 @@ +/** + * 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 { InstitutionAssociation } from './institutionAssociation'; + +export interface InstitutionAssociationsResponse { + id: string; + display_name: string; + associated_institutions?: Array; +} diff --git a/webapp/src/app/api/model/models.ts b/webapp/src/app/api/model/models.ts index afed834d..3c72f9c1 100644 --- a/webapp/src/app/api/model/models.ts +++ b/webapp/src/app/api/model/models.ts @@ -134,6 +134,8 @@ export * from './idTokenMetadata'; export * from './inseAccountManagementModelOrganizationProfile'; export * from './inseOrganizationManagementModelOrganizationProfile'; export * from './institution'; +export * from './institutionAssociation'; +export * from './institutionAssociationsResponse'; export * from './institutionFunderSummary'; export * from './institutionGeo'; export * from './institutionIds'; diff --git a/webapp/src/app/api/model/updateOrganizationRequest.ts b/webapp/src/app/api/model/updateOrganizationRequest.ts index e12063b6..eede4ba0 100644 --- a/webapp/src/app/api/model/updateOrganizationRequest.ts +++ b/webapp/src/app/api/model/updateOrganizationRequest.ts @@ -1,17 +1,16 @@ /** * 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 UpdateOrganizationRequest { - name?: string | null; - other_inst_id?: string | null; - deleted?: boolean | null; +export interface UpdateOrganizationRequest { + name?: string | null; + other_inst_id?: string | null; + selected_openalex_institution_ids?: Array | null; + deleted?: boolean | null; } - diff --git a/webapp/src/app/modules/accounts/accounts.component.html b/webapp/src/app/modules/accounts/accounts.component.html index 8c88c468..fbab8c8f 100644 --- a/webapp/src/app/modules/accounts/accounts.component.html +++ b/webapp/src/app/modules/accounts/accounts.component.html @@ -10,8 +10,22 @@ }}

    + + +
    FördererPublikationenErstautorMitautorLetztautor + Förderer + @if (sortColumn === 'name') { + {{ + sortDirection === 'asc' ? 'arrow_upward' : 'arrow_downward' + }} + } + + Publikationen + @if (sortColumn === 'publications') { + {{ + sortDirection === 'asc' ? 'arrow_upward' : 'arrow_downward' + }} + } + + Erstautor + @if (sortColumn === 'first') { + {{ + sortDirection === 'asc' ? 'arrow_upward' : 'arrow_downward' + }} + } + + Mitautor + @if (sortColumn === 'middle') { + {{ + sortDirection === 'asc' ? 'arrow_upward' : 'arrow_downward' + }} + } + + Letztautor + @if (sortColumn === 'last') { + {{ + sortDirection === 'asc' ? 'arrow_upward' : 'arrow_downward' + }} + } +
    PatentQuelleJahr + Quelle + @if (sortColumn === 'source') { + {{ + sortDirection === 'asc' ? 'arrow_upward' : 'arrow_downward' + }} + } + + Jahr + @if (sortColumn === 'year') { + {{ + sortDirection === 'asc' ? 'arrow_upward' : 'arrow_downward' + }} + } + Erfinder Anmelder
    {{ patent.publication_year ?? '-' }} - {{ getInventorsLabel(patent) }} + + @if (patent.publication_year) { + {{ + patent.publication_year + }} + } @else { + - + } - {{ getAssigneesLabel(patent) }} + + @if (patent.inventors && patent.inventors.length) { +
    + @for ( + inventor of patent.inventors.slice(0, 2); + track inventor + ) { + + person + {{ inventor }} + + } + @if (patent.inventors.length > 2) { + + + person + {{ patent.inventors[2] }} + + @if (patent.inventors.length > 3) { + +{{ patent.inventors.length - 3 }} + } + + } +
    + } @else { + - + } +
    + @if (patent.assignees && patent.assignees.length) { +
    + @for ( + assignee of patent.assignees.slice(0, 2); + track assignee + ) { + + {{ + isAssigneeLikelyPerson(assignee, patent) + ? 'person' + : 'apartment' + }} + {{ assignee }} + + } + @if (patent.assignees.length > 2) { + + + {{ + isAssigneeLikelyPerson( + patent.assignees[2], + patent + ) + ? 'person' + : 'apartment' + }} + {{ patent.assignees[2] }} + + @if (patent.assignees.length > 3) { + +{{ patent.assignees.length - 3 }} + } + + } +
    + } @else { + - + }
    - - - - - - - - - - - - - @for ( - patent of getPagedPatents(); - track trackPatent($index, patent) - ) { - - - - - - - - - - } - -
    Patent - Quelle - @if (sortColumn === 'source') { - {{ - sortDirection === 'asc' ? 'arrow_upward' : 'arrow_downward' - }} - } - - Jahr - @if (sortColumn === 'year') { - {{ - sortDirection === 'asc' ? 'arrow_upward' : 'arrow_downward' - }} - } - ErfinderApplicant/Assignee - Match-Typ - @if (sortColumn === 'matchType') { - {{ - sortDirection === 'asc' ? 'arrow_upward' : 'arrow_downward' - }} - } - Personen
    - {{ patent.title ?? patent.patent_id }} - - - {{ patent.source }} - - - @if (patent.publication_year) { - {{ - patent.publication_year - }} - } @else { - - - } - - @if (patent.inventors && patent.inventors.length) { -
    - @for ( - inventor of patent.inventors.slice(0, 2); - track inventor - ) { - - person - {{ inventor }} - - } - @if (patent.inventors.length > 2) { - - - person - {{ patent.inventors[2] }} - - @if (patent.inventors.length > 3) { - +{{ patent.inventors.length - 3 }} - } - - } -
    - } @else { - - - } -
    - @if (patent.assignees && patent.assignees.length) { -
    - @for ( - assignee of patent.assignees.slice(0, 2); - track assignee - ) { - - {{ - isAssigneeLikelyPerson(assignee, patent) - ? 'person' - : 'apartment' - }} - {{ assignee }} - - } - @if (patent.assignees.length > 2) { - - - {{ - isAssigneeLikelyPerson( - patent.assignees[2], - patent - ) - ? 'person' - : 'apartment' - }} - {{ patent.assignees[2] }} - - @if (patent.assignees.length > 3) { - +{{ patent.assignees.length - 3 }} - } - - } -
    - } @else { - - - } -
    - - {{ getMatchTypeLabel(patent) }} - - -
    - @if ( - patent.matched_authors && patent.matched_authors.length - ) { - @for ( - author of patent.matched_authors.slice(0, 2); - track author.openalex_author_id - ) { - - {{ author.author_name }} - - } - } @else { - - - } -
    -
    + { switch (this.sortColumn) { - case 'year': { + case 'publication_year': { const yearA = a.publication_date ?? String(a.publication_year ?? ''); const yearB = b.publication_date ?? String(b.publication_year ?? ''); return direction * yearA.localeCompare(yearB); } case 'source': return direction * a.source.localeCompare(b.source); - case 'matchType': + case 'match_type': return direction * a.match_type.localeCompare(b.match_type); default: return ( @@ -239,9 +252,9 @@ export class InstitutionPatentsComponent implements OnInit { private isValidSortColumn(value: string | null): value is SortColumn { return ( value === 'title' || - value === 'year' || + value === 'publication_year' || value === 'source' || - value === 'matchType' + value === 'match_type' ); } @@ -288,15 +301,6 @@ export class InstitutionPatentsComponent implements OnInit { return this.patents.filter((p) => p.match_type === 'both').length; } - trackPatent(_index: number, patent: OrgPatentEntry): string { - return [ - patent.source, - patent.patent_id, - patent.publication_date ?? '', - patent.kind ?? patent.application_type ?? '', - ].join('|'); - } - getAbstractPreview(abstract: string | null | undefined): string | null { if (!abstract?.trim()) { return null; @@ -324,50 +328,4 @@ export class InstitutionPatentsComponent implements OnInit { return patent.match_type; } } - - private static readonly ORG_SUFFIX_PATTERN = - /\b(Inc|Ltd|LLC|LLP|GmbH|Corp(oration)?|Co|KG|AG|SE|S\.?A\.?|N\.?V\.?|B\.?V\.?|PLC|Universit(y|ät|é)|Institut(e)?|Foundation|Laborator(y|ies)|Labs?|Group|Holdings?|Company|Gesellschaft)\b\.?/i; - private static readonly PERSON_SUFFIX_PATTERN = - /\b(Dr|Prof|PhD|Ph\.D|M\.D|Jr|Sr)\b\.?/i; - - private normalizeNameForComparison(name: string): string { - return name - .normalize('NFD') - .replace(/[̀-ͯ]/g, '') - .replace(/[.,]/g, '') - .toUpperCase() - .split(/\s+/) - .filter(Boolean) - .sort() - .join(' '); - } - - isAssigneeLikelyPerson(assignee: string, patent: OrgPatentEntry): boolean { - if (InstitutionPatentsComponent.ORG_SUFFIX_PATTERN.test(assignee)) { - return false; - } - - const normalizedAssignee = this.normalizeNameForComparison( - assignee.replace(InstitutionPatentsComponent.PERSON_SUFFIX_PATTERN, ''), - ); - const matchesInventor = (patent.inventors ?? []).some( - (inventor) => - this.normalizeNameForComparison(inventor) === normalizedAssignee, - ); - if (matchesInventor) { - return true; - } - - return InstitutionPatentsComponent.PERSON_SUFFIX_PATTERN.test(assignee); - } - - getMatchedAuthorsPreview(patent: OrgPatentEntry): string { - if (!patent.matched_authors?.length) { - return '-'; - } - return patent.matched_authors - .slice(0, 2) - .map((author) => author.author_name) - .join(', '); - } } diff --git a/webapp/src/app/modules/keywords-search/keywords-patents/keywords-patents.component.html b/webapp/src/app/modules/keywords-search/keywords-patents/keywords-patents.component.html index 838a42ad..3bce037a 100644 --- a/webapp/src/app/modules/keywords-search/keywords-patents/keywords-patents.component.html +++ b/webapp/src/app/modules/keywords-search/keywords-patents/keywords-patents.component.html @@ -34,147 +34,18 @@ [value]="sortColumn()" (selectionChange)="setSort($event.value)"> Sortieren nach - Jahr + Jahr Titel Quelle - - - - - - - - - - - - @for (item of getPagedMatches(); track trackMatch($index, item)) { - - - - - - - - } - -
    Patent - Quelle - @if (sortColumn() === 'source') { - {{ - sortDirection() === 'asc' - ? 'arrow_upward' - : 'arrow_downward' - }} - } - - Jahr - @if (sortColumn() === 'year') { - {{ - sortDirection() === 'asc' - ? 'arrow_upward' - : 'arrow_downward' - }} - } - ErfinderAnmelder
    - {{ item.patent.title ?? item.patent.patent_id }} - - - {{ item.patent.source }} - - - @if (item.patent.publication_year) { - {{ - item.patent.publication_year - }} - } @else { - - - } - - @if (item.patent.inventors && item.patent.inventors.length) { -
    - @for ( - inventor of item.patent.inventors.slice(0, 2); - track inventor - ) { - - person - {{ inventor }} - - } - @if (item.patent.inventors.length > 2) { - - - person - {{ item.patent.inventors[2] }} - - @if (item.patent.inventors.length > 3) { - +{{ item.patent.inventors.length - 3 }} - } - - } -
    - } @else { - - - } -
    - @if (item.patent.assignees && item.patent.assignees.length) { -
    - @for ( - assignee of item.patent.assignees.slice(0, 2); - track assignee - ) { - - {{ - isAssigneeLikelyPerson(assignee, item.patent) - ? 'person' - : 'apartment' - }} - {{ assignee }} - - } - @if (item.patent.assignees.length > 2) { - - - {{ - isAssigneeLikelyPerson( - item.patent.assignees[2], - item.patent - ) - ? 'person' - : 'apartment' - }} - {{ item.patent.assignees[2] }} - - @if (item.patent.assignees.length > 3) { - +{{ item.patent.assignees.length - 3 }} - } - - } -
    - } @else { - - - } -
    + (); activeFilter = signal('all'); - sortColumn = signal('year'); + sortColumn = signal('publication_year'); sortDirection = signal('desc'); selectedMatch = signal(null); @@ -68,6 +75,8 @@ export class KeywordsPatentsComponent { return this.sortMatches(items); }); + readonly selectedPatent = computed(() => this.selectedMatch()?.patent ?? null); + emptyMessage(): string { switch (this.mappingStatus()) { case 'search_error': @@ -82,57 +91,42 @@ export class KeywordsPatentsComponent { return this.filteredMatches().slice(start, start + this.pageSize()); } + getPagedPatents(): PatentEntry[] { + return this.getPagedMatches().map((item) => item.patent); + } + setFilter(filter: SourceFilter): void { this.activeFilter.set(filter); this.selectedMatch.set(null); this.resetPage(); } + onSortChange(sort: Sort): void { + if (!sort.direction || !isValidSortColumn(sort.active)) { + return; + } + this.sortColumn.set(sort.active); + this.sortDirection.set(sort.direction); + this.selectedMatch.set(null); + this.resetPage(); + } + setSort(column: SortColumn): void { if (this.sortColumn() === column) { this.sortDirection.set(this.sortDirection() === 'asc' ? 'desc' : 'asc'); } else { this.sortColumn.set(column); - this.sortDirection.set(column === 'year' ? 'desc' : 'asc'); + this.sortDirection.set(column === 'publication_year' ? 'desc' : 'asc'); } this.selectedMatch.set(null); this.resetPage(); } - isAssigneeLikelyPerson(assignee: string, patent: PatentEntry): boolean { - if (KeywordsPatentsComponent.ORG_SUFFIX_PATTERN.test(assignee)) { - return false; + selectPatentFromTable(patent: PatentEntry): void { + const match = this.matches().find((item) => item.patent === patent); + if (match) { + this.selectMatch(match); } - - const normalizedAssignee = this.normalizeNameForComparison( - assignee.replace(KeywordsPatentsComponent.PERSON_SUFFIX_PATTERN, ''), - ); - const matchesInventor = (patent.inventors ?? []).some( - (inventor) => - this.normalizeNameForComparison(inventor) === normalizedAssignee, - ); - if (matchesInventor) { - return true; - } - - return KeywordsPatentsComponent.PERSON_SUFFIX_PATTERN.test(assignee); - } - - private static readonly ORG_SUFFIX_PATTERN = - /\b(Inc|Ltd|LLC|LLP|GmbH|Corp(oration)?|Co|KG|AG|SE|S\.?A\.?|N\.?V\.?|B\.?V\.?|PLC|Universit(y|ät|é)|Institut(e)?|Foundation|Laborator(y|ies)|Labs?|Group|Holdings?|Company|Gesellschaft)\b\.?/i; - private static readonly PERSON_SUFFIX_PATTERN = - /\b(Dr|Prof|PhD|Ph\.D|M\.D|Jr|Sr)\b\.?/i; - - private normalizeNameForComparison(name: string): string { - return name - .normalize('NFD') - .replace(/[̀-ͯ]/g, '') - .replace(/[.,]/g, '') - .toUpperCase() - .split(/\s+/) - .filter(Boolean) - .sort() - .join(' '); } onPatentPageChange(_event: PageEvent): void { @@ -186,23 +180,12 @@ export class KeywordsPatentsComponent { return `${text.slice(0, 160).trimEnd()}…`; } - trackMatch(_index: number, item: KeywordPatentMatch): string { - const patent = item.patent; - return [ - patent.source, - patent.patent_id, - patent.publication_date ?? '', - patent.kind ?? patent.application_type ?? '', - item.match_score, - ].join('|'); - } - private sortMatches(items: KeywordPatentMatch[]): KeywordPatentMatch[] { const column = this.sortColumn(); const direction = this.sortDirection() === 'asc' ? 1 : -1; return [...items].sort((a, b) => { switch (column) { - case 'year': { + case 'publication_year': { const yearA = a.patent.publication_date ?? String(a.patent.publication_year ?? ''); diff --git a/webapp/src/app/modules/patent-detail/patent-detail.utils.ts b/webapp/src/app/modules/patent-detail/patent-detail.utils.ts index bc74fecd..11757964 100644 --- a/webapp/src/app/modules/patent-detail/patent-detail.utils.ts +++ b/webapp/src/app/modules/patent-detail/patent-detail.utils.ts @@ -122,6 +122,52 @@ export function getDescriptionPreview(text: string | null): string { return `${text.slice(0, DESCRIPTION_PREVIEW_LENGTH).trimEnd()}…`; } +const ORG_SUFFIX_PATTERN = + /\b(Inc|Ltd|LLC|LLP|GmbH|Corp(oration)?|Co|KG|AG|SE|S\.?A\.?|N\.?V\.?|B\.?V\.?|PLC|Universit(y|ät|é)|Institut(e)?|Foundation|Laborator(y|ies)|Labs?|Group|Holdings?|Company|Gesellschaft)\b\.?/i; +const PERSON_SUFFIX_PATTERN = /\b(Dr|Prof|PhD|Ph\.D|M\.D|Jr|Sr)\b\.?/i; + +function normalizeNameForComparison(name: string): string { + return name + .normalize('NFD') + .replace(/[̀-ͯ]/g, '') + .replace(/[.,]/g, '') + .toUpperCase() + .split(/\s+/) + .filter(Boolean) + .sort() + .join(' '); +} + +export function isAssigneeLikelyPerson( + assignee: string, + inventors: string[] | undefined, +): boolean { + if (ORG_SUFFIX_PATTERN.test(assignee)) { + return false; + } + + const normalizedAssignee = normalizeNameForComparison( + assignee.replace(PERSON_SUFFIX_PATTERN, ''), + ); + const matchesInventor = (inventors ?? []).some( + (inventor) => normalizeNameForComparison(inventor) === normalizedAssignee, + ); + if (matchesInventor) { + return true; + } + + return PERSON_SUFFIX_PATTERN.test(assignee); +} + +export function trackPatentEntry(patent: PatentEntry): string { + return [ + patent.source, + patent.patent_id, + patent.publication_date ?? '', + patent.kind ?? patent.application_type ?? '', + ].join('|'); +} + export function patentExternalLinks( patent: PatentEntry, ): { label: string; url: string }[] { diff --git a/webapp/src/app/modules/person-patents/person-patents.component.html b/webapp/src/app/modules/person-patents/person-patents.component.html index b32185a7..ba80b808 100644 --- a/webapp/src/app/modules/person-patents/person-patents.component.html +++ b/webapp/src/app/modules/person-patents/person-patents.component.html @@ -34,146 +34,18 @@ [value]="sortColumn" (selectionChange)="setSort($event.value)"> Sortieren nach - Jahr + Jahr Titel Quelle - - - - - - - - - - - - @for ( - patent of getPagedPatents(); - track trackPatent($index, patent) - ) { - - - - - - - - } - -
    Patent - Quelle - @if (sortColumn === 'source') { - {{ - sortDirection === 'asc' ? 'arrow_upward' : 'arrow_downward' - }} - } - - Jahr - @if (sortColumn === 'year') { - {{ - sortDirection === 'asc' ? 'arrow_upward' : 'arrow_downward' - }} - } - ErfinderAnmelder
    - {{ patent.title ?? patent.patent_id }} - - - {{ patent.source }} - - - @if (patent.publication_year) { - {{ - patent.publication_year - }} - } @else { - - - } - - @if (patent.inventors && patent.inventors.length) { -
    - @for ( - inventor of patent.inventors.slice(0, 2); - track inventor - ) { - - person - {{ inventor }} - - } - @if (patent.inventors.length > 2) { - - - person - {{ patent.inventors[2] }} - - @if (patent.inventors.length > 3) { - +{{ patent.inventors.length - 3 }} - } - - } -
    - } @else { - - - } -
    - @if (patent.assignees && patent.assignees.length) { -
    - @for ( - assignee of patent.assignees.slice(0, 2); - track assignee - ) { - - {{ - isAssigneeLikelyPerson(assignee, patent) - ? 'person' - : 'apartment' - }} - {{ assignee }} - - } - @if (patent.assignees.length > 2) { - - - {{ - isAssigneeLikelyPerson( - patent.assignees[2], - patent - ) - ? 'person' - : 'apartment' - }} - {{ patent.assignees[2] }} - - @if (patent.assignees.length > 3) { - +{{ patent.assignees.length - 3 }} - } - - } -
    - } @else { - - - } -
    + { switch (this.sortColumn) { - case 'year': { + case 'publication_year': { const yearA = a.publication_date ?? String(a.publication_year ?? ''); const yearB = b.publication_date ?? String(b.publication_year ?? ''); return direction * yearA.localeCompare(yearB); @@ -202,7 +215,9 @@ export class PersonPatentsComponent { } private isValidSortColumn(value: string | null): value is SortColumn { - return value === 'title' || value === 'year' || value === 'source'; + return ( + value === 'title' || value === 'publication_year' || value === 'source' + ); } private isValidSortDirection(value: string | null): value is SortDirection { @@ -214,42 +229,6 @@ export class PersonPatentsComponent { return this.filteredPatents.slice(start, start + this.pageSize); } - private static readonly ORG_SUFFIX_PATTERN = - /\b(Inc|Ltd|LLC|LLP|GmbH|Corp(oration)?|Co|KG|AG|SE|S\.?A\.?|N\.?V\.?|B\.?V\.?|PLC|Universit(y|ät|é)|Institut(e)?|Foundation|Laborator(y|ies)|Labs?|Group|Holdings?|Company|Gesellschaft)\b\.?/i; - private static readonly PERSON_SUFFIX_PATTERN = - /\b(Dr|Prof|PhD|Ph\.D|M\.D|Jr|Sr)\b\.?/i; - - private normalizeNameForComparison(name: string): string { - return name - .normalize('NFD') - .replace(/[̀-ͯ]/g, '') - .replace(/[.,]/g, '') - .toUpperCase() - .split(/\s+/) - .filter(Boolean) - .sort() - .join(' '); - } - - isAssigneeLikelyPerson(assignee: string, patent: PatentEntry): boolean { - if (PersonPatentsComponent.ORG_SUFFIX_PATTERN.test(assignee)) { - return false; - } - - const normalizedAssignee = this.normalizeNameForComparison( - assignee.replace(PersonPatentsComponent.PERSON_SUFFIX_PATTERN, ''), - ); - const matchesInventor = (patent.inventors ?? []).some( - (inventor) => - this.normalizeNameForComparison(inventor) === normalizedAssignee, - ); - if (matchesInventor) { - return true; - } - - return PersonPatentsComponent.PERSON_SUFFIX_PATTERN.test(assignee); - } - formatDate(date: string | null | undefined): string { return formatPatentDate(date); } @@ -262,15 +241,6 @@ export class PersonPatentsComponent { return this.patents.filter((p) => p.source === 'USPTO').length; } - trackPatent(_index: number, patent: PatentEntry): string { - return [ - patent.source, - patent.patent_id, - patent.publication_date ?? '', - patent.kind ?? patent.application_type ?? '', - ].join('|'); - } - getAbstractPreview(abstract: string | null | undefined): string | null { if (!abstract?.trim()) { return null; diff --git a/webapp/src/app/shared/ui/patent-table/patent-table.component.html b/webapp/src/app/shared/ui/patent-table/patent-table.component.html new file mode 100644 index 00000000..0a6fcdae --- /dev/null +++ b/webapp/src/app/shared/ui/patent-table/patent-table.component.html @@ -0,0 +1,125 @@ + + + + + + + + + {{ patent.source }} + + + + + @if (patent.publication_year) { + {{ patent.publication_year }} + } @else { + - + } + + + + @let expanded = isInventorsExpanded(patent); + @let visibleInventors = + expanded ? patent.inventors : (patent.inventors ?? []).slice(0, 3); +
    + @for (inventor of visibleInventors; track inventor) { + + person + {{ inventor }} + + } @empty { + - + } + @if ((patent.inventors ?? []).length > 3) { + + } +
    +
    + + + @let expanded = isAssigneesExpanded(patent); + @let visibleAssignees = + expanded ? patent.assignees : (patent.assignees ?? []).slice(0, 3); +
    + @for (assignee of visibleAssignees; track assignee) { + + {{ + isAssigneeLikelyPerson(assignee, patent) ? 'person' : 'apartment' + }} + {{ assignee }} + + } @empty { + - + } + @if ((patent.assignees ?? []).length > 3) { + + } +
    +
    + + + + {{ getMatchTypeLabel(patent.match_type) }} + + + + +
    + + + + + open_in_new + + diff --git a/webapp/src/app/shared/ui/patent-table/patent-table.component.scss b/webapp/src/app/shared/ui/patent-table/patent-table.component.scss new file mode 100644 index 00000000..76b50023 --- /dev/null +++ b/webapp/src/app/shared/ui/patent-table/patent-table.component.scss @@ -0,0 +1,149 @@ +:host { + display: block; +} + +.empty-text { + color: var(--sg-text-muted); +} + +.patent-title-btn { + display: inline-flex; + align-items: center; + gap: 2px; + padding: 0; + border: 0; + background: none; + color: var(--sg-text); + font-weight: 600; + font-size: 13px; + text-align: left; + white-space: normal; + word-break: break-word; + cursor: pointer; + + &:hover { + color: var(--sg-blue-highlight); + } + + &.selected { + color: var(--sg-blue-highlight); + } + + &__icon { + flex-shrink: 0; + width: 16px; + height: 16px; + font-size: 16px; + } +} + +.year-badge { + display: inline-flex; + align-items: center; + justify-content: center; + min-width: 26px; + padding: 2px 10px; + border-radius: 999px; + border: 1px solid var(--sg-border); + color: var(--sg-text); + font-size: 0.8rem; + font-weight: 600; +} + +.person-chips { + display: flex; + flex-direction: column; + align-items: flex-start; + gap: 4px; + max-width: 240px; +} + +.person-chip { + display: inline-flex; + align-items: center; + gap: 4px; + max-width: 100%; + padding: 2px 8px; + border: 1px solid var(--sg-border); + border-radius: var(--sg-radius-sm); + background: var(--sg-surface-soft); + color: var(--sg-text); + font-size: 0.75rem; + line-height: 1.4; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; + + mat-icon { + flex-shrink: 0; + width: 14px; + height: 14px; + font-size: 14px; + color: var(--sg-text-soft); + } +} + +.match-badge { + display: inline-flex; + align-items: center; + padding: 3px 10px; + border-radius: 999px; + font-size: 0.72rem; + font-weight: 700; + + &--institution { + background: var(--sg-primary-soft); + color: var(--sg-primary); + border: 1px solid var(--sg-border); + } + + &--name { + background: var(--sg-warning-soft); + color: var(--sg-warning); + border: 1px solid var(--sg-border); + } + + &--both { + background: var(--sg-success-soft); + color: var(--sg-success); + border: 1px solid var(--sg-border); + } +} + +.patent-chip-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: var(--sg-surface); + color: var(--sg-text-muted); + font-family: inherit; + font-size: 11px; + line-height: 1.2; + cursor: pointer; + transition: all 0.2s ease; + + &:hover { + background: var(--sg-surface-soft); + color: var(--sg-text); + } +} + +.cell-authors { + display: flex; + flex-direction: column; + gap: 4px; + min-width: 120px; +} + +.author-link { + color: var(--sg-blue-highlight); + text-decoration: none; + font-size: 0.82rem; + + &:hover { + text-decoration: underline; + } +} diff --git a/webapp/src/app/shared/ui/patent-table/patent-table.component.ts b/webapp/src/app/shared/ui/patent-table/patent-table.component.ts new file mode 100644 index 00000000..44b4d0df --- /dev/null +++ b/webapp/src/app/shared/ui/patent-table/patent-table.component.ts @@ -0,0 +1,169 @@ +import { Component, TemplateRef, input, output, signal, viewChild } from '@angular/core'; +import { RouterModule } from '@angular/router'; +import { MatIconModule } from '@angular/material/icon'; +import { MatButtonModule } from '@angular/material/button'; +import { MatTooltipModule } from '@angular/material/tooltip'; +import { Sort } from '@angular/material/sort'; +import { PatentEntry } from '../../../api/model/patentEntry'; +import { MatchedAuthor } from '../../../api/model/matchedAuthor'; +import { DataTableComponent, GenericColumn } from '../data-table/data-table.component'; +import { ChipComponent } from '../chip/chip.component'; +import { ComponentTooltipDirective } from '../../../directives/component-tooltip.directive'; +import { AppAuthorTooltipComponent } from '../app-author-tooltip/app-author-tooltip.component'; +import { isAssigneeLikelyPerson } from '../../../modules/patent-detail/patent-detail.utils'; + +export interface PatentTableEntry extends PatentEntry { + match_type?: string; + matched_authors?: MatchedAuthor[]; +} + +@Component({ + selector: 'app-patent-table', + imports: [ + RouterModule, + MatIconModule, + MatButtonModule, + MatTooltipModule, + DataTableComponent, + ChipComponent, + ComponentTooltipDirective, + ], + templateUrl: './patent-table.component.html', + styleUrl: './patent-table.component.scss', +}) +export class PatentTableComponent { + readonly AuthorTooltipComponent = AppAuthorTooltipComponent; + + patents = input.required(); + selectedPatent = input(null); + showMatchType = input(false); + + queryParamSortKey = input('sortBy'); + queryParamSortDirectionKey = input('sortDir'); + + selectPatent = output(); + handleSortChange = output(); + + titleTmp = viewChild.required>('titleTmp'); + sourceTmp = viewChild.required>('sourceTmp'); + yearTmp = viewChild.required>('yearTmp'); + inventorsTmp = viewChild.required>('inventorsTmp'); + assigneesTmp = viewChild.required>('assigneesTmp'); + matchTypeTmp = viewChild.required>('matchTypeTmp'); + matchedAuthorsTmp = viewChild.required>('matchedAuthorsTmp'); + actionsTmp = viewChild.required>('actionsTmp'); + + columns(): GenericColumn[] { + const baseColumns: GenericColumn[] = [ + { + id: 'title', + header: 'Patent', + type: 'accessor', + accessorKey: 'title' as keyof T, + cellTemplate: this.titleTmp(), + }, + { + id: 'source', + header: 'Quelle', + type: 'accessor', + accessorKey: 'source' as keyof T, + cellTemplate: this.sourceTmp(), + }, + { + id: 'publication_year', + header: 'Jahr', + type: 'accessor', + accessorKey: 'publication_year' as keyof T, + cellTemplate: this.yearTmp(), + }, + { + id: 'inventors', + header: 'Erfinder', + type: 'display', + cellTemplate: this.inventorsTmp(), + }, + { + id: 'assignees', + header: 'Anmelder', + type: 'display', + cellTemplate: this.assigneesTmp(), + }, + ]; + + if (this.showMatchType()) { + baseColumns.push( + { + id: 'match_type', + header: 'Match-Typ', + type: 'display', + cellTemplate: this.matchTypeTmp(), + }, + { + id: 'matched_authors', + header: 'Personen', + type: 'display', + cellTemplate: this.matchedAuthorsTmp(), + }, + ); + } + + baseColumns.push({ + id: 'actions', + header: '', + type: 'display', + cellTemplate: this.actionsTmp(), + }); + + return baseColumns; + } + + private readonly expandedInventorsIds = signal>(new Set()); + private readonly expandedAssigneesIds = signal>(new Set()); + + isInventorsExpanded(patent: T): boolean { + return this.expandedInventorsIds().has(patent.patent_id); + } + + toggleInventorsExpansion(patent: T): void { + this.expandedInventorsIds.update((ids) => toggleId(ids, patent.patent_id)); + } + + isAssigneesExpanded(patent: T): boolean { + return this.expandedAssigneesIds().has(patent.patent_id); + } + + toggleAssigneesExpansion(patent: T): void { + this.expandedAssigneesIds.update((ids) => toggleId(ids, patent.patent_id)); + } + + isSelected(patent: T): boolean { + return this.selectedPatent() === patent; + } + + isAssigneeLikelyPerson(assignee: string, patent: T): boolean { + return isAssigneeLikelyPerson(assignee, patent.inventors); + } + + getMatchTypeLabel(matchType: string | undefined): string { + switch (matchType) { + case 'institution': + return 'Institution'; + case 'name': + return 'Name'; + case 'both': + return 'Beides'; + default: + return matchType ?? '-'; + } + } +} + +function toggleId(ids: Set, id: string): Set { + const next = new Set(ids); + if (next.has(id)) { + next.delete(id); + } else { + next.add(id); + } + return next; +}