diff --git a/service/src/main/inse/dashboard/service.py b/service/src/main/inse/dashboard/service.py index 2a3e37f7..4f1fe83d 100644 --- a/service/src/main/inse/dashboard/service.py +++ b/service/src/main/inse/dashboard/service.py @@ -12,6 +12,7 @@ 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 @@ -240,20 +241,26 @@ async def get_dashboard_publications( ) -> DashboardStatisticValue: normalized_id = _normalize_institution_id(institution_id) period = _dashboard_period(from_year, to_year) - filters = [] - if year_filter := _publication_year_filter(period): - filters.append(year_filter) - query = _institution_works_query(normalized_id) - if filters: - query = {"bool": {"must": [query], "filter": filters}} - response = await elasticsearch.search( - index=config.settings.openalex_works_search_index, - query=query, - size=0, - track_total_hits=True, - cluster=ESCluster.NES, + 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]) + ) + ) + return DashboardStatisticValue( + institution_id=normalized_id, + organization_name=organization_name, + value=value, ) - return _dashboard_statistic_value(normalized_id, organization_name, response) async def get_dashboard_persons( @@ -2226,12 +2233,30 @@ async def _top_eu_project_publication_authors( cluster=ESCluster.NES, ) - return _openalex_work_authors_by_eu_projects( + 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( @@ -2321,6 +2346,7 @@ def _openalex_work_authors_by_eu_projects( 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. @@ -2356,14 +2382,58 @@ def _openalex_work_authors_by_eu_projects( key=lambda item: (-len(item[1]), author_names.get(item[0], ""), item[0]), ) - return [ + 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[:TOP_AUTHOR_LIMIT] + 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: + """Uses the same author-only EU project search as the person detail page.""" + 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=( + [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, + sort_by="title", + sort_direction="asc", + fuzzy=False, + skip_enrichment=True, + ) + return projects.total def _normalize_author_id(value: Any) -> str | None: diff --git a/service/src/main/inse/dashboard/test_service.py b/service/src/main/inse/dashboard/test_service.py index 53f1dc02..630f8121 100644 --- a/service/src/main/inse/dashboard/test_service.py +++ b/service/src/main/inse/dashboard/test_service.py @@ -17,12 +17,14 @@ from inse.dashboard.service import ( get_dashboard_eu_projects, 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.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 @@ -165,6 +167,9 @@ async def test_dashboard_statistics_counts_organization_data_and_all_projects(): 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)), ): result = await get_dashboard_statistics( ORG_INSTITUTION_ID, @@ -182,15 +187,41 @@ async def test_dashboard_statistics_counts_organization_data_and_all_projects(): "bmbf_projects": 5, } - publication_call = next( - call - for call in mocked_search.await_args_list - if call.kwargs["index"] == config.settings.openalex_works_search_index +@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), + ], ) - assert publication_call.kwargs["query"]["nested"]["query"]["term"] == { - "authorships.institutions.id": ORG_INSTITUTION_ID + + with patch( + "inse.dashboard.service.institutions_v2_service.get_institution_by_id_or_raise", + new=AsyncMock(return_value=institution), + ) as mocked_get_institution: + all_time = await get_dashboard_publications( + ORG_INSTITUTION_ID, + "Example Org", + ) + selected_period = await get_dashboard_publications( + ORG_INSTITUTION_ID, + "Example Org", + from_year=2021, + to_year=2022, + ) + + 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"], } + @pytest.mark.anyio async def test_dashboard_persons_uses_persons_service_for_organization(): response = CustomAuthorsListResponse( @@ -407,16 +438,9 @@ async def test_top_authors_maps_works_patents_news_and_eu_projects(): return {"aggregations": {"people": {"buckets": []}}} - 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"]), - ), patch( - "inse.dashboard.service.projects_service.search_eu_cordis_projects", - new=AsyncMock( - return_value=EuCordisProjectSearchPage( + async def eu_projects(**kwargs): + if kwargs.get("raw_oa_institution_id"): + return EuCordisProjectSearchPage( elements=[ EuCordisProjectSummary(id="P1", project_type=EuCordisProjectType.FP7), EuCordisProjectSummary(id="P2", project_type=EuCordisProjectType.H2020), @@ -426,7 +450,22 @@ async def test_top_authors_maps_works_patents_news_and_eu_projects(): page=0, size=1000, ) - ), + return EuCordisProjectSearchPage( + elements=[], + total={"A1": 3, "A2": 4}[kwargs["author_id"]], + page=0, + size=1, + ) + + 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"]), + ), 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( @@ -451,8 +490,8 @@ async def test_top_authors_maps_works_patents_news_and_eu_projects(): "count": 4, } assert [author.model_dump() for author in result.eu_projects] == [ - {"id": "A2", "name": "Grace Example", "count": 2}, - {"id": "A1", "name": "Ada Example", "count": 1}, + {"id": "A2", "name": "Grace Example", "count": 4}, + {"id": "A1", "name": "Ada Example", "count": 3}, ] assert result.news[0].model_dump() == { "id": "A1", @@ -711,16 +750,9 @@ async def test_top_eu_project_authors_count_filtered_projects_by_stable_author_i } return {"aggregations": {"authors": {"buckets": []}}} - 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( - return_value=EuCordisProjectSearchPage( + async def eu_projects(**kwargs): + if kwargs.get("raw_oa_institution_id"): + return EuCordisProjectSearchPage( elements=[ EuCordisProjectSummary(id="P1", project_type=EuCordisProjectType.FP7), EuCordisProjectSummary(id="P2", project_type=EuCordisProjectType.H2020), @@ -729,7 +761,22 @@ async def test_top_eu_project_authors_count_filtered_projects_by_stable_author_i page=0, size=1000, ) - ), + return EuCordisProjectSearchPage( + elements=[], + total={"A1": 4, "A2": 1}[kwargs["author_id"]], + page=0, + 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=[]), @@ -740,7 +787,7 @@ 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": 2}, + {"id": "A1", "name": "Ada Example", "count": 4}, {"id": "A2", "name": "Grace Example", "count": 1}, ]