feat(dashboard): add institution filter for organization-wide statistics
LocationBasedServices/smartguide/pipeline/head This commit looks good
LocationBasedServices/smartguide/pipeline/head This commit looks good
This commit is contained in:
@@ -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
|
||||
|
||||
@@ -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,
|
||||
)
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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,
|
||||
)
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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 []
|
||||
|
||||
@@ -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"]}})
|
||||
|
||||
@@ -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(
|
||||
|
||||
@@ -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<DashboardInstitution[]> {
|
||||
return this.httpClient.get<DashboardInstitution[]>(
|
||||
`${this.apiConfiguration?.basePath ?? ''}/api/dashboard/institutions`,
|
||||
);
|
||||
}
|
||||
|
||||
getStatistics(): Observable<DashboardStatistics> {
|
||||
return this.httpClient.get<DashboardStatistics>(
|
||||
`${this.apiConfiguration?.basePath ?? ''}/api/dashboard/statistics`,
|
||||
@@ -124,37 +135,41 @@ export class DashboardStatisticsService {
|
||||
|
||||
getPublicationCount(
|
||||
period: DashboardPeriodBounds = {},
|
||||
institutionId = 'all',
|
||||
): Observable<DashboardStatisticValue> {
|
||||
return this.httpClient.get<DashboardStatisticValue>(
|
||||
`${this.apiConfiguration?.basePath ?? ''}/api/dashboard/statistics/publications`,
|
||||
{ params: this.periodParams(period) },
|
||||
{ params: this.statisticParams(period, institutionId) },
|
||||
);
|
||||
}
|
||||
|
||||
getPersonCount(
|
||||
period: DashboardPeriodBounds = {},
|
||||
institutionId = 'all',
|
||||
): Observable<DashboardStatisticValue> {
|
||||
return this.httpClient.get<DashboardStatisticValue>(
|
||||
`${this.apiConfiguration?.basePath ?? ''}/api/dashboard/statistics/persons`,
|
||||
{ params: this.periodParams(period) },
|
||||
{ params: this.statisticParams(period, institutionId) },
|
||||
);
|
||||
}
|
||||
|
||||
getPatentCount(
|
||||
period: DashboardPeriodBounds = {},
|
||||
institutionId = 'all',
|
||||
): Observable<DashboardStatisticValue> {
|
||||
return this.httpClient.get<DashboardStatisticValue>(
|
||||
`${this.apiConfiguration?.basePath ?? ''}/api/dashboard/statistics/patents`,
|
||||
{ params: this.periodParams(period) },
|
||||
{ params: this.statisticParams(period, institutionId) },
|
||||
);
|
||||
}
|
||||
|
||||
getEuProjectCount(
|
||||
period: DashboardPeriodBounds = {},
|
||||
institutionId = 'all',
|
||||
): Observable<DashboardStatisticValue> {
|
||||
return this.httpClient.get<DashboardStatisticValue>(
|
||||
`${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<DashboardStatisticValue> {
|
||||
return this.httpClient.get<DashboardStatisticValue>(
|
||||
`${this.apiConfiguration?.basePath ?? ''}/api/dashboard/statistics/projects/bmbf`,
|
||||
{ params: this.periodParams(period) },
|
||||
{ params: this.statisticParams(period, institutionId) },
|
||||
);
|
||||
}
|
||||
|
||||
getDfgProjectCount(
|
||||
period: DashboardPeriodBounds = {},
|
||||
institutionId = 'all',
|
||||
): Observable<DashboardStatisticValue> {
|
||||
return this.httpClient.get<DashboardStatisticValue>(
|
||||
`${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<string, string | number> {
|
||||
return {
|
||||
...this.periodParams(period),
|
||||
institution_id: institutionId,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -30,6 +30,25 @@
|
||||
(endYearChange)="onDashboardPeriodRangeChange()">
|
||||
</app-year-range-slider>
|
||||
</div>
|
||||
<mat-form-field
|
||||
class="dashboard-institution-filter"
|
||||
appearance="outline"
|
||||
subscriptSizing="dynamic">
|
||||
<mat-label>Institution</mat-label>
|
||||
<mat-select
|
||||
[value]="selectedDashboardInstitutionId"
|
||||
[disabled]="
|
||||
dashboardInstitutionsLoading || dashboardInstitutions.length === 0
|
||||
"
|
||||
(selectionChange)="onDashboardInstitutionChange($event.value)">
|
||||
<mat-option value="all">Alle Institutionen</mat-option>
|
||||
@for (institution of dashboardInstitutions; track institution.id) {
|
||||
<mat-option [value]="institution.id">
|
||||
{{ institution.display_name }}
|
||||
</mat-option>
|
||||
}
|
||||
</mat-select>
|
||||
</mat-form-field>
|
||||
</section>
|
||||
|
||||
<section class="statistics-grid" aria-label="Kennzahlen">
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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,
|
||||
|
||||
Reference in New Issue
Block a user