Compare commits
36
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c8e5a65f5d | ||
|
|
a6c4668d13 | ||
|
|
df5f131320 | ||
|
|
2f22240d94 | ||
|
|
77095c8549 | ||
|
|
c733442300 | ||
|
|
8d7323a387 | ||
|
|
6a6ec8662c | ||
|
|
c70e6bf489 | ||
|
|
82fa2e816b | ||
|
|
fbcee778d2 | ||
|
|
1758227f1e | ||
|
|
545f38bc3d | ||
|
|
92e421a61c | ||
|
|
15f55af4c4 | ||
|
|
c8fa70e7f0 | ||
|
|
934c49bf49 | ||
|
|
70d6b3d698 | ||
|
|
e6e9628837 | ||
|
|
e1b3318e68 | ||
|
|
4d8a7405ca | ||
|
|
a3eebedb02 | ||
|
|
f8e5cd90a5 | ||
|
|
3d092b02f3 | ||
|
|
deb6448739 | ||
|
|
bfb3224684 | ||
|
|
aed1f33935 | ||
|
|
33192efa33 | ||
|
|
d48435b948 | ||
|
|
567b5ecd4f | ||
|
|
b21d8d3e88 | ||
|
|
727c3fde67 | ||
|
|
de880fb9f0 | ||
|
|
c054cf99fe | ||
|
|
98a742f024 | ||
|
|
bb791138cd |
@@ -88,6 +88,25 @@ class Organization(Durable, table=True):
|
||||
accounts: list["Account"] = Relationship(back_populates="organization")
|
||||
|
||||
|
||||
class OrganizationInstitution(SQLModel, table=True):
|
||||
__tablename__ = "organization_institution"
|
||||
__table_args__ = (
|
||||
UniqueConstraint(
|
||||
"organization_id",
|
||||
"position",
|
||||
name="uq_organization_institution_position",
|
||||
),
|
||||
)
|
||||
|
||||
organization_id: uuid.UUID = Field(
|
||||
foreign_key="organization.id",
|
||||
primary_key=True,
|
||||
index=True,
|
||||
)
|
||||
openalex_institution_id: str = Field(primary_key=True, index=True)
|
||||
position: int = Field(nullable=False)
|
||||
|
||||
|
||||
class Account(Durable, table=True):
|
||||
@model_validator(mode="before")
|
||||
@classmethod
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -22,6 +22,7 @@ from inse.auth.model import (
|
||||
IdTokenMetadata,
|
||||
LoginResponse,
|
||||
Organization,
|
||||
OrganizationInstitution,
|
||||
OtkResponse,
|
||||
RefreshTokenMetadata,
|
||||
Secret,
|
||||
@@ -98,9 +99,12 @@ def create_predefined_accounts(session: Session, file_path: str):
|
||||
with open(file_path, "r") as file:
|
||||
data: dict[str, Any] = json.loads(file.read())
|
||||
for organization_data in data.get("organizations", []):
|
||||
organization_id = organization_data.get("id")
|
||||
if organization_id is not None:
|
||||
organization_id = uuid.UUID(organization_id)
|
||||
organization_id_value = organization_data.get("id")
|
||||
organization_id = (
|
||||
uuid.UUID(organization_id_value)
|
||||
if organization_id_value is not None
|
||||
else uuid.uuid4()
|
||||
)
|
||||
organization_name = organization_data["name"]
|
||||
openalex_institution_id = organization_data.get(
|
||||
"openalex_institution_id"
|
||||
@@ -113,6 +117,14 @@ def create_predefined_accounts(session: Session, file_path: str):
|
||||
openalex_institution_id=openalex_institution_id,
|
||||
)
|
||||
session.add(organization)
|
||||
if openalex_institution_id:
|
||||
session.add(
|
||||
OrganizationInstitution(
|
||||
organization_id=organization.id,
|
||||
openalex_institution_id=openalex_institution_id,
|
||||
position=0,
|
||||
)
|
||||
)
|
||||
for account_data in data.get("accounts", []):
|
||||
organization_id = uuid.UUID(account_data["organization_id"])
|
||||
roles = normalize_roles(
|
||||
@@ -1455,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,
|
||||
@@ -1481,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
|
||||
|
||||
@@ -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"
|
||||
|
||||
@@ -0,0 +1,142 @@
|
||||
import hashlib
|
||||
from collections import defaultdict
|
||||
from typing import Any
|
||||
|
||||
from inse.institutions.institutions_search_client import InstitutionsSearchClient
|
||||
from inse.integrations import elasticsearch
|
||||
from inse.model import ESCluster, ESIndex
|
||||
from inse.projects import service as projects_service
|
||||
|
||||
from .model import BundProjectTopics, DfgProjectKeyword, DfgProjectTopic
|
||||
from .common import (
|
||||
dashboard_period as _dashboard_period,
|
||||
normalize_institution_id as _normalize_institution_id,
|
||||
raw_institution_id as _raw_institution_id,
|
||||
)
|
||||
|
||||
|
||||
async def get_dashboard_bund_topics(
|
||||
institution_id: str,
|
||||
organization_name: str,
|
||||
from_year: int | None = None,
|
||||
to_year: int | None = None,
|
||||
) -> BundProjectTopics:
|
||||
normalized_id = _normalize_institution_id(institution_id)
|
||||
period = _dashboard_period(from_year, to_year)
|
||||
page_size = 1000
|
||||
page_number = 0
|
||||
project_ids: set[str] = set()
|
||||
|
||||
while True:
|
||||
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),
|
||||
title=None,
|
||||
keywords=None,
|
||||
funding_arts=None,
|
||||
topic_ids=None,
|
||||
filter_topic_ids=None,
|
||||
funding_start_years=None,
|
||||
funding_end_years=None,
|
||||
active_from_year=period[0],
|
||||
active_to_year=period[1],
|
||||
countries=None,
|
||||
page=page_number,
|
||||
size=page_size,
|
||||
sort_by="id",
|
||||
sort_direction="asc",
|
||||
fuzzy=False,
|
||||
)
|
||||
project_ids.update(
|
||||
project.funding_code
|
||||
for project in projects.elements
|
||||
if project.funding_code
|
||||
)
|
||||
if len(project_ids) >= projects.total or not projects.elements:
|
||||
break
|
||||
page_number += 1
|
||||
|
||||
topics: dict[str, dict[str, Any]] = {}
|
||||
matched_project_ids: set[str] = set()
|
||||
if project_ids:
|
||||
mapping_project_ids = sorted(
|
||||
hashlib.sha256(project_id.encode("utf-8")).hexdigest()
|
||||
for project_id in project_ids
|
||||
)
|
||||
async for hit in elasticsearch.scan(
|
||||
index=str(ESIndex.PROJECTS_BUND_TOPICS),
|
||||
query={"terms": {"project_id": mapping_project_ids}},
|
||||
source=["project_id", "keyword", "topic_matches"],
|
||||
page_size=1000,
|
||||
cluster=ESCluster.INSE,
|
||||
):
|
||||
source = hit.get("_source", {})
|
||||
project_id = str(source.get("project_id") or "")
|
||||
if not project_id:
|
||||
continue
|
||||
keyword = str(source.get("keyword") or "").strip()
|
||||
matched_project_ids.add(project_id)
|
||||
for match in source.get("topic_matches", []):
|
||||
topic_id = str(match.get("topic_id") or "")
|
||||
if not topic_id:
|
||||
continue
|
||||
topic = topics.setdefault(
|
||||
topic_id,
|
||||
{
|
||||
"id": topic_id,
|
||||
"name": str(match.get("topic_display_name") or topic_id),
|
||||
"subfield": match.get("subfield"),
|
||||
"field": match.get("field"),
|
||||
"domain": match.get("domain"),
|
||||
"project_ids": set(),
|
||||
"keywords": {},
|
||||
},
|
||||
)
|
||||
topic["project_ids"].add(project_id)
|
||||
if keyword:
|
||||
topic["keywords"].setdefault(keyword, set()).add(project_id)
|
||||
|
||||
field_project_ids: dict[str, set[str]] = defaultdict(set)
|
||||
subfield_project_ids: dict[tuple[str, str], set[str]] = defaultdict(set)
|
||||
for topic in topics.values():
|
||||
field_name = str(topic["field"] or "")
|
||||
subfield_name = str(topic["subfield"] or "")
|
||||
field_project_ids[field_name].update(topic["project_ids"])
|
||||
subfield_project_ids[(field_name, subfield_name)].update(topic["project_ids"])
|
||||
|
||||
topic_list = [
|
||||
DfgProjectTopic(
|
||||
id=topic["id"],
|
||||
name=topic["name"],
|
||||
subfield=topic["subfield"],
|
||||
field=topic["field"],
|
||||
domain=topic["domain"],
|
||||
project_count=len(topic["project_ids"]),
|
||||
field_project_count=len(field_project_ids[str(topic["field"] or "")]),
|
||||
subfield_project_count=len(
|
||||
subfield_project_ids[
|
||||
(str(topic["field"] or ""), str(topic["subfield"] or ""))
|
||||
]
|
||||
),
|
||||
keywords=sorted(
|
||||
[
|
||||
DfgProjectKeyword(
|
||||
name=keyword,
|
||||
project_count=len(keyword_project_ids),
|
||||
)
|
||||
for keyword, keyword_project_ids in topic["keywords"].items()
|
||||
],
|
||||
key=lambda entry: (-entry.project_count, entry.name),
|
||||
),
|
||||
)
|
||||
for topic in topics.values()
|
||||
]
|
||||
topic_list.sort(key=lambda topic: (-topic.project_count, topic.name, topic.id))
|
||||
return BundProjectTopics(
|
||||
institution_id=normalized_id,
|
||||
organization_name=organization_name,
|
||||
project_count=len(project_ids),
|
||||
matched_project_count=len(matched_project_ids),
|
||||
topics=topic_list,
|
||||
)
|
||||
@@ -0,0 +1,92 @@
|
||||
from typing import Any, Literal
|
||||
|
||||
from fastapi import HTTPException, status
|
||||
|
||||
DashboardPeriod = tuple[int | None, int | None]
|
||||
|
||||
|
||||
def dashboard_period(
|
||||
from_year: int | None = None,
|
||||
to_year: int | None = None,
|
||||
) -> DashboardPeriod:
|
||||
if from_year is not None and to_year is not None and from_year > to_year:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
||||
detail="from_year must be less than or equal to to_year.",
|
||||
)
|
||||
return from_year, to_year
|
||||
|
||||
|
||||
def project_overlap_filter(
|
||||
start_field: str,
|
||||
end_field: str,
|
||||
period: DashboardPeriod,
|
||||
*,
|
||||
missing_end_is_ongoing: bool = False,
|
||||
) -> dict[str, Any] | None:
|
||||
from_year, to_year = period
|
||||
filters: list[dict[str, Any]] = []
|
||||
if to_year is not None:
|
||||
filters.append({"range": {start_field: {"lte": to_year}}})
|
||||
if from_year is not None:
|
||||
end_filter: dict[str, Any] = {"range": {end_field: {"gte": from_year}}}
|
||||
if missing_end_is_ongoing:
|
||||
end_filter = {
|
||||
"bool": {
|
||||
"should": [
|
||||
end_filter,
|
||||
{"bool": {"must_not": {"exists": {"field": end_field}}}},
|
||||
],
|
||||
"minimum_should_match": 1,
|
||||
}
|
||||
}
|
||||
filters.append(end_filter)
|
||||
return {"bool": {"filter": filters}} if filters else None
|
||||
|
||||
|
||||
def project_boundary_year_filter(
|
||||
start_field: str,
|
||||
end_field: str,
|
||||
period: DashboardPeriod,
|
||||
date_format: Literal["iso", "de", "year"],
|
||||
) -> dict[str, Any] | None:
|
||||
from_year, to_year = period
|
||||
filters: list[dict[str, Any]] = []
|
||||
if to_year is not None:
|
||||
if date_format == "year":
|
||||
filters.append({"range": {start_field: {"lte": to_year}}})
|
||||
else:
|
||||
last_day = (
|
||||
f"{to_year}-12-31" if date_format == "iso" else f"31.12.{to_year}"
|
||||
)
|
||||
filters.append({"range": {start_field: {"lte": last_day}}})
|
||||
if from_year is not None:
|
||||
if date_format == "year":
|
||||
filters.append({"range": {end_field: {"gte": from_year}}})
|
||||
else:
|
||||
first_day = (
|
||||
f"{from_year}-01-01" if date_format == "iso" else f"01.01.{from_year}"
|
||||
)
|
||||
filters.append({"range": {end_field: {"gte": first_day}}})
|
||||
return {"bool": {"filter": filters}} if filters else None
|
||||
|
||||
|
||||
def normalize_institution_id(value: str) -> str:
|
||||
return (
|
||||
value
|
||||
if value.startswith("https://openalex.org/")
|
||||
else f"https://openalex.org/{value}"
|
||||
)
|
||||
|
||||
|
||||
def raw_institution_id(value: str) -> str:
|
||||
return normalize_institution_id(value).removeprefix("https://openalex.org/")
|
||||
|
||||
|
||||
def institution_works_query(institution_id: str) -> dict[str, Any]:
|
||||
return {
|
||||
"nested": {
|
||||
"path": "authorships.institutions",
|
||||
"query": {"term": {"authorships.institutions.id": institution_id}},
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
from collections import defaultdict
|
||||
from typing import Any
|
||||
|
||||
from inse.integrations import elasticsearch
|
||||
from inse.model import ESCluster, ESIndex
|
||||
|
||||
from .model import DfgProjectKeyword, DfgProjectTopic, DfgProjectTopics
|
||||
from .common import normalize_institution_id as _normalize_institution_id
|
||||
from .project_ids_service import _get_dfg_project_ids_from_projects_service
|
||||
|
||||
|
||||
async def get_dashboard_dfg_topics(
|
||||
institution_id: str,
|
||||
organization_name: str,
|
||||
from_year: int | None = None,
|
||||
to_year: int | None = None,
|
||||
) -> DfgProjectTopics:
|
||||
normalized_id = _normalize_institution_id(institution_id)
|
||||
project_ids = await _get_dfg_project_ids_from_projects_service(
|
||||
normalized_id,
|
||||
from_year=from_year,
|
||||
to_year=to_year,
|
||||
)
|
||||
topics: dict[str, dict[str, Any]] = {}
|
||||
matched_project_ids: set[str] = set()
|
||||
|
||||
if project_ids:
|
||||
async for hit in elasticsearch.scan(
|
||||
index=str(ESIndex.PROJECTS_DFG_OPENALEX_TOPICS),
|
||||
query={"terms": {"project_id": project_ids}},
|
||||
source=["project_id", "keyword", "topic_matches"],
|
||||
page_size=1000,
|
||||
cluster=ESCluster.INSE,
|
||||
):
|
||||
source = hit.get("_source", {})
|
||||
project_id = str(source.get("project_id") or "")
|
||||
if not project_id:
|
||||
continue
|
||||
keyword = str(source.get("keyword") or "").strip()
|
||||
matched_project_ids.add(project_id)
|
||||
for match in source.get("topic_matches", []):
|
||||
topic_id = str(match.get("topic_id") or "")
|
||||
if not topic_id:
|
||||
continue
|
||||
topic = topics.setdefault(
|
||||
topic_id,
|
||||
{
|
||||
"id": topic_id,
|
||||
"name": str(match.get("topic_display_name") or topic_id),
|
||||
"subfield": match.get("subfield"),
|
||||
"field": match.get("field"),
|
||||
"domain": match.get("domain"),
|
||||
"project_ids": set(),
|
||||
"keywords": {},
|
||||
},
|
||||
)
|
||||
topic["project_ids"].add(project_id)
|
||||
if keyword:
|
||||
topic["keywords"].setdefault(keyword, set()).add(project_id)
|
||||
|
||||
field_project_ids: dict[str, set[str]] = defaultdict(set)
|
||||
subfield_project_ids: dict[tuple[str, str], set[str]] = defaultdict(set)
|
||||
for topic in topics.values():
|
||||
field_name = str(topic["field"] or "")
|
||||
subfield_name = str(topic["subfield"] or "")
|
||||
field_project_ids[field_name].update(topic["project_ids"])
|
||||
subfield_project_ids[(field_name, subfield_name)].update(topic["project_ids"])
|
||||
|
||||
topic_list = [
|
||||
DfgProjectTopic(
|
||||
id=topic["id"],
|
||||
name=topic["name"],
|
||||
subfield=topic["subfield"],
|
||||
field=topic["field"],
|
||||
domain=topic["domain"],
|
||||
project_count=len(topic["project_ids"]),
|
||||
field_project_count=len(field_project_ids[str(topic["field"] or "")]),
|
||||
subfield_project_count=len(
|
||||
subfield_project_ids[
|
||||
(str(topic["field"] or ""), str(topic["subfield"] or ""))
|
||||
]
|
||||
),
|
||||
keywords=sorted(
|
||||
[
|
||||
DfgProjectKeyword(
|
||||
name=keyword,
|
||||
project_count=len(keyword_project_ids),
|
||||
)
|
||||
for keyword, keyword_project_ids in topic["keywords"].items()
|
||||
],
|
||||
key=lambda entry: (-entry.project_count, entry.name),
|
||||
),
|
||||
)
|
||||
for topic in topics.values()
|
||||
]
|
||||
topic_list.sort(key=lambda topic: (-topic.project_count, topic.name, topic.id))
|
||||
return DfgProjectTopics(
|
||||
institution_id=normalized_id,
|
||||
organization_name=organization_name,
|
||||
project_count=len(project_ids),
|
||||
matched_project_count=len(matched_project_ids),
|
||||
topics=topic_list,
|
||||
)
|
||||
@@ -0,0 +1,109 @@
|
||||
from collections import defaultdict
|
||||
from typing import Any
|
||||
|
||||
from inse.integrations import elasticsearch
|
||||
from inse.model import ESCluster, ESIndex
|
||||
|
||||
from .model import DfgProjectKeyword, DfgProjectTopic, EuProjectTopics
|
||||
from .common import normalize_institution_id as _normalize_institution_id
|
||||
from .project_ids_service import _get_eu_project_ids_from_projects_service
|
||||
|
||||
|
||||
async def get_dashboard_eu_topics(
|
||||
institution_id: str,
|
||||
organization_name: str,
|
||||
from_year: int | None = None,
|
||||
to_year: int | None = None,
|
||||
) -> EuProjectTopics:
|
||||
normalized_id = _normalize_institution_id(institution_id)
|
||||
project_ids = await _get_eu_project_ids_from_projects_service(
|
||||
normalized_id,
|
||||
from_year=from_year,
|
||||
to_year=to_year,
|
||||
)
|
||||
topics: dict[str, dict[str, Any]] = {}
|
||||
matched_project_ids: set[str] = set()
|
||||
|
||||
if project_ids:
|
||||
mapping_indices = (
|
||||
ESIndex.PROJECTS_CORDIS_EU_FP7_TOPICS_MAPPING,
|
||||
ESIndex.PROJECTS_CORDIS_EU_H2020_TOPICS,
|
||||
ESIndex.PROJECTS_CORDIS_EU_HEUROPE_TOPICS,
|
||||
)
|
||||
for mapping_index in mapping_indices:
|
||||
async for hit in elasticsearch.scan(
|
||||
index=str(mapping_index),
|
||||
query={"terms": {"project_id": project_ids}},
|
||||
source=["project_id", "keyword", "topic_matches"],
|
||||
page_size=1000,
|
||||
cluster=ESCluster.INSE,
|
||||
):
|
||||
source = hit.get("_source", {})
|
||||
project_id = str(source.get("project_id") or "")
|
||||
if not project_id:
|
||||
continue
|
||||
keyword = str(source.get("keyword") or "").strip()
|
||||
matched_project_ids.add(project_id)
|
||||
for match in source.get("topic_matches", []):
|
||||
topic_id = str(match.get("topic_id") or "")
|
||||
if not topic_id:
|
||||
continue
|
||||
topic = topics.setdefault(
|
||||
topic_id,
|
||||
{
|
||||
"id": topic_id,
|
||||
"name": str(match.get("topic_display_name") or topic_id),
|
||||
"subfield": match.get("subfield"),
|
||||
"field": match.get("field"),
|
||||
"domain": match.get("domain"),
|
||||
"project_ids": set(),
|
||||
"keywords": {},
|
||||
},
|
||||
)
|
||||
topic["project_ids"].add(project_id)
|
||||
if keyword:
|
||||
topic["keywords"].setdefault(keyword, set()).add(project_id)
|
||||
|
||||
field_project_ids: dict[str, set[str]] = defaultdict(set)
|
||||
subfield_project_ids: dict[tuple[str, str], set[str]] = defaultdict(set)
|
||||
for topic in topics.values():
|
||||
field_name = str(topic["field"] or "")
|
||||
subfield_name = str(topic["subfield"] or "")
|
||||
field_project_ids[field_name].update(topic["project_ids"])
|
||||
subfield_project_ids[(field_name, subfield_name)].update(topic["project_ids"])
|
||||
|
||||
topic_list = [
|
||||
DfgProjectTopic(
|
||||
id=topic["id"],
|
||||
name=topic["name"],
|
||||
subfield=topic["subfield"],
|
||||
field=topic["field"],
|
||||
domain=topic["domain"],
|
||||
project_count=len(topic["project_ids"]),
|
||||
field_project_count=len(field_project_ids[str(topic["field"] or "")]),
|
||||
subfield_project_count=len(
|
||||
subfield_project_ids[
|
||||
(str(topic["field"] or ""), str(topic["subfield"] or ""))
|
||||
]
|
||||
),
|
||||
keywords=sorted(
|
||||
[
|
||||
DfgProjectKeyword(
|
||||
name=keyword,
|
||||
project_count=len(keyword_project_ids),
|
||||
)
|
||||
for keyword, keyword_project_ids in topic["keywords"].items()
|
||||
],
|
||||
key=lambda entry: (-entry.project_count, entry.name),
|
||||
),
|
||||
)
|
||||
for topic in topics.values()
|
||||
]
|
||||
topic_list.sort(key=lambda topic: (-topic.project_count, topic.name, topic.id))
|
||||
return EuProjectTopics(
|
||||
institution_id=normalized_id,
|
||||
organization_name=organization_name,
|
||||
project_count=len(project_ids),
|
||||
matched_project_count=len(matched_project_ids),
|
||||
topics=topic_list,
|
||||
)
|
||||
@@ -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
|
||||
@@ -54,6 +59,8 @@ class DfgProjectTopic(BaseModel):
|
||||
field: str | None = None
|
||||
domain: str | None = None
|
||||
project_count: int
|
||||
field_project_count: int
|
||||
subfield_project_count: int
|
||||
keywords: list[DfgProjectKeyword]
|
||||
|
||||
|
||||
@@ -65,6 +72,22 @@ class DfgProjectTopics(BaseModel):
|
||||
topics: list[DfgProjectTopic]
|
||||
|
||||
|
||||
class EuProjectTopics(BaseModel):
|
||||
institution_id: str
|
||||
organization_name: str
|
||||
project_count: int
|
||||
matched_project_count: int
|
||||
topics: list[DfgProjectTopic]
|
||||
|
||||
|
||||
class BundProjectTopics(BaseModel):
|
||||
institution_id: str
|
||||
organization_name: str
|
||||
project_count: int
|
||||
matched_project_count: int
|
||||
topics: list[DfgProjectTopic]
|
||||
|
||||
|
||||
class TopAuthor(BaseModel):
|
||||
id: str | None = None
|
||||
name: str
|
||||
@@ -80,6 +103,11 @@ class TopAuthorStatistics(BaseModel):
|
||||
news: list[TopAuthor]
|
||||
|
||||
|
||||
class TopAuthorAnalysis(BaseModel):
|
||||
institution_id: str
|
||||
authors: list[TopAuthor]
|
||||
|
||||
|
||||
class TopicHeatmapValue(BaseModel):
|
||||
year: int
|
||||
count: int
|
||||
|
||||
@@ -0,0 +1,102 @@
|
||||
from inse.institutions.institutions_search_client import InstitutionsSearchClient
|
||||
from inse.projects import service as projects_service
|
||||
from inse.projects.model import EuCordisProjectType
|
||||
|
||||
from .common import (
|
||||
dashboard_period as _dashboard_period,
|
||||
raw_institution_id as _raw_institution_id,
|
||||
)
|
||||
|
||||
|
||||
async def _get_dfg_project_ids_from_projects_service(
|
||||
institution_id: str,
|
||||
from_year: int | None = None,
|
||||
to_year: int | None = None,
|
||||
) -> list[str]:
|
||||
"""Returns every matching DFG project ID through the canonical project service."""
|
||||
period = _dashboard_period(from_year, to_year)
|
||||
page_size = 1000
|
||||
page_number = 0
|
||||
project_ids: set[str] = set()
|
||||
|
||||
while True:
|
||||
projects = await projects_service.get_dfg_projects(
|
||||
institutions_search_client=InstitutionsSearchClient(),
|
||||
raw_oa_institution_id=_raw_institution_id(institution_id),
|
||||
author_id=None,
|
||||
author_filter_ids=None,
|
||||
institution_ids=None,
|
||||
keywords=None,
|
||||
topic_ids=None,
|
||||
filter_topic_ids=None,
|
||||
title=None,
|
||||
funding_start_years=(
|
||||
[str(year) for year in range(1900, period[1] + 1)]
|
||||
if period[1] is not None
|
||||
else None
|
||||
),
|
||||
funding_end_years=(
|
||||
[str(year) for year in range(period[0], 2101)]
|
||||
if period[0] is not None
|
||||
else None
|
||||
),
|
||||
page=page_number,
|
||||
size=page_size,
|
||||
sort_by="id",
|
||||
sort_direction="asc",
|
||||
fuzzy=False,
|
||||
skip_enrichment=True,
|
||||
)
|
||||
project_ids.update(project.id for project in projects.elements if project.id)
|
||||
if len(project_ids) >= projects.total or not projects.elements:
|
||||
break
|
||||
page_number += 1
|
||||
|
||||
return sorted(project_ids)
|
||||
|
||||
|
||||
async def _get_eu_project_ids_from_projects_service(
|
||||
institution_id: str,
|
||||
from_year: int | None = None,
|
||||
to_year: int | None = None,
|
||||
) -> list[str]:
|
||||
"""Loads all organization EU project IDs from the canonical project service."""
|
||||
period = _dashboard_period(from_year, to_year)
|
||||
page_size = 1000
|
||||
page_number = 0
|
||||
project_ids: set[str] = set()
|
||||
|
||||
while True:
|
||||
projects = await projects_service.search_eu_cordis_projects(
|
||||
institutions_search_client=InstitutionsSearchClient(),
|
||||
raw_oa_institution_id=_raw_institution_id(institution_id),
|
||||
author_id=None,
|
||||
author_ids=None,
|
||||
organization_ids=None,
|
||||
organization_names=None,
|
||||
project_types=list(EuCordisProjectType),
|
||||
keywords=None,
|
||||
topic_ids=None,
|
||||
filter_topic_ids=None,
|
||||
title=None,
|
||||
funding_start_years=None,
|
||||
funding_end_years=None,
|
||||
active_from_year=period[0],
|
||||
active_to_year=period[1],
|
||||
countries=None,
|
||||
framework_programmes=None,
|
||||
funding_schemes=None,
|
||||
statuses=None,
|
||||
page=page_number,
|
||||
size=page_size,
|
||||
sort_by="id",
|
||||
sort_direction="asc",
|
||||
fuzzy=False,
|
||||
skip_enrichment=True,
|
||||
)
|
||||
project_ids.update(project.id for project in projects.elements if project.id)
|
||||
if len(project_ids) >= projects.total or not projects.elements:
|
||||
break
|
||||
page_number += 1
|
||||
|
||||
return sorted(project_ids)
|
||||
@@ -0,0 +1,172 @@
|
||||
import asyncio
|
||||
|
||||
from inse.institutions.institutions_search_client import InstitutionsSearchClient
|
||||
from inse.projects import service as projects_service
|
||||
from inse.projects.model import EuCordisProjectType
|
||||
|
||||
from .common import (
|
||||
dashboard_period as _dashboard_period,
|
||||
normalize_institution_id as _normalize_institution_id,
|
||||
raw_institution_id as _raw_institution_id,
|
||||
)
|
||||
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 | list[str],
|
||||
organization_name: str,
|
||||
from_year: int | None = None,
|
||||
to_year: int | None = None,
|
||||
) -> DashboardStatisticValue:
|
||||
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=(
|
||||
None if multiple_institutions else _raw_institution_id(institution_ids[0])
|
||||
),
|
||||
author_id=None,
|
||||
author_ids=None,
|
||||
organization_ids=None,
|
||||
organization_names=(
|
||||
await _institution_aliases(institution_ids)
|
||||
if multiple_institutions
|
||||
else None
|
||||
),
|
||||
project_types=list(EuCordisProjectType),
|
||||
keywords=None,
|
||||
topic_ids=None,
|
||||
filter_topic_ids=None,
|
||||
title=None,
|
||||
funding_start_years=None,
|
||||
funding_end_years=None,
|
||||
active_from_year=period[0],
|
||||
active_to_year=period[1],
|
||||
countries=None,
|
||||
framework_programmes=None,
|
||||
funding_schemes=None,
|
||||
statuses=None,
|
||||
page=0,
|
||||
size=1,
|
||||
sort_by="id",
|
||||
sort_direction="asc",
|
||||
fuzzy=False,
|
||||
)
|
||||
return DashboardStatisticValue(
|
||||
institution_id=_scope_id(institution_ids),
|
||||
organization_name=organization_name,
|
||||
value=projects.total,
|
||||
)
|
||||
|
||||
|
||||
async def get_dashboard_bmbf_projects(
|
||||
institution_id: str | list[str],
|
||||
organization_name: str,
|
||||
from_year: int | None = None,
|
||||
to_year: int | None = None,
|
||||
) -> DashboardStatisticValue:
|
||||
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=(
|
||||
None if multiple_institutions else _raw_institution_id(institution_ids[0])
|
||||
),
|
||||
title=None,
|
||||
keywords=None,
|
||||
funding_arts=None,
|
||||
topic_ids=None,
|
||||
filter_topic_ids=None,
|
||||
funding_start_years=None,
|
||||
funding_end_years=None,
|
||||
active_from_year=period[0],
|
||||
active_to_year=period[1],
|
||||
countries=None,
|
||||
page=0,
|
||||
size=1,
|
||||
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=_scope_id(institution_ids),
|
||||
organization_name=organization_name,
|
||||
value=projects.total,
|
||||
)
|
||||
|
||||
|
||||
async def get_dashboard_dfg_projects(
|
||||
institution_id: str | list[str],
|
||||
organization_name: str,
|
||||
from_year: int | None = None,
|
||||
to_year: int | None = None,
|
||||
) -> DashboardStatisticValue:
|
||||
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=(
|
||||
None if multiple_institutions else _raw_institution_id(institution_ids[0])
|
||||
),
|
||||
author_id=None,
|
||||
author_filter_ids=None,
|
||||
institution_ids=None,
|
||||
keywords=None,
|
||||
topic_ids=None,
|
||||
filter_topic_ids=None,
|
||||
title=None,
|
||||
funding_start_years=None,
|
||||
funding_end_years=None,
|
||||
active_from_year=period[0],
|
||||
active_to_year=period[1],
|
||||
page=0,
|
||||
size=1,
|
||||
sort_by="id",
|
||||
sort_direction="asc",
|
||||
fuzzy=False,
|
||||
skip_enrichment=True,
|
||||
institution_aliases=(
|
||||
await _institution_aliases(institution_ids)
|
||||
if multiple_institutions
|
||||
else None
|
||||
),
|
||||
)
|
||||
return DashboardStatisticValue(
|
||||
institution_id=_scope_id(institution_ids),
|
||||
organization_name=organization_name,
|
||||
value=projects.total,
|
||||
)
|
||||
@@ -0,0 +1,545 @@
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
|
||||
from inse.institutions.institutions_search_client import InstitutionsSearchClient
|
||||
|
||||
from inse.integrations import elasticsearch
|
||||
from inse.model import ESCluster, ESIndex
|
||||
|
||||
from .common import (
|
||||
DashboardPeriod,
|
||||
dashboard_period as _dashboard_period,
|
||||
normalize_institution_id as _normalize_institution_id,
|
||||
project_boundary_year_filter as _project_boundary_year_filter,
|
||||
project_overlap_filter as _project_overlap_filter,
|
||||
raw_institution_id as _raw_institution_id,
|
||||
)
|
||||
from .institute_helper import get_openalex_institution
|
||||
from .model import (
|
||||
BmbfProjectStatusStatistics,
|
||||
DfgProjectStatusStatistics,
|
||||
EuProjectStatusStatistics,
|
||||
)
|
||||
from .project_statistics_service import (
|
||||
get_dashboard_bmbf_projects,
|
||||
get_dashboard_dfg_projects,
|
||||
get_dashboard_eu_projects,
|
||||
)
|
||||
from .project_ids_service import _get_dfg_project_ids_from_projects_service
|
||||
|
||||
|
||||
def _status_count(aggregations: dict[str, Any], status_name: str) -> int:
|
||||
return int(aggregations.get(status_name, {}).get("projects", {}).get("value", 0))
|
||||
|
||||
|
||||
def reconcile_status_counts(
|
||||
total: int, ongoing: int, upcoming: int, completed: int
|
||||
) -> tuple[int, int, int]:
|
||||
"""Make status buckets add up to the authoritative project-service total."""
|
||||
counts = [max(0, ongoing), max(0, upcoming), max(0, completed)]
|
||||
difference = total - sum(counts)
|
||||
if difference >= 0:
|
||||
counts[0] += difference
|
||||
return counts[0], counts[1], counts[2]
|
||||
|
||||
excess = -difference
|
||||
for index in (0, 1, 2):
|
||||
reduction = min(counts[index], excess)
|
||||
counts[index] -= reduction
|
||||
excess -= reduction
|
||||
if excess == 0:
|
||||
break
|
||||
return counts[0], counts[1], counts[2]
|
||||
|
||||
|
||||
def _status_filter_aggregations(
|
||||
start_field: str, end_field: str, today: str
|
||||
) -> dict[str, Any]:
|
||||
return {
|
||||
"ongoing": {
|
||||
"filter": {
|
||||
"bool": {
|
||||
"filter": [
|
||||
{"range": {start_field: {"lte": today}}},
|
||||
{"range": {end_field: {"gte": today}}},
|
||||
]
|
||||
}
|
||||
}
|
||||
},
|
||||
"upcoming": {"filter": {"range": {start_field: {"gt": today}}}},
|
||||
"completed": {"filter": {"range": {end_field: {"lt": today}}}},
|
||||
}
|
||||
|
||||
|
||||
async def get_dashboard_eu_project_statuses(
|
||||
institution_id: str,
|
||||
organization_name: str,
|
||||
from_year: int | None = None,
|
||||
to_year: int | None = None,
|
||||
) -> EuProjectStatusStatistics:
|
||||
normalized_id = _normalize_institution_id(institution_id)
|
||||
total = (
|
||||
await get_dashboard_eu_projects(
|
||||
normalized_id, organization_name, from_year=from_year, to_year=to_year
|
||||
)
|
||||
).value
|
||||
if total == 0:
|
||||
return EuProjectStatusStatistics(
|
||||
institution_id=normalized_id,
|
||||
organization_name=organization_name,
|
||||
ongoing=0,
|
||||
upcoming=0,
|
||||
completed=0,
|
||||
)
|
||||
|
||||
aliases = await _institution_aliases(normalized_id, organization_name)
|
||||
project_ids = await _eu_project_ids_for_aliases(aliases)
|
||||
if not project_ids:
|
||||
return EuProjectStatusStatistics(
|
||||
institution_id=normalized_id,
|
||||
organization_name=organization_name,
|
||||
ongoing=total,
|
||||
upcoming=0,
|
||||
completed=0,
|
||||
)
|
||||
|
||||
today = datetime.now().date().isoformat()
|
||||
period = _dashboard_period(from_year, to_year)
|
||||
filters: list[dict[str, Any]] = [{"terms": {"id": sorted(project_ids)}}]
|
||||
if period_filter := _project_boundary_year_filter(
|
||||
"startDate", "endDate", period, "iso"
|
||||
):
|
||||
filters.append(period_filter)
|
||||
response = await elasticsearch.search(
|
||||
index=ESIndex.CORDIS_EU_PROJECTS_WILDCARD,
|
||||
body={
|
||||
"size": 0,
|
||||
"query": filters[0] if len(filters) == 1 else {"bool": {"filter": filters}},
|
||||
"aggs": {
|
||||
"ongoing": {
|
||||
"filter": {
|
||||
"bool": {
|
||||
"filter": [
|
||||
{"range": {"startDate": {"lte": today}}},
|
||||
{"range": {"endDate": {"gte": today}}},
|
||||
]
|
||||
}
|
||||
},
|
||||
"aggs": {"projects": {"cardinality": {"field": "id"}}},
|
||||
},
|
||||
"upcoming": {
|
||||
"filter": {"range": {"startDate": {"gt": today}}},
|
||||
"aggs": {"projects": {"cardinality": {"field": "id"}}},
|
||||
},
|
||||
"completed": {
|
||||
"filter": {"range": {"endDate": {"lt": today}}},
|
||||
"aggs": {"projects": {"cardinality": {"field": "id"}}},
|
||||
},
|
||||
},
|
||||
},
|
||||
cluster=ESCluster.INSE,
|
||||
)
|
||||
aggregations = response.get("aggregations", {})
|
||||
ongoing, upcoming, completed = reconcile_status_counts(
|
||||
total,
|
||||
_status_count(aggregations, "ongoing"),
|
||||
_status_count(aggregations, "upcoming"),
|
||||
_status_count(aggregations, "completed"),
|
||||
)
|
||||
return EuProjectStatusStatistics(
|
||||
institution_id=normalized_id,
|
||||
organization_name=organization_name,
|
||||
ongoing=ongoing,
|
||||
upcoming=upcoming,
|
||||
completed=completed,
|
||||
)
|
||||
|
||||
|
||||
async def get_dashboard_bmbf_project_statuses(
|
||||
institution_id: str,
|
||||
organization_name: str,
|
||||
from_year: int | None = None,
|
||||
to_year: int | None = None,
|
||||
) -> BmbfProjectStatusStatistics:
|
||||
normalized_id = _normalize_institution_id(institution_id)
|
||||
total = (
|
||||
await get_dashboard_bmbf_projects(
|
||||
normalized_id, organization_name, from_year=from_year, to_year=to_year
|
||||
)
|
||||
).value
|
||||
if total == 0:
|
||||
return BmbfProjectStatusStatistics(
|
||||
institution_id=normalized_id,
|
||||
organization_name=organization_name,
|
||||
ongoing=0,
|
||||
upcoming=0,
|
||||
completed=0,
|
||||
)
|
||||
|
||||
aliases = await _institution_aliases(normalized_id, organization_name)
|
||||
period = _dashboard_period(from_year, to_year)
|
||||
filters = [_alias_match_query("Zuwendungsempfänger", aliases)]
|
||||
if period_filter := _project_boundary_year_filter(
|
||||
"funding_start", "funding_end", period, "de"
|
||||
):
|
||||
filters.append(period_filter)
|
||||
response = await elasticsearch.search(
|
||||
index=ESIndex.PROJECTS_BUND_V1,
|
||||
body={
|
||||
"size": 0,
|
||||
"query": filters[0] if len(filters) == 1 else {"bool": {"filter": filters}},
|
||||
"aggs": _status_filter_aggregations(
|
||||
"funding_start", "funding_end", datetime.now().strftime("%d.%m.%Y")
|
||||
),
|
||||
},
|
||||
cluster=ESCluster.INSE,
|
||||
)
|
||||
aggregations = response.get("aggregations", {})
|
||||
ongoing, upcoming, completed = reconcile_status_counts(
|
||||
total,
|
||||
int(aggregations.get("ongoing", {}).get("doc_count", 0)),
|
||||
int(aggregations.get("upcoming", {}).get("doc_count", 0)),
|
||||
int(aggregations.get("completed", {}).get("doc_count", 0)),
|
||||
)
|
||||
return BmbfProjectStatusStatistics(
|
||||
institution_id=normalized_id,
|
||||
organization_name=organization_name,
|
||||
ongoing=ongoing,
|
||||
upcoming=upcoming,
|
||||
completed=completed,
|
||||
)
|
||||
|
||||
|
||||
async def get_dashboard_dfg_project_statuses(
|
||||
institution_id: str,
|
||||
organization_name: str,
|
||||
from_year: int | None = None,
|
||||
to_year: int | None = None,
|
||||
) -> DfgProjectStatusStatistics:
|
||||
normalized_id = _normalize_institution_id(institution_id)
|
||||
period = _dashboard_period(from_year, to_year)
|
||||
total = (
|
||||
await get_dashboard_dfg_projects(
|
||||
normalized_id, organization_name, from_year=from_year, to_year=to_year
|
||||
)
|
||||
).value
|
||||
if total == 0:
|
||||
return DfgProjectStatusStatistics(
|
||||
institution_id=normalized_id,
|
||||
organization_name=organization_name,
|
||||
ongoing=0,
|
||||
upcoming=0,
|
||||
completed=0,
|
||||
)
|
||||
|
||||
project_ids = await _get_dfg_project_ids_from_projects_service(
|
||||
normalized_id,
|
||||
from_year=from_year,
|
||||
to_year=to_year,
|
||||
)
|
||||
if not project_ids:
|
||||
return DfgProjectStatusStatistics(
|
||||
institution_id=normalized_id,
|
||||
organization_name=organization_name,
|
||||
ongoing=total,
|
||||
upcoming=0,
|
||||
completed=0,
|
||||
)
|
||||
|
||||
filters: list[dict[str, Any]] = [
|
||||
{
|
||||
"terms": {
|
||||
"projects.project_id": [int(project_id) for project_id in project_ids]
|
||||
}
|
||||
}
|
||||
]
|
||||
if period_filter := _project_boundary_year_filter(
|
||||
"projects.funding_start", "projects.funding_end", period, "year"
|
||||
):
|
||||
filters.append(period_filter)
|
||||
response = await elasticsearch.search(
|
||||
index=ESIndex.DFG_INSTITUTES_V2,
|
||||
body={
|
||||
"size": 0,
|
||||
"aggs": {
|
||||
"projects_nested": {
|
||||
"nested": {"path": "projects"},
|
||||
"aggs": {
|
||||
"selected_projects": {
|
||||
"filter": filters[0]
|
||||
if len(filters) == 1
|
||||
else {"bool": {"filter": filters}},
|
||||
"aggs": {
|
||||
"ongoing": {
|
||||
"filter": {
|
||||
"match_phrase": {
|
||||
"projects.status_de": "laufend"
|
||||
}
|
||||
},
|
||||
"aggs": {
|
||||
"projects": {
|
||||
"cardinality": {
|
||||
"field": "projects.project_id"
|
||||
}
|
||||
}
|
||||
},
|
||||
},
|
||||
"completed": {
|
||||
"filter": {
|
||||
"match_phrase": {
|
||||
"projects.status_de": "abgeschlossen"
|
||||
}
|
||||
},
|
||||
"aggs": {
|
||||
"projects": {
|
||||
"cardinality": {
|
||||
"field": "projects.project_id"
|
||||
}
|
||||
}
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
},
|
||||
}
|
||||
},
|
||||
},
|
||||
cluster=ESCluster.INSE,
|
||||
)
|
||||
aggregations = (
|
||||
response.get("aggregations", {})
|
||||
.get("projects_nested", {})
|
||||
.get("selected_projects", {})
|
||||
)
|
||||
ongoing, upcoming, completed = reconcile_status_counts(
|
||||
total,
|
||||
_status_count(aggregations, "ongoing"),
|
||||
0,
|
||||
_status_count(aggregations, "completed"),
|
||||
)
|
||||
return DfgProjectStatusStatistics(
|
||||
institution_id=normalized_id,
|
||||
organization_name=organization_name,
|
||||
ongoing=ongoing,
|
||||
upcoming=upcoming,
|
||||
completed=completed,
|
||||
)
|
||||
|
||||
|
||||
async def _get_dfg_project_ids_for_institution(
|
||||
institution_id: str,
|
||||
from_year: int | None = None,
|
||||
to_year: int | None = None,
|
||||
) -> list[str]:
|
||||
period = _dashboard_period(from_year, to_year)
|
||||
institution = await get_openalex_institution(institution_id)
|
||||
institution_names = _openalex_institution_names(institution)
|
||||
|
||||
institutes_response = await elasticsearch.search(
|
||||
index=ESIndex.DFG_INSTITUTES_V2,
|
||||
body={
|
||||
"size": 0,
|
||||
"query": _dfg_institute_name_query(institution_names),
|
||||
"aggs": {
|
||||
"institute_ids": {"terms": {"field": "institute_id", "size": 1000}}
|
||||
},
|
||||
},
|
||||
cluster=ESCluster.INSE,
|
||||
)
|
||||
institute_ids = [
|
||||
bucket["key"]
|
||||
for bucket in (
|
||||
institutes_response.get("aggregations", {})
|
||||
.get("institute_ids", {})
|
||||
.get("buckets", [])
|
||||
)
|
||||
if bucket.get("key") is not None
|
||||
]
|
||||
if not institute_ids:
|
||||
return []
|
||||
|
||||
projects_response = await elasticsearch.search(
|
||||
index=ESIndex.DFG_INSTITUTES_V2,
|
||||
body={
|
||||
"size": 0,
|
||||
"query": {"terms": {"institute_id": institute_ids}},
|
||||
"aggs": {
|
||||
"projects_nested": {
|
||||
"nested": {"path": "projects"},
|
||||
"aggs": {
|
||||
"project_ids": {
|
||||
"filter": {
|
||||
"terms": {"projects.institute_ref_id": institute_ids}
|
||||
},
|
||||
"aggs": {
|
||||
"values": {
|
||||
"terms": {
|
||||
"field": "projects.project_id",
|
||||
"size": 10000,
|
||||
}
|
||||
}
|
||||
},
|
||||
}
|
||||
},
|
||||
}
|
||||
},
|
||||
},
|
||||
cluster=ESCluster.INSE,
|
||||
)
|
||||
project_ids = [
|
||||
str(bucket["key"])
|
||||
for bucket in (
|
||||
projects_response.get("aggregations", {})
|
||||
.get("projects_nested", {})
|
||||
.get("project_ids", {})
|
||||
.get("values", {})
|
||||
.get("buckets", [])
|
||||
)
|
||||
if bucket.get("key") is not None
|
||||
]
|
||||
return await _filter_dfg_project_ids_by_period(project_ids, period)
|
||||
|
||||
|
||||
async def _eu_project_ids_for_aliases(aliases: list[str]) -> set[str]:
|
||||
project_ids: set[str] = set()
|
||||
async for hit in elasticsearch.scan(
|
||||
index=str(ESIndex.CORDIS_EU_ORGANIZATIONS_WILDCARD),
|
||||
query=_eu_organization_query(aliases),
|
||||
source=["projectID"],
|
||||
page_size=1000,
|
||||
cluster=ESCluster.INSE,
|
||||
):
|
||||
project_id = hit.get("_source", {}).get("projectID")
|
||||
if project_id is not None:
|
||||
project_ids.add(str(project_id))
|
||||
return project_ids
|
||||
|
||||
|
||||
async def _filter_dfg_project_ids_by_period(
|
||||
project_ids: list[str],
|
||||
period: DashboardPeriod,
|
||||
) -> list[str]:
|
||||
period_filter = _project_overlap_filter(
|
||||
"funding_start",
|
||||
"funding_end",
|
||||
period,
|
||||
missing_end_is_ongoing=True,
|
||||
)
|
||||
if not project_ids or not period_filter:
|
||||
return project_ids
|
||||
|
||||
numeric_project_ids = [
|
||||
int(project_id) for project_id in project_ids if str(project_id).isdigit()
|
||||
]
|
||||
if not numeric_project_ids:
|
||||
return []
|
||||
|
||||
response = await elasticsearch.search(
|
||||
index=ESIndex.DFG_PROJECTS,
|
||||
body={
|
||||
"size": 0,
|
||||
"query": {
|
||||
"bool": {
|
||||
"filter": [
|
||||
{"terms": {"id": numeric_project_ids}},
|
||||
period_filter,
|
||||
]
|
||||
}
|
||||
},
|
||||
"aggs": {
|
||||
"project_ids": {
|
||||
"terms": {
|
||||
"field": "id",
|
||||
"size": len(numeric_project_ids),
|
||||
}
|
||||
}
|
||||
},
|
||||
},
|
||||
cluster=ESCluster.INSE,
|
||||
)
|
||||
return [
|
||||
str(bucket["key"])
|
||||
for bucket in (
|
||||
response.get("aggregations", {}).get("project_ids", {}).get("buckets", [])
|
||||
)
|
||||
if bucket.get("key") is not None
|
||||
]
|
||||
|
||||
|
||||
async def _institution_aliases(
|
||||
institution_id: str,
|
||||
organization_name: str,
|
||||
) -> list[str]:
|
||||
aliases = (
|
||||
await InstitutionsSearchClient().get_institution_aliases_by_oa_institution_id(
|
||||
_raw_institution_id(institution_id)
|
||||
)
|
||||
)
|
||||
return sorted(
|
||||
{
|
||||
alias.strip()
|
||||
for alias in [organization_name, *aliases]
|
||||
if alias and alias.strip()
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
def _eu_organization_query(aliases: list[str]) -> dict[str, Any]:
|
||||
return {
|
||||
"terms": {
|
||||
"name.keyword": [alias.upper() for alias in aliases],
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
def _alias_match_query(field: str, aliases: list[str]) -> dict[str, Any]:
|
||||
return {
|
||||
"bool": {
|
||||
"should": [
|
||||
{
|
||||
"match": {
|
||||
field: {
|
||||
"query": alias,
|
||||
"operator": "and",
|
||||
}
|
||||
}
|
||||
}
|
||||
for alias in aliases
|
||||
],
|
||||
"minimum_should_match": 1,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
def _openalex_institution_names(institution: Any) -> list[str]:
|
||||
return sorted(
|
||||
{
|
||||
name.strip()
|
||||
for name in [
|
||||
institution.display_name,
|
||||
*(institution.display_name_alternatives or []),
|
||||
*(institution.display_name_acronyms or []),
|
||||
]
|
||||
if name and name.strip()
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
def _dfg_institute_name_query(institution_names: list[str]) -> dict[str, Any]:
|
||||
return {
|
||||
"bool": {
|
||||
"should": [
|
||||
{
|
||||
"terms": {
|
||||
"institute_name_de.keyword": institution_names,
|
||||
}
|
||||
},
|
||||
{
|
||||
"terms": {
|
||||
"institute_name_en.keyword": institution_names,
|
||||
}
|
||||
},
|
||||
],
|
||||
"minimum_should_match": 1,
|
||||
}
|
||||
}
|
||||
@@ -10,36 +10,69 @@ from inse.tags import Tags
|
||||
|
||||
from .model import (
|
||||
BmbfProjectStatusStatistics,
|
||||
BundProjectTopics,
|
||||
DashboardInstitution,
|
||||
DashboardStatistics,
|
||||
DashboardStatisticValue,
|
||||
DfgProjectStatusStatistics,
|
||||
DfgProjectTopics,
|
||||
EuProjectTopics,
|
||||
EuProjectStatusStatistics,
|
||||
TopAuthorStatistics,
|
||||
TopAuthorAnalysis,
|
||||
TopicHeatmap,
|
||||
TopicWordCloud,
|
||||
)
|
||||
from .service import (
|
||||
get_dashboard_bmbf_project_statuses,
|
||||
get_dashboard_bmbf_projects,
|
||||
get_dashboard_dfg_project_statuses,
|
||||
get_dashboard_dfg_projects,
|
||||
get_dashboard_dfg_topics,
|
||||
get_dashboard_eu_project_statuses,
|
||||
get_dashboard_eu_projects,
|
||||
get_dashboard_analytical_institution,
|
||||
get_dashboard_institutions,
|
||||
get_dashboard_organization,
|
||||
get_dashboard_patents,
|
||||
get_dashboard_persons,
|
||||
get_dashboard_publications,
|
||||
get_dashboard_statistic_institution_ids,
|
||||
get_dashboard_statistics,
|
||||
get_top_authors,
|
||||
get_topic_heatmap,
|
||||
get_topic_word_cloud,
|
||||
)
|
||||
from .project_statistics_service import (
|
||||
get_dashboard_bmbf_projects,
|
||||
get_dashboard_dfg_projects,
|
||||
get_dashboard_eu_projects,
|
||||
)
|
||||
from .bund_topics_service import get_dashboard_bund_topics
|
||||
from .dfg_topics_service import get_dashboard_dfg_topics
|
||||
from .eu_topics_service import get_dashboard_eu_topics
|
||||
from .project_status_service import (
|
||||
get_dashboard_bmbf_project_statuses,
|
||||
get_dashboard_dfg_project_statuses,
|
||||
get_dashboard_eu_project_statuses,
|
||||
)
|
||||
from .top_authors_service import (
|
||||
get_top_authors,
|
||||
get_top_eu_project_authors,
|
||||
get_top_news_authors,
|
||||
get_top_patent_authors,
|
||||
get_top_project_authors,
|
||||
get_top_work_authors,
|
||||
)
|
||||
|
||||
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",
|
||||
@@ -62,14 +95,18 @@ async def dashboard_statistics(
|
||||
response_model=DashboardStatisticValue,
|
||||
)
|
||||
async def dashboard_publications(
|
||||
institution_id: str | None = Query(default=None),
|
||||
from_year: int | None = Query(default=None, ge=1900, le=2100),
|
||||
to_year: int | None = Query(default=None, ge=1900, le=2100),
|
||||
session: Session = Depends(get_session),
|
||||
access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
|
||||
) -> DashboardStatisticValue:
|
||||
organization = get_dashboard_organization(session, access_token)
|
||||
institution_ids = await get_dashboard_statistic_institution_ids(
|
||||
session, organization, institution_id
|
||||
)
|
||||
return await get_dashboard_publications(
|
||||
organization.openalex_institution_id,
|
||||
institution_ids,
|
||||
organization.name,
|
||||
from_year=from_year,
|
||||
to_year=to_year,
|
||||
@@ -82,14 +119,18 @@ async def dashboard_publications(
|
||||
response_model=DashboardStatisticValue,
|
||||
)
|
||||
async def dashboard_persons(
|
||||
institution_id: str | None = Query(default=None),
|
||||
from_year: int | None = Query(default=None, ge=1900, le=2100),
|
||||
to_year: int | None = Query(default=None, ge=1900, le=2100),
|
||||
session: Session = Depends(get_session),
|
||||
access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
|
||||
) -> DashboardStatisticValue:
|
||||
organization = get_dashboard_organization(session, access_token)
|
||||
institution_ids = await get_dashboard_statistic_institution_ids(
|
||||
session, organization, institution_id
|
||||
)
|
||||
return await get_dashboard_persons(
|
||||
organization.openalex_institution_id,
|
||||
institution_ids,
|
||||
organization.name,
|
||||
from_year=from_year,
|
||||
to_year=to_year,
|
||||
@@ -102,14 +143,18 @@ async def dashboard_persons(
|
||||
response_model=DashboardStatisticValue,
|
||||
)
|
||||
async def dashboard_patents(
|
||||
institution_id: str | None = Query(default=None),
|
||||
from_year: int | None = Query(default=None, ge=1900, le=2100),
|
||||
to_year: int | None = Query(default=None, ge=1900, le=2100),
|
||||
session: Session = Depends(get_session),
|
||||
access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
|
||||
) -> DashboardStatisticValue:
|
||||
organization = get_dashboard_organization(session, access_token)
|
||||
institution_ids = await get_dashboard_statistic_institution_ids(
|
||||
session, organization, institution_id
|
||||
)
|
||||
return await get_dashboard_patents(
|
||||
organization.openalex_institution_id,
|
||||
institution_ids,
|
||||
organization.name,
|
||||
from_year=from_year,
|
||||
to_year=to_year,
|
||||
@@ -122,14 +167,18 @@ async def dashboard_patents(
|
||||
response_model=DashboardStatisticValue,
|
||||
)
|
||||
async def dashboard_eu_projects(
|
||||
institution_id: str | None = Query(default=None),
|
||||
from_year: int | None = Query(default=None, ge=1900, le=2100),
|
||||
to_year: int | None = Query(default=None, ge=1900, le=2100),
|
||||
session: Session = Depends(get_session),
|
||||
access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
|
||||
) -> DashboardStatisticValue:
|
||||
organization = get_dashboard_organization(session, access_token)
|
||||
institution_ids = await get_dashboard_statistic_institution_ids(
|
||||
session, organization, institution_id
|
||||
)
|
||||
return await get_dashboard_eu_projects(
|
||||
organization.openalex_institution_id,
|
||||
institution_ids,
|
||||
organization.name,
|
||||
from_year=from_year,
|
||||
to_year=to_year,
|
||||
@@ -142,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,
|
||||
)
|
||||
@@ -162,14 +217,18 @@ async def dashboard_eu_project_statuses(
|
||||
response_model=DashboardStatisticValue,
|
||||
)
|
||||
async def dashboard_bmbf_projects(
|
||||
institution_id: str | None = Query(default=None),
|
||||
from_year: int | None = Query(default=None, ge=1900, le=2100),
|
||||
to_year: int | None = Query(default=None, ge=1900, le=2100),
|
||||
session: Session = Depends(get_session),
|
||||
access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
|
||||
) -> DashboardStatisticValue:
|
||||
organization = get_dashboard_organization(session, access_token)
|
||||
institution_ids = await get_dashboard_statistic_institution_ids(
|
||||
session, organization, institution_id
|
||||
)
|
||||
return await get_dashboard_bmbf_projects(
|
||||
organization.openalex_institution_id,
|
||||
institution_ids,
|
||||
organization.name,
|
||||
from_year=from_year,
|
||||
to_year=to_year,
|
||||
@@ -182,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,
|
||||
)
|
||||
@@ -202,14 +267,18 @@ async def dashboard_bmbf_project_statuses(
|
||||
response_model=DashboardStatisticValue,
|
||||
)
|
||||
async def dashboard_dfg_projects(
|
||||
institution_id: str | None = Query(default=None),
|
||||
from_year: int | None = Query(default=None, ge=1900, le=2100),
|
||||
to_year: int | None = Query(default=None, ge=1900, le=2100),
|
||||
session: Session = Depends(get_session),
|
||||
access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
|
||||
) -> DashboardStatisticValue:
|
||||
organization = get_dashboard_organization(session, access_token)
|
||||
institution_ids = await get_dashboard_statistic_institution_ids(
|
||||
session, organization, institution_id
|
||||
)
|
||||
return await get_dashboard_dfg_projects(
|
||||
organization.openalex_institution_id,
|
||||
institution_ids,
|
||||
organization.name,
|
||||
from_year=from_year,
|
||||
to_year=to_year,
|
||||
@@ -222,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,
|
||||
)
|
||||
@@ -242,15 +317,73 @@ 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,
|
||||
)
|
||||
|
||||
|
||||
@router.get(
|
||||
"/projects/eu/topics",
|
||||
operation_id="getDashboardEuProjectTopics",
|
||||
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(
|
||||
selected_institution_id,
|
||||
selected_institution_name,
|
||||
from_year=from_year,
|
||||
to_year=to_year,
|
||||
)
|
||||
|
||||
|
||||
@router.get(
|
||||
"/projects/bund/topics",
|
||||
operation_id="getDashboardBundProjectTopics",
|
||||
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(
|
||||
selected_institution_id,
|
||||
selected_institution_name,
|
||||
from_year=from_year,
|
||||
to_year=to_year,
|
||||
)
|
||||
@@ -266,27 +399,144 @@ 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,
|
||||
)
|
||||
|
||||
|
||||
@router.get(
|
||||
"/top-authors/works",
|
||||
operation_id="getDashboardTopWorkAuthors",
|
||||
response_model=TopAuthorAnalysis,
|
||||
)
|
||||
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(
|
||||
selected_institution_id, works_period, from_year, to_year
|
||||
)
|
||||
|
||||
|
||||
@router.get(
|
||||
"/top-authors/projects",
|
||||
operation_id="getDashboardTopProjectAuthors",
|
||||
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(
|
||||
selected_institution_id, selected_institution_name, from_year, to_year
|
||||
)
|
||||
|
||||
|
||||
@router.get(
|
||||
"/top-authors/eu-projects",
|
||||
operation_id="getDashboardTopEuProjectAuthors",
|
||||
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(
|
||||
selected_institution_id, from_year, to_year
|
||||
)
|
||||
|
||||
|
||||
@router.get(
|
||||
"/top-authors/patents",
|
||||
operation_id="getDashboardTopPatentAuthors",
|
||||
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(
|
||||
selected_institution_id, from_year, to_year
|
||||
)
|
||||
|
||||
|
||||
@router.get(
|
||||
"/top-authors/news",
|
||||
operation_id="getDashboardTopNewsAuthors",
|
||||
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(
|
||||
selected_institution_id, from_year, to_year
|
||||
)
|
||||
|
||||
|
||||
@router.get(
|
||||
"/topic-heatmap",
|
||||
operation_id="getDashboardTopicHeatmap",
|
||||
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),
|
||||
@@ -294,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,
|
||||
@@ -310,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),
|
||||
@@ -317,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,
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -107,6 +107,30 @@ def create_db_and_tables():
|
||||
)
|
||||
)
|
||||
|
||||
# Preserve the former single institution as the first manually selected
|
||||
# institution.
|
||||
# The legacy column remains synchronized for portal sections that have not yet
|
||||
# been migrated to organization-wide institution lists.
|
||||
with engine.begin() as connection:
|
||||
connection.execute(
|
||||
text(
|
||||
"""
|
||||
INSERT INTO organization_institution (
|
||||
organization_id, openalex_institution_id, position
|
||||
)
|
||||
SELECT id, openalex_institution_id, 0
|
||||
FROM organization
|
||||
WHERE openalex_institution_id IS NOT NULL
|
||||
AND TRIM(openalex_institution_id) != ''
|
||||
AND NOT EXISTS (
|
||||
SELECT 1
|
||||
FROM organization_institution oi
|
||||
WHERE oi.organization_id = organization.id
|
||||
)
|
||||
"""
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
def get_session():
|
||||
"""Yields a database session for use in FastAPI endpoints.
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import uuid
|
||||
from typing import Literal
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
@@ -7,6 +8,7 @@ class OrganizationProfile(BaseModel):
|
||||
id: uuid.UUID
|
||||
name: str
|
||||
other_inst_id: str | None = None
|
||||
selected_openalex_institution_ids: list[str] = Field(default_factory=list)
|
||||
deleted: bool
|
||||
member_count: int
|
||||
|
||||
@@ -21,9 +23,25 @@ class OrganizationPage(BaseModel):
|
||||
class CreateOrganizationRequest(BaseModel):
|
||||
name: str = Field(min_length=1)
|
||||
other_inst_id: str | None = None
|
||||
selected_openalex_institution_ids: list[str] | None = None
|
||||
|
||||
|
||||
class UpdateOrganizationRequest(BaseModel):
|
||||
name: str | None = Field(default=None, min_length=1)
|
||||
other_inst_id: str | None = None
|
||||
selected_openalex_institution_ids: list[str] | None = None
|
||||
deleted: bool | None = None
|
||||
|
||||
|
||||
class InstitutionAssociation(BaseModel):
|
||||
id: str
|
||||
display_name: str
|
||||
relationship: Literal["child", "related"]
|
||||
|
||||
|
||||
class InstitutionAssociationsResponse(BaseModel):
|
||||
id: str
|
||||
display_name: str
|
||||
associated_institutions: list[InstitutionAssociation] = Field(
|
||||
default_factory=list
|
||||
)
|
||||
|
||||
@@ -11,6 +11,7 @@ from inse.tags import Tags
|
||||
from . import service
|
||||
from .model import (
|
||||
CreateOrganizationRequest,
|
||||
InstitutionAssociationsResponse,
|
||||
OrganizationPage,
|
||||
OrganizationProfile,
|
||||
UpdateOrganizationRequest,
|
||||
@@ -19,6 +20,18 @@ from .model import (
|
||||
router = APIRouter(prefix="/api/organizations", tags=[Tags.ORGANIZATION])
|
||||
|
||||
|
||||
@router.get(
|
||||
"/institutions/associations",
|
||||
operation_id="getOrganizationInstitutionAssociations",
|
||||
response_model=list[InstitutionAssociationsResponse],
|
||||
)
|
||||
async def get_organization_institution_associations(
|
||||
institution_ids: list[str] = Query(),
|
||||
access_token: AccessTokenMetadata = auth_service.CurrentUserAccessTokenPayloadDep,
|
||||
) -> list[InstitutionAssociationsResponse]:
|
||||
return await service.get_institution_associations(access_token, institution_ids)
|
||||
|
||||
|
||||
@router.get("", operation_id="getOrganisations", response_model=OrganizationPage)
|
||||
async def get_organizations(
|
||||
page: int = Query(default=0, ge=0),
|
||||
|
||||
@@ -1,18 +1,43 @@
|
||||
import logging
|
||||
import re
|
||||
import uuid
|
||||
|
||||
from fastapi import HTTPException, status
|
||||
from sqlmodel import Session, func, select
|
||||
|
||||
from inse.auth.model import AccessTokenMetadata, Account, Organization, UserRole
|
||||
from inse.auth.model import (
|
||||
AccessTokenMetadata,
|
||||
Account,
|
||||
Organization,
|
||||
OrganizationInstitution,
|
||||
UserRole,
|
||||
)
|
||||
from inse.integrations import elasticsearch
|
||||
from inse.model import ESIndex
|
||||
|
||||
from .model import (
|
||||
CreateOrganizationRequest,
|
||||
InstitutionAssociation,
|
||||
InstitutionAssociationsResponse,
|
||||
OrganizationPage,
|
||||
OrganizationProfile,
|
||||
UpdateOrganizationRequest,
|
||||
)
|
||||
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
OPENALEX_INSTITUTION_ID_PATTERN = re.compile(
|
||||
r"^(?:https?://openalex\.org/)?(I\d+)/?$", re.IGNORECASE
|
||||
)
|
||||
KNOWN_ASSOCIATION_TYPES = {
|
||||
"parent",
|
||||
"child",
|
||||
"related",
|
||||
"predecessor",
|
||||
"successor",
|
||||
}
|
||||
|
||||
|
||||
def _require_super_admin(access_token: AccessTokenMetadata) -> None:
|
||||
if access_token.effective_role != UserRole.SUPER_ADMIN:
|
||||
raise HTTPException(
|
||||
@@ -31,6 +56,27 @@ def _normalize_name(name: str) -> str:
|
||||
return normalized_name
|
||||
|
||||
|
||||
def _normalize_institution_id(institution_id: str) -> str:
|
||||
match = OPENALEX_INSTITUTION_ID_PATTERN.fullmatch(institution_id.strip())
|
||||
if match is None:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
||||
detail=f"Invalid OpenAlex institution ID: {institution_id}",
|
||||
)
|
||||
return f"I{match.group(1)[1:]}"
|
||||
|
||||
|
||||
def _normalize_institution_ids(institution_ids: list[str]) -> list[str]:
|
||||
normalized: list[str] = []
|
||||
seen: set[str] = set()
|
||||
for institution_id in institution_ids:
|
||||
clean_id = _normalize_institution_id(institution_id)
|
||||
if clean_id not in seen:
|
||||
normalized.append(clean_id)
|
||||
seen.add(clean_id)
|
||||
return normalized
|
||||
|
||||
|
||||
def _ensure_name_available(
|
||||
session: Session,
|
||||
name: str,
|
||||
@@ -79,18 +125,76 @@ def _member_counts(
|
||||
return {organization_id: count for organization_id, count in rows}
|
||||
|
||||
|
||||
def _institution_data(
|
||||
session: Session, organization_ids: list[uuid.UUID]
|
||||
) -> dict[uuid.UUID, list[str]]:
|
||||
ids_by_organization: dict[uuid.UUID, list[str]] = {
|
||||
organization_id: [] for organization_id in organization_ids
|
||||
}
|
||||
if not organization_ids:
|
||||
return ids_by_organization
|
||||
|
||||
institution_rows = session.exec(
|
||||
select(OrganizationInstitution)
|
||||
.where(OrganizationInstitution.organization_id.in_(organization_ids))
|
||||
.order_by(
|
||||
OrganizationInstitution.organization_id,
|
||||
OrganizationInstitution.position,
|
||||
)
|
||||
).all()
|
||||
for row in institution_rows:
|
||||
ids_by_organization[row.organization_id].append(
|
||||
row.openalex_institution_id
|
||||
)
|
||||
|
||||
return ids_by_organization
|
||||
|
||||
|
||||
def _to_profile(
|
||||
organization: Organization, member_count: int
|
||||
organization: Organization,
|
||||
member_count: int,
|
||||
institution_ids: list[str],
|
||||
) -> OrganizationProfile:
|
||||
if not institution_ids and organization.openalex_institution_id:
|
||||
legacy_id = _normalize_institution_id(organization.openalex_institution_id)
|
||||
institution_ids = [legacy_id]
|
||||
return OrganizationProfile(
|
||||
id=organization.id,
|
||||
name=organization.name,
|
||||
other_inst_id=organization.openalex_institution_id,
|
||||
other_inst_id=institution_ids[0] if institution_ids else None,
|
||||
selected_openalex_institution_ids=institution_ids,
|
||||
deleted=organization.deleted,
|
||||
member_count=member_count,
|
||||
)
|
||||
|
||||
|
||||
def _replace_organization_institutions(
|
||||
session: Session,
|
||||
organization: Organization,
|
||||
institution_ids: list[str],
|
||||
) -> None:
|
||||
normalized_ids = _normalize_institution_ids(institution_ids)
|
||||
for row in session.exec(
|
||||
select(OrganizationInstitution).where(
|
||||
OrganizationInstitution.organization_id == organization.id
|
||||
)
|
||||
).all():
|
||||
session.delete(row)
|
||||
session.flush()
|
||||
|
||||
for position, institution_id in enumerate(normalized_ids):
|
||||
session.add(
|
||||
OrganizationInstitution(
|
||||
organization_id=organization.id,
|
||||
openalex_institution_id=institution_id,
|
||||
position=position,
|
||||
)
|
||||
)
|
||||
organization.openalex_institution_id = (
|
||||
normalized_ids[0] if normalized_ids else None
|
||||
)
|
||||
|
||||
|
||||
def _deactivate_organization_accounts(
|
||||
session: Session, organization_id: uuid.UUID
|
||||
) -> None:
|
||||
@@ -106,6 +210,27 @@ def _deactivate_organization_accounts(
|
||||
session.add(account)
|
||||
|
||||
|
||||
def _ensure_not_current_organization(
|
||||
session: Session,
|
||||
access_token: AccessTokenMetadata,
|
||||
organization_id: uuid.UUID,
|
||||
) -> None:
|
||||
protected_organization_ids = {access_token.effective_organization_id}
|
||||
if access_token.real_account_id is not None:
|
||||
real_account = session.get(Account, access_token.real_account_id)
|
||||
if real_account is not None:
|
||||
protected_organization_ids.add(real_account.organization_id)
|
||||
|
||||
if organization_id in protected_organization_ids:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_409_CONFLICT,
|
||||
detail=(
|
||||
"The organization of the real or effective account "
|
||||
"cannot be deleted."
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def get_organizations(
|
||||
session: Session,
|
||||
access_token: AccessTokenMetadata,
|
||||
@@ -130,10 +255,15 @@ def get_organizations(
|
||||
).all()
|
||||
organization_ids = [organization.id for organization in organizations]
|
||||
counts = _member_counts(session, organization_ids)
|
||||
institution_ids = _institution_data(session, organization_ids)
|
||||
|
||||
return OrganizationPage(
|
||||
items=[
|
||||
_to_profile(organization, counts.get(organization.id, 0))
|
||||
_to_profile(
|
||||
organization,
|
||||
counts.get(organization.id, 0),
|
||||
institution_ids.get(organization.id, []),
|
||||
)
|
||||
for organization in organizations
|
||||
],
|
||||
total=total,
|
||||
@@ -153,12 +283,25 @@ def create_organization(
|
||||
|
||||
organization = Organization(
|
||||
name=name,
|
||||
openalex_institution_id=(payload.other_inst_id or '').strip() or None,
|
||||
)
|
||||
session.add(organization)
|
||||
session.flush()
|
||||
requested_ids = payload.selected_openalex_institution_ids
|
||||
if requested_ids is None:
|
||||
requested_ids = [payload.other_inst_id] if payload.other_inst_id else []
|
||||
_replace_organization_institutions(
|
||||
session,
|
||||
organization,
|
||||
requested_ids,
|
||||
)
|
||||
session.commit()
|
||||
session.refresh(organization)
|
||||
return _to_profile(organization, 0)
|
||||
institution_ids = _institution_data(session, [organization.id])
|
||||
return _to_profile(
|
||||
organization,
|
||||
0,
|
||||
institution_ids[organization.id],
|
||||
)
|
||||
|
||||
|
||||
def update_organization(
|
||||
@@ -174,10 +317,21 @@ def update_organization(
|
||||
name = _normalize_name(payload.name)
|
||||
_ensure_name_available(session, name, organization.id)
|
||||
organization.name = name
|
||||
if payload.other_inst_id is not None:
|
||||
organization.openalex_institution_id = payload.other_inst_id.strip() or None
|
||||
if payload.selected_openalex_institution_ids is not None:
|
||||
_replace_organization_institutions(
|
||||
session,
|
||||
organization,
|
||||
payload.selected_openalex_institution_ids,
|
||||
)
|
||||
elif payload.other_inst_id is not None:
|
||||
_replace_organization_institutions(
|
||||
session,
|
||||
organization,
|
||||
[payload.other_inst_id] if payload.other_inst_id.strip() else [],
|
||||
)
|
||||
if payload.deleted is not None:
|
||||
if payload.deleted and not organization.deleted:
|
||||
_ensure_not_current_organization(session, access_token, organization.id)
|
||||
_deactivate_organization_accounts(session, organization.id)
|
||||
organization.deleted = payload.deleted
|
||||
|
||||
@@ -185,7 +339,113 @@ def update_organization(
|
||||
session.commit()
|
||||
session.refresh(organization)
|
||||
counts = _member_counts(session, [organization.id])
|
||||
return _to_profile(organization, counts.get(organization.id, 0))
|
||||
institution_ids = _institution_data(session, [organization.id])
|
||||
return _to_profile(
|
||||
organization,
|
||||
counts.get(organization.id, 0),
|
||||
institution_ids[organization.id],
|
||||
)
|
||||
|
||||
|
||||
async def get_institution_associations(
|
||||
access_token: AccessTokenMetadata,
|
||||
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 []
|
||||
|
||||
response = await elasticsearch.search(
|
||||
index=ESIndex.OPENALEX_INSTITUTIONS,
|
||||
query={
|
||||
"terms": {
|
||||
"id": [
|
||||
f"https://openalex.org/{institution_id}"
|
||||
for institution_id in clean_ids
|
||||
]
|
||||
}
|
||||
},
|
||||
source=["id", "display_name", "associated_institutions"],
|
||||
size=len(clean_ids),
|
||||
)
|
||||
sources_by_id: dict[str, dict] = {}
|
||||
for hit in response.get("hits", {}).get("hits", []):
|
||||
source = hit.get("_source") or {}
|
||||
raw_id = source.get("id")
|
||||
if isinstance(raw_id, str):
|
||||
sources_by_id[_normalize_institution_id(raw_id)] = source
|
||||
|
||||
missing_id = next(
|
||||
(
|
||||
institution_id
|
||||
for institution_id in clean_ids
|
||||
if institution_id not in sources_by_id
|
||||
),
|
||||
None,
|
||||
)
|
||||
if missing_id is not None:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND,
|
||||
detail=f"OpenAlex institution {missing_id} not found.",
|
||||
)
|
||||
|
||||
results: list[InstitutionAssociationsResponse] = []
|
||||
for clean_id in clean_ids:
|
||||
source = sources_by_id[clean_id]
|
||||
display_name = source.get("display_name")
|
||||
if not isinstance(display_name, str) or not display_name.strip():
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_502_BAD_GATEWAY,
|
||||
detail=f"OpenAlex institution {clean_id} has no display name.",
|
||||
)
|
||||
|
||||
associations_by_id: dict[str, InstitutionAssociation] = {}
|
||||
for association in source.get("associated_institutions") or []:
|
||||
if not isinstance(association, dict):
|
||||
continue
|
||||
relationship = str(association.get("relationship") or "").lower()
|
||||
if relationship not in KNOWN_ASSOCIATION_TYPES:
|
||||
logger.warning(
|
||||
"Ignoring unknown OpenAlex institution relationship %r for %s",
|
||||
relationship,
|
||||
clean_id,
|
||||
)
|
||||
continue
|
||||
if relationship not in {"child", "related"}:
|
||||
continue
|
||||
raw_association_id = association.get("id")
|
||||
association_name = association.get("display_name")
|
||||
if not isinstance(raw_association_id, str) or not isinstance(
|
||||
association_name, str
|
||||
):
|
||||
continue
|
||||
associated_id = _normalize_institution_id(raw_association_id)
|
||||
candidate = InstitutionAssociation(
|
||||
id=associated_id,
|
||||
display_name=association_name,
|
||||
relationship=relationship,
|
||||
)
|
||||
existing = associations_by_id.get(associated_id)
|
||||
if existing is None or (
|
||||
existing.relationship == "related" and relationship == "child"
|
||||
):
|
||||
associations_by_id[associated_id] = candidate
|
||||
|
||||
results.append(
|
||||
InstitutionAssociationsResponse(
|
||||
id=clean_id,
|
||||
display_name=display_name,
|
||||
associated_institutions=list(associations_by_id.values()),
|
||||
)
|
||||
)
|
||||
return results
|
||||
|
||||
|
||||
def delete_organization(
|
||||
@@ -196,6 +456,7 @@ def delete_organization(
|
||||
_require_super_admin(access_token)
|
||||
organization = _get_organization_or_404(session, organization_id)
|
||||
if not organization.deleted:
|
||||
_ensure_not_current_organization(session, access_token, organization.id)
|
||||
_deactivate_organization_accounts(session, organization.id)
|
||||
organization.deleted = True
|
||||
session.add(organization)
|
||||
|
||||
@@ -1,10 +1,16 @@
|
||||
import asyncio
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
from fastapi import HTTPException
|
||||
from sqlmodel import Session, SQLModel, create_engine
|
||||
from sqlmodel import Session, SQLModel, create_engine, select
|
||||
|
||||
from inse.auth.model import Account, Organization, UserRole
|
||||
from inse.auth.model import (
|
||||
Account,
|
||||
Organization,
|
||||
OrganizationInstitution,
|
||||
UserRole,
|
||||
)
|
||||
from inse.organization_management import service
|
||||
from inse.organization_management.model import (
|
||||
CreateOrganizationRequest,
|
||||
@@ -22,10 +28,11 @@ def session():
|
||||
yield database_session
|
||||
|
||||
|
||||
def token(role: UserRole, organization_id):
|
||||
def token(role: UserRole, organization_id, real_account_id=None):
|
||||
return SimpleNamespace(
|
||||
effective_role=role,
|
||||
effective_organization_id=organization_id,
|
||||
real_account_id=real_account_id,
|
||||
)
|
||||
|
||||
|
||||
@@ -105,8 +112,115 @@ def test_superadmin_can_create_update_and_soft_delete(session):
|
||||
assert session.get(Organization, created.id).deleted is True
|
||||
|
||||
|
||||
def test_organization_stores_ordered_selected_institution_ids(session):
|
||||
scope = Organization(name="Scope")
|
||||
session.add(scope)
|
||||
session.commit()
|
||||
|
||||
created = service.create_organization(
|
||||
session,
|
||||
token(UserRole.SUPER_ADMIN, scope.id),
|
||||
CreateOrganizationRequest(
|
||||
name="Institution list",
|
||||
selected_openalex_institution_ids=[
|
||||
"https://openalex.org/I123",
|
||||
"I456",
|
||||
"I123",
|
||||
],
|
||||
),
|
||||
)
|
||||
|
||||
assert created.selected_openalex_institution_ids == ["I123", "I456"]
|
||||
assert created.other_inst_id == "I123"
|
||||
assert session.get(Organization, created.id).openalex_institution_id == "I123"
|
||||
rows = session.exec(
|
||||
select(OrganizationInstitution)
|
||||
.where(OrganizationInstitution.organization_id == created.id)
|
||||
.order_by(OrganizationInstitution.position)
|
||||
).all()
|
||||
assert [row.openalex_institution_id for row in rows] == ["I123", "I456"]
|
||||
|
||||
|
||||
def test_empty_institution_list_clears_legacy_primary_institution(session):
|
||||
organization = Organization(name="Organization", openalex_institution_id="I123")
|
||||
session.add(organization)
|
||||
session.commit()
|
||||
|
||||
updated = service.update_organization(
|
||||
session,
|
||||
token(UserRole.SUPER_ADMIN, organization.id),
|
||||
organization.id,
|
||||
UpdateOrganizationRequest(selected_openalex_institution_ids=[]),
|
||||
)
|
||||
|
||||
assert updated.selected_openalex_institution_ids == []
|
||||
assert updated.other_inst_id is None
|
||||
assert session.get(Organization, organization.id).openalex_institution_id is None
|
||||
|
||||
|
||||
def test_association_expansion_adds_only_child_and_related_with_child_priority(
|
||||
monkeypatch,
|
||||
):
|
||||
async def fake_search(**kwargs):
|
||||
return {
|
||||
"hits": {
|
||||
"hits": [
|
||||
{
|
||||
"_source": {
|
||||
"id": "https://openalex.org/I100",
|
||||
"display_name": "Selected institution",
|
||||
"associated_institutions": [
|
||||
{
|
||||
"id": "https://openalex.org/I200",
|
||||
"display_name": "Duplicate",
|
||||
"relationship": "related",
|
||||
},
|
||||
{
|
||||
"id": "https://openalex.org/I200",
|
||||
"display_name": "Duplicate",
|
||||
"relationship": "child",
|
||||
},
|
||||
{
|
||||
"id": "https://openalex.org/I300",
|
||||
"display_name": "Related",
|
||||
"relationship": "related",
|
||||
},
|
||||
{
|
||||
"id": "https://openalex.org/I400",
|
||||
"display_name": "Parent",
|
||||
"relationship": "parent",
|
||||
},
|
||||
{
|
||||
"id": "https://openalex.org/I500",
|
||||
"display_name": "Successor",
|
||||
"relationship": "successor",
|
||||
},
|
||||
],
|
||||
},
|
||||
}
|
||||
],
|
||||
},
|
||||
}
|
||||
|
||||
monkeypatch.setattr(service.elasticsearch, "search", fake_search)
|
||||
|
||||
result = asyncio.run(
|
||||
service.get_institution_associations(
|
||||
token(UserRole.SUPER_ADMIN, None), ["https://openalex.org/I100"]
|
||||
)
|
||||
)
|
||||
|
||||
assert result[0].id == "I100"
|
||||
assert [
|
||||
(association.id, association.relationship)
|
||||
for association in result[0].associated_institutions
|
||||
] == [("I200", "child"), ("I300", "related")]
|
||||
|
||||
|
||||
def test_deleting_organization_deactivates_all_its_accounts(session):
|
||||
admin_scope = Organization(name="Admin scope for delete")
|
||||
organization = Organization(name="Organization to delete")
|
||||
session.add(admin_scope)
|
||||
session.add(organization)
|
||||
session.flush()
|
||||
active_account = Account(
|
||||
@@ -129,7 +243,7 @@ def test_deleting_organization_deactivates_all_its_accounts(session):
|
||||
session.commit()
|
||||
|
||||
service.delete_organization(
|
||||
session, token(UserRole.SUPER_ADMIN, organization.id), organization.id
|
||||
session, token(UserRole.SUPER_ADMIN, admin_scope.id), organization.id
|
||||
)
|
||||
|
||||
session.refresh(active_account)
|
||||
@@ -141,7 +255,9 @@ def test_deleting_organization_deactivates_all_its_accounts(session):
|
||||
|
||||
|
||||
def test_marking_organization_deleted_deactivates_its_accounts(session):
|
||||
admin_scope = Organization(name="Admin scope for update")
|
||||
organization = Organization(name="Organization to update")
|
||||
session.add(admin_scope)
|
||||
session.add(organization)
|
||||
session.flush()
|
||||
account = Account(
|
||||
@@ -155,7 +271,7 @@ def test_marking_organization_deleted_deactivates_its_accounts(session):
|
||||
|
||||
service.update_organization(
|
||||
session,
|
||||
token(UserRole.SUPER_ADMIN, organization.id),
|
||||
token(UserRole.SUPER_ADMIN, admin_scope.id),
|
||||
organization.id,
|
||||
UpdateOrganizationRequest(deleted=True),
|
||||
)
|
||||
@@ -165,6 +281,61 @@ def test_marking_organization_deleted_deactivates_its_accounts(session):
|
||||
assert account.epoch == 1
|
||||
|
||||
|
||||
@pytest.mark.parametrize("delete_via_update", [False, True])
|
||||
def test_current_organization_cannot_be_deleted(session, delete_via_update):
|
||||
organization = Organization(name="Current organization")
|
||||
session.add(organization)
|
||||
session.commit()
|
||||
access_token = token(UserRole.SUPER_ADMIN, organization.id)
|
||||
|
||||
with pytest.raises(HTTPException) as error:
|
||||
if delete_via_update:
|
||||
service.update_organization(
|
||||
session,
|
||||
access_token,
|
||||
organization.id,
|
||||
UpdateOrganizationRequest(deleted=True),
|
||||
)
|
||||
else:
|
||||
service.delete_organization(session, access_token, organization.id)
|
||||
|
||||
assert error.value.status_code == 409
|
||||
assert session.get(Organization, organization.id).deleted is False
|
||||
|
||||
|
||||
def test_real_account_organization_cannot_be_deleted_while_impersonating(session):
|
||||
real_organization = Organization(name="Real organization")
|
||||
effective_organization = Organization(name="Effective organization")
|
||||
session.add(real_organization)
|
||||
session.add(effective_organization)
|
||||
session.flush()
|
||||
real_account = Account(
|
||||
email="real-superadmin@example.org",
|
||||
name="Real superadmin",
|
||||
password_hash="hash",
|
||||
organization_id=real_organization.id,
|
||||
roles=[UserRole.SUPER_ADMIN],
|
||||
)
|
||||
session.add(real_account)
|
||||
session.commit()
|
||||
|
||||
access_token = token(
|
||||
UserRole.SUPER_ADMIN,
|
||||
effective_organization.id,
|
||||
real_account.id,
|
||||
)
|
||||
with pytest.raises(HTTPException) as error:
|
||||
service.delete_organization(
|
||||
session,
|
||||
access_token,
|
||||
real_organization.id,
|
||||
)
|
||||
|
||||
assert error.value.status_code == 409
|
||||
assert session.get(Organization, real_organization.id).deleted is False
|
||||
assert session.get(Account, real_account.id).activated is True
|
||||
|
||||
|
||||
@pytest.mark.parametrize("role", [UserRole.ADMIN, UserRole.MANAGER, UserRole.USER])
|
||||
def test_only_superadmin_can_create_organizations(session, role):
|
||||
organization = Organization(name="Scope")
|
||||
|
||||
@@ -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"]}})
|
||||
|
||||
@@ -741,6 +741,8 @@ async def _build_eu_cordis_search_query(
|
||||
title: str | None = None,
|
||||
funding_start_years: list[str] | None = None,
|
||||
funding_end_years: list[str] | None = None,
|
||||
active_from_year: int | None = None,
|
||||
active_to_year: int | None = None,
|
||||
countries: list[str] | None = None,
|
||||
framework_programmes: list[str] | None = None,
|
||||
funding_schemes: list[str] | None = None,
|
||||
@@ -876,6 +878,18 @@ async def _build_eu_cordis_search_query(
|
||||
if funding_end_years:
|
||||
must_clauses.append(_eu_year_filters("endDate", funding_end_years))
|
||||
|
||||
# Period-overlap filter: a project was active in the selected interval when
|
||||
# it started no later than the interval end and ended no earlier than the
|
||||
# interval start. This is intentionally separate from exact-year filters.
|
||||
if active_to_year is not None:
|
||||
must_clauses.append(
|
||||
{"range": {"startDate": {"lte": f"{active_to_year}-12-31"}}}
|
||||
)
|
||||
if active_from_year is not None:
|
||||
must_clauses.append(
|
||||
{"range": {"endDate": {"gte": f"{active_from_year}-01-01"}}}
|
||||
)
|
||||
|
||||
# === Project core filters ===
|
||||
if framework_programmes:
|
||||
must_clauses.append({"terms": {"frameworkProgramme": framework_programmes}})
|
||||
@@ -937,6 +951,8 @@ async def search_eu_cordis_projects(
|
||||
title: str | None = None,
|
||||
funding_start_years: list[str] | None = None,
|
||||
funding_end_years: list[str] | None = None,
|
||||
active_from_year: int | None = None,
|
||||
active_to_year: int | None = None,
|
||||
countries: list[str] | None = None,
|
||||
framework_programmes: list[str] | None = None,
|
||||
funding_schemes: list[str] | None = None,
|
||||
@@ -965,6 +981,8 @@ async def search_eu_cordis_projects(
|
||||
title=title,
|
||||
funding_start_years=funding_start_years,
|
||||
funding_end_years=funding_end_years,
|
||||
active_from_year=active_from_year,
|
||||
active_to_year=active_to_year,
|
||||
countries=countries,
|
||||
framework_programmes=framework_programmes,
|
||||
funding_schemes=funding_schemes,
|
||||
|
||||
@@ -369,6 +369,8 @@ async def search_dfg_projects(
|
||||
sort_direction: str = "asc",
|
||||
fuzzy: bool = False,
|
||||
skip_enrichment: bool = False,
|
||||
active_from_year: int | None = None,
|
||||
active_to_year: int | None = None,
|
||||
) -> DfgProjectPage:
|
||||
"""Searches for DFG projects based on the provided filtering and sorting criteria.
|
||||
|
||||
@@ -489,6 +491,11 @@ async def search_dfg_projects(
|
||||
if funding_end_years:
|
||||
must_clauses.append({"terms": {"funding_end": funding_end_years}})
|
||||
|
||||
if active_to_year is not None:
|
||||
must_clauses.append({"range": {"funding_start": {"lte": str(active_to_year)}}})
|
||||
if active_from_year is not None:
|
||||
must_clauses.append({"range": {"funding_end": {"gte": str(active_from_year)}}})
|
||||
|
||||
if names:
|
||||
name_must_clauses = []
|
||||
for full_name in names:
|
||||
@@ -600,7 +607,6 @@ async def search_dfg_projects(
|
||||
body["sort"] = [sort_config]
|
||||
# print(f"Executing DFG project search with body: {json.dumps(body, indent=2)}")
|
||||
# === Execute Search ===
|
||||
print(f"Executing DFG project search with body: {json.dumps(body, indent=2)}")
|
||||
response = await elasticsearch.search(
|
||||
index=ESIndex.DFG_PROJECTS,
|
||||
body=body,
|
||||
@@ -612,6 +618,9 @@ async def search_dfg_projects(
|
||||
if skip_enrichment:
|
||||
return _complete_response_to_dfg_project_page(response, page, size)
|
||||
|
||||
if not hits:
|
||||
return _complete_response_to_dfg_project_page(response, page, size)
|
||||
|
||||
project_ids = [hit["_source"]["id"] for hit in hits]
|
||||
topic_lookup = await get_openalex_topics_for_dfg_projects(project_ids=project_ids)
|
||||
|
||||
@@ -858,6 +867,8 @@ async def search_bund_projects_with_filters(
|
||||
sort_direction: str = "asc",
|
||||
fuzzy: bool = False,
|
||||
skip_topic_enrichment: bool = False,
|
||||
active_from_year: int | None = None,
|
||||
active_to_year: int | None = None,
|
||||
) -> BundProjectPage:
|
||||
"""
|
||||
Main search function for BUND projects, analogous to the DFG search.
|
||||
@@ -999,6 +1010,15 @@ async def search_bund_projects_with_filters(
|
||||
if funding_end_years:
|
||||
must_clauses.append(_bund_year_filters("funding_end", funding_end_years))
|
||||
|
||||
if active_to_year is not None:
|
||||
must_clauses.append(
|
||||
{"range": {"funding_start": {"lte": f"31.12.{active_to_year}"}}}
|
||||
)
|
||||
if active_from_year is not None:
|
||||
must_clauses.append(
|
||||
{"range": {"funding_end": {"gte": f"01.01.{active_from_year}"}}}
|
||||
)
|
||||
|
||||
body["query"] = {"bool": {"must": must_clauses}} if must_clauses else {"match_all": {}}
|
||||
# === Sorting ===
|
||||
sort_by = sort_by.strip().lower()
|
||||
|
||||
@@ -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,
|
||||
)
|
||||
)
|
||||
|
||||
@@ -188,6 +188,9 @@ async def get_dfg_projects(
|
||||
sort_direction: str = "asc",
|
||||
fuzzy: bool = False,
|
||||
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, "
|
||||
@@ -249,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,
|
||||
@@ -270,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,
|
||||
@@ -284,6 +287,8 @@ async def get_dfg_projects(
|
||||
sort_direction=sort_direction,
|
||||
fuzzy=fuzzy,
|
||||
skip_enrichment=skip_enrichment,
|
||||
active_from_year=active_from_year,
|
||||
active_to_year=active_to_year,
|
||||
)
|
||||
|
||||
async def get_institution_cordis_eu_projects_funding_over_time(
|
||||
@@ -459,8 +464,11 @@ async def search_bund_projects_with_filters(
|
||||
sort_by: str = "title",
|
||||
sort_direction: str = "asc",
|
||||
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(
|
||||
@@ -494,7 +502,9 @@ async def search_bund_projects_with_filters(
|
||||
size=size,
|
||||
sort_by=sort_by,
|
||||
sort_direction=sort_direction,
|
||||
fuzzy=fuzzy
|
||||
fuzzy=fuzzy,
|
||||
active_from_year=active_from_year,
|
||||
active_to_year=active_to_year,
|
||||
)
|
||||
|
||||
def _calculate_funding_over_time(
|
||||
@@ -656,6 +666,8 @@ async def search_eu_cordis_projects(
|
||||
title: str | None = None,
|
||||
funding_start_years: list[str] | None = None,
|
||||
funding_end_years: list[str] | None = None,
|
||||
active_from_year: int | None = None,
|
||||
active_to_year: int | None = None,
|
||||
countries: list[str] | None = None,
|
||||
framework_programmes: list[str] | None = None,
|
||||
funding_schemes: list[str] | None = None,
|
||||
@@ -716,6 +728,8 @@ async def search_eu_cordis_projects(
|
||||
title=title,
|
||||
funding_start_years=funding_start_years,
|
||||
funding_end_years=funding_end_years,
|
||||
active_from_year=active_from_year,
|
||||
active_to_year=active_to_year,
|
||||
countries=countries,
|
||||
framework_programmes=framework_programmes,
|
||||
funding_schemes=funding_schemes,
|
||||
|
||||
@@ -2,6 +2,21 @@ import pytest
|
||||
from inse.projects import eu_cordis_projects_client as eu_cordis_search_client
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_active_period_filter_matches_projects_overlapping_interval():
|
||||
query, _, _ = await eu_cordis_search_client._build_eu_cordis_search_query(
|
||||
active_from_year=2022,
|
||||
active_to_year=2026,
|
||||
)
|
||||
|
||||
assert {"range": {"startDate": {"lte": "2026-12-31"}}} in query["bool"][
|
||||
"must"
|
||||
]
|
||||
assert {"range": {"endDate": {"gte": "2022-01-01"}}} in query["bool"][
|
||||
"must"
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_search_eu_cordis_projects_by_title():
|
||||
"""Test searching EU CORDIS projects by title."""
|
||||
@@ -362,4 +377,4 @@ async def test_search_eu_cordis_projects_with_fuzzy_topic_search():
|
||||
# Note: This may return 0 results if the topic ID doesn't exist
|
||||
# The important thing is that it doesn't crash
|
||||
assert isinstance(res.total, int)
|
||||
assert isinstance(res.elements, list)
|
||||
assert isinstance(res.elements, list)
|
||||
|
||||
@@ -1,4 +1,7 @@
|
||||
from unittest.mock import AsyncMock, patch
|
||||
|
||||
import pytest
|
||||
|
||||
from inse.projects import projects_search_client
|
||||
|
||||
|
||||
@@ -20,6 +23,33 @@ async def test_search_dfg_projects():
|
||||
for name in element.names
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_search_dfg_projects_returns_empty_page_without_enrichment_crash():
|
||||
response = {
|
||||
"hits": {
|
||||
"total": {"value": 0},
|
||||
"hits": [],
|
||||
}
|
||||
}
|
||||
with patch(
|
||||
"inse.projects.projects_search_client.elasticsearch.search",
|
||||
new=AsyncMock(return_value=response),
|
||||
) as mocked_search:
|
||||
result = await projects_search_client.search_dfg_projects(
|
||||
page=0,
|
||||
size=1,
|
||||
funding_start_years=["2022"],
|
||||
funding_end_years=["2026"],
|
||||
)
|
||||
|
||||
assert result.total == 0
|
||||
assert result.elements == []
|
||||
query = mocked_search.await_args.kwargs["body"]["query"]
|
||||
assert {"terms": {"funding_start": ["2022"]}} in query["bool"]["must"]
|
||||
assert {"terms": {"funding_end": ["2026"]}} in query["bool"]["must"]
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_get_dfg_project_by_id():
|
||||
# Get by ID of the project we found or a known one
|
||||
|
||||
Generated
+88
@@ -712,6 +712,53 @@ wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/df/b2/87e62e8c3e2f4b32e5fe99e0b86d576da1312593b39f47d8ceef365e95ed/packaging-26.2-py3-none-any.whl", hash = "sha256:5fc45236b9446107ff2415ce77c807cee2862cb6fac22b8a73826d0693b0980e", size = 100195, upload-time = "2026-04-24T20:15:22.081Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "pandas"
|
||||
version = "2.3.3"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
dependencies = [
|
||||
{ name = "numpy" },
|
||||
{ name = "python-dateutil" },
|
||||
{ name = "pytz" },
|
||||
{ name = "tzdata" },
|
||||
]
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/33/01/d40b85317f86cf08d853a4f495195c73815fdf205eef3993821720274518/pandas-2.3.3.tar.gz", hash = "sha256:e05e1af93b977f7eafa636d043f9f94c7ee3ac81af99c13508215942e64c993b", size = 4495223, upload-time = "2025-09-29T23:34:51.853Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/9c/fb/231d89e8637c808b997d172b18e9d4a4bc7bf31296196c260526055d1ea0/pandas-2.3.3-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:6d21f6d74eb1725c2efaa71a2bfc661a0689579b58e9c0ca58a739ff0b002b53", size = 11597846, upload-time = "2025-09-29T23:19:48.856Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/5c/bd/bf8064d9cfa214294356c2d6702b716d3cf3bb24be59287a6a21e24cae6b/pandas-2.3.3-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:3fd2f887589c7aa868e02632612ba39acb0b8948faf5cc58f0850e165bd46f35", size = 10729618, upload-time = "2025-09-29T23:39:08.659Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/57/56/cf2dbe1a3f5271370669475ead12ce77c61726ffd19a35546e31aa8edf4e/pandas-2.3.3-cp312-cp312-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:ecaf1e12bdc03c86ad4a7ea848d66c685cb6851d807a26aa245ca3d2017a1908", size = 11737212, upload-time = "2025-09-29T23:19:59.765Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/e5/63/cd7d615331b328e287d8233ba9fdf191a9c2d11b6af0c7a59cfcec23de68/pandas-2.3.3-cp312-cp312-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:b3d11d2fda7eb164ef27ffc14b4fcab16a80e1ce67e9f57e19ec0afaf715ba89", size = 12362693, upload-time = "2025-09-29T23:20:14.098Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/a6/de/8b1895b107277d52f2b42d3a6806e69cfef0d5cf1d0ba343470b9d8e0a04/pandas-2.3.3-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:a68e15f780eddf2b07d242e17a04aa187a7ee12b40b930bfdd78070556550e98", size = 12771002, upload-time = "2025-09-29T23:20:26.76Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/87/21/84072af3187a677c5893b170ba2c8fbe450a6ff911234916da889b698220/pandas-2.3.3-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:371a4ab48e950033bcf52b6527eccb564f52dc826c02afd9a1bc0ab731bba084", size = 13450971, upload-time = "2025-09-29T23:20:41.344Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/86/41/585a168330ff063014880a80d744219dbf1dd7a1c706e75ab3425a987384/pandas-2.3.3-cp312-cp312-win_amd64.whl", hash = "sha256:a16dcec078a01eeef8ee61bf64074b4e524a2a3f4b3be9326420cabe59c4778b", size = 10992722, upload-time = "2025-09-29T23:20:54.139Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/cd/4b/18b035ee18f97c1040d94debd8f2e737000ad70ccc8f5513f4eefad75f4b/pandas-2.3.3-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:56851a737e3470de7fa88e6131f41281ed440d29a9268dcbf0002da5ac366713", size = 11544671, upload-time = "2025-09-29T23:21:05.024Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/31/94/72fac03573102779920099bcac1c3b05975c2cb5f01eac609faf34bed1ca/pandas-2.3.3-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:bdcd9d1167f4885211e401b3036c0c8d9e274eee67ea8d0758a256d60704cfe8", size = 10680807, upload-time = "2025-09-29T23:21:15.979Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/16/87/9472cf4a487d848476865321de18cc8c920b8cab98453ab79dbbc98db63a/pandas-2.3.3-cp313-cp313-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:e32e7cc9af0f1cc15548288a51a3b681cc2a219faa838e995f7dc53dbab1062d", size = 11709872, upload-time = "2025-09-29T23:21:27.165Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/15/07/284f757f63f8a8d69ed4472bfd85122bd086e637bf4ed09de572d575a693/pandas-2.3.3-cp313-cp313-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:318d77e0e42a628c04dc56bcef4b40de67918f7041c2b061af1da41dcff670ac", size = 12306371, upload-time = "2025-09-29T23:21:40.532Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/33/81/a3afc88fca4aa925804a27d2676d22dcd2031c2ebe08aabd0ae55b9ff282/pandas-2.3.3-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:4e0a175408804d566144e170d0476b15d78458795bb18f1304fb94160cabf40c", size = 12765333, upload-time = "2025-09-29T23:21:55.77Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/8d/0f/b4d4ae743a83742f1153464cf1a8ecfafc3ac59722a0b5c8602310cb7158/pandas-2.3.3-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:93c2d9ab0fc11822b5eece72ec9587e172f63cff87c00b062f6e37448ced4493", size = 13418120, upload-time = "2025-09-29T23:22:10.109Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/4f/c7/e54682c96a895d0c808453269e0b5928a07a127a15704fedb643e9b0a4c8/pandas-2.3.3-cp313-cp313-win_amd64.whl", hash = "sha256:f8bfc0e12dc78f777f323f55c58649591b2cd0c43534e8355c51d3fede5f4dee", size = 10993991, upload-time = "2025-09-29T23:25:04.889Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/f9/ca/3f8d4f49740799189e1395812f3bf23b5e8fc7c190827d55a610da72ce55/pandas-2.3.3-cp313-cp313t-macosx_10_13_x86_64.whl", hash = "sha256:75ea25f9529fdec2d2e93a42c523962261e567d250b0013b16210e1d40d7c2e5", size = 12048227, upload-time = "2025-09-29T23:22:24.343Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/0e/5a/f43efec3e8c0cc92c4663ccad372dbdff72b60bdb56b2749f04aa1d07d7e/pandas-2.3.3-cp313-cp313t-macosx_11_0_arm64.whl", hash = "sha256:74ecdf1d301e812db96a465a525952f4dde225fdb6d8e5a521d47e1f42041e21", size = 11411056, upload-time = "2025-09-29T23:22:37.762Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/46/b1/85331edfc591208c9d1a63a06baa67b21d332e63b7a591a5ba42a10bb507/pandas-2.3.3-cp313-cp313t-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:6435cb949cb34ec11cc9860246ccb2fdc9ecd742c12d3304989017d53f039a78", size = 11645189, upload-time = "2025-09-29T23:22:51.688Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/44/23/78d645adc35d94d1ac4f2a3c4112ab6f5b8999f4898b8cdf01252f8df4a9/pandas-2.3.3-cp313-cp313t-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:900f47d8f20860de523a1ac881c4c36d65efcb2eb850e6948140fa781736e110", size = 12121912, upload-time = "2025-09-29T23:23:05.042Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/53/da/d10013df5e6aaef6b425aa0c32e1fc1f3e431e4bcabd420517dceadce354/pandas-2.3.3-cp313-cp313t-musllinux_1_2_aarch64.whl", hash = "sha256:a45c765238e2ed7d7c608fc5bc4a6f88b642f2f01e70c0c23d2224dd21829d86", size = 12712160, upload-time = "2025-09-29T23:23:28.57Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/bd/17/e756653095a083d8a37cbd816cb87148debcfcd920129b25f99dd8d04271/pandas-2.3.3-cp313-cp313t-musllinux_1_2_x86_64.whl", hash = "sha256:c4fc4c21971a1a9f4bdb4c73978c7f7256caa3e62b323f70d6cb80db583350bc", size = 13199233, upload-time = "2025-09-29T23:24:24.876Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/04/fd/74903979833db8390b73b3a8a7d30d146d710bd32703724dd9083950386f/pandas-2.3.3-cp314-cp314-macosx_10_13_x86_64.whl", hash = "sha256:ee15f284898e7b246df8087fc82b87b01686f98ee67d85a17b7ab44143a3a9a0", size = 11540635, upload-time = "2025-09-29T23:25:52.486Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/21/00/266d6b357ad5e6d3ad55093a7e8efc7dd245f5a842b584db9f30b0f0a287/pandas-2.3.3-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:1611aedd912e1ff81ff41c745822980c49ce4a7907537be8692c8dbc31924593", size = 10759079, upload-time = "2025-09-29T23:26:33.204Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/ca/05/d01ef80a7a3a12b2f8bbf16daba1e17c98a2f039cbc8e2f77a2c5a63d382/pandas-2.3.3-cp314-cp314-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:6d2cefc361461662ac48810cb14365a365ce864afe85ef1f447ff5a1e99ea81c", size = 11814049, upload-time = "2025-09-29T23:27:15.384Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/15/b2/0e62f78c0c5ba7e3d2c5945a82456f4fac76c480940f805e0b97fcbc2f65/pandas-2.3.3-cp314-cp314-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:ee67acbbf05014ea6c763beb097e03cd629961c8a632075eeb34247120abcb4b", size = 12332638, upload-time = "2025-09-29T23:27:51.625Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/c5/33/dd70400631b62b9b29c3c93d2feee1d0964dc2bae2e5ad7a6c73a7f25325/pandas-2.3.3-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:c46467899aaa4da076d5abc11084634e2d197e9460643dd455ac3db5856b24d6", size = 12886834, upload-time = "2025-09-29T23:28:21.289Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/d3/18/b5d48f55821228d0d2692b34fd5034bb185e854bdb592e9c640f6290e012/pandas-2.3.3-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:6253c72c6a1d990a410bc7de641d34053364ef8bcd3126f7e7450125887dffe3", size = 13409925, upload-time = "2025-09-29T23:28:58.261Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/a6/3d/124ac75fcd0ecc09b8fdccb0246ef65e35b012030defb0e0eba2cbbbe948/pandas-2.3.3-cp314-cp314-win_amd64.whl", hash = "sha256:1b07204a219b3b7350abaae088f451860223a52cfb8a6c53358e7948735158e5", size = 11109071, upload-time = "2025-09-29T23:32:27.484Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/89/9c/0e21c895c38a157e0faa1fb64587a9226d6dd46452cac4532d80c3c4a244/pandas-2.3.3-cp314-cp314t-macosx_10_13_x86_64.whl", hash = "sha256:2462b1a365b6109d275250baaae7b760fd25c726aaca0054649286bcfbb3e8ec", size = 12048504, upload-time = "2025-09-29T23:29:31.47Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/d7/82/b69a1c95df796858777b68fbe6a81d37443a33319761d7c652ce77797475/pandas-2.3.3-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:0242fe9a49aa8b4d78a4fa03acb397a58833ef6199e9aa40a95f027bb3a1b6e7", size = 11410702, upload-time = "2025-09-29T23:29:54.591Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/f9/88/702bde3ba0a94b8c73a0181e05144b10f13f29ebfc2150c3a79062a8195d/pandas-2.3.3-cp314-cp314t-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:a21d830e78df0a515db2b3d2f5570610f5e6bd2e27749770e8bb7b524b89b450", size = 11634535, upload-time = "2025-09-29T23:30:21.003Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/a4/1e/1bac1a839d12e6a82ec6cb40cda2edde64a2013a66963293696bbf31fbbb/pandas-2.3.3-cp314-cp314t-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:2e3ebdb170b5ef78f19bfb71b0dc5dc58775032361fa188e814959b74d726dd5", size = 12121582, upload-time = "2025-09-29T23:30:43.391Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/44/91/483de934193e12a3b1d6ae7c8645d083ff88dec75f46e827562f1e4b4da6/pandas-2.3.3-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:d051c0e065b94b7a3cea50eb1ec32e912cd96dba41647eb24104b6c6c14c5788", size = 12699963, upload-time = "2025-09-29T23:31:10.009Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/70/44/5191d2e4026f86a2a109053e194d3ba7a31a2d10a9c2348368c63ed4e85a/pandas-2.3.3-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:3869faf4bd07b3b66a9f462417d0ca3a9df29a9f6abd5d0d0dbab15dac7abe87", size = 13202175, upload-time = "2025-09-29T23:31:59.173Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "pluggy"
|
||||
version = "1.6.0"
|
||||
@@ -823,6 +870,18 @@ wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/f0/d7/a812a0bd0f5160823e647524488cc9734f93782f2c273b8f77e8afc60a37/pytest-8.1.2-py3-none-any.whl", hash = "sha256:6c06dc309ff46a05721e6fd48e492a775ed8165d2ecdf57f156a80c7e95bb142", size = 337456, upload-time = "2024-04-26T18:05:15.452Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "python-dateutil"
|
||||
version = "2.9.0.post0"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
dependencies = [
|
||||
{ name = "six" },
|
||||
]
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/66/c0/0c8b6ad9f17a802ee498c46e004a0eb49bc148f2fd230864601a86dcf6db/python-dateutil-2.9.0.post0.tar.gz", hash = "sha256:37dd54208da7e1cd875388217d5e00ebd4179249f90fb72437e91a35459a0ad3", size = 342432, upload-time = "2024-03-01T18:36:20.211Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/ec/57/56b9bcc3c9c6a792fcbaf139543cee77261f3651ca9da0c93f5c1221264b/python_dateutil-2.9.0.post0-py2.py3-none-any.whl", hash = "sha256:a8b2bc7bffae282281c8140a97d3aa9c14da0b136dfe83f850eea9a5f7470427", size = 229892, upload-time = "2024-03-01T18:36:18.57Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "python-dotenv"
|
||||
version = "1.2.2"
|
||||
@@ -841,6 +900,15 @@ wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/8f/cb/769cfc37177252872a45a71f3fbdde9d51b471a3f3c14bfe95dde3407386/python_multipart-0.0.29-py3-none-any.whl", hash = "sha256:2ddcc971cef266225f54f552d8fa10bcfbb1f14446caec199060daac59ff2d69", size = 29640, upload-time = "2026-05-17T17:29:45.69Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "pytz"
|
||||
version = "2026.3.post1"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/fb/48/fb042503b6ca6cd271261dc559fd6432f7d8c713153e9ec5c591af4dfc1c/pytz-2026.3.post1.tar.gz", hash = "sha256:2211d3fcf9a797d3405cac96ac7f61d80e6a644f72a3309607282fe8a2010c5d", size = 319745, upload-time = "2026-07-25T15:12:07.385Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/0f/7b/39c34ca613b0b198cb866466651b26b045e2009864c5183c979a3b83f383/pytz-2026.3.post1-py2.py3-none-any.whl", hash = "sha256:dd95840dd199baea12d9cc096a1d452caa6596a1c1e4b5f3dbd1541855d5e815", size = 508283, upload-time = "2026-07-25T15:12:05.782Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "pyyaml"
|
||||
version = "6.0.3"
|
||||
@@ -1143,6 +1211,7 @@ dependencies = [
|
||||
{ name = "fastapi" },
|
||||
{ name = "httpx" },
|
||||
{ name = "openai" },
|
||||
{ name = "pandas" },
|
||||
{ name = "pydantic" },
|
||||
{ name = "pydantic-settings" },
|
||||
{ name = "pyjwt" },
|
||||
@@ -1165,6 +1234,7 @@ requires-dist = [
|
||||
{ name = "fastapi", specifier = "~=0.115.0" },
|
||||
{ name = "httpx", specifier = "~=0.27.0" },
|
||||
{ name = "openai", specifier = "~=2.41.0" },
|
||||
{ name = "pandas", specifier = "~=2.3.3" },
|
||||
{ name = "pydantic", specifier = "~=2.7.1" },
|
||||
{ name = "pydantic-settings", specifier = "~=2.2.1" },
|
||||
{ name = "pyjwt", specifier = "~=2.8.0" },
|
||||
@@ -1196,6 +1266,15 @@ wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/e0/f9/0595336914c5619e5f28a1fb793285925a8cd4b432c9da0a987836c7f822/shellingham-1.5.4-py2.py3-none-any.whl", hash = "sha256:7ecfff8f2fd72616f7481040475a65b2bf8af90a56c89140852d1120324e8686", size = 9755, upload-time = "2023-10-24T04:13:38.866Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "six"
|
||||
version = "1.17.0"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/94/e7/b2c673351809dca68a0e064b6af791aa332cf192da575fd474ed7d6f16a2/six-1.17.0.tar.gz", hash = "sha256:ff70335d468e7eb6ec65b95b99d3a2836546063f63acc5171de367e834932a81", size = 34031, upload-time = "2024-12-04T17:35:28.174Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/b7/ce/149a00dd41f10bc29e5921b496af8b574d8413afcd5e30dfa0ed46c2cc5e/six-1.17.0-py2.py3-none-any.whl", hash = "sha256:4721f391ed90541fddacab5acf947aa0d3dc7d27b2e1e8eda2be8970586c3274", size = 11050, upload-time = "2024-12-04T17:35:26.475Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "sniffio"
|
||||
version = "1.3.1"
|
||||
@@ -1441,6 +1520,15 @@ wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/18/67/36e9267722cc04a6b9f15c7f3441c2363321a3ea07da7ae0c0707beb2a9c/typing_extensions-4.15.0-py3-none-any.whl", hash = "sha256:f0fa19c6845758ab08074a0cfa8b7aecb71c999ca73d62883bc25cc018c4e548", size = 44614, upload-time = "2025-08-25T13:49:24.86Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tzdata"
|
||||
version = "2026.3"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/92/ff/5a28bdfd8c3ebec42564ac7d0e54ca3db65044a9314a97f9564fa7a1e926/tzdata-2026.3.tar.gz", hash = "sha256:4a1518b8993086a7982523e071643f3c0e5f213e75b21318e78bcabfff9d1415", size = 198674, upload-time = "2026-07-10T08:50:37.887Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/e5/6d/b53b99a9f2766d095985947a5782f1702cabb129a34f7a802d7197af832f/tzdata-2026.3-py2.py3-none-any.whl", hash = "sha256:dc096730c87af6cab1b171c9d532be840741ff5d459015e7f6947bd7d7e54931", size = 348168, upload-time = "2026-07-10T08:50:36.46Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "uvicorn"
|
||||
version = "0.29.0"
|
||||
|
||||
@@ -169,6 +169,8 @@ model/idTokenMetadata.ts
|
||||
model/inseAccountManagementModelOrganizationProfile.ts
|
||||
model/inseOrganizationManagementModelOrganizationProfile.ts
|
||||
model/institution.ts
|
||||
model/institutionAssociation.ts
|
||||
model/institutionAssociationsResponse.ts
|
||||
model/institutionFunderSummary.ts
|
||||
model/institutionGeo.ts
|
||||
model/institutionIds.ts
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
/**
|
||||
* Innovation Search Engine API
|
||||
*
|
||||
*
|
||||
*
|
||||
*
|
||||
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
|
||||
* https://openapi-generator.tech
|
||||
@@ -9,12 +9,18 @@
|
||||
*/
|
||||
/* tslint:disable:no-unused-variable member-ordering */
|
||||
|
||||
import { Inject, Injectable, Optional } from '@angular/core';
|
||||
import { HttpClient, HttpHeaders, HttpParams,
|
||||
HttpResponse, HttpEvent, HttpParameterCodec, HttpContext
|
||||
} from '@angular/common/http';
|
||||
import { CustomHttpParameterCodec } from '../encoder';
|
||||
import { Observable } from 'rxjs';
|
||||
import { Inject, Injectable, Optional } from '@angular/core';
|
||||
import {
|
||||
HttpClient,
|
||||
HttpHeaders,
|
||||
HttpParams,
|
||||
HttpResponse,
|
||||
HttpEvent,
|
||||
HttpParameterCodec,
|
||||
HttpContext,
|
||||
} from '@angular/common/http';
|
||||
import { CustomHttpParameterCodec } from '../encoder';
|
||||
import { Observable } from 'rxjs';
|
||||
|
||||
// @ts-ignore
|
||||
import { CreateOrganizationRequest } from '../model/createOrganizationRequest';
|
||||
@@ -23,292 +29,679 @@ import { HTTPValidationError } from '../model/hTTPValidationError';
|
||||
// @ts-ignore
|
||||
import { InseOrganizationManagementModelOrganizationProfile } from '../model/inseOrganizationManagementModelOrganizationProfile';
|
||||
// @ts-ignore
|
||||
import { InstitutionAssociationsResponse } from '../model/institutionAssociationsResponse';
|
||||
// @ts-ignore
|
||||
import { OrganizationPage } from '../model/organizationPage';
|
||||
// @ts-ignore
|
||||
import { UpdateOrganizationRequest } from '../model/updateOrganizationRequest';
|
||||
|
||||
// @ts-ignore
|
||||
import { BASE_PATH, COLLECTION_FORMATS } from '../variables';
|
||||
import { Configuration } from '../configuration';
|
||||
import { BASE_PATH, COLLECTION_FORMATS } from '../variables';
|
||||
import { Configuration } from '../configuration';
|
||||
import { BaseService } from '../api.base.service';
|
||||
|
||||
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root'
|
||||
providedIn: 'root',
|
||||
})
|
||||
export class OrganizationService extends BaseService {
|
||||
constructor(
|
||||
protected httpClient: HttpClient,
|
||||
@Optional() @Inject(BASE_PATH) basePath: string | string[],
|
||||
@Optional() configuration?: Configuration,
|
||||
) {
|
||||
super(basePath, configuration);
|
||||
}
|
||||
|
||||
constructor(protected httpClient: HttpClient, @Optional() @Inject(BASE_PATH) basePath: string|string[], @Optional() configuration?: Configuration) {
|
||||
super(basePath, configuration);
|
||||
/**
|
||||
* Create Organization
|
||||
* @endpoint post /api/organizations
|
||||
* @param createOrganizationRequest
|
||||
* @param secureFgpAcc
|
||||
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
|
||||
* @param reportProgress flag to report request and response progress.
|
||||
*/
|
||||
public createOrganisation(
|
||||
createOrganizationRequest: CreateOrganizationRequest,
|
||||
secureFgpAcc?: string,
|
||||
observe?: 'body',
|
||||
reportProgress?: boolean,
|
||||
options?: {
|
||||
httpHeaderAccept?: 'application/json';
|
||||
context?: HttpContext;
|
||||
transferCache?: boolean;
|
||||
},
|
||||
): Observable<InseOrganizationManagementModelOrganizationProfile>;
|
||||
public createOrganisation(
|
||||
createOrganizationRequest: CreateOrganizationRequest,
|
||||
secureFgpAcc?: string,
|
||||
observe?: 'response',
|
||||
reportProgress?: boolean,
|
||||
options?: {
|
||||
httpHeaderAccept?: 'application/json';
|
||||
context?: HttpContext;
|
||||
transferCache?: boolean;
|
||||
},
|
||||
): Observable<
|
||||
HttpResponse<InseOrganizationManagementModelOrganizationProfile>
|
||||
>;
|
||||
public createOrganisation(
|
||||
createOrganizationRequest: CreateOrganizationRequest,
|
||||
secureFgpAcc?: string,
|
||||
observe?: 'events',
|
||||
reportProgress?: boolean,
|
||||
options?: {
|
||||
httpHeaderAccept?: 'application/json';
|
||||
context?: HttpContext;
|
||||
transferCache?: boolean;
|
||||
},
|
||||
): Observable<HttpEvent<InseOrganizationManagementModelOrganizationProfile>>;
|
||||
public createOrganisation(
|
||||
createOrganizationRequest: CreateOrganizationRequest,
|
||||
secureFgpAcc?: string,
|
||||
observe: any = 'body',
|
||||
reportProgress: boolean = false,
|
||||
options?: {
|
||||
httpHeaderAccept?: 'application/json';
|
||||
context?: HttpContext;
|
||||
transferCache?: boolean;
|
||||
},
|
||||
): Observable<any> {
|
||||
if (
|
||||
createOrganizationRequest === null ||
|
||||
createOrganizationRequest === undefined
|
||||
) {
|
||||
throw new Error(
|
||||
'Required parameter createOrganizationRequest was null or undefined when calling createOrganisation.',
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create Organization
|
||||
* @endpoint post /api/organizations
|
||||
* @param createOrganizationRequest
|
||||
* @param secureFgpAcc
|
||||
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
|
||||
* @param reportProgress flag to report request and response progress.
|
||||
*/
|
||||
public createOrganisation(createOrganizationRequest: CreateOrganizationRequest, secureFgpAcc?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<InseOrganizationManagementModelOrganizationProfile>;
|
||||
public createOrganisation(createOrganizationRequest: CreateOrganizationRequest, secureFgpAcc?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<InseOrganizationManagementModelOrganizationProfile>>;
|
||||
public createOrganisation(createOrganizationRequest: CreateOrganizationRequest, secureFgpAcc?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<InseOrganizationManagementModelOrganizationProfile>>;
|
||||
public createOrganisation(createOrganizationRequest: CreateOrganizationRequest, secureFgpAcc?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||
if (createOrganizationRequest === null || createOrganizationRequest === undefined) {
|
||||
throw new Error('Required parameter createOrganizationRequest was null or undefined when calling createOrganisation.');
|
||||
}
|
||||
let localVarHeaders = this.defaultHeaders;
|
||||
|
||||
let localVarHeaders = this.defaultHeaders;
|
||||
// authentication (HTTPBearer) required
|
||||
localVarHeaders = this.configuration.addCredentialToHeaders(
|
||||
'HTTPBearer',
|
||||
'Authorization',
|
||||
localVarHeaders,
|
||||
'Bearer ',
|
||||
);
|
||||
|
||||
// authentication (HTTPBearer) required
|
||||
localVarHeaders = this.configuration.addCredentialToHeaders('HTTPBearer', 'Authorization', localVarHeaders, 'Bearer ');
|
||||
const localVarHttpHeaderAcceptSelected: string | undefined =
|
||||
options?.httpHeaderAccept ??
|
||||
this.configuration.selectHeaderAccept(['application/json']);
|
||||
if (localVarHttpHeaderAcceptSelected !== undefined) {
|
||||
localVarHeaders = localVarHeaders.set(
|
||||
'Accept',
|
||||
localVarHttpHeaderAcceptSelected,
|
||||
);
|
||||
}
|
||||
|
||||
const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([
|
||||
'application/json'
|
||||
]);
|
||||
if (localVarHttpHeaderAcceptSelected !== undefined) {
|
||||
localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected);
|
||||
}
|
||||
const localVarHttpContext: HttpContext =
|
||||
options?.context ?? new HttpContext();
|
||||
|
||||
const localVarHttpContext: HttpContext = options?.context ?? new HttpContext();
|
||||
const localVarTransferCache: boolean = options?.transferCache ?? true;
|
||||
|
||||
const localVarTransferCache: boolean = options?.transferCache ?? true;
|
||||
// to determine the Content-Type header
|
||||
const consumes: string[] = ['application/json'];
|
||||
const httpContentTypeSelected: string | undefined =
|
||||
this.configuration.selectHeaderContentType(consumes);
|
||||
if (httpContentTypeSelected !== undefined) {
|
||||
localVarHeaders = localVarHeaders.set(
|
||||
'Content-Type',
|
||||
httpContentTypeSelected,
|
||||
);
|
||||
}
|
||||
|
||||
let responseType_: 'text' | 'json' | 'blob' = 'json';
|
||||
if (localVarHttpHeaderAcceptSelected) {
|
||||
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
|
||||
responseType_ = 'text';
|
||||
} else if (
|
||||
this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)
|
||||
) {
|
||||
responseType_ = 'json';
|
||||
} else {
|
||||
responseType_ = 'blob';
|
||||
}
|
||||
}
|
||||
|
||||
// to determine the Content-Type header
|
||||
const consumes: string[] = [
|
||||
'application/json'
|
||||
];
|
||||
const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes);
|
||||
if (httpContentTypeSelected !== undefined) {
|
||||
localVarHeaders = localVarHeaders.set('Content-Type', httpContentTypeSelected);
|
||||
}
|
||||
let localVarPath = `/api/organizations`;
|
||||
const { basePath, withCredentials } = this.configuration;
|
||||
return this.httpClient.request<InseOrganizationManagementModelOrganizationProfile>(
|
||||
'post',
|
||||
`${basePath}${localVarPath}`,
|
||||
{
|
||||
context: localVarHttpContext,
|
||||
body: createOrganizationRequest,
|
||||
responseType: <any>responseType_,
|
||||
...(withCredentials ? { withCredentials } : {}),
|
||||
headers: localVarHeaders,
|
||||
observe: observe,
|
||||
...(localVarTransferCache !== undefined
|
||||
? { transferCache: localVarTransferCache }
|
||||
: {}),
|
||||
reportProgress: reportProgress,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
let responseType_: 'text' | 'json' | 'blob' = 'json';
|
||||
if (localVarHttpHeaderAcceptSelected) {
|
||||
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
|
||||
responseType_ = 'text';
|
||||
} else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) {
|
||||
responseType_ = 'json';
|
||||
} else {
|
||||
responseType_ = 'blob';
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Delete Organization
|
||||
* @endpoint delete /api/organizations/{organization_id}
|
||||
* @param organizationId
|
||||
* @param secureFgpAcc
|
||||
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
|
||||
* @param reportProgress flag to report request and response progress.
|
||||
*/
|
||||
public deleteOrganisation(
|
||||
organizationId: string,
|
||||
secureFgpAcc?: string,
|
||||
observe?: 'body',
|
||||
reportProgress?: boolean,
|
||||
options?: {
|
||||
httpHeaderAccept?: 'application/json';
|
||||
context?: HttpContext;
|
||||
transferCache?: boolean;
|
||||
},
|
||||
): Observable<any>;
|
||||
public deleteOrganisation(
|
||||
organizationId: string,
|
||||
secureFgpAcc?: string,
|
||||
observe?: 'response',
|
||||
reportProgress?: boolean,
|
||||
options?: {
|
||||
httpHeaderAccept?: 'application/json';
|
||||
context?: HttpContext;
|
||||
transferCache?: boolean;
|
||||
},
|
||||
): Observable<HttpResponse<any>>;
|
||||
public deleteOrganisation(
|
||||
organizationId: string,
|
||||
secureFgpAcc?: string,
|
||||
observe?: 'events',
|
||||
reportProgress?: boolean,
|
||||
options?: {
|
||||
httpHeaderAccept?: 'application/json';
|
||||
context?: HttpContext;
|
||||
transferCache?: boolean;
|
||||
},
|
||||
): Observable<HttpEvent<any>>;
|
||||
public deleteOrganisation(
|
||||
organizationId: string,
|
||||
secureFgpAcc?: string,
|
||||
observe: any = 'body',
|
||||
reportProgress: boolean = false,
|
||||
options?: {
|
||||
httpHeaderAccept?: 'application/json';
|
||||
context?: HttpContext;
|
||||
transferCache?: boolean;
|
||||
},
|
||||
): Observable<any> {
|
||||
if (organizationId === null || organizationId === undefined) {
|
||||
throw new Error(
|
||||
'Required parameter organizationId was null or undefined when calling deleteOrganisation.',
|
||||
);
|
||||
}
|
||||
|
||||
let localVarPath = `/api/organizations`;
|
||||
const { basePath, withCredentials } = this.configuration;
|
||||
return this.httpClient.request<InseOrganizationManagementModelOrganizationProfile>('post', `${basePath}${localVarPath}`,
|
||||
{
|
||||
context: localVarHttpContext,
|
||||
body: createOrganizationRequest,
|
||||
responseType: <any>responseType_,
|
||||
...(withCredentials ? { withCredentials } : {}),
|
||||
headers: localVarHeaders,
|
||||
observe: observe,
|
||||
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
|
||||
reportProgress: reportProgress
|
||||
}
|
||||
let localVarHeaders = this.defaultHeaders;
|
||||
|
||||
// authentication (HTTPBearer) required
|
||||
localVarHeaders = this.configuration.addCredentialToHeaders(
|
||||
'HTTPBearer',
|
||||
'Authorization',
|
||||
localVarHeaders,
|
||||
'Bearer ',
|
||||
);
|
||||
|
||||
const localVarHttpHeaderAcceptSelected: string | undefined =
|
||||
options?.httpHeaderAccept ??
|
||||
this.configuration.selectHeaderAccept(['application/json']);
|
||||
if (localVarHttpHeaderAcceptSelected !== undefined) {
|
||||
localVarHeaders = localVarHeaders.set(
|
||||
'Accept',
|
||||
localVarHttpHeaderAcceptSelected,
|
||||
);
|
||||
}
|
||||
|
||||
const localVarHttpContext: HttpContext =
|
||||
options?.context ?? new HttpContext();
|
||||
|
||||
const localVarTransferCache: boolean = options?.transferCache ?? true;
|
||||
|
||||
let responseType_: 'text' | 'json' | 'blob' = 'json';
|
||||
if (localVarHttpHeaderAcceptSelected) {
|
||||
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
|
||||
responseType_ = 'text';
|
||||
} else if (
|
||||
this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)
|
||||
) {
|
||||
responseType_ = 'json';
|
||||
} else {
|
||||
responseType_ = 'blob';
|
||||
}
|
||||
}
|
||||
|
||||
let localVarPath = `/api/organizations/${this.configuration.encodeParam({ name: 'organizationId', value: organizationId, in: 'path', style: 'simple', explode: false, dataType: 'string', dataFormat: 'uuid' })}`;
|
||||
const { basePath, withCredentials } = this.configuration;
|
||||
return this.httpClient.request<any>(
|
||||
'delete',
|
||||
`${basePath}${localVarPath}`,
|
||||
{
|
||||
context: localVarHttpContext,
|
||||
responseType: <any>responseType_,
|
||||
...(withCredentials ? { withCredentials } : {}),
|
||||
headers: localVarHeaders,
|
||||
observe: observe,
|
||||
...(localVarTransferCache !== undefined
|
||||
? { transferCache: localVarTransferCache }
|
||||
: {}),
|
||||
reportProgress: reportProgress,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get Organizations
|
||||
* @endpoint get /api/organizations
|
||||
* @param page
|
||||
* @param pageSize
|
||||
* @param offset
|
||||
* @param secureFgpAcc
|
||||
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
|
||||
* @param reportProgress flag to report request and response progress.
|
||||
*/
|
||||
public getOrganisations(
|
||||
page?: number,
|
||||
pageSize?: number,
|
||||
offset?: number,
|
||||
secureFgpAcc?: string,
|
||||
observe?: 'body',
|
||||
reportProgress?: boolean,
|
||||
options?: {
|
||||
httpHeaderAccept?: 'application/json';
|
||||
context?: HttpContext;
|
||||
transferCache?: boolean;
|
||||
},
|
||||
): Observable<OrganizationPage>;
|
||||
public getOrganisations(
|
||||
page?: number,
|
||||
pageSize?: number,
|
||||
offset?: number,
|
||||
secureFgpAcc?: string,
|
||||
observe?: 'response',
|
||||
reportProgress?: boolean,
|
||||
options?: {
|
||||
httpHeaderAccept?: 'application/json';
|
||||
context?: HttpContext;
|
||||
transferCache?: boolean;
|
||||
},
|
||||
): Observable<HttpResponse<OrganizationPage>>;
|
||||
public getOrganisations(
|
||||
page?: number,
|
||||
pageSize?: number,
|
||||
offset?: number,
|
||||
secureFgpAcc?: string,
|
||||
observe?: 'events',
|
||||
reportProgress?: boolean,
|
||||
options?: {
|
||||
httpHeaderAccept?: 'application/json';
|
||||
context?: HttpContext;
|
||||
transferCache?: boolean;
|
||||
},
|
||||
): Observable<HttpEvent<OrganizationPage>>;
|
||||
public getOrganisations(
|
||||
page?: number,
|
||||
pageSize?: number,
|
||||
offset?: number,
|
||||
secureFgpAcc?: string,
|
||||
observe: any = 'body',
|
||||
reportProgress: boolean = false,
|
||||
options?: {
|
||||
httpHeaderAccept?: 'application/json';
|
||||
context?: HttpContext;
|
||||
transferCache?: boolean;
|
||||
},
|
||||
): Observable<any> {
|
||||
let localVarQueryParameters = new HttpParams({ encoder: this.encoder });
|
||||
localVarQueryParameters = this.addToHttpParams(
|
||||
localVarQueryParameters,
|
||||
<any>page,
|
||||
'page',
|
||||
);
|
||||
localVarQueryParameters = this.addToHttpParams(
|
||||
localVarQueryParameters,
|
||||
<any>pageSize,
|
||||
'page_size',
|
||||
);
|
||||
localVarQueryParameters = this.addToHttpParams(
|
||||
localVarQueryParameters,
|
||||
<any>offset,
|
||||
'offset',
|
||||
);
|
||||
|
||||
let localVarHeaders = this.defaultHeaders;
|
||||
|
||||
// authentication (HTTPBearer) required
|
||||
localVarHeaders = this.configuration.addCredentialToHeaders(
|
||||
'HTTPBearer',
|
||||
'Authorization',
|
||||
localVarHeaders,
|
||||
'Bearer ',
|
||||
);
|
||||
|
||||
const localVarHttpHeaderAcceptSelected: string | undefined =
|
||||
options?.httpHeaderAccept ??
|
||||
this.configuration.selectHeaderAccept(['application/json']);
|
||||
if (localVarHttpHeaderAcceptSelected !== undefined) {
|
||||
localVarHeaders = localVarHeaders.set(
|
||||
'Accept',
|
||||
localVarHttpHeaderAcceptSelected,
|
||||
);
|
||||
}
|
||||
|
||||
const localVarHttpContext: HttpContext =
|
||||
options?.context ?? new HttpContext();
|
||||
|
||||
const localVarTransferCache: boolean = options?.transferCache ?? true;
|
||||
|
||||
let responseType_: 'text' | 'json' | 'blob' = 'json';
|
||||
if (localVarHttpHeaderAcceptSelected) {
|
||||
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
|
||||
responseType_ = 'text';
|
||||
} else if (
|
||||
this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)
|
||||
) {
|
||||
responseType_ = 'json';
|
||||
} else {
|
||||
responseType_ = 'blob';
|
||||
}
|
||||
}
|
||||
|
||||
let localVarPath = `/api/organizations`;
|
||||
const { basePath, withCredentials } = this.configuration;
|
||||
return this.httpClient.request<OrganizationPage>(
|
||||
'get',
|
||||
`${basePath}${localVarPath}`,
|
||||
{
|
||||
context: localVarHttpContext,
|
||||
params: localVarQueryParameters,
|
||||
responseType: <any>responseType_,
|
||||
...(withCredentials ? { withCredentials } : {}),
|
||||
headers: localVarHeaders,
|
||||
observe: observe,
|
||||
...(localVarTransferCache !== undefined
|
||||
? { transferCache: localVarTransferCache }
|
||||
: {}),
|
||||
reportProgress: reportProgress,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get Organization Institution Associations
|
||||
* @endpoint get /api/organizations/institutions/associations
|
||||
* @param institutionIds
|
||||
* @param secureFgpAcc
|
||||
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
|
||||
* @param reportProgress flag to report request and response progress.
|
||||
*/
|
||||
public getOrganizationInstitutionAssociations(
|
||||
institutionIds: Array<string>,
|
||||
secureFgpAcc?: string,
|
||||
observe?: 'body',
|
||||
reportProgress?: boolean,
|
||||
options?: {
|
||||
httpHeaderAccept?: 'application/json';
|
||||
context?: HttpContext;
|
||||
transferCache?: boolean;
|
||||
},
|
||||
): Observable<Array<InstitutionAssociationsResponse>>;
|
||||
public getOrganizationInstitutionAssociations(
|
||||
institutionIds: Array<string>,
|
||||
secureFgpAcc?: string,
|
||||
observe?: 'response',
|
||||
reportProgress?: boolean,
|
||||
options?: {
|
||||
httpHeaderAccept?: 'application/json';
|
||||
context?: HttpContext;
|
||||
transferCache?: boolean;
|
||||
},
|
||||
): Observable<HttpResponse<Array<InstitutionAssociationsResponse>>>;
|
||||
public getOrganizationInstitutionAssociations(
|
||||
institutionIds: Array<string>,
|
||||
secureFgpAcc?: string,
|
||||
observe?: 'events',
|
||||
reportProgress?: boolean,
|
||||
options?: {
|
||||
httpHeaderAccept?: 'application/json';
|
||||
context?: HttpContext;
|
||||
transferCache?: boolean;
|
||||
},
|
||||
): Observable<HttpEvent<Array<InstitutionAssociationsResponse>>>;
|
||||
public getOrganizationInstitutionAssociations(
|
||||
institutionIds: Array<string>,
|
||||
secureFgpAcc?: string,
|
||||
observe: any = 'body',
|
||||
reportProgress: boolean = false,
|
||||
options?: {
|
||||
httpHeaderAccept?: 'application/json';
|
||||
context?: HttpContext;
|
||||
transferCache?: boolean;
|
||||
},
|
||||
): Observable<any> {
|
||||
if (institutionIds === null || institutionIds === undefined) {
|
||||
throw new Error(
|
||||
'Required parameter institutionIds was null or undefined when calling getOrganizationInstitutionAssociations.',
|
||||
);
|
||||
}
|
||||
|
||||
let localVarQueryParameters = new HttpParams({ encoder: this.encoder });
|
||||
if (institutionIds) {
|
||||
institutionIds.forEach((element) => {
|
||||
localVarQueryParameters = this.addToHttpParams(
|
||||
localVarQueryParameters,
|
||||
<any>element,
|
||||
'institution_ids',
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete Organization
|
||||
* @endpoint delete /api/organizations/{organization_id}
|
||||
* @param organizationId
|
||||
* @param secureFgpAcc
|
||||
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
|
||||
* @param reportProgress flag to report request and response progress.
|
||||
*/
|
||||
public deleteOrganisation(organizationId: string, secureFgpAcc?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any>;
|
||||
public deleteOrganisation(organizationId: string, secureFgpAcc?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<any>>;
|
||||
public deleteOrganisation(organizationId: string, secureFgpAcc?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<any>>;
|
||||
public deleteOrganisation(organizationId: string, secureFgpAcc?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||
if (organizationId === null || organizationId === undefined) {
|
||||
throw new Error('Required parameter organizationId was null or undefined when calling deleteOrganisation.');
|
||||
}
|
||||
let localVarHeaders = this.defaultHeaders;
|
||||
|
||||
let localVarHeaders = this.defaultHeaders;
|
||||
// authentication (HTTPBearer) required
|
||||
localVarHeaders = this.configuration.addCredentialToHeaders(
|
||||
'HTTPBearer',
|
||||
'Authorization',
|
||||
localVarHeaders,
|
||||
'Bearer ',
|
||||
);
|
||||
|
||||
// authentication (HTTPBearer) required
|
||||
localVarHeaders = this.configuration.addCredentialToHeaders('HTTPBearer', 'Authorization', localVarHeaders, 'Bearer ');
|
||||
|
||||
const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([
|
||||
'application/json'
|
||||
]);
|
||||
if (localVarHttpHeaderAcceptSelected !== undefined) {
|
||||
localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected);
|
||||
}
|
||||
|
||||
const localVarHttpContext: HttpContext = options?.context ?? new HttpContext();
|
||||
|
||||
const localVarTransferCache: boolean = options?.transferCache ?? true;
|
||||
|
||||
|
||||
let responseType_: 'text' | 'json' | 'blob' = 'json';
|
||||
if (localVarHttpHeaderAcceptSelected) {
|
||||
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
|
||||
responseType_ = 'text';
|
||||
} else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) {
|
||||
responseType_ = 'json';
|
||||
} else {
|
||||
responseType_ = 'blob';
|
||||
}
|
||||
}
|
||||
|
||||
let localVarPath = `/api/organizations/${this.configuration.encodeParam({name: "organizationId", value: organizationId, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: "uuid"})}`;
|
||||
const { basePath, withCredentials } = this.configuration;
|
||||
return this.httpClient.request<any>('delete', `${basePath}${localVarPath}`,
|
||||
{
|
||||
context: localVarHttpContext,
|
||||
responseType: <any>responseType_,
|
||||
...(withCredentials ? { withCredentials } : {}),
|
||||
headers: localVarHeaders,
|
||||
observe: observe,
|
||||
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
|
||||
reportProgress: reportProgress
|
||||
}
|
||||
);
|
||||
const localVarHttpHeaderAcceptSelected: string | undefined =
|
||||
options?.httpHeaderAccept ??
|
||||
this.configuration.selectHeaderAccept(['application/json']);
|
||||
if (localVarHttpHeaderAcceptSelected !== undefined) {
|
||||
localVarHeaders = localVarHeaders.set(
|
||||
'Accept',
|
||||
localVarHttpHeaderAcceptSelected,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get Organizations
|
||||
* @endpoint get /api/organizations
|
||||
* @param page
|
||||
* @param pageSize
|
||||
* @param offset
|
||||
* @param secureFgpAcc
|
||||
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
|
||||
* @param reportProgress flag to report request and response progress.
|
||||
*/
|
||||
public getOrganisations(page?: number, pageSize?: number, offset?: number, secureFgpAcc?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<OrganizationPage>;
|
||||
public getOrganisations(page?: number, pageSize?: number, offset?: number, secureFgpAcc?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<OrganizationPage>>;
|
||||
public getOrganisations(page?: number, pageSize?: number, offset?: number, secureFgpAcc?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<OrganizationPage>>;
|
||||
public getOrganisations(page?: number, pageSize?: number, offset?: number, secureFgpAcc?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||
const localVarHttpContext: HttpContext =
|
||||
options?.context ?? new HttpContext();
|
||||
|
||||
let localVarQueryParameters = new HttpParams({encoder: this.encoder});
|
||||
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
||||
<any>page, 'page');
|
||||
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
||||
<any>pageSize, 'page_size');
|
||||
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
||||
<any>offset, 'offset');
|
||||
const localVarTransferCache: boolean = options?.transferCache ?? true;
|
||||
|
||||
let localVarHeaders = this.defaultHeaders;
|
||||
|
||||
// authentication (HTTPBearer) required
|
||||
localVarHeaders = this.configuration.addCredentialToHeaders('HTTPBearer', 'Authorization', localVarHeaders, 'Bearer ');
|
||||
|
||||
const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([
|
||||
'application/json'
|
||||
]);
|
||||
if (localVarHttpHeaderAcceptSelected !== undefined) {
|
||||
localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected);
|
||||
}
|
||||
|
||||
const localVarHttpContext: HttpContext = options?.context ?? new HttpContext();
|
||||
|
||||
const localVarTransferCache: boolean = options?.transferCache ?? true;
|
||||
|
||||
|
||||
let responseType_: 'text' | 'json' | 'blob' = 'json';
|
||||
if (localVarHttpHeaderAcceptSelected) {
|
||||
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
|
||||
responseType_ = 'text';
|
||||
} else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) {
|
||||
responseType_ = 'json';
|
||||
} else {
|
||||
responseType_ = 'blob';
|
||||
}
|
||||
}
|
||||
|
||||
let localVarPath = `/api/organizations`;
|
||||
const { basePath, withCredentials } = this.configuration;
|
||||
return this.httpClient.request<OrganizationPage>('get', `${basePath}${localVarPath}`,
|
||||
{
|
||||
context: localVarHttpContext,
|
||||
params: localVarQueryParameters,
|
||||
responseType: <any>responseType_,
|
||||
...(withCredentials ? { withCredentials } : {}),
|
||||
headers: localVarHeaders,
|
||||
observe: observe,
|
||||
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
|
||||
reportProgress: reportProgress
|
||||
}
|
||||
);
|
||||
let responseType_: 'text' | 'json' | 'blob' = 'json';
|
||||
if (localVarHttpHeaderAcceptSelected) {
|
||||
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
|
||||
responseType_ = 'text';
|
||||
} else if (
|
||||
this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)
|
||||
) {
|
||||
responseType_ = 'json';
|
||||
} else {
|
||||
responseType_ = 'blob';
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Update Organization
|
||||
* @endpoint put /api/organizations/{organization_id}
|
||||
* @param organizationId
|
||||
* @param updateOrganizationRequest
|
||||
* @param secureFgpAcc
|
||||
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
|
||||
* @param reportProgress flag to report request and response progress.
|
||||
*/
|
||||
public updateOrganisation(organizationId: string, updateOrganizationRequest: UpdateOrganizationRequest, secureFgpAcc?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<InseOrganizationManagementModelOrganizationProfile>;
|
||||
public updateOrganisation(organizationId: string, updateOrganizationRequest: UpdateOrganizationRequest, secureFgpAcc?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<InseOrganizationManagementModelOrganizationProfile>>;
|
||||
public updateOrganisation(organizationId: string, updateOrganizationRequest: UpdateOrganizationRequest, secureFgpAcc?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<InseOrganizationManagementModelOrganizationProfile>>;
|
||||
public updateOrganisation(organizationId: string, updateOrganizationRequest: UpdateOrganizationRequest, secureFgpAcc?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||
if (organizationId === null || organizationId === undefined) {
|
||||
throw new Error('Required parameter organizationId was null or undefined when calling updateOrganisation.');
|
||||
}
|
||||
if (updateOrganizationRequest === null || updateOrganizationRequest === undefined) {
|
||||
throw new Error('Required parameter updateOrganizationRequest was null or undefined when calling updateOrganisation.');
|
||||
}
|
||||
let localVarPath = `/api/organizations/institutions/associations`;
|
||||
const { basePath, withCredentials } = this.configuration;
|
||||
return this.httpClient.request<Array<InstitutionAssociationsResponse>>(
|
||||
'get',
|
||||
`${basePath}${localVarPath}`,
|
||||
{
|
||||
context: localVarHttpContext,
|
||||
params: localVarQueryParameters,
|
||||
responseType: <any>responseType_,
|
||||
...(withCredentials ? { withCredentials } : {}),
|
||||
headers: localVarHeaders,
|
||||
observe: observe,
|
||||
...(localVarTransferCache !== undefined
|
||||
? { transferCache: localVarTransferCache }
|
||||
: {}),
|
||||
reportProgress: reportProgress,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
let localVarHeaders = this.defaultHeaders;
|
||||
|
||||
// authentication (HTTPBearer) required
|
||||
localVarHeaders = this.configuration.addCredentialToHeaders('HTTPBearer', 'Authorization', localVarHeaders, 'Bearer ');
|
||||
|
||||
const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([
|
||||
'application/json'
|
||||
]);
|
||||
if (localVarHttpHeaderAcceptSelected !== undefined) {
|
||||
localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected);
|
||||
}
|
||||
|
||||
const localVarHttpContext: HttpContext = options?.context ?? new HttpContext();
|
||||
|
||||
const localVarTransferCache: boolean = options?.transferCache ?? true;
|
||||
|
||||
|
||||
// to determine the Content-Type header
|
||||
const consumes: string[] = [
|
||||
'application/json'
|
||||
];
|
||||
const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes);
|
||||
if (httpContentTypeSelected !== undefined) {
|
||||
localVarHeaders = localVarHeaders.set('Content-Type', httpContentTypeSelected);
|
||||
}
|
||||
|
||||
let responseType_: 'text' | 'json' | 'blob' = 'json';
|
||||
if (localVarHttpHeaderAcceptSelected) {
|
||||
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
|
||||
responseType_ = 'text';
|
||||
} else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) {
|
||||
responseType_ = 'json';
|
||||
} else {
|
||||
responseType_ = 'blob';
|
||||
}
|
||||
}
|
||||
|
||||
let localVarPath = `/api/organizations/${this.configuration.encodeParam({name: "organizationId", value: organizationId, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: "uuid"})}`;
|
||||
const { basePath, withCredentials } = this.configuration;
|
||||
return this.httpClient.request<InseOrganizationManagementModelOrganizationProfile>('put', `${basePath}${localVarPath}`,
|
||||
{
|
||||
context: localVarHttpContext,
|
||||
body: updateOrganizationRequest,
|
||||
responseType: <any>responseType_,
|
||||
...(withCredentials ? { withCredentials } : {}),
|
||||
headers: localVarHeaders,
|
||||
observe: observe,
|
||||
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
|
||||
reportProgress: reportProgress
|
||||
}
|
||||
);
|
||||
/**
|
||||
* Update Organization
|
||||
* @endpoint put /api/organizations/{organization_id}
|
||||
* @param organizationId
|
||||
* @param updateOrganizationRequest
|
||||
* @param secureFgpAcc
|
||||
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
|
||||
* @param reportProgress flag to report request and response progress.
|
||||
*/
|
||||
public updateOrganisation(
|
||||
organizationId: string,
|
||||
updateOrganizationRequest: UpdateOrganizationRequest,
|
||||
secureFgpAcc?: string,
|
||||
observe?: 'body',
|
||||
reportProgress?: boolean,
|
||||
options?: {
|
||||
httpHeaderAccept?: 'application/json';
|
||||
context?: HttpContext;
|
||||
transferCache?: boolean;
|
||||
},
|
||||
): Observable<InseOrganizationManagementModelOrganizationProfile>;
|
||||
public updateOrganisation(
|
||||
organizationId: string,
|
||||
updateOrganizationRequest: UpdateOrganizationRequest,
|
||||
secureFgpAcc?: string,
|
||||
observe?: 'response',
|
||||
reportProgress?: boolean,
|
||||
options?: {
|
||||
httpHeaderAccept?: 'application/json';
|
||||
context?: HttpContext;
|
||||
transferCache?: boolean;
|
||||
},
|
||||
): Observable<
|
||||
HttpResponse<InseOrganizationManagementModelOrganizationProfile>
|
||||
>;
|
||||
public updateOrganisation(
|
||||
organizationId: string,
|
||||
updateOrganizationRequest: UpdateOrganizationRequest,
|
||||
secureFgpAcc?: string,
|
||||
observe?: 'events',
|
||||
reportProgress?: boolean,
|
||||
options?: {
|
||||
httpHeaderAccept?: 'application/json';
|
||||
context?: HttpContext;
|
||||
transferCache?: boolean;
|
||||
},
|
||||
): Observable<HttpEvent<InseOrganizationManagementModelOrganizationProfile>>;
|
||||
public updateOrganisation(
|
||||
organizationId: string,
|
||||
updateOrganizationRequest: UpdateOrganizationRequest,
|
||||
secureFgpAcc?: string,
|
||||
observe: any = 'body',
|
||||
reportProgress: boolean = false,
|
||||
options?: {
|
||||
httpHeaderAccept?: 'application/json';
|
||||
context?: HttpContext;
|
||||
transferCache?: boolean;
|
||||
},
|
||||
): Observable<any> {
|
||||
if (organizationId === null || organizationId === undefined) {
|
||||
throw new Error(
|
||||
'Required parameter organizationId was null or undefined when calling updateOrganisation.',
|
||||
);
|
||||
}
|
||||
if (
|
||||
updateOrganizationRequest === null ||
|
||||
updateOrganizationRequest === undefined
|
||||
) {
|
||||
throw new Error(
|
||||
'Required parameter updateOrganizationRequest was null or undefined when calling updateOrganisation.',
|
||||
);
|
||||
}
|
||||
|
||||
let localVarHeaders = this.defaultHeaders;
|
||||
|
||||
// authentication (HTTPBearer) required
|
||||
localVarHeaders = this.configuration.addCredentialToHeaders(
|
||||
'HTTPBearer',
|
||||
'Authorization',
|
||||
localVarHeaders,
|
||||
'Bearer ',
|
||||
);
|
||||
|
||||
const localVarHttpHeaderAcceptSelected: string | undefined =
|
||||
options?.httpHeaderAccept ??
|
||||
this.configuration.selectHeaderAccept(['application/json']);
|
||||
if (localVarHttpHeaderAcceptSelected !== undefined) {
|
||||
localVarHeaders = localVarHeaders.set(
|
||||
'Accept',
|
||||
localVarHttpHeaderAcceptSelected,
|
||||
);
|
||||
}
|
||||
|
||||
const localVarHttpContext: HttpContext =
|
||||
options?.context ?? new HttpContext();
|
||||
|
||||
const localVarTransferCache: boolean = options?.transferCache ?? true;
|
||||
|
||||
// to determine the Content-Type header
|
||||
const consumes: string[] = ['application/json'];
|
||||
const httpContentTypeSelected: string | undefined =
|
||||
this.configuration.selectHeaderContentType(consumes);
|
||||
if (httpContentTypeSelected !== undefined) {
|
||||
localVarHeaders = localVarHeaders.set(
|
||||
'Content-Type',
|
||||
httpContentTypeSelected,
|
||||
);
|
||||
}
|
||||
|
||||
let responseType_: 'text' | 'json' | 'blob' = 'json';
|
||||
if (localVarHttpHeaderAcceptSelected) {
|
||||
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
|
||||
responseType_ = 'text';
|
||||
} else if (
|
||||
this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)
|
||||
) {
|
||||
responseType_ = 'json';
|
||||
} else {
|
||||
responseType_ = 'blob';
|
||||
}
|
||||
}
|
||||
|
||||
let localVarPath = `/api/organizations/${this.configuration.encodeParam({ name: 'organizationId', value: organizationId, in: 'path', style: 'simple', explode: false, dataType: 'string', dataFormat: 'uuid' })}`;
|
||||
const { basePath, withCredentials } = this.configuration;
|
||||
return this.httpClient.request<InseOrganizationManagementModelOrganizationProfile>(
|
||||
'put',
|
||||
`${basePath}${localVarPath}`,
|
||||
{
|
||||
context: localVarHttpContext,
|
||||
body: updateOrganizationRequest,
|
||||
responseType: <any>responseType_,
|
||||
...(withCredentials ? { withCredentials } : {}),
|
||||
headers: localVarHeaders,
|
||||
observe: observe,
|
||||
...(localVarTransferCache !== undefined
|
||||
? { transferCache: localVarTransferCache }
|
||||
: {}),
|
||||
reportProgress: reportProgress,
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,16 +1,15 @@
|
||||
/**
|
||||
* Innovation Search Engine API
|
||||
*
|
||||
*
|
||||
*
|
||||
*
|
||||
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
|
||||
* https://openapi-generator.tech
|
||||
* Do not edit the class manually.
|
||||
*/
|
||||
|
||||
|
||||
export interface CreateOrganizationRequest {
|
||||
name: string;
|
||||
other_inst_id?: string | null;
|
||||
export interface CreateOrganizationRequest {
|
||||
name: string;
|
||||
other_inst_id?: string | null;
|
||||
selected_openalex_institution_ids?: Array<string> | null;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,19 +1,18 @@
|
||||
/**
|
||||
* Innovation Search Engine API
|
||||
*
|
||||
*
|
||||
*
|
||||
*
|
||||
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
|
||||
* https://openapi-generator.tech
|
||||
* Do not edit the class manually.
|
||||
*/
|
||||
|
||||
|
||||
export interface InseOrganizationManagementModelOrganizationProfile {
|
||||
id: string;
|
||||
name: string;
|
||||
other_inst_id?: string | null;
|
||||
deleted: boolean;
|
||||
member_count: number;
|
||||
export interface InseOrganizationManagementModelOrganizationProfile {
|
||||
id: string;
|
||||
name: string;
|
||||
other_inst_id?: string | null;
|
||||
selected_openalex_institution_ids?: Array<string>;
|
||||
deleted: boolean;
|
||||
member_count: number;
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
/**
|
||||
* Innovation Search Engine API
|
||||
*
|
||||
*
|
||||
*
|
||||
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
|
||||
* https://openapi-generator.tech
|
||||
* Do not edit the class manually.
|
||||
*/
|
||||
|
||||
export interface InstitutionAssociation {
|
||||
id: string;
|
||||
display_name: string;
|
||||
relationship: InstitutionAssociation.RelationshipEnum;
|
||||
}
|
||||
export namespace InstitutionAssociation {
|
||||
export const RelationshipEnum = {
|
||||
Child: 'child',
|
||||
Related: 'related',
|
||||
} as const;
|
||||
export type RelationshipEnum =
|
||||
(typeof RelationshipEnum)[keyof typeof RelationshipEnum];
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
/**
|
||||
* Innovation Search Engine API
|
||||
*
|
||||
*
|
||||
*
|
||||
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
|
||||
* https://openapi-generator.tech
|
||||
* Do not edit the class manually.
|
||||
*/
|
||||
import { InstitutionAssociation } from './institutionAssociation';
|
||||
|
||||
export interface InstitutionAssociationsResponse {
|
||||
id: string;
|
||||
display_name: string;
|
||||
associated_institutions?: Array<InstitutionAssociation>;
|
||||
}
|
||||
@@ -137,6 +137,8 @@ export * from './idTokenMetadata';
|
||||
export * from './inseAccountManagementModelOrganizationProfile';
|
||||
export * from './inseOrganizationManagementModelOrganizationProfile';
|
||||
export * from './institution';
|
||||
export * from './institutionAssociation';
|
||||
export * from './institutionAssociationsResponse';
|
||||
export * from './institutionFunderSummary';
|
||||
export * from './institutionGeo';
|
||||
export * from './institutionIds';
|
||||
|
||||
@@ -1,17 +1,16 @@
|
||||
/**
|
||||
* Innovation Search Engine API
|
||||
*
|
||||
*
|
||||
*
|
||||
*
|
||||
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
|
||||
* https://openapi-generator.tech
|
||||
* Do not edit the class manually.
|
||||
*/
|
||||
|
||||
|
||||
export interface UpdateOrganizationRequest {
|
||||
name?: string | null;
|
||||
other_inst_id?: string | null;
|
||||
deleted?: boolean | null;
|
||||
export interface UpdateOrganizationRequest {
|
||||
name?: string | null;
|
||||
other_inst_id?: string | null;
|
||||
selected_openalex_institution_ids?: Array<string> | null;
|
||||
deleted?: boolean | null;
|
||||
}
|
||||
|
||||
|
||||
@@ -10,8 +10,22 @@
|
||||
}}
|
||||
</p>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<section class="account-toolbar">
|
||||
<app-query-param-input
|
||||
class="account-search"
|
||||
queryParamKey="search"
|
||||
label="Nach Name oder E-Mail suchen" />
|
||||
<app-query-param-selector
|
||||
class="account-organization"
|
||||
queryParamKey="organization_id"
|
||||
[options]="selectorOptions()"
|
||||
label="Organisation"
|
||||
[allowEmptyValue]="true" />
|
||||
@if (!isReadOnly) {
|
||||
<button
|
||||
class="create-account-button"
|
||||
mat-flat-button
|
||||
color="primary"
|
||||
type="button"
|
||||
@@ -21,19 +35,6 @@
|
||||
Neuer Account
|
||||
</button>
|
||||
}
|
||||
</header>
|
||||
|
||||
<section style="display: flex; gap: 1rem; align-items: center">
|
||||
<app-query-param-input
|
||||
queryParamKey="search"
|
||||
label="Nach Name oder E-Mail suchen"
|
||||
style="width: 35%" />
|
||||
<app-query-param-selector
|
||||
queryParamKey="organization_id"
|
||||
[options]="selectorOptions()"
|
||||
label="Organisation"
|
||||
[allowEmptyValue]="true"
|
||||
style="width: 25%" />
|
||||
</section>
|
||||
<mat-card appearance="outlined">
|
||||
<mat-card-content>
|
||||
|
||||
@@ -19,6 +19,25 @@
|
||||
gap: 16px;
|
||||
}
|
||||
|
||||
.account-toolbar {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 16px;
|
||||
}
|
||||
|
||||
.account-search {
|
||||
flex: 0 1 35%;
|
||||
}
|
||||
|
||||
.account-organization {
|
||||
flex: 0 1 25%;
|
||||
}
|
||||
|
||||
.create-account-button {
|
||||
flex: 0 0 auto;
|
||||
margin-left: auto;
|
||||
}
|
||||
|
||||
h1,
|
||||
h2,
|
||||
p {
|
||||
@@ -155,6 +174,22 @@ tr.deactivated:not(.deleted) {
|
||||
align-items: flex-start;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.account-toolbar {
|
||||
align-items: stretch;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.account-search,
|
||||
.account-organization {
|
||||
flex-basis: auto;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.create-account-button {
|
||||
align-self: flex-start;
|
||||
margin-left: 0;
|
||||
}
|
||||
}
|
||||
|
||||
mat-card,
|
||||
|
||||
@@ -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: [],
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,6 +1,6 @@
|
||||
import { HttpClient } from '@angular/common/http';
|
||||
import { Injectable, inject } from '@angular/core';
|
||||
import { Observable } from 'rxjs';
|
||||
import { Observable, catchError, forkJoin, map, of } from 'rxjs';
|
||||
|
||||
import { Configuration } from '../../api';
|
||||
import { TopicTreemapData } from '../../shared/ui/topic-treemap/topic-treemap.models';
|
||||
@@ -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;
|
||||
@@ -59,6 +64,8 @@ export interface DfgProjectTopic {
|
||||
field?: string | null;
|
||||
domain?: string | null;
|
||||
project_count: number;
|
||||
field_project_count: number;
|
||||
subfield_project_count: number;
|
||||
keywords: DfgProjectKeyword[];
|
||||
}
|
||||
|
||||
@@ -75,6 +82,9 @@ export interface DfgProjectTopics {
|
||||
topics: DfgProjectTopic[];
|
||||
}
|
||||
|
||||
export interface EuProjectTopics extends DfgProjectTopics {}
|
||||
export interface BundProjectTopics extends DfgProjectTopics {}
|
||||
|
||||
export interface TopAuthor {
|
||||
id?: string | null;
|
||||
name: string;
|
||||
@@ -90,6 +100,11 @@ export interface TopAuthorStatistics {
|
||||
news: TopAuthor[];
|
||||
}
|
||||
|
||||
export interface TopAuthorAnalysis {
|
||||
institution_id: string;
|
||||
authors: TopAuthor[];
|
||||
}
|
||||
|
||||
export interface TopicWordCloudWord {
|
||||
id: string;
|
||||
name: string;
|
||||
@@ -106,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`,
|
||||
@@ -114,108 +135,171 @@ 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) },
|
||||
);
|
||||
}
|
||||
|
||||
getEuProjectStatuses(
|
||||
period: DashboardPeriodBounds = {},
|
||||
institutionId = 'all',
|
||||
): Observable<EuProjectStatusStatistics> {
|
||||
return this.httpClient.get<EuProjectStatusStatistics>(
|
||||
`${this.apiConfiguration?.basePath ?? ''}/api/dashboard/projects/eu/status`,
|
||||
{ params: this.periodParams(period) },
|
||||
{ params: this.analyticalParams(period, institutionId) },
|
||||
);
|
||||
}
|
||||
|
||||
getBmbfProjectStatuses(
|
||||
period: DashboardPeriodBounds = {},
|
||||
institutionId = 'all',
|
||||
): Observable<BmbfProjectStatusStatistics> {
|
||||
return this.httpClient.get<BmbfProjectStatusStatistics>(
|
||||
`${this.apiConfiguration?.basePath ?? ''}/api/dashboard/projects/bmbf/status`,
|
||||
{ params: this.periodParams(period) },
|
||||
{ params: this.analyticalParams(period, institutionId) },
|
||||
);
|
||||
}
|
||||
|
||||
getDfgProjectStatuses(
|
||||
period: DashboardPeriodBounds = {},
|
||||
institutionId = 'all',
|
||||
): Observable<DfgProjectStatusStatistics> {
|
||||
return this.httpClient.get<DfgProjectStatusStatistics>(
|
||||
`${this.apiConfiguration?.basePath ?? ''}/api/dashboard/projects/dfg/status`,
|
||||
{ params: this.periodParams(period) },
|
||||
{ params: this.analyticalParams(period, institutionId) },
|
||||
);
|
||||
}
|
||||
|
||||
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) },
|
||||
);
|
||||
}
|
||||
|
||||
getDfgProjectTopics(
|
||||
period: DashboardPeriodBounds = {},
|
||||
institutionId = 'all',
|
||||
): Observable<DfgProjectTopics> {
|
||||
return this.httpClient.get<DfgProjectTopics>(
|
||||
`${this.apiConfiguration?.basePath ?? ''}/api/dashboard/projects/dfg/topics`,
|
||||
{ params: this.periodParams(period) },
|
||||
{ params: this.analyticalParams(period, institutionId) },
|
||||
);
|
||||
}
|
||||
|
||||
getEuProjectTopics(
|
||||
period: DashboardPeriodBounds = {},
|
||||
institutionId = 'all',
|
||||
): Observable<EuProjectTopics> {
|
||||
return this.httpClient.get<EuProjectTopics>(
|
||||
`${this.apiConfiguration?.basePath ?? ''}/api/dashboard/projects/eu/topics`,
|
||||
{ params: this.analyticalParams(period, institutionId) },
|
||||
);
|
||||
}
|
||||
|
||||
getBundProjectTopics(
|
||||
period: DashboardPeriodBounds = {},
|
||||
institutionId = 'all',
|
||||
): Observable<BundProjectTopics> {
|
||||
return this.httpClient.get<BundProjectTopics>(
|
||||
`${this.apiConfiguration?.basePath ?? ''}/api/dashboard/projects/bund/topics`,
|
||||
{ params: this.analyticalParams(period, institutionId) },
|
||||
);
|
||||
}
|
||||
|
||||
getTopAuthors(
|
||||
period: DashboardPeriodBounds = {},
|
||||
institutionId = 'all',
|
||||
): Observable<TopAuthorStatistics> {
|
||||
return this.httpClient.get<TopAuthorStatistics>(
|
||||
`${this.apiConfiguration?.basePath ?? ''}/api/dashboard/top-authors`,
|
||||
{ params: this.periodParams(period) },
|
||||
const analysis = (source: string) =>
|
||||
this.httpClient
|
||||
.get<TopAuthorAnalysis>(
|
||||
`${this.apiConfiguration?.basePath ?? ''}/api/dashboard/top-authors/${source}`,
|
||||
{ params: this.analyticalParams(period, institutionId) },
|
||||
)
|
||||
.pipe(catchError(() => of(null)));
|
||||
|
||||
return forkJoin({
|
||||
works: analysis('works'),
|
||||
projects: analysis('projects'),
|
||||
euProjects: analysis('eu-projects'),
|
||||
patents: analysis('patents'),
|
||||
news: analysis('news'),
|
||||
}).pipe(
|
||||
map((responses) => {
|
||||
const successfulResponse = Object.values(responses).find(
|
||||
(response) => response !== null,
|
||||
);
|
||||
if (!successfulResponse) {
|
||||
throw new Error('All top-author analyses failed.');
|
||||
}
|
||||
|
||||
return {
|
||||
institution_id: successfulResponse.institution_id,
|
||||
works: responses.works?.authors ?? [],
|
||||
projects: responses.projects?.authors ?? [],
|
||||
eu_projects: responses.euProjects?.authors ?? [],
|
||||
patents: responses.patents?.authors ?? [],
|
||||
news: responses.news?.authors ?? [],
|
||||
};
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
getTopicTreemap(
|
||||
fromYear?: number,
|
||||
toYear?: number,
|
||||
institutionId = 'all',
|
||||
): Observable<TopicTreemapData> {
|
||||
const params: Record<string, number> = {};
|
||||
const params: Record<string, string | number> = {
|
||||
institution_id: institutionId,
|
||||
};
|
||||
if (fromYear !== undefined) params['from_year'] = fromYear;
|
||||
if (toYear !== undefined) params['to_year'] = toYear;
|
||||
|
||||
@@ -229,8 +313,12 @@ export class DashboardStatisticsService {
|
||||
topicId: string,
|
||||
fromYear?: number,
|
||||
toYear?: number,
|
||||
institutionId = 'all',
|
||||
): Observable<TopicWordCloud> {
|
||||
const params: Record<string, string | number> = { topicId };
|
||||
const params: Record<string, string | number> = {
|
||||
topicId,
|
||||
institution_id: institutionId,
|
||||
};
|
||||
if (fromYear !== undefined) params['from_year'] = fromYear;
|
||||
if (toYear !== undefined) params['to_year'] = toYear;
|
||||
return this.httpClient.get<TopicWordCloud>(
|
||||
@@ -245,4 +333,24 @@ 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,
|
||||
};
|
||||
}
|
||||
|
||||
private analyticalParams(
|
||||
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">
|
||||
@@ -40,7 +59,9 @@
|
||||
[attr.aria-disabled]="!institutionRouteId()"
|
||||
[attr.aria-label]="
|
||||
'Publikationen von ' + organizationName() + ' anzeigen'
|
||||
">
|
||||
"
|
||||
matTooltip="Anzahl der Publikationen im ausgewählten Zeitraum"
|
||||
matTooltipPosition="above">
|
||||
<div class="statistics-icon statistics-icon--publications">
|
||||
<mat-icon>menu_book</mat-icon>
|
||||
</div>
|
||||
@@ -60,7 +81,9 @@
|
||||
class="statistics-card"
|
||||
routerLink="/persons"
|
||||
[queryParams]="personListQueryParams()"
|
||||
[attr.aria-label]="'Personen von ' + organizationName() + ' anzeigen'">
|
||||
[attr.aria-label]="'Personen von ' + organizationName() + ' anzeigen'"
|
||||
matTooltip="Anzahl der Personen im ausgewählten Zeitraum"
|
||||
matTooltipPosition="above">
|
||||
<div class="statistics-icon statistics-icon--persons">
|
||||
<mat-icon>groups</mat-icon>
|
||||
</div>
|
||||
@@ -81,9 +104,11 @@
|
||||
[routerLink]="['/institution', institutionRouteId(), 'patents']"
|
||||
[class.disabled]="!institutionRouteId()"
|
||||
[attr.aria-disabled]="!institutionRouteId()"
|
||||
[attr.aria-label]="'Patente von ' + organizationName() + ' anzeigen'">
|
||||
[attr.aria-label]="'Patente von ' + organizationName() + ' anzeigen'"
|
||||
matTooltip="Anzahl der Patente im ausgewählten Zeitraum"
|
||||
matTooltipPosition="above">
|
||||
<div class="statistics-icon statistics-icon--patents">
|
||||
<mat-icon>description</mat-icon>
|
||||
<mat-icon>{{ patentIcon }}</mat-icon>
|
||||
</div>
|
||||
<div>
|
||||
<span>Patente</span>
|
||||
@@ -101,7 +126,9 @@
|
||||
class="statistics-card"
|
||||
routerLink="/projects"
|
||||
[queryParams]="{ selected_project_types: 'eu' }"
|
||||
aria-label="EU-Projekte anzeigen">
|
||||
aria-label="EU-Projekte anzeigen"
|
||||
matTooltip="Anzahl der laufenden, abgeschlossenen und kommenden EU-Projekte im ausgewählten Zeitraum"
|
||||
matTooltipPosition="above">
|
||||
<div class="statistics-icon statistics-icon--eu-projects">
|
||||
<mat-icon>public</mat-icon>
|
||||
</div>
|
||||
@@ -121,7 +148,9 @@
|
||||
class="statistics-card"
|
||||
routerLink="/projects"
|
||||
[queryParams]="{ selected_project_types: 'bund' }"
|
||||
aria-label="Bund-Projekte anzeigen">
|
||||
aria-label="Bund-Projekte anzeigen"
|
||||
matTooltip="Anzahl der laufenden, abgeschlossenen und kommenden Bund-Projekte im ausgewählten Zeitraum"
|
||||
matTooltipPosition="above">
|
||||
<div class="statistics-icon statistics-icon--bund-projects">
|
||||
<mat-icon>account_balance</mat-icon>
|
||||
</div>
|
||||
@@ -141,7 +170,9 @@
|
||||
class="statistics-card"
|
||||
routerLink="/projects"
|
||||
[queryParams]="{ selected_project_types: 'dfg' }"
|
||||
aria-label="DFG-Projekte anzeigen">
|
||||
aria-label="DFG-Projekte anzeigen"
|
||||
matTooltip="Anzahl der laufenden, abgeschlossenen und kommenden DFG-Projekte im ausgewählten Zeitraum"
|
||||
matTooltipPosition="above">
|
||||
<div class="statistics-icon statistics-icon--dfg-projects">
|
||||
<mat-icon>science</mat-icon>
|
||||
</div>
|
||||
@@ -162,6 +193,32 @@
|
||||
<p class="statistics-error">Die Kennzahlen konnten nicht geladen werden.</p>
|
||||
}
|
||||
|
||||
<section
|
||||
class="dashboard-institution-tabs"
|
||||
aria-label="Institutionen für Analysebereiche">
|
||||
<h2>Institution auswählen</h2>
|
||||
<div class="dashboard-institution-tab-list sg-tab-nav" role="tablist">
|
||||
@for (institution of dashboardInstitutions; track institution.id) {
|
||||
<button
|
||||
type="button"
|
||||
role="tab"
|
||||
[attr.aria-selected]="
|
||||
selectedAnalyticalInstitutionId === institution.id
|
||||
"
|
||||
[class.active]="selectedAnalyticalInstitutionId === institution.id"
|
||||
(click)="onAnalyticalInstitutionChange(institution.id)">
|
||||
{{ institution.display_name }}
|
||||
</button>
|
||||
}
|
||||
</div>
|
||||
@if (dashboardInstitutionsError) {
|
||||
<p class="statistics-error">
|
||||
Die Institutionen konnten nicht geladen werden.
|
||||
</p>
|
||||
}
|
||||
</section>
|
||||
|
||||
@if (selectedAnalyticalInstitutionId) {
|
||||
@if (
|
||||
euProjectStatusesLoading ||
|
||||
bmbfProjectStatusesLoading ||
|
||||
@@ -223,8 +280,8 @@
|
||||
diameter="64"></app-loading>
|
||||
</div>
|
||||
} @else if (
|
||||
euProjectStatusesError ||
|
||||
bmbfProjectStatusesError ||
|
||||
euProjectStatusesError &&
|
||||
bmbfProjectStatusesError &&
|
||||
dfgProjectStatusesError
|
||||
) {
|
||||
<p class="statistics-error">
|
||||
@@ -234,6 +291,17 @@
|
||||
} @else if (
|
||||
euProjectStatuses && bmbfProjectStatuses && dfgProjectStatuses
|
||||
) {
|
||||
@if (
|
||||
euProjectStatusesError ||
|
||||
bmbfProjectStatusesError ||
|
||||
dfgProjectStatusesError
|
||||
) {
|
||||
<p class="statistics-error">
|
||||
Projektstatusdaten für {{ failedProjectStatusSources() }} konnten
|
||||
nicht geladen werden. Die übrigen Daten werden weiterhin
|
||||
angezeigt.
|
||||
</p>
|
||||
}
|
||||
<app-eu-project-status-chart
|
||||
[statuses]="euProjectStatuses"
|
||||
[bmbfStatuses]="bmbfProjectStatuses"
|
||||
@@ -317,6 +385,92 @@
|
||||
</section>
|
||||
}
|
||||
|
||||
@if (euTopicsLoading || euTopicsError || euProjectTopics) {
|
||||
<section class="topic-heatmap-section">
|
||||
<header class="topic-heatmap-header">
|
||||
<div>
|
||||
<h2>EU-Projekt-Topics</h2>
|
||||
<p>
|
||||
Gematchte EU-Projekte nach Field, Subfield und Topic. Ein Klick
|
||||
auf ein Topic zeigt die zugehörigen Keywords.
|
||||
</p>
|
||||
</div>
|
||||
@if (euProjectTopics) {
|
||||
<p class="dfg-topic-summary">
|
||||
{{ euProjectTopics.matched_project_count | number }} von
|
||||
{{ euProjectTopics.project_count | number }} Projekten gematcht
|
||||
</p>
|
||||
}
|
||||
</header>
|
||||
|
||||
@if (euTopicsLoading) {
|
||||
<div class="topic-heatmap-loading" role="status" aria-live="polite">
|
||||
<app-loading
|
||||
text="EU-Topics werden geladen …"
|
||||
icon="account_tree"
|
||||
size="72"
|
||||
diameter="72"></app-loading>
|
||||
</div>
|
||||
} @else if (euTopicsError) {
|
||||
<p class="statistics-error">
|
||||
Die EU-Topic-Treemap konnte nicht geladen werden.
|
||||
</p>
|
||||
} @else {
|
||||
<app-topic-treemap
|
||||
[data]="euTopicTreemap"
|
||||
[selectedNodeId]="selectedEuTopicTreemapNode"
|
||||
countLabel="EU-Projekte"
|
||||
[showCountInTooltip]="false"
|
||||
(selectedNodeIdChange)="onEuTopicTreemapNodeChange($event)"
|
||||
(topicSelect)="onEuTopicTreemapTopicSelect($event)">
|
||||
</app-topic-treemap>
|
||||
}
|
||||
</section>
|
||||
}
|
||||
|
||||
@if (bundTopicsLoading || bundTopicsError || bundProjectTopics) {
|
||||
<section class="topic-heatmap-section">
|
||||
<header class="topic-heatmap-header">
|
||||
<div>
|
||||
<h2>BUND-Projekt-Topics</h2>
|
||||
<p>
|
||||
Gematchte BUND-Projekte nach Field, Subfield und Topic. Ein Klick
|
||||
auf ein Topic zeigt die zugehörigen Keywords.
|
||||
</p>
|
||||
</div>
|
||||
@if (bundProjectTopics) {
|
||||
<p class="dfg-topic-summary">
|
||||
{{ bundProjectTopics.matched_project_count | number }} von
|
||||
{{ bundProjectTopics.project_count | number }} Projekten gematcht
|
||||
</p>
|
||||
}
|
||||
</header>
|
||||
|
||||
@if (bundTopicsLoading) {
|
||||
<div class="topic-heatmap-loading" role="status" aria-live="polite">
|
||||
<app-loading
|
||||
text="BUND-Topics werden geladen …"
|
||||
icon="account_tree"
|
||||
size="72"
|
||||
diameter="72"></app-loading>
|
||||
</div>
|
||||
} @else if (bundTopicsError) {
|
||||
<p class="statistics-error">
|
||||
Die BUND-Topic-Treemap konnte nicht geladen werden.
|
||||
</p>
|
||||
} @else {
|
||||
<app-topic-treemap
|
||||
[data]="bundTopicTreemap"
|
||||
[selectedNodeId]="selectedBundTopicTreemapNode"
|
||||
countLabel="BUND-Projekte"
|
||||
[showCountInTooltip]="false"
|
||||
(selectedNodeIdChange)="onBundTopicTreemapNodeChange($event)"
|
||||
(topicSelect)="onBundTopicTreemapTopicSelect($event)">
|
||||
</app-topic-treemap>
|
||||
}
|
||||
</section>
|
||||
}
|
||||
|
||||
@if (topAuthorsLoading || topAuthorsError || hasTopAuthorData()) {
|
||||
<section class="top-authors-section">
|
||||
<header class="top-authors-header">
|
||||
@@ -355,6 +509,8 @@
|
||||
class="author-name author-link"
|
||||
[routerLink]="authorLink(dataset, entry)"
|
||||
[queryParams]="authorQueryParams(dataset, entry)"
|
||||
[appComponentTooltip]="AuthorTooltipComponent"
|
||||
[tooltipInputs]="{ authorId: entry.id }"
|
||||
[title]="authorDisplayName(dataset, entry)">
|
||||
{{ authorDisplayName(dataset, entry) }}
|
||||
</a>
|
||||
@@ -391,4 +547,5 @@
|
||||
}
|
||||
</section>
|
||||
}
|
||||
}
|
||||
</div>
|
||||
|
||||
@@ -39,7 +39,22 @@
|
||||
}
|
||||
|
||||
.dashboard-period-slider {
|
||||
width: min(100%, 34rem);
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
.statistics-grid {
|
||||
@@ -137,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;
|
||||
}
|
||||
|
||||
@@ -1,9 +1,15 @@
|
||||
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';
|
||||
import { MatDialog } from '@angular/material/dialog';
|
||||
import { ComponentTooltipDirective } from '../../directives/component-tooltip.directive';
|
||||
import { AppAuthorTooltipComponent } from '../../shared/ui/app-author-tooltip/app-author-tooltip.component';
|
||||
import { PATENT_ICON } from '../../shared/ui/icons';
|
||||
import { EuProjectStatusChartComponent } from './eu-project-status-chart/eu-project-status-chart.component';
|
||||
import { YearRangeSliderComponent } from '../../shared/ui/year-range-slider/year-range-slider.component';
|
||||
import { LoadingComponent } from '../../shared/ui/loading/loading.component';
|
||||
@@ -18,6 +24,8 @@ import {
|
||||
} from './topic-wordcloud-dialog/topic-wordcloud-dialog.component';
|
||||
import {
|
||||
BmbfProjectStatusStatistics,
|
||||
BundProjectTopics,
|
||||
DashboardInstitution,
|
||||
DashboardPeriodBounds,
|
||||
DashboardStatisticValue,
|
||||
DashboardStatistics,
|
||||
@@ -26,6 +34,7 @@ import {
|
||||
DfgProjectTopic,
|
||||
DfgProjectTopics,
|
||||
EuProjectStatusStatistics,
|
||||
EuProjectTopics,
|
||||
TopAuthor,
|
||||
TopAuthorStatistics,
|
||||
} from './dashboard-statistics.service';
|
||||
@@ -55,7 +64,11 @@ type DashboardPeriodMode =
|
||||
selector: 'dashboard',
|
||||
imports: [
|
||||
DecimalPipe,
|
||||
MatFormFieldModule,
|
||||
MatIconModule,
|
||||
MatSelectModule,
|
||||
MatTooltipModule,
|
||||
ComponentTooltipDirective,
|
||||
RouterLink,
|
||||
LoadingComponent,
|
||||
EuProjectStatusChartComponent,
|
||||
@@ -66,6 +79,8 @@ type DashboardPeriodMode =
|
||||
styleUrl: './dashboard.component.scss',
|
||||
})
|
||||
export class DashboardComponent implements OnInit {
|
||||
readonly AuthorTooltipComponent = AppAuthorTooltipComponent;
|
||||
readonly patentIcon = PATENT_ICON;
|
||||
statistics?: Partial<DashboardStatistics>;
|
||||
statisticsLoading = false;
|
||||
statisticsError = false;
|
||||
@@ -96,6 +111,14 @@ export class DashboardComponent implements OnInit {
|
||||
dfgTopicTreemap?: TopicTreemapData;
|
||||
dfgTopicsLoading = false;
|
||||
dfgTopicsError = false;
|
||||
euProjectTopics?: EuProjectTopics;
|
||||
euTopicTreemap?: TopicTreemapData;
|
||||
euTopicsLoading = false;
|
||||
euTopicsError = false;
|
||||
bundProjectTopics?: BundProjectTopics;
|
||||
bundTopicTreemap?: TopicTreemapData;
|
||||
bundTopicsLoading = false;
|
||||
bundTopicsError = false;
|
||||
euProjectStatuses?: EuProjectStatusStatistics;
|
||||
euProjectStatusesLoading = false;
|
||||
euProjectStatusesError = false;
|
||||
@@ -108,12 +131,20 @@ export class DashboardComponent implements OnInit {
|
||||
readonly topicTreemapMinYear = 1900;
|
||||
readonly topicTreemapMaxYear = new Date().getFullYear();
|
||||
dashboardPeriodMode: DashboardPeriodMode = 'all_time';
|
||||
dashboardFromYear = this.topicTreemapMaxYear - 4;
|
||||
dashboardFromYear = this.topicTreemapMinYear;
|
||||
dashboardToYear = this.topicTreemapMaxYear;
|
||||
dashboardInstitutions: DashboardInstitution[] = [];
|
||||
selectedDashboardInstitutionId = 'all';
|
||||
selectedAnalyticalInstitutionId = '';
|
||||
dashboardInstitutionsLoading = false;
|
||||
dashboardInstitutionsError = false;
|
||||
selectedTopicTreemapNode?: string;
|
||||
selectedDfgTopicTreemapNode?: string;
|
||||
selectedEuTopicTreemapNode?: string;
|
||||
selectedBundTopicTreemapNode?: string;
|
||||
private topicTreemapReloadQueued = false;
|
||||
private topicTreemapRequestId = 0;
|
||||
private analyticalRequestId = 0;
|
||||
|
||||
constructor(
|
||||
private statisticsService: DashboardStatisticsService,
|
||||
@@ -124,41 +155,73 @@ export class DashboardComponent implements OnInit {
|
||||
|
||||
ngOnInit() {
|
||||
this.restoreDashboardPeriodState();
|
||||
this.loadDashboardInstitutions();
|
||||
this.loadStatistics();
|
||||
this.loadTopAuthors();
|
||||
this.loadTopicTreemap();
|
||||
this.loadDfgProjectTopics();
|
||||
this.loadEuProjectStatuses();
|
||||
this.loadBmbfProjectStatuses();
|
||||
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();
|
||||
}
|
||||
const restoredAnalyticalInstitution =
|
||||
restoredInstitution === 'all' ? '' : restoredInstitution;
|
||||
if (
|
||||
restoredAnalyticalInstitution !== this.selectedAnalyticalInstitutionId
|
||||
) {
|
||||
this.selectedAnalyticalInstitutionId = restoredAnalyticalInstitution;
|
||||
this.reloadAnalyticalData();
|
||||
}
|
||||
},
|
||||
error: () => {
|
||||
this.dashboardInstitutions = [];
|
||||
this.dashboardInstitutionsError = true;
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
private loadStatistics(): void {
|
||||
this.statisticsError = false;
|
||||
const period = this.selectedPeriodBounds();
|
||||
const institutionId = this.selectedDashboardInstitutionId;
|
||||
this.loadStatistic(
|
||||
'publications',
|
||||
this.statisticsService.getPublicationCount(period),
|
||||
this.statisticsService.getPublicationCount(period, institutionId),
|
||||
);
|
||||
this.loadStatistic(
|
||||
'persons',
|
||||
this.statisticsService.getPersonCount(period),
|
||||
this.statisticsService.getPersonCount(period, institutionId),
|
||||
);
|
||||
this.loadStatistic(
|
||||
'patents',
|
||||
this.statisticsService.getPatentCount(period),
|
||||
this.statisticsService.getPatentCount(period, institutionId),
|
||||
);
|
||||
this.loadStatistic(
|
||||
'eu_projects',
|
||||
this.statisticsService.getEuProjectCount(period),
|
||||
this.statisticsService.getEuProjectCount(period, institutionId),
|
||||
);
|
||||
this.loadStatistic(
|
||||
'bmbf_projects',
|
||||
this.statisticsService.getBmbfProjectCount(period),
|
||||
this.statisticsService.getBmbfProjectCount(period, institutionId),
|
||||
);
|
||||
this.loadStatistic(
|
||||
'dfg_projects',
|
||||
this.statisticsService.getDfgProjectCount(period),
|
||||
this.statisticsService.getDfgProjectCount(period, institutionId),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -245,10 +308,12 @@ export class DashboardComponent implements OnInit {
|
||||
([subfieldName, group]) => ({
|
||||
id: `${fieldName}::${subfieldName}`,
|
||||
name: subfieldName,
|
||||
total: group.topics.reduce(
|
||||
(sum, topic) => sum + topic.project_count,
|
||||
0,
|
||||
),
|
||||
total:
|
||||
group.topics[0]?.subfield_project_count ??
|
||||
group.topics.reduce(
|
||||
(sum, topic) => sum + topic.project_count,
|
||||
0,
|
||||
),
|
||||
values: [],
|
||||
topics: group.topics.map((topic) => ({
|
||||
id: topic.id,
|
||||
@@ -261,10 +326,12 @@ export class DashboardComponent implements OnInit {
|
||||
return {
|
||||
id: fieldName,
|
||||
name: fieldName,
|
||||
total: mappedSubfields.reduce(
|
||||
(sum, subfield) => sum + subfield.total,
|
||||
0,
|
||||
),
|
||||
total:
|
||||
[...subfields.values()][0]?.topics[0]?.field_project_count ??
|
||||
mappedSubfields.reduce(
|
||||
(sum, subfield) => sum + subfield.total,
|
||||
0,
|
||||
),
|
||||
values: [],
|
||||
subfields: mappedSubfields,
|
||||
};
|
||||
@@ -314,11 +381,22 @@ export class DashboardComponent implements OnInit {
|
||||
}
|
||||
|
||||
institutionRouteId(): string {
|
||||
return (
|
||||
this.statistics?.institution_id?.replace('https://openalex.org/', '') ??
|
||||
this.topAuthors?.institution_id?.replace('https://openalex.org/', '') ??
|
||||
''
|
||||
const selectedInstitutionId = this.routeableInstitutionId(
|
||||
this.selectedDashboardInstitutionId,
|
||||
);
|
||||
if (selectedInstitutionId) return selectedInstitutionId;
|
||||
|
||||
return this.routeableInstitutionId(this.dashboardInstitutions[0]?.id) ?? '';
|
||||
}
|
||||
|
||||
private routeableInstitutionId(institutionId?: string | null): string | null {
|
||||
const normalizedInstitutionId = institutionId
|
||||
?.replace('https://openalex.org/', '')
|
||||
.trim();
|
||||
|
||||
return normalizedInstitutionId && normalizedInstitutionId !== 'all'
|
||||
? normalizedInstitutionId
|
||||
: null;
|
||||
}
|
||||
|
||||
personListQueryParams(): PersonListQueryParams {
|
||||
@@ -345,6 +423,41 @@ export class DashboardComponent implements OnInit {
|
||||
});
|
||||
}
|
||||
|
||||
onDashboardInstitutionChange(institutionId: string): void {
|
||||
this.selectedDashboardInstitutionId = institutionId;
|
||||
const analyticalInstitutionId =
|
||||
institutionId === 'all' ? '' : institutionId;
|
||||
const analyticalInstitutionChanged =
|
||||
analyticalInstitutionId !== this.selectedAnalyticalInstitutionId;
|
||||
this.selectedAnalyticalInstitutionId = analyticalInstitutionId;
|
||||
this.updateDashboardPeriodUrl();
|
||||
this.loadStatistics();
|
||||
if (analyticalInstitutionChanged) {
|
||||
if (analyticalInstitutionId) {
|
||||
this.reloadAnalyticalData();
|
||||
} else {
|
||||
// Invalidate pending requests when "Alle Institutionen" is selected.
|
||||
this.analyticalRequestId += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
onAnalyticalInstitutionChange(institutionId: string): void {
|
||||
if (institutionId === this.selectedAnalyticalInstitutionId) return;
|
||||
this.selectedAnalyticalInstitutionId = institutionId;
|
||||
this.updateDashboardPeriodUrl();
|
||||
this.reloadAnalyticalData();
|
||||
}
|
||||
|
||||
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();
|
||||
@@ -352,6 +465,7 @@ export class DashboardComponent implements OnInit {
|
||||
|
||||
onDfgTopicTreemapNodeChange(nodeId: string | undefined): void {
|
||||
this.selectedDfgTopicTreemapNode = nodeId;
|
||||
this.updateDashboardPeriodUrl();
|
||||
}
|
||||
|
||||
onDfgTopicTreemapTopicSelect(topic: TopicTreemapTopicSelect): void {
|
||||
@@ -378,6 +492,64 @@ export class DashboardComponent implements OnInit {
|
||||
);
|
||||
}
|
||||
|
||||
onEuTopicTreemapNodeChange(nodeId: string | undefined): void {
|
||||
this.selectedEuTopicTreemapNode = nodeId;
|
||||
this.updateDashboardPeriodUrl();
|
||||
}
|
||||
|
||||
onEuTopicTreemapTopicSelect(topic: TopicTreemapTopicSelect): void {
|
||||
const euTopic = this.euProjectTopics?.topics.find(
|
||||
(entry) => entry.id === topic.topicId,
|
||||
);
|
||||
if (!euTopic) return;
|
||||
|
||||
this.dialog.open<TopicWordCloudDialogComponent, TopicWordCloudDialogData>(
|
||||
TopicWordCloudDialogComponent,
|
||||
{
|
||||
width: '85vw',
|
||||
maxWidth: '92vw',
|
||||
data: {
|
||||
...topic,
|
||||
source: 'eu',
|
||||
words: euTopic.keywords.map((keyword) => ({
|
||||
id: keyword.name,
|
||||
name: keyword.name,
|
||||
count: keyword.project_count,
|
||||
})),
|
||||
},
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
onBundTopicTreemapNodeChange(nodeId: string | undefined): void {
|
||||
this.selectedBundTopicTreemapNode = nodeId;
|
||||
this.updateDashboardPeriodUrl();
|
||||
}
|
||||
|
||||
onBundTopicTreemapTopicSelect(topic: TopicTreemapTopicSelect): void {
|
||||
const bundTopic = this.bundProjectTopics?.topics.find(
|
||||
(entry) => entry.id === topic.topicId,
|
||||
);
|
||||
if (!bundTopic) return;
|
||||
|
||||
this.dialog.open<TopicWordCloudDialogComponent, TopicWordCloudDialogData>(
|
||||
TopicWordCloudDialogComponent,
|
||||
{
|
||||
width: '85vw',
|
||||
maxWidth: '92vw',
|
||||
data: {
|
||||
...topic,
|
||||
source: 'bund',
|
||||
words: bundTopic.keywords.map((keyword) => ({
|
||||
id: keyword.name,
|
||||
name: keyword.name,
|
||||
count: keyword.project_count,
|
||||
})),
|
||||
},
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
onTopicTreemapTopicSelect(topic: TopicTreemapTopicSelect): void {
|
||||
const period = this.selectedPeriodBounds();
|
||||
this.dialog.open<TopicWordCloudDialogComponent, TopicWordCloudDialogData>(
|
||||
@@ -389,6 +561,7 @@ export class DashboardComponent implements OnInit {
|
||||
...topic,
|
||||
fromYear: period.fromYear,
|
||||
toYear: period.toYear,
|
||||
institutionId: this.selectedAnalyticalInstitutionId,
|
||||
},
|
||||
},
|
||||
);
|
||||
@@ -406,23 +579,34 @@ export class DashboardComponent implements OnInit {
|
||||
this.dashboardPeriodMode = mode;
|
||||
}
|
||||
this.applyPresetPeriod();
|
||||
this.dashboardFromYear = this.parseDashboardYear(
|
||||
params.get('fromYear'),
|
||||
this.dashboardFromYear,
|
||||
);
|
||||
this.dashboardToYear = this.parseDashboardYear(
|
||||
params.get('toYear'),
|
||||
this.dashboardToYear,
|
||||
);
|
||||
if (this.dashboardPeriodMode !== 'all_time') {
|
||||
this.dashboardFromYear = this.parseDashboardYear(
|
||||
params.get('fromYear'),
|
||||
this.dashboardFromYear,
|
||||
);
|
||||
this.dashboardToYear = this.parseDashboardYear(
|
||||
params.get('toYear'),
|
||||
this.dashboardToYear,
|
||||
);
|
||||
}
|
||||
if (this.dashboardFromYear > this.dashboardToYear) {
|
||||
this.dashboardFromYear = this.dashboardToYear;
|
||||
}
|
||||
this.selectedTopicTreemapNode = params.get('treemapNode') ?? undefined;
|
||||
this.selectedDfgTopicTreemapNode =
|
||||
params.get('dfgTreemapNode') ?? undefined;
|
||||
this.selectedEuTopicTreemapNode =
|
||||
params.get('euTreemapNode') ?? undefined;
|
||||
this.selectedBundTopicTreemapNode =
|
||||
params.get('bundTreemapNode') ?? undefined;
|
||||
}
|
||||
|
||||
private applyPresetPeriod(): void {
|
||||
const currentYear = this.topicTreemapMaxYear;
|
||||
if (this.dashboardPeriodMode === 'last_10_years') {
|
||||
if (this.dashboardPeriodMode === 'all_time') {
|
||||
this.dashboardFromYear = this.topicTreemapMinYear;
|
||||
this.dashboardToYear = currentYear;
|
||||
} else if (this.dashboardPeriodMode === 'last_10_years') {
|
||||
this.dashboardFromYear = currentYear - 9;
|
||||
this.dashboardToYear = currentYear;
|
||||
} else if (this.dashboardPeriodMode === 'last_5_years') {
|
||||
@@ -440,6 +624,11 @@ export class DashboardComponent implements OnInit {
|
||||
fromYear: period.fromYear ?? null,
|
||||
toYear: period.toYear ?? null,
|
||||
treemapNode: this.selectedTopicTreemapNode ?? null,
|
||||
dfgTreemapNode: this.selectedDfgTopicTreemapNode ?? null,
|
||||
euTreemapNode: this.selectedEuTopicTreemapNode ?? null,
|
||||
bundTreemapNode: this.selectedBundTopicTreemapNode ?? null,
|
||||
institution: this.selectedDashboardInstitutionId,
|
||||
analyticalInstitution: this.selectedAnalyticalInstitutionId || null,
|
||||
},
|
||||
queryParamsHandling: 'merge',
|
||||
replaceUrl: true,
|
||||
@@ -466,12 +655,23 @@ export class DashboardComponent implements OnInit {
|
||||
|
||||
private reloadPeriodData(): void {
|
||||
this.loadStatistics();
|
||||
this.loadTopAuthors();
|
||||
this.loadTopicTreemap();
|
||||
this.loadDfgProjectTopics();
|
||||
this.loadEuProjectStatuses();
|
||||
this.loadBmbfProjectStatuses();
|
||||
this.loadDfgProjectStatuses();
|
||||
this.reloadAnalyticalData();
|
||||
}
|
||||
|
||||
private reloadAnalyticalData(): void {
|
||||
if (!this.selectedAnalyticalInstitutionId) return;
|
||||
const requestId = ++this.analyticalRequestId;
|
||||
this.euProjectStatuses = undefined;
|
||||
this.bmbfProjectStatuses = undefined;
|
||||
this.dfgProjectStatuses = undefined;
|
||||
this.loadTopAuthors(requestId);
|
||||
this.loadTopicTreemap(requestId);
|
||||
this.loadDfgProjectTopics(requestId);
|
||||
this.loadEuProjectTopics(requestId);
|
||||
this.loadBundProjectTopics(requestId);
|
||||
this.loadEuProjectStatuses(requestId);
|
||||
this.loadBmbfProjectStatuses(requestId);
|
||||
this.loadDfgProjectStatuses(requestId);
|
||||
}
|
||||
|
||||
private loadStatistic(
|
||||
@@ -519,115 +719,269 @@ export class DashboardComponent implements OnInit {
|
||||
this.statistics = nextStatistics;
|
||||
}
|
||||
|
||||
private loadTopAuthors(): void {
|
||||
private loadTopAuthors(requestId = this.analyticalRequestId): void {
|
||||
this.topAuthorsLoading = true;
|
||||
this.topAuthorsError = false;
|
||||
this.statisticsService
|
||||
.getTopAuthors(this.selectedPeriodBounds())
|
||||
.pipe(finalize(() => (this.topAuthorsLoading = false)))
|
||||
.getTopAuthors(
|
||||
this.selectedPeriodBounds(),
|
||||
this.selectedAnalyticalInstitutionId,
|
||||
)
|
||||
.pipe(
|
||||
finalize(() => {
|
||||
if (requestId === this.analyticalRequestId) {
|
||||
this.topAuthorsLoading = false;
|
||||
}
|
||||
}),
|
||||
)
|
||||
.subscribe({
|
||||
next: (statistics) => {
|
||||
this.topAuthors = statistics;
|
||||
if (requestId === this.analyticalRequestId) {
|
||||
this.topAuthors = statistics;
|
||||
}
|
||||
},
|
||||
error: () => {
|
||||
this.topAuthorsError = true;
|
||||
if (requestId === this.analyticalRequestId) {
|
||||
this.topAuthorsError = true;
|
||||
}
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
private loadDfgProjectTopics(): void {
|
||||
private loadDfgProjectTopics(requestId = this.analyticalRequestId): void {
|
||||
this.dfgTopicsLoading = true;
|
||||
this.dfgTopicsError = false;
|
||||
this.statisticsService
|
||||
.getDfgProjectTopics(this.selectedPeriodBounds())
|
||||
.pipe(finalize(() => (this.dfgTopicsLoading = false)))
|
||||
.getDfgProjectTopics(
|
||||
this.selectedPeriodBounds(),
|
||||
this.selectedAnalyticalInstitutionId,
|
||||
)
|
||||
.pipe(
|
||||
finalize(() => {
|
||||
if (requestId === this.analyticalRequestId) {
|
||||
this.dfgTopicsLoading = false;
|
||||
}
|
||||
}),
|
||||
)
|
||||
.subscribe({
|
||||
next: (topics) => {
|
||||
this.dfgProjectTopics = topics;
|
||||
this.dfgTopicTreemap = this.buildDfgTopicTreemapData(topics);
|
||||
if (requestId === this.analyticalRequestId) {
|
||||
this.dfgProjectTopics = topics;
|
||||
this.dfgTopicTreemap = this.buildDfgTopicTreemapData(topics);
|
||||
}
|
||||
},
|
||||
error: () => {
|
||||
this.dfgTopicsError = true;
|
||||
if (requestId === this.analyticalRequestId) {
|
||||
this.dfgTopicsError = true;
|
||||
}
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
private loadEuProjectStatuses(): void {
|
||||
private loadEuProjectTopics(requestId = this.analyticalRequestId): void {
|
||||
this.euTopicsLoading = true;
|
||||
this.euTopicsError = false;
|
||||
this.statisticsService
|
||||
.getEuProjectTopics(
|
||||
this.selectedPeriodBounds(),
|
||||
this.selectedAnalyticalInstitutionId,
|
||||
)
|
||||
.pipe(
|
||||
finalize(() => {
|
||||
if (requestId === this.analyticalRequestId) {
|
||||
this.euTopicsLoading = false;
|
||||
}
|
||||
}),
|
||||
)
|
||||
.subscribe({
|
||||
next: (topics) => {
|
||||
if (requestId === this.analyticalRequestId) {
|
||||
this.euProjectTopics = topics;
|
||||
this.euTopicTreemap = this.buildDfgTopicTreemapData(topics);
|
||||
}
|
||||
},
|
||||
error: () => {
|
||||
if (requestId === this.analyticalRequestId) {
|
||||
this.euTopicsError = true;
|
||||
}
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
private loadBundProjectTopics(requestId = this.analyticalRequestId): void {
|
||||
this.bundTopicsLoading = true;
|
||||
this.bundTopicsError = false;
|
||||
this.statisticsService
|
||||
.getBundProjectTopics(
|
||||
this.selectedPeriodBounds(),
|
||||
this.selectedAnalyticalInstitutionId,
|
||||
)
|
||||
.pipe(
|
||||
finalize(() => {
|
||||
if (requestId === this.analyticalRequestId) {
|
||||
this.bundTopicsLoading = false;
|
||||
}
|
||||
}),
|
||||
)
|
||||
.subscribe({
|
||||
next: (topics) => {
|
||||
if (requestId === this.analyticalRequestId) {
|
||||
this.bundProjectTopics = topics;
|
||||
this.bundTopicTreemap = this.buildDfgTopicTreemapData(topics);
|
||||
}
|
||||
},
|
||||
error: () => {
|
||||
if (requestId === this.analyticalRequestId) {
|
||||
this.bundTopicsError = true;
|
||||
}
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
private loadEuProjectStatuses(requestId = this.analyticalRequestId): void {
|
||||
this.euProjectStatusesLoading = true;
|
||||
this.euProjectStatusesError = false;
|
||||
this.statisticsService
|
||||
.getEuProjectStatuses(this.selectedPeriodBounds())
|
||||
.pipe(finalize(() => (this.euProjectStatusesLoading = false)))
|
||||
.getEuProjectStatuses(
|
||||
this.selectedPeriodBounds(),
|
||||
this.selectedAnalyticalInstitutionId,
|
||||
)
|
||||
.pipe(
|
||||
finalize(() => {
|
||||
if (requestId === this.analyticalRequestId) {
|
||||
this.euProjectStatusesLoading = false;
|
||||
}
|
||||
}),
|
||||
)
|
||||
.subscribe({
|
||||
next: (statuses) => {
|
||||
this.euProjectStatuses = statuses;
|
||||
if (requestId === this.analyticalRequestId) {
|
||||
this.euProjectStatuses = statuses;
|
||||
}
|
||||
},
|
||||
error: () => {
|
||||
this.euProjectStatusesError = true;
|
||||
if (requestId === this.analyticalRequestId) {
|
||||
this.euProjectStatusesError = true;
|
||||
this.euProjectStatuses = this.emptyProjectStatuses();
|
||||
}
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
private loadBmbfProjectStatuses(): void {
|
||||
private loadBmbfProjectStatuses(requestId = this.analyticalRequestId): void {
|
||||
this.bmbfProjectStatusesLoading = true;
|
||||
this.bmbfProjectStatusesError = false;
|
||||
this.statisticsService
|
||||
.getBmbfProjectStatuses(this.selectedPeriodBounds())
|
||||
.pipe(finalize(() => (this.bmbfProjectStatusesLoading = false)))
|
||||
.getBmbfProjectStatuses(
|
||||
this.selectedPeriodBounds(),
|
||||
this.selectedAnalyticalInstitutionId,
|
||||
)
|
||||
.pipe(
|
||||
finalize(() => {
|
||||
if (requestId === this.analyticalRequestId) {
|
||||
this.bmbfProjectStatusesLoading = false;
|
||||
}
|
||||
}),
|
||||
)
|
||||
.subscribe({
|
||||
next: (statuses) => {
|
||||
this.bmbfProjectStatuses = statuses;
|
||||
if (requestId === this.analyticalRequestId) {
|
||||
this.bmbfProjectStatuses = statuses;
|
||||
}
|
||||
},
|
||||
error: () => {
|
||||
this.bmbfProjectStatusesError = true;
|
||||
if (requestId === this.analyticalRequestId) {
|
||||
this.bmbfProjectStatusesError = true;
|
||||
this.bmbfProjectStatuses = this.emptyProjectStatuses();
|
||||
}
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
private loadDfgProjectStatuses(): void {
|
||||
private loadDfgProjectStatuses(requestId = this.analyticalRequestId): void {
|
||||
this.dfgProjectStatusesLoading = true;
|
||||
this.dfgProjectStatusesError = false;
|
||||
this.statisticsService
|
||||
.getDfgProjectStatuses(this.selectedPeriodBounds())
|
||||
.pipe(finalize(() => (this.dfgProjectStatusesLoading = false)))
|
||||
.getDfgProjectStatuses(
|
||||
this.selectedPeriodBounds(),
|
||||
this.selectedAnalyticalInstitutionId,
|
||||
)
|
||||
.pipe(
|
||||
finalize(() => {
|
||||
if (requestId === this.analyticalRequestId) {
|
||||
this.dfgProjectStatusesLoading = false;
|
||||
}
|
||||
}),
|
||||
)
|
||||
.subscribe({
|
||||
next: (statuses) => {
|
||||
this.dfgProjectStatuses = statuses;
|
||||
if (requestId === this.analyticalRequestId) {
|
||||
this.dfgProjectStatuses = statuses;
|
||||
}
|
||||
},
|
||||
error: () => {
|
||||
this.dfgProjectStatusesError = true;
|
||||
if (requestId === this.analyticalRequestId) {
|
||||
this.dfgProjectStatusesError = true;
|
||||
this.dfgProjectStatuses = this.emptyProjectStatuses();
|
||||
}
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
private loadTopicTreemap(): void {
|
||||
private emptyProjectStatuses(): EuProjectStatusStatistics {
|
||||
const institution = this.dashboardInstitutions.find(
|
||||
({ id }) => id === this.selectedAnalyticalInstitutionId,
|
||||
);
|
||||
return {
|
||||
institution_id: this.selectedAnalyticalInstitutionId,
|
||||
organization_name: institution?.display_name ?? '',
|
||||
ongoing: 0,
|
||||
upcoming: 0,
|
||||
completed: 0,
|
||||
};
|
||||
}
|
||||
|
||||
private loadTopicTreemap(analyticalRequestId = this.analyticalRequestId): void {
|
||||
if (this.dashboardFromYear > this.dashboardToYear) {
|
||||
this.topicTreemapLoading = false;
|
||||
this.topicTreemapError = true;
|
||||
return;
|
||||
}
|
||||
|
||||
const requestId = ++this.topicTreemapRequestId;
|
||||
const treemapRequestId = ++this.topicTreemapRequestId;
|
||||
const period = this.selectedPeriodBounds();
|
||||
this.topicTreemapLoading = true;
|
||||
this.topicTreemapError = false;
|
||||
this.statisticsService
|
||||
.getTopicTreemap(period.fromYear, period.toYear)
|
||||
.getTopicTreemap(
|
||||
period.fromYear,
|
||||
period.toYear,
|
||||
this.selectedAnalyticalInstitutionId,
|
||||
)
|
||||
.pipe(
|
||||
finalize(() => {
|
||||
if (requestId === this.topicTreemapRequestId) {
|
||||
if (
|
||||
analyticalRequestId === this.analyticalRequestId &&
|
||||
treemapRequestId === this.topicTreemapRequestId
|
||||
) {
|
||||
this.topicTreemapLoading = false;
|
||||
}
|
||||
}),
|
||||
)
|
||||
.subscribe({
|
||||
next: (treemap) => {
|
||||
if (requestId === this.topicTreemapRequestId) {
|
||||
if (
|
||||
analyticalRequestId === this.analyticalRequestId &&
|
||||
treemapRequestId === this.topicTreemapRequestId
|
||||
) {
|
||||
this.topicTreemap = treemap;
|
||||
}
|
||||
},
|
||||
error: () => {
|
||||
if (requestId === this.topicTreemapRequestId) {
|
||||
if (
|
||||
analyticalRequestId === this.analyticalRequestId &&
|
||||
treemapRequestId === this.topicTreemapRequestId
|
||||
) {
|
||||
this.topicTreemapError = true;
|
||||
}
|
||||
},
|
||||
|
||||
+3
-1
@@ -22,8 +22,9 @@ export interface TopicWordCloudDialogData {
|
||||
subfieldName?: string;
|
||||
fromYear?: number;
|
||||
toYear?: number;
|
||||
institutionId?: string;
|
||||
words?: TopicWordCloudWord[];
|
||||
source?: 'publications' | 'dfg';
|
||||
source?: 'publications' | 'dfg' | 'eu' | 'bund';
|
||||
}
|
||||
|
||||
interface DisplayWord extends TopicWordCloudWord {
|
||||
@@ -82,6 +83,7 @@ export class TopicWordCloudDialogComponent {
|
||||
this.data.topicId,
|
||||
this.data.fromYear,
|
||||
this.data.toYear,
|
||||
this.data.institutionId,
|
||||
)
|
||||
.pipe(takeUntilDestroyed(this.destroyRef))
|
||||
.subscribe({
|
||||
|
||||
+65
@@ -0,0 +1,65 @@
|
||||
import { Component, inject } from '@angular/core';
|
||||
import { MatButtonModule } from '@angular/material/button';
|
||||
import {
|
||||
MAT_DIALOG_DATA,
|
||||
MatDialogActions,
|
||||
MatDialogContent,
|
||||
MatDialogRef,
|
||||
MatDialogTitle,
|
||||
} from '@angular/material/dialog';
|
||||
|
||||
@Component({
|
||||
selector: 'app-institution-removal-dialog',
|
||||
standalone: true,
|
||||
imports: [
|
||||
MatButtonModule,
|
||||
MatDialogActions,
|
||||
MatDialogContent,
|
||||
MatDialogTitle,
|
||||
],
|
||||
template: `
|
||||
<h3 mat-dialog-title>Manuelle Auswahl entfernen</h3>
|
||||
<mat-dialog-content>
|
||||
<p>
|
||||
Möchtest du die manuelle Auswahl der Institution „{{
|
||||
data.institutionName
|
||||
}}“ wirklich entfernen?
|
||||
</p>
|
||||
@if (data.dependentCount === 1) {
|
||||
<p>
|
||||
Dadurch wird außerdem 1 automatisch zugeordnete Institution aus der
|
||||
Organisation entfernt.
|
||||
</p>
|
||||
} @else if (data.dependentCount > 1) {
|
||||
<p>
|
||||
Dadurch werden außerdem {{ data.dependentCount }} automatisch
|
||||
zugeordnete Institutionen aus der Organisation entfernt.
|
||||
</p>
|
||||
}
|
||||
</mat-dialog-content>
|
||||
<mat-dialog-actions align="end">
|
||||
<button mat-button type="button" (click)="close()">Abbrechen</button>
|
||||
<button mat-flat-button color="primary" type="button" (click)="confirm()">
|
||||
Entfernen
|
||||
</button>
|
||||
</mat-dialog-actions>
|
||||
`,
|
||||
})
|
||||
export class InstitutionRemovalDialogComponent {
|
||||
private readonly dialogRef =
|
||||
inject<MatDialogRef<InstitutionRemovalDialogComponent, boolean>>(
|
||||
MatDialogRef,
|
||||
);
|
||||
protected readonly data = inject<{
|
||||
institutionName: string;
|
||||
dependentCount: number;
|
||||
}>(MAT_DIALOG_DATA);
|
||||
|
||||
protected close(): void {
|
||||
this.dialogRef.close(false);
|
||||
}
|
||||
|
||||
protected confirm(): void {
|
||||
this.dialogRef.close(true);
|
||||
}
|
||||
}
|
||||
+85
-5
@@ -16,10 +16,85 @@
|
||||
}
|
||||
</mat-form-field>
|
||||
|
||||
<mat-form-field appearance="outline">
|
||||
<mat-label>Externe Institutions-ID</mat-label>
|
||||
<input matInput formControlName="otherInstId" />
|
||||
</mat-form-field>
|
||||
<section class="institution-section">
|
||||
<div class="section-heading">
|
||||
<div>
|
||||
<h3>OpenAlex-Institutionen</h3>
|
||||
<p>
|
||||
Bei der Auswahl werden untergeordnete und verbundene Institutionen
|
||||
automatisch ergänzt.
|
||||
</p>
|
||||
</div>
|
||||
@if (isLoadingAssociations()) {
|
||||
<mat-spinner diameter="24" />
|
||||
}
|
||||
</div>
|
||||
|
||||
<mat-form-field appearance="outline" subscriptSizing="dynamic">
|
||||
<mat-label>Institution hinzufügen</mat-label>
|
||||
<mat-icon matPrefix>search</mat-icon>
|
||||
<input
|
||||
matInput
|
||||
type="text"
|
||||
placeholder="Name der Institution eingeben"
|
||||
[formControl]="institutionSearch"
|
||||
[matAutocomplete]="institutionAutocomplete"
|
||||
[readonly]="isLoadingAssociations()" />
|
||||
@if (isSearchingInstitutions()) {
|
||||
<mat-spinner matSuffix diameter="20" />
|
||||
}
|
||||
<mat-autocomplete
|
||||
#institutionAutocomplete="matAutocomplete"
|
||||
[displayWith]="displayInstitution"
|
||||
(optionSelected)="selectAutocompleteInstitution($event)">
|
||||
@for (
|
||||
institution of institutionSearchResults();
|
||||
track institution.id
|
||||
) {
|
||||
<mat-option [value]="institution">
|
||||
<span>{{ institution.display_name }}</span>
|
||||
<small class="autocomplete-description">
|
||||
{{ institution.country_code }} · {{ institution.type }}
|
||||
</small>
|
||||
</mat-option>
|
||||
}
|
||||
</mat-autocomplete>
|
||||
</mat-form-field>
|
||||
|
||||
<div class="institution-list" aria-live="polite">
|
||||
@for (entry of institutions(); track entry.id) {
|
||||
<article class="institution-item">
|
||||
<mat-icon class="institution-icon">apartment</mat-icon>
|
||||
<div class="institution-details">
|
||||
<strong>{{ entry.institution.display_name }}</strong>
|
||||
<span class="institution-id">{{ entry.id }}</span>
|
||||
<div class="origin-labels">
|
||||
@for (label of originLabels(entry); track label.relationship) {
|
||||
<span
|
||||
class="origin-label"
|
||||
[matTooltip]="label.tooltip ?? ''"
|
||||
[matTooltipDisabled]="!label.tooltip"
|
||||
matTooltipClass="institution-origin-tooltip">
|
||||
{{ label.label }}
|
||||
</span>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
@if (entry.manuallySelected) {
|
||||
<button
|
||||
mat-icon-button
|
||||
type="button"
|
||||
aria-label="Manuelle Auswahl entfernen"
|
||||
(click)="removeInstitution(entry)">
|
||||
<mat-icon>close</mat-icon>
|
||||
</button>
|
||||
}
|
||||
</article>
|
||||
} @empty {
|
||||
<p class="empty-institutions">Noch keine Institution ausgewählt.</p>
|
||||
}
|
||||
</div>
|
||||
</section>
|
||||
|
||||
@if (data.mode === 'edit') {
|
||||
<mat-checkbox formControlName="deleted">
|
||||
@@ -31,7 +106,12 @@
|
||||
|
||||
<mat-dialog-actions align="end">
|
||||
<button mat-button type="button" (click)="close()">Abbrechen</button>
|
||||
<button mat-flat-button color="primary" type="button" (click)="submit()">
|
||||
<button
|
||||
mat-flat-button
|
||||
color="primary"
|
||||
type="button"
|
||||
[disabled]="isLoadingAssociations()"
|
||||
(click)="submit()">
|
||||
<mat-icon>save</mat-icon>
|
||||
Speichern
|
||||
</button>
|
||||
|
||||
+93
-3
@@ -1,7 +1,7 @@
|
||||
.organization-form {
|
||||
display: grid;
|
||||
gap: 12px;
|
||||
min-width: min(540px, calc(100vw - 64px));
|
||||
gap: 18px;
|
||||
min-width: min(680px, calc(100vw - 64px));
|
||||
padding-top: 4px;
|
||||
}
|
||||
|
||||
@@ -9,11 +9,101 @@
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.institution-section {
|
||||
display: grid;
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.section-heading {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
justify-content: space-between;
|
||||
gap: 16px;
|
||||
}
|
||||
|
||||
.section-heading h3 {
|
||||
margin: 0 0 4px;
|
||||
font-size: 16px;
|
||||
}
|
||||
|
||||
.section-heading p,
|
||||
.empty-institutions {
|
||||
margin: 0;
|
||||
color: var(--sg-text-muted);
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.institution-list {
|
||||
display: grid;
|
||||
gap: 8px;
|
||||
max-height: 320px;
|
||||
overflow: auto;
|
||||
}
|
||||
|
||||
.autocomplete-description {
|
||||
display: block;
|
||||
color: var(--sg-text-muted);
|
||||
line-height: 1.2;
|
||||
}
|
||||
|
||||
.institution-item {
|
||||
display: grid;
|
||||
grid-template-columns: auto minmax(0, 1fr) auto;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
padding: 10px 8px 10px 12px;
|
||||
border: 1px solid var(--sg-border-color, #d8d8d8);
|
||||
border-radius: 8px;
|
||||
}
|
||||
|
||||
.institution-icon {
|
||||
color: var(--sg-text-muted);
|
||||
}
|
||||
|
||||
.institution-details {
|
||||
display: grid;
|
||||
min-width: 0;
|
||||
gap: 3px;
|
||||
}
|
||||
|
||||
.institution-details strong {
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.institution-id {
|
||||
color: var(--sg-text-muted);
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.origin-labels {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 5px;
|
||||
margin-top: 3px;
|
||||
}
|
||||
|
||||
.origin-label {
|
||||
padding: 2px 7px;
|
||||
border-radius: 999px;
|
||||
background: color-mix(in srgb, var(--mat-sys-primary) 10%, transparent);
|
||||
color: var(--mat-sys-primary);
|
||||
font-size: 11px;
|
||||
}
|
||||
|
||||
.empty-institutions {
|
||||
padding: 14px;
|
||||
border: 1px dashed var(--sg-border-color, #d8d8d8);
|
||||
border-radius: 8px;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
mat-dialog-actions {
|
||||
padding: 12px 24px 20px;
|
||||
}
|
||||
|
||||
@media (max-width: 600px) {
|
||||
@media (max-width: 760px) {
|
||||
.organization-form {
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
+266
-20
@@ -1,58 +1,108 @@
|
||||
import { CommonModule } from '@angular/common';
|
||||
import { Component, inject } from '@angular/core';
|
||||
import { Component, computed, DestroyRef, inject, signal } from '@angular/core';
|
||||
import {
|
||||
FormControl,
|
||||
FormGroup,
|
||||
ReactiveFormsModule,
|
||||
Validators,
|
||||
} from '@angular/forms';
|
||||
import {
|
||||
MatAutocompleteModule,
|
||||
MatAutocompleteSelectedEvent,
|
||||
} from '@angular/material/autocomplete';
|
||||
import { MatButtonModule } from '@angular/material/button';
|
||||
import { MatCheckboxModule } from '@angular/material/checkbox';
|
||||
import {
|
||||
MAT_DIALOG_DATA,
|
||||
MatDialog,
|
||||
MatDialogModule,
|
||||
MatDialogRef,
|
||||
} from '@angular/material/dialog';
|
||||
import { MatFormFieldModule } from '@angular/material/form-field';
|
||||
import { MatIconModule } from '@angular/material/icon';
|
||||
import { MatInputModule } from '@angular/material/input';
|
||||
import { InseOrganizationManagementModelOrganizationProfile } from '../../../api';
|
||||
import { MatProgressSpinnerModule } from '@angular/material/progress-spinner';
|
||||
import { MatSnackBar, MatSnackBarModule } from '@angular/material/snack-bar';
|
||||
import { MatTooltipModule } from '@angular/material/tooltip';
|
||||
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
|
||||
import {
|
||||
catchError,
|
||||
debounceTime,
|
||||
distinctUntilChanged,
|
||||
finalize,
|
||||
of,
|
||||
switchMap,
|
||||
} from 'rxjs';
|
||||
import {
|
||||
CreateOrganizationRequest,
|
||||
InseOrganizationManagementModelOrganizationProfile,
|
||||
Institution,
|
||||
InstitutionAssociation,
|
||||
InstitutionAssociationsResponse,
|
||||
InstitutionsV2Service,
|
||||
OrganizationService,
|
||||
UpdateOrganizationRequest,
|
||||
} from '../../../api';
|
||||
import { InstitutionRemovalDialogComponent } from './institution-removal-dialog.component';
|
||||
|
||||
export interface CreateOrganizationPayload {
|
||||
name: string;
|
||||
other_inst_id?: string | null;
|
||||
type Relationship = InstitutionAssociation.RelationshipEnum;
|
||||
|
||||
interface InstitutionOrigin {
|
||||
sourceId: string;
|
||||
sourceName: string;
|
||||
relationship: Relationship;
|
||||
}
|
||||
|
||||
export interface UpdateOrganizationPayload {
|
||||
name?: string;
|
||||
other_inst_id?: string | null;
|
||||
deleted?: boolean;
|
||||
interface EditableInstitution {
|
||||
id: string;
|
||||
institution: Institution;
|
||||
manuallySelected: boolean;
|
||||
origins: InstitutionOrigin[];
|
||||
}
|
||||
|
||||
interface OriginLabel {
|
||||
relationship: 'selected' | Relationship;
|
||||
label: string;
|
||||
tooltip?: string;
|
||||
}
|
||||
|
||||
type OrganizationWithInstitutions =
|
||||
InseOrganizationManagementModelOrganizationProfile & {
|
||||
institutionAssociations?: InstitutionAssociationsResponse[];
|
||||
};
|
||||
|
||||
export interface OrganizationDialogData {
|
||||
mode: 'create' | 'edit';
|
||||
organization?: InseOrganizationManagementModelOrganizationProfile;
|
||||
organization?: OrganizationWithInstitutions;
|
||||
isCurrentOrganization?: boolean;
|
||||
}
|
||||
|
||||
export type OrganizationDialogResult =
|
||||
| { mode: 'create'; payload: CreateOrganizationPayload }
|
||||
| { mode: 'create'; payload: CreateOrganizationRequest }
|
||||
| {
|
||||
mode: 'edit';
|
||||
organizationId: string;
|
||||
payload: UpdateOrganizationPayload;
|
||||
payload: UpdateOrganizationRequest;
|
||||
};
|
||||
|
||||
const cleanInstitutionId = (id: string): string =>
|
||||
id.split('/').filter(Boolean).pop() ?? id;
|
||||
|
||||
@Component({
|
||||
selector: 'app-organization-dialog',
|
||||
imports: [
|
||||
CommonModule,
|
||||
ReactiveFormsModule,
|
||||
MatAutocompleteModule,
|
||||
MatButtonModule,
|
||||
MatCheckboxModule,
|
||||
MatDialogModule,
|
||||
MatFormFieldModule,
|
||||
MatIconModule,
|
||||
MatInputModule,
|
||||
MatProgressSpinnerModule,
|
||||
MatSnackBarModule,
|
||||
MatTooltipModule,
|
||||
],
|
||||
templateUrl: './organization-dialog.component.html',
|
||||
styleUrl: './organization-dialog.component.scss',
|
||||
@@ -66,23 +116,217 @@ export class OrganizationDialogComponent {
|
||||
OrganizationDialogResult | undefined
|
||||
>
|
||||
>(MatDialogRef);
|
||||
private readonly dialog = inject(MatDialog);
|
||||
private readonly organizationService = inject(OrganizationService);
|
||||
private readonly institutionsService = inject(InstitutionsV2Service);
|
||||
private readonly snackBar = inject(MatSnackBar);
|
||||
private readonly destroyRef = inject(DestroyRef);
|
||||
protected readonly data = inject<OrganizationDialogData>(MAT_DIALOG_DATA);
|
||||
|
||||
protected readonly isLoadingAssociations = signal(false);
|
||||
protected readonly isSearchingInstitutions = signal(false);
|
||||
protected readonly institutionSearchResults = signal<Institution[]>([]);
|
||||
private readonly selectedAssociations = signal<
|
||||
InstitutionAssociationsResponse[]
|
||||
>([...(this.data.organization?.institutionAssociations ?? [])]);
|
||||
protected readonly institutions = computed(() =>
|
||||
this.expandInstitutions(this.selectedAssociations()),
|
||||
);
|
||||
protected readonly institutionSearch = new FormControl<string | Institution>(
|
||||
'',
|
||||
{ nonNullable: true },
|
||||
);
|
||||
|
||||
protected readonly form = new FormGroup({
|
||||
name: new FormControl(this.data.organization?.name ?? '', {
|
||||
nonNullable: true,
|
||||
validators: [Validators.required],
|
||||
}),
|
||||
otherInstId: new FormControl(this.data.organization?.other_inst_id ?? '', {
|
||||
nonNullable: true,
|
||||
}),
|
||||
deleted: new FormControl(this.data.organization?.deleted ?? false, {
|
||||
nonNullable: true,
|
||||
}),
|
||||
deleted: new FormControl(
|
||||
{
|
||||
value: this.data.organization?.deleted ?? false,
|
||||
disabled: this.data.isCurrentOrganization ?? false,
|
||||
},
|
||||
{ nonNullable: true },
|
||||
),
|
||||
});
|
||||
|
||||
constructor() {
|
||||
this.institutionSearch.valueChanges
|
||||
.pipe(
|
||||
debounceTime(300),
|
||||
distinctUntilChanged(),
|
||||
switchMap((value) => {
|
||||
if (typeof value !== 'string' || !value.trim()) {
|
||||
this.isSearchingInstitutions.set(false);
|
||||
return of({ elements: [] as Institution[] });
|
||||
}
|
||||
this.isSearchingInstitutions.set(true);
|
||||
return this.institutionsService
|
||||
.getInstitutionAutocompleteForSelector(value.trim())
|
||||
.pipe(
|
||||
catchError(() => {
|
||||
this.snackBar.open(
|
||||
'Institutionen konnten nicht geladen werden. Bitte versuche es später erneut.',
|
||||
'OK',
|
||||
{ duration: 5000 },
|
||||
);
|
||||
return of({ elements: [] as Institution[] });
|
||||
}),
|
||||
finalize(() => this.isSearchingInstitutions.set(false)),
|
||||
);
|
||||
}),
|
||||
takeUntilDestroyed(this.destroyRef),
|
||||
)
|
||||
.subscribe((page) =>
|
||||
this.institutionSearchResults.set(page.elements ?? []),
|
||||
);
|
||||
}
|
||||
|
||||
private expandInstitutions(
|
||||
roots: InstitutionAssociationsResponse[],
|
||||
): EditableInstitution[] {
|
||||
const entries = new Map<string, EditableInstitution>();
|
||||
for (const root of roots) {
|
||||
const id = cleanInstitutionId(root.id);
|
||||
entries.set(id, {
|
||||
id,
|
||||
institution: {
|
||||
id: `https://openalex.org/${id}`,
|
||||
display_name: root.display_name,
|
||||
},
|
||||
manuallySelected: true,
|
||||
origins: [],
|
||||
});
|
||||
}
|
||||
for (const root of roots) {
|
||||
const sourceId = cleanInstitutionId(root.id);
|
||||
for (const association of root.associated_institutions ?? []) {
|
||||
const id = cleanInstitutionId(association.id);
|
||||
const entry = entries.get(id) ?? {
|
||||
id,
|
||||
institution: {
|
||||
id: `https://openalex.org/${id}`,
|
||||
display_name: association.display_name,
|
||||
},
|
||||
manuallySelected: false,
|
||||
origins: [],
|
||||
};
|
||||
entry.origins.push({
|
||||
sourceId,
|
||||
sourceName: root.display_name,
|
||||
relationship: association.relationship,
|
||||
});
|
||||
entries.set(id, entry);
|
||||
}
|
||||
}
|
||||
return [...entries.values()];
|
||||
}
|
||||
|
||||
protected selectInstitution(institution: Institution): void {
|
||||
if (!institution.id || this.isLoadingAssociations()) return;
|
||||
|
||||
const selectedId = cleanInstitutionId(institution.id);
|
||||
this.isLoadingAssociations.set(true);
|
||||
this.organizationService
|
||||
.getOrganizationInstitutionAssociations([selectedId])
|
||||
.pipe(finalize(() => this.isLoadingAssociations.set(false)))
|
||||
.subscribe({
|
||||
next: ([response]) => {
|
||||
if (!response) return;
|
||||
const roots = [...this.selectedAssociations()];
|
||||
const existingIndex = roots.findIndex(
|
||||
(root) => cleanInstitutionId(root.id) === selectedId,
|
||||
);
|
||||
if (existingIndex === -1) roots.push(response);
|
||||
else roots[existingIndex] = response;
|
||||
this.selectedAssociations.set(roots);
|
||||
},
|
||||
error: () => {
|
||||
this.snackBar.open(
|
||||
'Die Institution konnte nicht hinzugefügt werden. Bitte versuche es später erneut.',
|
||||
'OK',
|
||||
{ duration: 5000 },
|
||||
);
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
protected selectAutocompleteInstitution(
|
||||
event: MatAutocompleteSelectedEvent,
|
||||
): void {
|
||||
const institution = event.option.value as Institution;
|
||||
this.institutionSearch.setValue('', { emitEvent: false });
|
||||
this.institutionSearchResults.set([]);
|
||||
this.selectInstitution(institution);
|
||||
}
|
||||
|
||||
protected displayInstitution(institution: Institution | string): string {
|
||||
return typeof institution === 'string'
|
||||
? institution
|
||||
: (institution.display_name ?? '');
|
||||
}
|
||||
|
||||
protected originLabels(entry: EditableInstitution): OriginLabel[] {
|
||||
const labels: OriginLabel[] = [];
|
||||
if (entry.manuallySelected) {
|
||||
labels.push({ relationship: 'selected', label: 'Manuell ausgewählt' });
|
||||
}
|
||||
for (const relationship of ['child', 'related'] as const) {
|
||||
const sourceNames = [
|
||||
...new Set(
|
||||
entry.origins
|
||||
.filter((origin) => origin.relationship === relationship)
|
||||
.map((origin) => origin.sourceName),
|
||||
),
|
||||
];
|
||||
if (sourceNames.length === 0) continue;
|
||||
labels.push({
|
||||
relationship,
|
||||
label: relationship === 'child' ? 'Untergeordnet' : 'Verbunden',
|
||||
tooltip: `Automatisch hinzugefügt durch:\n${sourceNames.map((name) => `• ${name}`).join('\n')}`,
|
||||
});
|
||||
}
|
||||
return labels;
|
||||
}
|
||||
|
||||
protected removeInstitution(entry: EditableInstitution): void {
|
||||
if (!entry.manuallySelected) return;
|
||||
|
||||
const remainingRoots = this.selectedAssociations().filter(
|
||||
(root) => cleanInstitutionId(root.id) !== entry.id,
|
||||
);
|
||||
const remainingIds = new Set(
|
||||
this.expandInstitutions(remainingRoots).map(
|
||||
(institution) => institution.id,
|
||||
),
|
||||
);
|
||||
const dependentCount = this.institutions().filter(
|
||||
(institution) =>
|
||||
institution.id !== entry.id && !remainingIds.has(institution.id),
|
||||
).length;
|
||||
|
||||
this.dialog
|
||||
.open<
|
||||
InstitutionRemovalDialogComponent,
|
||||
{ institutionName: string; dependentCount: number },
|
||||
boolean | undefined
|
||||
>(InstitutionRemovalDialogComponent, {
|
||||
data: {
|
||||
institutionName: entry.institution.display_name ?? entry.id,
|
||||
dependentCount,
|
||||
},
|
||||
width: '520px',
|
||||
maxWidth: 'calc(100vw - 32px)',
|
||||
})
|
||||
.afterClosed()
|
||||
.subscribe((confirmed) => {
|
||||
if (confirmed) this.selectedAssociations.set(remainingRoots);
|
||||
});
|
||||
}
|
||||
|
||||
protected submit(): void {
|
||||
if (this.form.invalid) {
|
||||
if (this.form.invalid || this.isLoadingAssociations()) {
|
||||
this.form.markAllAsTouched();
|
||||
return;
|
||||
}
|
||||
@@ -90,7 +334,9 @@ export class OrganizationDialogComponent {
|
||||
const value = this.form.getRawValue();
|
||||
const payload = {
|
||||
name: value.name.trim(),
|
||||
other_inst_id: value.otherInstId.trim(),
|
||||
selected_openalex_institution_ids: this.selectedAssociations().map(
|
||||
(root) => cleanInstitutionId(root.id),
|
||||
),
|
||||
};
|
||||
|
||||
if (this.data.mode === 'create') {
|
||||
|
||||
@@ -1,18 +1,17 @@
|
||||
<section class="organizations-page">
|
||||
<header class="page-header">
|
||||
<div>
|
||||
<h1>Organisationen</h1>
|
||||
<p>Mandanten, externe Institutions-IDs und Status verwalten.</p>
|
||||
<!-- Was meinte die KI mit Mandanten? -->
|
||||
<h1>Organisationen</h1>
|
||||
<div class="page-header-meta">
|
||||
<p>Organisationen verwalten, OpenAlex-Institutionen zuordnen und Status festlegen</p>
|
||||
<button
|
||||
mat-flat-button
|
||||
color="primary"
|
||||
type="button"
|
||||
(click)="startCreate()">
|
||||
<mat-icon>add_business</mat-icon>
|
||||
Neue Organisation
|
||||
</button>
|
||||
</div>
|
||||
<button
|
||||
mat-flat-button
|
||||
color="primary"
|
||||
type="button"
|
||||
(click)="startCreate()">
|
||||
<mat-icon>add_business</mat-icon>
|
||||
Neue Organisation
|
||||
</button>
|
||||
</header>
|
||||
|
||||
<mat-card appearance="outlined">
|
||||
@@ -31,6 +30,32 @@
|
||||
</span>
|
||||
</ng-template>
|
||||
|
||||
<ng-template #organizationInstitutionsTmp let-row>
|
||||
@if ($any(row).institutions.length > 0) {
|
||||
<span>
|
||||
@for (
|
||||
institution of $any(row).institutions;
|
||||
track institution.id;
|
||||
let index = $index
|
||||
) {
|
||||
@if (index < 3) {
|
||||
{{ institution.display_name
|
||||
}}{{
|
||||
index < 2 && index < $any(row).institutions.length - 1 ? ', ' : ''
|
||||
}}
|
||||
}
|
||||
}
|
||||
@if ($any(row).institutions.length > 3) {
|
||||
<span class="more-institutions">
|
||||
+ {{ $any(row).institutions.length - 3 }} weitere
|
||||
</span>
|
||||
}
|
||||
</span>
|
||||
} @else {
|
||||
<span class="no-institutions">Keine Institutionen</span>
|
||||
}
|
||||
</ng-template>
|
||||
|
||||
<ng-template #organizationActionsTmp let-row>
|
||||
<div class="row-actions">
|
||||
<button
|
||||
@@ -44,7 +69,7 @@
|
||||
mat-icon-button
|
||||
type="button"
|
||||
aria-label="Deaktivieren"
|
||||
[disabled]="row.deleted"
|
||||
[disabled]="row.deleted || isCurrentOrganization(row)"
|
||||
(click)="deleteOrganization(row)">
|
||||
<mat-icon>delete</mat-icon>
|
||||
</button>
|
||||
|
||||
@@ -6,6 +6,12 @@
|
||||
}
|
||||
|
||||
.page-header {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 6px;
|
||||
}
|
||||
|
||||
.page-header-meta {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
@@ -24,7 +30,7 @@ p {
|
||||
}
|
||||
|
||||
.page-header p {
|
||||
margin-top: 6px;
|
||||
flex: 1 1 auto;
|
||||
}
|
||||
|
||||
.status {
|
||||
@@ -49,7 +55,7 @@ p {
|
||||
padding: 16px;
|
||||
}
|
||||
|
||||
.page-header {
|
||||
.page-header-meta {
|
||||
align-items: flex-start;
|
||||
flex-direction: column;
|
||||
}
|
||||
@@ -59,3 +65,8 @@ mat-card,
|
||||
mat-paginator {
|
||||
background-color: var(--sg-background);
|
||||
}
|
||||
|
||||
.more-institutions,
|
||||
.no-institutions {
|
||||
color: var(--sg-text-muted);
|
||||
}
|
||||
|
||||
@@ -16,11 +16,7 @@ import type {
|
||||
OrganizationDialogData,
|
||||
OrganizationDialogResult,
|
||||
} from './organization-dialog/organization-dialog.component';
|
||||
import {
|
||||
InseOrganizationManagementModelOrganizationProfile,
|
||||
OrganizationPage,
|
||||
OrganizationService,
|
||||
} from '../../api';
|
||||
import { OrganizationService } from '../../api';
|
||||
import {
|
||||
GenericColumn,
|
||||
DataTableComponent,
|
||||
@@ -29,6 +25,11 @@ import { MatCardModule } from '@angular/material/card';
|
||||
import { StatusPipe } from '../../shared/pipes/status.pipe';
|
||||
import { QueryParamPaginatorComponent } from '../../shared/ui/query-param-paginator/query-param-paginator.component';
|
||||
import { Router } from '@angular/router';
|
||||
import {
|
||||
OrganizationPageWithInstitutions,
|
||||
OrganizationWithInstitutions,
|
||||
} from '../../resolvers/organizations-organizations.resolver';
|
||||
import { CredentialService } from '../../shared/services/credential.service';
|
||||
|
||||
@Component({
|
||||
selector: 'app-organizations',
|
||||
@@ -52,10 +53,10 @@ export class OrganizationsComponent implements OnInit {
|
||||
private readonly dialog = inject(MatDialog);
|
||||
private readonly snackBar = inject(MatSnackBar);
|
||||
private readonly organizationService = inject(OrganizationService);
|
||||
private readonly credentialService = inject(CredentialService);
|
||||
|
||||
organizationPage = input.required<OrganizationPage>();
|
||||
organizationColumns: GenericColumn<InseOrganizationManagementModelOrganizationProfile>[] =
|
||||
[];
|
||||
organizationPage = input.required<OrganizationPageWithInstitutions>();
|
||||
organizationColumns: GenericColumn<OrganizationWithInstitutions>[] = [];
|
||||
|
||||
organizationStatusTmp = viewChild.required<TemplateRef<any>>(
|
||||
'organizationStatusTmp',
|
||||
@@ -63,6 +64,9 @@ export class OrganizationsComponent implements OnInit {
|
||||
organizationActionsTmp = viewChild.required<TemplateRef<any>>(
|
||||
'organizationActionsTmp',
|
||||
);
|
||||
organizationInstitutionsTmp = viewChild.required<TemplateRef<any>>(
|
||||
'organizationInstitutionsTmp',
|
||||
);
|
||||
|
||||
ngOnInit(): void {
|
||||
this.organizationColumns = [
|
||||
@@ -73,10 +77,10 @@ export class OrganizationsComponent implements OnInit {
|
||||
accessorKey: 'name',
|
||||
},
|
||||
{
|
||||
id: 'other_inst_id',
|
||||
header: 'Externe ID',
|
||||
type: 'accessor',
|
||||
accessorKey: 'other_inst_id',
|
||||
id: 'institutions',
|
||||
header: 'OpenAlex-Institutionen',
|
||||
type: 'display',
|
||||
cellTemplate: this.organizationInstitutionsTmp(),
|
||||
},
|
||||
{
|
||||
id: 'member_count',
|
||||
@@ -104,16 +108,29 @@ export class OrganizationsComponent implements OnInit {
|
||||
this.openDialog({ mode: 'create' });
|
||||
}
|
||||
|
||||
protected startEdit(
|
||||
organization: InseOrganizationManagementModelOrganizationProfile,
|
||||
): void {
|
||||
this.openDialog({ mode: 'edit', organization });
|
||||
protected startEdit(organization: OrganizationWithInstitutions): void {
|
||||
this.openDialog({
|
||||
mode: 'edit',
|
||||
organization,
|
||||
isCurrentOrganization: this.isCurrentOrganization(organization),
|
||||
});
|
||||
}
|
||||
|
||||
protected isCurrentOrganization(
|
||||
organization: OrganizationWithInstitutions,
|
||||
): boolean {
|
||||
return organization.id === this.credentialService.effectiveOrganizationId();
|
||||
}
|
||||
|
||||
protected deleteOrganization(
|
||||
organization: InseOrganizationManagementModelOrganizationProfile,
|
||||
organization: OrganizationWithInstitutions,
|
||||
): void {
|
||||
if (organization.deleted) return;
|
||||
if (
|
||||
organization.deleted ||
|
||||
this.isCurrentOrganization(organization)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
import('../../shared/ui/confirmation-dialog/confirmation-dialog.component').then(
|
||||
({ ConfirmationDialogComponent }) => {
|
||||
@@ -134,7 +151,7 @@ export class OrganizationsComponent implements OnInit {
|
||||
}
|
||||
|
||||
private softDeleteOrganization(
|
||||
organization: InseOrganizationManagementModelOrganizationProfile,
|
||||
organization: OrganizationWithInstitutions,
|
||||
): void {
|
||||
this.organizationService.deleteOrganisation(organization.id).subscribe({
|
||||
next: () => {
|
||||
@@ -146,8 +163,12 @@ export class OrganizationsComponent implements OnInit {
|
||||
queryParamsHandling: 'merge',
|
||||
});
|
||||
},
|
||||
error: () =>
|
||||
this.showError('Organisation konnte nicht deaktiviert werden.'),
|
||||
error: (error) =>
|
||||
this.showError(
|
||||
this.isProtectedOrganizationError(error)
|
||||
? 'Die eigene Organisation kann nicht deaktiviert werden.'
|
||||
: 'Organisation konnte nicht deaktiviert werden.',
|
||||
),
|
||||
});
|
||||
}
|
||||
|
||||
@@ -159,7 +180,7 @@ export class OrganizationsComponent implements OnInit {
|
||||
OrganizationDialogData,
|
||||
OrganizationDialogResult | undefined
|
||||
>(OrganizationDialogComponent, {
|
||||
width: '620px',
|
||||
width: '780px',
|
||||
maxWidth: 'calc(100vw - 32px)',
|
||||
data,
|
||||
});
|
||||
@@ -192,13 +213,24 @@ export class OrganizationsComponent implements OnInit {
|
||||
},
|
||||
error: (error) =>
|
||||
this.showError(
|
||||
error.status === 409
|
||||
this.isProtectedOrganizationError(error)
|
||||
? 'Die eigene Organisation kann nicht deaktiviert werden.'
|
||||
: error.status === 409
|
||||
? 'Eine Organisation mit diesem Namen existiert bereits.'
|
||||
: 'Organisation konnte nicht gespeichert werden.',
|
||||
),
|
||||
});
|
||||
}
|
||||
|
||||
private isProtectedOrganizationError(error: {
|
||||
error?: { detail?: string };
|
||||
}): boolean {
|
||||
return (
|
||||
error.error?.detail ===
|
||||
'The organization of the real or effective account cannot be deleted.'
|
||||
);
|
||||
}
|
||||
|
||||
private showError(message: string): void {
|
||||
this.snackBar.open(message, 'OK', { duration: 5000 });
|
||||
}
|
||||
|
||||
@@ -1,13 +1,107 @@
|
||||
import { inject } from '@angular/core';
|
||||
import { ResolveFn } from '@angular/router';
|
||||
import { OrganizationPage, OrganizationService } from '../api';
|
||||
import {
|
||||
InseOrganizationManagementModelOrganizationProfile,
|
||||
Institution,
|
||||
InstitutionAssociationsResponse,
|
||||
OrganizationPage,
|
||||
OrganizationService,
|
||||
} from '../api';
|
||||
import { map, of, switchMap } from 'rxjs';
|
||||
|
||||
export const organizationsOrganizationsResolver: ResolveFn<OrganizationPage> = (
|
||||
route,
|
||||
state,
|
||||
) => {
|
||||
export type OrganizationWithInstitutions =
|
||||
InseOrganizationManagementModelOrganizationProfile & {
|
||||
institutions: Institution[];
|
||||
institutionAssociations: InstitutionAssociationsResponse[];
|
||||
};
|
||||
|
||||
export type OrganizationPageWithInstitutions = Omit<
|
||||
OrganizationPage,
|
||||
'items'
|
||||
> & {
|
||||
items: OrganizationWithInstitutions[];
|
||||
};
|
||||
|
||||
const cleanInstitutionId = (id: string): string =>
|
||||
id.split('/').filter(Boolean).pop() ?? id;
|
||||
|
||||
const expandInstitutions = (
|
||||
associations: InstitutionAssociationsResponse[],
|
||||
): Institution[] => {
|
||||
const institutions = new Map<string, Institution>();
|
||||
for (const root of associations) {
|
||||
institutions.set(cleanInstitutionId(root.id), {
|
||||
id: `https://openalex.org/${cleanInstitutionId(root.id)}`,
|
||||
display_name: root.display_name,
|
||||
});
|
||||
}
|
||||
for (const root of associations) {
|
||||
for (const association of root.associated_institutions ?? []) {
|
||||
const id = cleanInstitutionId(association.id);
|
||||
if (!institutions.has(id)) {
|
||||
institutions.set(id, {
|
||||
id: `https://openalex.org/${id}`,
|
||||
display_name: association.display_name,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
return [...institutions.values()];
|
||||
};
|
||||
|
||||
export const organizationsOrganizationsResolver: ResolveFn<
|
||||
OrganizationPageWithInstitutions
|
||||
> = (route) => {
|
||||
const page = Number(route.queryParamMap.get('page') ?? '0');
|
||||
const size = Number(route.queryParamMap.get('size') ?? '10');
|
||||
const organizationService = inject(OrganizationService);
|
||||
|
||||
return inject(OrganizationService).getOrganisations(page, size);
|
||||
return organizationService.getOrganisations(page, size).pipe(
|
||||
switchMap((organizationPage) => {
|
||||
const selectedIds = [
|
||||
...new Set(
|
||||
organizationPage.items.flatMap(
|
||||
(organization) =>
|
||||
organization.selected_openalex_institution_ids ?? [],
|
||||
),
|
||||
),
|
||||
];
|
||||
if (selectedIds.length === 0) {
|
||||
return of({
|
||||
...organizationPage,
|
||||
items: organizationPage.items.map((organization) => ({
|
||||
...organization,
|
||||
institutions: [],
|
||||
institutionAssociations: [],
|
||||
})),
|
||||
});
|
||||
}
|
||||
|
||||
return organizationService
|
||||
.getOrganizationInstitutionAssociations(selectedIds)
|
||||
.pipe(
|
||||
map((associationResponses) => {
|
||||
const responsesById = new Map(
|
||||
associationResponses.map((response) => [
|
||||
cleanInstitutionId(response.id),
|
||||
response,
|
||||
]),
|
||||
);
|
||||
return {
|
||||
...organizationPage,
|
||||
items: organizationPage.items.map((organization) => {
|
||||
const institutionAssociations = (
|
||||
organization.selected_openalex_institution_ids ?? []
|
||||
).map((id) => responsesById.get(cleanInstitutionId(id))!);
|
||||
return {
|
||||
...organization,
|
||||
institutions: expandInstitutions(institutionAssociations),
|
||||
institutionAssociations,
|
||||
};
|
||||
}),
|
||||
};
|
||||
}),
|
||||
);
|
||||
}),
|
||||
);
|
||||
};
|
||||
|
||||
@@ -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<Institution>();
|
||||
@@ -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({
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
<mat-form-field style="width: 100%">
|
||||
<mat-form-field style="width: 100%" subscriptSizing="dynamic">
|
||||
@if (label()) {
|
||||
<mat-label>{{ label() }}</mat-label>
|
||||
}
|
||||
|
||||
@@ -513,7 +513,10 @@ html.dark-theme {
|
||||
|
||||
.topic-chip-tooltip,
|
||||
.topic-chip-tooltip .mdc-tooltip__surface,
|
||||
.topic-chip-tooltip .mat-mdc-tooltip-surface {
|
||||
.topic-chip-tooltip .mat-mdc-tooltip-surface,
|
||||
.institution-origin-tooltip,
|
||||
.institution-origin-tooltip .mdc-tooltip__surface,
|
||||
.institution-origin-tooltip .mat-mdc-tooltip-surface {
|
||||
max-width: 320px;
|
||||
white-space: pre-line;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user