From 59a1f765d0735b218b01ae639d4dc2ea784c34b4 Mon Sep 17 00:00:00 2001 From: spsaefan <117728614+spsaefan@users.noreply.github.com> Date: Wed, 22 Jul 2026 23:14:05 +0200 Subject: [PATCH 1/6] Add DFG projects --- service/src/main/inse/dashboard/service.py | 306 ++++++++++++++---- .../src/main/inse/dashboard/test_service.py | 267 ++++++++++++--- .../dashboard/dashboard.component.html | 14 +- .../dashboard/dashboard.component.scss | 6 +- .../modules/dashboard/dashboard.component.ts | 37 ++- 5 files changed, 505 insertions(+), 125 deletions(-) diff --git a/service/src/main/inse/dashboard/service.py b/service/src/main/inse/dashboard/service.py index ce9a9b2b..a491c51f 100644 --- a/service/src/main/inse/dashboard/service.py +++ b/service/src/main/inse/dashboard/service.py @@ -12,6 +12,8 @@ from inse.integrations import elasticsearch from inse.institutions.institutions_search_client import InstitutionsSearchClient from inse.model import ESCluster, ESIndex from inse.patents.org.elastic_search_client import OrgPatentsSearchClient +from inse.projects.dfg_institutions.service import autocomplete_institutions_for_selector +from inse.projects.logic import get_person_ids_by_institution_ids from .model import ( DashboardStatisticValue, @@ -264,21 +266,39 @@ async def get_top_authors( works_period: WorksPeriod = "all_time", ) -> TopAuthorStatistics: normalized_id = _normalize_institution_id(institution_id) - authors = await _safe_institution_authors(normalized_id) + + authors, aliases = await asyncio.gather( + _safe_institution_authors(normalized_id), + _safe_institution_aliases(normalized_id, organization_name), + ) + + logger.info( + "Dashboard institution aliases for %s: %s", + organization_name, + aliases, + ) + works = _top_work_authors(authors, works_period) - aliases = await _safe_institution_aliases(normalized_id, organization_name) + projects = await _safe_top_authors( "projects", - _top_project_authors(authors, aliases), + _top_project_authors( + authors=authors, + organization_name=organization_name, + aliases=aliases, + ), ) + patents = await _safe_top_authors( "patents", _top_patent_authors(normalized_id), ) + news = await _safe_top_authors( "news", _top_news_authors(authors), ) + return TopAuthorStatistics( institution_id=normalized_id, works=works, @@ -593,89 +613,251 @@ async def _institution_authors(institution_id: str) -> list[dict[str, Any]]: async def _top_project_authors( authors: list[dict[str, Any]], + organization_name: str, aliases: list[str], ) -> list[TopAuthor]: - if not aliases: + 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 [] - counts: dict[str, int] = {} - names: dict[str, str] = {} - for bucket in await _top_dfg_project_author_buckets(aliases): - key = str(bucket.get("key", "")).strip() - if key: - normalized_key = key.casefold() - names[normalized_key] = key - counts[normalized_key] = counts.get(normalized_key, 0) + int( - bucket.get("doc_count", 0) - ) + + 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, + aliases=aliases, + ) + + 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 = { + author["name"].strip().casefold(): author + for author in authors + if author.get("name") + } - institution_authors = {author["name"].casefold(): author for author in authors} ranked = sorted( ( - (name, count) - for name, count in counts.items() - if count > 0 + (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(), ), - key=lambda item: (-item[1], names[item[0]].casefold()), ) - return [ - TopAuthor( - id=( - _short_author_id(institution_authors[name]["id"]) - if name in institution_authors - else None - ), - name=( - institution_authors[name]["name"] - if name in institution_authors - else names[name] - ), - count=count, + + result: list[TopAuthor] = [] + + for person_id, project_ids in ranked[:TOP_AUTHOR_LIMIT]: + dfg_name = names[person_id] + matched_author = institution_authors.get( + dfg_name.casefold() ) - for name, count in ranked[:TOP_AUTHOR_LIMIT] - ] + + 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 -async def _top_dfg_project_author_buckets( +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], aliases: list[str], -) -> list[dict[str, Any]]: +) -> tuple[list[dict[str, Any]], int]: response = await elasticsearch.search( index=ESIndex.DFG_PROJECTS, body={ - "size": 0, - "query": _dfg_institution_query(aliases), - "aggs": { - "people": { - "terms": { - "script": { - "lang": "painless", - "source": _dfg_involved_persons_script(), + "size": size, + "from": page * size, + "_source": [ + "id", + "project_id", + "persons", + *DFG_INSTITUTION_FIELDS, + ], + "query": { + "bool": { + "must": [ + + _dfg_institution_query(aliases), + + { + "nested": { + "path": "persons", + "query": { + "terms": { + "persons.person_id": sorted( + person_ids + ) + } + }, + } }, - "size": 10000, - } + ] } }, + "sort": [ + { + "id": { + "order": "asc", + "missing": "_last", + } + } + ], }, cluster=ESCluster.INSE, - ) - return ( - response.get("aggregations", {}).get("people", {}).get("buckets", []) + track_total_hits=True, ) + hits_block = response.get("hits", {}) -def _dfg_involved_persons_script() -> str: - return ( - "def names = new HashSet(); " - "def value = params['_source'].containsKey('Beteiligte Personen') " - " ? params['_source']['Beteiligte Personen'] : null; " - "if (value instanceof String && value.length() > 0) { " - " for (name in value.splitOnToken(';')) { " - " def trimmed = name.trim(); " - " if (trimmed.length() > 0) { names.add(trimmed); } " - " } " - "} " - "return new ArrayList(names);" + 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("project_id") + if project_id is None: + project_id = project.get("id") + return str(project_id) if project_id is not None else None + async def _top_patent_authors(institution_id: str) -> list[TopAuthor]: client = OrgPatentsSearchClient() @@ -729,4 +911,4 @@ async def _top_news_authors(authors: list[dict[str, Any]]) -> list[TopAuthor]: ) for bucket in buckets if str(bucket.get("key", "")).casefold() in institution_authors - ][:TOP_AUTHOR_LIMIT] + ][:TOP_AUTHOR_LIMIT] \ No newline at end of file diff --git a/service/src/main/inse/dashboard/test_service.py b/service/src/main/inse/dashboard/test_service.py index 0d2914c0..8244e305 100644 --- a/service/src/main/inse/dashboard/test_service.py +++ b/service/src/main/inse/dashboard/test_service.py @@ -1,5 +1,6 @@ from unittest.mock import AsyncMock, patch from datetime import datetime +from types import SimpleNamespace import pytest from fastapi import HTTPException @@ -133,10 +134,42 @@ async def test_top_authors_maps_works_and_dfg_project_aggregations(): } if kwargs["index"] == ESIndex.DFG_PROJECTS: return { - "aggregations": { - "people": { - "buckets": [{"key": "Grace Example", "doc_count": 3}] - } + "hits": { + "total": {"value": 3}, + "hits": [ + { + "_source": { + "id": "ES1", + "project_id": "P1", + "persons": [ + {"person_id": 2, "full_name": "Grace Example"}, + { + "person_id": 99, + "full_name": "Outside Collaborator", + }, + ], + } + }, + { + "_source": { + "id": "ES2", + "project_id": "P2", + "persons": [ + {"person_id": 2, "full_name": "Grace Example"}, + {"person_id": 2, "full_name": "Grace Example"}, + ], + } + }, + { + "_source": { + "id": "ES3", + "project_id": "P2", + "persons": [ + {"person_id": 2, "full_name": "Grace Example"}, + ], + } + }, + ], } } return {"aggregations": {"people": {"buckets": []}}} @@ -145,8 +178,18 @@ async def test_top_authors_maps_works_and_dfg_project_aggregations(): "inse.dashboard.service.elasticsearch.search", new=AsyncMock(side_effect=search), ) as mocked_search, patch( + "inse.dashboard.service.autocomplete_institutions_for_selector", + new=AsyncMock( + return_value=SimpleNamespace( + elements=[SimpleNamespace(id=101)] + ) + ), + ) as mocked_institutions, patch( + "inse.dashboard.service.get_person_ids_by_institution_ids", + new=AsyncMock(return_value=[2]), + ), patch( "inse.dashboard.service.InstitutionsSearchClient.get_institution_aliases_by_oa_institution_id", - new=AsyncMock(return_value=["Example University"]), + new=AsyncMock(return_value=[]), ), patch( "inse.dashboard.service.OrgPatentsSearchClient.top_authors_by_institution", new=AsyncMock( @@ -165,7 +208,7 @@ async def test_top_authors_maps_works_and_dfg_project_aggregations(): assert result.projects[0].model_dump() == { "id": "A2", "name": "Grace Example", - "count": 3, + "count": 2, } assert result.patents[0].model_dump() == { "id": "A1", @@ -177,20 +220,28 @@ async def test_top_authors_maps_works_and_dfg_project_aggregations(): "name": "Ada Example", "count": 6, } - project_calls = [ + mocked_institutions.assert_awaited_once_with( + query="Example Org", + page=0, + size=10000, + ) + dfg_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"] == ESIndex.DFG_PROJECTS ] - assert len(project_calls) == 1 - assert project_calls[0].kwargs["index"] == ESIndex.DFG_PROJECTS - assert project_calls[0].kwargs["body"]["query"]["bool"][ - "minimum_should_match" - ] == 1 - assert "Beteiligte Personen" in project_calls[0].kwargs["body"]["aggs"][ - "people" - ]["terms"]["script"]["source"] + assert len(dfg_project_calls) == 1 + assert dfg_project_calls[0].kwargs["body"]["_source"] == [ + "id", + "project_id", + "persons", + ] + assert dfg_project_calls[0].kwargs["body"]["query"] == { + "nested": { + "path": "persons", + "query": {"terms": {"persons.person_id": [2]}}, + } + } @pytest.mark.anyio @@ -200,10 +251,20 @@ async def test_top_authors_keeps_dfg_project_authors_without_openalex_match(): return {"hits": {"hits": []}} if kwargs["index"] == ESIndex.DFG_PROJECTS: return { - "aggregations": { - "people": { - "buckets": [{"key": "Project Person", "doc_count": 9}] - } + "hits": { + "total": {"value": 9}, + "hits": [ + { + "_source": { + "id": f"P{project_id}", + "project_id": None, + "persons": [ + {"person_id": 9, "full_name": "Project Person"}, + ], + } + } + for project_id in range(9) + ], } } return {"aggregations": {"people": {"buckets": []}}} @@ -212,8 +273,15 @@ async def test_top_authors_keeps_dfg_project_authors_without_openalex_match(): "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"]), + "inse.dashboard.service.autocomplete_institutions_for_selector", + new=AsyncMock( + return_value=SimpleNamespace( + elements=[SimpleNamespace(id=101)] + ) + ), + ), patch( + "inse.dashboard.service.get_person_ids_by_institution_ids", + new=AsyncMock(return_value=[9]), ), patch( "inse.dashboard.service.OrgPatentsSearchClient.top_authors_by_institution", new=AsyncMock(return_value=[]), @@ -227,6 +295,84 @@ async def test_top_authors_keeps_dfg_project_authors_without_openalex_match(): } +@pytest.mark.anyio +async def test_top_authors_processes_all_dfg_project_pages(): + async def search(**kwargs): + if kwargs["index"] == ESIndex.OPENALEX_AUTHORS: + return {"hits": {"hits": []}} + if kwargs["index"] == ESIndex.DFG_PROJECTS: + if kwargs["body"]["from"] == 0: + return { + "hits": { + "total": {"value": 10001}, + "hits": [ + { + "_source": { + "id": f"ES{project_id}", + "project_id": f"P{project_id}", + "persons": [ + { + "person_id": 9, + "full_name": "Project Person", + }, + ], + } + } + for project_id in range(10000) + ], + } + } + return { + "hits": { + "total": {"value": 10001}, + "hits": [ + { + "_source": { + "id": "ES10000", + "project_id": "P10000", + "persons": [ + {"person_id": 9, "full_name": "Project Person"}, + ], + } + } + ], + } + } + return {"aggregations": {"people": {"buckets": []}}} + + with patch( + "inse.dashboard.service.elasticsearch.search", + new=AsyncMock(side_effect=search), + ) as mocked_search, patch( + "inse.dashboard.service.autocomplete_institutions_for_selector", + new=AsyncMock( + return_value=SimpleNamespace(elements=[SimpleNamespace(id=101)]) + ), + ), patch( + "inse.dashboard.service.get_person_ids_by_institution_ids", + new=AsyncMock(return_value=[9]), + ), patch( + "inse.dashboard.service.OrgPatentsSearchClient.top_authors_by_institution", + new=AsyncMock(return_value=[]), + ): + result = await get_top_authors(ORG_INSTITUTION_ID, "Example Org") + + assert result.projects[0].model_dump() == { + "id": None, + "name": "Project Person", + "count": 10001, + } + dfg_project_calls = [ + call + for call in mocked_search.await_args_list + if call.kwargs["index"] == ESIndex.DFG_PROJECTS + ] + assert [call.kwargs["body"]["from"] for call in dfg_project_calls] == [ + 0, + 10000, + ] + + @pytest.mark.anyio async def test_top_authors_returns_top_ten_dfg_project_people_by_project_count(): async def search(**kwargs): @@ -234,13 +380,24 @@ async def test_top_authors_returns_top_ten_dfg_project_people_by_project_count() return {"hits": {"hits": []}} if kwargs["index"] == ESIndex.DFG_PROJECTS: return { - "aggregations": { - "people": { - "buckets": [ - {"key": f"Project Person {count}", "doc_count": count} - for count in range(1, 12) - ] - } + "hits": { + "total": {"value": 11}, + "hits": [ + { + "_source": { + "id": f"P{project_id}", + "project_id": None, + "persons": [ + { + "person_id": count, + "full_name": f"Project Person {count}", + } + for count in range(project_id, 12) + ], + } + } + for project_id in range(1, 12) + ], } } return {"aggregations": {"people": {"buckets": []}}} @@ -249,8 +406,15 @@ async def test_top_authors_returns_top_ten_dfg_project_people_by_project_count() "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"]), + "inse.dashboard.service.autocomplete_institutions_for_selector", + new=AsyncMock( + return_value=SimpleNamespace( + elements=[SimpleNamespace(id=101)] + ) + ), + ), patch( + "inse.dashboard.service.get_person_ids_by_institution_ids", + new=AsyncMock(return_value=list(range(1, 12))), ), patch( "inse.dashboard.service.OrgPatentsSearchClient.top_authors_by_institution", new=AsyncMock(return_value=[]), @@ -263,7 +427,7 @@ async def test_top_authors_returns_top_ten_dfg_project_people_by_project_count() @pytest.mark.anyio -async def test_top_authors_combines_dfg_involved_people_case_insensitively(): +async def test_top_authors_matches_dfg_project_people_to_openalex_case_insensitively(): async def search(**kwargs): if kwargs["index"] == ESIndex.OPENALEX_AUTHORS: return { @@ -282,14 +446,20 @@ async def test_top_authors_combines_dfg_involved_people_case_insensitively(): } if kwargs["index"] == ESIndex.DFG_PROJECTS: return { - "aggregations": { - "people": { - "buckets": [ - {"key": "Ada Example", "doc_count": 2}, - {"key": "ada example", "doc_count": 3}, - {"key": "DFG Person", "doc_count": 4}, - ] - } + "hits": { + "total": {"value": 1}, + "hits": [ + { + "_source": { + "id": "P1", + "project_id": None, + "persons": [ + {"person_id": 1, "full_name": "ada example"}, + {"person_id": 2, "full_name": "DFG Person"}, + ], + } + } + ], } } return {"aggregations": {"authors": {"buckets": []}}} @@ -298,8 +468,15 @@ async def test_top_authors_combines_dfg_involved_people_case_insensitively(): "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"]), + "inse.dashboard.service.autocomplete_institutions_for_selector", + new=AsyncMock( + return_value=SimpleNamespace( + elements=[SimpleNamespace(id=101)] + ) + ), + ), patch( + "inse.dashboard.service.get_person_ids_by_institution_ids", + new=AsyncMock(return_value=[1, 2]), ), patch( "inse.dashboard.service.OrgPatentsSearchClient.top_authors_by_institution", new=AsyncMock(return_value=[]), @@ -307,8 +484,8 @@ async def test_top_authors_combines_dfg_involved_people_case_insensitively(): result = await get_top_authors(ORG_INSTITUTION_ID, "Example Org") assert [author.model_dump() for author in result.projects] == [ - {"id": "A1", "name": "Ada Example", "count": 5}, - {"id": None, "name": "DFG Person", "count": 4}, + {"id": "A1", "name": "Ada Example", "count": 1}, + {"id": None, "name": "DFG Person", "count": 1}, ] diff --git a/webapp/src/app/modules/dashboard/dashboard.component.html b/webapp/src/app/modules/dashboard/dashboard.component.html index 4b827cb2..25d79648 100644 --- a/webapp/src/app/modules/dashboard/dashboard.component.html +++ b/webapp/src/app/modules/dashboard/dashboard.component.html @@ -178,7 +178,7 @@

Top 10 Personen aller Zeiten

-

Nach Anzahl der Works, Patente und News Ihrer Organisation.

+

Nach Anzahl der Works, DFG-Projekte, Patente und News Ihrer Organisation.

diff --git a/webapp/src/app/modules/dashboard/dashboard.component.scss b/webapp/src/app/modules/dashboard/dashboard.component.scss index 565fa58f..278954d9 100644 --- a/webapp/src/app/modules/dashboard/dashboard.component.scss +++ b/webapp/src/app/modules/dashboard/dashboard.component.scss @@ -303,8 +303,10 @@ margin-bottom: 0.25rem; font-size: 0.85rem; - span { + .author-name { overflow: hidden; + color: #1d4ed8; + font-weight: 600; text-overflow: ellipsis; white-space: nowrap; } @@ -312,8 +314,6 @@ .author-link { overflow: hidden; - color: #1d4ed8; - font-weight: 600; text-decoration: none; text-overflow: ellipsis; white-space: nowrap; diff --git a/webapp/src/app/modules/dashboard/dashboard.component.ts b/webapp/src/app/modules/dashboard/dashboard.component.ts index ea16ab26..22c575ea 100644 --- a/webapp/src/app/modules/dashboard/dashboard.component.ts +++ b/webapp/src/app/modules/dashboard/dashboard.component.ts @@ -24,6 +24,12 @@ type TopicTreemapPeriod = | 'last_10_years' | 'all_time' | 'custom'; +type TopAuthorDataset = { + title: string; + icon: string; + entries: TopAuthor[]; + stripAuthorTitle?: boolean; +}; @Component({ selector: 'dashboard', @@ -94,11 +100,7 @@ export class DashboardComponent implements OnInit { return this.statisticLoading[key]; } - topAuthorDatasets(): Array<{ - title: string; - icon: string; - entries: TopAuthor[]; - }> { + topAuthorDatasets(): TopAuthorDataset[] { return [ { title: 'Publikationen', @@ -110,15 +112,17 @@ export class DashboardComponent implements OnInit { icon: 'description', entries: this.topAuthors?.patents ?? [], }, + { + title: 'DFG Projekte', + icon: 'account_tree', + entries: this.topAuthors?.projects ?? [], + stripAuthorTitle: true, + }, { title: 'News', icon: 'article', entries: this.topAuthors?.news ?? [] }, ]; } - visibleTopAuthorDatasets(): Array<{ - title: string; - icon: string; - entries: TopAuthor[]; - }> { + visibleTopAuthorDatasets(): TopAuthorDataset[] { const datasets = this.topAuthorDatasets(); return this.topAuthorsLoading ? datasets @@ -149,6 +153,19 @@ export class DashboardComponent implements OnInit { return (count / maximum) * 100; } + authorDisplayName(dataset: TopAuthorDataset, entry: TopAuthor): string { + if (!dataset.stripAuthorTitle) return entry.name; + + return ( + entry.name + .replace( + /^(?:(?:(?:apl\.\s*)?prof(?:essor)?\.?|priv\.-doz\.?|pd|dr\.?)\s+)+/i, + '', + ) + .trim() || entry.name + ); + } + organizationName(): string { return this.statistics?.organization_name ?? 'Ihre Organisation'; } -- 2.56.1 From fc134dad8eb0651a749556e64efc910f972af0d9 Mon Sep 17 00:00:00 2001 From: spsaefan <117728614+spsaefan@users.noreply.github.com> Date: Wed, 22 Jul 2026 23:46:23 +0200 Subject: [PATCH 2/6] Update DFG project test --- .../src/main/inse/dashboard/test_service.py | 36 ++++++++++++++----- 1 file changed, 27 insertions(+), 9 deletions(-) diff --git a/service/src/main/inse/dashboard/test_service.py b/service/src/main/inse/dashboard/test_service.py index 8244e305..b2bbd0f0 100644 --- a/service/src/main/inse/dashboard/test_service.py +++ b/service/src/main/inse/dashboard/test_service.py @@ -9,6 +9,7 @@ from sqlmodel import Session, SQLModel, create_engine from inse import config from inse.auth.model import AccessToken, Organization, UserRole from inse.dashboard.service import ( + DFG_INSTITUTION_FIELDS, get_dashboard_organization, get_dashboard_statistics, get_top_authors, @@ -230,18 +231,35 @@ async def test_top_authors_maps_works_and_dfg_project_aggregations(): for call in mocked_search.await_args_list if call.kwargs["index"] == ESIndex.DFG_PROJECTS ] - assert len(dfg_project_calls) == 1 assert dfg_project_calls[0].kwargs["body"]["_source"] == [ - "id", - "project_id", - "persons", + "id", + "project_id", + "persons", + *DFG_INSTITUTION_FIELDS, ] - assert dfg_project_calls[0].kwargs["body"]["query"] == { - "nested": { - "path": "persons", - "query": {"terms": {"persons.person_id": [2]}}, - } + + query = dfg_project_calls[0].kwargs["body"]["query"] + + assert query["bool"]["must"][0]["bool"]["minimum_should_match"] == 1 + assert query["bool"]["must"][0]["bool"]["should"][0]["bool"]["should"][0][ + "match" + ] == { + "Antragstellende Institution": { + "query": "Example Org", + "operator": "and", } +} + + assert query["bool"]["must"][1] == { + "nested": { + "path": "persons", + "query": { + "terms": { + "persons.person_id": [2], + } + }, + } +} @pytest.mark.anyio -- 2.56.1 From 3d78ec900e88db0028cae40e15fae71f04da16e9 Mon Sep 17 00:00:00 2001 From: spsaefan <117728614+spsaefan@users.noreply.github.com> Date: Thu, 23 Jul 2026 01:06:44 +0200 Subject: [PATCH 3/6] Fix DFG top authors aggregation --- service/src/main/inse/dashboard/service.py | 32 ++++---------- .../src/main/inse/dashboard/test_service.py | 44 +++++++------------ 2 files changed, 23 insertions(+), 53 deletions(-) diff --git a/service/src/main/inse/dashboard/service.py b/service/src/main/inse/dashboard/service.py index a491c51f..ee4e11e6 100644 --- a/service/src/main/inse/dashboard/service.py +++ b/service/src/main/inse/dashboard/service.py @@ -660,7 +660,6 @@ async def _top_project_authors( page=page, size=size, person_ids=selected_person_ids, - aliases=aliases, ) if not project_hits: @@ -781,7 +780,6 @@ async def _dfg_project_author_hits( page: int, size: int, person_ids: set[int], - aliases: list[str], ) -> tuple[list[dict[str, Any]], int]: response = await elasticsearch.search( index=ESIndex.DFG_PROJECTS, @@ -792,27 +790,13 @@ async def _dfg_project_author_hits( "id", "project_id", "persons", - *DFG_INSTITUTION_FIELDS, ], "query": { - "bool": { - "must": [ - - _dfg_institution_query(aliases), - - { - "nested": { - "path": "persons", - "query": { - "terms": { - "persons.person_id": sorted( - person_ids - ) - } - }, - } - }, - ] + "nested": { + "path": "persons", + "query": { + "terms": {"persons.person_id": sorted(person_ids)} + }, } }, "sort": [ @@ -853,9 +837,9 @@ async def _dfg_project_author_hits( return hits, total def _dfg_project_id(project: dict[str, Any]) -> str | None: - project_id = project.get("project_id") + project_id = project.get("id") if project_id is None: - project_id = project.get("id") + project_id = project.get("project_id") return str(project_id) if project_id is not None else None @@ -911,4 +895,4 @@ async def _top_news_authors(authors: list[dict[str, Any]]) -> list[TopAuthor]: ) for bucket in buckets if str(bucket.get("key", "")).casefold() in institution_authors - ][:TOP_AUTHOR_LIMIT] \ No newline at end of file + ][:TOP_AUTHOR_LIMIT] diff --git a/service/src/main/inse/dashboard/test_service.py b/service/src/main/inse/dashboard/test_service.py index b2bbd0f0..1e053c92 100644 --- a/service/src/main/inse/dashboard/test_service.py +++ b/service/src/main/inse/dashboard/test_service.py @@ -9,7 +9,6 @@ from sqlmodel import Session, SQLModel, create_engine from inse import config from inse.auth.model import AccessToken, Organization, UserRole from inse.dashboard.service import ( - DFG_INSTITUTION_FIELDS, get_dashboard_organization, get_dashboard_statistics, get_top_authors, @@ -141,7 +140,7 @@ async def test_top_authors_maps_works_and_dfg_project_aggregations(): { "_source": { "id": "ES1", - "project_id": "P1", + "project_id": "legacy-P1", "persons": [ {"person_id": 2, "full_name": "Grace Example"}, { @@ -154,7 +153,7 @@ async def test_top_authors_maps_works_and_dfg_project_aggregations(): { "_source": { "id": "ES2", - "project_id": "P2", + "project_id": "legacy-P2a", "persons": [ {"person_id": 2, "full_name": "Grace Example"}, {"person_id": 2, "full_name": "Grace Example"}, @@ -163,8 +162,8 @@ async def test_top_authors_maps_works_and_dfg_project_aggregations(): }, { "_source": { - "id": "ES3", - "project_id": "P2", + "id": "ES2", + "project_id": "legacy-P2b", "persons": [ {"person_id": 2, "full_name": "Grace Example"}, ], @@ -232,34 +231,21 @@ async def test_top_authors_maps_works_and_dfg_project_aggregations(): if call.kwargs["index"] == ESIndex.DFG_PROJECTS ] assert dfg_project_calls[0].kwargs["body"]["_source"] == [ - "id", - "project_id", - "persons", - *DFG_INSTITUTION_FIELDS, + "id", + "project_id", + "persons", ] - query = dfg_project_calls[0].kwargs["body"]["query"] - - assert query["bool"]["must"][0]["bool"]["minimum_should_match"] == 1 - assert query["bool"]["must"][0]["bool"]["should"][0]["bool"]["should"][0][ - "match" - ] == { - "Antragstellende Institution": { - "query": "Example Org", - "operator": "and", - } -} - - assert query["bool"]["must"][1] == { - "nested": { - "path": "persons", - "query": { - "terms": { - "persons.person_id": [2], - } + assert dfg_project_calls[0].kwargs["body"]["query"] == { + "nested": { + "path": "persons", + "query": { + "terms": { + "persons.person_id": [2], + } + }, }, } -} @pytest.mark.anyio -- 2.56.1 From 2d485263d1c444ae01635e1a9c83ec0dd4d0d63a Mon Sep 17 00:00:00 2001 From: spsaefan <117728614+spsaefan@users.noreply.github.com> Date: Fri, 24 Jul 2026 11:31:25 +0200 Subject: [PATCH 4/6] Improve DFG top author OpenAlex matching --- service/src/main/inse/dashboard/model.py | 1 + service/src/main/inse/dashboard/service.py | 295 +++++++++++++++++- .../src/main/inse/dashboard/test_service.py | 259 ++++++++++++++- 3 files changed, 545 insertions(+), 10 deletions(-) diff --git a/service/src/main/inse/dashboard/model.py b/service/src/main/inse/dashboard/model.py index c59f8028..bbd9f1b2 100644 --- a/service/src/main/inse/dashboard/model.py +++ b/service/src/main/inse/dashboard/model.py @@ -20,6 +20,7 @@ class DashboardStatisticValue(BaseModel): class TopAuthor(BaseModel): id: str | None = None + dfg_person_id: int | None = None name: str count: int diff --git a/service/src/main/inse/dashboard/service.py b/service/src/main/inse/dashboard/service.py index ee4e11e6..93cdcea8 100644 --- a/service/src/main/inse/dashboard/service.py +++ b/service/src/main/inse/dashboard/service.py @@ -1,5 +1,6 @@ import asyncio import logging +import re from datetime import datetime from typing import Any, Literal @@ -30,6 +31,10 @@ TOPIC_HEATMAP_LIMIT = 25 TOPIC_HEATMAP_YEARS = 5 WorksPeriod = Literal["all_time", "last_5_years"] logger = logging.getLogger(__name__) +ACADEMIC_TITLE_RE = re.compile( + r"^(?:(?:professor(?:in)?|prof|dr)(?:\.-[a-z]+)?\.?|rer\.|nat\.|med\.|ing\.)\s+", + re.IGNORECASE, +) DFG_INSTITUTION_FIELDS = [ "Antragstellende Institution", @@ -50,6 +55,34 @@ def _total(response: dict[str, Any]) -> int: return int(total or 0) +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 get_dashboard_organization( session: Session, access_token: AccessToken, @@ -709,11 +742,13 @@ async def _top_project_authors( page += 1 - institution_authors = { - author["name"].strip().casefold(): author - for author in authors - if author.get("name") - } + 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( ( @@ -727,14 +762,33 @@ async def _top_project_authors( ), ) + 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 = institution_authors.get( - dfg_name.casefold() + 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=( @@ -742,6 +796,7 @@ async def _top_project_authors( if matched_author else None ), + dfg_person_id=person_id, name=( matched_author["name"] if matched_author @@ -767,6 +822,230 @@ async def _top_project_authors( 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, @@ -797,7 +1076,7 @@ async def _dfg_project_author_hits( "query": { "terms": {"persons.person_id": sorted(person_ids)} }, - } + }, }, "sort": [ { diff --git a/service/src/main/inse/dashboard/test_service.py b/service/src/main/inse/dashboard/test_service.py index 1e053c92..ae0a99a4 100644 --- a/service/src/main/inse/dashboard/test_service.py +++ b/service/src/main/inse/dashboard/test_service.py @@ -202,21 +202,25 @@ async def test_top_authors_maps_works_and_dfg_project_aggregations(): assert result.works[0].model_dump() == { "id": "A1", + "dfg_person_id": None, "name": "Ada Example", "count": 42, } assert result.projects[0].model_dump() == { "id": "A2", + "dfg_person_id": 2, "name": "Grace Example", "count": 2, } assert result.patents[0].model_dump() == { "id": "A1", + "dfg_person_id": None, "name": "Ada Example", "count": 4, } assert result.news[0].model_dump() == { "id": "A1", + "dfg_person_id": None, "name": "Ada Example", "count": 6, } @@ -294,6 +298,7 @@ async def test_top_authors_keeps_dfg_project_authors_without_openalex_match(): assert result.projects[0].model_dump() == { "id": None, + "dfg_person_id": 9, "name": "Project Person", "count": 9, } @@ -363,6 +368,7 @@ async def test_top_authors_processes_all_dfg_project_pages(): assert result.projects[0].model_dump() == { "id": None, + "dfg_person_id": 9, "name": "Project Person", "count": 10001, } @@ -488,8 +494,255 @@ async def test_top_authors_matches_dfg_project_people_to_openalex_case_insensiti result = await get_top_authors(ORG_INSTITUTION_ID, "Example Org") assert [author.model_dump() for author in result.projects] == [ - {"id": "A1", "name": "Ada Example", "count": 1}, - {"id": None, "name": "DFG Person", "count": 1}, + {"id": "A1", "dfg_person_id": 1, "name": "Ada Example", "count": 1}, + {"id": None, "dfg_person_id": 2, "name": "DFG Person", "count": 1}, + ] + + +@pytest.mark.anyio +async def test_top_authors_links_dfg_project_people_by_title_stripped_name_or_orcid(): + async def search(**kwargs): + if kwargs["index"] == config.settings.openalex_works_search_index: + return { + "hits": { + "hits": [ + { + "_source": { + "doi": "https://doi.org/10.1/example", + "authorships": [ + { + "author": { + "id": "https://openalex.org/A5056038758", + "display_name": "G. Bacher", + } + } + ], + } + }, + { + "_source": { + "doi": "https://doi.org/10.2/example", + "authorships": [ + { + "author": { + "id": "https://openalex.org/A5056038758", + "display_name": "G. Bacher", + } + } + ], + } + }, + { + "_source": { + "doi": "https://doi.org/10.3/example", + "authorships": [ + { + "author": { + "id": "https://openalex.org/A5025875670", + "display_name": "Stephan Barcikowski", + } + } + ], + } + }, + { + "_source": { + "doi": "https://doi.org/10.4/example", + "authorships": [ + { + "author": { + "id": "https://openalex.org/A5025875670", + "display_name": "Stephan Barcikowski", + } + } + ], + } + }, + ] + } + } + if kwargs["index"] == ESIndex.OPENALEX_AUTHORS: + if kwargs.get("query") is not None: + return { + "hits": { + "hits": [ + { + "_source": { + "id": "https://openalex.org/A3", + "display_name": "Stephan Schulz", + "works_count": 1, + "counts_by_year": [], + } + } + ] + } + } + return { + "hits": { + "hits": [ + { + "_source": { + "id": "https://openalex.org/A5068103398", + "display_name": "U. Bovensiepen", + } + } + ] + } + } + if kwargs["index"] == ESIndex.DFG_PERSONS: + return { + "hits": { + "hits": [ + { + "_source": { + "person_id": 1, + "orcid_id": "0000-0002-1506-4491", + } + }, + { + "_source": { + "person_id": 3, + "orcid_id": "0000-0003-2896-4488", + } + }, + ] + } + } + if kwargs["index"] == ESIndex.DFG_PROJECTS: + if kwargs["body"].get("_source") == ["publications.doi"]: + return { + "hits": { + "hits": [ + { + "_source": { + "publications": [ + {"doi": "https://doi.org/10.1/example"} + ] + } + }, + { + "_source": { + "publications": [ + {"doi": "https://doi.org/10.2/example"} + ] + } + }, + { + "_source": { + "publications": [ + {"doi": "https://doi.org/10.3/example"}, + {"doi": "https://doi.org/10.4/example"}, + ] + } + }, + ] + } + } + return { + "hits": { + "total": {"value": 3}, + "hits": [ + { + "_source": { + "id": 1, + "project_id": None, + "persons": [ + { + "person_id": 1, + "full_name": "Professor Dr. Uwe Bovensiepen", + }, + { + "person_id": 2, + "full_name": "Professor Dr. Gerd Bacher", + }, + { + "person_id": 3, + "full_name": "Professor Dr. Stephan Schulz", + }, + { + "person_id": 4, + "full_name": "Professor Dr.-Ing. Stephan Barcikowski", + }, + ], + } + }, + { + "_source": { + "id": 2, + "project_id": None, + "persons": [ + { + "person_id": 1, + "full_name": "Professor Dr. Uwe Bovensiepen", + }, + { + "person_id": 2, + "full_name": "Professor Dr. Gerd Bacher", + }, + ], + } + }, + { + "_source": { + "id": 3, + "project_id": None, + "persons": [ + { + "person_id": 1, + "full_name": "Professor Dr. Uwe Bovensiepen", + }, + ], + } + }, + ], + } + } + return {"aggregations": {"authors": {"buckets": []}}} + + with patch( + "inse.dashboard.service.elasticsearch.search", + new=AsyncMock(side_effect=search), + ), patch( + "inse.dashboard.service.autocomplete_institutions_for_selector", + new=AsyncMock( + return_value=SimpleNamespace( + elements=[SimpleNamespace(id=101)] + ) + ), + ), patch( + "inse.dashboard.service.get_person_ids_by_institution_ids", + new=AsyncMock(return_value=[1, 2, 3, 4]), + ), patch( + "inse.dashboard.service.OrgPatentsSearchClient.top_authors_by_institution", + new=AsyncMock(return_value=[]), + ): + result = await get_top_authors(ORG_INSTITUTION_ID, "Example Org") + + assert [author.model_dump() for author in result.projects] == [ + { + "id": "A5068103398", + "dfg_person_id": 1, + "name": "U. Bovensiepen", + "count": 3, + }, + { + "id": "A5056038758", + "dfg_person_id": 2, + "name": "G. Bacher", + "count": 2, + }, + { + "id": "A3", + "dfg_person_id": 3, + "name": "Stephan Schulz", + "count": 1, + }, + { + "id": "A5025875670", + "dfg_person_id": 4, + "name": "Stephan Barcikowski", + "count": 1, + }, ] @@ -585,11 +838,13 @@ async def test_top_authors_can_rank_works_by_last_five_years(): assert result.works[0].model_dump() == { "id": "A2", + "dfg_person_id": None, "name": "Grace Example", "count": 16, } assert result.works[1].model_dump() == { "id": "A1", + "dfg_person_id": None, "name": "Ada Example", "count": 2, } -- 2.56.1 From 0b5c6bed37cfad3f3fb71c12196af64d23323416 Mon Sep 17 00:00:00 2001 From: spsaefan <117728614+spsaefan@users.noreply.github.com> Date: Fri, 24 Jul 2026 11:31:55 +0200 Subject: [PATCH 5/6] Use DFG person IDs for project --- .../inse/projects/projects_search_client.py | 12 ++++ service/src/main/inse/projects/service.py | 15 +---- .../main/inse/projects/test_projects_dfg.py | 60 +++++++++++++++++++ 3 files changed, 74 insertions(+), 13 deletions(-) diff --git a/service/src/main/inse/projects/projects_search_client.py b/service/src/main/inse/projects/projects_search_client.py index 3a0a7557..3f5911d2 100644 --- a/service/src/main/inse/projects/projects_search_client.py +++ b/service/src/main/inse/projects/projects_search_client.py @@ -584,6 +584,7 @@ async def search_dfg_projects( page: int, size: int, institution_ids: Optional[List[int]] = None, + person_ids: Optional[List[int]] = None, names: Optional[List[str]] = None, keywords: Optional[List[str]] = None, topic_ids: Optional[List[str]] = None, @@ -601,6 +602,7 @@ async def search_dfg_projects( page (int): The page number. size (int): The number of items per page. institution_ids (Optional[List[int]], optional): Institution IDs to filter by. + person_ids (Optional[List[int]], optional): Person IDs to filter by. names (Optional[List[str]], optional): Names to search for. keywords (Optional[List[str]], optional): Raw keywords to search in title/abstract/subject fields. Only used when `fuzzy=False` (or when no topic_ids are given). @@ -742,6 +744,16 @@ async def search_dfg_projects( if name_must_clauses: must_clauses.append({"bool": {"must": name_must_clauses}}) + if person_ids: + must_clauses.append( + { + "nested": { + "path": "persons", + "query": {"terms": {"persons.person_id": person_ids}}, + } + } + ) + if institution_ids: matching_person_ids = await get_person_ids_by_institution_ids( institution_ids=institution_ids diff --git a/service/src/main/inse/projects/service.py b/service/src/main/inse/projects/service.py index 86637a6f..7cf83d11 100644 --- a/service/src/main/inse/projects/service.py +++ b/service/src/main/inse/projects/service.py @@ -26,7 +26,7 @@ from inse.institutions.institutions_search_client import ( ) from inse.exceptions import NotFoundException from inse.persons.logic import get_author_name_by_id -from inse.projects.logic import get_dfg_author_names_by_ids, get_dfg_institution_names_by_ids +from inse.projects.logic import get_dfg_institution_names_by_ids from inse.works.logic import get_publication_dois_of_author from inse.models.projects_eu_cordis.horizon2020.h2020_project_details import H2020ProjectDetails from inse.models.projects_eu_cordis.horizon_europe.heu_project_details import HEUProjectDetails @@ -192,17 +192,6 @@ async def get_dfg_projects_by_author_id( if author_id and not author_name: logger.debug("No author name found for author_id=%s", author_id) - filter_names = ( - await get_dfg_author_names_by_ids(author_ids=author_filter_ids) - if author_filter_ids - else [] - ) - if author_filter_ids and not filter_names: - logger.debug( - "No author names found for author_filter_ids=%s", - author_filter_ids, - ) - if author_name: filter_names.append(author_name) @@ -216,6 +205,7 @@ async def get_dfg_projects_by_author_id( page=page, size=size, names=filter_names or [], + person_ids=author_filter_ids or [], institution_ids=institution_ids, keywords=keywords, topic_ids=topic_ids, @@ -413,4 +403,3 @@ async def search_cordis_eu_projects_for_author_id( ) return funding_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 801859e6..3b83eae7 100644 --- a/service/src/main/inse/projects/test_projects_dfg.py +++ b/service/src/main/inse/projects/test_projects_dfg.py @@ -1,4 +1,8 @@ +from unittest.mock import AsyncMock, patch + import pytest + +from inse.model import ESCluster, ESIndex from inse.projects import projects_search_client @pytest.mark.anyio @@ -35,3 +39,59 @@ async def test_get_dfg_project_by_id(): "Leibniz" in inst for inst in project.institutions ) + + +@pytest.mark.anyio +async def test_search_dfg_projects_filters_directly_by_person_ids(): + mocked_search = AsyncMock( + return_value={ + "hits": { + "total": {"value": 1}, + "hits": [ + { + "_id": "P1", + "_source": { + "id": "P1", + "title": "Example project", + "persons": [ + { + "person_id": 1739927, + "full_name": "Professor Dr. Uwe Bovensiepen", + } + ], + "subject_classifications": [], + }, + } + ], + } + } + ) + + with patch( + "inse.projects.projects_search_client.elasticsearch.search", + new=mocked_search, + ), patch( + "inse.projects.projects_search_client.get_openalex_topics_for_dfg_projects", + new=AsyncMock(return_value={}), + ), patch( + "inse.projects.projects_search_client.get_person_institutes", + new=AsyncMock(return_value={}), + ): + result = await projects_search_client.search_dfg_projects( + page=0, + size=10, + person_ids=[1739927], + ) + + assert result.total == 1 + call = mocked_search.await_args + assert call.kwargs["index"] == ESIndex.DFG_PROJECTS + assert call.kwargs["cluster"] == ESCluster.INSE + assert call.kwargs["body"]["query"]["bool"]["must"] == [ + { + "nested": { + "path": "persons", + "query": {"terms": {"persons.person_id": [1739927]}}, + } + } + ] -- 2.56.1 From f25c5cd22267589a02dc72cf3b105433786975c5 Mon Sep 17 00:00:00 2001 From: spsaefan <117728614+spsaefan@users.noreply.github.com> Date: Fri, 24 Jul 2026 11:32:14 +0200 Subject: [PATCH 6/6] Link DFG top authors to person pages --- webapp/src/app/api/model/topAuthor.ts | 2 +- .../dashboard/dashboard-statistics.service.ts | 1 + .../dashboard/dashboard.component.html | 3 +- .../modules/dashboard/dashboard.component.ts | 28 +++++++++++++++++++ 4 files changed, 32 insertions(+), 2 deletions(-) diff --git a/webapp/src/app/api/model/topAuthor.ts b/webapp/src/app/api/model/topAuthor.ts index 6a74fa91..8171a2af 100644 --- a/webapp/src/app/api/model/topAuthor.ts +++ b/webapp/src/app/api/model/topAuthor.ts @@ -11,7 +11,7 @@ export interface TopAuthor { id?: string | null; + dfg_person_id?: number | null; name: string; count: number; } - diff --git a/webapp/src/app/modules/dashboard/dashboard-statistics.service.ts b/webapp/src/app/modules/dashboard/dashboard-statistics.service.ts index 828fd7ee..6cdd29f1 100644 --- a/webapp/src/app/modules/dashboard/dashboard-statistics.service.ts +++ b/webapp/src/app/modules/dashboard/dashboard-statistics.service.ts @@ -25,6 +25,7 @@ export interface DashboardStatisticValue { export interface TopAuthor { id?: string | null; + dfg_person_id?: number | null; name: string; count: number; } diff --git a/webapp/src/app/modules/dashboard/dashboard.component.html b/webapp/src/app/modules/dashboard/dashboard.component.html index 25d79648..30b8febd 100644 --- a/webapp/src/app/modules/dashboard/dashboard.component.html +++ b/webapp/src/app/modules/dashboard/dashboard.component.html @@ -220,7 +220,8 @@ @if (entry.id) { {{ authorDisplayName(dataset, entry) }} diff --git a/webapp/src/app/modules/dashboard/dashboard.component.ts b/webapp/src/app/modules/dashboard/dashboard.component.ts index 22c575ea..3d78b84e 100644 --- a/webapp/src/app/modules/dashboard/dashboard.component.ts +++ b/webapp/src/app/modules/dashboard/dashboard.component.ts @@ -29,6 +29,7 @@ type TopAuthorDataset = { icon: string; entries: TopAuthor[]; stripAuthorTitle?: boolean; + projectAuthors?: boolean; }; @Component({ @@ -117,6 +118,7 @@ export class DashboardComponent implements OnInit { icon: 'account_tree', entries: this.topAuthors?.projects ?? [], stripAuthorTitle: true, + projectAuthors: true, }, { title: 'News', icon: 'article', entries: this.topAuthors?.news ?? [] }, ]; @@ -166,6 +168,32 @@ export class DashboardComponent implements OnInit { ); } + authorLink(dataset: TopAuthorDataset, entry: TopAuthor): string[] { + if (dataset.projectAuthors && entry.dfg_person_id) { + return ['/person', entry.id!, 'projects']; + } + + return ['/person', entry.id!, 'overview']; + } + + authorQueryParams( + dataset: TopAuthorDataset, + entry: TopAuthor, + ): Record | null { + if (!dataset.projectAuthors || !entry.dfg_person_id) { + return null; + } + + return { + project_type: 'dfg', + page: 0, + size: 10, + sort_by: 'title', + sort_direction: 'asc', + authorId: entry.dfg_person_id, + }; + } + organizationName(): string { return this.statistics?.organization_name ?? 'Ihre Organisation'; } -- 2.56.1