diff --git a/service/src/main/inse/auth/router.py b/service/src/main/inse/auth/router.py index 4bb2ab31..378be6fc 100644 --- a/service/src/main/inse/auth/router.py +++ b/service/src/main/inse/auth/router.py @@ -213,6 +213,7 @@ async def change_password( operation_id="canFetchGdprRelevantData", ) async def can_fetch_gdpr_relevant_data( + session: SessionDep, access_token: Annotated[ AccessTokenMetadata, auth_service.CurrentUserAccessTokenPayloadDep, @@ -227,6 +228,7 @@ async def can_fetch_gdpr_relevant_data( ] = None, ) -> bool: return await auth_service.can_fetch_gdpr_relevant_data( + session=session, access_token=access_token, raw_oa_author_id=raw_oa_author_id, raw_oa_institution_id=raw_oa_institution_id, diff --git a/service/src/main/inse/auth/service.py b/service/src/main/inse/auth/service.py index 1b271e67..e7ec3d48 100644 --- a/service/src/main/inse/auth/service.py +++ b/service/src/main/inse/auth/service.py @@ -1467,6 +1467,7 @@ def change_password( async def can_fetch_gdpr_relevant_data( + session: Session, access_token: AccessTokenMetadata, raw_oa_author_id: str | None = None, raw_oa_institution_id: str | None = None, @@ -1493,40 +1494,71 @@ async def can_fetch_gdpr_relevant_data( logger.debug("No OpenAlex author ID or institution ID provided") return False - effective_institution_id = access_token.effective_institution_id - # Current user does not belong to any institution - if not effective_institution_id: + institution_ids = list( + session.exec( + select(OrganizationInstitution.openalex_institution_id) + .where( + OrganizationInstitution.organization_id + == access_token.effective_organization_id + ) + .order_by(OrganizationInstitution.position) + ).all() + ) + if not institution_ids and access_token.effective_institution_id: + institution_ids = [access_token.effective_institution_id] + + if not institution_ids: logger.debug( "Current user does not belong to any institution, cannot fetch GDPR-relevant data" ) return False - # Current user belongs to an institution, but the request is for a different institution + from inse.organization_management import service as organization_service + + association_groups = await organization_service.resolve_institution_associations( + institution_ids + ) + organization_institution_ids = set(institution_ids) + for group in association_groups: + organization_institution_ids.add(group.id.rstrip("/").split("/")[-1]) + organization_institution_ids.update( + association.id.rstrip("/").split("/")[-1] + for association in group.associated_institutions + ) + + requested_institution_id = ( + raw_oa_institution_id.rstrip("/").split("/")[-1] + if raw_oa_institution_id + else None + ) if ( - raw_oa_institution_id - and effective_institution_id - and raw_oa_institution_id != effective_institution_id + requested_institution_id + and requested_institution_id not in organization_institution_ids ): logger.debug( "Current user belongs to institution %s, but request is for institution %s, cannot fetch GDPR-relevant data", - effective_institution_id, - raw_oa_institution_id, + organization_institution_ids, + requested_institution_id, ) return False # Current user belongs to an institution, but request is for author not belonging to that institution if raw_oa_author_id: - author_belongs_to_institution = ( - await authors_service.author_currently_belongs_to_institution( - raw_oa_author_id or "", effective_institution_id - ) - ) + for institution_id in organization_institution_ids: + if await authors_service.author_currently_belongs_to_institution( + raw_oa_author_id, institution_id + ): + logger.debug( + "Author %s belongs to organization institution %s", + raw_oa_author_id, + institution_id, + ) + return True logger.debug( - "Author %s belongs to institution %s: %s", + "Author %s does not belong to any organization institution %s", raw_oa_author_id, - effective_institution_id, - author_belongs_to_institution, + organization_institution_ids, ) - return author_belongs_to_institution + return False return True diff --git a/service/src/main/inse/auth/test_auth_service.py b/service/src/main/inse/auth/test_auth_service.py index 1b5c92cb..a02e0a0f 100644 --- a/service/src/main/inse/auth/test_auth_service.py +++ b/service/src/main/inse/auth/test_auth_service.py @@ -1,6 +1,7 @@ import datetime as _dt import uuid from datetime import timedelta +from unittest.mock import AsyncMock, patch import pytest from fastapi import HTTPException, Response @@ -14,11 +15,16 @@ from inse.auth.model import ( Account, IdTokenMetadata, Organization, + OrganizationInstitution, RefreshTokenMetadata, Secret, SecretPurpose, UserRole, ) +from inse.organization_management.model import ( + InstitutionAssociation, + InstitutionAssociationsResponse, +) @pytest.fixture() @@ -81,6 +87,74 @@ def test_hash_and_verify_password(): assert auth_service._verify_password("wrong", h) is False +@pytest.mark.anyio +async def test_gdpr_access_allows_every_organization_institution(in_memory_session): + org, account = create_org_and_account( + in_memory_session, "multi-institution@example.com", "pw" + ) + in_memory_session.add_all( + [ + OrganizationInstitution( + organization_id=org.id, + openalex_institution_id="I111", + position=0, + ), + OrganizationInstitution( + organization_id=org.id, + openalex_institution_id="I222", + position=1, + ), + ] + ) + in_memory_session.commit() + token = AccessTokenMetadata( + real_account_id=account.id, + expires_at=_dt.datetime.now(_dt.UTC) + timedelta(hours=1), + user_fingerprint_hash="fingerprint", + effective_account_id=account.id, + effective_organization_id=org.id, + effective_institution_id="I111", + ) + + associations = [ + InstitutionAssociationsResponse( + id="I111", + display_name="Root institution", + associated_institutions=[ + InstitutionAssociation( + id="I333", + display_name="Child institution", + relationship="child", + ) + ], + ), + InstitutionAssociationsResponse( + id="I222", + display_name="Second institution", + associated_institutions=[], + ), + ] + with patch( + "inse.organization_management.service.resolve_institution_associations", + new=AsyncMock(return_value=associations), + ): + assert await auth_service.can_fetch_gdpr_relevant_data( + session=in_memory_session, + access_token=token, + raw_oa_institution_id="https://openalex.org/I222", + ) + assert await auth_service.can_fetch_gdpr_relevant_data( + session=in_memory_session, + access_token=token, + raw_oa_institution_id="I333", + ) + assert not await auth_service.can_fetch_gdpr_relevant_data( + session=in_memory_session, + access_token=token, + raw_oa_institution_id="I444", + ) + + def test_request_otk_and_login_flow(in_memory_session, settings_backup): config_module.settings.token_hmac_key = "test-hmac-key" config_module.settings.token_issuer_id = "test-issuer" @@ -113,7 +187,9 @@ def test_request_otk_and_login_flow(in_memory_session, settings_backup): assert login_result.id_token.real_account_id == acc.id raw_id_token = _get_cookie_value(response, auth_service.ID_TOKEN_COOKIE_KEY) - payload = auth_service._verify_id_token(raw_id_token=raw_id_token, session=in_memory_session) + payload = auth_service._verify_id_token( + raw_id_token=raw_id_token, session=in_memory_session + ) assert payload[auth_service.REAL_ACCOUNT_ID_KEY] == str(acc.id) @@ -175,7 +251,9 @@ def test_access_and_refresh_token_flow(in_memory_session, settings_backup): ) assert isinstance(access_response.access_token, AccessTokenMetadata) - raw_refresh_token = _get_cookie_value(response, auth_service.REFRESH_TOKEN_COOKIE_KEY) + raw_refresh_token = _get_cookie_value( + response, auth_service.REFRESH_TOKEN_COOKIE_KEY + ) refresh_payload = auth_service._verify_refresh_token( raw_refresh_token=raw_refresh_token, session=in_memory_session, @@ -185,9 +263,7 @@ def test_access_and_refresh_token_flow(in_memory_session, settings_backup): effective_account_id=uuid.UUID( refresh_payload[auth_service.EFFECTIVE_ACCOUNT_ID_KEY] ), - expires_at=_dt.datetime.fromtimestamp( - refresh_payload["exp"], tz=_dt.UTC - ), + expires_at=_dt.datetime.fromtimestamp(refresh_payload["exp"], tz=_dt.UTC), epoch=refresh_payload[auth_service.EPOCH_KEY], effective_role=UserRole(refresh_payload[auth_service.EFFECTIVE_ROLE_KEY]), effective_organization_id=uuid.UUID( @@ -240,7 +316,9 @@ def test_access_and_refresh_token_preserve_multiple_roles( UserRole.USER.value, ] - raw_refresh_token = _get_cookie_value(response, auth_service.REFRESH_TOKEN_COOKIE_KEY) + raw_refresh_token = _get_cookie_value( + response, auth_service.REFRESH_TOKEN_COOKIE_KEY + ) refresh_payload = auth_service._verify_refresh_token( raw_refresh_token=raw_refresh_token, session=in_memory_session, @@ -634,7 +712,6 @@ def test_get_account_epoch_not_found(in_memory_session): auth_service._get_account_epoch(in_memory_session, random_id) - def test_request_password_reset_creates_secret(in_memory_session, settings_backup): email = "reset@example.com" password = "oldpw123" diff --git a/service/src/main/inse/dashboard/model.py b/service/src/main/inse/dashboard/model.py index bbc047db..d4871d2b 100644 --- a/service/src/main/inse/dashboard/model.py +++ b/service/src/main/inse/dashboard/model.py @@ -1,6 +1,11 @@ from pydantic import BaseModel +class DashboardInstitution(BaseModel): + id: str + display_name: str + + class DashboardStatistics(BaseModel): institution_id: str organization_name: str diff --git a/service/src/main/inse/dashboard/project_statistics_service.py b/service/src/main/inse/dashboard/project_statistics_service.py index 10f68bde..86915d86 100644 --- a/service/src/main/inse/dashboard/project_statistics_service.py +++ b/service/src/main/inse/dashboard/project_statistics_service.py @@ -1,3 +1,5 @@ +import asyncio + from inse.institutions.institutions_search_client import InstitutionsSearchClient from inse.projects import service as projects_service from inse.projects.model import EuCordisProjectType @@ -10,21 +12,53 @@ from .common import ( from .model import DashboardStatisticValue +def _institution_ids(value: str | list[str]) -> list[str]: + return value if isinstance(value, list) else [value] + + +def _scope_id(institution_ids: list[str]) -> str: + return ( + _normalize_institution_id(institution_ids[0]) + if len(institution_ids) == 1 + else "all" + ) + + +async def _institution_aliases(institution_ids: list[str]) -> list[str]: + client = InstitutionsSearchClient() + aliases = await asyncio.gather( + *( + client.get_institution_aliases_by_oa_institution_id( + _raw_institution_id(institution_id) + ) + for institution_id in institution_ids + ) + ) + return list(dict.fromkeys(alias for group in aliases for alias in group)) + + async def get_dashboard_eu_projects( - institution_id: str, + institution_id: str | list[str], organization_name: str, from_year: int | None = None, to_year: int | None = None, ) -> DashboardStatisticValue: - normalized_id = _normalize_institution_id(institution_id) + institution_ids = _institution_ids(institution_id) period = _dashboard_period(from_year, to_year) + multiple_institutions = len(institution_ids) > 1 projects = await projects_service.search_eu_cordis_projects( institutions_search_client=InstitutionsSearchClient(), - raw_oa_institution_id=_raw_institution_id(normalized_id), + raw_oa_institution_id=( + None if multiple_institutions else _raw_institution_id(institution_ids[0]) + ), author_id=None, author_ids=None, organization_ids=None, - organization_names=None, + organization_names=( + await _institution_aliases(institution_ids) + if multiple_institutions + else None + ), project_types=list(EuCordisProjectType), keywords=None, topic_ids=None, @@ -45,24 +79,27 @@ async def get_dashboard_eu_projects( fuzzy=False, ) return DashboardStatisticValue( - institution_id=normalized_id, + institution_id=_scope_id(institution_ids), organization_name=organization_name, value=projects.total, ) async def get_dashboard_bmbf_projects( - institution_id: str, + institution_id: str | list[str], organization_name: str, from_year: int | None = None, to_year: int | None = None, ) -> DashboardStatisticValue: - normalized_id = _normalize_institution_id(institution_id) + institution_ids = _institution_ids(institution_id) period = _dashboard_period(from_year, to_year) + multiple_institutions = len(institution_ids) > 1 projects = await projects_service.search_bund_projects_with_filters( institutions_search_client=InstitutionsSearchClient(), executing_agency=None, - raw_oa_institution_id=_raw_institution_id(normalized_id), + raw_oa_institution_id=( + None if multiple_institutions else _raw_institution_id(institution_ids[0]) + ), title=None, keywords=None, funding_arts=None, @@ -78,25 +115,33 @@ async def get_dashboard_bmbf_projects( sort_by="id", sort_direction="asc", fuzzy=False, + oa_institution_aliases=( + await _institution_aliases(institution_ids) + if multiple_institutions + else None + ), ) return DashboardStatisticValue( - institution_id=normalized_id, + institution_id=_scope_id(institution_ids), organization_name=organization_name, value=projects.total, ) async def get_dashboard_dfg_projects( - institution_id: str, + institution_id: str | list[str], organization_name: str, from_year: int | None = None, to_year: int | None = None, ) -> DashboardStatisticValue: - normalized_id = _normalize_institution_id(institution_id) + institution_ids = _institution_ids(institution_id) period = _dashboard_period(from_year, to_year) + multiple_institutions = len(institution_ids) > 1 projects = await projects_service.get_dfg_projects( institutions_search_client=InstitutionsSearchClient(), - raw_oa_institution_id=_raw_institution_id(normalized_id), + raw_oa_institution_id=( + None if multiple_institutions else _raw_institution_id(institution_ids[0]) + ), author_id=None, author_filter_ids=None, institution_ids=None, @@ -114,9 +159,14 @@ async def get_dashboard_dfg_projects( sort_direction="asc", fuzzy=False, skip_enrichment=True, + institution_aliases=( + await _institution_aliases(institution_ids) + if multiple_institutions + else None + ), ) return DashboardStatisticValue( - institution_id=normalized_id, + institution_id=_scope_id(institution_ids), organization_name=organization_name, value=projects.total, ) diff --git a/service/src/main/inse/dashboard/project_status_service.py b/service/src/main/inse/dashboard/project_status_service.py index 4c32b94b..803cb3ed 100644 --- a/service/src/main/inse/dashboard/project_status_service.py +++ b/service/src/main/inse/dashboard/project_status_service.py @@ -25,6 +25,7 @@ from .project_statistics_service import ( get_dashboard_dfg_projects, get_dashboard_eu_projects, ) +from .project_ids_service import _get_dfg_project_ids_from_projects_service def _status_count(aggregations: dict[str, Any], status_name: str) -> int: @@ -77,13 +78,22 @@ async def get_dashboard_eu_project_statuses( to_year: int | None = None, ) -> EuProjectStatusStatistics: normalized_id = _normalize_institution_id(institution_id) - aliases = await _institution_aliases(normalized_id, organization_name) - project_ids = await _eu_project_ids_for_aliases(aliases) total = ( await get_dashboard_eu_projects( normalized_id, organization_name, from_year=from_year, to_year=to_year ) ).value + if total == 0: + return EuProjectStatusStatistics( + institution_id=normalized_id, + organization_name=organization_name, + ongoing=0, + upcoming=0, + completed=0, + ) + + aliases = await _institution_aliases(normalized_id, organization_name) + project_ids = await _eu_project_ids_for_aliases(aliases) if not project_ids: return EuProjectStatusStatistics( institution_id=normalized_id, @@ -152,6 +162,20 @@ async def get_dashboard_bmbf_project_statuses( to_year: int | None = None, ) -> BmbfProjectStatusStatistics: normalized_id = _normalize_institution_id(institution_id) + total = ( + await get_dashboard_bmbf_projects( + normalized_id, organization_name, from_year=from_year, to_year=to_year + ) + ).value + if total == 0: + return BmbfProjectStatusStatistics( + institution_id=normalized_id, + organization_name=organization_name, + ongoing=0, + upcoming=0, + completed=0, + ) + aliases = await _institution_aliases(normalized_id, organization_name) period = _dashboard_period(from_year, to_year) filters = [_alias_match_query("Zuwendungsempfänger", aliases)] @@ -171,11 +195,6 @@ async def get_dashboard_bmbf_project_statuses( cluster=ESCluster.INSE, ) aggregations = response.get("aggregations", {}) - total = ( - await get_dashboard_bmbf_projects( - normalized_id, organization_name, from_year=from_year, to_year=to_year - ) - ).value ongoing, upcoming, completed = reconcile_status_counts( total, int(aggregations.get("ongoing", {}).get("doc_count", 0)), @@ -199,12 +218,25 @@ async def get_dashboard_dfg_project_statuses( ) -> DfgProjectStatusStatistics: normalized_id = _normalize_institution_id(institution_id) period = _dashboard_period(from_year, to_year) - project_ids = await _get_dfg_project_ids_for_institution(normalized_id) total = ( await get_dashboard_dfg_projects( normalized_id, organization_name, from_year=from_year, to_year=to_year ) ).value + if total == 0: + return DfgProjectStatusStatistics( + institution_id=normalized_id, + organization_name=organization_name, + ongoing=0, + upcoming=0, + completed=0, + ) + + project_ids = await _get_dfg_project_ids_from_projects_service( + normalized_id, + from_year=from_year, + to_year=to_year, + ) if not project_ids: return DfgProjectStatusStatistics( institution_id=normalized_id, diff --git a/service/src/main/inse/dashboard/router.py b/service/src/main/inse/dashboard/router.py index a0d0de82..96b1dbe0 100644 --- a/service/src/main/inse/dashboard/router.py +++ b/service/src/main/inse/dashboard/router.py @@ -11,6 +11,7 @@ from inse.tags import Tags from .model import ( BmbfProjectStatusStatistics, BundProjectTopics, + DashboardInstitution, DashboardStatistics, DashboardStatisticValue, DfgProjectStatusStatistics, @@ -23,10 +24,13 @@ from .model import ( TopicWordCloud, ) from .service import ( + get_dashboard_analytical_institution, + get_dashboard_institutions, get_dashboard_organization, get_dashboard_patents, get_dashboard_persons, get_dashboard_publications, + get_dashboard_statistic_institution_ids, get_dashboard_statistics, get_topic_heatmap, get_topic_word_cloud, @@ -56,6 +60,19 @@ from .top_authors_service import ( router = APIRouter(prefix="/api/dashboard", tags=[Tags.DASHBOARD]) +@router.get( + "/institutions", + operation_id="getDashboardInstitutions", + response_model=list[DashboardInstitution], +) +async def dashboard_institutions( + session: Session = Depends(get_session), + access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep, +) -> list[DashboardInstitution]: + organization = get_dashboard_organization(session, access_token) + return await get_dashboard_institutions(session, organization) + + @router.get( "/statistics", operation_id="getDashboardStatistics", @@ -78,14 +95,18 @@ async def dashboard_statistics( response_model=DashboardStatisticValue, ) async def dashboard_publications( + institution_id: str | None = Query(default=None), 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: organization = get_dashboard_organization(session, access_token) + institution_ids = await get_dashboard_statistic_institution_ids( + session, organization, institution_id + ) return await get_dashboard_publications( - organization.openalex_institution_id, + institution_ids, organization.name, from_year=from_year, to_year=to_year, @@ -98,14 +119,18 @@ async def dashboard_publications( response_model=DashboardStatisticValue, ) async def dashboard_persons( + institution_id: str | None = Query(default=None), 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: organization = get_dashboard_organization(session, access_token) + institution_ids = await get_dashboard_statistic_institution_ids( + session, organization, institution_id + ) return await get_dashboard_persons( - organization.openalex_institution_id, + institution_ids, organization.name, from_year=from_year, to_year=to_year, @@ -118,14 +143,18 @@ async def dashboard_persons( response_model=DashboardStatisticValue, ) async def dashboard_patents( + institution_id: str | None = Query(default=None), 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: organization = get_dashboard_organization(session, access_token) + institution_ids = await get_dashboard_statistic_institution_ids( + session, organization, institution_id + ) return await get_dashboard_patents( - organization.openalex_institution_id, + institution_ids, organization.name, from_year=from_year, to_year=to_year, @@ -138,14 +167,18 @@ async def dashboard_patents( response_model=DashboardStatisticValue, ) async def dashboard_eu_projects( + institution_id: str | None = Query(default=None), 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: organization = get_dashboard_organization(session, access_token) + institution_ids = await get_dashboard_statistic_institution_ids( + session, organization, institution_id + ) return await get_dashboard_eu_projects( - organization.openalex_institution_id, + institution_ids, organization.name, from_year=from_year, to_year=to_year, @@ -158,15 +191,21 @@ async def dashboard_eu_projects( response_model=EuProjectStatusStatistics, ) async def dashboard_eu_project_statuses( + institution_id: str | None = Query(default=None), 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: organization = get_dashboard_organization(session, access_token) + selected_institution_id, selected_institution_name = ( + await get_dashboard_analytical_institution( + session, organization, institution_id + ) + ) return await get_dashboard_eu_project_statuses( - organization.openalex_institution_id, - organization.name, + selected_institution_id, + selected_institution_name, from_year=from_year, to_year=to_year, ) @@ -178,14 +217,18 @@ async def dashboard_eu_project_statuses( response_model=DashboardStatisticValue, ) async def dashboard_bmbf_projects( + institution_id: str | None = Query(default=None), 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: organization = get_dashboard_organization(session, access_token) + institution_ids = await get_dashboard_statistic_institution_ids( + session, organization, institution_id + ) return await get_dashboard_bmbf_projects( - organization.openalex_institution_id, + institution_ids, organization.name, from_year=from_year, to_year=to_year, @@ -198,15 +241,21 @@ async def dashboard_bmbf_projects( response_model=BmbfProjectStatusStatistics, ) async def dashboard_bmbf_project_statuses( + institution_id: str | None = Query(default=None), 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: organization = get_dashboard_organization(session, access_token) + selected_institution_id, selected_institution_name = ( + await get_dashboard_analytical_institution( + session, organization, institution_id + ) + ) return await get_dashboard_bmbf_project_statuses( - organization.openalex_institution_id, - organization.name, + selected_institution_id, + selected_institution_name, from_year=from_year, to_year=to_year, ) @@ -218,14 +267,18 @@ async def dashboard_bmbf_project_statuses( response_model=DashboardStatisticValue, ) async def dashboard_dfg_projects( + institution_id: str | None = Query(default=None), 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: organization = get_dashboard_organization(session, access_token) + institution_ids = await get_dashboard_statistic_institution_ids( + session, organization, institution_id + ) return await get_dashboard_dfg_projects( - organization.openalex_institution_id, + institution_ids, organization.name, from_year=from_year, to_year=to_year, @@ -238,15 +291,21 @@ async def dashboard_dfg_projects( response_model=DfgProjectStatusStatistics, ) async def dashboard_dfg_project_statuses( + institution_id: str | None = Query(default=None), 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, ) -> DfgProjectStatusStatistics: organization = get_dashboard_organization(session, access_token) + selected_institution_id, selected_institution_name = ( + await get_dashboard_analytical_institution( + session, organization, institution_id + ) + ) return await get_dashboard_dfg_project_statuses( - organization.openalex_institution_id, - organization.name, + selected_institution_id, + selected_institution_name, from_year=from_year, to_year=to_year, ) @@ -258,15 +317,21 @@ async def dashboard_dfg_project_statuses( response_model=DfgProjectTopics, ) async def dashboard_dfg_project_topics( + institution_id: str | None = Query(default=None), 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: organization = get_dashboard_organization(session, access_token) + selected_institution_id, selected_institution_name = ( + await get_dashboard_analytical_institution( + session, organization, institution_id + ) + ) return await get_dashboard_dfg_topics( - organization.openalex_institution_id, - organization.name, + selected_institution_id, + selected_institution_name, from_year=from_year, to_year=to_year, ) @@ -278,15 +343,21 @@ async def dashboard_dfg_project_topics( response_model=EuProjectTopics, ) async def dashboard_eu_project_topics( + institution_id: str | None = Query(default=None), 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, ) -> EuProjectTopics: organization = get_dashboard_organization(session, access_token) + selected_institution_id, selected_institution_name = ( + await get_dashboard_analytical_institution( + session, organization, institution_id + ) + ) return await get_dashboard_eu_topics( - organization.openalex_institution_id, - organization.name, + selected_institution_id, + selected_institution_name, from_year=from_year, to_year=to_year, ) @@ -298,15 +369,21 @@ async def dashboard_eu_project_topics( response_model=BundProjectTopics, ) async def dashboard_bund_project_topics( + institution_id: str | None = Query(default=None), 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, ) -> BundProjectTopics: organization = get_dashboard_organization(session, access_token) + selected_institution_id, selected_institution_name = ( + await get_dashboard_analytical_institution( + session, organization, institution_id + ) + ) return await get_dashboard_bund_topics( - organization.openalex_institution_id, - organization.name, + selected_institution_id, + selected_institution_name, from_year=from_year, to_year=to_year, ) @@ -322,15 +399,21 @@ async def dashboard_top_authors( default="all_time", pattern="^(all_time|last_5_years)$", ), + institution_id: str | None = Query(default=None), 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: organization = get_dashboard_organization(session, access_token) + selected_institution_id, selected_institution_name = ( + await get_dashboard_analytical_institution( + session, organization, institution_id + ) + ) return await get_top_authors( - organization.openalex_institution_id, - organization.name, + selected_institution_id, + selected_institution_name, works_period=works_period, from_year=from_year, to_year=to_year, @@ -346,14 +429,18 @@ async def dashboard_top_work_authors( works_period: Literal["all_time", "last_5_years"] = Query( default="all_time", pattern="^(all_time|last_5_years)$" ), + institution_id: str | None = Query(default=None), 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, ) -> TopAuthorAnalysis: organization = get_dashboard_organization(session, access_token) + selected_institution_id, _ = await get_dashboard_analytical_institution( + session, organization, institution_id + ) return await get_top_work_authors( - organization.openalex_institution_id, works_period, from_year, to_year + selected_institution_id, works_period, from_year, to_year ) @@ -363,14 +450,20 @@ async def dashboard_top_work_authors( response_model=TopAuthorAnalysis, ) async def dashboard_top_project_authors( + institution_id: str | None = Query(default=None), 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, ) -> TopAuthorAnalysis: organization = get_dashboard_organization(session, access_token) + selected_institution_id, selected_institution_name = ( + await get_dashboard_analytical_institution( + session, organization, institution_id + ) + ) return await get_top_project_authors( - organization.openalex_institution_id, organization.name, from_year, to_year + selected_institution_id, selected_institution_name, from_year, to_year ) @@ -380,14 +473,18 @@ async def dashboard_top_project_authors( response_model=TopAuthorAnalysis, ) async def dashboard_top_eu_project_authors( + institution_id: str | None = Query(default=None), 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, ) -> TopAuthorAnalysis: organization = get_dashboard_organization(session, access_token) + selected_institution_id, _ = await get_dashboard_analytical_institution( + session, organization, institution_id + ) return await get_top_eu_project_authors( - organization.openalex_institution_id, from_year, to_year + selected_institution_id, from_year, to_year ) @@ -397,14 +494,18 @@ async def dashboard_top_eu_project_authors( response_model=TopAuthorAnalysis, ) async def dashboard_top_patent_authors( + institution_id: str | None = Query(default=None), 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, ) -> TopAuthorAnalysis: organization = get_dashboard_organization(session, access_token) + selected_institution_id, _ = await get_dashboard_analytical_institution( + session, organization, institution_id + ) return await get_top_patent_authors( - organization.openalex_institution_id, from_year, to_year + selected_institution_id, from_year, to_year ) @@ -414,14 +515,18 @@ async def dashboard_top_patent_authors( response_model=TopAuthorAnalysis, ) async def dashboard_top_news_authors( + institution_id: str | None = Query(default=None), 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, ) -> TopAuthorAnalysis: organization = get_dashboard_organization(session, access_token) + selected_institution_id, _ = await get_dashboard_analytical_institution( + session, organization, institution_id + ) return await get_top_news_authors( - organization.openalex_institution_id, from_year, to_year + selected_institution_id, from_year, to_year ) @@ -431,6 +536,7 @@ async def dashboard_top_news_authors( response_model=TopicHeatmap, ) async def dashboard_topic_heatmap( + institution_id: str | None = Query(default=None), from_year: int | None = Query(default=None, ge=1900, le=2100), to_year: int | None = Query(default=None, ge=1900, le=2100), limit: int = Query(default=25, ge=1, le=50), @@ -438,9 +544,14 @@ async def dashboard_topic_heatmap( access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep, ) -> TopicHeatmap: organization = get_dashboard_organization(session, access_token) + selected_institution_id, selected_institution_name = ( + await get_dashboard_analytical_institution( + session, organization, institution_id + ) + ) return await get_topic_heatmap( - institution_id=organization.openalex_institution_id, - organization_name=organization.name, + institution_id=selected_institution_id, + organization_name=selected_institution_name, from_year=from_year, to_year=to_year, limit=limit, @@ -454,6 +565,7 @@ async def dashboard_topic_heatmap( ) async def dashboard_topic_word_cloud( topic_id: str = Query(alias="topicId", min_length=1), + institution_id: str | None = Query(default=None), from_year: int | None = Query(default=None, ge=1900, le=2100), to_year: int | None = Query(default=None, ge=1900, le=2100), limit: int = Query(default=30, ge=1, le=100), @@ -461,8 +573,11 @@ async def dashboard_topic_word_cloud( access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep, ) -> TopicWordCloud: organization = get_dashboard_organization(session, access_token) + selected_institution_id, _ = await get_dashboard_analytical_institution( + session, organization, institution_id + ) return await get_topic_word_cloud( - institution_id=organization.openalex_institution_id, + institution_id=selected_institution_id, topic_id=topic_id, 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 873c55f0..21a7351d 100644 --- a/service/src/main/inse/dashboard/service.py +++ b/service/src/main/inse/dashboard/service.py @@ -3,13 +3,17 @@ import logging from typing import Any from fastapi import HTTPException, status -from sqlmodel import Session +from sqlmodel import Session, select from inse import config -from inse.auth.model import AccessToken, Organization +from inse.auth.model import AccessToken, Organization, OrganizationInstitution +from inse.authors.institution_membership_query import ( + build_institution_membership_query, +) from inse.institutions.v2 import service as institutions_v2_service from inse.integrations import elasticsearch from inse.model import ESCluster, ESIndex +from inse.organization_management import service as organization_management_service from inse.patents.org.elastic_search_client import OrgPatentsSearchClient from inse.persons import service as persons_service from inse.works.v2 import service as works_v2_service @@ -22,6 +26,7 @@ from .common import ( raw_institution_id as _raw_institution_id, ) from .model import ( + DashboardInstitution, DashboardStatistics, DashboardStatisticValue, TopicHeatmap, @@ -45,6 +50,92 @@ TOPIC_WORD_CLOUD_LIMIT = 30 logger = logging.getLogger(__name__) +async def get_dashboard_institutions( + session: Session, + organization: Organization, +) -> list[DashboardInstitution]: + rows = session.exec( + select(OrganizationInstitution) + .where(OrganizationInstitution.organization_id == organization.id) + .order_by(OrganizationInstitution.position) + ).all() + institution_ids = [row.openalex_institution_id for row in rows] + if not institution_ids and organization.openalex_institution_id: + institution_ids = [_raw_institution_id(organization.openalex_institution_id)] + if not institution_ids: + return [] + + association_groups = ( + await organization_management_service.resolve_institution_associations( + institution_ids + ) + ) + institutions: dict[str, DashboardInstitution] = {} + for group in association_groups: + root_id = _raw_institution_id(group.id) + institutions[root_id] = DashboardInstitution( + id=root_id, + display_name=group.display_name, + ) + for association in group.associated_institutions: + association_id = _raw_institution_id(association.id) + institutions.setdefault( + association_id, + DashboardInstitution( + id=association_id, + display_name=association.display_name, + ), + ) + return list(institutions.values()) + + +async def get_dashboard_statistic_institution_ids( + session: Session, + organization: Organization, + selected_institution_id: str | None, +) -> list[str]: + institutions = await get_dashboard_institutions(session, organization) + institution_ids = [institution.id for institution in institutions] + if selected_institution_id in (None, "all"): + return institution_ids + + selected_id = _raw_institution_id(selected_institution_id) + if selected_id not in institution_ids: + raise HTTPException( + status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, + detail="Institution is not associated with this organization.", + ) + return [selected_id] + + +async def get_dashboard_analytical_institution( + session: Session, + organization: Organization, + selected_institution_id: str | None, +) -> tuple[str, str]: + if selected_institution_id in (None, "all"): + return organization.openalex_institution_id, organization.name + + selected_id = _raw_institution_id(selected_institution_id) + institutions = await get_dashboard_institutions(session, organization) + for institution in institutions: + if institution.id == selected_id: + return selected_id, institution.display_name + + raise HTTPException( + status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, + detail="Institution is not associated with this organization.", + ) + + +def _statistic_scope_id(institution_ids: list[str]) -> str: + return ( + _normalize_institution_id(institution_ids[0]) + if len(institution_ids) == 1 + else "all" + ) + + def _publication_year_filter(period: DashboardPeriod) -> dict[str, Any] | None: from_year, to_year = period year_range: dict[str, int] = {} @@ -104,12 +195,15 @@ async def get_dashboard_statistics( async def get_dashboard_publications( - institution_id: str, + institution_id: str | list[str], organization_name: str, from_year: int | None = None, to_year: int | None = None, ) -> DashboardStatisticValue: - normalized_id = _normalize_institution_id(institution_id) + institution_ids = ( + institution_id if isinstance(institution_id, list) else [institution_id] + ) + normalized_ids = [_normalize_institution_id(value) for value in institution_ids] period = _dashboard_period(from_year, to_year) publication_years: list[int] = [] if period != (None, None): @@ -120,67 +214,94 @@ async def get_dashboard_publications( works = await works_v2_service.get_works( page=0, size=1, - institution_ids=[normalized_id], + institution_ids=normalized_ids, publication_years=publication_years, ) return DashboardStatisticValue( - institution_id=normalized_id, + institution_id=_statistic_scope_id(institution_ids), organization_name=organization_name, value=works.total, ) async def get_dashboard_persons( - institution_id: str, + institution_id: str | list[str], organization_name: str, from_year: int | None = None, to_year: int | None = None, ) -> DashboardStatisticValue: - normalized_id = _normalize_institution_id(institution_id) + institution_ids = institution_id if isinstance(institution_id, list) else [institution_id] + normalized_ids = [_normalize_institution_id(value) for value in institution_ids] period = _dashboard_period(from_year, to_year) if (period[0] is None) != (period[1] is None): raise HTTPException( status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, detail="from_year and to_year must either both be provided or both omitted.", ) - persons = await persons_service.search_persons_list( - query=None, - institution_id=normalized_id, - sort_by=None, - sort_order=None, - topic=None, - page=1, - page_size=1, - include="", - year_filter_enabled=period[0] is not None, - filter_mode="between" if period[0] is not None else None, - filter_year=period[0], - filter_year_to=period[1], + if len(normalized_ids) == 1: + persons = await persons_service.search_persons_list( + query=None, + institution_id=normalized_ids[0], + sort_by=None, + sort_order=None, + topic=None, + page=1, + page_size=1, + include="", + year_filter_enabled=period[0] is not None, + filter_mode="between" if period[0] is not None else None, + filter_year=period[0], + filter_year_to=period[1], + ) + return DashboardStatisticValue( + institution_id=normalized_ids[0], + organization_name=organization_name, + value=int(persons.meta.count or 0) if persons.meta else 0, + ) + + membership_queries = [ + build_institution_membership_query( + institution_id=value, + year_mode="between" if period[0] is not None else "all", + year=period[0], + year_to=period[1], + ) + for value in normalized_ids + ] + value = await elasticsearch.count( + index="openalex-authors", + query={ + "bool": { + "should": membership_queries, + "minimum_should_match": 1, + } + }, ) return DashboardStatisticValue( - institution_id=normalized_id, + institution_id=_statistic_scope_id(institution_ids), organization_name=organization_name, - value=int(persons.meta.count or 0) if persons.meta else 0, + value=value, ) async def get_dashboard_patents( - institution_id: str, + institution_id: str | list[str], organization_name: str, from_year: int | None = None, to_year: int | None = None, ) -> DashboardStatisticValue: - normalized_id = _normalize_institution_id(institution_id) + institution_ids = institution_id if isinstance(institution_id, list) else [institution_id] + normalized_ids = [_normalize_institution_id(value) for value in institution_ids] period = _dashboard_period(from_year, to_year) _, total = await OrgPatentsSearchClient().search_by_institution( - normalized_id, + normalized_ids, page=0, size=0, from_year=period[0], to_year=period[1], ) return DashboardStatisticValue( - institution_id=normalized_id, + institution_id=_statistic_scope_id(institution_ids), organization_name=organization_name, value=total, ) diff --git a/service/src/main/inse/dashboard/test_service.py b/service/src/main/inse/dashboard/test_service.py index 4445262a..8f21c89b 100644 --- a/service/src/main/inse/dashboard/test_service.py +++ b/service/src/main/inse/dashboard/test_service.py @@ -8,8 +8,15 @@ from fastapi import HTTPException from sqlmodel import Session, SQLModel, create_engine from inse import config -from inse.auth.model import AccessToken, Organization, UserRole +from inse.auth.model import ( + AccessToken, + Organization, + OrganizationInstitution, + UserRole, +) from inse.dashboard.service import ( + get_dashboard_analytical_institution, + get_dashboard_institutions, get_dashboard_organization, get_dashboard_persons, get_dashboard_publications, @@ -22,8 +29,13 @@ from inse.dashboard.common import ( ) from inse.dashboard.bund_topics_service import get_dashboard_bund_topics from inse.dashboard.eu_topics_service import get_dashboard_eu_topics -from inse.dashboard.model import TopAuthor -from inse.dashboard.project_status_service import reconcile_status_counts +from inse.dashboard.model import DashboardStatisticValue, TopAuthor +from inse.dashboard.project_status_service import ( + get_dashboard_bmbf_project_statuses, + get_dashboard_dfg_project_statuses, + get_dashboard_eu_project_statuses, + reconcile_status_counts, +) from inse.dashboard.project_ids_service import ( _get_dfg_project_ids_from_projects_service, ) @@ -42,6 +54,10 @@ from inse.exceptions import ElasticsearchException from inse.model import ESIndex from inse.models.openalex.institution import Institution from inse.models.openalex.meta import Meta +from inse.organization_management.model import ( + InstitutionAssociation, + InstitutionAssociationsResponse, +) from inse.persons.model import CustomAuthorsListResponse from inse.projects.model import ( BundProjectPage, @@ -116,6 +132,100 @@ def test_project_status_counts_match_authoritative_total(): assert reconcile_status_counts(7, 4, 2, 3) == (2, 2, 3) +@pytest.mark.anyio +@pytest.mark.parametrize( + ("status_loader", "count_loader", "extra_dependency"), + [ + ( + get_dashboard_eu_project_statuses, + "get_dashboard_eu_projects", + "_institution_aliases", + ), + ( + get_dashboard_bmbf_project_statuses, + "get_dashboard_bmbf_projects", + "_institution_aliases", + ), + ( + get_dashboard_dfg_project_statuses, + "get_dashboard_dfg_projects", + "_get_dfg_project_ids_from_projects_service", + ), + ], +) +async def test_project_status_zero_count_is_not_an_error( + status_loader, count_loader, extra_dependency +): + zero_count = DashboardStatisticValue( + institution_id=ORG_INSTITUTION_ID, + organization_name="Example University", + value=0, + ) + with ( + patch( + f"inse.dashboard.project_status_service.{count_loader}", + new=AsyncMock(return_value=zero_count), + ), + patch( + f"inse.dashboard.project_status_service.{extra_dependency}", + new=AsyncMock(side_effect=AssertionError("must not be called")), + ), + ): + result = await status_loader(ORG_INSTITUTION_ID, "Example University") + + assert result.ongoing == 0 + assert result.upcoming == 0 + assert result.completed == 0 + + +@pytest.mark.anyio +async def test_dfg_project_status_uses_card_project_ids_and_total(): + card_total = DashboardStatisticValue( + institution_id=ORG_INSTITUTION_ID, + organization_name="University Hospital Essen", + value=24, + ) + status_aggregations = { + "aggregations": { + "projects_nested": { + "selected_projects": { + "ongoing": {"projects": {"value": 7}}, + "completed": {"projects": {"value": 17}}, + } + } + } + } + with ( + patch( + "inse.dashboard.project_status_service.get_dashboard_dfg_projects", + new=AsyncMock(return_value=card_total), + ), + patch( + "inse.dashboard.project_status_service._get_dfg_project_ids_from_projects_service", + new=AsyncMock( + return_value=[str(project_id) for project_id in range(1, 25)] + ), + ) as project_ids_loader, + patch( + "inse.dashboard.project_status_service.elasticsearch.search", + new=AsyncMock(return_value=status_aggregations), + ), + ): + result = await get_dashboard_dfg_project_statuses( + ORG_INSTITUTION_ID, + "University Hospital Essen", + ) + + project_ids_loader.assert_awaited_once_with( + ORG_INSTITUTION_ID, + from_year=None, + to_year=None, + ) + assert result.ongoing == 7 + assert result.completed == 17 + assert result.ongoing + result.upcoming + result.completed == 24 + + def test_project_status_period_uses_interval_overlap(): assert _project_boundary_year_filter( "startDate", "endDate", (2022, 2026), "iso" @@ -971,11 +1081,11 @@ def test_eu_author_count_groups_multiple_publications_by_project_id(): works_response, doi_project_ids, ORG_INSTITUTION_ID, - {"https://openalex.org/A5007170803"}, ) assert [author.model_dump() for author in result] == [ - {"id": "A5007170803", "name": "Marcus Example", "count": 1} + {"id": "A999", "name": "External Example", "count": 1}, + {"id": "A5007170803", "name": "Marcus Example", "count": 1}, ] @@ -1618,6 +1728,161 @@ def test_get_dashboard_organization_uses_effective_organization(): assert result.openalex_institution_id == "I456" +@pytest.mark.anyio +async def test_dashboard_institutions_include_openalex_associations(): + engine = create_engine("sqlite://", connect_args={"check_same_thread": False}) + SQLModel.metadata.create_all(engine) + + with Session(engine) as session: + organization = Organization( + name="Example University", + openalex_institution_id="I123", + ) + session.add(organization) + session.commit() + session.refresh(organization) + session.add( + OrganizationInstitution( + organization_id=organization.id, + openalex_institution_id="I123", + position=0, + ) + ) + session.commit() + + associations = [ + InstitutionAssociationsResponse( + id="I123", + display_name="Main institution", + associated_institutions=[ + InstitutionAssociation( + id="I456", + display_name="Child institution", + relationship="child", + ), + InstitutionAssociation( + id="I789", + display_name="Related institution", + relationship="related", + ), + ], + ) + ] + with patch( + "inse.dashboard.service.organization_management_service." + "resolve_institution_associations", + new=AsyncMock(return_value=associations), + ): + result = await get_dashboard_institutions(session, organization) + + assert [institution.model_dump() for institution in result] == [ + {"id": "I123", "display_name": "Main institution"}, + {"id": "I456", "display_name": "Child institution"}, + {"id": "I789", "display_name": "Related institution"}, + ] + + +@pytest.mark.anyio +async def test_dashboard_analytical_institution_all_uses_root_organization(): + engine = create_engine("sqlite://", connect_args={"check_same_thread": False}) + SQLModel.metadata.create_all(engine) + + with Session(engine) as session: + organization = Organization( + name="Example University", + openalex_institution_id="I123", + ) + session.add(organization) + session.commit() + session.refresh(organization) + + result = await get_dashboard_analytical_institution( + session, + organization, + "all", + ) + + assert result == ("I123", "Example University") + + +@pytest.mark.anyio +async def test_dashboard_analytical_institution_uses_selected_tab_institution(): + engine = create_engine("sqlite://", connect_args={"check_same_thread": False}) + SQLModel.metadata.create_all(engine) + + with Session(engine) as session: + organization = Organization( + name="Example University", + openalex_institution_id="I123", + ) + session.add(organization) + session.commit() + session.refresh(organization) + session.add( + OrganizationInstitution( + organization_id=organization.id, + openalex_institution_id="I123", + position=0, + ) + ) + session.commit() + + associations = [ + InstitutionAssociationsResponse( + id="I123", + display_name="Main institution", + associated_institutions=[ + InstitutionAssociation( + id="I456", + display_name="Child institution", + relationship="child", + ), + ], + ) + ] + with patch( + "inse.dashboard.service.organization_management_service." + "resolve_institution_associations", + new=AsyncMock(return_value=associations), + ): + result = await get_dashboard_analytical_institution( + session, + organization, + "https://openalex.org/I456", + ) + + assert result == ("I456", "Child institution") + + +@pytest.mark.anyio +async def test_dashboard_analytical_institution_rejects_unassociated_selection(): + engine = create_engine("sqlite://", connect_args={"check_same_thread": False}) + SQLModel.metadata.create_all(engine) + + with Session(engine) as session: + organization = Organization( + name="Example University", + openalex_institution_id="I123", + ) + session.add(organization) + session.commit() + session.refresh(organization) + + with patch( + "inse.dashboard.service.organization_management_service." + "resolve_institution_associations", + new=AsyncMock(return_value=[]), + ): + with pytest.raises(HTTPException) as exc_info: + await get_dashboard_analytical_institution( + session, + organization, + "I999", + ) + + assert exc_info.value.status_code == 422 + + def test_get_dashboard_organization_rejects_missing_openalex_id(): engine = create_engine("sqlite://", connect_args={"check_same_thread": False}) SQLModel.metadata.create_all(engine) diff --git a/service/src/main/inse/dashboard/top_authors_service.py b/service/src/main/inse/dashboard/top_authors_service.py index 72a8c1e2..79d63846 100644 --- a/service/src/main/inse/dashboard/top_authors_service.py +++ b/service/src/main/inse/dashboard/top_authors_service.py @@ -79,7 +79,6 @@ async def get_top_authors( "eu_projects", _top_eu_project_publication_authors( normalized_id, - authors, from_year=period[0], to_year=period[1], ), @@ -152,12 +151,10 @@ async def get_top_eu_project_authors( ) -> TopAuthorAnalysis: normalized_id = _normalize_institution_id(institution_id) period = _period(from_year=from_year, to_year=to_year) - authors = await _safe_institution_authors(normalized_id) return TopAuthorAnalysis( institution_id=normalized_id, authors=await _top_eu_project_publication_authors( normalized_id, - authors, from_year=period[0], to_year=period[1], ), @@ -825,18 +822,9 @@ async def _top_patent_authors( async def _top_eu_project_publication_authors( institution_id: str, - institution_authors: list[dict[str, Any]], from_year: int | None = None, to_year: int | None = None, ) -> list[TopAuthor]: - institution_author_ids = { - author_id - for author in institution_authors - if (author_id := _normalize_author_id(author.get("id"))) - } - if not institution_author_ids: - return [] - # Candidate discovery is deliberately all-time. The selected period is # applied to each person's authoritative project count below. Otherwise a # person can disappear merely because their recent projects have no linked @@ -889,7 +877,6 @@ async def _top_eu_project_publication_authors( works_response, doi_project_ids, institution_id, - institution_author_ids, limit=None, ) ranked = await _count_eu_projects_for_candidates( @@ -976,7 +963,6 @@ def _openalex_work_authors_by_eu_projects( response: dict[str, Any], 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 @@ -999,11 +985,7 @@ def _openalex_work_authors_by_eu_projects( author = authorship.get("author") or {} author_id = _normalize_author_id(author.get("id")) author_name = str(author.get("display_name") or "").strip() - if ( - not author_id - or author_id not in institution_author_ids - or not author_name - ): + if not author_id or not author_name: continue author_project_ids[author_id].update(project_ids) author_names.setdefault(author_id, author_name) diff --git a/service/src/main/inse/organization_management/service.py b/service/src/main/inse/organization_management/service.py index 072db92a..6b8b4c10 100644 --- a/service/src/main/inse/organization_management/service.py +++ b/service/src/main/inse/organization_management/service.py @@ -352,6 +352,12 @@ async def get_institution_associations( institution_ids: list[str], ) -> list[InstitutionAssociationsResponse]: _require_super_admin(access_token) + return await resolve_institution_associations(institution_ids) + + +async def resolve_institution_associations( + institution_ids: list[str], +) -> list[InstitutionAssociationsResponse]: clean_ids = _normalize_institution_ids(institution_ids) if not clean_ids: return [] 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 0bee7f9e..8d8d6cd2 100644 --- a/service/src/main/inse/patents/org/elastic_search_client.py +++ b/service/src/main/inse/patents/org/elastic_search_client.py @@ -251,7 +251,7 @@ class OrgPatentsSearchClient: async def search_by_institution( self, - institution_id: str, + institution_id: str | list[str], match_type: MatchTypeFilter = "all", page: int = 0, size: int = DEFAULT_PAGE_SIZE, @@ -259,8 +259,16 @@ class OrgPatentsSearchClient: 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}}] + institution_ids = ( + institution_id if isinstance(institution_id, list) else [institution_id] + ) + short_ids = [ + value.replace("https://openalex.org/", "").upper() + for value in institution_ids + ] + filters: list[dict[str, Any]] = [ + {"terms": {"institution_id": short_ids}} + ] if match_type == "institution": filters.append({"terms": {"match_type": ["institution", "both"]}}) diff --git a/service/src/main/inse/projects/router.py b/service/src/main/inse/projects/router.py index 69aaae66..963c1f96 100644 --- a/service/src/main/inse/projects/router.py +++ b/service/src/main/inse/projects/router.py @@ -30,6 +30,7 @@ from inse.projects.model import ( SortDirection, ) from inse.tags import Tags +from inse.database import SessionDep from inse.auth.service import can_fetch_gdpr_relevant_data from fastapi import HTTPException as HttpException @@ -78,26 +79,36 @@ async def search_bund_projects( "model": DfgProjectPage, }, status.HTTP_404_NOT_FOUND: {"description": "Institution not found"}, - status.HTTP_403_FORBIDDEN: {"description": "Access denied for the provided institution ID"}, + status.HTTP_403_FORBIDDEN: { + "description": "Access denied for the provided institution ID" + }, }, response_model_by_alias=False, ) async def get_dfg_projects( - access_token_metadata: Annotated[AccessTokenMetadata, CurrentUserAccessTokenPayloadDep], + session: SessionDep, + access_token_metadata: Annotated[ + AccessTokenMetadata, CurrentUserAccessTokenPayloadDep + ], institutions_search_client: Annotated[ InstitutionsSearchClient, Depends(get_institutions_search_client) ], raw_oa_institution_id: Annotated[ str | None, Query(description="The openalex institution ID to filter by.") ] = None, - author_id: Annotated[str | None, Query(description="The openalex author ID to filter by.")] = None, - author_filter_ids: Annotated[list[str] | None, Query(description="The dfg author IDs to filter by.")] = None, - institution_ids: Annotated[list[str] | None, Query(description="The institution IDs to filter by.")] = None, - title: Annotated[ - str | None, Query(description="The title to filter by.") + author_id: Annotated[ + str | None, Query(description="The openalex author ID to filter by.") ] = None, + author_filter_ids: Annotated[ + list[str] | None, Query(description="The dfg author IDs to filter by.") + ] = None, + institution_ids: Annotated[ + list[str] | None, Query(description="The institution IDs to filter by.") + ] = None, + title: Annotated[str | None, Query(description="The title to filter by.")] = None, keywords: Annotated[ - list[str] | None, Query(description="Raw keywords to search in title/abstract/subject fields.") + list[str] | None, + Query(description="Raw keywords to search in title/abstract/subject fields."), ] = None, topic_ids: Annotated[ list[str] | None, Query(description="The openalex topic IDs to filter by.") @@ -106,12 +117,15 @@ async def get_dfg_projects( list[str] | None, Query( description="Additional topic IDs to merge into the fuzzy topic-id resolution " - "(union with topic_ids). Only used when fuzzy=True." + "(union with topic_ids). Only used when fuzzy=True." ), ] = None, - funding_start_years: Annotated[list[str] | None, Query(description="The funding start years to filter by.")] = None, - funding_end_years: Annotated[list[str] | None, Query(description="The funding end years to filter by.")] = None, - + funding_start_years: Annotated[ + list[str] | None, Query(description="The funding start years to filter by.") + ] = None, + funding_end_years: Annotated[ + list[str] | None, Query(description="The funding end years to filter by.") + ] = None, page: Annotated[int, Query(description="The page number.", ge=0)] = 0, size: Annotated[int, Query(description="The page size.", ge=1)] = 20, sort_by: Annotated[str, Query(description="The field to sort by.")] = "", @@ -120,9 +134,10 @@ async def get_dfg_projects( ] = "asc", fuzzy: Annotated[ bool, - Query(description="Use topic_id resolution if True, otherwise use raw keyword search."), + Query( + description="Use topic_id resolution if True, otherwise use raw keyword search." + ), ] = False, - ) -> DfgProjectPage: logger.debug( "Received request to get DFG projects for author_id=%s, author_filter_ids=%s, " @@ -144,8 +159,13 @@ async def get_dfg_projects( sort_direction, fuzzy, ) - if (author_id or raw_oa_institution_id): - is_allowed = await can_fetch_gdpr_relevant_data(access_token = access_token_metadata, raw_oa_author_id = author_id, raw_oa_institution_id = raw_oa_institution_id) + if author_id or raw_oa_institution_id: + is_allowed = await can_fetch_gdpr_relevant_data( + session=session, + access_token=access_token_metadata, + raw_oa_author_id=author_id, + raw_oa_institution_id=raw_oa_institution_id, + ) if not is_allowed: raise HttpException( status_code=403, @@ -170,6 +190,7 @@ async def get_dfg_projects( fuzzy=fuzzy, ) + @router.get( "/dfg/{id}", summary="Get a single DFG project.", @@ -204,12 +225,17 @@ async def get_single_dfg_project( "model": BundProjectPage, }, status.HTTP_404_NOT_FOUND: {"description": "Institution not found"}, - status.HTTP_403_FORBIDDEN: {"description": "Access denied for the provided institution ID"}, + status.HTTP_403_FORBIDDEN: { + "description": "Access denied for the provided institution ID" + }, }, response_model_by_alias=False, ) async def search_bund_projects( - access_token_metadata: Annotated[AccessTokenMetadata, CurrentUserAccessTokenPayloadDep], + session: SessionDep, + access_token_metadata: Annotated[ + AccessTokenMetadata, CurrentUserAccessTokenPayloadDep + ], institutions_search_client: Annotated[ InstitutionsSearchClient, Depends(get_institutions_search_client) ], @@ -262,11 +288,18 @@ async def search_bund_projects( ] = "asc", fuzzy: Annotated[ bool, - Query(description="Use OpenAlex topic-id resolution if true, otherwise raw keyword search."), + Query( + description="Use OpenAlex topic-id resolution if true, otherwise raw keyword search." + ), ] = False, ) -> BundProjectPage: - if (raw_oa_institution_id): - is_allowed = await can_fetch_gdpr_relevant_data(access_token = access_token_metadata, raw_oa_author_id = None, raw_oa_institution_id = raw_oa_institution_id) + if raw_oa_institution_id: + is_allowed = await can_fetch_gdpr_relevant_data( + session=session, + access_token=access_token_metadata, + raw_oa_author_id=None, + raw_oa_institution_id=raw_oa_institution_id, + ) if not is_allowed: raise HttpException( status_code=403, @@ -288,9 +321,10 @@ async def search_bund_projects( size=size, sort_by=sort_by, sort_direction=sort_direction, - fuzzy=fuzzy + fuzzy=fuzzy, ) - + + @router.get( "/bund/{id}", summary="Get a single BUND project.", @@ -313,6 +347,7 @@ async def get_single_bund_project( project_id=id, ) + ######## from inse.projects.model import EuCordisProjectSearchPage, EuCordisProjectType from inse.projects.service import search_eu_cordis_projects @@ -334,12 +369,17 @@ from inse.projects.service import search_eu_cordis_projects "model": EuCordisProjectSearchPage, }, status.HTTP_404_NOT_FOUND: {"description": "Institution not found"}, - status.HTTP_403_FORBIDDEN: {"description": "Access denied for the provided institution ID"}, + status.HTTP_403_FORBIDDEN: { + "description": "Access denied for the provided institution ID" + }, }, response_model_by_alias=False, ) async def search_eu_cordis_projects_endpoint( - access_token_metadata: Annotated[AccessTokenMetadata, CurrentUserAccessTokenPayloadDep], + session: SessionDep, + access_token_metadata: Annotated[ + AccessTokenMetadata, CurrentUserAccessTokenPayloadDep + ], institutions_search_client: Annotated[ InstitutionsSearchClient, Depends(get_institutions_search_client) ], @@ -353,15 +393,21 @@ async def search_eu_cordis_projects_endpoint( ] = None, author_ids: Annotated[ list[str] | None, - Query(description="Additional OpenAlex author IDs to filter by. All selected authors must match."), + Query( + description="Additional OpenAlex author IDs to filter by. All selected authors must match." + ), ] = None, organization_ids: Annotated[ list[str] | None, - Query(description="CORDIS organisation IDs. All selected organizations must match."), + Query( + description="CORDIS organisation IDs. All selected organizations must match." + ), ] = None, organization_names: Annotated[ list[str] | None, - Query(description="CORDIS organization names. All selected organizations must match."), + Query( + description="CORDIS organization names. All selected organizations must match." + ), ] = None, project_types: Annotated[ list[EuCordisProjectType] | None, @@ -416,9 +462,10 @@ async def search_eu_cordis_projects_endpoint( ] = "asc", fuzzy: Annotated[ bool, - Query(description="Use OpenAlex topic-id resolution if true, otherwise raw keyword search."), + Query( + description="Use OpenAlex topic-id resolution if true, otherwise raw keyword search." + ), ] = False, - ) -> EuCordisProjectSearchPage: logger.debug( "Received EU CORDIS search request: raw_oa_institution_id=%s, " @@ -450,8 +497,13 @@ async def search_eu_cordis_projects_endpoint( sort_direction, fuzzy, ) - if (author_id or raw_oa_institution_id): - is_allowed = await can_fetch_gdpr_relevant_data(access_token = access_token_metadata, raw_oa_author_id = author_id, raw_oa_institution_id = raw_oa_institution_id) + if author_id or raw_oa_institution_id: + is_allowed = await can_fetch_gdpr_relevant_data( + session=session, + access_token=access_token_metadata, + raw_oa_author_id=author_id, + raw_oa_institution_id=raw_oa_institution_id, + ) if not is_allowed: raise HttpException( status_code=403, @@ -482,6 +534,7 @@ async def search_eu_cordis_projects_endpoint( fuzzy=fuzzy, ) + @router.get( "/eu/{id}", summary="Get a single EU Cordis project.", @@ -494,27 +547,29 @@ async def search_eu_cordis_projects_endpoint( }, status.HTTP_404_NOT_FOUND: { "description": "Project not found", - "model": EuCordisProjectResponse + "model": EuCordisProjectResponse, }, status.HTTP_500_INTERNAL_SERVER_ERROR: { "description": "Internal server error", - "model": EuCordisProjectResponse - } + "model": EuCordisProjectResponse, + }, }, ) async def get_single_eu_cordis_project( - id: Annotated[str, Path(description="The ID of the EU Cordis project to retrieve.")], + id: Annotated[ + str, Path(description="The ID of the EU Cordis project to retrieve.") + ], ) -> EuCordisProjectResponse: """ Get a single EU Cordis project by ID. Returns a wrapper response containing the project data or error information. """ logger.debug(f"Received request to get single EU Cordis project for id={id}") - + try: # Get the project from the service project = await projects_service.get_single_eu_cordis_project(project_id=id) - + # Check if project exists if project is None: logger.warning(f"Project with ID {id} not found") @@ -522,9 +577,9 @@ async def get_single_eu_cordis_project( success=False, project_type=None, eu_project_data=None, - error=f"Project with ID {id} not found" + error=f"Project with ID {id} not found", ) - + # Determine the project type if isinstance(project, Fp7ProjectDetails): project_type = "fp7" @@ -539,24 +594,21 @@ async def get_single_eu_cordis_project( success=False, project_type=None, eu_project_data=None, - error=f"Unknown project type for ID {id}" + error=f"Unknown project type for ID {id}", ) - + # Return success with the project data return EuCordisProjectResponse( - success=True, - project_type=project_type, - eu_project_data=project, - error=None + success=True, project_type=project_type, eu_project_data=project, error=None ) - + except Exception as e: logger.error(f"Error retrieving project with ID {id}: {e!s}", exc_info=True) return EuCordisProjectResponse( success=False, project_type=None, eu_project_data=None, - error=f"Internal server error: {e!s}" + error=f"Internal server error: {e!s}", ) @@ -623,7 +675,9 @@ async def get_institution_bund_projects_funding_over_time( ] = None, fuzzy: Annotated[ bool, - Query(description="Use OpenAlex topic-id resolution if true, otherwise raw keyword search."), + Query( + description="Use OpenAlex topic-id resolution if true, otherwise raw keyword search." + ), ] = False, ) -> InstitutionFunderSummary: return await projects_service.get_institution_bund_projects_funding_over_time( @@ -674,15 +728,21 @@ async def get_institution_cordis_eu_projects_funding_over_time( ] = None, author_ids: Annotated[ list[str] | None, - Query(description="Additional OpenAlex author IDs to filter by. All selected authors must match."), + Query( + description="Additional OpenAlex author IDs to filter by. All selected authors must match." + ), ] = None, organization_ids: Annotated[ list[str] | None, - Query(description="CORDIS organisation IDs. All selected organizations must match."), + Query( + description="CORDIS organisation IDs. All selected organizations must match." + ), ] = None, organization_names: Annotated[ list[str] | None, - Query(description="CORDIS organization names. All selected organizations must match."), + Query( + description="CORDIS organization names. All selected organizations must match." + ), ] = None, project_types: Annotated[ list[EuCordisProjectType] | None, @@ -730,7 +790,9 @@ async def get_institution_cordis_eu_projects_funding_over_time( ] = None, fuzzy: Annotated[ bool, - Query(description="Use OpenAlex topic-id resolution if true, otherwise raw keyword search."), + Query( + description="Use OpenAlex topic-id resolution if true, otherwise raw keyword search." + ), ] = False, ) -> InstitutionFunderSummary: return await projects_service.get_institution_cordis_eu_projects_funding_over_time( @@ -777,9 +839,7 @@ async def search_projects( description="The set of project types to filter by (e.g., 'bund', 'eu', 'dfg'). If not provided, projects of all types will be included." ), ] = None, - title: Annotated[ - str | None, Query(description="The title to filter by.") - ] = None, + title: Annotated[str | None, Query(description="The title to filter by.")] = None, sort_by: Annotated[ ProjectsSortBy, Query(description="The field to sort by.") ] = ProjectsSortBy.TITLE, @@ -794,4 +854,4 @@ async def search_projects( title=title, sort_by=sort_by, sort_direction=sort_direction, - ) \ No newline at end of file + ) diff --git a/service/src/main/inse/projects/service.py b/service/src/main/inse/projects/service.py index 331cc6c8..f17e6b6b 100644 --- a/service/src/main/inse/projects/service.py +++ b/service/src/main/inse/projects/service.py @@ -190,6 +190,7 @@ async def get_dfg_projects( skip_enrichment: bool = False, active_from_year: int | None = None, active_to_year: int | None = None, + institution_aliases: list[str] | None = None, ) -> DfgProjectPage: logger.debug( "Fetching DFG projects for author_id=%s, author_filter_ids=%s, " @@ -251,18 +252,18 @@ async def get_dfg_projects( "No author names found for author_filter_ids=%s", author_filter_ids_int, ) - institution_aliases = [] + resolved_institution_aliases = list(institution_aliases or []) if raw_oa_institution_id: if institutions_search_client is None: raise ValueError( "institutions_search_client must be provided when raw_oa_institution_id is set" ) - institution_aliases = ( + resolved_institution_aliases.extend( await institutions_search_client.get_institution_aliases_by_oa_institution_id( raw_oa_institution_id ) ) - if not institution_aliases: + if not resolved_institution_aliases: return DfgProjectPage( elements=[], page=page, @@ -272,7 +273,7 @@ async def get_dfg_projects( return await projects_search_client.search_dfg_projects( page=page, size=size, - institution_aliases=institution_aliases, + institution_aliases=resolved_institution_aliases, project_ids=author_project_ids, names=filter_names or [], institution_ids=institution_ids_int, @@ -465,8 +466,9 @@ async def search_bund_projects_with_filters( fuzzy: bool = False, active_from_year: int | None = None, active_to_year: int | None = None, + oa_institution_aliases: list[str] | None = None, ) -> BundProjectPage: - institution_aliases = [] + institution_aliases = list(oa_institution_aliases or []) if raw_oa_institution_id: if institutions_search_client is None: raise ValueError( diff --git a/service/uv.lock b/service/uv.lock index 2305fae5..3992b104 100644 --- a/service/uv.lock +++ b/service/uv.lock @@ -712,6 +712,53 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/df/b2/87e62e8c3e2f4b32e5fe99e0b86d576da1312593b39f47d8ceef365e95ed/packaging-26.2-py3-none-any.whl", hash = "sha256:5fc45236b9446107ff2415ce77c807cee2862cb6fac22b8a73826d0693b0980e", size = 100195, upload-time = "2026-04-24T20:15:22.081Z" }, ] +[[package]] +name = "pandas" +version = "2.3.3" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "numpy" }, + { name = "python-dateutil" }, + { name = "pytz" }, + { name = "tzdata" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/33/01/d40b85317f86cf08d853a4f495195c73815fdf205eef3993821720274518/pandas-2.3.3.tar.gz", hash = "sha256:e05e1af93b977f7eafa636d043f9f94c7ee3ac81af99c13508215942e64c993b", size = 4495223, upload-time = "2025-09-29T23:34:51.853Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/9c/fb/231d89e8637c808b997d172b18e9d4a4bc7bf31296196c260526055d1ea0/pandas-2.3.3-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:6d21f6d74eb1725c2efaa71a2bfc661a0689579b58e9c0ca58a739ff0b002b53", size = 11597846, upload-time = "2025-09-29T23:19:48.856Z" }, + { url = "https://files.pythonhosted.org/packages/5c/bd/bf8064d9cfa214294356c2d6702b716d3cf3bb24be59287a6a21e24cae6b/pandas-2.3.3-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:3fd2f887589c7aa868e02632612ba39acb0b8948faf5cc58f0850e165bd46f35", size = 10729618, upload-time = "2025-09-29T23:39:08.659Z" }, + { url = "https://files.pythonhosted.org/packages/57/56/cf2dbe1a3f5271370669475ead12ce77c61726ffd19a35546e31aa8edf4e/pandas-2.3.3-cp312-cp312-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:ecaf1e12bdc03c86ad4a7ea848d66c685cb6851d807a26aa245ca3d2017a1908", size = 11737212, upload-time = "2025-09-29T23:19:59.765Z" }, + { url = "https://files.pythonhosted.org/packages/e5/63/cd7d615331b328e287d8233ba9fdf191a9c2d11b6af0c7a59cfcec23de68/pandas-2.3.3-cp312-cp312-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:b3d11d2fda7eb164ef27ffc14b4fcab16a80e1ce67e9f57e19ec0afaf715ba89", size = 12362693, upload-time = "2025-09-29T23:20:14.098Z" }, + { url = "https://files.pythonhosted.org/packages/a6/de/8b1895b107277d52f2b42d3a6806e69cfef0d5cf1d0ba343470b9d8e0a04/pandas-2.3.3-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:a68e15f780eddf2b07d242e17a04aa187a7ee12b40b930bfdd78070556550e98", size = 12771002, upload-time = "2025-09-29T23:20:26.76Z" }, + { url = "https://files.pythonhosted.org/packages/87/21/84072af3187a677c5893b170ba2c8fbe450a6ff911234916da889b698220/pandas-2.3.3-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:371a4ab48e950033bcf52b6527eccb564f52dc826c02afd9a1bc0ab731bba084", size = 13450971, upload-time = "2025-09-29T23:20:41.344Z" }, + { url = "https://files.pythonhosted.org/packages/86/41/585a168330ff063014880a80d744219dbf1dd7a1c706e75ab3425a987384/pandas-2.3.3-cp312-cp312-win_amd64.whl", hash = "sha256:a16dcec078a01eeef8ee61bf64074b4e524a2a3f4b3be9326420cabe59c4778b", size = 10992722, upload-time = "2025-09-29T23:20:54.139Z" }, + { url = "https://files.pythonhosted.org/packages/cd/4b/18b035ee18f97c1040d94debd8f2e737000ad70ccc8f5513f4eefad75f4b/pandas-2.3.3-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:56851a737e3470de7fa88e6131f41281ed440d29a9268dcbf0002da5ac366713", size = 11544671, upload-time = "2025-09-29T23:21:05.024Z" }, + { url = "https://files.pythonhosted.org/packages/31/94/72fac03573102779920099bcac1c3b05975c2cb5f01eac609faf34bed1ca/pandas-2.3.3-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:bdcd9d1167f4885211e401b3036c0c8d9e274eee67ea8d0758a256d60704cfe8", size = 10680807, upload-time = "2025-09-29T23:21:15.979Z" }, + { url = "https://files.pythonhosted.org/packages/16/87/9472cf4a487d848476865321de18cc8c920b8cab98453ab79dbbc98db63a/pandas-2.3.3-cp313-cp313-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:e32e7cc9af0f1cc15548288a51a3b681cc2a219faa838e995f7dc53dbab1062d", size = 11709872, upload-time = "2025-09-29T23:21:27.165Z" }, + { url = "https://files.pythonhosted.org/packages/15/07/284f757f63f8a8d69ed4472bfd85122bd086e637bf4ed09de572d575a693/pandas-2.3.3-cp313-cp313-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:318d77e0e42a628c04dc56bcef4b40de67918f7041c2b061af1da41dcff670ac", size = 12306371, upload-time = "2025-09-29T23:21:40.532Z" }, + { url = "https://files.pythonhosted.org/packages/33/81/a3afc88fca4aa925804a27d2676d22dcd2031c2ebe08aabd0ae55b9ff282/pandas-2.3.3-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:4e0a175408804d566144e170d0476b15d78458795bb18f1304fb94160cabf40c", size = 12765333, upload-time = "2025-09-29T23:21:55.77Z" }, + { url = "https://files.pythonhosted.org/packages/8d/0f/b4d4ae743a83742f1153464cf1a8ecfafc3ac59722a0b5c8602310cb7158/pandas-2.3.3-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:93c2d9ab0fc11822b5eece72ec9587e172f63cff87c00b062f6e37448ced4493", size = 13418120, upload-time = "2025-09-29T23:22:10.109Z" }, + { url = "https://files.pythonhosted.org/packages/4f/c7/e54682c96a895d0c808453269e0b5928a07a127a15704fedb643e9b0a4c8/pandas-2.3.3-cp313-cp313-win_amd64.whl", hash = "sha256:f8bfc0e12dc78f777f323f55c58649591b2cd0c43534e8355c51d3fede5f4dee", size = 10993991, upload-time = "2025-09-29T23:25:04.889Z" }, + { url = "https://files.pythonhosted.org/packages/f9/ca/3f8d4f49740799189e1395812f3bf23b5e8fc7c190827d55a610da72ce55/pandas-2.3.3-cp313-cp313t-macosx_10_13_x86_64.whl", hash = "sha256:75ea25f9529fdec2d2e93a42c523962261e567d250b0013b16210e1d40d7c2e5", size = 12048227, upload-time = "2025-09-29T23:22:24.343Z" }, + { url = "https://files.pythonhosted.org/packages/0e/5a/f43efec3e8c0cc92c4663ccad372dbdff72b60bdb56b2749f04aa1d07d7e/pandas-2.3.3-cp313-cp313t-macosx_11_0_arm64.whl", hash = "sha256:74ecdf1d301e812db96a465a525952f4dde225fdb6d8e5a521d47e1f42041e21", size = 11411056, upload-time = "2025-09-29T23:22:37.762Z" }, + { url = "https://files.pythonhosted.org/packages/46/b1/85331edfc591208c9d1a63a06baa67b21d332e63b7a591a5ba42a10bb507/pandas-2.3.3-cp313-cp313t-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:6435cb949cb34ec11cc9860246ccb2fdc9ecd742c12d3304989017d53f039a78", size = 11645189, upload-time = "2025-09-29T23:22:51.688Z" }, + { url = "https://files.pythonhosted.org/packages/44/23/78d645adc35d94d1ac4f2a3c4112ab6f5b8999f4898b8cdf01252f8df4a9/pandas-2.3.3-cp313-cp313t-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:900f47d8f20860de523a1ac881c4c36d65efcb2eb850e6948140fa781736e110", size = 12121912, upload-time = "2025-09-29T23:23:05.042Z" }, + { url = "https://files.pythonhosted.org/packages/53/da/d10013df5e6aaef6b425aa0c32e1fc1f3e431e4bcabd420517dceadce354/pandas-2.3.3-cp313-cp313t-musllinux_1_2_aarch64.whl", hash = "sha256:a45c765238e2ed7d7c608fc5bc4a6f88b642f2f01e70c0c23d2224dd21829d86", size = 12712160, upload-time = "2025-09-29T23:23:28.57Z" }, + { url = "https://files.pythonhosted.org/packages/bd/17/e756653095a083d8a37cbd816cb87148debcfcd920129b25f99dd8d04271/pandas-2.3.3-cp313-cp313t-musllinux_1_2_x86_64.whl", hash = "sha256:c4fc4c21971a1a9f4bdb4c73978c7f7256caa3e62b323f70d6cb80db583350bc", size = 13199233, upload-time = "2025-09-29T23:24:24.876Z" }, + { url = "https://files.pythonhosted.org/packages/04/fd/74903979833db8390b73b3a8a7d30d146d710bd32703724dd9083950386f/pandas-2.3.3-cp314-cp314-macosx_10_13_x86_64.whl", hash = "sha256:ee15f284898e7b246df8087fc82b87b01686f98ee67d85a17b7ab44143a3a9a0", size = 11540635, upload-time = "2025-09-29T23:25:52.486Z" }, + { url = "https://files.pythonhosted.org/packages/21/00/266d6b357ad5e6d3ad55093a7e8efc7dd245f5a842b584db9f30b0f0a287/pandas-2.3.3-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:1611aedd912e1ff81ff41c745822980c49ce4a7907537be8692c8dbc31924593", size = 10759079, upload-time = "2025-09-29T23:26:33.204Z" }, + { url = "https://files.pythonhosted.org/packages/ca/05/d01ef80a7a3a12b2f8bbf16daba1e17c98a2f039cbc8e2f77a2c5a63d382/pandas-2.3.3-cp314-cp314-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:6d2cefc361461662ac48810cb14365a365ce864afe85ef1f447ff5a1e99ea81c", size = 11814049, upload-time = "2025-09-29T23:27:15.384Z" }, + { url = "https://files.pythonhosted.org/packages/15/b2/0e62f78c0c5ba7e3d2c5945a82456f4fac76c480940f805e0b97fcbc2f65/pandas-2.3.3-cp314-cp314-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:ee67acbbf05014ea6c763beb097e03cd629961c8a632075eeb34247120abcb4b", size = 12332638, upload-time = "2025-09-29T23:27:51.625Z" }, + { url = "https://files.pythonhosted.org/packages/c5/33/dd70400631b62b9b29c3c93d2feee1d0964dc2bae2e5ad7a6c73a7f25325/pandas-2.3.3-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:c46467899aaa4da076d5abc11084634e2d197e9460643dd455ac3db5856b24d6", size = 12886834, upload-time = "2025-09-29T23:28:21.289Z" }, + { url = "https://files.pythonhosted.org/packages/d3/18/b5d48f55821228d0d2692b34fd5034bb185e854bdb592e9c640f6290e012/pandas-2.3.3-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:6253c72c6a1d990a410bc7de641d34053364ef8bcd3126f7e7450125887dffe3", size = 13409925, upload-time = "2025-09-29T23:28:58.261Z" }, + { url = "https://files.pythonhosted.org/packages/a6/3d/124ac75fcd0ecc09b8fdccb0246ef65e35b012030defb0e0eba2cbbbe948/pandas-2.3.3-cp314-cp314-win_amd64.whl", hash = "sha256:1b07204a219b3b7350abaae088f451860223a52cfb8a6c53358e7948735158e5", size = 11109071, upload-time = "2025-09-29T23:32:27.484Z" }, + { url = "https://files.pythonhosted.org/packages/89/9c/0e21c895c38a157e0faa1fb64587a9226d6dd46452cac4532d80c3c4a244/pandas-2.3.3-cp314-cp314t-macosx_10_13_x86_64.whl", hash = "sha256:2462b1a365b6109d275250baaae7b760fd25c726aaca0054649286bcfbb3e8ec", size = 12048504, upload-time = "2025-09-29T23:29:31.47Z" }, + { url = "https://files.pythonhosted.org/packages/d7/82/b69a1c95df796858777b68fbe6a81d37443a33319761d7c652ce77797475/pandas-2.3.3-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:0242fe9a49aa8b4d78a4fa03acb397a58833ef6199e9aa40a95f027bb3a1b6e7", size = 11410702, upload-time = "2025-09-29T23:29:54.591Z" }, + { url = "https://files.pythonhosted.org/packages/f9/88/702bde3ba0a94b8c73a0181e05144b10f13f29ebfc2150c3a79062a8195d/pandas-2.3.3-cp314-cp314t-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:a21d830e78df0a515db2b3d2f5570610f5e6bd2e27749770e8bb7b524b89b450", size = 11634535, upload-time = "2025-09-29T23:30:21.003Z" }, + { url = "https://files.pythonhosted.org/packages/a4/1e/1bac1a839d12e6a82ec6cb40cda2edde64a2013a66963293696bbf31fbbb/pandas-2.3.3-cp314-cp314t-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:2e3ebdb170b5ef78f19bfb71b0dc5dc58775032361fa188e814959b74d726dd5", size = 12121582, upload-time = "2025-09-29T23:30:43.391Z" }, + { url = "https://files.pythonhosted.org/packages/44/91/483de934193e12a3b1d6ae7c8645d083ff88dec75f46e827562f1e4b4da6/pandas-2.3.3-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:d051c0e065b94b7a3cea50eb1ec32e912cd96dba41647eb24104b6c6c14c5788", size = 12699963, upload-time = "2025-09-29T23:31:10.009Z" }, + { url = "https://files.pythonhosted.org/packages/70/44/5191d2e4026f86a2a109053e194d3ba7a31a2d10a9c2348368c63ed4e85a/pandas-2.3.3-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:3869faf4bd07b3b66a9f462417d0ca3a9df29a9f6abd5d0d0dbab15dac7abe87", size = 13202175, upload-time = "2025-09-29T23:31:59.173Z" }, +] + [[package]] name = "pluggy" version = "1.6.0" @@ -823,6 +870,18 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/f0/d7/a812a0bd0f5160823e647524488cc9734f93782f2c273b8f77e8afc60a37/pytest-8.1.2-py3-none-any.whl", hash = "sha256:6c06dc309ff46a05721e6fd48e492a775ed8165d2ecdf57f156a80c7e95bb142", size = 337456, upload-time = "2024-04-26T18:05:15.452Z" }, ] +[[package]] +name = "python-dateutil" +version = "2.9.0.post0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "six" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/66/c0/0c8b6ad9f17a802ee498c46e004a0eb49bc148f2fd230864601a86dcf6db/python-dateutil-2.9.0.post0.tar.gz", hash = "sha256:37dd54208da7e1cd875388217d5e00ebd4179249f90fb72437e91a35459a0ad3", size = 342432, upload-time = "2024-03-01T18:36:20.211Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/ec/57/56b9bcc3c9c6a792fcbaf139543cee77261f3651ca9da0c93f5c1221264b/python_dateutil-2.9.0.post0-py2.py3-none-any.whl", hash = "sha256:a8b2bc7bffae282281c8140a97d3aa9c14da0b136dfe83f850eea9a5f7470427", size = 229892, upload-time = "2024-03-01T18:36:18.57Z" }, +] + [[package]] name = "python-dotenv" version = "1.2.2" @@ -841,6 +900,15 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/8f/cb/769cfc37177252872a45a71f3fbdde9d51b471a3f3c14bfe95dde3407386/python_multipart-0.0.29-py3-none-any.whl", hash = "sha256:2ddcc971cef266225f54f552d8fa10bcfbb1f14446caec199060daac59ff2d69", size = 29640, upload-time = "2026-05-17T17:29:45.69Z" }, ] +[[package]] +name = "pytz" +version = "2026.3.post1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/fb/48/fb042503b6ca6cd271261dc559fd6432f7d8c713153e9ec5c591af4dfc1c/pytz-2026.3.post1.tar.gz", hash = "sha256:2211d3fcf9a797d3405cac96ac7f61d80e6a644f72a3309607282fe8a2010c5d", size = 319745, upload-time = "2026-07-25T15:12:07.385Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/0f/7b/39c34ca613b0b198cb866466651b26b045e2009864c5183c979a3b83f383/pytz-2026.3.post1-py2.py3-none-any.whl", hash = "sha256:dd95840dd199baea12d9cc096a1d452caa6596a1c1e4b5f3dbd1541855d5e815", size = 508283, upload-time = "2026-07-25T15:12:05.782Z" }, +] + [[package]] name = "pyyaml" version = "6.0.3" @@ -1143,6 +1211,7 @@ dependencies = [ { name = "fastapi" }, { name = "httpx" }, { name = "openai" }, + { name = "pandas" }, { name = "pydantic" }, { name = "pydantic-settings" }, { name = "pyjwt" }, @@ -1165,6 +1234,7 @@ requires-dist = [ { name = "fastapi", specifier = "~=0.115.0" }, { name = "httpx", specifier = "~=0.27.0" }, { name = "openai", specifier = "~=2.41.0" }, + { name = "pandas", specifier = "~=2.3.3" }, { name = "pydantic", specifier = "~=2.7.1" }, { name = "pydantic-settings", specifier = "~=2.2.1" }, { name = "pyjwt", specifier = "~=2.8.0" }, @@ -1196,6 +1266,15 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/e0/f9/0595336914c5619e5f28a1fb793285925a8cd4b432c9da0a987836c7f822/shellingham-1.5.4-py2.py3-none-any.whl", hash = "sha256:7ecfff8f2fd72616f7481040475a65b2bf8af90a56c89140852d1120324e8686", size = 9755, upload-time = "2023-10-24T04:13:38.866Z" }, ] +[[package]] +name = "six" +version = "1.17.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/94/e7/b2c673351809dca68a0e064b6af791aa332cf192da575fd474ed7d6f16a2/six-1.17.0.tar.gz", hash = "sha256:ff70335d468e7eb6ec65b95b99d3a2836546063f63acc5171de367e834932a81", size = 34031, upload-time = "2024-12-04T17:35:28.174Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/b7/ce/149a00dd41f10bc29e5921b496af8b574d8413afcd5e30dfa0ed46c2cc5e/six-1.17.0-py2.py3-none-any.whl", hash = "sha256:4721f391ed90541fddacab5acf947aa0d3dc7d27b2e1e8eda2be8970586c3274", size = 11050, upload-time = "2024-12-04T17:35:26.475Z" }, +] + [[package]] name = "sniffio" version = "1.3.1" @@ -1441,6 +1520,15 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/18/67/36e9267722cc04a6b9f15c7f3441c2363321a3ea07da7ae0c0707beb2a9c/typing_extensions-4.15.0-py3-none-any.whl", hash = "sha256:f0fa19c6845758ab08074a0cfa8b7aecb71c999ca73d62883bc25cc018c4e548", size = 44614, upload-time = "2025-08-25T13:49:24.86Z" }, ] +[[package]] +name = "tzdata" +version = "2026.3" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/92/ff/5a28bdfd8c3ebec42564ac7d0e54ca3db65044a9314a97f9564fa7a1e926/tzdata-2026.3.tar.gz", hash = "sha256:4a1518b8993086a7982523e071643f3c0e5f213e75b21318e78bcabfff9d1415", size = 198674, upload-time = "2026-07-10T08:50:37.887Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/e5/6d/b53b99a9f2766d095985947a5782f1702cabb129a34f7a802d7197af832f/tzdata-2026.3-py2.py3-none-any.whl", hash = "sha256:dc096730c87af6cab1b171c9d532be840741ff5d459015e7f6947bd7d7e54931", size = 348168, upload-time = "2026-07-10T08:50:36.46Z" }, +] + [[package]] name = "uvicorn" version = "0.29.0" diff --git a/webapp/src/app/modules/dashboard/dashboard-statistics.service.spec.ts b/webapp/src/app/modules/dashboard/dashboard-statistics.service.spec.ts new file mode 100644 index 00000000..b1129469 --- /dev/null +++ b/webapp/src/app/modules/dashboard/dashboard-statistics.service.spec.ts @@ -0,0 +1,91 @@ +import { TestBed } from '@angular/core/testing'; +import { + HttpTestingController, + provideHttpClientTesting, +} from '@angular/common/http/testing'; +import { provideHttpClient } from '@angular/common/http'; + +import { DashboardStatisticsService } from './dashboard-statistics.service'; + +describe('DashboardStatisticsService', () => { + let service: DashboardStatisticsService; + let httpMock: HttpTestingController; + + beforeEach(() => { + TestBed.configureTestingModule({ + providers: [ + DashboardStatisticsService, + provideHttpClient(), + provideHttpClientTesting(), + ], + }); + + service = TestBed.inject(DashboardStatisticsService); + httpMock = TestBed.inject(HttpTestingController); + }); + + afterEach(() => { + httpMock.verify(); + }); + + it('sends the selected institution and period for lower project status requests', () => { + service + .getEuProjectStatuses({ fromYear: 2024, toYear: 2026 }, 'I456') + .subscribe(); + + const request = httpMock.expectOne((req) => { + return req.url === '/api/dashboard/projects/eu/status'; + }); + + expect(request.request.params.get('institution_id')).toBe('I456'); + expect(request.request.params.get('from_year')).toBe('2024'); + expect(request.request.params.get('to_year')).toBe('2026'); + + request.flush({ + institution_id: 'https://openalex.org/I456', + organization_name: 'Selected institution', + ongoing: 1, + upcoming: 0, + completed: 2, + }); + }); + + it('sends only the active institution for a topic treemap request', () => { + service.getTopicTreemap(2024, 2026, 'I789').subscribe(); + + const request = httpMock.expectOne((req) => { + return req.url === '/api/dashboard/topic-heatmap'; + }); + + expect(request.request.params.get('institution_id')).toBe('I789'); + expect(request.request.params.get('from_year')).toBe('2024'); + expect(request.request.params.get('to_year')).toBe('2026'); + + request.flush({ + institution_id: 'https://openalex.org/I789', + organization_name: 'Selected institution', + years: [], + fields: [], + }); + }); + + it('keeps all as the default lower-dashboard institution scope', () => { + service.getBundProjectTopics().subscribe(); + + const request = httpMock.expectOne((req) => { + return req.url === '/api/dashboard/projects/bund/topics'; + }); + + expect(request.request.params.get('institution_id')).toBe('all'); + expect(request.request.params.has('from_year')).toBeFalse(); + expect(request.request.params.has('to_year')).toBeFalse(); + + request.flush({ + institution_id: 'https://openalex.org/I123', + organization_name: 'Root organization', + project_count: 0, + matched_project_count: 0, + topics: [], + }); + }); +}); diff --git a/webapp/src/app/modules/dashboard/dashboard-statistics.service.ts b/webapp/src/app/modules/dashboard/dashboard-statistics.service.ts index 629cb31d..831d48a7 100644 --- a/webapp/src/app/modules/dashboard/dashboard-statistics.service.ts +++ b/webapp/src/app/modules/dashboard/dashboard-statistics.service.ts @@ -10,6 +10,11 @@ export interface DashboardPeriodBounds { toYear?: number; } +export interface DashboardInstitution { + id: string; + display_name: string; +} + export interface DashboardStatistics { institution_id: string; organization_name: string; @@ -116,6 +121,12 @@ export class DashboardStatisticsService { private readonly httpClient = inject(HttpClient); private readonly apiConfiguration = inject(Configuration, { optional: true }); + getInstitutions(): Observable { + return this.httpClient.get( + `${this.apiConfiguration?.basePath ?? ''}/api/dashboard/institutions`, + ); + } + getStatistics(): Observable { return this.httpClient.get( `${this.apiConfiguration?.basePath ?? ''}/api/dashboard/statistics`, @@ -124,120 +135,133 @@ export class DashboardStatisticsService { getPublicationCount( period: DashboardPeriodBounds = {}, + institutionId = 'all', ): Observable { return this.httpClient.get( `${this.apiConfiguration?.basePath ?? ''}/api/dashboard/statistics/publications`, - { params: this.periodParams(period) }, + { params: this.statisticParams(period, institutionId) }, ); } getPersonCount( period: DashboardPeriodBounds = {}, + institutionId = 'all', ): Observable { return this.httpClient.get( `${this.apiConfiguration?.basePath ?? ''}/api/dashboard/statistics/persons`, - { params: this.periodParams(period) }, + { params: this.statisticParams(period, institutionId) }, ); } getPatentCount( period: DashboardPeriodBounds = {}, + institutionId = 'all', ): Observable { return this.httpClient.get( `${this.apiConfiguration?.basePath ?? ''}/api/dashboard/statistics/patents`, - { params: this.periodParams(period) }, + { params: this.statisticParams(period, institutionId) }, ); } getEuProjectCount( period: DashboardPeriodBounds = {}, + institutionId = 'all', ): Observable { return this.httpClient.get( `${this.apiConfiguration?.basePath ?? ''}/api/dashboard/statistics/projects/eu`, - { params: this.periodParams(period) }, + { params: this.statisticParams(period, institutionId) }, ); } getEuProjectStatuses( period: DashboardPeriodBounds = {}, + institutionId = 'all', ): Observable { return this.httpClient.get( `${this.apiConfiguration?.basePath ?? ''}/api/dashboard/projects/eu/status`, - { params: this.periodParams(period) }, + { params: this.analyticalParams(period, institutionId) }, ); } getBmbfProjectStatuses( period: DashboardPeriodBounds = {}, + institutionId = 'all', ): Observable { return this.httpClient.get( `${this.apiConfiguration?.basePath ?? ''}/api/dashboard/projects/bmbf/status`, - { params: this.periodParams(period) }, + { params: this.analyticalParams(period, institutionId) }, ); } getDfgProjectStatuses( period: DashboardPeriodBounds = {}, + institutionId = 'all', ): Observable { return this.httpClient.get( `${this.apiConfiguration?.basePath ?? ''}/api/dashboard/projects/dfg/status`, - { params: this.periodParams(period) }, + { params: this.analyticalParams(period, institutionId) }, ); } getBmbfProjectCount( period: DashboardPeriodBounds = {}, + institutionId = 'all', ): Observable { return this.httpClient.get( `${this.apiConfiguration?.basePath ?? ''}/api/dashboard/statistics/projects/bmbf`, - { params: this.periodParams(period) }, + { params: this.statisticParams(period, institutionId) }, ); } getDfgProjectCount( period: DashboardPeriodBounds = {}, + institutionId = 'all', ): Observable { return this.httpClient.get( `${this.apiConfiguration?.basePath ?? ''}/api/dashboard/statistics/projects/dfg`, - { params: this.periodParams(period) }, + { params: this.statisticParams(period, institutionId) }, ); } getDfgProjectTopics( period: DashboardPeriodBounds = {}, + institutionId = 'all', ): Observable { return this.httpClient.get( `${this.apiConfiguration?.basePath ?? ''}/api/dashboard/projects/dfg/topics`, - { params: this.periodParams(period) }, + { params: this.analyticalParams(period, institutionId) }, ); } getEuProjectTopics( period: DashboardPeriodBounds = {}, + institutionId = 'all', ): Observable { return this.httpClient.get( `${this.apiConfiguration?.basePath ?? ''}/api/dashboard/projects/eu/topics`, - { params: this.periodParams(period) }, + { params: this.analyticalParams(period, institutionId) }, ); } getBundProjectTopics( period: DashboardPeriodBounds = {}, + institutionId = 'all', ): Observable { return this.httpClient.get( `${this.apiConfiguration?.basePath ?? ''}/api/dashboard/projects/bund/topics`, - { params: this.periodParams(period) }, + { params: this.analyticalParams(period, institutionId) }, ); } getTopAuthors( period: DashboardPeriodBounds = {}, + institutionId = 'all', ): Observable { const analysis = (source: string) => this.httpClient .get( `${this.apiConfiguration?.basePath ?? ''}/api/dashboard/top-authors/${source}`, - { params: this.periodParams(period) }, + { params: this.analyticalParams(period, institutionId) }, ) .pipe(catchError(() => of(null))); @@ -271,8 +295,11 @@ export class DashboardStatisticsService { getTopicTreemap( fromYear?: number, toYear?: number, + institutionId = 'all', ): Observable { - const params: Record = {}; + const params: Record = { + institution_id: institutionId, + }; if (fromYear !== undefined) params['from_year'] = fromYear; if (toYear !== undefined) params['to_year'] = toYear; @@ -286,8 +313,12 @@ export class DashboardStatisticsService { topicId: string, fromYear?: number, toYear?: number, + institutionId = 'all', ): Observable { - const params: Record = { topicId }; + const params: Record = { + topicId, + institution_id: institutionId, + }; if (fromYear !== undefined) params['from_year'] = fromYear; if (toYear !== undefined) params['to_year'] = toYear; return this.httpClient.get( @@ -302,4 +333,24 @@ export class DashboardStatisticsService { if (period.toYear !== undefined) params['to_year'] = period.toYear; return params; } + + private statisticParams( + period: DashboardPeriodBounds, + institutionId: string, + ): Record { + return { + ...this.periodParams(period), + institution_id: institutionId, + }; + } + + private analyticalParams( + period: DashboardPeriodBounds, + institutionId: string, + ): Record { + return { + ...this.periodParams(period), + institution_id: institutionId, + }; + } } diff --git a/webapp/src/app/modules/dashboard/dashboard.component.html b/webapp/src/app/modules/dashboard/dashboard.component.html index 8de37ebf..aa2e5ec3 100644 --- a/webapp/src/app/modules/dashboard/dashboard.component.html +++ b/webapp/src/app/modules/dashboard/dashboard.component.html @@ -30,6 +30,25 @@ (endYearChange)="onDashboardPeriodRangeChange()"> + + Institution + + Alle Institutionen + @for (institution of dashboardInstitutions; track institution.id) { + + {{ institution.display_name }} + + } + +
@@ -174,6 +193,56 @@

Die Kennzahlen konnten nicht geladen werden.

} +
+

Institution auswählen

+
+ +
+ @for (institution of dashboardInstitutions; track institution.id) { + + } +
+ +
+ @if (dashboardInstitutionsError) { +

+ Die Institutionen konnten nicht geladen werden. +

+ } +
+ + @if (selectedAnalyticalInstitutionId) { @if ( euProjectStatusesLoading || bmbfProjectStatusesLoading || @@ -235,8 +304,8 @@ diameter="64"> } @else if ( - euProjectStatusesError || - bmbfProjectStatusesError || + euProjectStatusesError && + bmbfProjectStatusesError && dfgProjectStatusesError ) {

@@ -246,6 +315,17 @@ } @else if ( euProjectStatuses && bmbfProjectStatuses && dfgProjectStatuses ) { + @if ( + euProjectStatusesError || + bmbfProjectStatusesError || + dfgProjectStatusesError + ) { +

+ Projektstatusdaten für {{ failedProjectStatusSources() }} konnten + nicht geladen werden. Die übrigen Daten werden weiterhin + angezeigt. +

+ } } + } diff --git a/webapp/src/app/modules/dashboard/dashboard.component.scss b/webapp/src/app/modules/dashboard/dashboard.component.scss index 68839065..6df707ba 100644 --- a/webapp/src/app/modules/dashboard/dashboard.component.scss +++ b/webapp/src/app/modules/dashboard/dashboard.component.scss @@ -41,10 +41,16 @@ .dashboard-period-slider { width: 280px; max-width: 100%; + } + + .dashboard-institution-filter { + width: 280px; + max-width: 100%; margin-left: auto; } @media (max-width: 720px) { + .dashboard-institution-filter, .dashboard-period-slider { width: 100%; margin-left: 0; @@ -146,6 +152,120 @@ color: var(--sg-error); } + .dashboard-institution-tabs { + margin: -0.25rem 0 2rem; + + h2 { + margin: 0 0 0.75rem; + font-size: 1.2rem; + line-height: 1.25; + } + } + + .dashboard-institution-tab-bar { + display: grid; + grid-template-columns: 40px minmax(0, 1fr) 40px; + align-items: stretch; + border-bottom: 1px solid var(--sg-border); + } + + .dashboard-institution-tab-arrow { + display: grid; + width: 40px; + height: 48px; + padding: 0; + place-items: center; + border: 0; + background: transparent; + color: var(--sg-text-muted); + cursor: pointer; + transition: + color 0.15s ease, + background-color 0.15s ease, + opacity 0.15s ease; + + &:hover:not(:disabled) { + background: var(--sg-option-hover); + color: var(--sg-text); + } + + &:focus-visible { + outline-offset: -3px; + } + + &:disabled { + cursor: default; + } + + &.is-hidden { + visibility: hidden; + opacity: 0; + } + } + + .dashboard-institution-tab-list { + display: flex; + overflow-x: auto; + overflow-y: hidden; + border-bottom: 0; + background: transparent; + scrollbar-width: none; + + &::-webkit-scrollbar { + display: none; + } + + button { + position: relative; + flex: 0 0 auto; + min-width: 120px; + height: 48px; + padding: 0 16px; + border: 0; + border-radius: 0; + background: transparent; + color: var(--sg-text-muted); + cursor: pointer; + font: inherit; + font-size: 14px; + font-weight: 600; + line-height: 48px; + text-align: center; + white-space: nowrap; + transition: + color 0.15s ease, + background-color 0.15s ease; + + &::after { + position: absolute; + right: 0; + bottom: 0; + left: 0; + border-top: 3px solid transparent; + background: transparent; + content: ''; + } + + &:hover { + background: var(--sg-option-hover); + color: var(--sg-text); + } + + &:focus-visible { + outline: 3px solid var(--sg-card-hover-border); + outline-offset: -3px; + } + + &.active { + color: var(--sg-blue-highlight); + + &::after { + border-top-color: var(--sg-blue-highlight); + } + } + } + } + .top-authors-section { margin-bottom: 2.5rem; } diff --git a/webapp/src/app/modules/dashboard/dashboard.component.ts b/webapp/src/app/modules/dashboard/dashboard.component.ts index 2fe8d26d..a556e42c 100644 --- a/webapp/src/app/modules/dashboard/dashboard.component.ts +++ b/webapp/src/app/modules/dashboard/dashboard.component.ts @@ -1,6 +1,15 @@ -import { Component, OnInit } from '@angular/core'; +import { + AfterViewInit, + Component, + ElementRef, + HostListener, + OnInit, + ViewChild, +} from '@angular/core'; import { DecimalPipe } from '@angular/common'; +import { MatFormFieldModule } from '@angular/material/form-field'; import { MatIconModule } from '@angular/material/icon'; +import { MatSelectModule } from '@angular/material/select'; import { MatTooltipModule } from '@angular/material/tooltip'; import { Observable, finalize } from 'rxjs'; import { ActivatedRoute, Router, RouterLink } from '@angular/router'; @@ -34,6 +43,7 @@ import { import { BmbfProjectStatusStatistics, BundProjectTopics, + DashboardInstitution, DashboardPeriodBounds, DashboardStatisticValue, DashboardStatistics, @@ -72,7 +82,9 @@ type DashboardPeriodMode = selector: 'dashboard', imports: [ DecimalPipe, + MatFormFieldModule, MatIconModule, + MatSelectModule, MatTooltipModule, ComponentTooltipDirective, RouterLink, @@ -84,7 +96,10 @@ type DashboardPeriodMode = templateUrl: './dashboard.component.html', styleUrl: './dashboard.component.scss', }) -export class DashboardComponent implements OnInit { +export class DashboardComponent implements OnInit, AfterViewInit { + @ViewChild('analyticalInstitutionTabList') + private analyticalInstitutionTabList?: ElementRef; + readonly AuthorTooltipComponent = AppAuthorTooltipComponent; readonly patentIcon = PATENT_ICON; readonly MENU_BOOK_ICON = MENU_BOOK_ICON; @@ -147,12 +162,20 @@ export class DashboardComponent implements OnInit { dashboardPeriodMode: DashboardPeriodMode = 'all_time'; dashboardFromYear = this.topicTreemapMinYear; dashboardToYear = this.topicTreemapMaxYear; + dashboardInstitutions: DashboardInstitution[] = []; + selectedDashboardInstitutionId = 'all'; + selectedAnalyticalInstitutionId = ''; + dashboardInstitutionsLoading = false; + dashboardInstitutionsError = false; + canScrollAnalyticalInstitutionTabsLeft = false; + canScrollAnalyticalInstitutionTabsRight = false; selectedTopicTreemapNode?: string; selectedDfgTopicTreemapNode?: string; selectedEuTopicTreemapNode?: string; selectedBundTopicTreemapNode?: string; private topicTreemapReloadQueued = false; private topicTreemapRequestId = 0; + private analyticalRequestId = 0; constructor( private statisticsService: DashboardStatisticsService, @@ -163,43 +186,83 @@ export class DashboardComponent implements OnInit { ngOnInit() { this.restoreDashboardPeriodState(); + this.loadDashboardInstitutions(); this.loadStatistics(); - this.loadTopAuthors(); - this.loadTopicTreemap(); - this.loadDfgProjectTopics(); - this.loadEuProjectTopics(); - this.loadBundProjectTopics(); - this.loadEuProjectStatuses(); - this.loadBmbfProjectStatuses(); - this.loadDfgProjectStatuses(); + } + + ngAfterViewInit(): void { + setTimeout(() => this.updateAnalyticalInstitutionTabScrollState()); + } + + @HostListener('window:resize') + onWindowResize(): void { + this.updateAnalyticalInstitutionTabScrollState(); + } + + private loadDashboardInstitutions(): void { + this.dashboardInstitutionsLoading = true; + this.dashboardInstitutionsError = false; + this.statisticsService + .getInstitutions() + .pipe(finalize(() => (this.dashboardInstitutionsLoading = false))) + .subscribe({ + next: (institutions) => { + this.dashboardInstitutions = institutions; + setTimeout(() => this.updateAnalyticalInstitutionTabScrollState()); + const requestedInstitution = + this.route.snapshot.queryParamMap.get('institution') ?? 'all'; + const restoredInstitution = institutions.some( + (institution) => institution.id === requestedInstitution, + ) + ? requestedInstitution + : 'all'; + if (restoredInstitution !== this.selectedDashboardInstitutionId) { + this.selectedDashboardInstitutionId = restoredInstitution; + this.loadStatistics(); + } + const restoredAnalyticalInstitution = + restoredInstitution === 'all' ? '' : restoredInstitution; + if ( + restoredAnalyticalInstitution !== this.selectedAnalyticalInstitutionId + ) { + this.selectedAnalyticalInstitutionId = restoredAnalyticalInstitution; + this.reloadAnalyticalData(); + } + }, + error: () => { + this.dashboardInstitutions = []; + this.dashboardInstitutionsError = true; + }, + }); } private loadStatistics(): void { this.statisticsError = false; const period = this.selectedPeriodBounds(); + const institutionId = this.selectedDashboardInstitutionId; this.loadStatistic( 'publications', - this.statisticsService.getPublicationCount(period), + this.statisticsService.getPublicationCount(period, institutionId), ); this.loadStatistic( 'persons', - this.statisticsService.getPersonCount(period), + this.statisticsService.getPersonCount(period, institutionId), ); this.loadStatistic( 'patents', - this.statisticsService.getPatentCount(period), + this.statisticsService.getPatentCount(period, institutionId), ); this.loadStatistic( 'eu_projects', - this.statisticsService.getEuProjectCount(period), + this.statisticsService.getEuProjectCount(period, institutionId), ); this.loadStatistic( 'bmbf_projects', - this.statisticsService.getBmbfProjectCount(period), + this.statisticsService.getBmbfProjectCount(period, institutionId), ); this.loadStatistic( 'dfg_projects', - this.statisticsService.getDfgProjectCount(period), + this.statisticsService.getDfgProjectCount(period, institutionId), ); } @@ -357,11 +420,22 @@ export class DashboardComponent implements OnInit { } institutionRouteId(): string { - return ( - this.statistics?.institution_id?.replace('https://openalex.org/', '') ?? - this.topAuthors?.institution_id?.replace('https://openalex.org/', '') ?? - '' + const selectedInstitutionId = this.routeableInstitutionId( + this.selectedDashboardInstitutionId, ); + if (selectedInstitutionId) return selectedInstitutionId; + + return this.routeableInstitutionId(this.dashboardInstitutions[0]?.id) ?? ''; + } + + private routeableInstitutionId(institutionId?: string | null): string | null { + const normalizedInstitutionId = institutionId + ?.replace('https://openalex.org/', '') + .trim(); + + return normalizedInstitutionId && normalizedInstitutionId !== 'all' + ? normalizedInstitutionId + : null; } personListQueryParams(): PersonListQueryParams { @@ -388,6 +462,65 @@ export class DashboardComponent implements OnInit { }); } + onDashboardInstitutionChange(institutionId: string): void { + this.selectedDashboardInstitutionId = institutionId; + const analyticalInstitutionId = + institutionId === 'all' ? '' : institutionId; + const analyticalInstitutionChanged = + analyticalInstitutionId !== this.selectedAnalyticalInstitutionId; + this.selectedAnalyticalInstitutionId = analyticalInstitutionId; + this.updateDashboardPeriodUrl(); + this.loadStatistics(); + if (analyticalInstitutionChanged) { + if (analyticalInstitutionId) { + this.reloadAnalyticalData(); + } else { + // Invalidate pending requests when "Alle Institutionen" is selected. + this.analyticalRequestId += 1; + } + } + } + + onAnalyticalInstitutionChange(institutionId: string): void { + if (institutionId === this.selectedAnalyticalInstitutionId) return; + this.selectedAnalyticalInstitutionId = institutionId; + this.updateDashboardPeriodUrl(); + this.reloadAnalyticalData(); + } + + scrollAnalyticalInstitutionTabs(direction: -1 | 1): void { + const tabList = this.analyticalInstitutionTabList?.nativeElement; + if (!tabList) return; + + tabList.scrollBy({ + left: direction * Math.floor(tabList.clientWidth * 0.75), + behavior: 'smooth', + }); + } + + updateAnalyticalInstitutionTabScrollState(): void { + const tabList = this.analyticalInstitutionTabList?.nativeElement; + if (!tabList) { + this.canScrollAnalyticalInstitutionTabsLeft = false; + this.canScrollAnalyticalInstitutionTabsRight = false; + return; + } + + const maxScrollLeft = tabList.scrollWidth - tabList.clientWidth; + this.canScrollAnalyticalInstitutionTabsLeft = tabList.scrollLeft > 1; + this.canScrollAnalyticalInstitutionTabsRight = + tabList.scrollLeft < maxScrollLeft - 1; + } + + failedProjectStatusSources(): string { + const sources = [ + this.euProjectStatusesError ? 'EU' : undefined, + this.bmbfProjectStatusesError ? 'Bund' : undefined, + this.dfgProjectStatusesError ? 'DFG' : undefined, + ].filter((source): source is string => source !== undefined); + return sources.join(' und '); + } + onTopicTreemapNodeChange(nodeId: string | undefined): void { this.selectedTopicTreemapNode = nodeId; this.updateDashboardPeriodUrl(); @@ -491,6 +624,7 @@ export class DashboardComponent implements OnInit { ...topic, fromYear: period.fromYear, toYear: period.toYear, + institutionId: this.selectedAnalyticalInstitutionId, }, }, ); @@ -555,6 +689,8 @@ export class DashboardComponent implements OnInit { dfgTreemapNode: this.selectedDfgTopicTreemapNode ?? null, euTreemapNode: this.selectedEuTopicTreemapNode ?? null, bundTreemapNode: this.selectedBundTopicTreemapNode ?? null, + institution: this.selectedDashboardInstitutionId, + analyticalInstitution: this.selectedAnalyticalInstitutionId || null, }, queryParamsHandling: 'merge', replaceUrl: true, @@ -581,14 +717,23 @@ export class DashboardComponent implements OnInit { private reloadPeriodData(): void { this.loadStatistics(); - this.loadTopAuthors(); - this.loadTopicTreemap(); - this.loadDfgProjectTopics(); - this.loadEuProjectTopics(); - this.loadBundProjectTopics(); - this.loadEuProjectStatuses(); - this.loadBmbfProjectStatuses(); - this.loadDfgProjectStatuses(); + this.reloadAnalyticalData(); + } + + private reloadAnalyticalData(): void { + if (!this.selectedAnalyticalInstitutionId) return; + const requestId = ++this.analyticalRequestId; + this.euProjectStatuses = undefined; + this.bmbfProjectStatuses = undefined; + this.dfgProjectStatuses = undefined; + this.loadTopAuthors(requestId); + this.loadTopicTreemap(requestId); + this.loadDfgProjectTopics(requestId); + this.loadEuProjectTopics(requestId); + this.loadBundProjectTopics(requestId); + this.loadEuProjectStatuses(requestId); + this.loadBmbfProjectStatuses(requestId); + this.loadDfgProjectStatuses(requestId); } private loadStatistic( @@ -636,149 +781,269 @@ export class DashboardComponent implements OnInit { this.statistics = nextStatistics; } - private loadTopAuthors(): void { + private loadTopAuthors(requestId = this.analyticalRequestId): void { this.topAuthorsLoading = true; this.topAuthorsError = false; this.statisticsService - .getTopAuthors(this.selectedPeriodBounds()) - .pipe(finalize(() => (this.topAuthorsLoading = false))) + .getTopAuthors( + this.selectedPeriodBounds(), + this.selectedAnalyticalInstitutionId, + ) + .pipe( + finalize(() => { + if (requestId === this.analyticalRequestId) { + this.topAuthorsLoading = false; + } + }), + ) .subscribe({ next: (statistics) => { - this.topAuthors = statistics; + if (requestId === this.analyticalRequestId) { + this.topAuthors = statistics; + } }, error: () => { - this.topAuthorsError = true; + if (requestId === this.analyticalRequestId) { + this.topAuthorsError = true; + } }, }); } - private loadDfgProjectTopics(): void { + private loadDfgProjectTopics(requestId = this.analyticalRequestId): void { this.dfgTopicsLoading = true; this.dfgTopicsError = false; this.statisticsService - .getDfgProjectTopics(this.selectedPeriodBounds()) - .pipe(finalize(() => (this.dfgTopicsLoading = false))) + .getDfgProjectTopics( + this.selectedPeriodBounds(), + this.selectedAnalyticalInstitutionId, + ) + .pipe( + finalize(() => { + if (requestId === this.analyticalRequestId) { + this.dfgTopicsLoading = false; + } + }), + ) .subscribe({ next: (topics) => { - this.dfgProjectTopics = topics; - this.dfgTopicTreemap = this.buildDfgTopicTreemapData(topics); + if (requestId === this.analyticalRequestId) { + this.dfgProjectTopics = topics; + this.dfgTopicTreemap = this.buildDfgTopicTreemapData(topics); + } }, error: () => { - this.dfgTopicsError = true; + if (requestId === this.analyticalRequestId) { + this.dfgTopicsError = true; + } }, }); } - private loadEuProjectTopics(): void { + private loadEuProjectTopics(requestId = this.analyticalRequestId): void { this.euTopicsLoading = true; this.euTopicsError = false; this.statisticsService - .getEuProjectTopics(this.selectedPeriodBounds()) - .pipe(finalize(() => (this.euTopicsLoading = false))) + .getEuProjectTopics( + this.selectedPeriodBounds(), + this.selectedAnalyticalInstitutionId, + ) + .pipe( + finalize(() => { + if (requestId === this.analyticalRequestId) { + this.euTopicsLoading = false; + } + }), + ) .subscribe({ next: (topics) => { - this.euProjectTopics = topics; - this.euTopicTreemap = this.buildDfgTopicTreemapData(topics); + if (requestId === this.analyticalRequestId) { + this.euProjectTopics = topics; + this.euTopicTreemap = this.buildDfgTopicTreemapData(topics); + } }, error: () => { - this.euTopicsError = true; + if (requestId === this.analyticalRequestId) { + this.euTopicsError = true; + } }, }); } - private loadBundProjectTopics(): void { + private loadBundProjectTopics(requestId = this.analyticalRequestId): void { this.bundTopicsLoading = true; this.bundTopicsError = false; this.statisticsService - .getBundProjectTopics(this.selectedPeriodBounds()) - .pipe(finalize(() => (this.bundTopicsLoading = false))) + .getBundProjectTopics( + this.selectedPeriodBounds(), + this.selectedAnalyticalInstitutionId, + ) + .pipe( + finalize(() => { + if (requestId === this.analyticalRequestId) { + this.bundTopicsLoading = false; + } + }), + ) .subscribe({ next: (topics) => { - this.bundProjectTopics = topics; - this.bundTopicTreemap = this.buildDfgTopicTreemapData(topics); + if (requestId === this.analyticalRequestId) { + this.bundProjectTopics = topics; + this.bundTopicTreemap = this.buildDfgTopicTreemapData(topics); + } }, error: () => { - this.bundTopicsError = true; + if (requestId === this.analyticalRequestId) { + this.bundTopicsError = true; + } }, }); } - private loadEuProjectStatuses(): void { + private loadEuProjectStatuses(requestId = this.analyticalRequestId): void { this.euProjectStatusesLoading = true; this.euProjectStatusesError = false; this.statisticsService - .getEuProjectStatuses(this.selectedPeriodBounds()) - .pipe(finalize(() => (this.euProjectStatusesLoading = false))) + .getEuProjectStatuses( + this.selectedPeriodBounds(), + this.selectedAnalyticalInstitutionId, + ) + .pipe( + finalize(() => { + if (requestId === this.analyticalRequestId) { + this.euProjectStatusesLoading = false; + } + }), + ) .subscribe({ next: (statuses) => { - this.euProjectStatuses = statuses; + if (requestId === this.analyticalRequestId) { + this.euProjectStatuses = statuses; + } }, error: () => { - this.euProjectStatusesError = true; + if (requestId === this.analyticalRequestId) { + this.euProjectStatusesError = true; + this.euProjectStatuses = this.emptyProjectStatuses(); + } }, }); } - private loadBmbfProjectStatuses(): void { + private loadBmbfProjectStatuses(requestId = this.analyticalRequestId): void { this.bmbfProjectStatusesLoading = true; this.bmbfProjectStatusesError = false; this.statisticsService - .getBmbfProjectStatuses(this.selectedPeriodBounds()) - .pipe(finalize(() => (this.bmbfProjectStatusesLoading = false))) + .getBmbfProjectStatuses( + this.selectedPeriodBounds(), + this.selectedAnalyticalInstitutionId, + ) + .pipe( + finalize(() => { + if (requestId === this.analyticalRequestId) { + this.bmbfProjectStatusesLoading = false; + } + }), + ) .subscribe({ next: (statuses) => { - this.bmbfProjectStatuses = statuses; + if (requestId === this.analyticalRequestId) { + this.bmbfProjectStatuses = statuses; + } }, error: () => { - this.bmbfProjectStatusesError = true; + if (requestId === this.analyticalRequestId) { + this.bmbfProjectStatusesError = true; + this.bmbfProjectStatuses = this.emptyProjectStatuses(); + } }, }); } - private loadDfgProjectStatuses(): void { + private loadDfgProjectStatuses(requestId = this.analyticalRequestId): void { this.dfgProjectStatusesLoading = true; this.dfgProjectStatusesError = false; this.statisticsService - .getDfgProjectStatuses(this.selectedPeriodBounds()) - .pipe(finalize(() => (this.dfgProjectStatusesLoading = false))) + .getDfgProjectStatuses( + this.selectedPeriodBounds(), + this.selectedAnalyticalInstitutionId, + ) + .pipe( + finalize(() => { + if (requestId === this.analyticalRequestId) { + this.dfgProjectStatusesLoading = false; + } + }), + ) .subscribe({ next: (statuses) => { - this.dfgProjectStatuses = statuses; + if (requestId === this.analyticalRequestId) { + this.dfgProjectStatuses = statuses; + } }, error: () => { - this.dfgProjectStatusesError = true; + if (requestId === this.analyticalRequestId) { + this.dfgProjectStatusesError = true; + this.dfgProjectStatuses = this.emptyProjectStatuses(); + } }, }); } - private loadTopicTreemap(): void { + private emptyProjectStatuses(): EuProjectStatusStatistics { + const institution = this.dashboardInstitutions.find( + ({ id }) => id === this.selectedAnalyticalInstitutionId, + ); + return { + institution_id: this.selectedAnalyticalInstitutionId, + organization_name: institution?.display_name ?? '', + ongoing: 0, + upcoming: 0, + completed: 0, + }; + } + + private loadTopicTreemap(analyticalRequestId = this.analyticalRequestId): void { if (this.dashboardFromYear > this.dashboardToYear) { this.topicTreemapLoading = false; this.topicTreemapError = true; return; } - const requestId = ++this.topicTreemapRequestId; + const treemapRequestId = ++this.topicTreemapRequestId; const period = this.selectedPeriodBounds(); this.topicTreemapLoading = true; this.topicTreemapError = false; this.statisticsService - .getTopicTreemap(period.fromYear, period.toYear) + .getTopicTreemap( + period.fromYear, + period.toYear, + this.selectedAnalyticalInstitutionId, + ) .pipe( finalize(() => { - if (requestId === this.topicTreemapRequestId) { + if ( + analyticalRequestId === this.analyticalRequestId && + treemapRequestId === this.topicTreemapRequestId + ) { this.topicTreemapLoading = false; } }), ) .subscribe({ next: (treemap) => { - if (requestId === this.topicTreemapRequestId) { + if ( + analyticalRequestId === this.analyticalRequestId && + treemapRequestId === this.topicTreemapRequestId + ) { this.topicTreemap = treemap; } }, error: () => { - if (requestId === this.topicTreemapRequestId) { + if ( + analyticalRequestId === this.analyticalRequestId && + treemapRequestId === this.topicTreemapRequestId + ) { this.topicTreemapError = true; } }, diff --git a/webapp/src/app/modules/dashboard/topic-wordcloud-dialog/topic-wordcloud-dialog.component.ts b/webapp/src/app/modules/dashboard/topic-wordcloud-dialog/topic-wordcloud-dialog.component.ts index afb5415c..0fa56005 100644 --- a/webapp/src/app/modules/dashboard/topic-wordcloud-dialog/topic-wordcloud-dialog.component.ts +++ b/webapp/src/app/modules/dashboard/topic-wordcloud-dialog/topic-wordcloud-dialog.component.ts @@ -35,6 +35,7 @@ export interface TopicWordCloudDialogData { subfieldName?: string; fromYear?: number; toYear?: number; + institutionId?: string; words?: TopicWordCloudWord[]; source?: 'publications' | 'dfg' | 'eu' | 'bund'; } @@ -107,6 +108,7 @@ export class TopicWordCloudDialogComponent { this.data.topicId, this.data.fromYear, this.data.toYear, + this.data.institutionId, ) .pipe(takeUntilDestroyed(this.destroyRef)) .subscribe({ diff --git a/webapp/src/app/shared/ui/app-institution-card/app-institution-card.component.ts b/webapp/src/app/shared/ui/app-institution-card/app-institution-card.component.ts index 8a3124b0..25b39ca4 100644 --- a/webapp/src/app/shared/ui/app-institution-card/app-institution-card.component.ts +++ b/webapp/src/app/shared/ui/app-institution-card/app-institution-card.component.ts @@ -6,7 +6,7 @@ import { input, signal, } from '@angular/core'; -import { Institution } from '../../../api'; +import { AuthService, Institution } from '../../../api'; import { PatentsService } from '../../../api/api/patents.service'; import { MatCardModule } from '@angular/material/card'; import { RouterModule } from '@angular/router'; @@ -14,7 +14,6 @@ import { MatDividerModule } from '@angular/material/divider'; import { MatIconModule } from '@angular/material/icon'; import { MatButtonModule } from '@angular/material/button'; import { DecimalPipe } from '@angular/common'; -import { CredentialService } from '../../services/credential.service'; import { CountryFlagComponent } from '../country-flag/country-flag.component'; import { @@ -44,7 +43,7 @@ export class AppInstitutionCardComponent { readonly PROJECT_ICON = PROJECT_ICON; readonly VERIFIED_ICON = VERIFIED_ICON; - private readonly credentialService = inject(CredentialService); + private readonly authService = inject(AuthService); private readonly patentsApi = inject(PatentsService); institution = input.required(); @@ -59,15 +58,8 @@ export class AppInstitutionCardComponent { return 'Unbekannte Institution'; }); - isOwnInstitution = computed(() => { - const institutionId = this.stripOpenAlexId(this.institution().id); - if (!institutionId) return false; - - const effectiveInstitutionId = - this.credentialService.effectiveInstitutionId(); - - return institutionId === effectiveInstitutionId; - }); + private readonly isOwnInstitutionSignal = signal(false); + isOwnInstitution = this.isOwnInstitutionSignal.asReadonly(); // The "Patente" action only makes sense once org_patents has been indexed // for this institution (currently a manual, per-institution process), so @@ -79,9 +71,14 @@ export class AppInstitutionCardComponent { constructor() { effect(() => { const id = this.stripOpenAlexId(this.institution().id); + this.isOwnInstitutionSignal.set(false); this.hasPatentsSignal.set(false); if (!id) return; + this.authService.canFetchGdprRelevantData(undefined, id).subscribe({ + next: (isAllowed) => this.isOwnInstitutionSignal.set(isAllowed), + }); + this.patentsApi .getOrgPatentsByInstitution(id, undefined, 0, 0) .subscribe({