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 1/3] 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 2/3] 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 d48435b948f794468480eeda3c3278f19b44186b Mon Sep 17 00:00:00 2001 From: Farajollahi Date: Thu, 6 Aug 2026 18:12:38 +0200 Subject: [PATCH 3/3] 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}], } ] },