diff --git a/service/src/main/inse/dashboard/service.py b/service/src/main/inse/dashboard/service.py index ff80d646..ec1a9b8f 100644 --- a/service/src/main/inse/dashboard/service.py +++ b/service/src/main/inse/dashboard/service.py @@ -30,7 +30,6 @@ from inse.projects.model import ( ProjectsFilteringProperties, ProjectType, ) -from inse.works.v2 import service as works_v2_service from .institute_helper import get_openalex_institution from .model import ( @@ -177,17 +176,48 @@ def _project_overlap_filter( return {"bool": {"filter": filters}} if filters else None -def _date_period(period: DashboardPeriod, date_format: str) -> DashboardPeriod: +def _project_boundary_year_filter( + start_field: str, + end_field: str, + period: DashboardPeriod, + date_format: Literal["iso", "de", "year"], +) -> dict[str, Any] | None: from_year, to_year = period - if date_format == "iso": - return ( - f"{from_year}-01-01" if from_year is not None else None, - f"{to_year}-12-31" if to_year is not None else None, - ) - return ( - f"01.01.{from_year}" if from_year is not None else None, - f"31.12.{to_year}" if to_year is not None else None, - ) + filters: list[dict[str, Any]] = [] + + if from_year is not None: + if date_format == "year": + filters.append({"term": {start_field: from_year}}) + else: + first_day = ( + f"{from_year}-01-01" + if date_format == "iso" + else f"01.01.{from_year}" + ) + last_day = ( + f"{from_year}-12-31" + if date_format == "iso" + else f"31.12.{from_year}" + ) + filters.append( + {"range": {start_field: {"gte": first_day, "lte": last_day}}} + ) + + if to_year is not None: + if date_format == "year": + filters.append({"term": {end_field: to_year}}) + else: + first_day = ( + f"{to_year}-01-01" if date_format == "iso" else f"01.01.{to_year}" + ) + last_day = ( + f"{to_year}-12-31" if date_format == "iso" else f"31.12.{to_year}" + ) + filters.append( + {"range": {end_field: {"gte": first_day, "lte": last_day}}} + ) + + return {"bool": {"filter": filters}} if filters else None def get_dashboard_organization( @@ -257,17 +287,36 @@ async def get_dashboard_publications( last_year = period[1] if period[1] is not None else 2100 publication_years = list(range(first_year, last_year + 1)) - works = await works_v2_service.get_institution_works( - raw_oa_institution_id=_raw_institution_id(normalized_id), - page=0, - size=1, - publication_years=publication_years, + value = await elasticsearch.count( + index=ESIndex.OPENALEX_WORKS_WILDCARD, + query={ + "bool": { + "filter": [ + { + "nested": { + "path": "authorships", + "query": { + "nested": { + "path": "authorships.institutions", + "query": { + "term": { + "authorships.institutions.id": normalized_id + } + }, + } + }, + } + }, + {"terms": {"publication_year": publication_years}}, + ] + } + }, ) return DashboardStatisticValue( institution_id=normalized_id, organization_name=organization_name, - value=works.total, + value=value, ) @@ -396,10 +445,11 @@ async def get_dashboard_eu_project_statuses( today = datetime.now().date().isoformat() period = _dashboard_period(from_year, to_year) filters: list[dict[str, Any]] = [{"terms": {"id": sorted(project_ids)}}] - if period_filter := _project_overlap_filter( + if period_filter := _project_boundary_year_filter( "startDate", "endDate", - _date_period(period, "iso"), + period, + "iso", ): filters.append(period_filter) query = ( @@ -541,10 +591,11 @@ async def get_dashboard_bmbf_project_statuses( aliases = await _institution_aliases(normalized_id, organization_name) period = _dashboard_period(from_year, to_year) filters = [_alias_match_query("Zuwendungsempfänger", aliases)] - if period_filter := _project_overlap_filter( + if period_filter := _project_boundary_year_filter( "funding_start", "funding_end", - _date_period(period, "de"), + period, + "de", ): filters.append(period_filter) today = datetime.now().strftime("%d.%m.%Y") @@ -631,6 +682,7 @@ async def get_dashboard_dfg_projects( sort_by="id", sort_direction="asc", fuzzy=False, + skip_enrichment=True, ) return DashboardStatisticValue( institution_id=normalized_id, @@ -676,11 +728,11 @@ async def get_dashboard_dfg_project_statuses( } } ] - if period_filter := _project_overlap_filter( + if period_filter := _project_boundary_year_filter( "projects.funding_start", "projects.funding_end", period, - missing_end_is_ongoing=True, + "year", ): selected_project_filters.append(period_filter) diff --git a/service/src/main/inse/dashboard/test_service.py b/service/src/main/inse/dashboard/test_service.py index 305a27de..74be4583 100644 --- a/service/src/main/inse/dashboard/test_service.py +++ b/service/src/main/inse/dashboard/test_service.py @@ -9,8 +9,9 @@ from sqlmodel import Session, SQLModel, create_engine from inse import config from inse.auth.model import AccessToken, Organization, UserRole from inse.dashboard.service import ( - _openalex_work_authors_by_eu_projects, _get_dfg_project_ids_from_projects_service, + _openalex_work_authors_by_eu_projects, + _project_boundary_year_filter, _reconcile_project_status_counts, _top_news_authors, get_dashboard_bmbf_projects, @@ -50,6 +51,40 @@ def test_project_status_counts_match_authoritative_total(): assert _reconcile_project_status_counts(7, 4, 2, 3) == (2, 2, 3) +def test_project_status_period_uses_exact_boundary_years(): + assert _project_boundary_year_filter( + "startDate", "endDate", (2022, 2026), "iso" + ) == { + "bool": { + "filter": [ + { + "range": { + "startDate": {"gte": "2022-01-01", "lte": "2022-12-31"} + } + }, + { + "range": { + "endDate": {"gte": "2026-01-01", "lte": "2026-12-31"} + } + }, + ] + } + } + assert _project_boundary_year_filter( + "projects.funding_start", + "projects.funding_end", + (2022, 2026), + "year", + ) == { + "bool": { + "filter": [ + {"term": {"projects.funding_start": 2022}}, + {"term": {"projects.funding_end": 2026}}, + ] + } + } + + @pytest.mark.anyio async def test_top_news_authors_applies_dashboard_period(): response = { @@ -230,16 +265,16 @@ async def test_dashboard_statistics_counts_organization_data_and_all_projects(): @pytest.mark.anyio -async def test_dashboard_publications_uses_works_v2_only_for_period(): +async def test_dashboard_publications_uses_exact_es_count_for_period(): with patch( "inse.dashboard.service.institutions_v2_service.get_institution_by_id_or_raise", new=AsyncMock( return_value=Institution(id=ORG_INSTITUTION_ID, works_count=250) ), ) as mocked_get_institution, patch( - "inse.dashboard.service.works_v2_service.get_institution_works", - new=AsyncMock(return_value=SimpleNamespace(elements=[], total=22)), - ) as mocked_get_works: + "inse.dashboard.service.elasticsearch.count", + new=AsyncMock(return_value=22), + ) as mocked_count: all_time = await get_dashboard_publications( ORG_INSTITUTION_ID, "Example Org", @@ -257,12 +292,15 @@ async def test_dashboard_publications_uses_works_v2_only_for_period(): raw_oa_institution_id="I123", source=["id", "works_count"], ) - assert mocked_get_works.await_args_list[0].kwargs == { - "raw_oa_institution_id": "I123", - "page": 0, - "size": 1, - "publication_years": [2021, 2022], + mocked_count.assert_awaited_once() + count_call = mocked_count.await_args.kwargs + assert count_call["index"] == ESIndex.OPENALEX_WORKS_WILDCARD + filters = count_call["query"]["bool"]["filter"] + assert filters[0]["nested"]["path"] == "authorships" + assert filters[0]["nested"]["query"]["nested"]["query"] == { + "term": {"authorships.institutions.id": ORG_INSTITUTION_ID} } + assert filters[1] == {"terms": {"publication_year": [2021, 2022]}} @pytest.mark.anyio @@ -311,8 +349,9 @@ async def test_dashboard_dfg_projects_uses_projects_service_total(): mocked_get_projects.assert_awaited_once() call = mocked_get_projects.await_args assert call.kwargs["raw_oa_institution_id"] == "I123" - assert call.kwargs["funding_start_years"][-1] == "2022" - assert call.kwargs["funding_end_years"][0] == "2020" + assert call.kwargs["funding_start_years"] == ["2020"] + assert call.kwargs["funding_end_years"] == ["2022"] + assert call.kwargs["skip_enrichment"] is True assert call.kwargs["page"] == 0 assert call.kwargs["size"] == 1 diff --git a/service/src/main/inse/projects/projects_search_client.py b/service/src/main/inse/projects/projects_search_client.py index 3b80b959..05911790 100644 --- a/service/src/main/inse/projects/projects_search_client.py +++ b/service/src/main/inse/projects/projects_search_client.py @@ -599,7 +599,6 @@ async def search_dfg_projects( body["sort"] = [sort_config] # print(f"Executing DFG project search with body: {json.dumps(body, indent=2)}") # === Execute Search === - print(f"Executing DFG project search with body: {json.dumps(body, indent=2)}") response = await elasticsearch.search( index=ESIndex.DFG_PROJECTS, body=body, @@ -611,6 +610,9 @@ async def search_dfg_projects( if skip_enrichment: return _complete_response_to_dfg_project_page(response, page, size) + if not hits: + return _complete_response_to_dfg_project_page(response, page, size) + project_ids = [hit["_source"]["id"] for hit in hits] topic_lookup = await get_openalex_topics_for_dfg_projects(project_ids=project_ids) @@ -647,7 +649,6 @@ async def search_dfg_projects( # person["institute_name_en"] = institute.get("institute_name_en") # person["address_country_de"] = institute.get("address_country_de") # person["address_country_en"] = institute.get("address_country_en") - print("ENRIECHED",source.get("institutions", [])) return _complete_response_to_dfg_project_page(response, page, size) def _complete_response_to_dfg_project_page( diff --git a/service/src/main/inse/projects/test_projects_dfg.py b/service/src/main/inse/projects/test_projects_dfg.py index f9eb82b9..bc331c62 100644 --- a/service/src/main/inse/projects/test_projects_dfg.py +++ b/service/src/main/inse/projects/test_projects_dfg.py @@ -1,4 +1,7 @@ +from unittest.mock import AsyncMock, patch + import pytest + from inse.projects import projects_search_client @@ -20,6 +23,33 @@ async def test_search_dfg_projects(): for name in element.names ) + +@pytest.mark.anyio +async def test_search_dfg_projects_returns_empty_page_without_enrichment_crash(): + response = { + "hits": { + "total": {"value": 0}, + "hits": [], + } + } + with patch( + "inse.projects.projects_search_client.elasticsearch.search", + new=AsyncMock(return_value=response), + ) as mocked_search: + result = await projects_search_client.search_dfg_projects( + page=0, + size=1, + funding_start_years=["2022"], + funding_end_years=["2026"], + ) + + assert result.total == 0 + assert result.elements == [] + query = mocked_search.await_args.kwargs["body"]["query"] + assert {"terms": {"funding_start": ["2022"]}} in query["bool"]["must"] + assert {"terms": {"funding_end": ["2026"]}} in query["bool"]["must"] + + @pytest.mark.anyio async def test_get_dfg_project_by_id(): # Get by ID of the project we found or a known one