diff --git a/service/src/main/inse/dashboard/router.py b/service/src/main/inse/dashboard/router.py index 403bcb9d..611e3a4e 100644 --- a/service/src/main/inse/dashboard/router.py +++ b/service/src/main/inse/dashboard/router.py @@ -60,6 +60,8 @@ async def dashboard_statistics( response_model=DashboardStatisticValue, ) async def dashboard_publications( + from_year: int | None = Query(default=None, ge=1900, le=2100), + to_year: int | None = Query(default=None, ge=1900, le=2100), session: Session = Depends(get_session), access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep, ) -> DashboardStatisticValue: @@ -67,6 +69,8 @@ async def dashboard_publications( return await get_dashboard_publications( organization.openalex_institution_id, organization.name, + from_year=from_year, + to_year=to_year, ) @@ -92,6 +96,8 @@ async def dashboard_persons( response_model=DashboardStatisticValue, ) async def dashboard_patents( + from_year: int | None = Query(default=None, ge=1900, le=2100), + to_year: int | None = Query(default=None, ge=1900, le=2100), session: Session = Depends(get_session), access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep, ) -> DashboardStatisticValue: @@ -99,6 +105,8 @@ async def dashboard_patents( return await get_dashboard_patents( organization.openalex_institution_id, organization.name, + from_year=from_year, + to_year=to_year, ) @@ -108,6 +116,8 @@ async def dashboard_patents( response_model=DashboardStatisticValue, ) async def dashboard_eu_projects( + from_year: int | None = Query(default=None, ge=1900, le=2100), + to_year: int | None = Query(default=None, ge=1900, le=2100), session: Session = Depends(get_session), access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep, ) -> DashboardStatisticValue: @@ -115,6 +125,8 @@ async def dashboard_eu_projects( return await get_dashboard_eu_projects( organization.openalex_institution_id, organization.name, + from_year=from_year, + to_year=to_year, ) @@ -124,6 +136,8 @@ async def dashboard_eu_projects( response_model=EuProjectStatusStatistics, ) async def dashboard_eu_project_statuses( + from_year: int | None = Query(default=None, ge=1900, le=2100), + to_year: int | None = Query(default=None, ge=1900, le=2100), session: Session = Depends(get_session), access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep, ) -> EuProjectStatusStatistics: @@ -131,6 +145,8 @@ async def dashboard_eu_project_statuses( return await get_dashboard_eu_project_statuses( organization.openalex_institution_id, organization.name, + from_year=from_year, + to_year=to_year, ) @@ -140,6 +156,8 @@ async def dashboard_eu_project_statuses( response_model=DashboardStatisticValue, ) async def dashboard_bmbf_projects( + from_year: int | None = Query(default=None, ge=1900, le=2100), + to_year: int | None = Query(default=None, ge=1900, le=2100), session: Session = Depends(get_session), access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep, ) -> DashboardStatisticValue: @@ -147,6 +165,8 @@ async def dashboard_bmbf_projects( return await get_dashboard_bmbf_projects( organization.openalex_institution_id, organization.name, + from_year=from_year, + to_year=to_year, ) @@ -156,6 +176,8 @@ async def dashboard_bmbf_projects( response_model=BmbfProjectStatusStatistics, ) async def dashboard_bmbf_project_statuses( + from_year: int | None = Query(default=None, ge=1900, le=2100), + to_year: int | None = Query(default=None, ge=1900, le=2100), session: Session = Depends(get_session), access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep, ) -> BmbfProjectStatusStatistics: @@ -163,6 +185,8 @@ async def dashboard_bmbf_project_statuses( return await get_dashboard_bmbf_project_statuses( organization.openalex_institution_id, organization.name, + from_year=from_year, + to_year=to_year, ) @@ -172,6 +196,8 @@ async def dashboard_bmbf_project_statuses( response_model=DashboardStatisticValue, ) async def dashboard_dfg_projects( + from_year: int | None = Query(default=None, ge=1900, le=2100), + to_year: int | None = Query(default=None, ge=1900, le=2100), session: Session = Depends(get_session), access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep, ) -> DashboardStatisticValue: @@ -179,6 +205,8 @@ async def dashboard_dfg_projects( return await get_dashboard_dfg_projects( organization.openalex_institution_id, organization.name, + from_year=from_year, + to_year=to_year, ) @@ -188,6 +216,8 @@ async def dashboard_dfg_projects( response_model=DfgProjectTopics, ) async def dashboard_dfg_project_topics( + from_year: int | None = Query(default=None, ge=1900, le=2100), + to_year: int | None = Query(default=None, ge=1900, le=2100), session: Session = Depends(get_session), access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep, ) -> DfgProjectTopics: @@ -195,6 +225,8 @@ async def dashboard_dfg_project_topics( return await get_dashboard_dfg_topics( organization.openalex_institution_id, organization.name, + from_year=from_year, + to_year=to_year, ) @@ -208,6 +240,8 @@ async def dashboard_top_authors( default="all_time", pattern="^(all_time|last_5_years)$", ), + from_year: int | None = Query(default=None, ge=1900, le=2100), + to_year: int | None = Query(default=None, ge=1900, le=2100), session: Session = Depends(get_session), access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep, ) -> TopAuthorStatistics: @@ -216,6 +250,8 @@ async def dashboard_top_authors( organization.openalex_institution_id, organization.name, works_period=works_period, + from_year=from_year, + to_year=to_year, ) diff --git a/service/src/main/inse/dashboard/service.py b/service/src/main/inse/dashboard/service.py index b71a9609..d855b91a 100644 --- a/service/src/main/inse/dashboard/service.py +++ b/service/src/main/inse/dashboard/service.py @@ -43,8 +43,8 @@ TOPIC_HEATMAP_LIMIT = 25 TOPIC_HEATMAP_SUBFIELD_LIMIT = 100 TOPIC_HEATMAP_TOPIC_LIMIT = 100 TOPIC_WORD_CLOUD_LIMIT = 30 -TOPIC_HEATMAP_YEARS = 5 WorksPeriod = Literal["all_time", "last_5_years"] +DashboardPeriod = tuple[int | None, int | None] logger = logging.getLogger(__name__) @@ -89,6 +89,68 @@ def _total(response: dict[str, Any]) -> int: return int(total or 0) +def _dashboard_period( + from_year: int | None = None, + to_year: int | None = None, +) -> DashboardPeriod: + if from_year is not None and to_year is not None and from_year > to_year: + raise HTTPException( + status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, + detail="from_year must be less than or equal to to_year.", + ) + return from_year, to_year + + +def _publication_year_filter(period: DashboardPeriod) -> dict[str, Any] | None: + from_year, to_year = period + year_range: dict[str, int] = {} + if from_year is not None: + year_range["gte"] = from_year + if to_year is not None: + year_range["lte"] = to_year + return {"range": {"publication_year": year_range}} if year_range else None + + +def _project_overlap_filter( + start_field: str, + end_field: str, + period: DashboardPeriod, + *, + missing_end_is_ongoing: bool = False, +) -> dict[str, Any] | None: + from_year, to_year = period + filters: list[dict[str, Any]] = [] + if to_year is not None: + filters.append({"range": {start_field: {"lte": to_year}}}) + if from_year is not None: + end_filter: dict[str, Any] = {"range": {end_field: {"gte": from_year}}} + if missing_end_is_ongoing: + end_filter = { + "bool": { + "should": [ + end_filter, + {"bool": {"must_not": {"exists": {"field": end_field}}}}, + ], + "minimum_should_match": 1, + } + } + filters.append(end_filter) + return {"bool": {"filter": filters}} if filters else None + + +def _date_period(period: DashboardPeriod, date_format: str) -> DashboardPeriod: + 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, + ) + + def get_dashboard_organization( session: Session, access_token: AccessToken, @@ -136,11 +198,20 @@ async def get_dashboard_statistics( async def get_dashboard_publications( institution_id: str, organization_name: str, + from_year: int | None = None, + to_year: int | None = None, ) -> 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=_institution_works_query(normalized_id), + query=query, size=0, track_total_hits=True, cluster=ESCluster.NES, @@ -166,12 +237,17 @@ async def get_dashboard_persons( async def get_dashboard_patents( institution_id: str, organization_name: str, + from_year: int | None = None, + to_year: int | None = None, ) -> DashboardStatisticValue: normalized_id = _normalize_institution_id(institution_id) + period = _dashboard_period(from_year, to_year) _, total = await OrgPatentsSearchClient().search_by_institution( normalized_id, page=0, size=0, + from_year=period[0], + to_year=period[1], ) return DashboardStatisticValue( institution_id=normalized_id, @@ -183,9 +259,26 @@ async def get_dashboard_patents( async def get_dashboard_eu_projects( institution_id: str, organization_name: str, + from_year: int | None = None, + to_year: int | None = None, ) -> DashboardStatisticValue: normalized_id = _normalize_institution_id(institution_id) aliases = await _institution_aliases(normalized_id, organization_name) + period = _dashboard_period(from_year, to_year) + period_filter = _project_overlap_filter( + "startDate", + "endDate", + _date_period(period, "iso"), + ) + if period_filter: + project_ids = await _eu_project_ids_for_aliases(aliases) + value = await _count_eu_projects_in_period(project_ids, period_filter) + return DashboardStatisticValue( + institution_id=normalized_id, + organization_name=organization_name, + value=value, + ) + response = await elasticsearch.search( index=ESIndex.CORDIS_EU_ORGANIZATIONS_WILDCARD, body={ @@ -215,21 +308,12 @@ async def get_dashboard_eu_projects( async def get_dashboard_eu_project_statuses( institution_id: str, organization_name: str, + from_year: int | None = None, + to_year: int | None = None, ) -> EuProjectStatusStatistics: normalized_id = _normalize_institution_id(institution_id) aliases = await _institution_aliases(normalized_id, organization_name) - project_ids: set[str] = set() - - async for hit in elasticsearch.scan( - index=str(ESIndex.CORDIS_EU_ORGANIZATIONS_WILDCARD), - query=_eu_organization_query(aliases), - source=["projectID"], - page_size=1000, - cluster=ESCluster.INSE, - ): - project_id = hit.get("_source", {}).get("projectID") - if project_id is not None: - project_ids.add(str(project_id)) + project_ids = await _eu_project_ids_for_aliases(aliases) if not project_ids: return EuProjectStatusStatistics( @@ -241,11 +325,24 @@ 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( + "startDate", + "endDate", + _date_period(period, "iso"), + ): + filters.append(period_filter) + query = ( + {"terms": {"id": sorted(project_ids)}} + if len(filters) == 1 + else {"bool": {"filter": filters}} + ) response = await elasticsearch.search( index=ESIndex.CORDIS_EU_PROJECTS_WILDCARD, body={ "size": 0, - "query": {"terms": {"id": sorted(project_ids)}}, + "query": query, "aggs": { "ongoing": { "filter": { @@ -295,12 +392,22 @@ def _project_status_count(aggregations: dict[str, Any], status_name: str) -> int async def get_dashboard_bmbf_projects( institution_id: str, organization_name: str, + from_year: int | None = None, + to_year: int | None = None, ) -> DashboardStatisticValue: normalized_id = _normalize_institution_id(institution_id) 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( + "funding_start", + "funding_end", + _date_period(period, "de"), + ): + filters.append(period_filter) response = await elasticsearch.search( index=ESIndex.PROJECTS_BUND_V1, - query=_alias_match_query("Zuwendungsempfänger", aliases), + query=filters[0] if len(filters) == 1 else {"bool": {"filter": filters}}, size=0, track_total_hits=True, cluster=ESCluster.INSE, @@ -311,15 +418,25 @@ async def get_dashboard_bmbf_projects( async def get_dashboard_bmbf_project_statuses( institution_id: str, organization_name: str, + from_year: int | None = None, + to_year: int | None = None, ) -> BmbfProjectStatusStatistics: normalized_id = _normalize_institution_id(institution_id) 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( + "funding_start", + "funding_end", + _date_period(period, "de"), + ): + filters.append(period_filter) today = datetime.now().strftime("%d.%m.%Y") response = await elasticsearch.search( index=ESIndex.PROJECTS_BUND_V1, body={ "size": 0, - "query": _alias_match_query("Zuwendungsempfänger", aliases), + "query": filters[0] if len(filters) == 1 else {"bool": {"filter": filters}}, "aggs": _project_status_filter_aggregations( start_field="funding_start", end_field="funding_end", @@ -362,9 +479,15 @@ def _project_status_filter_aggregations( async def get_dashboard_dfg_projects( institution_id: str, organization_name: str, + from_year: int | None = None, + to_year: int | None = None, ) -> DashboardStatisticValue: normalized_id = _normalize_institution_id(institution_id) - project_ids = await _get_dfg_project_ids_for_institution(normalized_id) + project_ids = await _get_dfg_project_ids_for_institution( + normalized_id, + from_year=from_year, + to_year=to_year, + ) return DashboardStatisticValue( institution_id=normalized_id, organization_name=organization_name, @@ -375,9 +498,15 @@ async def get_dashboard_dfg_projects( async def get_dashboard_dfg_topics( institution_id: str, organization_name: str, + from_year: int | None = None, + to_year: int | None = None, ) -> DfgProjectTopics: normalized_id = _normalize_institution_id(institution_id) - project_ids = await _get_dfg_project_ids_for_institution(normalized_id) + project_ids = await _get_dfg_project_ids_for_institution( + normalized_id, + from_year=from_year, + to_year=to_year, + ) topics: dict[str, dict[str, Any]] = {} matched_project_ids: set[str] = set() @@ -434,7 +563,10 @@ async def get_dashboard_dfg_topics( async def _get_dfg_project_ids_for_institution( institution_id: str, + from_year: int | None = None, + to_year: int | None = None, ) -> list[str]: + period = _dashboard_period(from_year, to_year) institution = await get_openalex_institution(institution_id) institution_names = _openalex_institution_names(institution) @@ -491,7 +623,7 @@ async def _get_dfg_project_ids_for_institution( }, cluster=ESCluster.INSE, ) - return [ + project_ids = [ str(bucket["key"]) for bucket in ( projects_response.get("aggregations", {}) @@ -502,6 +634,106 @@ async def _get_dfg_project_ids_for_institution( ) if bucket.get("key") is not None ] + return await _filter_dfg_project_ids_by_period(project_ids, period) + + +async def _eu_project_ids_for_aliases(aliases: list[str]) -> set[str]: + project_ids: set[str] = set() + async for hit in elasticsearch.scan( + index=str(ESIndex.CORDIS_EU_ORGANIZATIONS_WILDCARD), + query=_eu_organization_query(aliases), + source=["projectID"], + page_size=1000, + cluster=ESCluster.INSE, + ): + project_id = hit.get("_source", {}).get("projectID") + if project_id is not None: + project_ids.add(str(project_id)) + return project_ids + + +async def _count_eu_projects_in_period( + project_ids: set[str], + period_filter: dict[str, Any], +) -> int: + if not project_ids: + return 0 + response = await elasticsearch.search( + index=ESIndex.CORDIS_EU_PROJECTS_WILDCARD, + body={ + "size": 0, + "query": { + "bool": { + "filter": [ + {"terms": {"id": sorted(project_ids)}}, + period_filter, + ] + } + }, + "aggs": {"projects": {"cardinality": {"field": "id"}}}, + }, + cluster=ESCluster.INSE, + ) + return int( + response.get("aggregations", {}) + .get("projects", {}) + .get("value", 0) + ) + + +async def _filter_dfg_project_ids_by_period( + project_ids: list[str], + period: DashboardPeriod, +) -> list[str]: + period_filter = _project_overlap_filter( + "funding_start", + "funding_end", + period, + missing_end_is_ongoing=True, + ) + if not project_ids or not period_filter: + return project_ids + + numeric_project_ids = [ + int(project_id) + for project_id in project_ids + if str(project_id).isdigit() + ] + if not numeric_project_ids: + return [] + + response = await elasticsearch.search( + index=ESIndex.DFG_PROJECTS, + body={ + "size": 0, + "query": { + "bool": { + "filter": [ + {"terms": {"id": numeric_project_ids}}, + period_filter, + ] + } + }, + "aggs": { + "project_ids": { + "terms": { + "field": "id", + "size": len(numeric_project_ids), + } + } + }, + }, + cluster=ESCluster.INSE, + ) + return [ + str(bucket["key"]) + for bucket in ( + response.get("aggregations", {}) + .get("project_ids", {}) + .get("buckets", []) + ) + if bucket.get("key") is not None + ] def _dashboard_statistic_value( @@ -597,15 +829,23 @@ async def get_top_authors( institution_id: str, organization_name: str, works_period: WorksPeriod = "all_time", + from_year: int | None = None, + to_year: int | None = None, ) -> TopAuthorStatistics: normalized_id = _normalize_institution_id(institution_id) + if from_year is None and to_year is None and works_period == "last_5_years": + from_year = datetime.now().year - 4 + to_year = datetime.now().year + period = _dashboard_period(from_year, to_year) authors = await _safe_institution_authors(normalized_id) - works = _top_work_authors(authors, works_period) + works = _top_work_authors(authors, period) projects = await _safe_top_authors( "projects", _top_project_authors( authors=authors, organization_name=organization_name, + from_year=period[0], + to_year=period[1], ), ) eu_projects = await _safe_top_authors( @@ -614,7 +854,11 @@ async def get_top_authors( ) patents = await _safe_top_authors( "patents", - _top_patent_authors(normalized_id), + _top_patent_authors( + normalized_id, + from_year=period[0], + to_year=period[1], + ), ) news = await _safe_top_authors( "news", @@ -638,15 +882,16 @@ async def get_topic_heatmap( limit: int = TOPIC_HEATMAP_LIMIT, ) -> TopicHeatmap: normalized_id = _normalize_institution_id(institution_id) - current_year = datetime.now().year - effective_to_year = to_year or current_year - effective_from_year = from_year or (effective_to_year - TOPIC_HEATMAP_YEARS + 1) - if effective_from_year > effective_to_year: - raise HTTPException( - status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, - detail="from_year must be less than or equal to to_year.", - ) - years = list(range(effective_from_year, effective_to_year + 1)) + period = _dashboard_period(from_year, to_year) + filters: list[dict[str, Any]] = [] + if year_filter := _publication_year_filter(period): + filters.append(year_filter) + years = ( + list(range(from_year, to_year + 1)) + if from_year is not None and to_year is not None + else [] + ) + year_bucket_size = len(years) if years else 300 response = await elasticsearch.search( index=config.settings.openalex_works_search_index, @@ -655,23 +900,14 @@ async def get_topic_heatmap( "query": { "bool": { "must": [_institution_works_query(normalized_id)], - "filter": [ - { - "range": { - "publication_year": { - "gte": effective_from_year, - "lte": effective_to_year, - } - } - } - ], + "filter": filters, } }, "aggs": { "publication_years": { "terms": { "field": "publication_year", - "size": len(years), + "size": year_bucket_size, "order": {"_key": "asc"}, } }, @@ -700,7 +936,7 @@ async def get_topic_heatmap( "by_year": { "terms": { "field": "publication_year", - "size": len(years), + "size": year_bucket_size, "order": {"_key": "asc"}, } } @@ -757,6 +993,8 @@ async def get_topic_heatmap( cluster=ESCluster.NES, ) year_totals = _year_totals(response) + if not years: + years = sorted(year_totals) buckets = ( response.get("aggregations", {}) .get("topics_nested", {}) @@ -786,13 +1024,8 @@ async def get_topic_word_cloud( ) -> TopicWordCloud: normalized_institution_id = _normalize_institution_id(institution_id) filters: list[dict[str, Any]] = [] - if from_year is not None or to_year is not None: - year_range: dict[str, int] = {} - if from_year is not None: - year_range["gte"] = from_year - if to_year is not None: - year_range["lte"] = to_year - filters.append({"range": {"publication_year": year_range}}) + if year_filter := _publication_year_filter(_dashboard_period(from_year, to_year)): + filters.append(year_filter) response = await elasticsearch.search( index=config.settings.openalex_works_search_index, @@ -1011,15 +1244,14 @@ def _short_author_id(value: str) -> str: def _top_work_authors( authors: list[dict[str, Any]], - works_period: WorksPeriod, + period: DashboardPeriod, ) -> list[TopAuthor]: - if works_period == "last_5_years": - from_year = datetime.now().year - 4 + if period != (None, None): ranked_authors = sorted( ( { **author, - "selected_works_count": _works_count_since(author, from_year), + "selected_works_count": _works_count_in_period(author, period), } for author in authors ), @@ -1043,11 +1275,15 @@ def _top_work_authors( ] -def _works_count_since(author: dict[str, Any], from_year: int) -> int: +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 int(item.get("year", 0) or 0) >= from_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) + ) ) @@ -1089,7 +1325,10 @@ async def _institution_authors(institution_id: str) -> list[dict[str, Any]]: async def _top_project_authors( authors: list[dict[str, Any]], organization_name: str, + from_year: int | None = None, + to_year: int | None = None, ) -> list[TopAuthor]: + period = _dashboard_period(from_year, to_year) institution_ids = await _dfg_institution_ids_for_organization( organization_name=organization_name, ) @@ -1132,6 +1371,7 @@ async def _top_project_authors( page=page, size=size, person_ids=selected_person_ids, + period=period, ) if not project_hits: @@ -1482,7 +1722,25 @@ async def _dfg_project_author_hits( page: int, size: int, person_ids: set[int], + period: DashboardPeriod = (None, None), ) -> tuple[list[dict[str, Any]], int]: + person_query = { + "nested": { + "path": "persons", + "query": {"terms": {"persons.person_id": sorted(person_ids)}}, + }, + } + period_filter = _project_overlap_filter( + "funding_start", + "funding_end", + period, + missing_end_is_ongoing=True, + ) + query = ( + {"bool": {"filter": [person_query, period_filter]}} + if period_filter + else person_query + ) response = await elasticsearch.search( index=ESIndex.DFG_PROJECTS, body={ @@ -1493,12 +1751,7 @@ async def _dfg_project_author_hits( "project_id", "persons", ], - "query": { - "nested": { - "path": "persons", - "query": {"terms": {"persons.person_id": sorted(person_ids)}}, - }, - }, + "query": query, "sort": [ { "id": { @@ -1543,11 +1796,17 @@ def _dfg_project_id(project: dict[str, Any]) -> str | None: return str(project_id) if project_id is not None else None -async def _top_patent_authors(institution_id: str) -> list[TopAuthor]: +async def _top_patent_authors( + institution_id: str, + from_year: int | None = None, + to_year: int | None = None, +) -> list[TopAuthor]: client = OrgPatentsSearchClient() authors = await client.top_authors_by_institution( institution_id=institution_id, size=TOP_AUTHOR_LIMIT, + from_year=from_year, + to_year=to_year, ) return [ TopAuthor( diff --git a/service/src/main/inse/dashboard/test_service.py b/service/src/main/inse/dashboard/test_service.py index df9f6e62..182c0162 100644 --- a/service/src/main/inse/dashboard/test_service.py +++ b/service/src/main/inse/dashboard/test_service.py @@ -17,6 +17,7 @@ from inse.dashboard.service import ( get_dashboard_dfg_topics, get_dashboard_eu_project_statuses, get_dashboard_patents, + get_dashboard_publications, get_dashboard_statistics, get_top_authors, get_topic_heatmap, @@ -46,7 +47,36 @@ async def test_dashboard_patents_uses_org_patent_total(): "organization_name": "Example Org", "value": 42, } - search.assert_awaited_once_with(ORG_INSTITUTION_ID, page=0, size=0) + search.assert_awaited_once_with( + ORG_INSTITUTION_ID, + page=0, + size=0, + from_year=None, + to_year=None, + ) + + +@pytest.mark.anyio +async def test_dashboard_publications_filters_by_publication_year_period(): + with patch( + "inse.dashboard.service.elasticsearch.search", + new=AsyncMock(return_value={"hits": {"total": {"value": 7}}}), + ) as search: + result = await get_dashboard_publications( + ORG_INSTITUTION_ID, + "Example Org", + from_year=2020, + to_year=2024, + ) + + assert result.value == 7 + query = search.await_args.kwargs["query"] + assert query["bool"]["must"][0]["nested"]["query"]["term"] == { + "authorships.institutions.id": ORG_INSTITUTION_ID + } + assert query["bool"]["filter"] == [ + {"range": {"publication_year": {"gte": 2020, "lte": 2024}}} + ] @pytest.mark.anyio @@ -107,6 +137,51 @@ async def test_dashboard_eu_project_statuses_deduplicates_projects(): ) +@pytest.mark.anyio +async def test_dashboard_eu_project_statuses_restricts_project_set_by_period(): + async def scan(**kwargs): + yield {"_source": {"projectID": "P2"}} + yield {"_source": {"projectID": "P1"}} + + with patch( + "inse.dashboard.service.InstitutionsSearchClient.get_institution_aliases_by_oa_institution_id", + new=AsyncMock(return_value=["Example University"]), + ), patch("inse.dashboard.service.elasticsearch.scan", new=scan), patch( + "inse.dashboard.service.elasticsearch.search", + new=AsyncMock( + return_value={ + "aggregations": { + "ongoing": {"projects": {"value": 1}}, + "upcoming": {"projects": {"value": 0}}, + "completed": {"projects": {"value": 1}}, + } + } + ), + ) as search: + await get_dashboard_eu_project_statuses( + ORG_INSTITUTION_ID, + "Example Org", + from_year=2020, + to_year=2024, + ) + + assert search.await_args.kwargs["body"]["query"] == { + "bool": { + "filter": [ + {"terms": {"id": ["P1", "P2"]}}, + { + "bool": { + "filter": [ + {"range": {"startDate": {"lte": "2024-12-31"}}}, + {"range": {"endDate": {"gte": "2020-01-01"}}}, + ] + } + }, + ] + } + } + + @pytest.mark.anyio async def test_dashboard_bmbf_project_statuses_uses_funding_dates(): response = { @@ -790,7 +865,7 @@ async def test_topic_heatmap_maps_field_year_counts_and_shares(): @pytest.mark.anyio -async def test_topic_heatmap_defaults_to_last_five_years(): +async def test_topic_heatmap_defaults_to_all_time(): async def search(**kwargs): if kwargs["index"] == config.settings.openalex_works_search_index: return { @@ -810,13 +885,9 @@ async def test_topic_heatmap_defaults_to_last_five_years(): organization_name="Example Org", ) - current_year = datetime.now().year - assert result.years == list(range(current_year - 4, current_year + 1)) + assert result.years == [] body = mocked_search.await_args_list[0].kwargs["body"] - assert body["query"]["bool"]["filter"][0]["range"]["publication_year"] == { - "gte": current_year - 4, - "lte": current_year, - } + assert body["query"]["bool"]["filter"] == [] @pytest.mark.anyio diff --git a/service/src/main/inse/patents/org/elastic_search_client.py b/service/src/main/inse/patents/org/elastic_search_client.py index 157fefe1..1dc73042 100644 --- a/service/src/main/inse/patents/org/elastic_search_client.py +++ b/service/src/main/inse/patents/org/elastic_search_client.py @@ -256,6 +256,8 @@ class OrgPatentsSearchClient: page: int = 0, size: int = DEFAULT_PAGE_SIZE, source: str | None = None, + from_year: int | None = None, + to_year: int | None = None, ) -> tuple[list[OrgPatentEntry], int]: short_id = institution_id.replace("https://openalex.org/", "").upper() filters: list[dict[str, Any]] = [{"term": {"institution_id": short_id}}] @@ -270,6 +272,14 @@ class OrgPatentsSearchClient: if source in ("EPO", "USPTO"): filters.append({"term": {"source": source}}) + year_range: dict[str, int] = {} + if from_year is not None: + year_range["gte"] = from_year + if to_year is not None: + year_range["lte"] = to_year + if year_range: + filters.append({"range": {"publication_year": year_range}}) + payload = { "from": page * size, "size": size, @@ -304,11 +314,27 @@ class OrgPatentsSearchClient: self, institution_id: str, size: int = 10, + from_year: int | None = None, + to_year: int | None = None, ) -> list[dict[str, Any]]: short_id = institution_id.replace("https://openalex.org/", "").upper() + filters: list[dict[str, Any]] = [{"term": {"institution_id": short_id}}] + year_range: dict[str, int] = {} + if from_year is not None: + year_range["gte"] = from_year + if to_year is not None: + year_range["lte"] = to_year + if year_range: + filters.append({"range": {"publication_year": year_range}}) + + query = ( + {"term": {"institution_id": short_id}} + if len(filters) == 1 + else {"bool": {"filter": filters}} + ) payload = { "size": 0, - "query": {"term": {"institution_id": short_id}}, + "query": query, "aggs": { "matched_authors_nested": { "nested": {"path": "matched_authors"}, diff --git a/service/src/main/inse/patents/org/test_elastic_search_client.py b/service/src/main/inse/patents/org/test_elastic_search_client.py index 6ac6ac7c..c5692f67 100644 --- a/service/src/main/inse/patents/org/test_elastic_search_client.py +++ b/service/src/main/inse/patents/org/test_elastic_search_client.py @@ -53,3 +53,43 @@ async def test_top_authors_by_institution_aggregates_matched_authors(): payload["aggs"]["matched_authors_nested"]["nested"]["path"] == "matched_authors" ) + + +@pytest.mark.anyio +async def test_top_authors_by_institution_filters_by_publication_year(): + requests: list[httpx.Request] = [] + + def handler(request: httpx.Request) -> httpx.Response: + requests.append(request) + return httpx.Response( + 200, + json={ + "aggregations": { + "matched_authors_nested": { + "authors": {"buckets": []} + } + } + }, + ) + + client = OrgPatentsSearchClient( + base_url="https://example.test", + api_key="key", + transport=httpx.MockTransport(handler), + ) + + await client.top_authors_by_institution( + "https://openalex.org/I123", + from_year=2020, + to_year=2024, + ) + + payload = json.loads(requests[0].content) + assert payload["query"] == { + "bool": { + "filter": [ + {"term": {"institution_id": "I123"}}, + {"range": {"publication_year": {"gte": 2020, "lte": 2024}}}, + ] + } + } diff --git a/webapp/src/app/modules/dashboard/dashboard-statistics.service.ts b/webapp/src/app/modules/dashboard/dashboard-statistics.service.ts index a216fa2b..79a5e80d 100644 --- a/webapp/src/app/modules/dashboard/dashboard-statistics.service.ts +++ b/webapp/src/app/modules/dashboard/dashboard-statistics.service.ts @@ -5,7 +5,10 @@ import { Observable } from 'rxjs'; import { Configuration } from '../../api'; import { TopicTreemapData } from '../../shared/ui/topic-treemap/topic-treemap.models'; -export type TopAuthorsWorksPeriod = 'all_time' | 'last_5_years'; +export interface DashboardPeriodBounds { + fromYear?: number; + toYear?: number; +} export interface DashboardStatistics { institution_id: string; @@ -95,9 +98,12 @@ export class DashboardStatisticsService { ); } - getPublicationCount(): Observable { + getPublicationCount( + period: DashboardPeriodBounds = {}, + ): Observable { return this.httpClient.get( `${this.apiConfiguration?.basePath ?? ''}/api/dashboard/statistics/publications`, + { params: this.periodParams(period) }, ); } @@ -107,56 +113,75 @@ export class DashboardStatisticsService { ); } - getPatentCount(): Observable { + getPatentCount( + period: DashboardPeriodBounds = {}, + ): Observable { return this.httpClient.get( `${this.apiConfiguration?.basePath ?? ''}/api/dashboard/statistics/patents`, + { params: this.periodParams(period) }, ); } - getEuProjectCount(): Observable { + getEuProjectCount( + period: DashboardPeriodBounds = {}, + ): Observable { return this.httpClient.get( `${this.apiConfiguration?.basePath ?? ''}/api/dashboard/statistics/projects/eu`, + { params: this.periodParams(period) }, ); } - getEuProjectStatuses(): Observable { + getEuProjectStatuses( + period: DashboardPeriodBounds = {}, + ): Observable { return this.httpClient.get( `${this.apiConfiguration?.basePath ?? ''}/api/dashboard/projects/eu/status`, + { params: this.periodParams(period) }, ); } - getBmbfProjectStatuses(): Observable { + getBmbfProjectStatuses( + period: DashboardPeriodBounds = {}, + ): Observable { return this.httpClient.get( `${this.apiConfiguration?.basePath ?? ''}/api/dashboard/projects/bmbf/status`, + { params: this.periodParams(period) }, ); } - getBmbfProjectCount(): Observable { + getBmbfProjectCount( + period: DashboardPeriodBounds = {}, + ): Observable { return this.httpClient.get( `${this.apiConfiguration?.basePath ?? ''}/api/dashboard/statistics/projects/bmbf`, + { params: this.periodParams(period) }, ); } - getDfgProjectCount(): Observable { + getDfgProjectCount( + period: DashboardPeriodBounds = {}, + ): Observable { return this.httpClient.get( `${this.apiConfiguration?.basePath ?? ''}/api/dashboard/statistics/projects/dfg`, + { params: this.periodParams(period) }, ); } - getDfgProjectTopics(): Observable { + getDfgProjectTopics( + period: DashboardPeriodBounds = {}, + ): Observable { return this.httpClient.get( `${this.apiConfiguration?.basePath ?? ''}/api/dashboard/projects/dfg/topics`, + { params: this.periodParams(period) }, ); } getTopAuthors( - worksPeriod: TopAuthorsWorksPeriod = 'all_time', + period: DashboardPeriodBounds = {}, ): Observable { return this.httpClient.get( `${this.apiConfiguration?.basePath ?? ''}/api/dashboard/top-authors`, - { - params: { works_period: worksPeriod }, - }, + { params: this.periodParams(period) }, ); } @@ -187,4 +212,13 @@ export class DashboardStatisticsService { { params }, ); } + + private periodParams( + period: DashboardPeriodBounds, + ): Record { + const params: Record = {}; + if (period.fromYear !== undefined) params['from_year'] = period.fromYear; + if (period.toYear !== undefined) params['to_year'] = period.toYear; + return params; + } } diff --git a/webapp/src/app/modules/dashboard/dashboard.component.html b/webapp/src/app/modules/dashboard/dashboard.component.html index 28b1365f..21a02f91 100644 --- a/webapp/src/app/modules/dashboard/dashboard.component.html +++ b/webapp/src/app/modules/dashboard/dashboard.component.html @@ -1,4 +1,37 @@
+
+
+ + + +
+
+ + +
+
+
Field Treemap

Publikationen Ihrer Organisation nach Field.

-
- - -
@if (topicTreemapLoading) { @@ -270,23 +293,9 @@
-

Top 10 Personen aller Zeiten

+

Top 10 Personen

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

-
- - -
@if (topAuthorsError) { diff --git a/webapp/src/app/modules/dashboard/dashboard.component.scss b/webapp/src/app/modules/dashboard/dashboard.component.scss index 124f8053..9af762eb 100644 --- a/webapp/src/app/modules/dashboard/dashboard.component.scss +++ b/webapp/src/app/modules/dashboard/dashboard.component.scss @@ -4,6 +4,46 @@ font-family: 'Inter', sans-serif; color: #333; + .dashboard-period-filter { + display: flex; + align-items: center; + gap: 1rem; + margin-bottom: 1.5rem; + flex-wrap: wrap; + } + + .dashboard-period-presets { + display: inline-flex; + overflow: hidden; + flex: 0 0 auto; + border: 1px solid #cbd5e1; + border-radius: 6px; + background: #fff; + + button { + padding: 0.55rem 0.8rem; + border: 0; + border-right: 1px solid #cbd5e1; + background: transparent; + color: #334155; + cursor: pointer; + font: inherit; + + &.active { + background: #1d4ed8; + color: #fff; + } + } + + button:last-child { + border-right: 0; + } + } + + .dashboard-period-slider { + width: min(100%, 34rem); + } + .statistics-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(220px, 1fr)); @@ -134,10 +174,6 @@ } } - .topic-treemap-year-slider { - width: min(100%, 34rem); - } - .topic-heatmap-loading { min-height: 25rem; display: grid; @@ -194,38 +230,6 @@ } } - .top-authors-period-toggle { - display: inline-flex; - overflow: hidden; - border: 1px solid #cbd5e1; - border-radius: 6px; - background: #fff; - - button { - padding: 0.55rem 0.8rem; - border: 0; - border-right: 1px solid #cbd5e1; - background: transparent; - color: #334155; - cursor: pointer; - font: inherit; - - &:last-child { - border-right: 0; - } - - &.active { - background: #1d4ed8; - color: #fff; - } - - &:focus-visible { - outline: 3px solid #93c5fd; - outline-offset: -3px; - } - } - } - .top-authors-grid { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); diff --git a/webapp/src/app/modules/dashboard/dashboard.component.ts b/webapp/src/app/modules/dashboard/dashboard.component.ts index 5d8ae1d2..204895cc 100644 --- a/webapp/src/app/modules/dashboard/dashboard.component.ts +++ b/webapp/src/app/modules/dashboard/dashboard.component.ts @@ -19,6 +19,7 @@ import { } from './topic-wordcloud-dialog/topic-wordcloud-dialog.component'; import { BmbfProjectStatusStatistics, + DashboardPeriodBounds, DashboardStatisticValue, DashboardStatistics, DashboardStatisticsService, @@ -26,7 +27,6 @@ import { EuProjectStatusStatistics, TopAuthor, TopAuthorStatistics, - TopAuthorsWorksPeriod, } from './dashboard-statistics.service'; import { activeInstitutionPersonListQueryParams, @@ -45,6 +45,11 @@ type TopAuthorDataset = { entries: TopAuthor[]; stripAuthorTitle?: boolean; }; +type DashboardPeriodMode = + | 'all_time' + | 'last_10_years' + | 'last_5_years' + | 'custom'; @Component({ selector: 'dashboard', imports: [ @@ -84,7 +89,6 @@ export class DashboardComponent implements OnInit { topAuthors?: TopAuthorStatistics; topAuthorsLoading = false; topAuthorsError = false; - topAuthorsWorksPeriod: TopAuthorsWorksPeriod = 'all_time'; topicTreemap?: TopicTreemapData; topicTreemapLoading = false; topicTreemapError = false; @@ -99,8 +103,9 @@ export class DashboardComponent implements OnInit { bmbfProjectStatusesError = false; readonly topicTreemapMinYear = 1900; readonly topicTreemapMaxYear = new Date().getFullYear(); - topicTreemapFromYear = this.topicTreemapMaxYear - 4; - topicTreemapToYear = this.topicTreemapMaxYear; + dashboardPeriodMode: DashboardPeriodMode = 'all_time'; + dashboardFromYear = this.topicTreemapMaxYear - 4; + dashboardToYear = this.topicTreemapMaxYear; selectedTopicTreemapNode?: string; private topicTreemapReloadQueued = false; private topicTreemapRequestId = 0; @@ -113,7 +118,7 @@ export class DashboardComponent implements OnInit { ) {} ngOnInit() { - this.restoreTopicTreemapState(); + this.restoreDashboardPeriodState(); this.loadStatistics(); this.loadTopAuthors(); this.loadTopicTreemap(); @@ -124,23 +129,24 @@ export class DashboardComponent implements OnInit { private loadStatistics(): void { this.statisticsError = false; + const period = this.selectedPeriodBounds(); this.loadStatistic( 'publications', - this.statisticsService.getPublicationCount(), + this.statisticsService.getPublicationCount(period), ); this.loadStatistic('persons', this.statisticsService.getPersonCount()); - this.loadStatistic('patents', this.statisticsService.getPatentCount()); + this.loadStatistic('patents', this.statisticsService.getPatentCount(period)); this.loadStatistic( 'eu_projects', - this.statisticsService.getEuProjectCount(), + this.statisticsService.getEuProjectCount(period), ); this.loadStatistic( 'bmbf_projects', - this.statisticsService.getBmbfProjectCount(), + this.statisticsService.getBmbfProjectCount(period), ); this.loadStatistic( 'dfg_projects', - this.statisticsService.getDfgProjectCount(), + this.statisticsService.getDfgProjectCount(period), ); } @@ -199,10 +205,12 @@ export class DashboardComponent implements OnInit { return (this.dfgProjectTopics?.topics.length ?? 0) > 0; } - setTopAuthorsWorksPeriod(period: TopAuthorsWorksPeriod): void { - if (period === this.topAuthorsWorksPeriod) return; - this.topAuthorsWorksPeriod = period; - this.loadTopAuthors(); + setDashboardPeriodMode(mode: DashboardPeriodMode): void { + if (mode === this.dashboardPeriodMode) return; + this.dashboardPeriodMode = mode; + this.applyPresetPeriod(); + this.updateDashboardPeriodUrl(); + this.reloadPeriodData(); } authorBarWidth(entries: TopAuthor[], count: number): number { @@ -253,22 +261,23 @@ export class DashboardComponent implements OnInit { ); } - onTopicTreemapRangeChange(): void { + onDashboardPeriodRangeChange(): void { + this.dashboardPeriodMode = 'custom'; this.topicTreemapLoading = true; this.topicTreemapError = false; this.topicTreemapRequestId += 1; - this.updateTopicTreemapUrl(); + this.updateDashboardPeriodUrl(); if (this.topicTreemapReloadQueued) return; this.topicTreemapReloadQueued = true; setTimeout(() => { this.topicTreemapReloadQueued = false; - this.loadTopicTreemap(); + this.reloadPeriodData(); }); } onTopicTreemapNodeChange(nodeId: string | undefined): void { this.selectedTopicTreemapNode = nodeId; - this.updateTopicTreemapUrl(); + this.updateDashboardPeriodUrl(); } onTopicTreemapTopicSelect(topic: TopicTreemapTopicSelect): void { @@ -282,28 +291,51 @@ export class DashboardComponent implements OnInit { ); } - private restoreTopicTreemapState(): void { + private restoreDashboardPeriodState(): void { const params = this.route.snapshot.queryParamMap; - this.topicTreemapFromYear = this.parseTreemapYear( - params.get('treemapFrom'), - this.topicTreemapFromYear, + const mode = params.get('period'); + if ( + mode === 'all_time' || + mode === 'last_10_years' || + mode === 'last_5_years' || + mode === 'custom' + ) { + this.dashboardPeriodMode = mode; + } + this.applyPresetPeriod(); + this.dashboardFromYear = this.parseDashboardYear( + params.get('fromYear'), + this.dashboardFromYear, ); - this.topicTreemapToYear = this.parseTreemapYear( - params.get('treemapTo'), - this.topicTreemapToYear, + this.dashboardToYear = this.parseDashboardYear( + params.get('toYear'), + this.dashboardToYear, ); - if (this.topicTreemapFromYear > this.topicTreemapToYear) { - this.topicTreemapFromYear = this.topicTreemapToYear; + if (this.dashboardFromYear > this.dashboardToYear) { + this.dashboardFromYear = this.dashboardToYear; } this.selectedTopicTreemapNode = params.get('treemapNode') ?? undefined; } - private updateTopicTreemapUrl(): void { + private applyPresetPeriod(): void { + const currentYear = this.topicTreemapMaxYear; + if (this.dashboardPeriodMode === 'last_10_years') { + this.dashboardFromYear = currentYear - 9; + this.dashboardToYear = currentYear; + } else if (this.dashboardPeriodMode === 'last_5_years') { + this.dashboardFromYear = currentYear - 4; + this.dashboardToYear = currentYear; + } + } + + private updateDashboardPeriodUrl(): void { + const period = this.selectedPeriodBounds(); void this.router.navigate([], { relativeTo: this.route, queryParams: { - treemapFrom: this.topicTreemapFromYear, - treemapTo: this.topicTreemapToYear, + period: this.dashboardPeriodMode, + fromYear: period.fromYear ?? null, + toYear: period.toYear ?? null, treemapNode: this.selectedTopicTreemapNode ?? null, }, queryParamsHandling: 'merge', @@ -311,7 +343,7 @@ export class DashboardComponent implements OnInit { }); } - private parseTreemapYear(value: string | null, fallback: number): number { + private parseDashboardYear(value: string | null, fallback: number): number { const year = Number(value); return Number.isInteger(year) && year >= this.topicTreemapMinYear && @@ -320,6 +352,24 @@ export class DashboardComponent implements OnInit { : fallback; } + private selectedPeriodBounds(): DashboardPeriodBounds { + return this.dashboardPeriodMode === 'all_time' + ? {} + : { + fromYear: this.dashboardFromYear, + toYear: this.dashboardToYear, + }; + } + + private reloadPeriodData(): void { + this.loadStatistics(); + this.loadTopAuthors(); + this.loadTopicTreemap(); + this.loadDfgProjectTopics(); + this.loadEuProjectStatuses(); + this.loadBmbfProjectStatuses(); + } + private loadStatistic( key: DashboardStatisticKey, request: Observable, @@ -369,7 +419,7 @@ export class DashboardComponent implements OnInit { this.topAuthorsLoading = true; this.topAuthorsError = false; this.statisticsService - .getTopAuthors(this.topAuthorsWorksPeriod) + .getTopAuthors(this.selectedPeriodBounds()) .pipe(finalize(() => (this.topAuthorsLoading = false))) .subscribe({ next: (statistics) => { @@ -385,7 +435,7 @@ export class DashboardComponent implements OnInit { this.dfgTopicsLoading = true; this.dfgTopicsError = false; this.statisticsService - .getDfgProjectTopics() + .getDfgProjectTopics(this.selectedPeriodBounds()) .pipe(finalize(() => (this.dfgTopicsLoading = false))) .subscribe({ next: (topics) => { @@ -401,7 +451,7 @@ export class DashboardComponent implements OnInit { this.euProjectStatusesLoading = true; this.euProjectStatusesError = false; this.statisticsService - .getEuProjectStatuses() + .getEuProjectStatuses(this.selectedPeriodBounds()) .pipe(finalize(() => (this.euProjectStatusesLoading = false))) .subscribe({ next: (statuses) => { @@ -417,7 +467,7 @@ export class DashboardComponent implements OnInit { this.bmbfProjectStatusesLoading = true; this.bmbfProjectStatusesError = false; this.statisticsService - .getBmbfProjectStatuses() + .getBmbfProjectStatuses(this.selectedPeriodBounds()) .pipe(finalize(() => (this.bmbfProjectStatusesLoading = false))) .subscribe({ next: (statuses) => { @@ -430,17 +480,18 @@ export class DashboardComponent implements OnInit { } private loadTopicTreemap(): void { - if (this.topicTreemapFromYear > this.topicTreemapToYear) { + if (this.dashboardFromYear > this.dashboardToYear) { this.topicTreemapLoading = false; this.topicTreemapError = true; return; } const requestId = ++this.topicTreemapRequestId; + const period = this.selectedPeriodBounds(); this.topicTreemapLoading = true; this.topicTreemapError = false; this.statisticsService - .getTopicTreemap(this.topicTreemapFromYear, this.topicTreemapToYear) + .getTopicTreemap(period.fromYear, period.toYear) .pipe( finalize(() => { if (requestId === this.topicTreemapRequestId) {