From c8fa70e7f02ce840d98ce59c80e7b84046c43923 Mon Sep 17 00:00:00 2001 From: Farajollahi Date: Tue, 11 Aug 2026 12:53:13 +0200 Subject: [PATCH 01/15] feat(dashboard): add institution filter for organization-wide statistics --- service/src/main/inse/dashboard/model.py | 5 + .../dashboard/project_statistics_service.py | 76 ++++++-- service/src/main/inse/dashboard/router.py | 52 ++++- service/src/main/inse/dashboard/service.py | 177 ++++++++++++++---- .../src/main/inse/dashboard/test_service.py | 66 ++++++- .../inse/organization_management/service.py | 6 + .../inse/patents/org/elastic_search_client.py | 14 +- service/src/main/inse/projects/service.py | 12 +- .../dashboard/dashboard-statistics.service.ts | 39 +++- .../dashboard/dashboard.component.html | 19 ++ .../dashboard/dashboard.component.scss | 6 + .../modules/dashboard/dashboard.component.ts | 58 +++++- 12 files changed, 449 insertions(+), 81 deletions(-) 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/router.py b/service/src/main/inse/dashboard/router.py index a0d0de82..f6408c94 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,12 @@ from .model import ( TopicWordCloud, ) from .service import ( + 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 +59,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 +94,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 +118,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 +142,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 +166,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, @@ -178,14 +210,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, @@ -218,14 +254,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, diff --git a/service/src/main/inse/dashboard/service.py b/service/src/main/inse/dashboard/service.py index a162da74..c5fe4af3 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,72 @@ 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] + + +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,97 +175,121 @@ 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) - if period == (None, None): + if len(normalized_ids) == 1 and period == (None, None): institution = await institutions_v2_service.get_institution_by_id_or_raise( - raw_oa_institution_id=_raw_institution_id(normalized_id), + raw_oa_institution_id=_raw_institution_id(normalized_ids[0]), source=["id", "works_count"], ) return DashboardStatisticValue( - institution_id=normalized_id, + institution_id=normalized_ids[0], organization_name=organization_name, value=int(institution.works_count or 0), ) - first_year = period[0] if period[0] is not None else 1900 - last_year = period[1] if period[1] is not None else 2100 - publication_years = list(range(first_year, last_year + 1)) - + filters = [works_v2_service._institutions_nested_query(normalized_ids)] + if period != (None, None): + first_year = period[0] if period[0] is not None else 1900 + last_year = period[1] if period[1] is not None else 2100 + filters.append( + {"terms": {"publication_year": list(range(first_year, last_year + 1))}} + ) value = await elasticsearch.count( index=ESIndex.OPENALEX_WORKS_WILDCARD, - query={ - "bool": { - "filter": [ - works_v2_service._institutions_nested_query([normalized_id]), - {"terms": {"publication_year": publication_years}}, - ] - } - }, + query={"bool": {"filter": filters}}, ) return DashboardStatisticValue( - institution_id=normalized_id, + institution_id=_statistic_scope_id(institution_ids), organization_name=organization_name, value=value, ) 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 6d438e0f..0d8f3ba1 100644 --- a/service/src/main/inse/dashboard/test_service.py +++ b/service/src/main/inse/dashboard/test_service.py @@ -8,8 +8,14 @@ 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_institutions, get_dashboard_organization, get_dashboard_persons, get_dashboard_publications, @@ -42,6 +48,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, @@ -1619,6 +1629,60 @@ 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"}, + ] + + 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/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/service.py b/service/src/main/inse/projects/service.py index eabd2228..0d2f0f29 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/webapp/src/app/modules/dashboard/dashboard-statistics.service.ts b/webapp/src/app/modules/dashboard/dashboard-statistics.service.ts index 629cb31d..3ae23a74 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,37 +135,41 @@ 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) }, ); } @@ -187,19 +202,21 @@ export class DashboardStatisticsService { 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) }, ); } @@ -302,4 +319,14 @@ 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, + }; + } } diff --git a/webapp/src/app/modules/dashboard/dashboard.component.html b/webapp/src/app/modules/dashboard/dashboard.component.html index 75bceafa..f25fcc0b 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 }} + + } + +
diff --git a/webapp/src/app/modules/dashboard/dashboard.component.scss b/webapp/src/app/modules/dashboard/dashboard.component.scss index 68839065..00aa14a1 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; diff --git a/webapp/src/app/modules/dashboard/dashboard.component.ts b/webapp/src/app/modules/dashboard/dashboard.component.ts index 14fadca4..d396c12b 100644 --- a/webapp/src/app/modules/dashboard/dashboard.component.ts +++ b/webapp/src/app/modules/dashboard/dashboard.component.ts @@ -1,6 +1,8 @@ import { Component, OnInit } 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'; @@ -23,6 +25,7 @@ import { import { BmbfProjectStatusStatistics, BundProjectTopics, + DashboardInstitution, DashboardPeriodBounds, DashboardStatisticValue, DashboardStatistics, @@ -61,7 +64,9 @@ type DashboardPeriodMode = selector: 'dashboard', imports: [ DecimalPipe, + MatFormFieldModule, MatIconModule, + MatSelectModule, MatTooltipModule, ComponentTooltipDirective, RouterLink, @@ -128,6 +133,10 @@ export class DashboardComponent implements OnInit { dashboardPeriodMode: DashboardPeriodMode = 'all_time'; dashboardFromYear = this.topicTreemapMinYear; dashboardToYear = this.topicTreemapMaxYear; + dashboardInstitutions: DashboardInstitution[] = []; + selectedDashboardInstitutionId = 'all'; + dashboardInstitutionsLoading = false; + dashboardInstitutionsError = false; selectedTopicTreemapNode?: string; selectedDfgTopicTreemapNode?: string; selectedEuTopicTreemapNode?: string; @@ -144,6 +153,7 @@ export class DashboardComponent implements OnInit { ngOnInit() { this.restoreDashboardPeriodState(); + this.loadDashboardInstitutions(); this.loadStatistics(); this.loadTopAuthors(); this.loadTopicTreemap(); @@ -155,32 +165,61 @@ export class DashboardComponent implements OnInit { this.loadDfgProjectStatuses(); } + private loadDashboardInstitutions(): void { + this.dashboardInstitutionsLoading = true; + this.dashboardInstitutionsError = false; + this.statisticsService + .getInstitutions() + .pipe(finalize(() => (this.dashboardInstitutionsLoading = false))) + .subscribe({ + next: (institutions) => { + this.dashboardInstitutions = institutions; + 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(); + } + }, + 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), ); } @@ -371,6 +410,12 @@ export class DashboardComponent implements OnInit { }); } + onDashboardInstitutionChange(institutionId: string): void { + this.selectedDashboardInstitutionId = institutionId; + this.updateDashboardPeriodUrl(); + this.loadStatistics(); + } + onTopicTreemapNodeChange(nodeId: string | undefined): void { this.selectedTopicTreemapNode = nodeId; this.updateDashboardPeriodUrl(); @@ -539,6 +584,7 @@ export class DashboardComponent implements OnInit { dfgTreemapNode: this.selectedDfgTopicTreemapNode ?? null, euTreemapNode: this.selectedEuTopicTreemapNode ?? null, bundTreemapNode: this.selectedBundTopicTreemapNode ?? null, + institution: this.selectedDashboardInstitutionId, }, queryParamsHandling: 'merge', replaceUrl: true, -- 2.56.1 From 1758227f1e6092b577b1c1c89138556296e3bb20 Mon Sep 17 00:00:00 2001 From: spsaefan <117728614+spsaefan@users.noreply.github.com> Date: Sat, 15 Aug 2026 22:43:52 +0200 Subject: [PATCH 02/15] Add institution tabs --- .../dashboard/dashboard.component.html | 33 +++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/webapp/src/app/modules/dashboard/dashboard.component.html b/webapp/src/app/modules/dashboard/dashboard.component.html index f25fcc0b..d9683eb5 100644 --- a/webapp/src/app/modules/dashboard/dashboard.component.html +++ b/webapp/src/app/modules/dashboard/dashboard.component.html @@ -193,6 +193,39 @@

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 ( euProjectStatusesLoading || bmbfProjectStatusesLoading || -- 2.56.1 From fbcee778d2ecf6903dc025c3c99d071cb1897120 Mon Sep 17 00:00:00 2001 From: spsaefan <117728614+spsaefan@users.noreply.github.com> Date: Sat, 15 Aug 2026 22:44:34 +0200 Subject: [PATCH 03/15] Add institution tab styles --- .../dashboard/dashboard.component.scss | 68 +++++++++++++++++++ 1 file changed, 68 insertions(+) diff --git a/webapp/src/app/modules/dashboard/dashboard.component.scss b/webapp/src/app/modules/dashboard/dashboard.component.scss index 00aa14a1..ebc289ad 100644 --- a/webapp/src/app/modules/dashboard/dashboard.component.scss +++ b/webapp/src/app/modules/dashboard/dashboard.component.scss @@ -152,6 +152,74 @@ 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-list { + display: flex; + overflow-x: auto; + overflow-y: hidden; + border-bottom: 1px solid var(--sg-border); + background: transparent; + scrollbar-width: thin; + + 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; + 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; } -- 2.56.1 From 82fa2e816b857343d83f28d3a73dedadfc272965 Mon Sep 17 00:00:00 2001 From: spsaefan <117728614+spsaefan@users.noreply.github.com> Date: Sat, 15 Aug 2026 22:45:24 +0200 Subject: [PATCH 04/15] Add institution filtering --- .../dashboard/dashboard-statistics.service.ts | 42 +++- .../modules/dashboard/dashboard.component.ts | 238 ++++++++++++++---- 2 files changed, 219 insertions(+), 61 deletions(-) diff --git a/webapp/src/app/modules/dashboard/dashboard-statistics.service.ts b/webapp/src/app/modules/dashboard/dashboard-statistics.service.ts index 3ae23a74..831d48a7 100644 --- a/webapp/src/app/modules/dashboard/dashboard-statistics.service.ts +++ b/webapp/src/app/modules/dashboard/dashboard-statistics.service.ts @@ -175,28 +175,31 @@ export class DashboardStatisticsService { 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) }, ); } @@ -222,39 +225,43 @@ export class DashboardStatisticsService { 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))); @@ -288,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; @@ -303,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( @@ -329,4 +343,14 @@ export class DashboardStatisticsService { 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.ts b/webapp/src/app/modules/dashboard/dashboard.component.ts index d396c12b..52bffe64 100644 --- a/webapp/src/app/modules/dashboard/dashboard.component.ts +++ b/webapp/src/app/modules/dashboard/dashboard.component.ts @@ -135,6 +135,7 @@ export class DashboardComponent implements OnInit { dashboardToYear = this.topicTreemapMaxYear; dashboardInstitutions: DashboardInstitution[] = []; selectedDashboardInstitutionId = 'all'; + selectedAnalyticalInstitutionId = 'all'; dashboardInstitutionsLoading = false; dashboardInstitutionsError = false; selectedTopicTreemapNode?: string; @@ -143,6 +144,7 @@ export class DashboardComponent implements OnInit { selectedBundTopicTreemapNode?: string; private topicTreemapReloadQueued = false; private topicTreemapRequestId = 0; + private analyticalRequestId = 0; constructor( private statisticsService: DashboardStatisticsService, @@ -185,6 +187,20 @@ export class DashboardComponent implements OnInit { this.selectedDashboardInstitutionId = restoredInstitution; this.loadStatistics(); } + const requestedAnalyticalInstitution = + this.route.snapshot.queryParamMap.get('analyticalInstitution') ?? + 'all'; + const restoredAnalyticalInstitution = institutions.some( + (institution) => institution.id === requestedAnalyticalInstitution, + ) + ? requestedAnalyticalInstitution + : 'all'; + if ( + restoredAnalyticalInstitution !== this.selectedAnalyticalInstitutionId + ) { + this.selectedAnalyticalInstitutionId = restoredAnalyticalInstitution; + this.reloadAnalyticalData(); + } }, error: () => { this.dashboardInstitutions = []; @@ -416,6 +432,13 @@ export class DashboardComponent implements OnInit { this.loadStatistics(); } + onAnalyticalInstitutionChange(institutionId: string): void { + if (institutionId === this.selectedAnalyticalInstitutionId) return; + this.selectedAnalyticalInstitutionId = institutionId; + this.updateDashboardPeriodUrl(); + this.reloadAnalyticalData(); + } + onTopicTreemapNodeChange(nodeId: string | undefined): void { this.selectedTopicTreemapNode = nodeId; this.updateDashboardPeriodUrl(); @@ -519,6 +542,7 @@ export class DashboardComponent implements OnInit { ...topic, fromYear: period.fromYear, toYear: period.toYear, + institutionId: this.selectedAnalyticalInstitutionId, }, }, ); @@ -585,6 +609,7 @@ export class DashboardComponent implements OnInit { euTreemapNode: this.selectedEuTopicTreemapNode ?? null, bundTreemapNode: this.selectedBundTopicTreemapNode ?? null, institution: this.selectedDashboardInstitutionId, + analyticalInstitution: this.selectedAnalyticalInstitutionId, }, queryParamsHandling: 'merge', replaceUrl: true, @@ -611,14 +636,19 @@ 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 { + const requestId = ++this.analyticalRequestId; + 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( @@ -666,149 +696,253 @@ 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; + } }, }); } - 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; + } }, }); } - 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; + } }, }); } - private loadTopicTreemap(): void { + 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; } }, -- 2.56.1 From c70e6bf4890ef7316378d3d2e0326779fd04e0d2 Mon Sep 17 00:00:00 2001 From: spsaefan <117728614+spsaefan@users.noreply.github.com> Date: Sat, 15 Aug 2026 22:45:40 +0200 Subject: [PATCH 05/15] Filter word cloud by institution --- .../topic-wordcloud-dialog/topic-wordcloud-dialog.component.ts | 2 ++ 1 file changed, 2 insertions(+) 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 a8b75dc0..21bb9610 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 @@ -22,6 +22,7 @@ export interface TopicWordCloudDialogData { subfieldName?: string; fromYear?: number; toYear?: number; + institutionId?: string; words?: TopicWordCloudWord[]; source?: 'publications' | 'dfg' | 'eu' | 'bund'; } @@ -82,6 +83,7 @@ export class TopicWordCloudDialogComponent { this.data.topicId, this.data.fromYear, this.data.toYear, + this.data.institutionId, ) .pipe(takeUntilDestroyed(this.destroyRef)) .subscribe({ -- 2.56.1 From 6a6ec8662cf5e353590415a8d2b6ae0c165d0d56 Mon Sep 17 00:00:00 2001 From: spsaefan <117728614+spsaefan@users.noreply.github.com> Date: Sat, 15 Aug 2026 22:45:56 +0200 Subject: [PATCH 06/15] Filter dashboard analytics by institution --- service/src/main/inse/dashboard/router.py | 119 +++++++++++++++++---- service/src/main/inse/dashboard/service.py | 20 ++++ 2 files changed, 117 insertions(+), 22 deletions(-) diff --git a/service/src/main/inse/dashboard/router.py b/service/src/main/inse/dashboard/router.py index f6408c94..96b1dbe0 100644 --- a/service/src/main/inse/dashboard/router.py +++ b/service/src/main/inse/dashboard/router.py @@ -24,6 +24,7 @@ from .model import ( TopicWordCloud, ) from .service import ( + get_dashboard_analytical_institution, get_dashboard_institutions, get_dashboard_organization, get_dashboard_patents, @@ -190,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, ) @@ -234,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, ) @@ -278,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, ) @@ -298,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, ) @@ -318,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, ) @@ -338,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, ) @@ -362,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, @@ -386,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 ) @@ -403,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 ) @@ -420,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 ) @@ -437,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 ) @@ -454,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 ) @@ -471,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), @@ -478,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, @@ -494,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), @@ -501,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 a45ec108..21a7351d 100644 --- a/service/src/main/inse/dashboard/service.py +++ b/service/src/main/inse/dashboard/service.py @@ -108,6 +108,26 @@ async def get_dashboard_statistic_institution_ids( 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]) -- 2.56.1 From 8d7323a387a94ad5daf6b8ac145a6c93c2c22bca Mon Sep 17 00:00:00 2001 From: spsaefan <117728614+spsaefan@users.noreply.github.com> Date: Sat, 15 Aug 2026 22:46:05 +0200 Subject: [PATCH 07/15] Add institution filter tests --- .../src/main/inse/dashboard/test_service.py | 102 ++++++++++++++++++ .../dashboard-statistics.service.spec.ts | 91 ++++++++++++++++ 2 files changed, 193 insertions(+) create mode 100644 webapp/src/app/modules/dashboard/dashboard-statistics.service.spec.ts diff --git a/service/src/main/inse/dashboard/test_service.py b/service/src/main/inse/dashboard/test_service.py index c325780e..a57c762b 100644 --- a/service/src/main/inse/dashboard/test_service.py +++ b/service/src/main/inse/dashboard/test_service.py @@ -15,6 +15,7 @@ from inse.auth.model import ( UserRole, ) from inse.dashboard.service import ( + get_dashboard_analytical_institution, get_dashboard_institutions, get_dashboard_organization, get_dashboard_persons, @@ -1682,6 +1683,107 @@ async def test_dashboard_institutions_include_openalex_associations(): ] +@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/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: [], + }); + }); +}); -- 2.56.1 From c7334423004c7f4e6c14d50d26cba768ad8e5227 Mon Sep 17 00:00:00 2001 From: spsaefan <117728614+spsaefan@users.noreply.github.com> Date: Mon, 17 Aug 2026 11:47:43 +0200 Subject: [PATCH 08/15] Remove all institutions tab --- webapp/src/app/modules/dashboard/dashboard.component.html | 8 -------- 1 file changed, 8 deletions(-) diff --git a/webapp/src/app/modules/dashboard/dashboard.component.html b/webapp/src/app/modules/dashboard/dashboard.component.html index d9683eb5..2f6410ea 100644 --- a/webapp/src/app/modules/dashboard/dashboard.component.html +++ b/webapp/src/app/modules/dashboard/dashboard.component.html @@ -198,14 +198,6 @@ aria-label="Institutionen für Analysebereiche">

Institution auswählen

- @for (institution of dashboardInstitutions; track institution.id) {
+ @if (selectedAnalyticalInstitutionId) { @if ( euProjectStatusesLoading || bmbfProjectStatusesLoading || @@ -279,8 +280,8 @@ diameter="64"> } @else if ( - euProjectStatusesError || - bmbfProjectStatusesError || + euProjectStatusesError && + bmbfProjectStatusesError && dfgProjectStatusesError ) {

@@ -290,6 +291,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.ts b/webapp/src/app/modules/dashboard/dashboard.component.ts index f3e12edd..5f620214 100644 --- a/webapp/src/app/modules/dashboard/dashboard.component.ts +++ b/webapp/src/app/modules/dashboard/dashboard.component.ts @@ -135,8 +135,7 @@ export class DashboardComponent implements OnInit { dashboardToYear = this.topicTreemapMaxYear; dashboardInstitutions: DashboardInstitution[] = []; selectedDashboardInstitutionId = 'all'; - readonly defaultAnalyticalInstitutionId = 'I62318514'; - selectedAnalyticalInstitutionId = this.defaultAnalyticalInstitutionId; + selectedAnalyticalInstitutionId = ''; dashboardInstitutionsLoading = false; dashboardInstitutionsError = false; selectedTopicTreemapNode?: string; @@ -158,14 +157,6 @@ export class DashboardComponent implements OnInit { this.restoreDashboardPeriodState(); this.loadDashboardInstitutions(); this.loadStatistics(); - this.loadTopAuthors(); - this.loadTopicTreemap(); - this.loadDfgProjectTopics(); - this.loadEuProjectTopics(); - this.loadBundProjectTopics(); - this.loadEuProjectStatuses(); - this.loadBmbfProjectStatuses(); - this.loadDfgProjectStatuses(); } private loadDashboardInstitutions(): void { @@ -188,14 +179,8 @@ export class DashboardComponent implements OnInit { this.selectedDashboardInstitutionId = restoredInstitution; this.loadStatistics(); } - const requestedAnalyticalInstitution = - this.route.snapshot.queryParamMap.get('analyticalInstitution') ?? - this.defaultAnalyticalInstitutionId; - const restoredAnalyticalInstitution = institutions.some( - (institution) => institution.id === requestedAnalyticalInstitution, - ) - ? requestedAnalyticalInstitution - : this.defaultAnalyticalInstitutionId; + const restoredAnalyticalInstitution = + restoredInstitution === 'all' ? '' : restoredInstitution; if ( restoredAnalyticalInstitution !== this.selectedAnalyticalInstitutionId ) { @@ -440,8 +425,21 @@ 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 { @@ -451,6 +449,15 @@ export class DashboardComponent implements OnInit { this.reloadAnalyticalData(); } + 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(); @@ -621,7 +628,7 @@ export class DashboardComponent implements OnInit { euTreemapNode: this.selectedEuTopicTreemapNode ?? null, bundTreemapNode: this.selectedBundTopicTreemapNode ?? null, institution: this.selectedDashboardInstitutionId, - analyticalInstitution: this.selectedAnalyticalInstitutionId, + analyticalInstitution: this.selectedAnalyticalInstitutionId || null, }, queryParamsHandling: 'merge', replaceUrl: true, @@ -652,7 +659,11 @@ export class DashboardComponent implements OnInit { } 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); @@ -851,6 +862,7 @@ export class DashboardComponent implements OnInit { error: () => { if (requestId === this.analyticalRequestId) { this.euProjectStatusesError = true; + this.euProjectStatuses = this.emptyProjectStatuses(); } }, }); @@ -880,6 +892,7 @@ export class DashboardComponent implements OnInit { error: () => { if (requestId === this.analyticalRequestId) { this.bmbfProjectStatusesError = true; + this.bmbfProjectStatuses = this.emptyProjectStatuses(); } }, }); @@ -909,11 +922,25 @@ export class DashboardComponent implements OnInit { error: () => { if (requestId === this.analyticalRequestId) { this.dfgProjectStatusesError = true; + this.dfgProjectStatuses = this.emptyProjectStatuses(); } }, }); } + 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; -- 2.56.1 From 9c593a0d0984cf882191f58bf5b0c3e41ad88f00 Mon Sep 17 00:00:00 2001 From: spsaefan <117728614+spsaefan@users.noreply.github.com> Date: Mon, 17 Aug 2026 14:30:09 +0200 Subject: [PATCH 12/15] Update institution tab style --- .../dashboard/dashboard.component.html | 50 ++++++++++++++----- .../dashboard/dashboard.component.scss | 50 ++++++++++++++++++- 2 files changed, 85 insertions(+), 15 deletions(-) diff --git a/webapp/src/app/modules/dashboard/dashboard.component.html b/webapp/src/app/modules/dashboard/dashboard.component.html index 2f6410ea..927668ac 100644 --- a/webapp/src/app/modules/dashboard/dashboard.component.html +++ b/webapp/src/app/modules/dashboard/dashboard.component.html @@ -197,19 +197,43 @@ class="dashboard-institution-tabs" aria-label="Institutionen für Analysebereiche">

Institution auswählen

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

diff --git a/webapp/src/app/modules/dashboard/dashboard.component.scss b/webapp/src/app/modules/dashboard/dashboard.component.scss index ebc289ad..6df707ba 100644 --- a/webapp/src/app/modules/dashboard/dashboard.component.scss +++ b/webapp/src/app/modules/dashboard/dashboard.component.scss @@ -162,13 +162,58 @@ } } + .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: 1px solid var(--sg-border); + border-bottom: 0; background: transparent; - scrollbar-width: thin; + scrollbar-width: none; + + &::-webkit-scrollbar { + display: none; + } button { position: relative; @@ -185,6 +230,7 @@ font-size: 14px; font-weight: 600; line-height: 48px; + text-align: center; white-space: nowrap; transition: color 0.15s ease, -- 2.56.1 From dbe8f2449aab031c46fbf6ef46275d3a8b040dd9 Mon Sep 17 00:00:00 2001 From: spsaefan <117728614+spsaefan@users.noreply.github.com> Date: Mon, 17 Aug 2026 14:30:38 +0200 Subject: [PATCH 13/15] Add institution tab navigation --- .../modules/dashboard/dashboard.component.ts | 50 ++++++++++++++++++- 1 file changed, 48 insertions(+), 2 deletions(-) diff --git a/webapp/src/app/modules/dashboard/dashboard.component.ts b/webapp/src/app/modules/dashboard/dashboard.component.ts index f3e12edd..4a65d7aa 100644 --- a/webapp/src/app/modules/dashboard/dashboard.component.ts +++ b/webapp/src/app/modules/dashboard/dashboard.component.ts @@ -1,4 +1,11 @@ -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'; @@ -78,7 +85,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; statistics?: Partial; @@ -139,6 +149,8 @@ export class DashboardComponent implements OnInit { selectedAnalyticalInstitutionId = this.defaultAnalyticalInstitutionId; dashboardInstitutionsLoading = false; dashboardInstitutionsError = false; + canScrollAnalyticalInstitutionTabsLeft = false; + canScrollAnalyticalInstitutionTabsRight = false; selectedTopicTreemapNode?: string; selectedDfgTopicTreemapNode?: string; selectedEuTopicTreemapNode?: string; @@ -168,6 +180,15 @@ export class DashboardComponent implements OnInit { this.loadDfgProjectStatuses(); } + ngAfterViewInit(): void { + setTimeout(() => this.updateAnalyticalInstitutionTabScrollState()); + } + + @HostListener('window:resize') + onWindowResize(): void { + this.updateAnalyticalInstitutionTabScrollState(); + } + private loadDashboardInstitutions(): void { this.dashboardInstitutionsLoading = true; this.dashboardInstitutionsError = false; @@ -177,6 +198,7 @@ export class DashboardComponent implements OnInit { .subscribe({ next: (institutions) => { this.dashboardInstitutions = institutions; + setTimeout(() => this.updateAnalyticalInstitutionTabScrollState()); const requestedInstitution = this.route.snapshot.queryParamMap.get('institution') ?? 'all'; const restoredInstitution = institutions.some( @@ -451,6 +473,30 @@ export class DashboardComponent implements OnInit { 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; + } + onTopicTreemapNodeChange(nodeId: string | undefined): void { this.selectedTopicTreemapNode = nodeId; this.updateDashboardPeriodUrl(); -- 2.56.1 From a6c4668d13f57c4043ef2b867eff60e02dfceda7 Mon Sep 17 00:00:00 2001 From: Farajollahi Date: Mon, 17 Aug 2026 14:57:31 +0200 Subject: [PATCH 14/15] show projects of institut --- service/src/main/inse/auth/router.py | 2 + service/src/main/inse/auth/service.py | 68 +++++-- .../src/main/inse/auth/test_auth_service.py | 91 ++++++++- service/src/main/inse/projects/router.py | 174 ++++++++++++------ .../app-institution-card.component.ts | 21 +-- 5 files changed, 262 insertions(+), 94 deletions(-) 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/projects/router.py b/service/src/main/inse/projects/router.py index 3c3f2c97..b2b1e0f8 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.")] = "title", @@ -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/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 8b92a5b4..a7196245 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'; @Component({ selector: 'app-institution-card', @@ -30,7 +29,7 @@ import { CredentialService } from '../../services/credential.service'; styleUrl: './app-institution-card.component.scss', }) export class AppInstitutionCardComponent { - private readonly credentialService = inject(CredentialService); + private readonly authService = inject(AuthService); private readonly patentsApi = inject(PatentsService); institution = input.required(); @@ -45,15 +44,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 @@ -65,9 +57,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({ -- 2.56.1 From c8e5a65f5d8f0db9b0ba77145132ca0c67d15a4d Mon Sep 17 00:00:00 2001 From: Farajollahi Date: Mon, 17 Aug 2026 16:32:50 +0200 Subject: [PATCH 15/15] fix(dashboard): support multiple institutions and improve project analytics --- .../src/main/inse/dashboard/test_service.py | 4 ++-- .../inse/dashboard/top_authors_service.py | 20 +------------------ 2 files changed, 3 insertions(+), 21 deletions(-) diff --git a/service/src/main/inse/dashboard/test_service.py b/service/src/main/inse/dashboard/test_service.py index 5d1a1c58..8f21c89b 100644 --- a/service/src/main/inse/dashboard/test_service.py +++ b/service/src/main/inse/dashboard/test_service.py @@ -1081,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}, ] 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) -- 2.56.1