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] 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():